Added examples from markus
[cc1516.git] / sem.icl
1 implementation module sem
2
3 import qualified Data.Map as Map
4 from Data.Func import $
5 import Data.Maybe
6 import Data.Void
7 import Data.Either
8 import Data.Functor
9 import Control.Applicative
10 import Control.Monad
11 import Control.Monad.State
12 import Control.Monad.Identity
13 import Math.Random
14 import Control.Monad.Trans
15 import StdMisc
16 from StdFunc import id, const, o
17 import StdString
18 import StdTuple
19 import StdList
20 import StdBool
21
22 from Text import class Text(concat), instance Text String
23
24 import AST
25 from parse import :: ParserOutput, :: Error
26
27 :: Gamma :== ('Map'.Map String Type, [String])
28 :: Env a :== StateT Gamma (Either SemError) a
29 //StateT (Gamma -> Either SemError (a, Gamma))
30
31 //we need to redefine this even though it is in Control.Monad.State
32 instance MonadTrans (StateT Gamma) where
33 liftT m = StateT \s-> m >>= \a-> return (a, s)
34
35 get = gets id
36
37 sem :: AST -> SemOutput
38 sem (AST vd fd) = case runStateT m ('Map'.newMap, getRandomStream 1) of
39 Left e = Left [e]
40 Right ((vds, fds), gamma) = Right ((AST vds fds), gamma)
41 where
42 m :: Env ([VarDecl], [FunDecl])
43 m = mapM semVarDecl vd >>= \vds ->
44 mapM semFunDecl fd >>= \fds ->
45 pure (vds, fds)
46
47 semFunDecl :: FunDecl -> Env FunDecl
48 semFunDecl fd=:(FunDecl p f args mt vds stmts) =
49 saveGamma >>= \gamma ->
50 (case mt of
51 Nothing = let t = IdType f in putIdent f t >>| pure t
52 Just t = putIdent f t >>| pure t) >>= \ft ->
53 matchFunctions args ft >>|
54 mapM semVarDecl vds >>= \newvds->
55 mapM_ (checkStmt $ resultType ft) stmts >>|
56 restoreGamma gamma >>|
57 pure (FunDecl p f args mt newvds stmts)
58
59 matchFunctions :: [String] Type -> Env Void
60 matchFunctions [] (_ ->> _) = liftT $ Left $ Error "Niet genoeg argumentenerror"
61 matchFunctions [] t = pure Void
62 matchFunctions [x:xs] (t1 ->> t2) =
63 modify (\(st, r)->('Map'.put x t1 st, r)) >>| matchFunctions xs t2
64
65 semVarDecl :: VarDecl -> Env VarDecl
66 semVarDecl (VarDecl pos type ident ex) = unify type ex
67 >>= \t-> putIdent ident t >>| (pure $ VarDecl pos t ident ex)
68
69 checkStmt ::Type Stmt -> Env Stmt
70 checkStmt t (IfStmt c st se) = unify BoolType c >>| mapM (checkStmt t) st
71 >>= \st1-> mapM (checkStmt t) se >>= \se1-> pure (IfStmt c st1 se1)
72 checkStmt t w=:(WhileStmt c et) = unify BoolType c >>| mapM (checkStmt t) et
73 >>= \et1-> pure w
74 checkStmt t a=:(AssStmt (VarDef ident fs) e) = gets (\(st, r)->'Map'.get ident st)
75 >>= \mt->case mt of
76 Nothing = liftT $ Left $ UndeclaredVariableError zero ident
77 Just t = unify t fs >>= \t1 -> unify t1 e >>| pure a
78 checkStmt t r=:(FunStmt (FunCall f es)) = typeFun f es >>| pure r
79 checkStmt VoidType r=:(ReturnStmt Nothing) = pure r
80 checkStmt t r=:(ReturnStmt (Just e)) = unify t e >>| pure r
81
82 typeExpr :: Expr -> Env Type
83 typeExpr (IntExpr _ _) = pure IntType
84 typeExpr (CharExpr _ _) = pure CharType
85 typeExpr (BoolExpr _ _) = pure BoolType
86 typeExpr (Op1Expr p UnNegation expr) = unify BoolType expr
87 typeExpr (Op1Expr p UnMinus expr) = unify IntType expr
88 typeExpr (TupleExpr p (e1, e2)) = typeExpr e1
89 >>= \t1-> typeExpr e2 >>= \t2-> pure $ TupleType (t1, t2)
90 typeExpr (Op2Expr p e1 op e2)
91 | isMember op [BiPlus, BiMinus, BiTimes, BiDivide, BiMod] =
92 typeOp2 e1 e2 op [IntType] IntType
93 | isMember op [BiEquals, BiUnEqual] =
94 typeOp2 e1 e2 op [IntType, BoolType, CharType] BoolType
95 | isMember op [BiLesser, BiGreater, BiLesserEq, BiGreaterEq] =
96 typeOp2 e1 e2 op [IntType, CharType] BoolType
97 | isMember op [BiAnd, BiOr] =
98 typeOp2 e1 e2 op [BoolType] BoolType
99 | op == BiCons = typeExpr e1 >>= \t1-> typeExpr e2
100 >>= \t2-> unify (ListType t1) t2
101 typeExpr (EmptyListExpr p) = freshIdent >>= \frsh-> let t = IdType frsh in
102 putIdent frsh t >>| pure t
103 typeExpr (FunExpr p (FunCall f es)) = typeFun f es
104 typeExpr (VarExpr p (VarDef ident fs)) = gets (\(st, r)->'Map'.get ident st)
105 >>= \mt->case mt of
106 Nothing = liftT $ Left $ UndeclaredVariableError p ident
107 Just t = unify t fs
108 typeOp2 :: Expr Expr Op2 [Type] Type -> Env Type
109 typeOp2 e1 e2 op ts ret = typeExpr e1 >>= \t1-> typeExpr e2 >>= \t2->
110 unify t1 t2 >>= \t3->if (isMember t3 ts) (pure ret)
111 (liftT $ Left $ OperatorError (extrPos e1) op t3)
112
113 buildFunctionType :: String [Expr] -> Env Type
114 buildFunctionType frsh [] = let t = IdType frsh in putIdent frsh t >>| pure t
115 buildFunctionType frsh [e:es] = (->>) <$> typeExpr e <*> buildFunctionType frsh es
116
117 unifyApp :: Type [Expr] -> Env Type
118 unifyApp t [] = pure t
119 unifyApp (tf1 ->> tf2) [t1:ts] = unify tf1 t1 >>| unifyApp tf2 ts
120 unifyApp t1 t2 = liftT $ Left $ UnifyError zero t1 (IdType "[expressions, FIXME]")
121
122 typeFun :: String [Expr] -> Env Type
123 typeFun f es = gets (\(st, r)->'Map'.get f st) >>= \mt-> case mt of
124 Nothing = freshIdent >>= \frsh-> buildFunctionType frsh es
125 >>= \ft-> putIdent f ft >>| (pure $ IdType frsh)
126 Just t = unifyApp t es
127
128 resultType :: Type -> Type
129 resultType (_ ->> t) = resultType t
130 resultType t = t
131
132 class unify a :: Type a -> Env Type
133
134 instance unify [FieldSelector] where
135 unify t [] = pure t
136 unify (ListType t) [FieldHd:fs] = unify t fs
137 unify t=:(ListType _) [FieldTl:fs] = unify t fs
138 unify (TupleType (t, _)) [FieldFst:fs] = unify t fs
139 unify (TupleType (_, t)) [FieldSnd:fs] = unify t fs
140 unify t [fs:_] = liftT $ Left $ FieldSelectorError zero t fs
141
142 instance unify Expr where
143 unify (_ ->> _) e = liftT $ Left $ ParseError (extrPos e)
144 "Expression cannot be a higher order function. Yet..."
145 unify VoidType e = liftT $ Left $ ParseError (extrPos e)
146 "Expression cannot be a Void type."
147 unify (IdType _) e = liftT $ Left $ ParseError (extrPos e)
148 "Expression cannot be an polymorf type."
149 unify VarType e = typeExpr e
150 //we have to cheat to decorate the error, can be done nicer?
151 unify t e = StateT $ \s0 -> let res = runStateT m s0 in case res of
152 Left err = Left $ decErr e err
153 Right t = Right t //note, t :: (Type, Gamma)
154 where m = typeExpr e >>= \tex-> unify t tex
155
156 instance unify Type where
157 unify IntType IntType = pure IntType
158 unify BoolType BoolType = pure BoolType
159 unify CharType CharType = pure CharType
160 unify (IdType i) t=:(IdType j) = replace i t >>| pure t
161 unify t (IdType i) = unify (IdType i) t
162 unify (IdType i) t = replace i t >>| pure t
163 unify (ListType t1) (ListType t2) = unify t1 t2 >>| (pure $ ListType t1)
164 unify (ta1 ->> ta2) (tb1 ->> tb2) = unify ta1 tb1 >>= \ta-> unify ta2 tb2
165 >>= \tb-> pure (ta ->> tb)
166 unify t1 t2 = liftT $ Left $ UnifyError zero t1 t2
167
168 instance zero Pos where
169 zero = {line=0,col=0}
170
171 decErr :: Expr SemError -> SemError
172 decErr e (UnifyError _ t1 t2) = UnifyError (extrPos e) t1 t2
173 decErr e (FieldSelectorError _ t fs) = FieldSelectorError (extrPos e) t fs
174 decErr e (ParseError _ s) = ParseError (extrPos e) s
175 decErr e err = err
176
177 dc2 :: Expr (Either SemError a) -> Either SemError a
178 dc2 e (Right t) = Right t
179 dc2 e (Left err) = Left err
180
181 extrPos :: Expr -> Pos
182 extrPos (VarExpr p _) = p
183 extrPos (Op2Expr p _ _ _) = p
184 extrPos (Op1Expr p _ _) = p
185 extrPos (IntExpr p _) = p
186 extrPos (CharExpr p _) = p
187 extrPos (BoolExpr p _) = p
188 extrPos (FunExpr p _) = p
189 extrPos (EmptyListExpr p) = p
190 extrPos (TupleExpr p _) = p
191
192 instance toString Gamma where
193 toString (mp, _) = concat
194 [concat [k, ": ", toString v, "\n"]\\(k, v) <- 'Map'.toList mp]
195
196 getRandomStream :: Int -> [String]
197 getRandomStream i = genIdents $ filter (isAlpha o toChar) (genRandInt i)
198 where
199 genIdents r = let (ic, r2) = splitAt 5 r in [toString ic: genIdents r2]
200
201 freshIdent :: Env String
202 freshIdent = get >>= \(st, [ident:rest])-> put (st, rest)
203 >>| case 'Map'.get ident st of
204 Nothing = pure ident
205 _ = freshIdent
206
207 putIdent :: String Type -> Env Void
208 putIdent i t = gets (\(st, r)->'Map'.get i st) >>= \mt -> case mt of
209 Nothing = modify (\(st, r)->('Map'.put i t st, r))
210 Just t2 = unify t t2 >>= \t3-> modify (\(st, r)->('Map'.put i t3 st, r))
211
212 replace :: String Type -> Env Void
213 replace ident type = get >>= \(st, fr)->put ('Map'.fromList $
214 map (itupdate ident type) ('Map'.toList st), fr)
215 where
216 itupdate :: String Type (String, Type) -> (String, Type)
217 itupdate ident newtype ov=:(key, IdType type) = if (ident == type)
218 (key, newtype) ov
219 itupdate ident newtype (key, TupleType (t1, t2))
220 # (_, t1) = itupdate ident newtype (key, t1)
221 # (_, t2) = itupdate ident newtype (key, t2)
222 = (key, TupleType (t1, t2))
223 itupdate ident newtype (key, ListType t1)
224 # (_, t1) = itupdate ident newtype (key, t1)
225 = (key, ListType t1)
226 itupdate _ _ k = k
227
228 instance toString SemError where
229 toString (ParseError p e) = concat [
230 toString p,"SemError: ParseError: ", e]
231 toString (Error e) = "SemError: " +++ e
232 toString (UnifyError p t1 t2) = concat [
233 toString p,
234 "SemError: Cannot unify types. Expected: ",
235 toString t1, ". Given: ", toString t2]
236 toString (FieldSelectorError p t fs) = concat [
237 toString p,
238 "SemError: Cannot select ", toString fs, " from type: ",
239 toString t]
240 toString (OperatorError p o t) = concat [
241 toString p,
242 "SemError: No ", toString o, " for type ",
243 toString t]
244 toString (UndeclaredVariableError p ident) = concat [
245 toString p, "SemError: identifier: ", ident, " undefined."]
246
247 saveGamma :: Env Gamma
248 saveGamma = get
249
250 restoreGamma :: Gamma -> Env Void
251 restoreGamma g = put g