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