Paul King created GROOVY-12481:
----------------------------------

             Summary: SC: `this::method` in a static context fails to compile 
with "Failed to find method ... for the type: java.lang.Class<A>"
                 Key: GROOVY-12481
                 URL: https://issues.apache.org/jira/browse/GROOVY-12481
             Project: Groovy
          Issue Type: Improvement
          Components: Static compilation
    Affects Versions: 6.0.0, 5.1.2
            Reporter: Paul King


h2. Description:

In a static context, `this` is the class itself (a `Class<A>` value). Under 
{{@CompileStatic}}, a method reference with a {{this}} receiver in a static 
method, static initializer or static script method looks for the method on 
{{java.lang.Class}} only, not as a static method of the class. So {{this::foo}} 
fails to compile, although {{A::foo}}, {{this.foo()}} and {{this.&foo}} all 
work. With {{@TypeChecked}} or dynamic compilation, {{this::foo}} works.

{code:groovy}
import groovy.transform.CompileStatic
import java.util.function.Supplier

@CompileStatic
class A {
    static foo() { 42 }
    static m() {
        Supplier s = this::foo
        s.get()
    }
}
assert A.m() == 42
{code}
{noformat}
Failed to find method 'foo()' for the type: java.lang.Class<A>
{noformat}

||Form, in a static method||{{@CompileStatic}}||{{@TypeChecked}}||dynamic||
|{{this::foo}} (static {{foo()}})|*compile error*|42|42|
|{{this::bar}} (static {{bar(int)}}, {{Function<Integer,Object>}})|*compile 
error*|works|works|
|{{this::foo}} in a {{static \{ \}}} initializer|*compile error*|works|works|
|{{this::foo}} in a static method of a script|*compile error*|works|works|
|{{this::getSimpleName}} (method of {{java.lang.Class}})|"A"|"A"|"A"|
|{{A::foo}}|42|42|42|
|{{this.foo()}}|42|42|42|
|{{this.&foo}}|42|42|42|
|{{this::inst}} (instance method {{inst()}})|compile error (same wrong 
message)|{{MissingMethodException}} at runtime|{{MissingMethodException}} at 
runtime|

Expected: in a static context, {{this::name}} resolves the way {{this.name()}} 
already does under {{@CompileStatic}}: first as a static method of the 
enclosing class, otherwise as a method of {{java.lang.Class}}, so that 
{{this::getSimpleName}} keeps working. When neither exists, the error should 
name the enclosing class, not only {{Class<A>}}.

Cause: 
{{StaticTypesMethodReferenceExpressionWriter.resolveMethodReferenceTarget}} 
treats only a {{ClassExpression}} receiver as a type reference. For any other 
receiver it takes the type from the type chooser, which for {{this}} in a 
static context is {{Class<A>}}. So the lookup runs against {{java.lang.Class}} 
and fails in {{validate}}. Because the error is raised during class generation, 
the type checker has already accepted the code, which is why {{@TypeChecked}} 
compiles it.

Workaround: use {{A::foo}} or {{this.&foo}}.




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

Reply via email to