I have a very simple test grammar as following:
grammar Test;
statement: expression EOF;
expression
: Identifier
| expression binary_op expression
| expression assignment_operator expression
| expression '.' Identifier
;
binary_op: '+';
assignment_operator : '=' ;
Identifier : [a-zA-Z]+ ;
WS : [ \n\r\t]+ -> channel(HIDDEN) ;
With this version of the grammar I got the expected behavior if I write the following code:
b.x + b.y
I get a tree as (+ (. b x) (. b y))
However, if I replace expression binary_op expression
by expression '+' expression
I get a very different tree: (. (+ (. b x) b) y)
Is there any explanation for this?
Thanks
You have to set the precendence using something like this:
expr : expr2 (assignment_operator expr3)? # Equals
expr2 : expr1 (binary_op expr2)? # Add
expr1 : Identifier |
expr1 . Identifier
;
This removes all ambiguity on operator precendence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With