[jdk20u] RFR: 8302202: Incorrect desugaring of null-allowed nested patterns

Jan Lahoda jlahoda at openjdk.org
Mon Feb 20 08:40:33 UTC 2023


Original PR:
https://github.com/openjdk/jdk/pull/12572

Original PR description:
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.

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

Commit messages:
 - Backport dc55a7fc877ab5ea4efbed90454194008143aeb4

Changes: https://git.openjdk.org/jdk20u/pull/7/files
 Webrev: https://webrevs.openjdk.org/?repo=jdk20u&pr=7&range=00
  Issue: https://bugs.openjdk.org/browse/JDK-8302202
  Stats: 182 lines in 2 files changed: 174 ins; 2 del; 6 mod
  Patch: https://git.openjdk.org/jdk20u/pull/7.diff
  Fetch: git fetch https://git.openjdk.org/jdk20u pull/7/head:pull/7

PR: https://git.openjdk.org/jdk20u/pull/7


More information about the jdk-updates-dev mailing list