You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/06/25 05:04:35 UTC

(groovy) branch GROOVY_5_0_X updated: GROOVY-12093: Static method override on trait implementer ignored when called via this in trait body (cont'd)

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

paulk-asert pushed a commit to branch GROOVY_5_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git


The following commit(s) were added to refs/heads/GROOVY_5_0_X by this push:
     new e22b2008cd GROOVY-12093: Static method override on trait implementer ignored when called via this in trait body (cont'd)
e22b2008cd is described below

commit e22b2008cdba213eb80f63d5123d103b0d2f4e2d
Author: Paul King <pa...@asert.com.au>
AuthorDate: Thu Jun 25 14:58:21 2026 +1000

    GROOVY-12093: Static method override on trait implementer ignored when called via this in trait body (cont'd)
    
    Backport to GROOVY_5_0_X. Preserves existing 5.x-vs-master differences in
    the trait transforms (the createHelperClasses refactor, javadoc and pattern-
    matching differences are master-only and left untouched). The
    TraitStaticDispatchMatrix test remains master-only for now; Groovy12093's
    comment is adjusted accordingly and @Anchored is marked @since 5.0.7.
---
 src/main/java/groovy/transform/Anchored.java       |  70 ++++++
 .../transform/trait/TraitASTTransformation.java    | 127 ++++++++++
 .../transform/trait/TraitReceiverTransformer.java  |  15 +-
 .../groovy/transform/traitx/Groovy12093.groovy     | 266 +++++++++++++++++++++
 4 files changed, 475 insertions(+), 3 deletions(-)

diff --git a/src/main/java/groovy/transform/Anchored.java b/src/main/java/groovy/transform/Anchored.java
new file mode 100644
index 0000000000..2f4b369c68
--- /dev/null
+++ b/src/main/java/groovy/transform/Anchored.java
@@ -0,0 +1,70 @@
+/*
+ *  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 groovy.transform;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a trait method as <em>anchored to the trait</em> — dispatch is fixed
+ * to the trait's own definition rather than routed through the implementing
+ * class.
+ *
+ * <p>Applied to a trait <code>static</code> method, this opts out of the
+ * default per-implementer override dispatch (the Groovy distinctive that the
+ * Grails <code>Validateable.defaultNullable()</code> pattern depends on) and
+ * substitutes the JVM interface-static dispatch model: the implementer's
+ * same-signature static is an independent method, not an override; the trait
+ * body always calls the trait's own copy.
+ *
+ * <p>By default the marker also promotes the annotated method onto the
+ * generated trait interface as a JVM-native public static. That makes
+ * external <code>Trait.m()</code> calls and from-trait <code>T.m()</code>
+ * calls both resolve at the JVM level rather than throwing
+ * <code>MissingMethodException</code>. The {@link #inInterface()} attribute
+ * is provided as an opt-out for the narrow case where dispatch should be
+ * trait-anchored but the method should <em>not</em> be published on the
+ * interface (e.g. a soft-deprecated trait-internal helper that needs to
+ * remain publicly callable for backward compatibility but should not gain a
+ * fresh Java-visible API surface).
+ *
+ * <p>Use this marker for trait statics that are part of the trait's published
+ * contract — guaranteed-invariant utilities the trait author does not want
+ * implementers to redefine. Continue to use plain <code>static</code> when
+ * the trait offers a default that implementers may legitimately override.
+ *
+ * @since 5.0.7
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.METHOD)
+public @interface Anchored {
+    /**
+     * Whether the annotated method should also be promoted onto the generated
+     * trait interface. Default <code>true</code>: the marker bundles
+     * declarer-bound dispatch with external interface visibility (the
+     * coherent JVM interface-static model). Set to <code>false</code> for the
+     * narrow opt-out described above — dispatch stays trait-anchored but the
+     * method is not exposed on the interface.
+     */
+    boolean inInterface() default true;
+}
diff --git a/src/main/java/org/codehaus/groovy/transform/trait/TraitASTTransformation.java b/src/main/java/org/codehaus/groovy/transform/trait/TraitASTTransformation.java
index 0fc1e881b3..3ce40b577f 100644
--- a/src/main/java/org/codehaus/groovy/transform/trait/TraitASTTransformation.java
+++ b/src/main/java/org/codehaus/groovy/transform/trait/TraitASTTransformation.java
@@ -27,6 +27,7 @@ import org.codehaus.groovy.ast.ASTNode;
 import org.codehaus.groovy.ast.AnnotatedNode;
 import org.codehaus.groovy.ast.AnnotationNode;
 import org.codehaus.groovy.ast.ClassCodeExpressionTransformer;
+import org.codehaus.groovy.ast.ClassHelper;
 import org.codehaus.groovy.ast.ClassNode;
 import org.codehaus.groovy.ast.FieldNode;
 import org.codehaus.groovy.ast.GenericsType;
@@ -36,6 +37,7 @@ import org.codehaus.groovy.ast.MethodNode;
 import org.codehaus.groovy.ast.Parameter;
 import org.codehaus.groovy.ast.PropertyNode;
 import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
 import org.codehaus.groovy.ast.expr.Expression;
 import org.codehaus.groovy.ast.expr.MethodCallExpression;
 import org.codehaus.groovy.ast.expr.SpreadExpression;
@@ -115,6 +117,9 @@ import static org.objectweb.asm.Opcodes.ACC_SYNTHETIC;
 @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
 public class TraitASTTransformation extends AbstractASTTransformation implements CompilationUnitAware {
 
+    /** Marker annotation type for {@code @Anchored} trait static methods. */
+    private static final ClassNode ANCHORED_TYPE = ClassHelper.make(groovy.transform.Anchored.class);
+
     public static final String DO_DYNAMIC = TraitReceiverTransformer.class + ".doDynamic";
     public static final String POST_TYPECHECKING_REPLACEMENT = TraitReceiverTransformer.class + ".replacement";
 
@@ -246,6 +251,19 @@ public class TraitASTTransformation extends AbstractASTTransformation implements
             processField(field, initializer, staticInitializer, fieldHelper, helper, staticFieldHelper, cNode, fieldNames);
         }
 
+        // Reject misapplied @Anchored markers before we waste effort
+        // processing them. Errors are registered against the source unit but
+        // processing continues so that multiple violations can be reported
+        // in a single compilation.
+        validateAnchoredAnnotations(cNode);
+
+        // Identify @Anchored public statics whose bodies the main loop will
+        // emit on the helper. Captured up front so the main loop carries no
+        // @Anchored-specific branching and so the interface forwarders can be
+        // installed in a single post-processing step after the originals are
+        // removed from the trait interface.
+        List<MethodNode> anchoredOnInterface = collectAnchoredOnInterface(cNode);
+
         // add methods
         List<MethodNode> nonPublicAPIMethods = new ArrayList<>();
         List<Statement> staticInitStatements = null;
@@ -274,6 +292,15 @@ public class TraitASTTransformation extends AbstractASTTransformation implements
             cNode.removeMethod(privateMethod);
         }
 
+        // Install a public-static method on the trait interface for each
+        // @Anchored callee identified above. The forwarder delegates to the
+        // helper so external `Trait.m()` and from-trait `T.m()` calls resolve
+        // at the JVM level. Done after the removal step so the original
+        // static method is no longer on cNode when the forwarder is added.
+        for (MethodNode anchored : anchoredOnInterface) {
+            cNode.addMethod(createAnchoredInterfaceForwarder(cNode, helper, anchored));
+        }
+
         // copy statements from static and instance init blocks
         if (staticInitStatements != null) {
             BlockStatement toBlock = getBlockStatement(staticInitializer, staticInitializer.getCode());
@@ -617,6 +644,106 @@ public class TraitASTTransformation extends AbstractASTTransformation implements
         fieldHelper.addField(dummyField);
     }
 
+    /**
+     * Reports a compile error for any {@code @Anchored} annotation that is
+     * applied to something other than a public static non-abstract trait
+     * method. Without this check the misapplied annotation would be silently
+     * ignored, leaving the user with no signal that the marker had no effect.
+     */
+    private void validateAnchoredAnnotations(final ClassNode traitClass) {
+        for (MethodNode methodNode : traitClass.getMethods()) {
+            List<AnnotationNode> annotations = methodNode.getAnnotations(ANCHORED_TYPE);
+            if (annotations.isEmpty()) continue;
+            String issue;
+            if (!methodNode.isStatic()) {
+                issue = "is not static";
+            } else if (methodNode.isPrivate()) {
+                issue = "is private";
+            } else if (methodNode.isAbstract()) {
+                issue = "is abstract";
+            } else {
+                continue; // valid
+            }
+            AnnotationNode anchored = annotations.get(0);
+            sourceUnit.addError(new SyntaxException(
+                    "@Anchored can only be applied to public static trait methods; "
+                            + traitClass.getName() + "#" + methodNode.getTypeDescriptor() + " " + issue,
+                    anchored.getLineNumber(), anchored.getColumnNumber()));
+        }
+    }
+
+    /**
+     * Returns the public {@code static} trait methods whose {@code @Anchored}
+     * marker requests interface promotion (i.e. {@code inInterface=true}, the
+     * default). The returned list snapshots the trait's method set so the
+     * caller can iterate the methods without being affected by later
+     * mutations to {@code traitClass.getMethods()}.
+     */
+    private static List<MethodNode> collectAnchoredOnInterface(final ClassNode traitClass) {
+        List<MethodNode> result = new ArrayList<>();
+        for (MethodNode methodNode : traitClass.getMethods()) {
+            if (methodNode.isStatic() && !methodNode.isPrivate() && !methodNode.isAbstract()
+                    && isAnchoredOnInterface(methodNode)) {
+                result.add(methodNode);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Returns {@code true} if the method is annotated with {@code @Anchored}
+     * and the {@code inInterface} attribute is true (the default).
+     */
+    private static boolean isAnchoredOnInterface(final MethodNode methodNode) {
+        List<AnnotationNode> anns = methodNode.getAnnotations(ANCHORED_TYPE);
+        if (anns.isEmpty()) return false;
+        Expression member = anns.get(0).getMember("inInterface");
+        if (member instanceof ConstantExpression
+                && Boolean.FALSE.equals(((ConstantExpression) member).getValue())) {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Builds a public-static method on the trait interface that delegates to
+     * the corresponding helper method.
+     *
+     * <p>Emits {@code public static R m(args) { return T$Trait$Helper.m(T.class, args); }},
+     * preserving generics, exceptions and parameter list of the original
+     * trait static. The trait class itself is passed as the synthetic
+     * {@code $self} receiver expected by the helper, consistent with the
+     * declarer-bound dispatch model that {@code @Anchored} selects.
+     */
+    private static MethodNode createAnchoredInterfaceForwarder(final ClassNode traitClass, final ClassNode helper, final MethodNode original) {
+        Parameter[] params = original.getParameters();
+        Expression[] callArgs = new Expression[params.length + 1];
+        callArgs[0] = classX(traitClass);
+        for (int i = 0; i < params.length; i++) {
+            callArgs[i + 1] = varX(params[i]);
+        }
+        MethodCallExpression call = callX(classX(helper), original.getName(), args(callArgs));
+        Statement body = VOID_TYPE.equals(original.getReturnType()) ? stmt(call) : returnS(call);
+        MethodNode forwarder = new MethodNode(
+                original.getName(),
+                ACC_PUBLIC | ACC_STATIC,
+                original.getReturnType(),
+                params,
+                original.getExceptions(),
+                body);
+        forwarder.setGenericsTypes(original.getGenericsTypes());
+        forwarder.setSynthetic(true);
+        forwarder.setSourcePosition(original);
+        // Carry over the trait method's RUNTIME/CLASS-retention annotations (e.g.
+        // @Deprecated) so the promoted interface static behaves like the original,
+        // consistent with the forwarders generated by TraitComposer. The helper
+        // filters out SOURCE-retention/transform markers and closure-member ones.
+        List<AnnotationNode> copied = new ArrayList<>(), notCopied = new ArrayList<>();
+        GeneralUtils.copyAnnotatedNodeAnnotations(original, copied, notCopied);
+        forwarder.addAnnotations(copied);
+        return forwarder;
+    }
+
     private MethodNode processMethod(final ClassNode traitClass, final ClassNode traitHelperClass, final MethodNode methodNode, final ClassNode fieldHelper, final Collection<String> knownFields) {
         boolean isAbstractMethod = methodNode.isAbstract();
         boolean isPrivateMethod = methodNode.isPrivate();
diff --git a/src/main/java/org/codehaus/groovy/transform/trait/TraitReceiverTransformer.java b/src/main/java/org/codehaus/groovy/transform/trait/TraitReceiverTransformer.java
index 0cdc502cba..9db8cf8d2d 100644
--- a/src/main/java/org/codehaus/groovy/transform/trait/TraitReceiverTransformer.java
+++ b/src/main/java/org/codehaus/groovy/transform/trait/TraitReceiverTransformer.java
@@ -66,6 +66,8 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;
  */
 class TraitReceiverTransformer extends ClassCodeExpressionTransformer {
 
+    private static final ClassNode ANCHORED_TYPE = ClassHelper.make(groovy.transform.Anchored.class);
+
     private final VariableExpression weaved;
     private final SourceUnit unit;
     private final ClassNode traitClass;
@@ -278,16 +280,23 @@ class TraitReceiverTransformer extends ClassCodeExpressionTransformer {
             MethodNode methodNode = findConcreteMethod(traitClass, call.getMethodAsString());
             if (methodNode != null) {
                 MethodCallExpression newCall;
-                if (methodNode.isStatic() && !methodNode.isPrivate() && !inClosure) {
+                boolean anchored = !methodNode.getAnnotations(ANCHORED_TYPE).isEmpty();
+                if (methodNode.isStatic() && !methodNode.isPrivate() && !anchored && !inClosure) {
                     // GROOVY-11985: dispatch unqualified/this-qualified calls to
-                    // public trait statics through the implementing class so an
-                    // override declared on the implementer is visible from trait code.
+                    // public, non-@Anchored trait statics through the
+                    // implementing class so an override declared on the
+                    // implementer is visible from trait code. Annotating the
+                    // trait static with @Anchored opts out of this override
+                    // path and keeps dispatch declarer-bound through the trait
+                    // helper (Java/interface-static flavour); the matching
+                    // interface promotion is performed in TraitASTTransformation.
                     Expression implClass = ClassHelper.isClassType(weaved.getOriginType()) ? varX(weaved) : castX(ClassHelper.CLASS_Type.getPlainNodeReference(), callX(varX(weaved), "getClass"));
                     newCall = callX(implClass, method, transform(arguments));
                     newCall.setImplicitThis(false);
                     newCall.putNodeMetaData(TraitASTTransformation.DO_DYNAMIC, methodNode.getReturnType());
                 } else {
                     // this.m(x) --> (this or T$Trait$Helper).m($self or $static$self or (Class)$self.getClass(), x)
+                    // Reached for: private static, @Anchored static, instance method, or any call inside a closure.
                     Expression selfClassOrObject = methodNode.isStatic() && !ClassHelper.isClassType(weaved.getOriginType()) ? castX(ClassHelper.CLASS_Type.getPlainNodeReference(), callX(weaved, "getClass")) : weaved;
                     newCall = callX(!inClosure ? thisExpr : classX(traitHelper), method, createArgumentList(selfClassOrObject, arguments));
                 }
diff --git a/src/test/groovy/org/codehaus/groovy/transform/traitx/Groovy12093.groovy b/src/test/groovy/org/codehaus/groovy/transform/traitx/Groovy12093.groovy
new file mode 100644
index 0000000000..c2074ab6f3
--- /dev/null
+++ b/src/test/groovy/org/codehaus/groovy/transform/traitx/Groovy12093.groovy
@@ -0,0 +1,266 @@
+/*
+ *  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 org.codehaus.groovy.transform.traitx
+
+import org.codehaus.groovy.control.MultipleCompilationErrorsException
+import org.junit.Test
+
+import static groovy.test.GroovyAssert.assertScript
+import static groovy.test.GroovyAssert.shouldFail
+
+/**
+ * Exercises the {@code @Anchored} marker on trait static methods (GROOVY-12093).
+ *
+ * <p>The marker selects declarer-bound dispatch (Java/interface-static
+ * flavour) in place of the default override-flavour dispatch, and (by
+ * default) also promotes the annotated method onto the generated trait
+ * interface.
+ *
+ * <pre>
+ *   plain  static m()              -&gt; override flavour (dispatch via
+ *                                      implementer; Grails Validateable
+ *                                      canary; Groovy 4.0.32 + post-#2529)
+ *   {@literal @}Anchored static m()           -&gt; declarer-bound dispatch + on the
+ *                                      generated trait interface
+ *   {@literal @}Anchored(inInterface=false)
+ *     static m()                   -&gt; declarer-bound dispatch only, not
+ *                                      published on the interface
+ * </pre>
+ *
+ * Dispatch is implemented in {@code TraitReceiverTransformer}; interface
+ * promotion is implemented in {@code TraitASTTransformation}.
+ */
+final class Groovy12093 {
+
+    // This class covers the @Anchored-specific behaviour: that the marker
+    // makes dispatch trait-anchored, the from-trait T.m() and external
+    // Trait.m() resolution, the inInterface=false opt-out, per-callee
+    // keying, @CompileStatic variants, the inInterface=false STC
+    // compile-error case, and validation that @Anchored is rejected on
+    // non-public-static targets.
+
+    /**
+     * The marker is keyed on the <em>callee</em>, not the caller — same
+     * discipline as the existing private-static escape.
+     */
+    @Test
+    void anchored_isKeyedOnCallee() {
+        assertScript '''
+            import groovy.transform.Anchored
+
+            trait V {
+                static       boolean overridable() { false }
+                @Anchored
+                static       boolean anchored()    { false }
+                // Same caller, different callees: result depends on each
+                // callee's own marker, not the caller's.
+                static List<Boolean> bothSeen() { [this.overridable(), this.anchored()] }
+            }
+            class Over implements V {
+                static boolean overridable() { true }
+                static boolean anchored()    { true }
+            }
+            assert Over.bothSeen() == [true, false]
+        '''
+    }
+
+    /** Plain {@code static} inside {@code @CompileStatic} still routes via the implementer. */
+    @Test
+    void plainStatic_compileStatic_overrideVisible() {
+        assertScript '''
+            @groovy.transform.CompileStatic
+            trait V {
+                static String name() { 'trait' }
+                static String seen() { this.name() }
+            }
+            @groovy.transform.CompileStatic
+            class Impl implements V { static String name() { 'impl' } }
+
+            assert Impl.seen() == 'impl'
+        '''
+    }
+
+    /** {@code @Anchored} inside {@code @CompileStatic} stays trait-anchored. */
+    @Test
+    void anchored_compileStatic_traitAnchored() {
+        assertScript '''
+            import groovy.transform.Anchored
+
+            @groovy.transform.CompileStatic
+            trait V {
+                @Anchored
+                static String name() { 'trait' }
+                static String seen() { this.name() }
+            }
+            @groovy.transform.CompileStatic
+            class Impl implements V { static String name() { 'impl' } }
+
+            assert Impl.seen() == 'trait'
+        '''
+    }
+
+    /**
+     * STC sanity check: external {@code V.name()} from a {@code @CompileStatic}
+     * caller type-checks and runs — the interface static is visible to the
+     * static type checker, not just to dynamic dispatch.
+     */
+    @Test
+    void anchored_compileStatic_externalTraitDotM_typeChecks() {
+        assertScript '''
+            import groovy.transform.Anchored
+            import groovy.transform.CompileStatic
+
+            trait V {
+                @Anchored
+                static String name() { 'trait' }
+            }
+            class Impl implements V { }
+
+            @CompileStatic
+            static String callExternally() {
+                V.name()        // must type-check against the interface static
+            }
+
+            assert callExternally() == 'trait'
+        '''
+    }
+
+    /**
+     * STC sanity check: from-trait {@code V.m()} from inside a
+     * {@code @CompileStatic} trait body also type-checks against the
+     * interface static.
+     */
+    @Test
+    void anchored_compileStatic_fromTraitT_DotM_typeChecks() {
+        assertScript '''
+            import groovy.transform.Anchored
+
+            @groovy.transform.CompileStatic
+            trait V {
+                @Anchored
+                static String name() { 'trait' }
+                static String forced() { V.name() }   // trait-qualified, under @CS
+            }
+            @groovy.transform.CompileStatic
+            class Over implements V { static String name() { 'over' } }
+
+            assert Over.forced() == 'trait'
+        '''
+    }
+
+    /**
+     * STC sanity check: with the {@code inInterface=false} opt-out, external
+     * {@code V.name()} from a {@code @CompileStatic} caller should fail to
+     * compile — no interface static to bind against.
+     */
+    @Test
+    void anchored_inInterfaceFalse_compileStatic_externalCall_isCompileError() {
+        shouldFail(MultipleCompilationErrorsException) {
+            new GroovyShell().evaluate '''
+                import groovy.transform.Anchored
+                import groovy.transform.CompileStatic
+
+                trait V {
+                    @Anchored(inInterface=false)
+                    static String name() { 'trait' }
+                }
+                class Impl implements V { }
+
+                @CompileStatic
+                static String callExternally() {
+                    V.name()       // not on the interface — should be a compile error under @CS
+                }
+                callExternally()
+            '''
+        }
+    }
+
+    /**
+     * The generated interface forwarder for an {@code @Anchored} static should
+     * carry the original method's runtime-retention annotations (e.g.
+     * {@code @Deprecated}), matching the forwarders {@code TraitComposer} creates
+     * for ordinary trait methods.
+     */
+    @Test
+    void anchored_propagatesRuntimeAnnotationsToInterfaceForwarder() {
+        assertScript '''
+            import groovy.transform.Anchored
+            import java.lang.reflect.Modifier
+
+            trait T {
+                @Deprecated
+                @Anchored
+                static String m() { 'T' }
+            }
+
+            def m = T.getDeclaredMethod('m')
+            assert Modifier.isStatic(m.modifiers)
+            assert m.isAnnotationPresent(Deprecated)
+        '''
+    }
+
+    // ---- Validation: @Anchored must target a public static (non-abstract) trait method ----
+
+    /** {@code @Anchored} on an instance method must be a compile error. */
+    @Test
+    void anchored_onInstanceMethod_isCompileError() {
+        def err = shouldFail '''
+            import groovy.transform.Anchored
+            trait V {
+                @Anchored
+                def m() { 'V' }            // instance, not static
+            }
+            new Object()
+        '''
+        assert err.message.contains('@Anchored can only be applied to public static trait methods')
+        assert err.message.contains('is not static')
+    }
+
+    /** {@code @Anchored} on a private static method must be a compile error. */
+    @Test
+    void anchored_onPrivateStatic_isCompileError() {
+        def err = shouldFail '''
+            import groovy.transform.Anchored
+            trait V {
+                @Anchored
+                private static m() { 'V' }
+            }
+            new Object()
+        '''
+        assert err.message.contains('@Anchored can only be applied to public static trait methods')
+        assert err.message.contains('is private')
+    }
+
+    /** {@code @Anchored} on an abstract trait method (which is implicitly
+     * non-static — Groovy rejects {@code abstract static}) surfaces the same
+     * "not static" diagnostic. */
+    @Test
+    void anchored_onAbstractInstanceMethod_isCompileError() {
+        def err = shouldFail '''
+            import groovy.transform.Anchored
+            trait V {
+                @Anchored
+                abstract m()
+            }
+            new Object()
+        '''
+        assert err.message.contains('@Anchored can only be applied to public static trait methods')
+        assert err.message.contains('is not static')
+    }
+}