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