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