Simplifying switch labels
Dan Smith
daniel.smith at oracle.com
Thu Jun 2 20:22:03 UTC 2022
> On Jun 2, 2022, at 12:08 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
>
>> In this framing, the restrictions about sets of elements in a single label don't apply, because we're talking about two different labels. But we have rules to prevent various abuses. Examples:
>>
>> case 23: case Pattern: // illegal before and now, due to fallthrough Pattern rule
>
> Ideally, the fallthrough rule should be about _bindings_, not _patterns_. If P an Q are patterns with no binding variables, then it should be OK to say:
>
> case P:
> case Q:
>
> The rule about fallthrough is to prevent falling into code where the bindings are not DA.
Yes, understood.
The current explanation doesn't actually treat this as fallthrough, though: it treats it as if you said 'case 23, Pattern:', which is disallowed by a different rule.
I'm suggesting not doing that implicit rewrite, and instead leaving this case to the fallthrough rule.
>> Note that the second kind of Pattern SwitchLabel is especially weird—it binds 'null' to a pattern variable, and requires the pattern to be a (possibly parenthesized) type pattern. So it's nice to break it out as its own syntactic case. I'd also suggest rethinking whether "case null," is the right way to express the two kinds of nullable SwitchLabels, but anyway now it's really clear that they are special.
>
> This is a painful compromise. While this may be a transitional phenomena, the rule "switch matches null only when `null` appears in a case" is a helpful way to transition people away from "switch always throws on null."
Right. So 'case null, String s' is good in that it's easy to see the null. What's troubling about it is that, at runtime, instead of testing "is this a null, or is this a String named s?", we do "is this a null that we can treat as a String named s, or is this a String named s?" (Of course these two questions are equivalent in terms of the true/false test, but they mean something different for variable bindings.)
Anyway, I don't have a good alternative syntax proposal, but I at least want to draw attention to the weirdness of this case (the comma doesn't mean what you think it means), and appeal to that weirdness to push back on a framing that switch labels are just an open-ended mixture of things drawn from the "element" bucket.
More information about the amber-spec-experts
mailing list