From a33620210a161a20b60a138a0b984a5336a45f2d Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Sun, 4 Sep 2022 08:21:31 +0100 Subject: Type-checking variable declaration --- src/Compiler.hs | 11 ++++++++++- test/Language.hs | 20 +++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/Compiler.hs b/src/Compiler.hs index f36083c..40e5f73 100644 --- a/src/Compiler.hs +++ b/src/Compiler.hs @@ -153,7 +153,16 @@ compile x = do if not (definedType typ) then Error UndefinedType ("undefined type in variable declaration \"" ++ ident ++ "\"") pos : errs else errs - -- TODO: typecheck value + -- type-check value + vt <- compile val + errs <- case vt of + Right (Just t) -> + if t == typ + then return $ errs + else return $ (Error TypeError ("value type mismatch\n found: " ++ show t ++ "\n expected: " ++ show typ) pos) : errs + _ -> do + (_, errs) <- get -- error resolving value + return $ errs put (ev, errs) return $ Right $ Just typ (A.Return value pos) -> do diff --git a/test/Language.hs b/test/Language.hs index 19ec5bf..84c72ae 100644 --- a/test/Language.hs +++ b/test/Language.hs @@ -309,6 +309,22 @@ testCaseE12 = \var a: undef = 1;\n" E.UndefinedType +testCaseE13 = + TestLabel "type mismatch in variable declaration" $ + TestCase $ + expectError + "module main\n\ + \var a: bool = 0;\n" + E.TypeError + +testCaseE14 = + TestLabel "type mismatch in variable declaration (lambda)" $ + TestCase $ + expectError + "module main\n\ + \var a: bool = (a:u8): u8 { return a; };\n" + E.TypeError + language = [ testCase2, testCase3, @@ -334,5 +350,7 @@ language = testCaseE9, testCaseE10, testCaseE11, - testCaseE12 + testCaseE12, + testCaseE13, + testCaseE14 ] -- cgit v1.2.3