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