RFR: JDK-8302202: Incorrect desugaring of null-allowed nested patterns
Jan Lahoda
jlahoda at openjdk.org
Wed Feb 15 13:22:28 UTC 2023
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:
- JDK-8302202: Incorrect desugaring of null-allowed nested patterns
Changes: https://git.openjdk.org/jdk/pull/12572/files
Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=12572&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/jdk/pull/12572.diff
Fetch: git fetch https://git.openjdk.org/jdk pull/12572/head:pull/12572
PR: https://git.openjdk.org/jdk/pull/12572
More information about the compiler-dev
mailing list