From 70b68c91e008efb7a7b5baf638140cb76380f931 Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Sun, 4 Sep 2022 08:31:51 +0100 Subject: Refactored typecheck value --- src/Compiler.hs | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/Compiler.hs b/src/Compiler.hs index 40e5f73..f0169be 100644 --- a/src/Compiler.hs +++ b/src/Compiler.hs @@ -64,20 +64,25 @@ showMaybet :: Maybe A.Type -> String showMaybet Nothing = "()" showMaybet (Just t) = show t --- | @typecheckReturn value fret@ resolves @value@ and compares it with @fret@, --- returning a string decribing an error or Nothing in case of a type match. -typecheckReturn :: Maybe A.Expr -> Maybe A.Type -> State CompState (Maybe String) -typecheckReturn Nothing Nothing = return $ Nothing -typecheckReturn Nothing fret = return $ Just $ "invalid return value\n found: ()\n expected: " ++ showMaybet fret -typecheckReturn (Just value) fret = do +-- | @typecheckVal value typ@ resolves @value@ and compares it to @typ@ type, +-- returning a string describing an error or Nothin in case of type match. +typecheckVal :: A.Expr -> Maybe A.Type -> State CompState (Maybe String) +typecheckVal value typ = do r <- compile value case r of Right r -> - if r == fret + if r == typ then return $ Nothing - else return $ Just $ "invalid return value\n found: " ++ showMaybet r ++ "\n expected: " ++ showMaybet fret + else return $ Just $ "type mismatch\n found: " ++ showMaybet r ++ "\n expected: " ++ showMaybet typ Left _ -> return $ Nothing -- error resolving return value +-- | @typecheckReturn value fret@ resolves @value@ and compares it with @fret@, +-- returning a string decribing an error or Nothing in case of a type match. +typecheckReturn :: Maybe A.Expr -> Maybe A.Type -> State CompState (Maybe String) +typecheckReturn Nothing Nothing = return $ Nothing +typecheckReturn Nothing fret = return $ Just $ "invalid return value\n found: ()\n expected: " ++ showMaybet fret +typecheckReturn (Just value) fret = typecheckVal value fret + -- built-in types types = ["bool", "u8", "s8", "u16", "s16"] @@ -153,16 +158,10 @@ compile x = do if not (definedType typ) then Error UndefinedType ("undefined type in variable declaration \"" ++ ident ++ "\"") pos : errs else errs - -- type-check value - vt <- compile val + vt <- typecheckVal val $ Just typ 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 + Just err -> return $ Error TypeError err pos : errs + Nothing -> return $ errs put (ev, errs) return $ Right $ Just typ (A.Return value pos) -> do -- cgit v1.2.3