daniellansun commented on code in PR #3293:
URL: https://github.com/apache/groovy/pull/3293#discussion_r4578891992


##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -2250,16 +2264,258 @@ private void checkTypeGenerics(final ClassNode 
leftExpressionType, final ClassNo
             return;
         }
         ClassNode right = wrapTypeIfNecessary(rightExpressionType);
+        if (hasIncompatibleGenerics(leftExpressionType, right)) {
+            if (isTypedByTarget(leftExpressionType, right, rightExpression)) {
+                rightExpression.setNodeMetaData(TARGET_TYPED, 
leftExpressionType); // the expression has the type of its target
+            } else {
+                addStaticTypeError("Incompatible generic argument types. 
Cannot assign " + prettyPrintType(rightExpressionType) + " to: " + 
prettyPrintType(leftExpressionType), rightExpression);
+            }
+        }
+    }
+
+    private static boolean hasIncompatibleGenerics(final ClassNode targetType, 
final ClassNode type) {
         // A type variable is not "missing" generics: its bound is known.
         // Raw types and uninferred diamonds still skip the check.
-        boolean unresolved = missesGenericsTypes(right);
+        boolean unresolved = missesGenericsTypes(type);
         boolean incompatible = !unresolved && (
-                
!GenericsUtils.buildWildcardType(leftExpressionType).isCompatibleWith(right)
-                || concreteArgumentContainsWildcard(leftExpressionType, 
right));
-        boolean typeVariableEscapes = unresolved && 
(typeVariableBoundEscapes(leftExpressionType, right)
-                || concreteArgumentContainsWildcard(leftExpressionType, 
right));
-        if (incompatible || typeVariableEscapes) {
-            addStaticTypeError("Incompatible generic argument types. Cannot 
assign " + prettyPrintType(rightExpressionType) + " to: " + 
prettyPrintType(leftExpressionType), rightExpression);
+                
!GenericsUtils.buildWildcardType(targetType).isCompatibleWith(type)
+                || concreteArgumentContainsWildcard(targetType, type)
+                || typeVariableArgumentGetsWildcard(targetType, type)
+                || upperBoundEscapes(targetType, type));
+        boolean typeVariableEscapes = unresolved && 
(typeVariableBoundEscapes(targetType, type)
+                || concreteArgumentContainsWildcard(targetType, type)
+                || upperBoundEscapes(targetType, type));
+        return incompatible || typeVariableEscapes;
+    }
+
+    /**
+     * Whether an expression whose own type does not fit the target is typed 
by the target:
+     * a call of a generic method or a spread expression, in an assignment or 
return context.
+     */
+    private boolean isTypedByTarget(final ClassNode targetType, final 
ClassNode type, final Expression expression) {
+        return isApplicableForTargetType(targetType, expression)
+                || isSpreadApplicableForTargetType(targetType, type, 
expression);
+    }
+
+    /**
+     * A spread expression such as {@code list*.getClass()} or {@code 
list*.name} makes a new
+     * list, so in an assignment or return context its element type is taken 
from the target,
+     * as it is for {@code list.collect { it.getClass() }}. The expression is 
accepted when the
+     * type of its elements fits the type argument of the target.
+     */
+    private boolean isSpreadApplicableForTargetType(final ClassNode 
targetType, final ClassNode spreadType, final Expression expression) {
+        boolean spread = expression instanceof MethodCallExpression ? 
((MethodCallExpression) expression).isSpreadSafe()
+                : expression instanceof PropertyExpression && 
((PropertyExpression) expression).isSpreadSafe();
+        if (!spread || !LIST_TYPE.equals(spreadType)) return false;
+        GenericsType[] elementTypes = spreadType.getGenericsTypes();
+        if (elementTypes == null || elementTypes.length != 1 || 
elementTypes[0].isWildcard() || elementTypes[0].isPlaceholder()) return false;
+        if (!LIST_TYPE.equals(targetType) && 
!implementsInterfaceOrIsSubclassOf(LIST_TYPE, targetType)) return false;
+
+        ClassNode declared = LIST_TYPE.redirect();
+        ClassNode viewed = LIST_TYPE.equals(targetType) ? declared : 
GenericsUtils.parameterizeType(declared, targetType);
+        Map<GenericsTypeName, GenericsType> connections = new HashMap<>();
+        extractGenericsConnections(connections, targetType, viewed);
+        GenericsType expected = connections.get(new 
GenericsTypeName(declared.getGenericsTypes()[0].getName()));
+        if (expected == null || expected.isWildcard() || 
expected.isPlaceholder()) return false;
+
+        ClassNode elementType = wrapTypeIfNecessary(elementTypes[0].getType());
+        return typeCheckMethodArgumentWithGenerics(expected.getType(), 
elementType, false)
+                && isSubtypeWithoutConversion(elementTypes[0].getType(), 
expected.getType())
+                && !hasIncompatibleGenerics(expected.getType(), elementType);
+    }
+
+    /**
+     * Whether a value of {@code type} is a {@code target} as it is. A value 
given a type argument
+     * from the target is stored as it is, so it is not converted as an 
assigned value may be, such
+     * as an {@code int} to a {@code Long} or a {@code GString} to a {@code 
String}.
+     */
+    private static boolean isSubtypeWithoutConversion(final ClassNode type, 
final ClassNode target) {
+        if (type.isArray() && target.isArray()) { // Integer[] is a Number[], 
but not a Long[]; int[] is only an int[]
+            ClassNode typeComponent = type.getComponentType(), targetComponent 
= target.getComponentType();
+            if (isPrimitiveType(typeComponent) || 
isPrimitiveType(targetComponent)) return typeComponent.equals(targetComponent);
+            return isSubtypeWithoutConversion(typeComponent, targetComponent);
+        }
+        if (type.isArray() || target.isArray() || 
target.isGenericsPlaceHolder()) return true; // checked elsewhere
+        return implementsInterfaceOrIsSubclassOf(wrapTypeIfNecessary(type), 
wrapTypeIfNecessary(target));
+    }
+
+    /**
+     * A call of a generic method in an assignment or return context takes its 
type arguments
+     * from the target type as well as from the arguments (JLS 18.5.2), so that
+     * {@code List<Class<?>> list = Collections.singletonList(x.getClass())} 
is accepted although
+     * the arguments alone give {@code List<Class<? extends String>>}. The 
call is accepted when
+     * the type parameters that the target determines keep their bounds and 
every argument fits
+     * its parameter with them.
+     */
+    private boolean isApplicableForTargetType(final ClassNode targetType, 
final Expression call) {
+        if (!(call instanceof MethodCall) || (call instanceof 
MethodCallExpression && ((MethodCallExpression) call).isUsingGenerics())) 
return false;
+        MethodNode method = call.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
+        if (method == null) return false;
+        List<ClassNode> argumentTypes = new ArrayList<>();
+        List<Expression> arguments = new 
ArrayList<>(InvocationWriter.makeArgumentList(((MethodCall) 
call).getArguments()).getExpressions());
+        if (method instanceof ExtensionMethodNode) {
+            if (!(call instanceof MethodCallExpression)) return false;
+            Expression receiver = ((MethodCallExpression) 
call).getObjectExpression();
+            method = ((ExtensionMethodNode) method).getExtensionMethodNode();
+            arguments.add(0, receiver);
+        }
+        GenericsType[] typeParameters = method.getGenericsTypes();
+        ClassNode returnType = method.getReturnType();
+        if (typeParameters == null || typeParameters.length == 0 || 
!GenericsUtils.hasUnresolvedGenerics(returnType)) return false;
+        Set<String> names = new HashSet<>();
+        for (GenericsType tp : typeParameters) names.add(tp.getName());
+        // only the type parameters of the method may take their type from the 
target
+        Set<String> used = new HashSet<>();
+        collectTypeVariableNames(returnType, used);
+        if (!names.containsAll(used)) return false;
+
+        ClassNode viewed = returnType;
+        if (!returnType.equals(targetType)) {
+            if (!implementsInterfaceOrIsSubclassOf(returnType, targetType)) 
return false;
+            viewed = GenericsUtils.parameterizeType(returnType, targetType);
+        }
+        Map<GenericsTypeName, GenericsType> connections = new HashMap<>();
+        extractGenericsConnections(connections, targetType, viewed);
+        connections.keySet().removeIf(name -> !names.contains(name.getName()));
+        for (Map.Entry<GenericsTypeName, GenericsType> entry : 
connections.entrySet()) {
+            GenericsType value = entry.getValue();
+            if (value.isWildcard()) { // take "? extends B" or "? super B" as B
+                ClassNode bound = value.getLowerBound() != null ? 
value.getLowerBound()
+                        : value.getUpperBounds() != null ? 
value.getUpperBounds()[0] : OBJECT_TYPE;
+                entry.setValue(bound.asGenericsType());
+            }
+        }
+        if (connections.isEmpty()) return false;
+
+        for (GenericsType tp : typeParameters) { // the target must keep each 
type parameter within its bounds
+            GenericsType value = connections.get(new 
GenericsTypeName(tp.getName()));
+            if (value == null || tp.getUpperBounds() == null) continue;
+            for (ClassNode bound : applyGenericsContext(connections, 
tp.getUpperBounds())) {
+                if (GenericsUtils.hasUnresolvedGenerics(bound) ? 
!isAssignableTo(value.getType(), bound)
+                        : !typeCheckMethodArgumentWithGenerics(bound, 
value.getType(), false)) return false;
+            }
+        }
+        // a wildcard taken as its bound must still fit the target where the 
type parameter is
+        // nested in an invariant type argument, as T is in List<List<T>>
+        ClassNode instantiated = applyGenericsContext(connections, viewed);
+        if (!GenericsUtils.hasUnresolvedGenerics(instantiated) && 
hasIncompatibleGenerics(targetType, instantiated)) return false;
+
+        Parameter[] parameters = method.getParameters();
+        int n = arguments.size();
+        if (parameters.length == 0 || (n != parameters.length && 
!isVargs(parameters))) return false;
+        for (int i = 0; i < n; i += 1) {
+            Expression argument = arguments.get(i);
+            ClassNode parameterType = parameters[Math.min(i, parameters.length 
- 1)].getOriginType();
+            if (!GenericsUtils.hasUnresolvedGenerics(parameterType)) continue;
+            boolean lastArg = i >= parameters.length - 1;
+            if (lastArg && parameterType.isArray() && (n != parameters.length 
|| !getType(argument).isArray())) {
+                parameterType = parameterType.getComponentType();
+            }
+            parameterType = applyGenericsContext(connections, parameterType);
+            if (isNullConstant(argument)) continue;
+            if (argument instanceof ClosureExpression || argument instanceof 
LambdaExpression || argument instanceof MethodPointerExpression) {
+                // a closure or lambda must return what the parameterized 
target expects
+                ClassNode expected = null;
+                if (CLOSURE_TYPE.equals(parameterType)) {
+                    GenericsType[] gts = parameterType.getGenericsTypes();
+                    if (gts != null && gts.length == 1) expected = 
getCombinedBoundType(gts[0]);
+                } else if (isSAMType(parameterType)) {
+                    Tuple2<ClassNode[], ClassNode> sam = 
GenericsUtils.parameterizeSAM(parameterType);
+                    expected = sam.getV2();
+                    // the target gives the parameters of the SAM, so a 
closure or lambda must accept them
+                    if (argument instanceof ClosureExpression closure && 
!acceptsParameters(closure, sam.getV1())) return false;

Review Comment:
   Thanks for checking a closure or lambda against the SAM's parameters here; 
that is what closes `toConsumer((String s) -> s.length())`. A method reference 
still takes only the return-type path just below 
(`getMethodPointerReturnType`), so the same target with `String::length` is 
accepted and then fails at run time (`ClassCastException` under 
`@CompileStatic`, `MissingMethodException` under `@TypeChecked`):
   
   ```groovy
   import java.util.function.*
   
   @groovy.transform.CompileStatic
   class C {
       static <T> Consumer<T> toConsumer(Function<T, Object> fn) { (T t) -> { 
fn.apply(t); return } }
       static void test() {
           Consumer<Object> c = toConsumer(String::length)
           c.accept(1) // ClassCastException
       }
   }
   ```
   
   The two annotations agree on accept versus reject, and `javac` rejects the 
equivalent. `Consumer<String> c = toConsumer(String::length)` still compiles 
and runs, as do legal static and subtype-receiver references such as 
`String::valueOf` as a `Function<Object, String>`. Would it be possible, once 
the target has instantiated `T`, to check the referenced method's parameters — 
including the implicit receiver of an unbound instance reference — perhaps via 
`collateMethodReferenceParameterTypes` and `parameterizeSAM(...).getV1()`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to