You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2025/09/03 13:48:17 UTC
(groovy) branch GROOVY_5_0_X updated: GROOVY-11751: indexed for-each loop: support closure shared variable
This is an automated email from the ASF dual-hosted git repository.
emilles pushed a commit to branch GROOVY_5_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/GROOVY_5_0_X by this push:
new 063f055946 GROOVY-11751: indexed for-each loop: support closure shared variable
063f055946 is described below
commit 063f0559463b48247f1110b95b5fed9cf604cfe6
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Wed Sep 3 08:30:43 2025 -0500
GROOVY-11751: indexed for-each loop: support closure shared variable
---
.../org/codehaus/groovy/classgen/asm/StatementWriter.java | 13 ++++++++++++-
src/test/groovy/groovy/ForLoopTest.groovy | 11 +++++++++++
2 files changed, 23 insertions(+), 1 deletion(-)
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 2c2d8b0100..f821cd6757 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
@@ -150,7 +150,18 @@ public class StatementWriter {
operandStack.push(ClassHelper.OBJECT_TYPE);
operandStack.storeVar(valueVariable);
if (indexVariable != null) {
- mv.visitIincInsn(indexVariable.getIndex(), 1);
+ if (!indexVariable.isHolder()) {
+ mv.visitIincInsn(indexVariable.getIndex(), 1);
+ } else { // GROOVY-11751: shared variable reference
+ mv.visitVarInsn(ALOAD, indexVariable.getIndex());
+ mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;", false);
+ mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
+ mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
+ mv.visitInsn(ICONST_1);
+ mv.visitInsn(IADD);
+ operandStack.push(ClassHelper.int_TYPE);
+ operandStack.storeVar(indexVariable);
+ }
}
// generate the loop body
diff --git a/src/test/groovy/groovy/ForLoopTest.groovy b/src/test/groovy/groovy/ForLoopTest.groovy
index c44a28955d..ee795e97eb 100644
--- a/src/test/groovy/groovy/ForLoopTest.groovy
+++ b/src/test/groovy/groovy/ForLoopTest.groovy
@@ -144,6 +144,17 @@ final class ForLoopTest {
}
}
+ // GROOVY-11751
+ @Test
+ void testForEachWithIndex2() {
+ int x = 0
+ for (i, v in ['a','b','c']) {
+ def c = { -> x += i }
+ c()
+ }
+ assert x == (0 + 1 + 2)
+ }
+
@Test
void testClassicFor() {
for (int i = 0; i < 10; i++) {