1 module Typecheck (typeCheckExp, typeCheckStm, typeCheckVar) where
4 import Control.Monad.State
6 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 typeCheckExp :: (MonadState Types m) => Exp -> m Type
16 typeCheckExp (BiOpExp e o e') = do
19 if not(t1 == t2) then fail "The parameters for the binary operator aren't equal"
20 else if inList o [Eq,NEq] then return TBool
21 else if not(t1 == TInt) then fail "The parameters need to be of type int"
22 else if inList o [Plus,Minus,Times,Div]
25 typeCheckExp (EVar i) = typeCheckVar i
26 typeCheckExp (EAss i e) = do
29 if a == b then return a else fail "FEL!"
30 typeCheckExp (EInt i) = return TInt
31 typeCheckExp (EBool b) = return TBool
32 typeCheckExp EReadI = return TInt
33 typeCheckExp EReadB = return TBool
34 typeCheckExp (ExpT t e) = do
36 if t == t2 then return t else fail "FEL!"
37 typeCheckExp EDefault = return NoType
38 typeCheckExp (EPost i op) = do
39 TInt <- typeCheckVar i
41 typeCheckExp (ENeg e) = do
42 TInt <- typeCheckExp e
46 typeCheckVar :: (MonadState Types m) => Ident -> m Type
51 typeCheckStm :: (MonadState Types m) => Stm -> m Type
52 typeCheckStm SNoop = return NoType
53 typeCheckStm (SExp e) = do
56 typeCheckStm (SBlock ss) = do
59 typeCheckStm (SIf e s s') = do
60 TBool <- typeCheckExp e
61 NoType <- typeCheckStm s
62 NoType <- typeCheckStm s
64 typeCheckStm (SWhile e s) = do
65 TBool <- typeCheckExp e
66 NoType <- typeCheckStm s
68 typeCheckStm (SDecl t i e) = do
70 if t == t2 || t2 == NoType then do
72 case insertLookupWithKey (\k a1 a2 -> a1) i t m of
73 (Nothing,m') -> put m'
74 _ -> fail $ "Duplicate variable declaration: "++show i
76 else fail $ "Illegal to assign an expression of type "++show t2++" to variable "++show i++" of type "++show t
77 typeCheckStm (SPrint e) = do