Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -1736,6 +1736,60 @@ property access in a closure with a null owner or delegate. Nothing that ran
without an exception before behaves differently. No public API changes, so
`japicmp` does not report this.

### Groovy 7 — a closure passes a method of `Object` on for a closure nested in it (GROOVY-12829)

A call without a receiver to a method that every object has (`toString()`,
`hashCode()`, `equals`, `getClass()`, and the Groovy development kit methods
for `Object` such as `with`, `tap`, `is` and `inspect`) is first tried on the
closure's owner and delegate (GROOVY-11858, Groovy 6.0.0). When the owner is
itself a closure, as for a nested closure, a lambda in a closure, or a closure
passed to `each` or `collect` inside another closure, that enclosing closure
answered the call itself. It now passes the call on to its own owner and
delegate, by its own resolve strategy, as it does for any other name:

```groovy
class C {
String toString() { 'C' }
def m() {
def outer = { ->
def inner = { -> toString() }
[toString(), inner()]
}
outer()
}
}
assert new C().m() == ['C', 'C'] // was ['C', 'C$_m_closure1@...']
```

- **The call means what it would in the enclosing closure.** In a closure
nested in `new D().with { ... }` it reaches `D`. In a closure nested in one
with `DELEGATE_FIRST` or `DELEGATE_ONLY` it reaches that closure's delegate.
- **An enclosing closure still answers when it would for its own body:** with
`TO_SELF`, or when it has no owner and no delegate, as after `dehydrate()`.
- **Dynamic, type checked and statically compiled code agree.** Statically
compiled code had resolved `toString()`, `hashCode()`, `equals` and
`getClass()` against the enclosing closure, to match. For the Groovy
development kit methods, and in a lambda in a closure, it already reached
the enclosing instance.
- **`@PackedClosures`.** A statically compiled closure that makes such a call
in a nested closure is now packed, where it was left as a class before.

Unchanged: a call in a closure that is not nested, any other method or
property name, the methods that `Closure` declares (`call`, `curry`,
`getDelegate` and the rest), `this.toString()`, `owner.toString()`, and
`toString()` called on a closure from outside it. Up to Groovy 5 the nested
closure answered such a call itself.

The rules are stated in full under "Resolution rules" in
[`src/spec/doc/core-closures.adoc`](src/spec/doc/core-closures.adoc).

**Who is affected.** Code that calls `toString()`, `hashCode()`, `equals`,
`getClass()` or an `Object` extension method without a receiver in a nested
closure and relies on getting the enclosing closure: for example
`getClass().name` to obtain the closure's class name, or `with { ... }` to
operate on the closure. Use `owner.` or name the closure through a variable
to keep that. No public API changes, so `japicmp` does not report this.

### Groovy 7 — a closure's metaclass does not expose the private fields of `Closure` (GROOVY-12675, GROOVY-12680)

A closure class does not inherit the private fields of `groovy.lang.Closure`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,9 @@ private boolean isSyntacticallyDelegateIndependent(final ClosureExpression expre
* these against the closure itself, before the owner;</li>
* <li>in a closure nested directly in the body, an implicit-this call to an {@code Object} method
* or a GDK method a closure has, such as {@code toString()} or {@code with}: such a call tries the
* nested closure's owner, the enclosing closure, which answers it itself. {@code print},
* nested closure's owner, the enclosing closure, which passes it on by its own resolve strategy.
* That reaches the owner's method, as the hoisted body does, unless the strategy or a delegate
* of the enclosing closure decides otherwise, so this decline is a cautious one. {@code print},
* {@code println} and {@code printf} are kept: their {@code Closure} versions forward to the owner.</li>
* </ul>
* Methods that {@code Object} declares, called in the closure's own body, go to the owner first and
Expand Down Expand Up @@ -584,7 +586,7 @@ protected boolean isOpenPackTriggered(final ClosureExpression expression) {
protected String triggerDeclineReason(final ClosureExpression expression) {
if (callsClosureMethod(expression)) {
return "it calls a method on a closure object (a Closure method such as memoize(), or an Object or GDK "
+ "method such as toString() in a nested closure, whose owner is the closure)";
+ "method such as toString() in a nested closure, which asks the closure first)";
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ protected String triggerDeclineReason(final ClosureExpression expression) {
}
if (callsClosureMethod(expression)) {
return "it calls a method on a closure object (a Closure method such as memoize(), an Object method "
+ "such as toString() under TO_SELF, or one in a nested closure, whose owner is the closure)";
+ "such as toString() under TO_SELF, or a method that an enclosing closure answers)";
}
if (touchesMapOwnerProperties(expression)) {
return "it accesses properties of a Map owner, whose closure-context resolution "
Expand Down Expand Up @@ -211,10 +211,12 @@ protected boolean hoistedBodyUsesReceiver(final ClosureExpression expression) {
* True when an implicit-this call in the closure (or a nested closure) was resolved against a
* closure object rather than the owner class: a method that {@code Closure} declares, such as
* {@code memoize()}; a method of {@code Object} under {@code TO_SELF}, whose receiver STC types as
* {@code Closure}; or a method of {@code Object} in a nested closure, which STC resolves against
* the enclosing closure (receiver path {@code "owner"}). A hoisted body is a method of the owner
* class, where the same call would reach the owner's method, and a nested closure constructed in
* it has the owner instance, not the packed closure, as its owner.
* {@code Closure}; or a method in a nested closure that STC resolves against the enclosing
* closure (receiver path {@code "owner"}), such as a method of {@code Object} when the enclosing
* closure is {@code TO_SELF}. A hoisted body is a method of the owner class, where the same call
* would reach the owner's method, and a nested closure constructed in it has the owner instance,
* not the packed closure, as its owner. A method of {@code Object} in a nested closure is
* otherwise passed on by the enclosing closure and resolved against the owner class, so it packs.
*/
private static boolean callsClosureMethod(final ClosureExpression expression) {
Statement code = expression.getCode();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,11 @@ public Object invokeMethod(final Class sender, final Object object, final String
}

if (method != null) {
if (callObject instanceof GeneratedClosure && callObject instanceof Closure<?> candidate
&& candidate.getMetaClass() instanceof ClosureMetaClass candidateMetaClass) {
// a candidate that is a closure applies these rules itself, as for a call made in its own body
return candidateMetaClass.invokeMethod(getNonClosureOuter(candidate.getClass()), candidate, methodName, arguments, false, true);
}
var metaClass = registry.getMetaClass(callObject.getClass());
if (metaClass instanceof ProxyMetaClass) {
return metaClass.invokeMethod(callObject, methodName, arguments);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6572,6 +6572,11 @@ protected void addReceivers(final List<Receiver<String>> receivers, final Collec
private static void addReceivers(final List<Receiver<String>> receivers, final Collection<Receiver<String>> owners, final DelegationMetadata dmd, final String path) {
int strategy = dmd.getStrategy();
switch (strategy) {
case Closure.TO_SELF:
if (!path.isEmpty()) { // an enclosing closure that resolves to itself answers for a nested closure
receivers.add(new Receiver<>(CLOSURE_TYPE.getPlainNodeReference(), path.substring(0, path.length() - 1)));
}
break;
case Closure.DELEGATE_ONLY:
case Closure.DELEGATE_FIRST:
addDelegateReceiver(receivers, dmd.getType(), path + "delegate");
Expand Down Expand Up @@ -6599,16 +6604,6 @@ private static void addReceivers(final List<Receiver<String>> receivers, final C
}
}

/**
* Tells whether the innermost enclosing closure is a closure, not a lambda,
* whose owner is an enclosing closure.
*/
private static boolean isOwnerClosure(final List<TypeCheckingContext.EnclosingClosure> enclosingClosures) {
return enclosingClosures.size() > 1
&& !(enclosingClosures.get(0).getClosureExpression() instanceof LambdaExpression)
&& !(enclosingClosures.get(1).getClosureExpression() instanceof LambdaExpression);
}

/**
* Tells whether the given enclosing closure is a lambda that is statically
* compiled to a native lambda. In such a lambda, as in Java, a method of the
Expand Down Expand Up @@ -6756,17 +6751,9 @@ public void visitMethodCallExpression(final MethodCallExpression call) {
mn = chooseBestMethod(CLOSURE_TYPE, CLOSURE_TYPE.getMethods(name), args);
}
if (strategy != Closure.TO_SELF) {
// a method of Object is looked up on the delegate or owner, as at run time
List<MethodNode> objectMethods = new ArrayList<>(mn);
objectMethods.removeIf(m -> !isObjectType(m.getDeclaringClass()));
// a method of Object is looked up on the delegate or owner, as at run time;
// an owner that is a closure passes it on in the same way
mn.removeIf(m -> isObjectType(m.getDeclaringClass()));
if (mn.isEmpty() && !objectMethods.isEmpty()
&& (strategy == Closure.OWNER_FIRST || strategy == Closure.OWNER_ONLY)
&& isOwnerClosure(typeCheckingContext.getEnclosingClosureStack())) {
// the owner is a closure, so it is the owner's own method
mn = objectMethods;
chosenReceiver = new Receiver<>(CLOSURE_TYPE.getPlainNodeReference(), "owner");
}
}
if (!mn.isEmpty()) {
receiver = CLOSURE_TYPE.getPlainNodeReference();
Expand Down
21 changes: 19 additions & 2 deletions src/spec/doc/core-closures.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,9 @@ them its own meaning.
. *The candidates named by the resolve strategy*, in order, as shown in the table below. A candidate is used if
it <<_delegation_strategy_in_the_presence_of_metaprogramming,handles>> the property or method. A candidate that is `null`
is skipped. A candidate that is itself a closure, which is the case for the owner of a nested closure, applies these same
rules with its own owner, delegate and resolve strategy.
rules with its own owner, delegate and resolve strategy. That holds for every name, also for a method that every object
has, such as `toString()`: an enclosing closure passes the call on to its own candidates, and answers it itself only
under its own step 4.
. *For a method call only, any other method of the closure*, such as those inherited from `Object` or added by the
Groovy development kit (`toString()`, `with`, `tap`).
. Otherwise a `MissingMethodException` or a `MissingPropertyException` is thrown.
Expand Down Expand Up @@ -491,6 +493,18 @@ include::../test/ClosuresSpecTest.groovy[tags=resolution_nested,indent=0]
<1> `inner` asks its owner, the `outer` closure, for `name`
<2> `outer` does not find `name` on its own owner, the script, and so reads it from its delegate

A method that every object has, such as `toString()`, `hashCode()`, `equals` or `getClass()`, is resolved in the same
way. A closure is an object too, but an enclosing closure does not answer such a call for a closure nested in it.
The call means what it would mean in the enclosing closure, however deeply it is nested:

[source,groovy]
----
include::../test/ClosuresSpecTest.groovy[tags=resolution_nested_object_method,indent=0]
----
<1> `inner` asks its owner, the `outer` closure, which asks its own owner, the `Report` instance
<2> the same call written directly in `outer` gives the same result
<3> `outer` now asks its delegate first, and so does the call in `inner`

The owner or the delegate of a closure can be `null`: after `dehydrate()`, after `rehydrate` with a `null` argument,
or after assigning `null` to `delegate`. A `null` candidate is skipped, and when no candidate remains
the failure is a missing property or method, not a `NullPointerException`:
Expand Down Expand Up @@ -524,7 +538,10 @@ include::../test/ClosuresSpecTest.groovy[tags=resolution_to_self,indent=0]

NOTE: These rules describe dynamic Groovy, where resolution happens when the closure runs. In statically compiled
or type checked code the receiver of a name is determined at compile time from the declared types, with the help of
link:core-domain-specific-languages.html#section-delegatesto[`@DelegatesTo`].
link:core-domain-specific-languages.html#section-delegatesto[`@DelegatesTo`]. A name that the compiler resolves
to the enclosing class is then sent to the `this` object of the closure, where dynamic code asks the owner. The two
differ only for a closure that `rehydrate` gave an owner other than its `this` object; statically compiled code then
needs the `this` object to be an instance of the enclosing class.

== Closures in GStrings

Expand Down
29 changes: 29 additions & 0 deletions src/spec/test/ClosuresSpecTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,35 @@ final class ClosuresSpecTest {
'''
}

@Test
void testObjectMethodsInNestedClosures() {
assertScript '''
// tag::resolution_nested_object_method[]
class Draft {
String toString() { 'draft' }
}

class Report {
String toString() { 'report' }

List<String> describe() {
def outer = { ->
def inner = { -> toString() } // <1>
[inner(), toString()] // <2>
}
def plain = outer()

outer.resolveStrategy = Closure.DELEGATE_FIRST
outer.delegate = new Draft()
plain + outer() // <3>
}
}

assert new Report().describe() == ['report', 'report', 'draft', 'draft']
// end::resolution_nested_object_method[]
'''
}

@Test
void testResolutionWithNullOwner() {
assertScript '''
Expand Down
4 changes: 2 additions & 2 deletions src/test/groovy/groovy/transform/stc/ClosuresSTCTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -1684,14 +1684,14 @@ ${' ' * 46}value.prop += 1
[
tos[0] == tos[1],
nested[0] == nested[1],
outer() == outer.toString(),
outer(), // the enclosing closure passes the call on to its own owner
delegateOnly { -> toString() },
ownerOnly { -> toString() }
]
}
}

assert new C().m() == [true, true, true, 'd', 'C']
assert new C().m() == [true, true, 'C', 'd', 'C']
'''
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -834,9 +834,8 @@ final class PackedClosuresTransformTest {
@Test
void dynamicClosuresCallingObjectMethodsInANestedClosureDecline() {
// In a nested closure, toString(), hashCode(), equals(), getClass() and the GDK methods try the
// owner first, the enclosing closure, which answers them itself. A nested closure in a hoisted
// body has R as its owner, so they reached R. Those outer closures stay classes; calls that
// resolve to R anyway still pack.
// owner first, the enclosing closure, which passes them on to its own owner, so they reach R,
// as they would from a hoisted body. Those outer closures still stay classes.
def r = instance(DYNAMIC_CLOSURE_RECEIVER_OWNER + '''
List nested() {
def a = call0 { -> { -> toString() }() }
Expand All @@ -861,8 +860,8 @@ final class PackedClosuresTransformTest {
}
new R()
''')
assertEquals([[true, true, false, true, true, false, true], [false] * 7], r.nested())
assertEquals([['R', r.getClass(), true, true, true, 'p'], [true] * 6], r.ownerResolved())
assertEquals([[false, false, true, false, false, true, false], [false] * 7], r.nested())
assertEquals([['R', r.getClass(), true, true, false, 'p'], [true] * 6], r.ownerResolved())
}

// GROOVY-12663
Expand Down Expand Up @@ -1600,12 +1599,13 @@ final class PackedClosuresTransformTest {

// GROOVY-12660
@Test
void closuresCallingObjectMethodsOnAClosureDecline() {
void closuresCallingObjectMethodsDeclineOnlyWhenAClosureAnswers() {
// STC resolves toString(), hashCode(), equals() and getClass() against the closure itself under
// TO_SELF, and against the enclosing closure in a nested closure (OWNER_FIRST, OWNER_ONLY). A
// hoisted body is a method of R, where the call reached R's method (TO_SELF, nested) or the
// nested closure got R instead of the closure as its owner (MissingPropertyException: owner).
// Those closures stay classes; a top-level call, resolved against R, still packs.
// TO_SELF. A hoisted body is a method of R, where the call reached R's method, so those
// closures stay classes. In a nested closure (OWNER_FIRST, OWNER_ONLY) the enclosing closure
// passes the call on to its own owner, R, which is what a hoisted body calls, so those pack,
// as does a top-level call. A nested closure that names owner, delegate or thisObject would
// get R instead of the closure as its owner (MissingPropertyException: owner): no packing.
def r = instance(CLOSURE_RECEIVER_OWNER + '''
List<Object> toSelf() {
def a = self { -> toString() }
Expand Down Expand Up @@ -1640,7 +1640,7 @@ final class PackedClosuresTransformTest {
new R()
''')
assertEquals([[true, true, false, true], [false] * 4], r.toSelf())
assertEquals([[true, true, false, true, true, true], [false] * 6], r.nested())
assertEquals([[false, false, true, false, false, false], [true] * 6], r.nested())
assertEquals([[true, true, true], [false] * 3], r.nestedProperties())
assertEquals([['R', r.getClass(), 'R'], [true] * 3], r.ownerResolved())
}
Expand Down
Loading