1 module Typecheck (typeCheck,typeCheckExp, typeCheckStm, typeCheckVar) where
5 import Control.Monad.State
7 import Prelude hiding (lookup)
9 type Types = [Map Ident Type]
11 inList :: Eq a => a -> [a] -> Bool
13 inList a (x:xs) = if a == x then True else inList a xs
15 assert :: Monad m => Bool -> String -> m ()
16 assert True _ = return ()
17 assert False s = fail s
19 typeCheck :: [Stm] -> IO ()
20 typeCheck s = runStateT (mapM typeCheckStm s) [empty] >> return ()
22 typeCheckExp :: (MonadState Types m) => Exp -> m Type
23 typeCheckExp (BiOpExp e o e') = do
26 assert (t1 == t2) "The parameters for the binary operator aren't equal"
27 if inList o [Eq,NEq] then return TBool
29 assert (t1 == TInt) "The parameters need to be of type int"
30 if inList o [Plus,Minus,Times,Div]
33 typeCheckExp (EVar i) = typeCheckVar i
34 typeCheckExp (EAss i e) = do
37 assert (t == t2) $ "Illegal to assign an expression of type "++show t2++" to variable "++show i++" of type "++show t
39 typeCheckExp (EInt i) = return TInt
40 typeCheckExp (EBool b) = return TBool
41 typeCheckExp EReadI = return TInt
42 typeCheckExp EReadB = return TBool
43 typeCheckExp (EPost i op) = do
44 TInt <- typeCheckVar i
46 typeCheckExp (ENeg e) = do
47 TInt <- typeCheckExp e
49 typeCheckExp (ENot e) = do
50 TBool <- typeCheckExp e
53 typeCheckVar :: (MonadState Types m) => Ident -> m Type
58 findVariable :: (MonadState Types m) => Ident -> Types -> m Type
59 findVariable i [] = fail $ "Variable "++show i++" not found in any scope."
60 findVariable i (m:ms) = if member i m then lookup i m else findVariable i ms
62 pushAndPop :: (MonadState Types m) => m a -> m ()
68 typeCheckStm :: (MonadState Types m) => Stm -> m ()
69 typeCheckStm SNoop = return ()
70 typeCheckStm (SExp e) = do
73 typeCheckStm (SBlock ss) = pushAndPop $ mapM typeCheckStm ss
74 typeCheckStm (SIf e s s') = do
75 TBool <- typeCheckExp e
76 pushAndPop $ typeCheckStm s
77 pushAndPop $ typeCheckStm s'
78 typeCheckStm (SWhile e s) = do
79 TBool <- typeCheckExp e
80 pushAndPop $ typeCheckStm s
81 typeCheckStm (SDeclD t i) = addVariable i t
82 typeCheckStm (SDecl t i e) = do
84 assert (t == t2) $ "Illegal to assign an expression of type "++show t2++" to variable "++show i++" of type "++show t
86 typeCheckStm (SPrint e) = do
90 addVariable :: (MonadState Types m) => Ident -> Type -> m ()
93 case insertLookupWithKey (\k a1 a2 -> a1) i t m of
94 (Nothing,m') -> put (m':ms)
95 _ -> fail $ "Duplicate variable declaration: "++show i