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