1 module 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 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 t == t2 then return t else fail $ "Illegal to assign an expression of type "++show t2++" to variable "++show i++" of type "++show t
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 "Something went wrong ExpT is created with the wrong type"
37 typeCheckExp EDefault = return NoType
38 typeCheckExp (EPost i op) = do
39 TInt <- typeCheckVar i
41 typeCheckExp (ENeg e) = do
42 TInt <- typeCheckExp e
44 typeCheckExp (ENot e) = do
45 TBool <- typeCheckExp e
48 typeCheckVar :: (MonadState Types m) => Ident -> m Type
53 findVariable :: (MonadState Types m) => Ident -> Types -> m Type
54 findVariable i [] = fail $ "Variable "++show i++" not found in any scope."
55 findVariable i (m:ms) = if member i m then lookup i m else findVariable i ms
57 typeCheckStm :: (MonadState Types m) => Stm -> m Type
58 typeCheckStm SNoop = return NoType
59 typeCheckStm (SExp e) = do
62 typeCheckStm (SBlock ss) = do
67 typeCheckStm (SIf e s s') = do
68 TBool <- typeCheckExp e
69 NoType <- typeCheckStm s
70 NoType <- typeCheckStm s
72 typeCheckStm (SWhile e s) = do
73 TBool <- typeCheckExp e
74 NoType <- typeCheckStm s
76 typeCheckStm (SDecl t i e) = do
78 if t == t2 || t2 == NoType then do
80 case insertLookupWithKey (\k a1 a2 -> a1) i t m of
81 (Nothing,m') -> put (m':ms)
82 _ -> fail $ "Duplicate variable declaration: "++show i
84 else fail $ "Illegal to assign an expression of type "++show t2++" to variable "++show i++" of type "++show t
85 typeCheckStm (SPrint e) = do