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