You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2026/09/07 22:21:14 UTC

(groovy) branch master updated: GROOVY-12363: SC: compile anonymous inner classes of a @CompileStatic method statically

This is an automated email from the ASF dual-hosted git repository.

daniellansun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git


The following commit(s) were added to refs/heads/master by this push:
     new 8380d31a25 GROOVY-12363: SC: compile anonymous inner classes of a @CompileStatic method statically
8380d31a25 is described below

commit 8380d31a2527c1838d1ecee31ecf757f0d238ec5
Author: Paul King <pa...@asert.com.au>
AuthorDate: Sun Sep 6 13:31:04 2026 +1000

    GROOVY-12363: SC: compile anonymous inner classes of a @CompileStatic method statically
    
    An anonymous inner class declared in a method-level @CompileStatic
    method was marked as statically compiled only after the type checker
    had visited its body, so the body compiled dynamically while the class
    was generated with the static-compilation MOP writer, which emits no
    super$ bridges: any super.m() call failed with MissingMethodException.
    Mark the class from its enclosing method before the body is visited,
    and have the method-level transformation run StaticCompilationTransformer
    over such classes as the class-level path does, since operator
    expressions left unrewritten fail at class generation.
---
 .../transform/sc/StaticCompilationVisitor.java     |  21 ++-
 .../transform/sc/StaticCompileTransformation.java  |  15 +-
 src/test/groovy/bugs/Groovy12363.groovy            | 187 +++++++++++++++++++++
 3 files changed, 217 insertions(+), 6 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/transform/sc/StaticCompilationVisitor.java b/src/main/java/org/codehaus/groovy/transform/sc/StaticCompilationVisitor.java
index 4154e6857b..4e03422cf7 100644
--- a/src/main/java/org/codehaus/groovy/transform/sc/StaticCompilationVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/sc/StaticCompilationVisitor.java
@@ -268,14 +268,27 @@ public class StaticCompilationVisitor extends StaticTypeCheckingVisitor {
      */
     @Override
     public void visitConstructorCallExpression(final ConstructorCallExpression call) {
-        super.visitConstructorCallExpression(call);
-
-        if (call.isUsingAnonymousInnerClass() && call.getType().getNodeMetaData(StaticTypeCheckingVisitor.class) != null) {
+        if (call.isUsingAnonymousInnerClass()) {
+            // GROOVY-6925: an anonymous inner class follows its enclosing method, the
+            // most specific annotation (a @CompileStatic method inside a @CompileDynamic
+            // class, or the reverse). visitClass may already have recorded the class-level
+            // answer for it, so recompute here rather than keep that: this hook is only
+            // reached from a method that is actually visited. GROOVY-12363: decide before
+            // the type checker visits the body below, otherwise its methods are checked
+            // while still counting as dynamic (no direct call targets, no
+            // SUPER_MOP_METHOD_REQUIRED) and yet the class is generated as statically
+            // compiled, which omits the super$ MOP bridges a dynamic super call needs.
             ClassNode anonType = call.getType();
-            anonType.putNodeMetaData(STATIC_COMPILE_NODE, anonType.getEnclosingMethod().getNodeMetaData(STATIC_COMPILE_NODE));
+            MethodNode enclosingMethod = anonType.getEnclosingMethod();
+            boolean isSC = enclosingMethod != null
+                    ? isStaticallyCompiled(enclosingMethod)
+                    : isStaticallyCompiled(getEnclosingDeclaration());
+            anonType.putNodeMetaData(STATIC_COMPILE_NODE, isSC);
             anonType.putNodeMetaData(WriterControllerFactory.class, anonType.getOuterClass().getNodeMetaData(WriterControllerFactory.class));
         }
 
+        super.visitConstructorCallExpression(call);
+
         if (!isStaticallyCompiled(getEnclosingDeclaration())) return;
 
         MethodNode target = call.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
diff --git a/src/main/java/org/codehaus/groovy/transform/sc/StaticCompileTransformation.java b/src/main/java/org/codehaus/groovy/transform/sc/StaticCompileTransformation.java
index 6a78e692ea..a946c28c80 100644
--- a/src/main/java/org/codehaus/groovy/transform/sc/StaticCompileTransformation.java
+++ b/src/main/java/org/codehaus/groovy/transform/sc/StaticCompileTransformation.java
@@ -93,8 +93,19 @@ public class StaticCompileTransformation extends StaticTypesTransformation {
         StaticCompilationTransformer transformer = new StaticCompilationTransformer(source, visitor);
         if (target instanceof ClassNode) {
             transformer.visitClass((ClassNode) target);
-        } else if (target instanceof MethodNode) {
-            transformer.visitMethod((MethodNode) target);
+        } else if (target instanceof MethodNode methodNode) {
+            transformer.visitMethod(methodNode);
+            // GROOVY-12363: an anonymous inner class declared in this method is compiled
+            // statically with it (StaticCompilationVisitor marks it from the enclosing
+            // method), so its expressions need the same rewriting the class path applies
+            // to inner classes; e.g. an operator call left as a BinaryExpression fails at
+            // class generation in StaticTypesCallSiteWriter
+            methodNode.getDeclaringClass().getInnerClasses().forEachRemaining(innerClass -> {
+                if (innerClass.isAnonymous() && methodNode.equals(innerClass.getEnclosingMethod())
+                        && StaticCompilationVisitor.isStaticallyCompiled(innerClass)) {
+                    transformer.visitClass(innerClass);
+                }
+            });
         }
     }
 
diff --git a/src/test/groovy/bugs/Groovy12363.groovy b/src/test/groovy/bugs/Groovy12363.groovy
new file mode 100644
index 0000000000..6e4e555a04
--- /dev/null
+++ b/src/test/groovy/bugs/Groovy12363.groovy
@@ -0,0 +1,187 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package bugs
+
+import org.junit.jupiter.api.Test
+
+import static groovy.test.GroovyAssert.assertScript
+
+/**
+ * An anonymous inner class declared in a method-level {@code @CompileStatic}
+ * method (enclosing class not annotated) was marked as statically compiled only
+ * after the type checker had visited its body, so the body compiled dynamically
+ * while the class was generated with the static-compilation MOP writer, which
+ * emits no {@code super$} bridges: any {@code super.m()} call then failed with
+ * {@code MissingMethodException}.
+ */
+final class Groovy12363 {
+
+    @Test
+    void testSuperCallFromAnonymousClassInCompileStaticMethod() {
+        assertScript '''
+            import java.util.logging.*
+
+            class Holders {
+                @groovy.transform.CompileStatic
+                static Handler cs() {
+                    new StreamHandler(System.out, new SimpleFormatter()) {
+                        void publish(LogRecord r) { super.publish(r); flush() }
+                    }
+                }
+                static Handler dyn() {
+                    new StreamHandler(System.out, new SimpleFormatter()) {
+                        void publish(LogRecord r) { super.publish(r); flush() }
+                    }
+                }
+            }
+
+            def record = new LogRecord(Level.INFO, 'groovy12363')
+            Holders.cs().publish(record)   // threw MissingMethodException
+            Holders.dyn().publish(record)
+
+            // the body now compiles statically (direct super call, no bridge needed);
+            // the dynamic variant keeps its MOP bridge
+            assert !Holders.cs().getClass().declaredMethods.any { it.name.startsWith('super$') }
+            assert  Holders.dyn().getClass().declaredMethods.any { it.name.startsWith('super$') }
+        '''
+    }
+
+    @Test
+    void testSuperCallWithArgumentsAndResultFromGroovySuperclass() {
+        assertScript '''
+            abstract class Base {
+                String greet(String who) { "hi $who" }
+            }
+            class Factory {
+                @groovy.transform.CompileStatic
+                static Base make() {
+                    new Base() {
+                        String greet(String who) { 'cs:' + super.greet(who) }
+                    }
+                }
+            }
+            assert Factory.make().greet('x') == 'cs:hi x'
+        '''
+    }
+
+    @Test
+    void testOperatorsAndCapturedVariablesInAnonymousClassBody() {
+        // the statically compiled body also needs StaticCompilationTransformer's
+        // rewriting (operator calls), which the method-level path did not apply
+        // to anonymous classes; covers captured parameters, locals, fields and nesting
+        assertScript '''
+            class H {
+                StringBuilder field = new StringBuilder()
+                @groovy.transform.CompileStatic
+                Runnable make(StringBuilder param) {
+                    StringBuilder local = new StringBuilder()
+                    new Runnable() {
+                        void run() {
+                            param << 'p'
+                            local << 'l'
+                            field << 'f'
+                            def nested = new Runnable() { void run() { param << 'n' } }
+                            nested.run()
+                            param << local.toString() + field.toString()
+                        }
+                    }
+                }
+            }
+            def h = new H()
+            def param = new StringBuilder()
+            h.make(param).run()
+            assert param.toString() == 'pnlf'
+        '''
+    }
+
+    @Test
+    void testCompileStaticMethodInsideCompileDynamicClass() {
+        // the most specific annotation wins: the anonymous class body follows the
+        // @CompileStatic method even though the enclosing class is @CompileDynamic
+        assertScript '''
+            abstract class Base {
+                String greet(String who) { "hi $who" }
+            }
+            @groovy.transform.CompileDynamic
+            class Outer {
+                @groovy.transform.CompileStatic
+                Base make(StringBuilder sink) {
+                    new Base() {
+                        String greet(String who) { sink << who; 'cs:' + super.greet(who) }
+                    }
+                }
+            }
+            def sink = new StringBuilder()
+            def b = new Outer().make(sink)
+            assert b.greet('x') == 'cs:hi x'
+            assert sink.toString() == 'x'
+            assert !b.getClass().declaredMethods.any { it.name.startsWith('super$') } : 'body should be statically compiled'
+        '''
+    }
+
+    @Test
+    void testCompileDynamicMethodInsideCompileStaticClass() {
+        // the reverse: a dynamic method in a static class keeps a dynamic anonymous class
+        assertScript '''
+            abstract class Base {
+                String greet(String who) { "hi $who" }
+            }
+            @groovy.transform.CompileStatic
+            class Outer {
+                @groovy.transform.CompileDynamic
+                Base make(StringBuilder sink) {
+                    new Base() {
+                        String greet(String who) { sink << who; 'dyn:' + super.greet(who) }
+                    }
+                }
+            }
+            def sink = new StringBuilder()
+            def b = new Outer().make(sink)
+            assert b.greet('x') == 'dyn:hi x'
+            assert sink.toString() == 'x'
+        '''
+    }
+
+    @Test
+    void testInvokedFromJavaCode() {
+        // the shape of the original report: the JDK logger calls publish, which calls super
+        assertScript '''
+            import java.util.logging.*
+
+            class Holders {
+                @groovy.transform.CompileStatic
+                static Logger logger(StringBuilder sink) {
+                    def l = Logger.getLogger('groovy12363'); l.useParentHandlers = false
+                    l.addHandler(new Handler() {
+                        void publish(LogRecord r) { sink << r.message }
+                        void flush() {}
+                        void close() {}
+                    })
+                    l.addHandler(new StreamHandler(new ByteArrayOutputStream(), new SimpleFormatter()) {
+                        void publish(LogRecord r) { super.publish(r); sink << '!' }
+                    })
+                    l
+                }
+            }
+            def sink = new StringBuilder()
+            Holders.logger(sink).info('hello')
+            assert sink.toString() == 'hello!'
+        '''
+    }
+}