1

I have the rule:

expression
   : //...
   | expression (relative_operator expression)+
   | //...
   ;

Ideally, when I put in 1=1=1, it will produce the expression(1, =, 1, =, 1) tree. However, in reality it produces expression(1, =, expression(1, =, 1)). This is because it prefers to parse recursively rather than in a line. Is it possible to explicitly tell a rule that it either can't recurse on itself, or it should prefer to obey the +/* before trying to recurse on itself?

Unlocked
  • 648
  • 6
  • 19

1 Answers1

3

Is it possible to explicitly tell a rule that it either can't recurse on itself, or it should prefer to obey the +/* before trying to recurse on itself?

No, you will have to rewrite your grammar like this:

expr
 : add
 ;

add
 : mult ( ( '+' | '-' ) mult )*
 ;

mult
 : unary ( ( '*' | '/' ) unary )*
 ;

unary
 : '-'? atom
 ;

atom
 : '(' expr ')'
 | NUMBER
 | VARIABLE
 ;

which will parse input like 1 + 2 + 3 * 4 * 5 / 6 into the following tree:

enter image description here

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288