Scott Murphy Heiberg created GROOVY-12491:
---------------------------------------------
Summary: Object initializer code dispatches through the meta
class: trait $init$ calls, and instance initializer blocks of @CompileStatic
classes
Key: GROOVY-12491
URL: https://issues.apache.org/jira/browse/GROOVY-12491
Project: Groovy
Issue Type: Bug
Components: Compiler, Static compilation
Affects Versions: 6.0.0
Reporter: Scott Murphy Heiberg
Code that runs during object construction is dispatched through the meta-class
in two places, even in {{@CompileStatic}} classes. Both cost a dynamic dispatch
on every instantiation, and in a GraalVM native image both need reflection
metadata, or construction fails.
*Trait initializers.* When a class implements a trait,
{{TraitComposer.applyTrait}} adds {{Helper.$init$(this)}} to the class's object
initializer without a method target (the {{$static$init$}} call beside it has
one):
{code:groovy}
trait Greeting { String greeting = 'hello' }
@CompileStatic class StaticGreeter implements Greeting {}
class DynamicGreeter implements Greeting {}
{code}
* {{StaticGreeter.<init>}}: {{ldc Greeting$Trait$Helper; ldc "$init$"; ...
invokestatic ScriptBytecodeAdapter.invokeMethodN}}
* {{DynamicGreeter.<init>}}: {{invokedynamic
invoke:(Class,LDynamicGreeter;)Object}}
A native image therefore has to register every trait helper's {{$init$}} for
reflection, or construction fails with "No signature of static method: $init$".
*Instance initializer blocks of {{@CompileStatic}} classes.*
{{StaticTypeCheckingVisitor.visitObjectInitializerStatements}} checks the
statements against a placeholder constructor without a declaring class
(GROOVY-5450), so {{StaticCompilationVisitor}} treats them as not statically
compiled: it drops the method targets the type checker resolved and compiles
anonymous inner classes created there dynamically.
{code:groovy}
@CompileStatic
class C extends Base {
{ Other.baz(this) } // ScriptBytecodeAdapter.invokeMethodN
{ String s = 'y'; s.toUpperCase() } // ScriptBytecodeAdapter.invokeMethod0
{ super.hello() } // invokeMethodOnSuper0:
MissingMethodException at run time
}
{code}
The same calls in a constructor or field initializer are direct.
Proposed fix: give the {{$init$}} call its method target, and give the
placeholder constructor the class as its declaring class, as field initializers
already resolve.
PR: https://github.com/apache/groovy/pull/3025
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)