From 58c6c294e2c6a6488eab140b165071103612a5cb Mon Sep 17 00:00:00 2001 From: Oriol Linan Date: Wed, 8 Jan 2025 16:00:00 +0100 Subject: [PATCH] add: parse `Cast` --- lib/Ast/Parser/Expr.hs | 8 ++++++++ test/Ast/Parser/ExprSpec.hs | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/Ast/Parser/Expr.hs b/lib/Ast/Parser/Expr.hs index 147ece4..e0726a4 100644 --- a/lib/Ast/Parser/Expr.hs +++ b/lib/Ast/Parser/Expr.hs @@ -24,6 +24,7 @@ parseExpr = parseBreak, parseContinue, parseBlock, + parseCast, parseLit, M.try parseFunction, M.try parseDeclaration, @@ -184,6 +185,13 @@ parseArrayAccess = do pos <- PU.symbol "." *> parseExpr return $ AT.ArrayAccess srcLoc value pos +parseCast :: PU.Parser AT.Expr +parseCast = do + srcLoc <- parseSrcLoc + type' <- PU.symbol "@" *> PT.parseType + expr <- M.between (PU.symbol "(") (PU.symbol ")") parseExpr + return $ AT.Cast srcLoc type' expr + parseSrcLoc :: PU.Parser AT.SrcLoc parseSrcLoc = do (MP.SourcePos {MP.sourceName = _sourceName, MP.sourceLine = _sourceLine, MP.sourceColumn = _sourceColumn}) <- M.getSourcePos diff --git a/test/Ast/Parser/ExprSpec.hs b/test/Ast/Parser/ExprSpec.hs index 6c4c28c..fafd7a2 100644 --- a/test/Ast/Parser/ExprSpec.hs +++ b/test/Ast/Parser/ExprSpec.hs @@ -221,6 +221,17 @@ spec = do (AT.Lit normalizeLoc $ AT.LInt 1) result `shouldBe` expected + it "parses an type cast" $ do + let input = "@int('a')" + let result = normalizeExpr <$> parseWithEnv input + let expected = + Right $ + AT.Cast + normalizeLoc + (AT.TInt 32) + (AT.Lit normalizeLoc $ AT.LChar 'a') + result `shouldBe` expected + normalizeLoc :: AT.SrcLoc normalizeLoc = AT.SrcLoc "" 0 0