Skip to content

GROOVY-12576: SC: resolve Object methods in closures through the delegate and owner - #3102

Merged
paulk-asert merged 6 commits into
apache:masterfrom
codeconsole:trait-sc-closure-object-methods
Nov 1, 2026
Merged

paulk-asert merged 6 commits into
apache:masterfrom
codeconsole:trait-sc-closure-object-methods

Conversation

@codeconsole

@codeconsole codeconsole commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Under @CompileStatic, toString(), hashCode(), equals() and getClass() called without a receiver inside a closure or lambda now go to the delegate or the owner according to the resolve strategy, as they do in dynamic and @TypeChecked code since GROOVY-11858. So new StringBuilder().with { append('w'); toString() } returns 'w', not the closure's toString(). In a lambda, toString() is the enclosing instance's, as in Java; in a static method it is the class's. Methods that Closure declares, such as getDelegate() or getMetaClass(), still resolve against the closure.

toString() called inside a closure:

4.0.32 5.0.6 master this PR
dynamic closure closure owner owner
@CompileStatic owner closure closure owner

Dynamic code started going to the delegate or owner with GROOVY-11858, which is on master and 6.0.x but not on 5.1.x. This PR lines SC up with that 6.0+ dynamic behaviour.

The resolve strategy is followed as at run time:

  • TO_SELF: the closure's own method.
  • DELEGATE_FIRST, DELEGATE_ONLY: the delegate's.
  • OWNER_FIRST, OWNER_ONLY: the owner's. When the owner is an enclosing closure, that is the enclosing closure's own method, so { -> { -> toString() }() }() returns the outer closure's toString().

The type checker looked up the methods of Closure before the delegate and the owner, and that lookup also returned the methods Closure inherits from Object. It now leaves those out unless the strategy is TO_SELF, and in a closure whose owner is a closure it resolves them against that owner. The static invocation writer calls a method of Object that was resolved against the owner on the closure's this object, as it already did for other owner methods.

A closure can have no this object. rehydrate(null, owner, null) keeps only the owner, and the writer then calls the owner's method, as dynamic code does. After dehydrate() there is no owner either, and the closure's own method is called; dynamic code calls the method on null there.

Tests: ClosuresSTCTest.testClosureObjectMethodPrecedence, testClosureObjectMethodResolveStrategy and testClosureObjectMethodWithoutThisObject (also run statically compiled by ClosuresStaticCompileTest), and ClosuresStaticCompileTest.testObjectMethodsInClosureWithoutThisObject, fail without the change. The closure test classes and the groovy.transform.stc and org.codehaus.groovy.classgen.asm.sc packages pass, apart from MethodReferenceTest.testMethodReferencesInStaticAndDefaultMethodsOfInterface, which fails on master since #3056 (#3116 fixes it). The Checkstyle and CodeNarc gates pass.

Backport to 6.0.x, not 5.1.x: on 5.1.x dynamic code still calls the closure's method, so backporting would split SC from dynamic there, and the @TypeChecked variant of testClosureObjectMethodPrecedence fails on 5.1.x.

… and owner

Under static compilation, an implicit-this call to a method of Object in
a closure or lambda, such as toString(), hashCode(), equals(Object) or
getClass(), was made on the closure itself:

    @CompileStatic
    class C {
        String m() { new StringBuilder().with { append('w'); toString() } }
    }

new C().m() returned "C$_m_closure1@1b2c3d4" instead of "w". The type
checker looks up the methods of Closure before the delegate and the
owner, and that lookup also returned the methods Closure inherits from
Object. With with, tap, identity or a @DelegatesTo(strategy =
DELEGATE_FIRST) method this ignored the delegate. In a plain closure it
ignored the owner, and in a lambda it ignored the enclosing instance,
which Java and dynamic Groovy both use. This happened in methods,
constructors, field initializers and static initializers alike.

Dynamic Groovy only tries the closure first for methods that Closure or
GroovyObject declare; a method the closure inherits from elsewhere goes
to the delegate or the owner according to the resolve strategy. The type
checker now leaves the methods of Object out of that first lookup, so
the delegate or owner is chosen, and the static invocation writer calls
a method of Object that was resolved against the owner on the closure's
this object (the class itself in a static context), as it already did
for other owner methods. Methods declared by Closure, such as
getDelegate() or getMetaClass(), still resolve against the closure.
@TypeChecked code already behaved like dynamic Groovy at run time; only
the inferred types of such calls change there.
…is object is null

Under static compilation, toString(), hashCode(), equals(Object) and
getClass() called without a receiver in a closure now go to the
closure's this object, as other owner methods do. A closure can have no
this object: dehydrate() returns a copy whose owner, delegate and this
object are all null, which is how closures are made serializable or
shared between threads. For such a closure these calls failed with a
NullPointerException:

    @CompileStatic
    class C {
        Closure<Integer> c() { { -> hashCode() } }
    }

new C().c().dehydrate()() threw "Cannot invoke "Object.hashCode()"
because the return value of "C$_c_closure1.getThisObject()" is null".
Before the previous fixes these calls always went to the closure itself.

When the method is a public method of Object, or overrides one, the
static invocation writer now loads the this object and uses the closure
instead if it is null, and calls the method as declared by Object, so
the override of the this object still runs when there is one:

    ALOAD 0
    INVOKEVIRTUAL getThisObject()
    DUP
    IFNONNULL L
    POP
    ALOAD 0
    L: INVOKEVIRTUAL java/lang/Object.hashCode()I

Lambdas are left alone, since their enclosing instance is never null.
@codecov-commenter

codecov-commenter commented Oct 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.00000% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.1128%. Comparing base (cd944a5) to head (65c8326).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...groovy/classgen/asm/sc/StaticInvocationWriter.java 88.2353% 1 Missing and 3 partials ⚠️
...roovy/transform/stc/StaticTypeCheckingVisitor.java 75.0000% 0 Missing and 4 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3102        +/-   ##
==================================================
+ Coverage     74.1016%   74.1128%   +0.0112%     
- Complexity      43596      43625        +29     
==================================================
  Files            1692       1692                
  Lines          149245     149290        +45     
  Branches        28284      28295        +11     
==================================================
+ Hits           110593     110643        +50     
+ Misses          28475      28468         -7     
- Partials        10177      10179         +2     
Files with missing lines Coverage Δ
...groovy/classgen/asm/sc/StaticInvocationWriter.java 77.1863% <88.2353%> (+0.5734%) ⬆️
...roovy/transform/stc/StaticTypeCheckingVisitor.java 88.1828% <75.0000%> (-0.0262%) ⬇️

... and 12 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.

@daniellansun daniellansun left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM for GROOVY-12576.

Under @CompileStatic, bare toString/hashCode/equals/getClass in a closure/lambda must follow resolve strategy to delegate/owner (Groovy 4 / dynamic / @TypeChecked), not the closure’s own Object methods. Dropping Object-declared methods from the closure-method short-circuit in StaticTypeCheckingVisitor, and teaching StaticInvocationWriter to rewrite the receiver (including ThisObjectOrClosureExpression for dehydrated / null-thisObject closures), is the right split.

Tests cover with/tap/identity, ctor/field/static contexts, DELEGATE_FIRST, lambdas vs closures, and dehydrate/rehydrate fallbacks in ClosuresStaticCompileTest.

CI green. Codecov ~86% patch (a few StaticInvocationWriter partials on the null-thisObject branch) — non-blocking given the dedicated dehydrate test.

Note: overlaps StaticInvocationWriter with #3103/#3106/#3107 — rebase carefully.

@daniellansun

Copy link
Copy Markdown
Contributor

Friendly ping: this PR is approved. If there are no objections within 72 hours, this PR will be merged. Thanks!

@daniellansun

Copy link
Copy Markdown
Contributor

Friendly ping: this PR is approved and CI is green. If there are no objections within 72 hours, this PR will be merged. Thanks!

@paulk-asert

Copy link
Copy Markdown
Contributor

Thanks, this looks good overall. Two things before merge:

1. Closures using TO_SELF no longer compile. A closure whose resolve strategy is TO_SELF can't call toString() any more:

class C {
    String toString() { 'C' }
    static Object run(@DelegatesTo(value=String, strategy=Closure.TO_SELF) Closure c) {
        c.resolveStrategy = Closure.TO_SELF; c.delegate = 'd'; c()
    }
    Object m() { run { -> toString() } }
}

On master it compiles, and both dynamic and @CompileStatic return the closure's own toString(). With this PR, both @CompileStatic and @TypeChecked fail with [Static type checking] - Cannot find matching method C#toString(). With TO_SELF only the closure itself is searched, and its Object methods have now been removed from that search. Could the removeIf be skipped when the strategy is TO_SELF? A test for it would be good too.

2. The 4.0 claim in the description. Results for toString() called inside a closure:

4.0.32 5.0.6 master this PR
dynamic closure closure owner owner
@CompileStatic owner closure closure owner

Dynamic code only started going to the delegate or owner with GROOVY-11858, which is on master and 6.0.x but not on 5.1.x. So in 4.0, SC and dynamic disagreed, and in 5.x they agree. This PR lines SC up with 6.0+ dynamic behaviour.

For that reason I'd backport to 6.0.x (with the TO_SELF fix) but not to 5.1.x. On 5.1.x, the @TypeChecked variant of testClosureObjectMethodPrecedence fails, because it runs dynamically, while the statically compiled one passes. Backporting would split SC from dynamic there.

Minor and optional: with rehydrate(null, owner, null), dynamic code calls the owner's method, while this PR falls back to the closure. Trying getOwner() before the closure would match dynamic in that case. Not a blocker.

@paulk-asert paulk-asert left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As per last comment

…ject-methods

# Conflicts:
#	src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
…in closures

Under static compilation and type checking, toString(), hashCode(),
equals(Object) and getClass() called without a receiver in a closure
whose resolve strategy is TO_SELF no longer compiled:

    class C {
        static Object run(@DelegatesTo(value=String, strategy=Closure.TO_SELF) Closure c) { ... }
        Object m() { run { -> toString() } }
    }

failed with "Cannot find matching method C#toString()". With TO_SELF only
the closure is searched, and its methods of Object had been left out of
that search. They are kept for TO_SELF again, and the static compiler
calls them on the closure, as dynamic Groovy does.

A closure nested in another closure has that closure as its owner. With
OWNER_FIRST or OWNER_ONLY, dynamic Groovy calls the owner closure's own
method of Object; the type checker resolved it further out, against the
enclosing class or the outer closure's delegate. It now resolves it
against the owner closure, so { -> { -> toString() }() }() returns the
outer closure's toString(), and a nested closure in a TO_SELF closure no
longer fails with a ClassCastException.
…is object

Under static compilation, toString(), hashCode(), equals(Object) and
getClass() called without a receiver in a closure without a this object
fell back to the closure's own method. rehydrate(null, owner, null)
returns such a closure that still has an owner, and dynamic Groovy calls
the owner's method there:

    @CompileStatic
    class C {
        String toString() { 'C' }
        Closure<String> c() { { -> toString() } }
    }

new C().c().rehydrate(null, new C(), null)() returned the closure's
toString() instead of "C". The static invocation writer now loads the
owner when the this object is null, and uses the closure only when the
owner is null too, as after dehydrate().
@codeconsole

Copy link
Copy Markdown
Contributor Author

@paulk-asert Thanks.

  1. TO_SELF: fixed in 63ca12a. The Object methods stay in the closure lookup for TO_SELF, and SC calls them on the closure, so your example compiles and returns the closure's toString() under SC and TC, as dynamic does. DELEGATE_ONLY and OWNER_ONLY already matched dynamic ('d' and 'C'). The same commit fixes nested closures: with an owner-first strategy dynamic calls the owner closure's own method, while the PR went on out to the class or the outer delegate, and a closure nested in a TO_SELF closure even threw a ClassCastException. Covered by testClosureObjectMethodResolveStrategy (TC and SC).
  2. 4.0 claim: you're right. The description now has your table, says this lines SC up with 6.0+ dynamic behaviour (GROOVY-11858), and recommends backporting to 6.0.x, not 5.1.x.
  3. rehydrate: done in e01034c. The writer tries getOwner() before the closure, so rehydrate(null, owner, null) calls the owner's method. Covered by testClosureObjectMethodWithoutThisObject and the updated testObjectMethodsInClosureWithoutThisObject. After dehydrate() there is no owner either; SC calls the closure's own method there, where dynamic calls it on null (the description says so).

Also merged master (8d1b545); it conflicted with GROOVY-12574 in StaticInvocationWriter, and both changes are kept. MethodReferenceTest.testMethodReferencesInStaticAndDefaultMethodsOfInterface fails on master itself since #3056; #3116 fixes it.

@testlens-app

testlens-app Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 65c8326
▶️ Tests: 0 executed
🟡 Checks: 22/26 completed


Learn more about TestLens at testlens.app/docs.

@paulk-asert
paulk-asert merged commit c83bead into apache:master Nov 1, 2026
26 of 34 checks passed
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.

5 participants