+typeCheckStm (SReturn e) = do
+ t <- typeCheckExp e
+ state <- get
+ (t2,_) <- lookup (function state) $ functions state
+ assert (t == t2) $ "Illegal to return "++show t++" in function "++show (function state)++" which returns "++show t2
+
+
+addVariable :: (MonadState State m) => Ident -> Type -> m ()
+addVariable i t = do
+ s <- get
+ let (m:ms) = variables s in case insertLookupWithKey (\k a1 a2 -> a1) i t m of
+ (Nothing,m') -> modify (\s -> s{ variables = m':ms})
+ _ -> fail $ "Duplicate variable declaration: "++show i
+
+typeCheckFunction :: (MonadState State m) => Func -> m ()
+typeCheckFunction (Func t i d s) = do
+ state <- get
+ modify (\s -> s{variables=[empty], function=i})
+ mapM (\(Decl t i) -> addVariable i t) d
+ case last s of
+ (SReturn _) -> return ()
+ _ -> fail $ "Function "++show i++" doesn't end with return statement"
+ mapM typeCheckStm s
+ put state
+
+addFunction :: (MonadState State m) => Func -> m ()
+addFunction (Func t i d _) = do
+ s <- get
+ let m = functions s in case insertLookupWithKey (\k a1 a2 -> a1) i (t, map (\(Decl t i) -> t) d) m of
+ (Nothing,m') -> modify (\s -> s{ functions = m'})
+ _ -> fail $ "Duplicate variable declaration: "++show i