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