Scott Murphy Heiberg created GROOVY-12840:
---------------------------------------------

             Summary: Closure packing declines a closure that reads a parameter 
or local variable named owner, delegate or thisObject
                 Key: GROOVY-12840
                 URL: https://issues.apache.org/jira/browse/GROOVY-12840
             Project: Groovy
          Issue Type: Bug
          Components: Compiler
    Affects Versions: 6.0.1, 6.0.0
            Reporter: Scott Murphy Heiberg


The packability analysis (ClosureWriter#isPackable) keeps a closure as a class 
when its body names one of the Closure pseudo-properties: owner, delegate, 
thisObject, directive, resolveStrategy, metaClass. The test is on the name of 
every VariableExpression alone, so it also declines a closure that reads a 
method parameter or a local variable of that name. Such a variable hides the 
Closure property in a closure class too, so the body does not use the property 
and nothing prevents packing it.

{code:groovy}
import groovy.transform.CompileStatic
import groovy.transform.PackedClosures

@CompileStatic
@PackedClosures
class OwnerName {
    static String greet(String owner, List<String> pets) {
        Closure<String> c = { String pet -> owner + ' owns ' + pet }
        println c.getClass().name
        pets.collect(c).join(', ')
    }
    static String other(String name, List<String> pets) {
        Closure<String> c = { String pet -> name + ' owns ' + pet }
        println c.getClass().name
        pets.collect(c).join(', ')
    }
    static void main(String[] args) {
        println greet('Ann', ['Rex'])
        println other('Ann', ['Rex'])
    }
}
{code}

Actual (6.0.0, 6.0.1 and master, 7.0.0-SNAPSHOT):

{noformat}
OwnerName$_greet_closure1
Ann owns Rex
org.codehaus.groovy.runtime.PackedClosure$Fixed1
Ann owns Rex
{noformat}

Expected: both closures packed (PackedClosure$Fixed1 twice). The results are 
right either way; the cost is a closure class that need not exist, a warning 
with @PackedClosures(mode = WARN) or groovy.target.closure.pack.report, and a 
compile error with @PackedClosures(mode = STRICT), whose message says the 
closure "needs a real Closure (uses 
owner/delegate/thisObject/resolveStrategy/super or metaClass, ...)" although it 
uses none of them. The same with dynamic compilation.

Proposed fix (pull request to follow)

In the visitVariableExpression of ClosureWriter#isPackable, decline for one of 
those names only when the expression's accessed variable is not a Parameter or 
a declared local variable (a VariableExpression). A name bound to a field or 
property of the enclosing class, or to nothing, still reads the Closure 
property in a closure class and keeps declining.




--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to