Integrated: JDK-8302202: Incorrect desugaring of null-allowed nested patterns

Jan Lahoda jlahoda at openjdk.org
Fri Feb 17 13:16:20 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.

This pull request has now been integrated.

Changeset: dc55a7fc
Author:    Jan Lahoda <jlahoda at openjdk.org>
URL:       https://git.openjdk.org/jdk/commit/dc55a7fc877ab5ea4efbed90454194008143aeb4
Stats:     182 lines in 2 files changed: 174 ins; 2 del; 6 mod

8302202: Incorrect desugaring of null-allowed nested patterns

Reviewed-by: vromero

-------------

PR: https://git.openjdk.org/jdk/pull/12572


More information about the compiler-dev mailing list