diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java index fb0359e4464..d92a8807542 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java @@ -4650,11 +4650,11 @@ public class Check { if (previousCompletessNormally && c.stats.nonEmpty() && c.labels.head instanceof JCPatternCaseLabel patternLabel && - hasBindings(patternLabel.pat)) { + (hasBindings(patternLabel.pat) || hasBindings(c.guard))) { log.error(c.labels.head.pos(), Errors.FlowsThroughToPattern); } else if (c.stats.isEmpty() && c.labels.head instanceof JCPatternCaseLabel patternLabel && - hasBindings(patternLabel.pat) && + (hasBindings(patternLabel.pat) || hasBindings(c.guard)) && hasStatements(l.tail)) { log.error(c.labels.head.pos(), Errors.FlowsThroughFromPattern); } @@ -4663,7 +4663,7 @@ public class Check { } } - boolean hasBindings(JCPattern p) { + boolean hasBindings(JCTree p) { boolean[] bindings = new boolean[1]; new TreeScanner() { diff --git a/test/langtools/tools/javac/patterns/T8314578.java b/test/langtools/tools/javac/patterns/T8314578.java new file mode 100644 index 00000000000..28acaec3482 --- /dev/null +++ b/test/langtools/tools/javac/patterns/T8314578.java @@ -0,0 +1,43 @@ +/** + * @test /nodynamiccopyright/ + * @bug 8314578 + * @enablePreview + * @summary Parsing of erroneous patterns succeeds + * @compile/fail/ref=T8314578.out -XDrawDiagnostics T8314578.java + */ +public class T8314578 { + record R1() {} + record R2() {} + + static void test(Object o) { + switch (o) { + case R1() when o instanceof String s: + case R2() when o instanceof Integer i: + System.out.println("hello: " + i); + break; + default: + break; + } + } + + static void test2(Object o) { + switch (o) { + case R1() when o instanceof String s: + System.out.println("hello: " + s); + case R2() when o instanceof Integer i: + System.out.println("hello: " + i); + break; + default: + break; + } + } + + static int unnamedInGuardsOK(String s) { + return switch (s) { + case String _ when s instanceof String _ -> // should be OK + 1; + default -> + -1; + }; + } +} \ No newline at end of file diff --git a/test/langtools/tools/javac/patterns/T8314578.out b/test/langtools/tools/javac/patterns/T8314578.out new file mode 100644 index 00000000000..6d6acf6d48b --- /dev/null +++ b/test/langtools/tools/javac/patterns/T8314578.out @@ -0,0 +1,6 @@ +T8314578.java:14:18: compiler.err.flows.through.from.pattern +T8314578.java:15:18: compiler.err.flows.through.to.pattern +T8314578.java:27:18: compiler.err.flows.through.to.pattern +- compiler.note.preview.filename: T8314578.java, DEFAULT +- compiler.note.preview.recompile +3 errors \ No newline at end of file