You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2023/04/19 15:52:23 UTC

[groovy] branch GROOVY_4_0_X updated: GROOVY-10972: SC: select from closest matches for method reference

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

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


The following commit(s) were added to refs/heads/GROOVY_4_0_X by this push:
     new e3853b368f GROOVY-10972: SC: select from closest matches for method reference
e3853b368f is described below

commit e3853b368fda4068ee76f3f5bf6f58a31d312714
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Wed Apr 19 10:10:40 2023 -0500

    GROOVY-10972: SC: select from closest matches for method reference
---
 ...StaticTypesMethodReferenceExpressionWriter.java | 27 +++++++----
 .../transform/stc/MethodReferenceTest.groovy       | 53 ++++++++++++++--------
 2 files changed, 53 insertions(+), 27 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java
index d00748c774..62f2d9c544 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java
@@ -43,6 +43,7 @@ import org.objectweb.asm.Handle;
 import org.objectweb.asm.Opcodes;
 
 import java.util.Arrays;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 
@@ -59,6 +60,7 @@ import static org.codehaus.groovy.ast.tools.GenericsUtils.extractPlaceholders;
 import static org.codehaus.groovy.ast.tools.ParameterUtils.isVargs;
 import static org.codehaus.groovy.ast.tools.ParameterUtils.parametersCompatible;
 import static org.codehaus.groovy.runtime.DefaultGroovyMethods.last;
+import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.allParametersAndArgumentsMatch;
 import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.filterMethodsByVisibility;
 import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.findDGMMethodsForClassNode;
 import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isAssignableTo;
@@ -318,7 +320,11 @@ public class StaticTypesMethodReferenceExpressionWriter extends MethodReferenceE
     private MethodNode findMethodRefMethod(final String methodName, final Parameter[] samParameters, final Expression typeOrTargetRef, final ClassNode typeOrTargetRefType) {
         List<MethodNode> methods = findVisibleMethods(methodName, typeOrTargetRefType);
 
-        methods.removeIf(method -> {
+        java.util.function.ToIntFunction<Parameter[]> distance = (parameters) -> { // GROOVY-10972: select from closest matches
+            return allParametersAndArgumentsMatch(parameters, Arrays.stream(samParameters).map(Parameter::getType).toArray(ClassNode[]::new));
+        };
+
+        int[] distances = methods.stream().mapToInt(method -> {
             Parameter[] parameters = method.getParameters();
             if (isTypeReferringInstanceMethod(typeOrTargetRef, method)) {
                 // there is an implicit parameter for "String::length"
@@ -339,14 +345,14 @@ public class StaticTypesMethodReferenceExpressionWriter extends MethodReferenceE
             }
 
             // check direct match
-            if (parametersCompatible(samParameters, parameters)) return false;
+            if (parametersCompatible(samParameters, parameters)) return distance.applyAsInt(parameters);
 
             // check vararg match
             if (isVargs(parameters)) {
                 int nParameters = parameters.length;
                 if (samParameters.length == nParameters - 1) { // 0 case
                     parameters = Arrays.copyOf(parameters, nParameters - 1);
-                    if (parametersCompatible(samParameters, parameters)) return false;
+                    if (parametersCompatible(samParameters, parameters)) return distance.applyAsInt(parameters);
                 }
                 else if (samParameters.length >= nParameters) { // 1+ case
                     Parameter p = new Parameter(parameters[nParameters - 1].getType().getComponentType(), "");
@@ -354,19 +360,24 @@ public class StaticTypesMethodReferenceExpressionWriter extends MethodReferenceE
                     for (int i = nParameters - 1; i < parameters.length; i += 1){
                         parameters[i] = p;
                     }
-                    if (parametersCompatible(samParameters, parameters)) return false;
+                    if (parametersCompatible(samParameters, parameters)) return distance.applyAsInt(parameters);
                 }
             }
 
-            return true; // no match; remove method
-        });
+            return -1; // no match
+        }).toArray();
+
+        int i = 0, bestDistance = Arrays.stream(distances).filter(d -> d >= 0).min().orElse(0);
+        for (Iterator<MethodNode> it = methods.iterator(); it.hasNext(); ) {
+            it.next(); if (distances[i++] != bestDistance) it.remove();
+        }
 
+        if (methods.isEmpty()) return null;
+        if (methods.size() == 1) return methods.get(0);
         return chooseMethodRefMethod(methods, typeOrTargetRef, typeOrTargetRefType);
     }
 
     private MethodNode chooseMethodRefMethod(final List<MethodNode> methods, final Expression typeOrTargetRef, final ClassNode typeOrTargetRefType) {
-        if (methods.isEmpty()) return null;
-        if (methods.size() == 1) return methods.get(0);
         return methods.stream().max(comparingInt((MethodNode mn) -> {
             int score = 9;
             for (ClassNode cn = typeOrTargetRefType; cn != null && !cn.equals(mn.getDeclaringClass()); cn = cn.getSuperClass()) {
diff --git a/src/test/groovy/transform/stc/MethodReferenceTest.groovy b/src/test/groovy/transform/stc/MethodReferenceTest.groovy
index cbb14e0f64..8981dfebc0 100644
--- a/src/test/groovy/transform/stc/MethodReferenceTest.groovy
+++ b/src/test/groovy/transform/stc/MethodReferenceTest.groovy
@@ -238,25 +238,6 @@ final class MethodReferenceTest {
         '''
     }
 
-    @Test // class::instanceMethod -- GROOVY-11009
-    void testFunctionCI9() {
-        assertScript shell, '''
-            class C {
-                static <T> T clone(T t) { t }
-                // see also Object#clone()
-            }
-
-            @CompileStatic
-            Double test() {
-                Function<Double,Double> fn = C::clone
-                fn.apply(1.234d)
-            }
-
-            def n = test()
-            assert n == 1.234
-        '''
-    }
-
     @Test // class::instanceMethod -- GROOVY-9974
     void testPredicateCI() {
         assertScript shell, '''
@@ -406,6 +387,21 @@ final class MethodReferenceTest {
         '''
     }
 
+    @Test // instance::instanceMethod -- GROOVY-10972
+    void testFunctionII4() {
+        assertScript shell, '''
+            @CompileStatic
+            void test() {
+                LinkedList<String> list = new LinkedList<>()
+                list.add('works')
+                Function<Integer,String> func = list::remove
+                assert func.apply(0) == 'works'
+            }
+
+            test()
+        '''
+    }
+
     @Test // instance::instanceMethod -- GROOVY-10057
     void testPredicateII() {
         assertScript shell, '''
@@ -897,6 +893,25 @@ final class MethodReferenceTest {
         '''
     }
 
+    @Test // class::staticMethod -- GROOVY-11009
+    void testFunctionCS9() {
+        assertScript shell, '''
+            class C {
+                static <T> T clone(T t) { t }
+                // see also Object#clone()
+            }
+
+            @CompileStatic
+            Double test() {
+                Function<Double,Double> fn = C::clone
+                fn.apply(1.234d)
+            }
+
+            def n = test()
+            assert n == 1.234
+        '''
+    }
+
     @Test // class::instanceGroovyMethod
     void testFunctionCI_DGM() {
         assertScript shell, '''