I am trying to understand the features of antlr4, and going through the reference code and the book, and I have a question on the 'expression' rules in Java.g4 (https://raw.githubusercontent.com/antlr/grammars-v4/master/java/Java.g4) and the book (2nd ed 2012, page 73):
| expression ('*'|'/'|'%') expression
| expression ('+'|'-') expression
| expression '^' expression
// this indicates that precedence is: * > + > ^
// BUT it SHOULD be: ^ > * > +
// and both + and ^ are assoc=left
// BUT it SHOULD be: LEFT for + and RIGHT for ^
| <assoc=right> expression
In the language description we are interested in three subsections about binary operator expressions (15.2 Forms of Expressions). The earlier opearator is described the higher precedence it has.
The operators + and - are called the additive operators.
Then we read:
The additive operators have the same precedence and are syntactically left-associative (they group left-to-right).
The bitwise operators and logical operators include the AND operator &, exclusive OR operator ^, and inclusive OR operator |.
Then we read:
Each of these operators is syntactically left-associative (each groups left-to-right)
The assignment operators are:
= *= /= %= += -= <<= >>= >>>= &= ^= |=
There are 12 assignment operators; all are syntactically right-associative.
This allows for chained assignment.
In Java 8 additive plus operator
+ has a higher precedence than exclusive OR operator
^. The XOR
^ operator and the additive plus operator
+ are left-associative. Right-associativity of assignment operators (e.g.
^=) allows for chained assignment.
The Java.g4 code snippet pasted by you is correct.