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