Skip to content

Commit

Permalink
Give unary minus higher precedence, fixes #8
Browse files Browse the repository at this point in the history
  • Loading branch information
rockofox committed Dec 28, 2023
1 parent 68ecd7d commit c30c053
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/Parser.hs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ binOpTable :: [[Operator Parser Expr]]
binOpTable =
[ [prefix "^" Flexible]
, [prefix "$" StrictEval]
, [prefix "!" Not]
, [prefix "-" UnaryMinus]
, [binary "**" Power, binary "*" Mul, binary "/" Div]
, [binary "%" Modulo]
, [binary "+" Add, binary "-" Sub]
Expand All @@ -93,8 +95,6 @@ binOpTable =
, [binary ":" ListConcat]
, [binary "==" Eq, binary "!=" Neq, binary "<=" Le, binary ">=" Ge, binary "<" Lt, binary ">" Gt]
, [binary "&&" And, binary "||" Or]
, [prefix "!" Not]
, [prefix "-" UnaryMinus]
]

binary :: Text -> (Expr -> Expr -> Expr) -> Operator Parser Expr
Expand Down
13 changes: 13 additions & 0 deletions tests/ParserSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,16 @@ spec = do
parserCompilerFlags
`shouldBe` Right
(Program [FuncCall "filter" [FuncCall "==" [IntLit 1] anyPosition, ListLit [IntLit 1, IntLit 2, IntLit 3]] anyPosition])
describe "Unary minus" $ do
it "Should parse unary minus" $
parseProgram "-1" parserCompilerFlags
`shouldBe` Right
(Program [UnaryMinus (IntLit 1)])
it "Should be able to use negative numbers in multiplication" $
parseProgram "1 *-1" parserCompilerFlags
`shouldBe` Right
(Program [Mul (IntLit 1) (UnaryMinus (IntLit 1))])
it "Should be able to negate expressions in parentheses" $
parseProgram "2 * -(3-x*5)" parserCompilerFlags
`shouldBe` Right
(Program [Mul (IntLit 2) (UnaryMinus (Sub (IntLit 3) (Mul (Var "x" anyPosition) (IntLit 5))))])

0 comments on commit c30c053

Please sign in to comment.