Question about null handling in SwitchLabel
Gavin Bierman
gavin.bierman at oracle.com
Tue Sep 26 21:23:46 UTC 2023
If you look in 14.11.1 of JLS just under the grammar you quoted:
> Every case constant must be either a constant expression (§15.29), or the name of an enum constant (§8.9.1), otherwise a compile-time error occurs.
That’s why null is not allowed; it’s not a constant expression, or the name of an enum constant.
Hope this helps,
Gavin
> On 26 Sep 2023, at 20:32, Robert Olofsson <robo at khelekore.org> wrote:
>
> Hi!
>
> I hope this is the right place to ask about switch and null handling.
>
> A bit of background:
> So I am trying to build my own parser (parjac2) for the java language
> and was trying to implement handling for the updated "switch"
> according to the updated grammar. This caused me some problem. So I
> tried to test a few things with javac and to me it seems like javac
> and the grammar are not fully in synch.
>
> Some parts of the grammar to make it easier to understand:
>
> SwitchRule:
> SwitchLabel -> Expression;
>
> SwitchLabel:
> case CaseConstant {, CaseConstant}
> case null [, default]
>
> CaseConstant:
> ConditionalExpression
>
> We can follow ConditionalExpression to Primary and
> Primary can be Literal so it allows "null".
>
> So to me this looks like SwitchLabel say that "null" is allowed
> anywhere in a sequence of CaseConstants, but when I try this with
> javac I of course get "error: invalid case label combination"
>
> Example program:
> ------------------------------------------------------
> class Foo {
> void foo () {
> String foo = "hello";
> switch (foo) {
> case "A", "B", null -> System.out.println ("Yup");
> default -> System.out.println ("Nope!");
> }
> }
> }
> ------------------------------------------------------
>
> Looking closer at the JLS we do find a bullet point:
> * For each case constant associated with the switch block that is a
> constant expression, the constant is assignment compatible with T, and
> T is one of char, byte, short, int, Character, Byte, Short, Integer,
> or String.
>
> So I guess this is the reason null is not allowed as CaseConstant?
>
> Actual question:
> Now that we do have the option to have null by itself or with
> default as a SwitchLAbel is there really a strong case now for not
> allowing us to do 'case "A", "B", null -> ...'?
>
> For me right now I guess I will have to find a creative way to
> rewrite the grammar I use for my parser to avoid the problem, not yet
> sure how I will do that though. Basically I get a conflict that "case
> null" can be two versions of SwitchLabel and the earley parsing
> algorithm I use do not like that, this is of course for me to figure
> out.
>
> Thank you
> /robo
More information about the compiler-dev
mailing list