on 4bec310 help sign in
elk/compiler/Transform/Substitute.hs
44 lines 1.6 kB history raw
1{-# OPTIONS_GHC -Wall #-}
2module Transform.Substitute (subst) where
4import Control.Arrow (second, (***))
5import qualified Data.Set as Set
7import SourceSyntax.Annotation
8import SourceSyntax.Expression
9import qualified SourceSyntax.Pattern as Pattern
10import qualified SourceSyntax.Variable as V
12subst :: String -> Expr' -> Expr' -> Expr'
13subst old new expr =
14 let f (A a e) = A a (subst old new e) in
15 case expr of
16 Range e1 e2 -> Range (f e1) (f e2)
17 ExplicitList es -> ExplicitList (map f es)
18 Binop op e1 e2 -> Binop op (f e1) (f e2)
19 Lambda p e
20 | Set.member old (Pattern.boundVars p) -> expr
21 | otherwise -> Lambda p (f e)
22 App e1 e2 -> App (f e1) (f e2)
23 MultiIf ps -> MultiIf (map (f *** f) ps)
25 Let defs body
26 | anyShadow -> expr
27 | otherwise -> Let (map substDef defs) (f body)
28 where
29 substDef (Definition p e t) = Definition p (f e) t
30 anyShadow =
31 any (Set.member old . Pattern.boundVars) [ p | Definition p _ _ <- defs ]
33 Var (V.Raw x) -> if x == old then new else expr
34 Case e cases -> Case (f e) $ map (second f) cases
35 Data name es -> Data name (map f es)
36 Access e x -> Access (f e) x
37 Remove e x -> Remove (f e) x
38 Insert e x v -> Insert (f e) x (f v)
39 Modify r fs -> Modify (f r) (map (second f) fs)
40 Record fs -> Record (map (second f) fs)
41 Literal _ -> expr
42 Markdown uid md es -> Markdown uid md (map f es)
43 PortIn name st -> PortIn name st
44 PortOut name st signal -> PortOut name st (f signal)