Skip to content

Commit

Permalink
add: parse comments
Browse files Browse the repository at this point in the history
  • Loading branch information
oriollinan committed Dec 9, 2024
1 parent d2be80f commit c883ddb
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 29 deletions.
2 changes: 1 addition & 1 deletion lib/Ast/Parser.hs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ parseVarName = do
-- | Skips whitespace and comments during parsing.
-- Used to ensure parsers handle spacing correctly.
sc :: Parser ()
sc = ML.space MC.space1 empty empty
sc = ML.space MC.space1 (ML.skipLineComment ";") empty

-- | Wraps a parser to handle leading and trailing whitespace.
-- Returns the result of the inner parser.
Expand Down
64 changes: 36 additions & 28 deletions test/Ast/ParserSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -119,34 +119,6 @@ spec = do
(Op Add (Var "x") (Var "y"))
]
)
it "parses a recursive lambda" $ do
parse "" "(define (pow x n) ( if (< n 2) (x) (* x (pow x (- n 1)))))"
`shouldBe` Right
( AST
[ Define
"pow"
( Lambda
["x", "n"]
( If
( Op Lt (Var "n") (Lit (LInt 2))
)
(Seq [Var "x"])
( Op
Mult
(Var "x")
( Call
(Var "pow")
( Seq
[ Var "x",
Op Sub (Var "n") (Lit (LInt 1))
]
)
)
)
)
)
]
)

it "fails to parse a lambda with invalid parameter list" $ do
parse "" "(lambda 42 (* 2 2))" `shouldSatisfy` isLeft
Expand Down Expand Up @@ -191,6 +163,35 @@ spec = do
]
)

it "parses a recursive function" $ do
parse "" "(define (pow x n) ( if (< n 2) (x) (* x (pow x (- n 1)))))"
`shouldBe` Right
( AST
[ Define
"pow"
( Lambda
["x", "n"]
( If
( Op Lt (Var "n") (Lit (LInt 2))
)
(Seq [Var "x"])
( Op
Mult
(Var "x")
( Call
(Var "pow")
( Seq
[ Var "x",
Op Sub (Var "n") (Lit (LInt 1))
]
)
)
)
)
)
]
)

-- \**Operation Expression Tests **
describe "Operation Expressions" $ do
it "parses an addition operation" $ do
Expand Down Expand Up @@ -312,6 +313,13 @@ spec = do
Op Add (Var "x") (Lit (LInt 3))
]
)
-- \** Comment Tests **
describe "Comments" $ do
it "parses a comment" $ do
parse "" "(define x 10) ; This is a comment"
`shouldBe` Right
( AST [Define "x" (Lit (LInt 10))]
)

-- \**Error Handling Tests **
describe "Error Handling" $ do
Expand Down

0 comments on commit c883ddb

Please # to comment.