Skip to content

Commit 03acee8

Browse files
committed
8314578: Non-verifiable code is emitted when two guards declare pattern variables in colon-switch
Backport-of: 15588e08ed455eac356aa923c35503beaecd5b6d
1 parent af6df77 commit 03acee8

File tree

3 files changed

+52
-3
lines changed

3 files changed

+52
-3
lines changed

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -4635,11 +4635,11 @@ void checkSwitchCaseStructure(List<JCCase> cases) {
46354635
if (previousCompletessNormally &&
46364636
c.stats.nonEmpty() &&
46374637
c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4638-
hasBindings(patternLabel.pat)) {
4638+
(hasBindings(patternLabel.pat) || hasBindings(c.guard))) {
46394639
log.error(c.labels.head.pos(), Errors.FlowsThroughToPattern);
46404640
} else if (c.stats.isEmpty() &&
46414641
c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4642-
hasBindings(patternLabel.pat) &&
4642+
(hasBindings(patternLabel.pat) || hasBindings(c.guard)) &&
46434643
hasStatements(l.tail)) {
46444644
log.error(c.labels.head.pos(), Errors.FlowsThroughFromPattern);
46454645
}
@@ -4648,7 +4648,7 @@ void checkSwitchCaseStructure(List<JCCase> cases) {
46484648
}
46494649
}
46504650

4651-
boolean hasBindings(JCPattern p) {
4651+
boolean hasBindings(JCTree p) {
46524652
boolean[] bindings = new boolean[1];
46534653

46544654
new TreeScanner() {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @test /nodynamiccopyright/
3+
* @bug 8314578
4+
* @enablePreview
5+
* @summary Parsing of erroneous patterns succeeds
6+
* @compile/fail/ref=T8314578.out -XDrawDiagnostics T8314578.java
7+
*/
8+
public class T8314578 {
9+
record R1() {}
10+
record R2() {}
11+
12+
static void test(Object o) {
13+
switch (o) {
14+
case R1() when o instanceof String s:
15+
case R2() when o instanceof Integer i:
16+
System.out.println("hello: " + i);
17+
break;
18+
default:
19+
break;
20+
}
21+
}
22+
23+
static void test2(Object o) {
24+
switch (o) {
25+
case R1() when o instanceof String s:
26+
System.out.println("hello: " + s);
27+
case R2() when o instanceof Integer i:
28+
System.out.println("hello: " + i);
29+
break;
30+
default:
31+
break;
32+
}
33+
}
34+
35+
static int unnamedInGuardsOK(String s) {
36+
return switch (s) {
37+
case String _ when s instanceof String _ -> // should be OK
38+
1;
39+
default ->
40+
-1;
41+
};
42+
}
43+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
T8314578.java:14:18: compiler.err.flows.through.from.pattern
2+
T8314578.java:15:18: compiler.err.flows.through.to.pattern
3+
T8314578.java:27:18: compiler.err.flows.through.to.pattern
4+
- compiler.note.preview.filename: T8314578.java, DEFAULT
5+
- compiler.note.preview.recompile
6+
3 errors

0 commit comments

Comments
 (0)