Fix type mismatch and redefinition issues in typeCheckStatement function
This commit is contained in:
parent
0debfe995d
commit
ae6232380e
12
src/Ast.hs
12
src/Ast.hs
@ -278,7 +278,7 @@ typeCheckStatement (Block statements) symtab classes =
|
|||||||
|
|
||||||
If {} -> (accSts ++ [checkedStmt], currentSymtab, if stmtType /= "Void" then types ++ [stmtType] else types)
|
If {} -> (accSts ++ [checkedStmt], currentSymtab, if stmtType /= "Void" then types ++ [stmtType] else types)
|
||||||
While _ _ -> (accSts ++ [checkedStmt], currentSymtab, if stmtType /= "Void" then types ++ [stmtType] else types)
|
While _ _ -> (accSts ++ [checkedStmt], currentSymtab, if stmtType /= "Void" then types ++ [stmtType] else types)
|
||||||
Return _ -> (accSts ++ [checkedStmt], currentSymtab, if stmtType /= "Void" then types ++ [stmtType])
|
Return _ -> (accSts ++ [checkedStmt], currentSymtab, if stmtType /= "Void" then types ++ [stmtType] else types)
|
||||||
_ -> (accSts ++ [checkedStmt], currentSymtab, types)
|
_ -> (accSts ++ [checkedStmt], currentSymtab, types)
|
||||||
|
|
||||||
-- Initial accumulator: empty statements list, initial symbol table, empty types list
|
-- Initial accumulator: empty statements list, initial symbol table, empty types list
|
||||||
@ -290,8 +290,16 @@ typeCheckStatement (Block statements) symtab classes =
|
|||||||
in TypedStatement blockType (Block checkedStatements)
|
in TypedStatement blockType (Block checkedStatements)
|
||||||
|
|
||||||
typeCheckStatement (LocalVariableDeclaration (VariableDeclaration dataType identifier maybeExpr)) symtab classes =
|
typeCheckStatement (LocalVariableDeclaration (VariableDeclaration dataType identifier maybeExpr)) symtab classes =
|
||||||
|
-- Check for redefinition in the current scope
|
||||||
|
if any ((== identifier) . snd) symtab
|
||||||
|
then error $ "Variable '" ++ identifier ++ "' is redefined in the same scope"
|
||||||
|
else
|
||||||
|
-- If there's an initializer expression, type check it
|
||||||
let checkedExpr = fmap (\expr -> typeCheckExpression expr symtab classes) maybeExpr
|
let checkedExpr = fmap (\expr -> typeCheckExpression expr symtab classes) maybeExpr
|
||||||
in TypedStatement dataType (LocalVariableDeclaration (VariableDeclaration dataType identifier checkedExpr))
|
exprType = fmap getTypeFromExpr checkedExpr
|
||||||
|
in case exprType of
|
||||||
|
Just t | t /= dataType -> error $ "Type mismatch in declaration of '" ++ identifier ++ "': expected " ++ dataType ++ ", found " ++ t
|
||||||
|
_ -> TypedStatement dataType (LocalVariableDeclaration (VariableDeclaration dataType identifier checkedExpr))
|
||||||
|
|
||||||
typeCheckStatement (Return expr) symtab classes =
|
typeCheckStatement (Return expr) symtab classes =
|
||||||
let expr' = case expr of
|
let expr' = case expr of
|
||||||
|
Loading…
Reference in New Issue
Block a user