RFR: JDK-8302202: Incorrect desugaring of null-allowed nested patterns
Aggelos Biboudis
abimpoudis at openjdk.org
Fri Feb 17 10:59:51 UTC 2023
On Wed, 15 Feb 2023 13:16:10 GMT, Jan Lahoda <jlahoda at openjdk.org> wrote:
> Considering code like:
>
> private String test1b(Object i) {
> return switch (i) {
> case R1(Object o) when o == null -> "R1(null)";
> case R1(Object o) -> "R1(!null)";
> default -> "default";
> };
> }
>
>
> javac will try to factor-out the common prefix, i.e. `R1`, and produce something along these lines:
>
> switch (i) {
> case R1 $r:
> Object c = $r.c();
> switch (c) {
> case Object o when o == null: yield "R1(null)";
> case Object o: yield "R1(!null)";
> }
> default -> "default";
> };
>
>
> The problem with this code is that both cases in the nested switch must match `null`, but the bootstrap protocol only allows one case to match `null` (the `SwitchBootstraps.typeSwitch` method will return `-1` for `null`). So this translation is broken, and will not match the first case if the component is `null`.
>
> There are multiple ways to solve this problem, but the proposal here is change the way we accumulate the cases from which we factor out the common prefix, by stopping the accumulation after the first nullable case.
>
> Another related issue is that when factoring out the common prefix, if the last case in the nested switch is has an unconditional pattern, but also has a guard, we need to generate a default to continue properly in the outer switch. Currently, the default is not generated when there's an unconditional pattern in the case, despite having a guard, and hence the case as a whole is not unconditional.
After running some more examples, the patch looks good to me too 💯
-------------
PR: https://git.openjdk.org/jdk/pull/12572
More information about the compiler-dev
mailing list