Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design rationality of expression levels in the Java grammar

I'm currently looking at the Java 7 grammar, and trying to figure out why several different expression levels are used. Clearly, there are some design decision made to avoid certain constructs that are not valid. However, in the documentation of the Java grammar I am not able to find these decisions.

For instance, consider the production "Expression1Rest: ? Expression : Expression1". Why is the "if-part" an Expression, and the else-part an Expression1?

This means that the following Java code does not result in a syntax error in NetBeans:

String value = "";
String x = value.isEmpty() ? x = "empty" : "no";

The official Java grammar can be found here: reference link

The relevant expression productions:

Expression: 
    Expression1 [AssignmentOperator Expression1]

Expression1: 
    Expression2 [Expression1Rest]

Expression1Rest: 
    ? Expression : Expression1

Expression2:
    Expression3 [Expression2Rest]

Expression2Rest:
    { InfixOp Expression3 }
    instanceof Type

Expression3: 
    PrefixOp Expression3
    ( (Expression | Type) ) Expression3
    Primary { Selector } { PostfixOp }

Is there some documentation / research paper that explains the decisions behind the Java grammar?

like image 220
eider Avatar asked Jan 26 '26 00:01

eider


1 Answers

The grammar that you have posted allows the left-hand-side of an assignment operator to be a conditional expression:

shouldSetFoo() ? foo : bar = 47;

So it would naturally cause ambiguities if the "else" branch of a conditional expression could itself be an assignment expression.

This problem does not affect the "then" branch, since the ? and : set off that branch explicitly, preventing any ambiguity.

like image 57
ruakh Avatar answered Jan 27 '26 12:01

ruakh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!