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