You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/09/10 21:22:07 UTC
(groovy) branch master updated: GROOVY-12397: VerifyError for a pattern variable bound in a later && / || operand; break and continue end an if arm
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/master by this push:
new 3eca1c94b9 GROOVY-12397: VerifyError for a pattern variable bound in a later && / || operand; break and continue end an if arm
3eca1c94b9 is described below
commit 3eca1c94b999d74d955407862a53d21bfbd9f7dd
Author: Paul King <pa...@asert.com.au>
AuthorDate: Thu Sep 10 19:50:21 2026 +1000
GROOVY-12397: VerifyError for a pattern variable bound in a later && / || operand; break and continue end an if arm
A pattern variable declared in the right operand of && or || had its slot
allocated (and null-initialised) at its instanceof site only. That operand
is skipped when the left one decides the result, so at the join a later read
of the slot (a following conjunct, the then branch) failed verification:
if (p instanceof String s && s.length() > 0 && s.trim() instanceof String t)
threw VerifyError. BinaryExpressionHelper now pre-declares the pattern
variables of the right operand before the left operand runs, and the
instanceof site reuses the pre-declared slot (CompileStack keeps the set).
VariableScopeVisitor and the if-statement writer also treated an arm ending
in break or continue as completing normally, so that
if (!(o instanceof String s)) continue
did not introduce `s` after the if as JLS §6.3.2.2-200-C / §14.22 require.
Both now use mayCompleteNormally.
---
.../groovy/classgen/VariableScopeVisitor.java | 9 ++--
.../classgen/asm/BinaryExpressionHelper.java | 44 ++++++++++++++++-
.../codehaus/groovy/classgen/asm/CompileStack.java | 30 ++++++++++++
.../groovy/classgen/asm/StatementWriter.java | 9 ++--
src/test/groovy/groovy/InstanceofTest.groovy | 56 ++++++++++++++++++++++
5 files changed, 139 insertions(+), 9 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/classgen/VariableScopeVisitor.java b/src/main/java/org/codehaus/groovy/classgen/VariableScopeVisitor.java
index 36fa78b38e..53ccad97b3 100644
--- a/src/main/java/org/codehaus/groovy/classgen/VariableScopeVisitor.java
+++ b/src/main/java/org/codehaus/groovy/classgen/VariableScopeVisitor.java
@@ -86,7 +86,7 @@ import static java.lang.reflect.Modifier.isStatic;
import static org.apache.groovy.ast.tools.MethodNodeUtils.getPropertyName;
import static org.apache.groovy.ast.tools.MethodNodeUtils.withDefaultArgumentMethods;
import static org.codehaus.groovy.ast.tools.GeneralUtils.getAllProperties;
-import static org.codehaus.groovy.ast.tools.GeneralUtils.maybeFallsThrough;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.mayCompleteNormally;
import static org.codehaus.groovy.transform.trait.Traits.isTrait;
/**
@@ -703,13 +703,14 @@ public class VariableScopeVisitor extends ClassCodeVisitorSupport {
statement.getElseBlock().visit(this);
popState();
- // After the if-else:
+ // After the if-else ("cannot complete normally", JLS §14.22: return, throw,
+ // yield, break or continue):
// §6.3.2.2-200-C-B: if-block (S) is abrupt → e.whenFalse() survive after.
- if (!maybeFallsThrough(statement.getIfBlock())) {
+ if (!mayCompleteNormally(statement.getIfBlock())) {
declarePatternVariables(bindings.whenFalse());
}
// §6.3.2.2-200-C-A: else-block (T) is abrupt → e.whenTrue() survive after.
- if (!statement.getElseBlock().isEmpty() && !maybeFallsThrough(statement.getElseBlock())) {
+ if (!statement.getElseBlock().isEmpty() && !mayCompleteNormally(statement.getElseBlock())) {
declarePatternVariables(bindings.whenTrue());
}
}
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
index 0ef7b5ec9e..8e77b1e9a7 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
@@ -27,6 +27,8 @@ import org.codehaus.groovy.ast.Variable;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.DeclarationExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ElvisOperatorExpression;
@@ -952,6 +954,7 @@ public class BinaryExpressionHelper {
MethodVisitor mv = controller.getMethodVisitor();
OperandStack operandStack = controller.getOperandStack();
+ predeclarePatternVariables(expression.getRightExpression());
expression.getLeftExpression().visit(acg);
operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
Label falseCase = operandStack.jump(IFEQ);
@@ -976,6 +979,7 @@ public class BinaryExpressionHelper {
MethodVisitor mv = controller.getMethodVisitor();
OperandStack operandStack = controller.getOperandStack();
+ predeclarePatternVariables(expression.getRightExpression());
expression.getLeftExpression().visit(acg);
operandStack.doGroovyCast(ClassHelper.boolean_TYPE);
Label trueCase = operandStack.jump(IFNE);
@@ -1167,6 +1171,39 @@ public class BinaryExpressionHelper {
*
* @param expression an {@code instanceof} binary expression
*/
+ /**
+ * Allocates and null-initialises the slots of the pattern variables declared
+ * by {@code instanceof} tests in the right operand of {@code &&} / {@code ||}
+ * before the left operand runs. The right operand is skipped when the left
+ * one decides the result, so a slot first stored there would be undefined at
+ * the join that follows and any later read (a following conjunct, the then
+ * branch) would fail verification (GROOVY-12242).
+ */
+ private void predeclarePatternVariables(final Expression rightOperand) {
+ CompileStack compileStack = controller.getCompileStack();
+ rightOperand.visit(new CodeVisitorSupport() {
+ @Override
+ public void visitBinaryExpression(final BinaryExpression be) {
+ int op = be.getOperation().getType();
+ if ((op == KEYWORD_INSTANCEOF || op == COMPARE_NOT_INSTANCEOF)
+ && be.getRightExpression() instanceof DeclarationExpression decl
+ && !decl.isMultipleAssignmentDeclaration()) {
+ Variable variable = decl.getVariableExpression();
+ if (compileStack.getVariable(variable.getName(), false) == null) {
+ BytecodeVariable v = compileStack.defineVariable(variable, decl.getType(), false);
+ compileStack.predeclarePatternVariable(v);
+ }
+ }
+ super.visitBinaryExpression(be);
+ }
+
+ @Override
+ public void visitClosureExpression(final ClosureExpression expression) {
+ // a closure body is another method; its pattern variables are its own
+ }
+ });
+ }
+
private void evaluateInstanceof(final BinaryExpression expression) {
CompileStack compileStack = controller.getCompileStack();
OperandStack operandStack = controller.getOperandStack();
@@ -1187,8 +1224,11 @@ public class BinaryExpressionHelper {
if (patternMatch) {
var variable = (Variable) ((BinaryExpression) expression.getRightExpression()).getLeftExpression();
- BytecodeVariable v = compileStack.defineVariable(variable, targetType, false);
- compileStack.recordPatternVariable(v);
+ BytecodeVariable v = compileStack.takePredeclaredPatternVariable(variable.getName());
+ if (v == null) {
+ v = compileStack.defineVariable(variable, targetType, false);
+ compileStack.recordPatternVariable(v);
+ }
MethodVisitor mv = controller.getMethodVisitor();
mv.visitInsn(DUP_X1); // stack: ..., check, value, check
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/CompileStack.java b/src/main/java/org/codehaus/groovy/classgen/asm/CompileStack.java
index 782094bc46..385df3afe7 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/CompileStack.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/CompileStack.java
@@ -114,6 +114,7 @@ public class CompileStack {
* the slot indices recorded here remain valid for the whole method.
*/
private final Map<String, BytecodeVariable> patternVariables = new HashMap<>();
+ private final Set<String> predeclaredPatternVariables = new HashSet<>();
/** map containing named labels of parenting blocks */
private Map<String, Label> superBlockNamedLabels = new HashMap<>();
/** map containing named labels of current block */
@@ -526,6 +527,7 @@ public class CompileStack {
stackVariables.clear();
usedVariables.clear();
patternVariables.clear();
+ predeclaredPatternVariables.clear();
finallyBlocks.clear();
resetVariableIndex(false);
superBlockNamedLabels.clear();
@@ -1092,6 +1094,34 @@ public class CompileStack {
}
}
+ /**
+ * Records a pattern variable whose slot was allocated (and null-initialised)
+ * ahead of its {@code instanceof} site, so that every path reaching a later
+ * read has the slot initialised: the right operand of {@code &&} / {@code ||}
+ * is skipped when the left operand decides the result, and a slot first
+ * stored inside that operand would be undefined at the join otherwise.
+ *
+ * @see #takePredeclaredPatternVariable(String)
+ * @since 7.0.0
+ */
+ public void predeclarePatternVariable(final BytecodeVariable variable) {
+ recordPatternVariable(variable);
+ predeclaredPatternVariables.add(variable.getName());
+ }
+
+ /**
+ * Returns and forgets the pre-declared slot for the named pattern variable,
+ * or {@code null} when the {@code instanceof} site has to allocate one.
+ *
+ * @since 7.0.0
+ */
+ public BytecodeVariable takePredeclaredPatternVariable(final String name) {
+ if (predeclaredPatternVariables.remove(name)) {
+ return patternVariables.get(name);
+ }
+ return null;
+ }
+
/**
* Hides a named variable from name resolution while leaving its slot index
* allocated. The name becomes free in the <em>current</em> state frame only.
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
index 46d8dbe1bb..6af7cd85f3 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
@@ -69,6 +69,7 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.castX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.constantBooleanValue;
import static org.codehaus.groovy.ast.tools.GeneralUtils.isEmptyStatement;
import static org.codehaus.groovy.ast.tools.GeneralUtils.mayReachLoopCondition;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.mayCompleteNormally;
import static org.codehaus.groovy.ast.tools.GeneralUtils.maybeFallsThrough;
import static org.codehaus.groovy.ast.tools.GeneralUtils.maybeFallsThroughToNextSwitchCase;
import static org.objectweb.asm.Opcodes.ALOAD;
@@ -538,12 +539,14 @@ public class StatementWriter {
compileStack.pop();
}
- // Survivors per JLS §6.3.2.2-200-C on the outer frame.
+ // Survivors per JLS §6.3.2.2-200-C on the outer frame: an arm that cannot
+ // complete normally (§14.22, so break/continue count -- the same predicate
+ // as VariableScopeVisitor) introduces the other path's bindings after the if.
Set<String> survivors = new HashSet<>();
- if (!ifFallsThrough) {
+ if (!mayCompleteNormally(statement.getIfBlock())) {
survivors.addAll(bindings.whenFalseNames());
}
- if (!elseEmpty && !elseFallsThrough) {
+ if (!elseEmpty && !mayCompleteNormally(statement.getElseBlock())) {
survivors.addAll(bindings.whenTrueNames());
}
survivors.retainAll(introduced);
diff --git a/src/test/groovy/groovy/InstanceofTest.groovy b/src/test/groovy/groovy/InstanceofTest.groovy
index c85b2cabbe..1f4ed979f9 100644
--- a/src/test/groovy/groovy/InstanceofTest.groovy
+++ b/src/test/groovy/groovy/InstanceofTest.groovy
@@ -26,6 +26,7 @@ import org.codehaus.groovy.control.MultipleCompilationErrorsException
import java.util.List
import java.util.Map
+import static groovy.test.GroovyAssert.assertScript
import static groovy.test.GroovyAssert.shouldFail
final class InstanceofTest {
@@ -1112,4 +1113,59 @@ final class InstanceofTest {
assert f('ab') == 'AB'
assert f(1) == 'early'
}
+
+ // GROOVY-12242 follow-up: a pattern variable bound in a later conjunct is
+ // read after the join of the enclosing `&&`; its slot must exist on every path
+ @Test
+ void testPatternVariableBoundInLaterConjunct() {
+ assertScript '''
+ def m(Object p) {
+ if (p instanceof String s && s.length() > 0 && s.trim() instanceof String t) {
+ return t
+ }
+ return -1
+ }
+ assert m(' ab ') == 'ab'
+ assert m('') == -1
+ assert m(42) == -1
+ '''
+ assertScript '''
+ def m(Object p) {
+ if (!(p instanceof String s) || s.isEmpty() || !(s.trim() instanceof String t)) {
+ return -1
+ }
+ return t
+ }
+ assert m(' ab ') == 'ab'
+ assert m(42) == -1
+ '''
+ }
+
+ // GROOVY-12242 follow-up: JLS §14.22 -- break and continue cannot complete
+ // normally either, so the other path's bindings survive the if (§6.3.2.2-200-C)
+ @Test
+ void testVariableScopeAfterAbruptBreakOrContinue() {
+ assertScript '''
+ def m(List items) {
+ def out = []
+ for (o in items) {
+ if (!(o instanceof String s)) continue
+ out << s.toUpperCase()
+ }
+ out
+ }
+ assert m(['a', 1, 'b']) == ['A', 'B']
+ '''
+ assertScript '''
+ def m(List items) {
+ def out = []
+ for (o in items) {
+ if (o !instanceof String s) break
+ out << s.toUpperCase()
+ }
+ out
+ }
+ assert m(['a', 'b', 1, 'c']) == ['A', 'B']
+ '''
+ }
}