summaryrefslogtreecommitdiff
path: root/Unique.hs
blob: 1594b4ab01767ecfcf6d98d6879287a337a76d1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
module Unique
    ( UniqueFactory
    , freshUniques
    , genUnique
    , Unique
    , uniqueSymbol
    , uniquePattern
    , substituteUnique
    , multipleOccurances
    ) where

import Data.Generics.Aliases
import Data.Generics.Schemes
import Language.Haskell.Exts.Syntax

newtype UniqueFactory = UniqueFactory Integer

newtype Unique = Unique Integer
 deriving (Eq,Ord)

freshUniques :: UniqueFactory
freshUniques = UniqueFactory 0

genUnique :: UniqueFactory -> (Unique,UniqueFactory)
genUnique (UniqueFactory c) = (Unique c, UniqueFactory (succ c))

uniqueSymbol :: Unique -> Exp ()
uniqueSymbol (Unique i) = Var () (UnQual () (Ident () (showSym i)))

uniquePattern :: Unique -> Pat ()
uniquePattern (Unique i) = PVar () (Ident () (showSym i))

showSym :: Integer -> String
showSym i = " u" ++ show i

substituteUnique :: Unique -> Exp () -> Exp () -> Exp ()
substituteUnique u inner outer = everywhere (mkT $ subst inner) outer
 where
    subst x t | t == uniqueSymbol u  = x
              | otherwise            = t


multipleOccurances :: Unique -> Exp () -> Bool
multipleOccurances u x = case listify (== uniqueSymbol u) x of
    (x:y:ys) -> True
    _        -> False