Skip to content

Commit

Permalink
8314578: Non-verifiable code is emitted when two guards declare patte…
Browse files Browse the repository at this point in the history
…rn variables in colon-switch

Backport-of: 15588e08ed455eac356aa923c35503beaecd5b6d
  • Loading branch information
shipilev committed Dec 19, 2023
1 parent af6df77 commit 03acee8
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4635,11 +4635,11 @@ void checkSwitchCaseStructure(List<JCCase> cases) {
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);
}
Expand All @@ -4648,7 +4648,7 @@ void checkSwitchCaseStructure(List<JCCase> cases) {
}
}

boolean hasBindings(JCPattern p) {
boolean hasBindings(JCTree p) {
boolean[] bindings = new boolean[1];

new TreeScanner() {
Expand Down
43 changes: 43 additions & 0 deletions test/langtools/tools/javac/patterns/T8314578.java
Original file line number Diff line number Diff line change
@@ -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;
};
}
}
6 changes: 6 additions & 0 deletions test/langtools/tools/javac/patterns/T8314578.out
Original file line number Diff line number Diff line change
@@ -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

1 comment on commit 03acee8

@openjdk-notifier
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.