I have a small custom scripting language, and I am trying to update it to allow boolean expressions such as a > 2
and a > 2 and (b < 3 or c >
Boolean expressions are just the same as the additive- and multiplicative expression, and should therefore not be separated from them. Here's how to account for all types of expressions:
grammar test;
parse
: expression EOF
;
expression
: or
;
or
: and (OR and)*
;
and
: rel (AND rel)*
;
rel
: add (('=' | '>' | '<') add)*
;
add
: mult (('+' | '-') mult)*
;
mult
: unary (('*' | '/') unary)*
;
unary
: '-' term
| '+' term
| NOT term
| term
;
term
: INTEGER
| IDENT
| list
| '(' expression ')'
;
list
: '{' (expression (',' expression)*)? '}'
;
AND : 'and';
OR : 'or';
NOT : 'not';
IDENT : LETTER LETTER*;
INTEGER : DIGIT+;
WS : (' ' | '\n' | '\r' | '\t')+ { $channel = HIDDEN; };
fragment DIGIT : '0'..'9';
fragment LETTER : ('a'..'z' | 'A'..'Z');
which will parse the example input:
abc > 3 and (xyz < 5 or xyz > {1, 2, 3})
into the following parse tree: