Question about null handling in SwitchLabel

Robert Olofsson robo at khelekore.org
Fri Sep 29 18:37:11 UTC 2023


Hi!

Thank you Gavin, I do appreciate that you are trying to help.

On Tue, 26 Sep 2023 21:23:46 +0000
Gavin Bierman <gavin.bierman at oracle.com> wrote:

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

Yes, this much is clear. It is also in line with the comment I found.
It is however not what the actual grammar say.

I find it a bit funny and/or annoying that the grammar is not good
enough to really be used. I think it would be really nice to have an
accurate grammar, but it may be that java is too complex to really
allow this.

But I will try to be clearer.

Why is null only allowed on its own or with default.
Why is the grammar not looking like:
---------------------------------------------------------
SwitchLabel:
  case Switchable {, Switchable}

Switchable:
  CaseConstant
  null
  default
---------------------------------------------------------
CaseConstant would of course still be required to be a constant and
null and default could only be used once, but having something like
the above would allow for the example that I gave:
case "A", "B", null -> ....

I do not really have any real use case for this, but to me the current
grammar seems to have a bit complexity that may not be needed and I am
curious if there is a reason for it.

Now, talking about constant expressions is also a bit interesting,
when I look at the grammar
(https://docs.oracle.com/javase/specs/jls/se21/html/jls-19.html)
I find 
ConstantExpression:
  Expression

at the bottom, but searching for ConstantExpressioon gives only this
result, so ConstantExpression is not used in the grammar. Is it needed
by anything or is it something that ought to be removed?

Thanks!
/robo


More information about the compiler-dev mailing list