问题
say I have the following
Grammar #1
expr:
expr AND expr
| expr OR expr
| primary
;
and is turned into this.
Grammar #2
expr:
andExpr
| primary
;
andExpr: orExpr AND orExpr;
orExpr: ... OR ...;
but I still don't see how this would solve the problem? In Grammar #1 I can express
true and false and true and true or false
true or false and true
I can keep chaining like this with Grammar #1. But I am not seeing how to achieve this using grammar #2?
回答1:
You could write it like this:
grammar Test;
parse
: expr EOF
;
expr
: or_expr
;
or_expr
: and_expr (OR and_expr)*
;
and_expr
: primary (AND primary)*
;
primary
: TRUE
| FALSE
| '(' expr ')'
;
TRUE : 'true';
FALSE : 'false';
AND : 'and';
OR : 'or';
SPACES
: [ \t\r\n] -> skip
;
This will keep AND expressions have a higher precedence than OR expressions.
Parsing input like this: true and ((false or true) and true or false)
results in the following parse tree:
来源:https://stackoverflow.com/questions/60184169/can-left-recursion-be-eliminated-in-all-cases-in-antlr