8314578: Non-verifiable code is emitted when two guards declare pattern variables in colon-switch

Reviewed-by: vromero
This commit is contained in:
Aggelos Biboudis 2023-10-17 12:51:57 +00:00 committed by Jan Lahoda
parent e649c56324
commit 15588e08ed
3 changed files with 52 additions and 3 deletions
src/jdk.compiler/share/classes/com/sun/tools/javac/comp
test/langtools/tools/javac/patterns

@ -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() {

@ -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;
};
}
}

@ -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