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 2022/12/02 17:36:45 UTC
[groovy] branch GROOVY_4_0_X updated: GROOVY-10858: STC: method pointer/reference selection and reporting
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 d42fa1e4e0 GROOVY-10858: STC: method pointer/reference selection and reporting
d42fa1e4e0 is described below
commit d42fa1e4e0b12ab78fba3404e0a005537d9d4e1b
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Fri Dec 2 11:13:20 2022 -0600
GROOVY-10858: STC: method pointer/reference selection and reporting
---
...StaticTypesMethodReferenceExpressionWriter.java | 11 ++++-
.../transform/stc/StaticTypeCheckingVisitor.java | 53 +++++++++++++++++-----
.../transform/stc/MethodReferenceTest.groovy | 17 +++++--
3 files changed, 64 insertions(+), 17 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 a962f91ea1..3f1eb99bd5 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
@@ -189,8 +189,15 @@ public class StaticTypesMethodReferenceExpressionWriter extends MethodReferenceE
private void validate(final MethodReferenceExpression methodReference, final ClassNode targetType, final String methodName, final MethodNode methodNode, final Parameter[] samParameters, final ClassNode samReturnType) {
if (methodNode == null) {
- String error = String.format("Failed to find the expected method[%s(%s)] in the type[%s]",
- methodName, Arrays.stream(samParameters).map(e -> e.getType().getText()).collect(joining(",")), targetType.getText());
+ String error;
+ if (!(methodReference.getExpression() instanceof ClassExpression)) {
+ error = "Failed to find method '%s(%s)'";
+ } else {
+ error = "Failed to find class method '%s(%s)'";
+ if (samParameters.length > 0)
+ error += " or instance method '%1$s(" + Arrays.stream(samParameters).skip(1).map(e -> e.getType().toString(false)).collect(joining(",")) + ")'";
+ }
+ error = String.format(error + " for the type: %s", methodName, Arrays.stream(samParameters).map(e -> e.getType().toString(false)).collect(joining(",")), targetType.toString(false));
addFatalError(error, methodReference);
} else if (methodNode.isVoidMethod() && !ClassHelper.isPrimitiveVoid(samReturnType)) {
addFatalError("Invalid return type: void is not convertible to " + samReturnType.getText(), methodReference);
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 80f247880d..aba5dcb505 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -1765,11 +1765,18 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
} else if (member instanceof PropertyNode) {
isStatic = ((PropertyNode) member).isStatic();
} else { // assume member instanceof MethodNode
- isStatic = member instanceof ExtensionMethodNode ? ((ExtensionMethodNode) member).isStaticExtension() : ((MethodNode) member).isStatic();
+ isStatic = isStaticInContext((MethodNode) member);
}
return (isStatic ? member : null);
}
+ /**
+ * Is the method called in a static or non-static manner?
+ */
+ private boolean isStaticInContext(final MethodNode method) {
+ return method instanceof ExtensionMethodNode ? ((ExtensionMethodNode) method).isStaticExtension() : method.isStatic();
+ }
+
private boolean storeField(final FieldNode field, final PropertyExpression expressionToStoreOn, final ClassNode receiver, final ClassCodeVisitorSupport visitor, final String delegationData, final boolean lhsOfAssignment) {
if (visitor != null) visitor.visitField(field);
checkOrMarkPrivateAccess(expressionToStoreOn, field, lhsOfAssignment);
@@ -2396,12 +2403,14 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
candidates = findMethodsWithGenerated(receiverType, nameText);
// GROOVY-10741: check for reference to a property node's method
MethodNode generated = findPropertyMethod(receiverType, nameText);
- if (generated != null && candidates.stream().noneMatch(mn -> mn.getName().equals(generated.getName()))){
+ if (generated != null && candidates.stream().noneMatch(m -> m.getName().equals(generated.getName()))) {
candidates.add(generated);
}
candidates.addAll(findDGMMethodsForClassNode(getSourceUnit().getClassLoader(), receiverType, nameText));
- candidates = filterMethodsByVisibility(candidates, typeCheckingContext.getEnclosingClassNode());
+ if (candidates.size() > 1) {
+ candidates = filterMethodCandidates(candidates, expression.getExpression(), expression.getNodeMetaData(CLOSURE_ARGUMENTS));
+ }
if (!candidates.isEmpty()) {
break;
}
@@ -2453,6 +2462,28 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
return null;
}
+ private List<MethodNode> filterMethodCandidates(final List<MethodNode> candidates, final Expression objectOrType, /*@Nullable*/ ClassNode[] signature) {
+ List<MethodNode> result = filterMethodsByVisibility(candidates, typeCheckingContext.getEnclosingClassNode());
+ // assignment or parameter target type may help reduce the list
+ if (result.size() > 1 && signature != null) {
+ ClassNode type = getType(objectOrType);
+ if (!isClassClassNodeWrappingConcreteType(type)) {
+ result = chooseBestMethod(type, result, signature);
+ } else {
+ type = type.getGenericsTypes()[0].getType(); // Class<Type> --> Type
+ Map<Boolean, List<MethodNode>> staticAndNonStatic = result.stream().collect(Collectors.partitioningBy(this::isStaticInContext));
+
+ result = new ArrayList<>(result.size());
+ result.addAll(chooseBestMethod(type, staticAndNonStatic.get(Boolean.TRUE), signature));
+ if (!staticAndNonStatic.get(Boolean.FALSE).isEmpty()) {
+ if (signature.length > 0) signature= Arrays.copyOfRange(signature, 1, signature.length);
+ result.addAll(chooseBestMethod(type, staticAndNonStatic.get(Boolean.FALSE), signature));
+ }
+ }
+ }
+ return result;
+ }
+
protected DelegationMetadata getDelegationMetadata(final ClosureExpression expression) {
return expression.getNodeMetaData(DELEGATION_METADATA);
}
@@ -3632,8 +3663,7 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
if (isClassClassNodeWrappingConcreteType(sourceExprType) && !"new".equals(methodReference.getMethodName().getText())) {
// GROOVY-10734: Type::instanceMethod has implied first param
List<MethodNode> candidates = methodReference.getNodeMetaData(MethodNode.class);
- if (candidates != null && !candidates.isEmpty() && candidates.stream().allMatch(mn ->
- !(mn instanceof ExtensionMethodNode ? ((ExtensionMethodNode) mn).isStaticExtension() : mn.isStatic()))) {
+ if (candidates != null && !candidates.isEmpty() && candidates.stream().allMatch(mn -> !isStaticInContext(mn))) {
firstParamType = sourceExprType.getGenericsTypes()[0].getType();
}
}
@@ -4062,6 +4092,12 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
});
}
+ protected Map<VariableExpression, List<ClassNode>> pushAssignmentTracking() {
+ Map<VariableExpression, List<ClassNode>> oldTracker = typeCheckingContext.ifElseForWhileAssignmentTracker;
+ typeCheckingContext.ifElseForWhileAssignmentTracker = new HashMap<>();
+ return oldTracker;
+ }
+
protected Map<VariableExpression, ClassNode> popAssignmentTracking(final Map<VariableExpression, List<ClassNode>> oldTracker) {
Map<VariableExpression, ClassNode> assignments = new HashMap<>();
typeCheckingContext.ifElseForWhileAssignmentTracker.forEach((var, types) -> {
@@ -4075,13 +4111,6 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
return assignments;
}
- protected Map<VariableExpression, List<ClassNode>> pushAssignmentTracking() {
- // memorize current assignment context
- Map<VariableExpression, List<ClassNode>> oldTracker = typeCheckingContext.ifElseForWhileAssignmentTracker;
- typeCheckingContext.ifElseForWhileAssignmentTracker = new HashMap<>();
- return oldTracker;
- }
-
@Override
public void visitArrayExpression(final ArrayExpression expression) {
super.visitArrayExpression(expression);
diff --git a/src/test/groovy/transform/stc/MethodReferenceTest.groovy b/src/test/groovy/transform/stc/MethodReferenceTest.groovy
index 04a8c773f9..d1df6053b7 100644
--- a/src/test/groovy/transform/stc/MethodReferenceTest.groovy
+++ b/src/test/groovy/transform/stc/MethodReferenceTest.groovy
@@ -232,7 +232,7 @@ final class MethodReferenceTest {
@CompileStatic
Map test(Collection<C> items) {
items.stream().collect(
- Collectors.groupingBy(C::getP) // Failed to find the expected method[getP(Object)] in the type[C]
+ Collectors.groupingBy(C::getP)
)
}
@@ -896,7 +896,7 @@ final class MethodReferenceTest {
[1.0G, 2.0G, 3.0G].stream().reduce(0.0G, BigDecimal::addx)
}
'''
- assert err.message.contains('Failed to find the expected method[addx(java.math.BigDecimal,java.math.BigDecimal)] in the type[java.math.BigDecimal]')
+ assert err.message.contains("Failed to find class method 'addx(java.math.BigDecimal,java.math.BigDecimal)' or instance method 'addx(java.math.BigDecimal)' for the type: java.math.BigDecimal")
}
@Test // GROOVY-9463
@@ -907,7 +907,7 @@ final class MethodReferenceTest {
Function<String,String> reference = String::toLowerCaseX
}
'''
- assert err.message.contains('Failed to find the expected method[toLowerCaseX(java.lang.String)] in the type[java.lang.String]')
+ assert err.message.contains("Failed to find class method 'toLowerCaseX(java.lang.String)' or instance method 'toLowerCaseX()' for the type: java.lang.String")
}
@Test // GROOVY-10714
@@ -987,6 +987,17 @@ final class MethodReferenceTest {
'''
}
+ @Test // GROOVY-10813, GROOVY-10858
+ void testMethodSelection3() {
+ def err = shouldFail shell, '''
+ @CompileStatic
+ void test() {
+ Supplier<String> s = Object::toString // all options require an object
+ }
+ '''
+ assert err.message.contains("Failed to find class method 'toString()' for the type: java.lang.Object")
+ }
+
@Test // GROOVY-10742
void testIncompatibleReturnType() {
def err = shouldFail shell, '''