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 2023/10/03 10:32:31 UTC

[groovy] branch master updated (97556eb37b -> a3d7c7989d)

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

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


    from 97556eb37b Bump org.jfrog.buildinfo:build-info-extractor-gradle
     new 44d286e67e GROOVY-8299: implement interfaces with default methods (initial commit)
     new aa35bdd450 GROOVY-8299: restore trait marker in AstBuilder or traits won't work
     new 3f06e15647 GROOVY-9801: add default methods to stub generation
     new c8d0325356 GROOVY-8299: allow I.super for default methods
     new cb33dc6c8d GROOVY-8299: implement call to interface method using super with static compilation
     new 63d4a1e002 GROOVY-8299: implement dynamic path for default interface methods
     new a3d7c7989d GROOVY-8299: typechecking needs to use receiver to decide on target method being valid

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../apache/groovy/parser/antlr4/AstBuilder.java    | 10 ++-
 .../groovy/classgen/ClassCompletionVerifier.java   |  2 +-
 .../groovy/classgen/asm/InvocationWriter.java      | 23 ++++++-
 .../classgen/asm/indy/InvokeDynamicWriter.java     | 22 ++++++-
 .../classgen/asm/sc/StaticInvocationWriter.java    | 10 ++-
 .../codehaus/groovy/control/ResolveVisitor.java    |  8 ++-
 .../groovy/tools/javac/JavaStubGenerator.java      |  3 +
 .../transform/stc/StaticTypeCheckingVisitor.java   | 16 ++++-
 .../codehaus/groovy/vmplugin/v7/IndyInterface.java |  6 +-
 .../groovy/vmplugin/v8/CacheableCallSite.java      |  9 ++-
 .../codehaus/groovy/vmplugin/v8/IndyInterface.java | 41 +++++++-----
 .../org/codehaus/groovy/vmplugin/v8/Selector.java  | 74 +++++++++++++---------
 .../lang/DefaultInterfaceMethodsTest.groovy}       | 40 ++++++------
 src/test/groovy/transform/stc/BugsSTCTest.groovy   |  6 +-
 14 files changed, 186 insertions(+), 84 deletions(-)
 copy src/{spec/test/metaprogramming/StaticPropertyMissingAndMethodMissingTest.groovy => test/groovy/lang/DefaultInterfaceMethodsTest.groovy} (54%)


[groovy] 05/07: GROOVY-8299: implement call to interface method using super with static compilation

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit cb33dc6c8d54b89f738baf95a48121273e269bad
Author: Jochen Theodorou <bl...@gmx.org>
AuthorDate: Mon Sep 25 21:38:01 2023 +0200

    GROOVY-8299: implement call to interface method using super with static compilation
---
 .../groovy/classgen/asm/InvocationWriter.java      | 23 ++++++++++++++++++++--
 .../classgen/asm/sc/StaticInvocationWriter.java    | 10 +++++++++-
 .../transform/stc/StaticTypeCheckingVisitor.java   | 12 +++++++++++
 3 files changed, 42 insertions(+), 3 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/InvocationWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/InvocationWriter.java
index ce89bc4092..ed66155ed7 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/InvocationWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/InvocationWriter.java
@@ -157,7 +157,10 @@ public class InvocationWriter {
         if (!target.isStatic()) {
             if (receiver != null) {
                 Expression objectExpression = receiver;
-                if (implicitThis
+                if (!implicitThis && callSuperDefault(enclosingClass, target, receiver)) {
+                    compileStack.pushImplicitThis(true);
+                    objectExpression = new VariableExpression("this", declaringClass);
+                } else if (implicitThis
                         && enclosingClass.getOuterClass() != null
                         && !enclosingClass.isDerivedFrom(declaringClass)
                         && !enclosingClass.implementsInterface(declaringClass)) {
@@ -181,7 +184,7 @@ public class InvocationWriter {
         int opcode;
         if (target.isStatic()) {
             opcode = INVOKESTATIC;
-        } else if (isSuperExpression(receiver)) {
+        } else if (isSuperExpression(receiver) || isClassWithSuper(receiver)) {
             opcode = INVOKESPECIAL;
         } else if (declaringClass.isInterface()) {
             opcode = INVOKEINTERFACE;
@@ -227,6 +230,22 @@ public class InvocationWriter {
         return true;
     }
 
+    private boolean callSuperDefault(ClassNode enclosingClass, MethodNode target, Expression receiver) {
+        ClassNode declaringClass = target.getDeclaringClass();
+        if (declaringClass.isInterface() && enclosingClass.implementsInterface(declaringClass)) {
+            return isClassWithSuper(receiver);
+        }
+        return false;
+    }
+
+    private boolean isClassWithSuper(Expression exp) {
+        if (exp instanceof PropertyExpression) {
+            PropertyExpression pexp = (PropertyExpression) exp;
+            return pexp.getObjectExpression() instanceof ClassExpression && "super".equals(pexp.getPropertyAsString());
+        }
+        return false;
+    }
+
     /**
      * Supplements {@link org.apache.groovy.ast.tools.ExpressionUtils#isThisExpression isThisExpression}
      * with the ability to see into {@code CheckcastReceiverExpression}.
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
index 4631287a4d..0aa0e28738 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java
@@ -381,7 +381,7 @@ public class StaticInvocationWriter extends InvocationWriter {
                 }
             }
         }
-        if (receiver != null && !isSuperExpression(receiver)) {
+        if (receiver != null && !isSuperExpression(receiver) && !isClassWithSuper(receiver)) {
             // in order to avoid calls to castToType, which is the dynamic behaviour, make sure that we call CHECKCAST instead then replace the top operand type
             if (currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER) == null) fixedReceiver = new CheckcastReceiverExpression(fixedReceiver, target);
             return super.writeDirectMethodCall(target, fixedImplicitThis, fixedReceiver, args);
@@ -389,6 +389,14 @@ public class StaticInvocationWriter extends InvocationWriter {
         return super.writeDirectMethodCall(target, implicitThis, receiver, args);
     }
 
+    private boolean isClassWithSuper(Expression receiver) {
+        if (receiver instanceof PropertyExpression) {
+            PropertyExpression pexp = (PropertyExpression) receiver;
+            return pexp.getObjectExpression() instanceof ClassExpression && "super".equals(pexp.getPropertyAsString());
+        }
+        return false;
+    }
+
     private boolean tryPrivateMethod(final MethodNode target, final boolean implicitThis, final Expression receiver, final TupleExpression args, final ClassNode classNode) {
         ClassNode declaringClass = target.getDeclaringClass();
         if ((isPrivateBridgeMethodsCallAllowed(declaringClass, classNode) || isPrivateBridgeMethodsCallAllowed(classNode, declaringClass))
diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
index 0afd3f2765..f702ae6a15 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -1533,6 +1533,18 @@ out:    if ((samParameterTypes.length == 1 && isOrImplements(samParameterTypes[0
             }
         }
 
+        if (staticOnlyAccess && "super".equals(propertyName)) {
+            // handle "I.super" for default interface logic
+            ClassNode enclosingType = typeCheckingContext.getEnclosingClassNode();
+            ClassNode accessor = objectExpressionType.getGenericsTypes()[0].getType();
+            if (accessor.isInterface() && enclosingType.implementsInterface(accessor)) {
+                storeType(pexp, accessor);
+                return true;
+            } else {
+                return false;
+            }
+        }
+
         boolean foundGetterOrSetter = false;
         String capName = capitalize(propertyName);
         Set<ClassNode> handledNodes = new HashSet<>();


[groovy] 02/07: GROOVY-8299: restore trait marker in AstBuilder or traits won't work

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit aa35bdd450a6a9996fe6a9607ca66c1035071898
Author: Jochen Theodorou <bl...@gmx.org>
AuthorDate: Mon Sep 11 15:16:33 2023 +0200

    GROOVY-8299: restore trait marker in AstBuilder or traits won't work
---
 src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
index 733584e79f..2d9557508e 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
@@ -1313,6 +1313,10 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
         } else if (isNonSealed) {
             classNode.addAnnotation(makeAnnotationNode(NonSealed.class));
         }
+        if (asBoolean(ctx.TRAIT())) {
+            classNode.addAnnotation(makeAnnotationNode(Trait.class));
+        }
+
 
         classNode.addAnnotations(modifierManager.getAnnotations());
         if (isRecord && classNode.getAnnotations().stream().noneMatch(a ->


[groovy] 06/07: GROOVY-8299: implement dynamic path for default interface methods

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 63d4a1e002cfeece8e86ea7b7749467e304ed329
Author: Jochen Theodorou <bl...@gmx.org>
AuthorDate: Fri Sep 29 21:51:08 2023 +0200

    GROOVY-8299: implement dynamic path for default interface methods
---
 .../classgen/asm/indy/InvokeDynamicWriter.java     | 22 ++++++-
 .../codehaus/groovy/vmplugin/v7/IndyInterface.java |  6 +-
 .../groovy/vmplugin/v8/CacheableCallSite.java      |  9 ++-
 .../codehaus/groovy/vmplugin/v8/IndyInterface.java | 41 +++++++-----
 .../org/codehaus/groovy/vmplugin/v8/Selector.java  | 74 +++++++++++++---------
 5 files changed, 103 insertions(+), 49 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/indy/InvokeDynamicWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/indy/InvokeDynamicWriter.java
index 74aee3209d..041b177c3a 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/indy/InvokeDynamicWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/indy/InvokeDynamicWriter.java
@@ -25,6 +25,7 @@ import org.codehaus.groovy.ast.expr.ConstantExpression;
 import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
 import org.codehaus.groovy.ast.expr.EmptyExpression;
 import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.PropertyExpression;
 import org.codehaus.groovy.ast.tools.WideningCategories;
 import org.codehaus.groovy.classgen.AsmClassGenerator;
 import org.codehaus.groovy.classgen.asm.CompileStack;
@@ -35,6 +36,7 @@ import org.codehaus.groovy.classgen.asm.WriterController;
 import org.codehaus.groovy.runtime.wrappers.Wrapper;
 import org.codehaus.groovy.vmplugin.v8.IndyInterface;
 import org.objectweb.asm.Handle;
+import org.objectweb.asm.Opcodes;
 
 import java.lang.invoke.CallSite;
 import java.lang.invoke.MethodHandles.Lookup;
@@ -47,6 +49,7 @@ import static org.codehaus.groovy.ast.ClassHelper.boolean_TYPE;
 import static org.codehaus.groovy.ast.ClassHelper.getWrapper;
 import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveBoolean;
 import static org.codehaus.groovy.ast.ClassHelper.isWrapperBoolean;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.bytecodeX;
 import static org.codehaus.groovy.classgen.asm.BytecodeHelper.doCast;
 import static org.codehaus.groovy.classgen.asm.BytecodeHelper.getTypeDescription;
 import static org.codehaus.groovy.vmplugin.v8.IndyInterface.GROOVY_OBJECT;
@@ -57,6 +60,7 @@ import static org.codehaus.groovy.vmplugin.v8.IndyInterface.THIS_CALL;
 import static org.codehaus.groovy.vmplugin.v8.IndyInterface.CallType.CAST;
 import static org.codehaus.groovy.vmplugin.v8.IndyInterface.CallType.GET;
 import static org.codehaus.groovy.vmplugin.v8.IndyInterface.CallType.INIT;
+import static org.codehaus.groovy.vmplugin.v8.IndyInterface.CallType.INTERFACE;
 import static org.codehaus.groovy.vmplugin.v8.IndyInterface.CallType.METHOD;
 import static org.objectweb.asm.Opcodes.H_INVOKESTATIC;
 
@@ -122,9 +126,10 @@ public class InvokeDynamicWriter extends InvocationWriter {
         compileStack.popLHS();
     }
 
-    private void makeIndyCall(final MethodCallerMultiAdapter adapter, final Expression receiver, final boolean implicitThis, final boolean safe, final String methodName, final Expression arguments) {
+    private void makeIndyCall(final MethodCallerMultiAdapter adapter, final Expression origReceiver, final boolean implicitThis, final boolean safe, final String methodName, final Expression arguments) {
         OperandStack operandStack = controller.getOperandStack();
 
+        Expression receiver = correctReceiverForInterfaceCall(origReceiver, operandStack);
         StringBuilder sig = new StringBuilder(prepareIndyCall(receiver, implicitThis));
 
         // load arguments
@@ -150,12 +155,27 @@ public class InvokeDynamicWriter extends InvocationWriter {
         }
 
         sig.append(")Ljava/lang/Object;");
+
         String callSiteName = METHOD.getCallSiteName();
         if (adapter == null) callSiteName = INIT.getCallSiteName();
+        // receiver != origReceiver interface default method call
+        if (receiver != origReceiver) callSiteName = INTERFACE.getCallSiteName();
+
         int flags = getMethodCallFlags(adapter, safe, containsSpreadExpression);
+
         finishIndyCall(BSM, callSiteName, sig.toString(), numberOfArguments, methodName, flags);
     }
 
+    private Expression correctReceiverForInterfaceCall(Expression exp, OperandStack operandStack) {
+        if (exp instanceof PropertyExpression) {
+            PropertyExpression pexp = (PropertyExpression) exp;
+            if (pexp.getObjectExpression() instanceof ClassExpression && "super".equals(pexp.getPropertyAsString())) {
+                return bytecodeX(pexp.getObjectExpression().getType(), mv -> mv.visitIntInsn(Opcodes.ALOAD, 0));
+            }
+        }
+        return exp;
+    }
+
     private static int getMethodCallFlags(final MethodCallerMultiAdapter adapter, final boolean safe, final boolean spread) {
         int flags = 0;
         if (safe)                           flags |= SAFE_NAVIGATION;
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v7/IndyInterface.java b/src/main/java/org/codehaus/groovy/vmplugin/v7/IndyInterface.java
index 2583aeaf68..57e8da6e18 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v7/IndyInterface.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v7/IndyInterface.java
@@ -18,6 +18,8 @@
  */
 package org.codehaus.groovy.vmplugin.v7;
 
+import org.codehaus.groovy.vmplugin.v8.CacheableCallSite;
+
 import java.lang.invoke.CallSite;
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodHandles.Lookup;
@@ -121,14 +123,14 @@ public class IndyInterface {
      * Get the cached methodhandle. if the related methodhandle is not found in the inline cache, cache and return it.
      */
     public static Object fromCache(MutableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) throws Throwable {
-        return org.codehaus.groovy.vmplugin.v8.IndyInterface.fromCache(callSite, sender, methodName, callID, safeNavigation, thisCall, spreadCall, dummyReceiver, arguments);
+        return org.codehaus.groovy.vmplugin.v8.IndyInterface.fromCache((CacheableCallSite)callSite, sender, methodName, callID, safeNavigation, thisCall, spreadCall, dummyReceiver, arguments);
     }
 
     /**
      * Core method for indy method selection using runtime types.
      */
     public static Object selectMethod(MutableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) throws Throwable {
-        return org.codehaus.groovy.vmplugin.v8.IndyInterface.selectMethod(callSite, sender, methodName, callID, safeNavigation, thisCall, spreadCall, dummyReceiver, arguments);
+        return org.codehaus.groovy.vmplugin.v8.IndyInterface.selectMethod((CacheableCallSite)callSite, sender, methodName, callID, safeNavigation, thisCall, spreadCall, dummyReceiver, arguments);
     }
 
     /**
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/CacheableCallSite.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/CacheableCallSite.java
index a356f0a20c..9e00ccfa8e 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/CacheableCallSite.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/CacheableCallSite.java
@@ -22,6 +22,7 @@ import org.apache.groovy.util.SystemUtil;
 import org.codehaus.groovy.runtime.memoize.MemoizeCache;
 
 import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodType;
 import java.lang.invoke.MutableCallSite;
 import java.lang.ref.SoftReference;
@@ -38,6 +39,7 @@ public class CacheableCallSite extends MutableCallSite {
     private static final int CACHE_SIZE = SystemUtil.getIntegerSafe("groovy.indy.callsite.cache.size", 4);
     private static final float LOAD_FACTOR = 0.75f;
     private static final int INITIAL_CAPACITY = (int) Math.ceil(CACHE_SIZE / LOAD_FACTOR) + 1;
+    private final MethodHandles.Lookup lookup;
     private volatile SoftReference<MethodHandleWrapper> latestHitMethodHandleWrapperSoftReference = null;
     private final AtomicLong fallbackCount = new AtomicLong();
     private MethodHandle defaultTarget;
@@ -52,8 +54,9 @@ public class CacheableCallSite extends MutableCallSite {
                 }
             };
 
-    public CacheableCallSite(MethodType type) {
+    public CacheableCallSite(MethodType type, MethodHandles.Lookup lookup) {
         super(type);
+        this.lookup = lookup;
     }
 
     public MethodHandleWrapper getAndPut(String className, MemoizeCache.ValueProvider<? super String, ? extends MethodHandleWrapper> valueProvider) {
@@ -124,4 +127,8 @@ public class CacheableCallSite extends MutableCallSite {
     public void setFallbackTarget(MethodHandle fallbackTarget) {
         this.fallbackTarget = fallbackTarget;
     }
+
+    public MethodHandles.Lookup getLookup() {
+        return lookup;
+    }
 }
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
index 04a2d2d94a..b719d5e641 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyInterface.java
@@ -67,23 +67,28 @@ public class IndyInterface {
         /**
          * Method invocation type
          */
-        METHOD("invoke"),
+        METHOD("invoke", 0),
         /**
          * Constructor invocation type
          */
-        INIT("init"),
+        INIT("init", 1),
         /**
          * Get property invocation type
          */
-        GET("getProperty"),
+        GET("getProperty", 2),
         /**
          * Set property invocation type
          */
-        SET("setProperty"),
+        SET("setProperty", 3),
         /**
          * Cast invocation type
          */
-        CAST("cast");
+        CAST("cast", 4),
+
+        /**
+         * call to interface method
+         */
+        INTERFACE("interface", 5);
 
         private static final Map<String, CallType> NAME_CALLTYPE_MAP =
                 Stream.of(CallType.values()).collect(Collectors.toMap(CallType::getCallSiteName, Function.identity()));
@@ -92,8 +97,10 @@ public class IndyInterface {
          * The name of the call site type
          */
         private final String name;
+        private final int orderNumber;
 
-        CallType(String callSiteName) {
+        CallType(String callSiteName, int orderNumber) {
+            this.orderNumber = orderNumber;
             this.name = callSiteName;
         }
 
@@ -107,6 +114,10 @@ public class IndyInterface {
         public static CallType fromCallSiteName(String callSiteName) {
             return NAME_CALLTYPE_MAP.get(callSiteName);
         }
+
+        public int getOrderNumber() {
+            return this.orderNumber;
+        }
     }
 
     /**
@@ -153,14 +164,14 @@ public class IndyInterface {
     static {
 
         try {
-            MethodType mt = MethodType.methodType(Object.class, MutableCallSite.class, Class.class, String.class, int.class, Boolean.class, Boolean.class, Boolean.class, Object.class, Object[].class);
+            MethodType mt = MethodType.methodType(Object.class, CacheableCallSite.class, Class.class, String.class, int.class, Boolean.class, Boolean.class, Boolean.class, Object.class, Object[].class);
             FROM_CACHE_METHOD = LOOKUP.findStatic(IndyInterface.class, "fromCache", mt);
         } catch (Exception e) {
             throw new GroovyBugError(e);
         }
 
         try {
-            MethodType mt = MethodType.methodType(Object.class, MutableCallSite.class, Class.class, String.class, int.class, Boolean.class, Boolean.class, Boolean.class, Object.class, Object[].class);
+            MethodType mt = MethodType.methodType(Object.class, CacheableCallSite.class, Class.class, String.class, int.class, Boolean.class, Boolean.class, Boolean.class, Object.class, Object[].class);
             SELECT_METHOD = LOOKUP.findStatic(IndyInterface.class, "selectMethod", mt);
         } catch (Exception e) {
             throw new GroovyBugError(e);
@@ -208,7 +219,7 @@ public class IndyInterface {
         CallType ct = CallType.fromCallSiteName(callType);
         if (null == ct) throw new GroovyBugError("Unknown call type: " + callType);
 
-        int callID = ct.ordinal();
+        int callID = ct.getOrderNumber();
         boolean safe = (flags & SAFE_NAVIGATION) != 0;
         boolean thisCall = (flags & THIS_CALL) != 0;
         boolean spreadCall = (flags & SPREAD_CALL) != 0;
@@ -223,7 +234,7 @@ public class IndyInterface {
         // first produce a dummy call site, since indy doesn't give the runtime types;
         // the site then changes to the target when INDY_OPTIMIZE_THRESHOLD is reached
         // that does the method selection including the direct call to the real method
-        CacheableCallSite mc = new CacheableCallSite(type);
+        CacheableCallSite mc = new CacheableCallSite(type, caller);
         Class<?> sender = caller.lookupClass();
         if (thisCall) {
             while (GeneratedClosure.class.isAssignableFrom(sender)) {
@@ -258,7 +269,7 @@ public class IndyInterface {
     }
 
     private static class FallbackSupplier {
-        private final MutableCallSite callSite;
+        private final CacheableCallSite callSite;
         private final Class<?> sender;
         private final String methodName;
         private final int callID;
@@ -269,7 +280,7 @@ public class IndyInterface {
         private final Object[] arguments;
         private MethodHandleWrapper result;
 
-        FallbackSupplier(MutableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) {
+        FallbackSupplier(CacheableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) {
             this.callSite = callSite;
             this.sender = sender;
             this.methodName = methodName;
@@ -293,7 +304,7 @@ public class IndyInterface {
     /**
      * Get the cached methodhandle. if the related methodhandle is not found in the inline cache, cache and return it.
      */
-    public static Object fromCache(MutableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) throws Throwable {
+    public static Object fromCache(CacheableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) throws Throwable {
         FallbackSupplier fallbackSupplier = new FallbackSupplier(callSite, sender, methodName, callID, safeNavigation, thisCall, spreadCall, dummyReceiver, arguments);
 
         MethodHandleWrapper mhw =
@@ -334,7 +345,7 @@ public class IndyInterface {
     /**
      * Core method for indy method selection using runtime types.
      */
-    public static Object selectMethod(MutableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) throws Throwable {
+    public static Object selectMethod(CacheableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) throws Throwable {
         final MethodHandleWrapper mhw = fallback(callSite, sender, methodName, callID, safeNavigation, thisCall, spreadCall, dummyReceiver, arguments);
 
         if (callSite instanceof CacheableCallSite) {
@@ -359,7 +370,7 @@ public class IndyInterface {
         return mhw.getCachedMethodHandle().invokeExact(arguments);
     }
 
-    private static MethodHandleWrapper fallback(MutableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) {
+    private static MethodHandleWrapper fallback(CacheableCallSite callSite, Class<?> sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) {
         Selector selector = Selector.getSelector(callSite, sender, methodName, callID, safeNavigation, thisCall, spreadCall, arguments);
         selector.setCallSiteTarget();
 
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
index 7585f70c8d..b7cbbff9c8 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
@@ -18,7 +18,6 @@
  */
 package org.codehaus.groovy.vmplugin.v8;
 
-import groovy.lang.AdaptingMetaClass;
 import groovy.lang.Closure;
 import groovy.lang.ExpandoMetaClass;
 import groovy.lang.GroovyInterceptable;
@@ -57,7 +56,6 @@ import org.codehaus.groovy.vmplugin.VMPluginFactory;
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodType;
-import java.lang.invoke.MutableCallSite;
 import java.lang.reflect.Array;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Method;
@@ -108,7 +106,7 @@ public abstract class Selector {
     public String name;
     public MethodHandle handle;
     public boolean useMetaClass = false, cache = true;
-    public MutableCallSite callSite;
+    public CacheableCallSite callSite;
     public Class<?> sender;
     public boolean isVargs;
     public boolean safeNavigation, safeNavigationOrig, spread;
@@ -126,7 +124,7 @@ public abstract class Selector {
     /**
      * Returns the Selector
      */
-    public static Selector getSelector(MutableCallSite callSite, Class<?> sender, String methodName, int callID, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) {
+    public static Selector getSelector(CacheableCallSite callSite, Class<?> sender, String methodName, int callID, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) {
         CallType callType = CALL_TYPE_VALUES[callID];
         switch (callType) {
             case INIT:
@@ -139,6 +137,8 @@ public abstract class Selector {
                 throw new GroovyBugError("your call tried to do a property set, which is not supported.");
             case CAST:
                 return new CastSelector(callSite, arguments);
+            case INTERFACE:
+                return new InterfaceSelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments);
             default:
                 throw new GroovyBugError("unexpected call type");
         }
@@ -165,7 +165,7 @@ public abstract class Selector {
     private static class CastSelector extends MethodSelector {
         private final Class<?> staticSourceType, staticTargetType;
 
-        public CastSelector(MutableCallSite callSite, Object[] arguments) {
+        public CastSelector(CacheableCallSite callSite, Object[] arguments) {
             super(callSite, Selector.class, "", CallType.CAST, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, arguments);
             this.staticSourceType = callSite.type().parameterType(0);
             this.staticTargetType = callSite.type().returnType();
@@ -284,7 +284,7 @@ public abstract class Selector {
     private static class PropertySelector extends MethodSelector {
         private boolean insertName;
 
-        public PropertySelector(MutableCallSite callSite, Class<?> sender, String methodName, CallType callType, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) {
+        public PropertySelector(CacheableCallSite callSite, Class<?> sender, String methodName, CallType callType, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) {
             super(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments);
         }
 
@@ -384,7 +384,7 @@ public abstract class Selector {
         private static final MethodType MT_OBJECT = MethodType.methodType(Object.class);
         private boolean beanConstructor;
 
-        public InitSelector(MutableCallSite callSite, Class<?> sender, String methodName, CallType callType, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) {
+        public InitSelector(CacheableCallSite callSite, Class<?> sender, String methodName, CallType callType, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) {
             super(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments);
         }
 
@@ -434,7 +434,7 @@ public abstract class Selector {
                 if (LOG_ENABLED) LOG.info("meta method is MetaConstructor instance");
                 MetaConstructor mc = (MetaConstructor) method;
                 isVargs = mc.isVargsMethod();
-                Constructor con = mc.getCachedConstrcutor().getCachedConstructor();
+                Constructor<?> con = mc.getCachedConstrcutor().getCachedConstructor();
                 try {
                     handle = LOOKUP.unreflectConstructor(con);
                     if (LOG_ENABLED) LOG.info("successfully unreflected constructor");
@@ -466,7 +466,7 @@ public abstract class Selector {
 
         /**
          * In case of a bean constructor we don't do any varags or implicit null argument
-         * transformations. Otherwise we do the same as for {@link MethodSelector#correctParameterLength()}
+         * transformations. Otherwise, we do the same as for {@link MethodSelector#correctParameterLength()}
          */
         @Override
         public void correctParameterLength() {
@@ -499,6 +499,31 @@ public abstract class Selector {
         }
     }
 
+    private static class InterfaceSelector extends MethodSelector {
+        public InterfaceSelector(CacheableCallSite callSite, Class<?> sender, String methodName, CallType callType, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) {
+            super(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments);
+        }
+
+        @Override
+        public MetaClass getMetaClass() {
+            mc = GroovySystem.getMetaClassRegistry().getMetaClass(targetType.parameterType(0));
+            mc.initialize();
+            if (LOG_ENABLED) LOG.info("meta class is " + mc);
+            return mc;
+        }
+
+        @Override
+        public void setSelectionBase() {
+            selectionBase = mc.getTheClass();
+            if (LOG_ENABLED) LOG.info("selectionBase set to " + selectionBase);
+        }
+
+        @Override
+        public MethodHandle unreflect(Method cachedMethod) throws IllegalAccessException {
+            return this.callSite.getLookup().unreflectSpecial(cachedMethod, this.sender); // throws if sender cannot invoke method
+        }
+    }
+
     /**
      * Method invocation based {@link Selector}.
      * This Selector is called for method invocations and is base for constructor
@@ -509,7 +534,7 @@ public abstract class Selector {
         private boolean isCategoryMethod;
         protected MetaClass mc;
 
-        public MethodSelector(MutableCallSite callSite, Class<?> sender, String methodName, CallType callType, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object[] arguments) {
+        public MethodSelector(CacheableCallSite callSite, Class<?> sender, String methodName, CallType callType, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object[] arguments) {
             this.callType = callType;
             this.targetType = callSite.type();
             this.name = methodName;
@@ -654,8 +679,7 @@ public abstract class Selector {
                     } else if (parameterCount == 1 && name.equals("forName") && declaringClass == Class.class) {
                         handle = MethodHandles.insertArguments(CLASS_FOR_NAME, 1, Boolean.TRUE, sender.getClassLoader());
                     } else {
-                        MethodHandles.Lookup lookup = cm.isPublic() ? LOOKUP : ((Java8)vmplugin).newLookup(sender); // GROOVY-10070, et al.
-                        handle = lookup.unreflect(cm.getCachedMethod()); // throws if sender cannot invoke method
+                        handle = unreflect(cm.getCachedMethod());
                     }
                 } catch (ReflectiveOperationException e) {
                     throw new GroovyBugError(e);
@@ -686,6 +710,10 @@ public abstract class Selector {
             }
         }
 
+        protected MethodHandle unreflect(Method cachedMethod) throws IllegalAccessException {
+            return this.callSite.getLookup().unreflect(cachedMethod); // throws if sender cannot invoke method
+        }
+
         /**
          * Helper method to manipulate the given type to replace Wrapper with Object.
          */
@@ -834,10 +862,10 @@ public abstract class Selector {
 
                 // equal in terms of an assignment in Java. That means according to Java widening rules, or
                 // a subclass, interface, superclass relation, this case then handles also
-                // primitive to primitive conversion. Those case are also solved by explicitCastArguments.
+                // primitive to primitive conversion. Those cases are also solved by explicitCastArguments.
                 if (parameterType.isAssignableFrom(got)) continue;
 
-                // to aid explicitCastArguments we convert to the wrapper type to let is only unbox
+                // to aid explicitCastArguments we convert to the wrapper type to let it only unbox
                 handle = TypeTransformers.addTransformer(handle, i, arg, wrappedPara);
                 if (LOG_ENABLED)
                     LOG.info("added transformer at pos " + i + " for type " + got + " to type " + wrappedPara);
@@ -885,12 +913,7 @@ public abstract class Selector {
             if (handle == null) return;
             if (!cache) return;
 
-            MethodHandle fallback;
-            if (callSite instanceof CacheableCallSite) {
-                fallback = ((CacheableCallSite) callSite).getFallbackTarget();
-            } else {
-                throw new GroovyBugError("CacheableCallSite is expected, but the actual callsite is: " + callSite);
-            }
+            MethodHandle fallback = callSite.getFallbackTarget();
 
             // special guards for receiver
             if (receiver instanceof GroovyObject) {
@@ -970,14 +993,6 @@ public abstract class Selector {
          */
         public void doCallSiteTargetSet() {
             if (LOG_ENABLED) LOG.info("call site stays uncached");
-            /*
-            if (!cache) {
-                if (LOG_ENABLED) LOG.info("call site stays uncached");
-            } else {
-                callSite.setTarget(handle);
-                if (LOG_ENABLED) LOG.info("call site target set, preparing outside invocation");
-            }
-            */
         }
 
         /**
@@ -1049,11 +1064,10 @@ public abstract class Selector {
     private static MetaClassImpl getMetaClassImpl(final MetaClass mc, final boolean includeEMC) {
         Class<?> mcc = mc.getClass();
         boolean valid = mcc == MetaClassImpl.class
-                || mcc == AdaptingMetaClass.class
                 || mcc == ClosureMetaClass.class
                 || (includeEMC && mcc == ExpandoMetaClass.class);
         if (!valid) {
-            if (LOG_ENABLED) LOG.info("meta class is neither MetaClassImpl, nor AdoptingMetaClass, nor ClosureMetaClass, normal method selection path disabled.");
+            if (LOG_ENABLED) LOG.info("meta class is neither MetaClassImpl, nor ClosureMetaClass, normal method selection path disabled.");
             return null;
         }
         if (LOG_ENABLED) LOG.info("meta class is a recognized MetaClassImpl");


[groovy] 01/07: GROOVY-8299: implement interfaces with default methods (initial commit)

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 44d286e67ed2087238c304c75463fd897f039a63
Author: Jochen Theodorou <bl...@gmx.org>
AuthorDate: Mon Sep 11 14:38:30 2023 +0200

    GROOVY-8299: implement interfaces with default methods (initial commit)
---
 .../apache/groovy/parser/antlr4/AstBuilder.java    | 10 +---
 .../groovy/classgen/ClassCompletionVerifier.java   |  2 +-
 .../groovy/lang/DefaultInterfaceMethodsTest.groovy | 54 ++++++++++++++++++++++
 3 files changed, 57 insertions(+), 9 deletions(-)

diff --git a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
index b5ba5258b9..733584e79f 100644
--- a/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
+++ b/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
@@ -1313,9 +1313,7 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
         } else if (isNonSealed) {
             classNode.addAnnotation(makeAnnotationNode(NonSealed.class));
         }
-        if (isInterfaceWithDefaultMethods || asBoolean(ctx.TRAIT())) {
-            classNode.addAnnotation(makeAnnotationNode(Trait.class));
-        }
+
         classNode.addAnnotations(modifierManager.getAnnotations());
         if (isRecord && classNode.getAnnotations().stream().noneMatch(a ->
                         a.getClassNode().getName().equals(RECORD_TYPE_NAME))) {
@@ -1338,10 +1336,6 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
             classNode.setInterfaces(this.visitTypeList(ctx.is));
             this.initUsingGenerics(classNode);
 
-        } else if (isInterfaceWithDefaultMethods) { // GROOVY-9259
-            classNode.setInterfaces(this.visitTypeList(ctx.scs));
-            this.initUsingGenerics(classNode);
-
         } else if (isInterface) {
             classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT);
             classNode.setInterfaces(this.visitTypeList(ctx.scs));
@@ -1877,7 +1871,7 @@ public class AstBuilder extends GroovyParserBaseVisitor<Object> {
 
         }
 
-        modifiers |= !modifierManager.containsAny(STATIC) && (classNode.isInterface() || (isTrue(classNode, IS_INTERFACE_WITH_DEFAULT_METHODS) && !modifierManager.containsAny(DEFAULT))) ? Opcodes.ACC_ABSTRACT : 0;
+        modifiers |= !modifierManager.containsAny(STATIC) && classNode.isInterface() && !(isTrue(classNode, IS_INTERFACE_WITH_DEFAULT_METHODS) && modifierManager.containsAny(DEFAULT)) ? Opcodes.ACC_ABSTRACT : 0;
         MethodNode methodNode = new MethodNode(methodName, modifiers, returnType, parameters, exceptions, code);
         classNode.addMethod(methodNode);
 
diff --git a/src/main/java/org/codehaus/groovy/classgen/ClassCompletionVerifier.java b/src/main/java/org/codehaus/groovy/classgen/ClassCompletionVerifier.java
index 8ff9c1ef00..43abd86f23 100644
--- a/src/main/java/org/codehaus/groovy/classgen/ClassCompletionVerifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/ClassCompletionVerifier.java
@@ -310,7 +310,7 @@ public class ClassCompletionVerifier extends ClassCodeVisitorSupport {
     }
 
     private void checkAbstractDeclaration(final MethodNode methodNode) {
-        if (!methodNode.isAbstract() || currentClass.isAbstract()) return;
+        if (!methodNode.isAbstract() || currentClass.isAbstract() || methodNode.isDefault()) return;
 
         addError("Can't have an abstract method in a non-abstract class." +
                 " The " + getDescription(currentClass) + " must be declared abstract or the method '" +
diff --git a/src/test/groovy/lang/DefaultInterfaceMethodsTest.groovy b/src/test/groovy/lang/DefaultInterfaceMethodsTest.groovy
new file mode 100644
index 0000000000..bc833b8069
--- /dev/null
+++ b/src/test/groovy/lang/DefaultInterfaceMethodsTest.groovy
@@ -0,0 +1,54 @@
+/*
+ *  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.lang
+
+import groovy.test.GroovyTestCase
+
+/**
+ * Test for the BenchmarkInterceptor
+ */
+class DefaultInterfaceMethodsTest extends GroovyTestCase {
+
+    void testSimpleDeclarationAndCall() {
+        assertScript '''
+            public interface InterfaceWithDefault {
+                default String hello() {
+                    return 'Hello'
+                }
+            }
+            class UseDefault implements InterfaceWithDefault {}
+            assert new UseDefault().hello() == 'Hello'
+        '''
+    }
+    void testSimpleDeclarationAndOverride() {
+        assertScript '''
+            public interface InterfaceWithDefault {
+                default String hello() {
+                    return 'Hello'
+                }
+            }
+            class OverrideDefault implements InterfaceWithDefault {
+                public String hello() {
+                    return 'Bon jour'
+                }
+            }
+            assert new OverrideDefault().hello() == 'Bon jour'
+        '''
+    }
+}


[groovy] 03/07: GROOVY-9801: add default methods to stub generation

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 3f06e156473edba8a243270033c3bceb2aa24250
Author: Jochen Theodorou <bl...@gmx.org>
AuthorDate: Mon Sep 11 16:00:51 2023 +0200

    GROOVY-9801: add default methods to stub generation
---
 src/main/java/org/codehaus/groovy/tools/javac/JavaStubGenerator.java | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/src/main/java/org/codehaus/groovy/tools/javac/JavaStubGenerator.java b/src/main/java/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
index 2bd8fd4126..d8253c2f96 100644
--- a/src/main/java/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
+++ b/src/main/java/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
@@ -729,6 +729,9 @@ public class JavaStubGenerator {
             printModifiers(out, flags);
         }
 
+        if (methodNode.isDefault()) {
+            out.print("default ");
+        }
         printTypeParameters(out, methodNode.getGenericsTypes());
         out.print(" ");
         printType(out, methodNode.getReturnType());


[groovy] 07/07: GROOVY-8299: typechecking needs to use receiver to decide on target method being valid

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit a3d7c7989d500bb086a5116b3e118e3b619c3112
Author: Jochen Theodorou <bl...@gmx.org>
AuthorDate: Sun Oct 1 16:46:25 2023 +0200

    GROOVY-8299: typechecking needs to use receiver to decide on target method being valid
---
 .../codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java    | 4 ++--
 src/test/groovy/transform/stc/BugsSTCTest.groovy                    | 6 +++---
 2 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
index f702ae6a15..01ff32bc29 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -3670,9 +3670,9 @@ out:                if (mn.size() != 1) {
                         if (!targetMethod.isStatic() && !(isClassType(declaringClass) || isObjectType(declaringClass)) // GROOVY-10939: Class or Object
                                 && isClassType(receiver) && chosenReceiver.getData() == null && !Boolean.TRUE.equals(call.getNodeMetaData(DYNAMIC_RESOLUTION))) {
                             addStaticTypeError("Non-static method " + prettyPrintTypeName(declaringClass) + "#" + targetMethod.getName() + " cannot be called from static context", call);
-                        } else if (targetMethod.isAbstract() && isSuperExpression(objectExpression)) { // GROOVY-10341
+                        } else if ((chosenReceiver.getType().isInterface() || targetMethod.isAbstract()) && isSuperExpression(objectExpression)) { // GROOVY-10341, GROOVY-8299
                             String target = toMethodParametersString(targetMethod.getName(), extractTypesFromParameters(targetMethod.getParameters()));
-                            if (Traits.hasDefaultImplementation(targetMethod)) { // GROOVY-10494
+                            if (Traits.hasDefaultImplementation(targetMethod) || targetMethod.isDefault()) { // GROOVY-10494
                                 addStaticTypeError("Default method " + target + " requires qualified super", call);
                             } else {
                                 addStaticTypeError("Abstract method " + target + " cannot be called directly", call);
diff --git a/src/test/groovy/transform/stc/BugsSTCTest.groovy b/src/test/groovy/transform/stc/BugsSTCTest.groovy
index 9c50a07d80..137092e46c 100644
--- a/src/test/groovy/transform/stc/BugsSTCTest.groovy
+++ b/src/test/groovy/transform/stc/BugsSTCTest.groovy
@@ -1154,9 +1154,9 @@ class BugsSTCTest extends StaticTypeCheckingTestCase {
         '''
     }
 
-    // GROOVY-9909
+    // GROOVY-9909 tests changed for GROOVY-8299
     void testInvokeDefaultMethodFromDirectInterface() {
-        assertScript '''
+        shouldFailWithMessages('''
             class C implements groovy.transform.stc.Groovy9909 {
                 @Override String m() {
                     'it ' + super.m() // default method
@@ -1164,7 +1164,7 @@ class BugsSTCTest extends StaticTypeCheckingTestCase {
             }
             String result = new C().m()
             assert result == 'it works'
-        '''
+        ''',  "Default method m() requires qualified super")
     }
 
     // GROOVY-8339, GROOVY-10109, GROOVY-10594


[groovy] 04/07: GROOVY-8299: allow I.super for default methods

Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit c8d032535613fc5a3dc1145ea0a87acc6df3d225
Author: Jochen Theodorou <bl...@gmx.org>
AuthorDate: Mon Sep 11 16:45:58 2023 +0200

    GROOVY-8299: allow I.super for default methods
---
 src/main/java/org/codehaus/groovy/control/ResolveVisitor.java | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java b/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
index 8031113512..58c9a56c29 100644
--- a/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
+++ b/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
@@ -967,7 +967,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
         if (!prop.equals("this") && !prop.equals("super")) return;
 
         ClassNode type = expression.getObjectExpression().getType();
-        if (expression.getObjectExpression() instanceof ClassExpression) {
+        if (expression.getObjectExpression() instanceof ClassExpression && !isSuperCallToDefaultMethod(expression)) {
             if (!(currentClass instanceof InnerClassNode) && !Traits.isTrait(type)) {
                 addError("The usage of 'Class.this' and 'Class.super' is only allowed in nested/inner classes.", expression);
                 return;
@@ -991,6 +991,12 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
         }
     }
 
+    private boolean isSuperCallToDefaultMethod(PropertyExpression expression) {
+        // a more sophisticated check might be required in the future
+        ClassExpression clazzExpression = (ClassExpression) expression.getObjectExpression();
+        return clazzExpression.getType().isInterface() && expression.getPropertyAsString().equals("super");
+    }
+
     protected Expression transformVariableExpression(final VariableExpression ve) {
         visitAnnotations(ve);
         Variable v = ve.getAccessedVariable();