RFR: 8348928: Check for case label validity are misbehaving when binding patterns with unnamed bindings are present

Jan Lahoda jlahoda at openjdk.org
Fri Mar 21 14:15:18 UTC 2025


Consider code like:

public class Exp0 {
    public static void main(String... args) {
        Object o = "";
        record R(int i, String s) {}

        switch (o) {
            case Integer _, R(int i, String _) -> {}
            default -> {}
        }
    }
}


This compiles OK, but it should. The JLS says:
> It is a compile-time error for a case label to have more than one case pattern and declare any pattern variables (other than those declared by a guard associated with the case label).

Some similar cases leads to a javac crash:

$ cat Exp2.java 
public class Exp2 {
    public static void main(String... args) {
        Object o = "";
        record R(int i, String s) {}

        switch (o) {
            case Integer _:
            case R(int i, String _):
                System.err.println(i);
                break;
            default: break;
        }
    }
}

$ jdk-24/bin/javac Exp2.java
An exception has occurred in the compiler (24-internal). Please file a bug against the Java compiler via the Java bug reporting page (https://bugreport.java.com) after checking the Bug Database (https://bugs.java.com) for duplicates. Include your program, the following diagnostic, and the parameters passed to the Java compiler in your report. Thank you.
java.lang.AssertionError
        at jdk.compiler/com.sun.tools.javac.util.Assert.error(Assert.java:155)
        at jdk.compiler/com.sun.tools.javac.util.Assert.check(Assert.java:46)
        at jdk.compiler/com.sun.tools.javac.jvm.Items$LocalItem.<init>(Items.java:392)
        at jdk.compiler/com.sun.tools.javac.jvm.Items.makeLocalItem(Items.java:133)
        at jdk.compiler/com.sun.tools.javac.jvm.Gen.visitIdent(Gen.java:2350)
        at jdk.compiler/com.sun.tools.javac.tree.JCTree$JCIdent.accept(JCTree.java:2711)
...
printing javac parameters to: /tmp/javac.20250321_150757.args


The root cause here is a bug when determining whether or not a given case label contains bindings - the "has-bindings" flag gets cleared when `_` is used. The "has-bindings" flags must remain set despite seeing unnamed binding variables.

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

Commit messages:
 - Adding test for case fall-through.
 - Adding newline
 - Adjusting test.
 - 8348928: Check for case label validity are misbehaving when binding patterns with unnamed bindings are present

Changes: https://git.openjdk.org/jdk/pull/24155/files
  Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=24155&range=00
  Issue: https://bugs.openjdk.org/browse/JDK-8348928
  Stats: 23 lines in 3 files changed: 20 ins; 0 del; 3 mod
  Patch: https://git.openjdk.org/jdk/pull/24155.diff
  Fetch: git fetch https://git.openjdk.org/jdk.git pull/24155/head:pull/24155

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


More information about the compiler-dev mailing list