daniellansun commented on code in PR #3293:
URL: https://github.com/apache/groovy/pull/3293#discussion_r4601406006
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -2250,16 +2264,353 @@ 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);
+ }
+ } else if (GenericsUtils.hasUnresolvedGenerics(right) &&
!GenericsUtils.hasUnresolvedGenerics(leftExpressionType)
+ && isTypedByTarget(leftExpressionType, right,
rightExpression)) {
+ // a type parameter that the arguments left open takes its type
from the target
+ rightExpression.setNodeMetaData(TARGET_TYPED, leftExpressionType);
+ }
+ }
+
+ 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;
+
+ if (!keepsBounds(typeParameters, connections)) return false; // the
target must keep each type parameter within its bounds
+ // 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();
+ // a method with no parameters, such as Map.Entry.comparingByKey(),
takes its type arguments from the target alone
+ if (n != parameters.length && !isVargs(parameters)) return false;
+ // the functional interface types that the target gives the method
references of the call
+ Map<MethodReferenceExpression, ClassNode> retargeted = new HashMap<>();
+ 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;
+ ClassNode[] samParameterTypes = null;
+ List<FunctorSignature> fitting = 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();
+ samParameterTypes = sam.getV1();
+ // the target gives the parameters of the SAM, so a
closure, lambda or
+ // method reference must accept them
+ if (argument instanceof ClosureExpression closure &&
!acceptsParameters(closure, samParameterTypes)) return false;
+ if (argument instanceof MethodPointerExpression pointer) {
+ fitting = fittingSignatures(pointer,
samParameterTypes);
+ if (fitting != null && fitting.isEmpty()) return false;
+ if (pointer instanceof MethodReferenceExpression
reference && parameterType.isInterface()
+ &&
!GenericsUtils.hasUnresolvedGenerics(parameterType)) {
+ retargeted.put(reference, parameterType);
+ }
+ }
+ }
+ if (expected == null ||
GenericsUtils.hasUnresolvedGenerics(expected)) continue;
+ ClassNode inferred = argument instanceof
MethodPointerExpression ? getMethodPointerReturnType(argument) :
getInferredReturnType(argument);
+ // a method pointer to a method that returns its type
parameter has no type of its own for what
+ // it returns; the methods that fit give it
+ boolean declared = inferred == null && fitting != null &&
!fitting.isEmpty()
+ && fitting.stream().allMatch(f -> f.returnType() !=
null);
+ if (inferred == null && !declared) return false; // what the
argument returns is not known
+ // the reference was typed before the target gave the SAM's
parameters, so the type
+ // that each method that fits returns is taken from them; each
must fit the target
+ List<FunctorSignature> functors = declared ? fitting : fitting
!= null && fitting.size() > 1
+ && fitting.stream().anyMatch(f -> f.returnType() !=
null && GenericsUtils.hasUnresolvedGenerics(f.returnType()))
+ ? fitting : fitting != null && fitting.size() == 1 ?
fitting : Collections.singletonList(null);
+ for (FunctorSignature functor : functors) {
+ ClassNode actual = declared ? functor.returnType() :
inferred;
+ if (functor != null) {
+ // a type parameter of the referenced method takes its
type from the SAM's parameters
+ Map<GenericsTypeName, GenericsType> spec = new
HashMap<>();
+ for (int j = 0; j < samParameterTypes.length; j += 1) {
+ if (samParameterTypes[j] != null)
extractGenericsConnections(spec, samParameterTypes[j],
functor.parameterTypeFor(j, samParameterTypes));
+ }
+ if (functor.returnType() != null &&
GenericsUtils.hasUnresolvedGenerics(functor.returnType())) {
+ ClassNode returned = applyGenericsContext(spec,
functor.returnType());
+ if
(!GenericsUtils.hasUnresolvedGenerics(returned)) actual = returned;
+ }
+ if (GenericsUtils.hasUnresolvedGenerics(actual))
actual = applyGenericsContext(spec, actual);
+ }
+ if (functor != null && functor.typeParameters() != null &&
GenericsUtils.hasUnresolvedGenerics(actual)) {
+ // a type parameter that the SAM's parameters leave
open takes its type from what the SAM returns
+ Map<GenericsTypeName, GenericsType> returned =
typeArgumentsFromTarget(functor.typeParameters(), actual, expected);
+ if (!keepsBounds(functor.typeParameters(), returned))
return false;
+ actual = applyGenericsContext(returned, actual);
+ }
+ if (argument instanceof MethodPointerExpression &&
GenericsUtils.hasUnresolvedGenerics(actual)) continue; // its parameters were
checked
Review Comment:
This `continue` skips the assignability check that follows when `actual` is
still unresolved, which is how a method reference such as `toSupplier(C::nil)`
can still be accepted as `Supplier<ArrayList<String>>` (and a few nearby
forms). I do not think a blunt `return false` here is right: `Supplier<Object>
s = toSupplier(C::nil)` should stay legal. Please see the review body for the
rest of this family.
--
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]