[18][guarded pattern] conditional-and query - spec clarification
Gavin Bierman
gavin.bierman at oracle.com
Thu Mar 10 20:21:06 UTC 2022
Hi Manoj,
It’s a slightly moot point, given that we are likely to drop guarded patterns in the next preview but I think there has been some confusion here...
On 7 Mar 2022, at 07:08, Manoj Palat <manoj.palat at in.ibm.com<mailto:manoj.palat at in.ibm.com>> wrote:
Hi,
Given,
public void bar(Object o) {
int i = switch(o) {
case String a && o != null ? true : false -> 1;//ecj flags syntax error here
default -> 1;
};
}
ECJ(eclipse compiler for Java) flags a syntax error on the guarded pattern. However, javac accepts.
Ecj translates this into:
case ((String a) && (o != null)) ? true : false
and flags an error instead of
case ((String a) && ((o != null) ? true : false))
The idea of guarded patterns is that we give a secondary role to `&&` to serve as an operator for patterns.
After the `case` we parse a pattern. One of the form of a pattern is a guarded pattern which is:
GuardedPattern:
PrimaryPattern && ConditionalAndExpression
Given the grammar as per http://cr.openjdk.java.net/~gbierman/jep420/jep420-20211208/specs/patterns-switch-jls.html I think javac is parsing this correctly.
I don’t know quite what ecj is doing here because the translation you give above seems to suggest that it was accepting an expression after the `case` which is not correct. Moreover, the inner expression (String a) && (o != null) is not an expression but a (guarded) pattern.
And I think the ecj is correct in flagging the error due to:
From https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html we see that Conditional-And Operator “&&” has higher operator precedence than the Conditional Operator “?:” . From https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.23, we see that “The conditional-and operator is syntactically left-associative (it groups left-to-right).”
Also, I don't see any mention of the precedence changes in spec 420 [latest at https://cr.openjdk.java.net/~gbierman/jep420/latest]
I don’t see the connection with precedence - we certainly didn’t make any changes.
Am I understanding your issue correctly?
Thanks,
Gavin
More information about the amber-spec-observers
mailing list