Merge branch 'master' of github.com:dopefishh/cc1516
[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 import GenEq
22
23 from Text import class Text(concat), instance Text String
24
25 import AST
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 >>= \vd1 ->
44 mapM semFunDecl fd >>= \fd1 ->
45 mapM semVarDecl vd1 >>= \vd2 ->
46 mapM semFunDecl fd1 >>= \fd2 ->
47 mapM semVarDecl vd2 >>= \vd3 ->
48 mapM semFunDecl fd2 >>= \fd3 ->
49 mapM semVarDecl vd3 >>= \vd4 ->
50 mapM semFunDecl fd3 >>= \fd4 -> //Dit is puur om te proberen
51 pure (vd4, fd4)
52
53 semFunDecl :: FunDecl -> Env FunDecl
54 semFunDecl fd=:(FunDecl p f args mt vds stmts) =
55 (case mt of
56 Nothing = genType args >>= \infft->putIdent f infft >>| pure infft
57 Just t = putIdent f t >>| pure t) >>= \ft ->
58 saveGamma >>= \gamma ->
59 matchFunctions args ft >>= \tres->
60 mapM semVarDecl vds >>= \newvds->
61 mapM (checkStmt tres) stmts >>= \newstmts->
62 inferReturnType stmts >>= \returntype`->
63 unify returntype` tres >>= \returntype->
64 case mt of
65 Nothing = reconstructType args tres
66 >>= \ftype`->recoverType ftype`
67 >>= \ftype->restoreGamma gamma
68 >>| putIdent f ftype >>| pure (
69 FunDecl p f args (Just ftype) newvds newstmts)
70 Just t = restoreGamma gamma >>| updateFunType t returntype
71 >>= \tt-> pure (FunDecl p f args (Just tt) newvds newstmts)
72
73 recoverType :: Type -> Env Type
74 recoverType (IdType ident) = gets (\(st, r)->'Map'.get ident st)
75 >>= \mt->case mt of
76 Nothing = pure (IdType ident)
77 Just t = pure t
78 recoverType (t1 ->> t2) = recoverType t1 >>= \t1`->recoverType t2
79 >>= \t2`->pure (t1` ->> t2`)
80 recoverType t = pure t
81
82 updateFunType :: Type Type -> Env Type
83 updateFunType (t1 ->> t2) t3 = updateFunType t2 t3 >>= \t2`->pure $ t1 ->> t2`
84 updateFunType t1 t2 = unify t1 t2
85
86 inferReturnType :: [Stmt] -> Env Type
87 inferReturnType [] = pure VoidType
88 inferReturnType [ReturnStmt (Just t):rest] = typeExpr t
89 >>= \tx->inferReturnType rest >>= \ty->unify tx ty
90 inferReturnType [ReturnStmt _:rest] =
91 inferReturnType rest >>= \tx-> unify VoidType tx
92 inferReturnType [_:rest] = inferReturnType rest
93
94 reconstructType :: [String] Type -> Env Type
95 reconstructType [] t = pure t
96 reconstructType [x:xs] t = gets (\(st, r)->'Map'.get x st)
97 >>= \mtype->case mtype of
98 Nothing = liftT $ Left $ Error "Not used ????"
99 Just type = reconstructType xs t >>= \resttype->pure (type ->> resttype)
100
101 genType :: [String] -> Env Type
102 genType [] = freshIdent >>= \fi->pure $ IdType fi
103 genType [x:xs] = liftM2 (->>) (freshIdent >>= \fi->pure $ IdType fi)
104 (genType xs)
105
106 matchFunctions :: [String] Type -> Env Type
107 matchFunctions [] (_ ->> _) = liftT $ Left $
108 ArgumentMisMatchError zero "Not enough arguments"
109 matchFunctions _ (VoidType ->> _) = liftT $ Left $
110 ArgumentMisMatchError zero "Void can't be a non return type"
111 matchFunctions [x:xs] (t1 ->> t2) =
112 modify (\(st, r)->('Map'.put x t1 st, r)) >>| matchFunctions xs t2
113 matchFunctions [] t = pure t
114 matchFunctions _ t = liftT $ Left $
115 ArgumentMisMatchError zero "Too much argumnts"
116
117 semVarDecl :: VarDecl -> Env VarDecl
118 semVarDecl (VarDecl pos type ident ex) = unify type ex
119 >>= \t-> putIdent ident t >>| (pure $ VarDecl pos t ident ex)
120
121 checkStmt ::Type Stmt -> Env Stmt
122 checkStmt t (IfStmt c st se) = unify BoolType c >>| mapM (checkStmt t) st
123 >>= \st1-> mapM (checkStmt t) se >>= \se1-> pure (IfStmt c st1 se1)
124 checkStmt t w=:(WhileStmt c et) = unify BoolType c >>| mapM (checkStmt t) et
125 >>= \et1-> pure w
126 checkStmt t a=:(AssStmt (VarDef ident fs) e) = gets (\(st, r)->'Map'.get ident st)
127 >>= \mt->case mt of
128 Nothing = liftT $ Left $ UndeclaredVariableError zero ident
129 Just t = unify t fs >>= \t1 -> unify t1 e >>| pure a
130 checkStmt t r=:(FunStmt (FunCall f es)) = typeFun f es >>| pure r
131 checkStmt VoidType r=:(ReturnStmt Nothing) = pure r
132 checkStmt t r=:(ReturnStmt (Just e)) = unify t e >>| pure r
133
134 typeExpr :: Expr -> Env Type
135 typeExpr (IntExpr _ _) = pure IntType
136 typeExpr (CharExpr _ _) = pure CharType
137 typeExpr (BoolExpr _ _) = pure BoolType
138 typeExpr (Op1Expr p UnNegation expr) = unify BoolType expr
139 typeExpr (Op1Expr p UnMinus expr) = unify IntType expr
140 typeExpr (TupleExpr p (e1, e2)) = typeExpr e1
141 >>= \t1-> typeExpr e2 >>= \t2-> pure $ TupleType (t1, t2)
142 typeExpr (Op2Expr p e1 op e2)
143 | isMember op [BiPlus, BiMinus, BiTimes, BiDivide, BiMod] =
144 typeOp2 e1 e2 op [IntType] IntType
145 | isMember op [BiEquals, BiUnEqual] =
146 typeOp2 e1 e2 op [IntType, BoolType, CharType] BoolType
147 | isMember op [BiLesser, BiGreater, BiLesserEq, BiGreaterEq] =
148 typeOp2 e1 e2 op [IntType, CharType] BoolType
149 | isMember op [BiAnd, BiOr] =
150 typeOp2 e1 e2 op [BoolType] BoolType
151 | op == BiCons = typeExpr e1 >>= \t1-> typeExpr e2
152 >>= \t2-> unify (ListType t1) t2
153 typeExpr (EmptyListExpr p) = freshIdent >>= \frsh-> let t = IdType frsh in
154 putIdent frsh t >>| pure t
155 typeExpr (FunExpr p (FunCall f es)) = typeFun f es
156 typeExpr (VarExpr p (VarDef ident fs)) = gets (\(st, r)->'Map'.get ident st)
157 >>= \mt->case mt of
158 Nothing = liftT $ Left $ UndeclaredVariableError p ident
159 Just t = unify t fs
160 typeOp2 :: Expr Expr Op2 [Type] Type -> Env Type
161 typeOp2 e1 e2 op ts ret = typeExpr e1 >>= \t1-> typeExpr e2 >>= \t2->
162 unify t1 t2 >>= \t3->if (isMember t3 [IdType "":ts]) (pure ret)
163 (liftT $ Left $ OperatorError (extrPos e1) op t3)
164
165 buildFunctionType :: String [Expr] -> Env Type
166 buildFunctionType frsh [] = let t = IdType frsh in putIdent frsh t >>| pure t
167 buildFunctionType frsh [e:es] = (->>) <$> typeExpr e <*> buildFunctionType frsh es
168
169 unifyApp :: Type [Expr] -> Env Type
170 unifyApp t [] = pure t
171 unifyApp (tf1 ->> tf2) [t1:ts] = unify tf1 t1 >>| unifyApp tf2 ts
172 unifyApp t1 t2 = liftT $ Left $ UnifyError zero t1 (IdType "[expressions, FIXME]")
173
174 typeFun :: String [Expr] -> Env Type
175 typeFun f es = gets (\(st, r)->'Map'.get f st) >>= \mt-> case mt of
176 Nothing = freshIdent >>= \frsh-> buildFunctionType frsh es
177 >>= \ft-> putIdent f ft >>| (pure $ IdType frsh)
178 Just t = unifyApp t es
179
180 resultType :: Type -> Type
181 resultType (_ ->> t) = resultType t
182 resultType t = t
183
184 class unify a :: Type a -> Env Type
185
186 instance unify [FieldSelector] where
187 unify t [] = pure t
188 unify (ListType t) [FieldHd:fs] = unify t fs
189 unify t=:(ListType _) [FieldTl:fs] = unify t fs
190 unify (TupleType (t, _)) [FieldFst:fs] = unify t fs
191 unify (TupleType (_, t)) [FieldSnd:fs] = unify t fs
192 unify t [fs:_] = liftT $ Left $ FieldSelectorError zero t fs
193
194 instance unify Expr where
195 unify (_ ->> _) e = liftT $ Left $ ParseError (extrPos e)
196 "Expression cannot be a higher order function. Yet..."
197 unify VoidType e = liftT $ Left $ ParseError (extrPos e)
198 "Expression cannot be a Void type."
199 // unify (IdType _) e = liftT $ Left $ ParseError (extrPos e)
200 // "Expression cannot be an polymorf type."
201 unify VarType e = typeExpr e
202 //we have to cheat to decorate the error, can be done nicer?
203 unify t=:(IdType id) e = typeExpr e >>= \tex->unify t tex
204 >>= \type->putIdent id type >>| pure type
205 unify t e = StateT $ \s0 -> let res = runStateT m s0 in case res of
206 Left err = Left $ decErr e err
207 Right t = Right t //note, t :: (Type, Gamma)
208 where m = typeExpr e >>= \tex-> unify t tex
209
210 instance unify Type where
211 unify IntType IntType = pure IntType
212 unify BoolType BoolType = pure BoolType
213 unify CharType CharType = pure CharType
214 unify (IdType i) t=:(IdType j) = replace i t >>| pure t
215 unify t (IdType i) = unify (IdType i) t
216 unify (IdType i) t = replace i t >>| pure t
217 unify (ListType t1) (ListType t2) = unify t1 t2 >>| (pure $ ListType t1)
218 unify (ta1 ->> ta2) (tb1 ->> tb2) = unify ta1 tb1 >>= \ta-> unify ta2 tb2
219 >>= \tb-> pure (ta ->> tb)
220 unify VoidType VoidType = pure VoidType
221 unify VoidType t = pure t
222 unify t VoidType = pure t
223 unify t1 t2 = liftT $ Left $ UnifyError zero t1 t2
224
225 instance zero Pos where
226 zero = {line=0,col=0}
227
228 decErr :: Expr SemError -> SemError
229 decErr e (UnifyError _ t1 t2) = UnifyError (extrPos e) t1 t2
230 decErr e (FieldSelectorError _ t fs) = FieldSelectorError (extrPos e) t fs
231 decErr e (ParseError _ s) = ParseError (extrPos e) s
232 decErr e err = err
233
234 dc2 :: Expr (Either SemError a) -> Either SemError a
235 dc2 e (Right t) = Right t
236 dc2 e (Left err) = Left err
237
238 extrPos :: Expr -> Pos
239 extrPos (VarExpr p _) = p
240 extrPos (Op2Expr p _ _ _) = p
241 extrPos (Op1Expr p _ _) = p
242 extrPos (IntExpr p _) = p
243 extrPos (CharExpr p _) = p
244 extrPos (BoolExpr p _) = p
245 extrPos (FunExpr p _) = p
246 extrPos (EmptyListExpr p) = p
247 extrPos (TupleExpr p _) = p
248
249 instance toString Gamma where
250 toString (mp, _) = concat
251 [concat [k, ": ", toString v, "\n"]\\(k, v) <- 'Map'.toList mp]
252
253 getRandomStream :: Int -> [String]
254 getRandomStream i = genIdents $ filter (isAlpha o toChar) (genRandInt i)
255 where
256 genIdents r = let (ic, r2) = splitAt 5 r in [toString ic: genIdents r2]
257
258 freshIdent :: Env String
259 freshIdent = get >>= \(st, [ident:rest])-> put (st, rest)
260 >>| case 'Map'.get ident st of
261 Nothing = pure ident
262 _ = freshIdent
263
264 putIdent :: String Type -> Env Void
265 putIdent i t = gets (\(st, r)->'Map'.get i st) >>= \mt -> case mt of
266 Nothing = modify (\(st, r)->('Map'.put i t st, r))
267 Just t2 = unify t t2 >>= \t3-> modify (\(st, r)->('Map'.put i t3 st, r))
268
269 replace :: String Type -> Env Void
270 replace ident type = get >>= \(st, fr)->put ('Map'.fromList $
271 map (itupdate ident type) ('Map'.toList st), fr)
272 where
273 itupdate :: String Type (String, Type) -> (String, Type)
274 itupdate ident newtype ov=:(key, IdType type) = if (ident == type)
275 (key, newtype) ov
276 itupdate ident newtype (key, TupleType (t1, t2))
277 # (_, t1) = itupdate ident newtype (key, t1)
278 # (_, t2) = itupdate ident newtype (key, t2)
279 = (key, TupleType (t1, t2))
280 itupdate ident newtype (key, ListType t1)
281 # (_, t1) = itupdate ident newtype (key, t1)
282 = (key, ListType t1)
283 itupdate _ _ k = k
284
285 instance toString SemError where
286 toString (ParseError p e) = concat [toString p,
287 "SemError: ParseError: ", e]
288 toString (UnifyError p t1 t2) = concat [ toString p,
289 "SemError: Cannot unify types. Expected: ",
290 toString t1, ". Given: ", toString t2]
291 toString (FieldSelectorError p t fs) = concat [ toString p,
292 "SemError: Cannot select ", toString fs, " from type: ",
293 toString t]
294 toString (OperatorError p o t) = concat [
295 toString p,
296 "SemError: No ", toString o, " for type ",
297 toString t]
298 toString (UndeclaredVariableError p ident) = concat [
299 toString p, "SemError: identifier: ", ident, " undefined."]
300 toString (ArgumentMisMatchError p s) = concat [toString p,
301 "SemError: Argument mismatch: ", s]
302 toString (Error e) = "SemError: " +++ e
303
304 saveGamma :: Env Gamma
305 saveGamma = get
306
307 restoreGamma :: Gamma -> Env Void
308 restoreGamma (oldstate, _) = gets snd >>= \newr->put (oldstate, newr)
309
310 derive gEq Type
311 instance == Type where
312 (==) (IdType _) (IdType _) = True
313 (==) o1 o2 = gEq{|*|} o1 o2