Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AnTLR4 strange behavior in precedence

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

like image 742
pinker Avatar asked Aug 31 '15 21:08

pinker


1 Answers

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.

like image 177
M. Shaw Avatar answered Oct 19 '22 05:10

M. Shaw