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
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 typeOp2 :: Expr Expr Op2 [Type] Type -> Env Type
130 typeOp2 e1 e2 op ts ret = typeExpr e1 >>= \t1-> typeExpr e2 >>= \t2->
131 unify t1 t2 >>= \t3->if (isMember t3 ts) (pure ret)
132 (liftT $ Left $ OperatorError (extrPos e1) op t3)
133
134 buildFunctionType :: String [Expr] -> Env Type
135 buildFunctionType frsh [] = let t = IdType frsh in putIdent frsh t >>| pure t
136 buildFunctionType frsh [e:es] = (->>) <$> typeExpr e <*> buildFunctionType frsh es
137
138 unifyApp :: Type [Expr] -> Env Type
139 unifyApp t [] = pure t
140 unifyApp (tf1 ->> tf2) [t1:ts] = unify tf1 t1 >>| unifyApp tf2 ts
141 unifyApp t1 t2 = liftT $ Left $ UnifyError zero t1 (IdType "[expressions, FIXME]")
142
143 typeFun :: String [Expr] -> Env Type
144 typeFun f es = gets (\(st, r)->'Map'.get f st) >>= \mt-> case mt of
145 Nothing = freshIdent >>= \frsh-> buildFunctionType frsh es
146 >>= \ft-> putIdent f ft >>| (pure $ IdType frsh)
147 Just t = unifyApp t es
148
149 resultType :: Type -> Type
150 resultType (_ ->> t) = resultType t
151 resultType t = t
152
153 class unify a :: Type a -> Env Type
154
155 instance unify [FieldSelector] where
156 unify t [] = pure t
157 unify (ListType t) [FieldHd:fs] = unify t fs
158 unify t=:(ListType _) [FieldTl:fs] = unify t fs
159 unify (TupleType (t, _)) [FieldFst:fs] = unify t fs
160 unify (TupleType (_, t)) [FieldSnd:fs] = unify t fs
161 unify t [fs:_] = liftT $ Left $ FieldSelectorError zero t fs
162
163 instance unify Expr where
164 unify (_ ->> _) e = liftT $ Left $ ParseError (extrPos e)
165 "Expression cannot be a higher order function. Yet..."
166 unify VoidType e = liftT $ Left $ ParseError (extrPos e)
167 "Expression cannot be a Void type."
168 // unify (IdType _) e = liftT $ Left $ ParseError (extrPos e)
169 // "Expression cannot be an polymorf type."
170 unify VarType e = typeExpr e
171 //we have to cheat to decorate the error, can be done nicer?
172 unify t e = StateT $ \s0 -> let res = runStateT m s0 in case res of
173 Left err = Left $ decErr e err
174 Right t = Right t //note, t :: (Type, Gamma)
175 where m = typeExpr e >>= \tex-> unify t tex
176
177 instance unify Type where
178 unify IntType IntType = pure IntType
179 unify BoolType BoolType = pure BoolType
180 unify CharType CharType = pure CharType
181 unify (IdType i) t=:(IdType j) = replace i t >>| pure t
182 unify t (IdType i) = unify (IdType i) t
183 unify (IdType i) t = replace i t >>| pure t
184 unify (ListType t1) (ListType t2) = unify t1 t2 >>| (pure $ ListType t1)
185 unify (ta1 ->> ta2) (tb1 ->> tb2) = unify ta1 tb1 >>= \ta-> unify ta2 tb2
186 >>= \tb-> pure (ta ->> tb)
187 unify t1 t2 = liftT $ Left $ UnifyError zero t1 t2
188
189 instance zero Pos where
190 zero = {line=0,col=0}
191
192 decErr :: Expr SemError -> SemError
193 decErr e (UnifyError _ t1 t2) = UnifyError (extrPos e) t1 t2
194 decErr e (FieldSelectorError _ t fs) = FieldSelectorError (extrPos e) t fs
195 decErr e (ParseError _ s) = ParseError (extrPos e) s
196 decErr e err = err
197
198 dc2 :: Expr (Either SemError a) -> Either SemError a
199 dc2 e (Right t) = Right t
200 dc2 e (Left err) = Left err
201
202 extrPos :: Expr -> Pos
203 extrPos (VarExpr p _) = p
204 extrPos (Op2Expr p _ _ _) = p
205 extrPos (Op1Expr p _ _) = p
206 extrPos (IntExpr p _) = p
207 extrPos (CharExpr p _) = p
208 extrPos (BoolExpr p _) = p
209 extrPos (FunExpr p _) = p
210 extrPos (EmptyListExpr p) = p
211 extrPos (TupleExpr p _) = p
212
213 instance toString Gamma where
214 toString (mp, _) = concat
215 [concat [k, ": ", toString v, "\n"]\\(k, v) <- 'Map'.toList mp]
216
217 getRandomStream :: Int -> [String]
218 getRandomStream i = genIdents $ filter (isAlpha o toChar) (genRandInt i)
219 where
220 genIdents r = let (ic, r2) = splitAt 5 r in [toString ic: genIdents r2]
221
222 freshIdent :: Env String
223 freshIdent = get >>= \(st, [ident:rest])-> put (st, rest)
224 >>| case 'Map'.get ident st of
225 Nothing = pure ident
226 _ = freshIdent
227
228 putIdent :: String Type -> Env Void
229 putIdent i t = gets (\(st, r)->'Map'.get i st) >>= \mt -> case mt of
230 Nothing = modify (\(st, r)->('Map'.put i t st, r))
231 Just t2 = unify t t2 >>= \t3-> modify (\(st, r)->('Map'.put i t3 st, r))
232
233 replace :: String Type -> Env Void
234 replace ident type = get >>= \(st, fr)->put ('Map'.fromList $
235 map (itupdate ident type) ('Map'.toList st), fr)
236 where
237 itupdate :: String Type (String, Type) -> (String, Type)
238 itupdate ident newtype ov=:(key, IdType type) = if (ident == type)
239 (key, newtype) ov
240 itupdate ident newtype (key, TupleType (t1, t2))
241 # (_, t1) = itupdate ident newtype (key, t1)
242 # (_, t2) = itupdate ident newtype (key, t2)
243 = (key, TupleType (t1, t2))
244 itupdate ident newtype (key, ListType t1)
245 # (_, t1) = itupdate ident newtype (key, t1)
246 = (key, ListType t1)
247 itupdate _ _ k = k
248
249 instance toString SemError where
250 toString (ParseError p e) = concat [
251 toString p,"SemError: ParseError: ", e]
252 toString (Error e) = "SemError: " +++ e
253 toString (UnifyError p t1 t2) = concat [
254 toString p,
255 "SemError: Cannot unify types. Expected: ",
256 toString t1, ". Given: ", toString t2]
257 toString (FieldSelectorError p t fs) = concat [
258 toString p,
259 "SemError: Cannot select ", toString fs, " from type: ",
260 toString t]
261 toString (OperatorError p o t) = concat [
262 toString p,
263 "SemError: No ", toString o, " for type ",
264 toString t]
265 toString (UndeclaredVariableError p ident) = concat [
266 toString p, "SemError: identifier: ", ident, " undefined."]
267
268 saveGamma :: Env Gamma
269 saveGamma = get
270
271 restoreGamma :: Gamma -> Env Void
272 restoreGamma (oldstate, _) = gets snd >>= \newr->put (oldstate, newr)