This is an automated email from the ASF dual-hosted git repository. emilles 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 da8382ad5f GROOVY-11751: indexed for-each loop: support closure shared variable da8382ad5f is described below commit da8382ad5f7e0f5f5255dee0b3dc6a39690231a0 Author: Eric Milles <eric.mil...@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++) {