[
https://issues.apache.org/jira/browse/GROOVY-12653?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18137331#comment-18137331
]
ASF GitHub Bot commented on GROOVY-12653:
-----------------------------------------
codeconsole opened a new pull request, #3174:
URL: https://github.com/apache/groovy/pull/3174
With closure packing enabled (`-Dgroovy.target.closure.pack=true` or
`@PackedClosures`), a local captured by a closure in a constructor or an
instance initializer block, and written after the literal, was copied into the
packed closure by value, so the closure saw a stale value:
```groovy
class R { def r; R() { def c; c = { x -> c == null ? 'stale' : 'set' }; r =
c(1) } }
new R().r // 'stale'; 'set' without packing and in a method
```
`ClosureWriter.holderCaptureNames`, which decides which captures are
threaded as a shared `Reference`, looked the names written after the literal up
in `WriterController.getMethodNode()`, which is null while a constructor is
written. It now uses `ClosureWriter.enclosingMethod()`, which falls back to the
constructor node.
Stacked on #3173 (GROOVY-12652), which adds `enclosingMethod()`; this PR
shows its commit until that is merged. Seen in 6.0.0 too.
## Tests
`PackedClosuresTransformTest.captureWrittenAfterTheLiteralInAConstructorOrInitializerIsShared`
fails without the change. The packing test classes,
`org.codehaus.groovy.classgen.asm.sc.*` and `groovy.transform.stc.*` pass. The
Checkstyle and CodeNarc gates pass.
> Closure packing copies a local written after the literal by value in a
> constructor or instance initializer block
> ----------------------------------------------------------------------------------------------------------------
>
> Key: GROOVY-12653
> URL: https://issues.apache.org/jira/browse/GROOVY-12653
> Project: Groovy
> Issue Type: Bug
> Affects Versions: 7.0.0-alpha-1, 6.0.0
> Reporter: Scott Murphy Heiberg
> Priority: Major
>
> With closure packing enabled ({{-Dgroovy.target.closure.pack=true}} or
> {{@PackedClosures}}), a local captured by a closure literal in a constructor
> or an instance initializer block, and written after the literal, is copied
> into the packed closure by value instead of shared:
> {code:groovy}
> class R { def r; R() { def c; c = { x -> c == null ? 'stale' : 'set' }; r =
> c(1) }
> def m() { def c; c = { x -> c == null ? 'stale' : 'set' }; c(1) } }
> class I { def r; { def c; c = { x -> c == null ? 'stale' : 'set' }; r = c(1)
> } }
> [new R().r, new R().m(), new I().r]
> {code}
> *Actual* (dynamic and @CompileStatic, packing on): {{[stale, set, stale]}}.
> *Expected:* {{[set, set, set]}}, as without packing and as in a method.
> Cause: the lookup of names written after the literal
> ({{ClosureWriter.holderCaptureNames}}) uses
> {{WriterController.getMethodNode()}}, which is null while a constructor is
> written, so no capture is threaded as a shared Reference.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)