I spent the day playing around with ANTLR getting a little expression grammer working and trying to remember parsing theory from a very long time ago.
I modified the expression grammer found here to evaluate expressions like:
1 + 1
[1 + 1] + [3 + 3];
I haven’t got the unary negative/positive signs working yet but it doesn’t look too hard.
The square brackets are weird but I used them instead of the regular parenthesis ‘(’ ‘)’ because that was used by the generated code to delimit the abstract syntax tree.
Here’s the grammer I came up with.
expr : sumExpr END! ;sumExpr : prodExpr ( (PLUS^ | MINUS^) prodExpr)* ; prodExpr : powExpr ( (MUL^ | DIV^ | MOD^) powExpr)* ;powExpr : atom (POW^ atom)? ;atom : LPAREN^ sumExpr RPAREN! | INT;
I’ll leave it as an exercise to the reader to figure out what the lexical analysis part looked like.