[switch] Status of implementation of switch expression

John Rose john.r.rose at oracle.com
Tue Feb 27 21:58:17 UTC 2018


On Feb 27, 2018, at 12:24 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
> 
> Does the case null have to be first, or are there other ordering constraints?

I'd rather not see new extra-logical constraints on label placement,
although I understand that "default" looks problematic when it occurs
in the middle of a switch, and maybe has to come last in order to be
logically downstream of all other case labels.  (Or else it needs special
pleading to exempt it from ordering rules that apply other labels.)

In any case, null doesn't logically need further constraints.  Since all
labels come before the default label, and since the implicit NPE
generator only applies if no other labels apply, then we may as well
view the implicit NPE generator as *always* being present, on the
default path taken to the default: label.  That way, either some label
accepts a null, and so given a null transfers control to a non-NPE
statement, or else no label accepts a null, and so a null transfers
control the implicitly inserted NPE generator placed on the path
leading to the default label.

I say "path leading to the default label", and not just "code at
the default label", only because an explicit "case null:" or
other null-accepting case label *may* fall through into the
default label.  Such fall-through must *not* cross the NPE
generator logic.

Notice that if the compiler can statically prove that the explicit
cases will *always* accept a null, then the NPE generator goes
dead, since there is no way to reach it.

In order to show the "path to default" more clearly, a desugaring
specification could split the switch semantically into a decision
chain that ends in synthetic "goto" statements to the various case
labels.

switch (x) {
case A:
  …code…
case B:
  …code…
default:
  …code…
}

DESUGAR==>

{
  if (x matches A)  goto case_A
  if (x instanceof B)  goto case_B;
  // path to default starts here:
  requireNonNull(x);
  goto default;
  // goto labels start here:
case_A:
  …code…
case_B:
  …code…
default:
  …code…
}

> (For the current round, the only rule about placement of case null we strictly need to follow in order to not make trouble later is that case null must precede the default, if present.  But we may wish (or not) to make stricter requirements, for purposes of clarity.)

Maybe, but if we do that let's be clear that it's for stylistic
enforcement, not some logical reason.

— John



More information about the amber-dev mailing list