Skip to content

GROOVY-12673: report and set the delegate, resolve strategy and this object of the closure a wrapper wraps - #3194

Closed
codeconsole wants to merge 10 commits into
apache:masterfrom
codeconsole:closure-wrapper-delegate-this
Closed

codeconsole wants to merge 10 commits into
apache:masterfrom
codeconsole:closure-wrapper-delegate-this

Conversation

@codeconsole

@codeconsole codeconsole commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

The closures returned by trampoline(), memoize*(), curry(), >>/<< and asWritable() do not report or forward the delegation settings of the closure they wrap:

class D { def m() { 'delegate' } }
class O {
    def m() { 'owner' }
    def run() {
        def c = { x -> m() }
        assert c.curry(1).thisObject.is(this)   // null
        def t = c.trampoline()
        t.resolveStrategy = Closure.DELEGATE_FIRST
        t.delegate = new D()
        assert t(1) == 'delegate'               // 'owner'
    }
}
new O().run()

Seen in 4.0.33, 5.0.8 and 6.0.0 too.

  • TrampolineClosure passed the wrapped closure's delegate as its thisObject, so its delegate reported the owner. It now takes the wrapped closure's thisObject and forwards getDelegate, setDelegate, getResolveStrategy and setResolveStrategy to the wrapped closure, as ComposedClosure does. Its clone() copies the wrapped closure, so with/tap, which clone and then set the delegate, leave the original trampoline unchanged. Its parameter count and types now come from the wrapped closure's getters; before, a trampolined writable or composed closure reported a single Object[] parameter.
  • Memoize.MemoizeFunction gets the same forwarding, thisObject and clone(). The copy shares the cache.
  • CurriedClosure, ComposedClosure and Closure.WritableClosure forward getThisObject to the closure they call. getOwner() of these three still returns the wrapped closure, which they call through.
  • trampoline() and the Memoize.build* methods wrap a copy of the closure, as curry() already does, so a delegate or resolve strategy set on the wrapper reaches the copy and never the caller's closure.

One commit per wrapper.

Stacked on #3190 (GROOVY-12669, memoize rehydrate/dehydrate): this branch merges it, keeping #3190's cacheFactory field and constructor parameter, making closure non-final (needed by clone() here), and calling super(closure.getOwner(), closure.getThisObject()). Until #3190 lands, this PR's diff also shows its commits. #3195 (GROOVY-12674) and #3198 (GROOVY-12677) build on this one. With #3186 (GROOVY-12665, wrapper rehydrate/dehydrate) this merges cleanly.

Compatibility

A delegate or resolve strategy set on a trampolined or memoized closure now takes effect, and thisObject of curried, composed, writable, trampolined and memoized closures is the wrapped closure's. A delegate set on c after c.trampoline() or c.memoize*() no longer reaches the wrapper, which holds a copy, as with curry().

Tests

These fail without the change:

  • ClosureCurryTest.testThisObject
  • ClosureComposeTest.testThisObject
  • ClosureTest.testWritableClosureThisObject (includes a @CompileStatic case)
  • TrampolineTest: testDelegateAndThisObject, testSetDelegateAndResolveStrategy, testWith, testParametersOfWrappedClosure
  • TrampolineTest.testSetDelegateAndResolveStrategyLeavesTheTrampolinedClosureAlone
  • AbstractMemoizeTestCase: testDelegateAndThisObject, testSetDelegateAndResolveStrategy, testSetDelegateAndResolveStrategyLeavesTheMemoizedClosureAlone, testWith, run by MemoizeTest, MemoizeAtMostTest, MemoizeAtLeastTest and MemoizeBetweenTest

groovy.lang.*Closure*, groovy.*Closure*, org.codehaus.groovy.runtime.*Closure*, org.codehaus.groovy.runtime.trampoline.*, org.codehaus.groovy.runtime.memoize.*, MemoizedASTTransformationTest, gls.closures.*, groovy.transform.stc.* and org.codehaus.groovy.classgen.asm.sc.* pass. The Checkstyle and CodeNarc gates pass.

…wraps

A memoized closure calls the closure it wraps, which kept the original
owner, delegate and this object, so rehydrate had no effect on calls and
a dehydrated copy could not be serialized. The copy now dehydrates or
rehydrates the wrapped closure and memoizes it again with an empty cache
built the same way, since cached values were computed against the old
owner. Closure.memoize* pass a serializable cache factory to new
Memoize overloads; the existing overloads that take a cache instance
share it with the copy.
…object of the closure a memoized closure wraps
@codecov-commenter

codecov-commenter commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 74.1622%. Comparing base (0941dba) to head (35c676f).
⚠️ Report is 12 commits behind head on master.

Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3194        +/-   ##
==================================================
+ Coverage     74.1533%   74.1622%   +0.0089%     
- Complexity      43751      43762        +11     
==================================================
  Files            1692       1692                
  Lines          149516     149556        +40     
  Branches        28366      28371         +5     
==================================================
+ Hits           110871     110914        +43     
+ Misses          28448      28442         -6     
- Partials        10197      10200         +3     
Files with missing lines Coverage Δ
src/main/java/groovy/lang/Closure.java 85.8974% <100.0000%> (+0.9301%) ⬆️
src/main/java/groovy/lang/TrampolineClosure.java 95.8333% <100.0000%> (+13.4804%) ⬆️
...a/org/codehaus/groovy/runtime/ComposedClosure.java 82.6087% <100.0000%> (+5.3360%) ⬆️
...va/org/codehaus/groovy/runtime/CurriedClosure.java 91.3044% <100.0000%> (+0.0956%) ⬆️
...a/org/codehaus/groovy/runtime/memoize/Memoize.java 85.2941% <100.0000%> (+7.0333%) ⬆️

... and 14 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…ializable class rather than a serializable lambda

A serialized memoize() closure contained a java.lang.invoke.SerializedLambda,
which serialization filters commonly reject. The dehydrate test no longer
depends on which exception calling a closure with no owner throws.
# Conflicts:
#	src/main/java/org/codehaus/groovy/runtime/memoize/Memoize.java
…does

The trampoline and memoize wrappers now forward the delegate and resolve
strategy to the closure they wrap, so setting them on the wrapper changed
the caller's closure. Like CurriedClosure, they now wrap a copy.
@testlens-app

testlens-app Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

🚨 All tests passed but jobs failed 🚨

Failed Jobs without Test Failures

❌ Build and test / lts (17, ubuntu-latest)

🏷️ Commit: 35c676f
▶️ Tests: 93034 executed
⚪️ Checks: 27/27 completed

Rerun Controls

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants