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