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/06/09 09:46:19 UTC
(groovy) branch master updated: GROOVY-12072: groovy-contracts: loop invariant doesn't resolve normal imports
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 19bc55b098 GROOVY-12072: groovy-contracts: loop invariant doesn't resolve normal imports
19bc55b098 is described below
commit 19bc55b09880e6af91231d8b0bd057e812ed15a0
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Jun 9 19:46:09 2026 +1000
GROOVY-12072: groovy-contracts: loop invariant doesn't resolve normal imports
---
.../groovy/contracts/ast/LoopContractSupport.java | 74 +++++++++++++++-------
.../ast/LoopInvariantASTTransformation.java | 24 ++++---
.../ast/LoopVariantASTTransformation.java | 24 ++++---
.../contracts/tests/inv/LoopDecreasesTests.groovy | 20 ++++++
.../contracts/tests/inv/LoopInvariantTests.groovy | 37 +++++++++++
5 files changed, 136 insertions(+), 43 deletions(-)
diff --git a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopContractSupport.java b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopContractSupport.java
index 0555e35424..1f8191d0a5 100644
--- a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopContractSupport.java
+++ b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopContractSupport.java
@@ -25,6 +25,8 @@ import org.codehaus.groovy.ast.stmt.DoWhileStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.WhileStatement;
import org.codehaus.groovy.classgen.VariableScopeVisitor;
+import org.codehaus.groovy.control.CompilationUnit;
+import org.codehaus.groovy.control.ResolveVisitor;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.StaticImportVisitor;
@@ -50,36 +52,45 @@ final class LoopContractSupport {
}
/**
- * Re-resolves variable scopes for the classes of the given source so that variable references
- * inlined out of a loop-contract annotation closure are bound to their enclosing declarations.
- *
- * @param source the current source unit
- */
- static void resolveVariableScopes(final SourceUnit source) {
- if (source == null || source.getAST() == null) return;
- for (ClassNode classNode : source.getAST().getClasses()) {
- new VariableScopeVisitor(source).visitClass(classNode);
- }
- }
-
- /**
- * Re-runs static-import resolution for the class enclosing the given loop statement (GROOVY-12072).
+ * Re-runs the compiler's semantic-analysis resolution passes over the code inlined out of a
+ * loop-contract annotation closure (GROOVY-12072).
* <p>
- * The compiler's own {@link StaticImportVisitor} pass rewrites unqualified references to
- * statically imported members (e.g. {@code max(3, 4)} for {@code import static java.lang.Math.max})
- * by descending into the annotation members of {@link org.codehaus.groovy.ast.AnnotatedNode}s
- * (classes, methods, fields). A loop-contract annotation, however, sits on a plain statement that
- * the visitor never reaches, and this transform runs <em>after</em> that pass — so the expressions
- * lifted out of the closure keep their unresolved {@code max(...)} call and fail at runtime with a
- * {@code MissingMethodException}. Re-running the visitor over the enclosing class resolves the
- * freshly inlined statements; re-processing already-resolved code is a no-op.
+ * Class invariants and preconditions sit on {@link org.codehaus.groovy.ast.AnnotatedNode}s
+ * (classes, methods, fields), so the compiler's {@link ResolveVisitor}, {@link StaticImportVisitor}
+ * and {@link VariableScopeVisitor} descend into their annotation members and fully resolve the
+ * closure before the contracts framework extracts it. A loop-contract annotation, however, sits on
+ * a plain statement none of those visitors reach, and this transform runs <em>after</em> they have
+ * completed. The expressions it lifts into the loop body therefore arrive completely unresolved:
+ * type references such as {@code Math} are bare {@link org.codehaus.groovy.ast.expr.VariableExpression}s,
+ * unqualified statically imported members such as {@code max(3, 4)} are unresolved method calls, and
+ * local-variable references are unbound.
+ * <p>
+ * Re-running the three passes — in the same order the compiler uses — resolves the freshly inlined
+ * statements. Re-processing the rest of the (already-resolved) class is a no-op. Type resolution
+ * needs the {@link CompilationUnit}; when it is unavailable the type pass is skipped (qualified type
+ * references then remain unresolved, but static imports and variable scopes are still handled).
*
* @param source the current source unit
* @param target the loop statement whose enclosing class should be re-resolved
+ * @param unit the active compilation unit, or {@code null} if it could not be obtained
*/
- static void resolveStaticImports(final SourceUnit source, final ASTNode target) {
+ static void resolveInlinedContractCode(final SourceUnit source, final ASTNode target, final CompilationUnit unit) {
if (source == null || source.getAST() == null) return;
ClassNode enclosing = enclosingClassNode(source, target);
+
+ // 1. resolve type references (e.g. Math -> ClassExpression)
+ if (unit != null) {
+ ResolveVisitor resolveVisitor = new ResolveVisitor(unit);
+ if (enclosing != null) {
+ resolveVisitor.startResolving(enclosing, source);
+ } else {
+ for (ClassNode classNode : source.getAST().getClasses()) {
+ resolveVisitor.startResolving(classNode, source);
+ }
+ }
+ }
+
+ // 2. resolve unqualified statically imported members (e.g. max(3, 4) -> Math.max(3, 4))
if (enclosing != null) {
new StaticImportVisitor(enclosing, source).visitClass(enclosing);
} else {
@@ -87,6 +98,23 @@ final class LoopContractSupport {
new StaticImportVisitor(classNode, source).visitClass(classNode);
}
}
+
+ // 3. bind variable references to their enclosing declarations so @TypeChecked/@CompileStatic
+ // can see their declared types.
+ resolveVariableScopes(source);
+ }
+
+ /**
+ * Re-resolves variable scopes for the classes of the given source so that variable references
+ * inlined out of a contract annotation closure are bound to their enclosing declarations.
+ *
+ * @param source the current source unit
+ */
+ static void resolveVariableScopes(final SourceUnit source) {
+ if (source == null || source.getAST() == null) return;
+ for (ClassNode classNode : source.getAST().getClasses()) {
+ new VariableScopeVisitor(source).visitClass(classNode);
+ }
}
/**
diff --git a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopInvariantASTTransformation.java b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopInvariantASTTransformation.java
index 0e11683ae8..c828c5ca5e 100644
--- a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopInvariantASTTransformation.java
+++ b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopInvariantASTTransformation.java
@@ -19,6 +19,7 @@
package org.apache.groovy.contracts.ast;
import groovy.contracts.Invariant;
+import groovy.transform.CompilationUnitAware;
import org.apache.groovy.contracts.LoopInvariantViolation;
import org.apache.groovy.contracts.generation.AssertStatementCreationUtility;
import org.apache.groovy.contracts.generation.TryCatchBlockGenerator;
@@ -32,6 +33,7 @@ import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.LoopingStatement;
import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.transform.ASTTransformation;
@@ -62,7 +64,14 @@ import java.util.List;
* @see org.apache.groovy.contracts.LoopInvariantViolation
*/
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
-public class LoopInvariantASTTransformation implements ASTTransformation {
+public class LoopInvariantASTTransformation implements ASTTransformation, CompilationUnitAware {
+
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(final CompilationUnit unit) {
+ this.compilationUnit = unit;
+ }
/**
* Rewrites a loop-level {@link Invariant} annotation into assertion checks injected at the start
@@ -99,15 +108,10 @@ public class LoopInvariantASTTransformation implements ASTTransformation {
injectAtLoopBodyStart(loopStatement, wrapped);
- // The invariant closure lived inside a statement annotation, so the compiler's static-import
- // pass never reached it; resolve unqualified statically imported members (e.g. max(3, 4))
- // now that the expressions are real loop-body statements.
- LoopContractSupport.resolveStaticImports(source, (ASTNode) loopStatement);
-
- // The invariant closure lived inside an annotation, so its variable references were never
- // resolved; re-run scope analysis now that they are real loop-body statements so that
- // @TypeChecked/@CompileStatic can see their declared types.
- LoopContractSupport.resolveVariableScopes(source);
+ // The invariant closure lived inside a statement annotation, so the compiler's resolution
+ // passes never reached it; re-resolve types, static imports and variable scopes now that the
+ // expressions are real loop-body statements.
+ LoopContractSupport.resolveInlinedContractCode(source, (ASTNode) loopStatement, compilationUnit);
}
private static void injectAtLoopBodyStart(LoopingStatement loopStatement, Statement check) {
diff --git a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopVariantASTTransformation.java b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopVariantASTTransformation.java
index 2f8b5c119d..36ccad39f5 100644
--- a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopVariantASTTransformation.java
+++ b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/LoopVariantASTTransformation.java
@@ -19,6 +19,7 @@
package org.apache.groovy.contracts.ast;
import groovy.contracts.Decreases;
+import groovy.transform.CompilationUnitAware;
import org.apache.groovy.contracts.VariantSupport;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotationNode;
@@ -30,6 +31,7 @@ import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.LoopingStatement;
import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.transform.ASTTransformation;
@@ -82,10 +84,17 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;
* @see org.apache.groovy.contracts.LoopVariantViolation
*/
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
-public class LoopVariantASTTransformation implements ASTTransformation {
+public class LoopVariantASTTransformation implements ASTTransformation, CompilationUnitAware {
private static final AtomicLong COUNTER = new AtomicLong();
+ private CompilationUnit compilationUnit;
+
+ @Override
+ public void setCompilationUnit(final CompilationUnit unit) {
+ this.compilationUnit = unit;
+ }
+
/**
* Rewrites a loop-level {@link Decreases} annotation into variant bookkeeping and runtime checks.
*
@@ -133,15 +142,10 @@ public class LoopVariantASTTransformation implements ASTTransformation {
// Inject: save at start, check at end
injectAtLoopBodyStartAndEnd(loopStatement, savePrev, block(saveCurr, decreaseCheck));
- // The variant closure lived inside a statement annotation, so the compiler's static-import
- // pass never reached it; resolve unqualified statically imported members (e.g. max(3, 4))
- // now that the expressions are real loop-body statements.
- LoopContractSupport.resolveStaticImports(source, (ASTNode) loopStatement);
-
- // The variant closure lived inside an annotation, so its variable references were never
- // resolved; re-run scope analysis now that they are real loop-body statements so that
- // @TypeChecked/@CompileStatic can see their declared types.
- LoopContractSupport.resolveVariableScopes(source);
+ // The variant closure lived inside a statement annotation, so the compiler's resolution
+ // passes never reached it; re-resolve types, static imports and variable scopes now that the
+ // expressions are real loop-body statements.
+ LoopContractSupport.resolveInlinedContractCode(source, (ASTNode) loopStatement, compilationUnit);
}
private static Expression extractExpression(ClosureExpression closureExpression) {
diff --git a/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/inv/LoopDecreasesTests.groovy b/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/inv/LoopDecreasesTests.groovy
index 7be79790b4..0f76d75361 100644
--- a/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/inv/LoopDecreasesTests.groovy
+++ b/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/inv/LoopDecreasesTests.groovy
@@ -61,6 +61,26 @@ class LoopDecreasesTests extends BaseTestClass {
'''
}
+ // GROOVY-12072: a qualified type reference in a statement-level @Decreases must be resolved by
+ // the loop transform, as the compiler's ResolveVisitor never reaches the closure.
+ @Test
+ void decreasesWithQualifiedTypeReferenceUnderCompileStatic() {
+ assertScript '''
+ import groovy.contracts.Decreases
+ import java.lang.Math
+
+ @groovy.transform.CompileStatic
+ static int go(int n) {
+ int a = 0
+ @Decreases({ Math.max(0, n - a) })
+ while (a < n) { a++ }
+ return a
+ }
+
+ assert go(5) == 5
+ '''
+ }
+
@Test
void decreasesOnClassicForLoop() {
assertScript '''
diff --git a/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/inv/LoopInvariantTests.groovy b/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/inv/LoopInvariantTests.groovy
index 01c6a73837..24f5869ea4 100644
--- a/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/inv/LoopInvariantTests.groovy
+++ b/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/inv/LoopInvariantTests.groovy
@@ -374,6 +374,43 @@ class LoopInvariantTests extends BaseTestClass {
'''
}
+ // GROOVY-12072: a qualified type reference (Math) in the closure is likewise never resolved by
+ // the compiler's ResolveVisitor, so the loop transform must resolve it too — otherwise it is
+ // reported as an "apparent variable ... in a static scope", especially under @CompileStatic.
+ @Test
+ void invariantWithQualifiedTypeReferenceUnderCompileStatic() {
+ assertScript '''
+ import groovy.contracts.*
+ import java.lang.Math
+
+ @groovy.transform.CompileStatic
+ @Invariant({ Math.max(3, 4) == 4 })
+ class C {
+ @Requires({ Math.max(3, 4) == 4 })
+ static int iter(int n) {
+ int a = 0
+ @Invariant({ Math.max(3, 4) == 4 })
+ while (a < n) { a++ }
+ return a
+ }
+ }
+
+ assert C.iter(4) == 4
+ '''
+ }
+
+ @Test
+ void invariantWithFullyQualifiedTypeReference() {
+ assertScript '''
+ import groovy.contracts.Invariant
+
+ int s = 0
+ @Invariant({ java.lang.Math.max(1, 2) == 2 })
+ for (int i = 0; i < 3; i++) { s += i }
+ assert s == 3
+ '''
+ }
+
// A clashing instance method must still win over the static import in an instance-method
// context, confirming the re-resolution honours the enclosing method's static-ness.
@Test