R71 R71 - 3 years ago 76
Java Question

Associativity and precedence of Java operators in ANTLRv4 grammar

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):


  1. According to the book, '+' has less priority than '^' and hence the '+' rule is below the '^' rule. But the Java code is the opposite.

  2. According to the book, the '^' rule has assoc=right. But the Java code does not have it, except for '^=' and similar rules.



Which is right, the book or the code?

BTW, there is another difference between the code and the book. In the code, assoc=right is at the beginning of the rule, whereas in the book it is after the operator, but it looks like the syntax was changed (the code works for 4.5.3) and the book has to be updated for this.

Here is the relevant Java.g4 code snippet:

expression
: primary
| 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
( '='
| '+='
| '^='
)
expression
;


Note: In the above question, I had assumed that ^ meant exponentiation, but as the answer pointed out, in java ^ has a different meaning.

Answer Source

Explanation

The right answer is in a Java language specification. We will focus on the current specification which is Java SE 8.

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.

15.18 Additive Operators (page 563)

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).

15.22 Bitwise and Logical Operators (page 575)

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)

15.26 Assignment Operators (page 588)

The assignment operators are:

= *= /= %= += -= <<= >>= >>>= &= ^= |=

There are 12 assignment operators; all are syntactically right-associative.

This allows for chained assignment.

Conclusion

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download