[
https://issues.apache.org/jira/browse/GROOVY-12754?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18145636#comment-18145636
]
ASF GitHub Bot commented on GROOVY-12754:
-----------------------------------------
daniellansun commented on code in PR #3293:
URL: https://github.com/apache/groovy/pull/3293#discussion_r4586019096
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -2250,16 +2264,313 @@ 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);
+ if (inferred == null) 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 = 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 = 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 (argument instanceof MethodPointerExpression &&
GenericsUtils.hasUnresolvedGenerics(actual)) continue; // its parameters were
checked
Review Comment:
When the referenced method's type parameter appears only in the return type,
the specification just above is taken from the SAM's parameters, so a
`Supplier` leaves `List<T>` unresolved and this `continue` accepts it.
`Supplier<List<String>> s = toSupplier(C::nil)` for `<T extends Number> List<T>
nil()` then compiles, and a `String` can be stored in a `List<Integer>` under
`@CompileStatic`. `javac` rejects the equivalent, and current master rejects
this wrapper form. A `Supplier<List<Integer>>` is accepted, as it should be.
Would it be possible to instantiate the method's type parameters from the SAM's
return type as well, and then check that bound?
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -2250,16 +2264,313 @@ 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);
+ if (inferred == null) 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 = 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 = 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 (argument instanceof MethodPointerExpression &&
GenericsUtils.hasUnresolvedGenerics(actual)) continue; // its parameters were
checked
+ actual = wrapTypeIfNecessary(actual);
+ if (!isAssignableTo(actual, wrapTypeIfNecessary(expected))
|| !isSubtypeWithoutConversion(actual, expected)
+ || (expected.isUsingGenerics() &&
(!GenericsUtils.buildWildcardType(expected).isCompatibleWith(actual)
+ || hasIncompatibleGenerics(expected,
actual)))) return false;
+ }
+ continue;
+ }
+ ClassNode argumentType = wrapTypeIfNecessary(getType(argument));
+ if (GenericsUtils.hasUnresolvedGenerics(parameterType)) {
+ // a type parameter that the target does not determine was
inferred from the arguments
+ if (!isAssignableTo(argumentType, parameterType)) return false;
+ } else if (!typeCheckMethodArgumentWithGenerics(parameterType,
argumentType, lastArg)
+ || !isSubtypeWithoutConversion(argumentType, parameterType)
+ // a wildcard is not within the type argument that the
target gives the parameter
+ || (!GenericsUtils.hasUnresolvedGenerics(argumentType)
+ && (concreteArgumentContainsWildcard(parameterType,
argumentType) || upperBoundEscapes(parameterType, argumentType)))) {
+ // a nested generic call or spread expression is typed by the
parameter in turn
+ if (!isTypedByTarget(parameterType, argumentType, argument))
return false;
Review Comment:
A nested generic call is typed by the parameter here, and that accepts
`Consumer<String> c = toConsumer(identC(C::takeNumber))`, which then fails at
run time (`ClassCastException` under `@CompileStatic`). The one-level form
`toConsumer(C::takeNumber)` is now a compile error, as is this programme on
current master and with `javac`. I wonder whether the `Consumer<String>` target
can be pushed into the inner reference, as it is when `C::takeNumber` is passed
to `toConsumer` directly.
> STC: an upper-bounded wildcard argument is checked against a type parameter's
> bound the wrong way round
> -------------------------------------------------------------------------------------------------------
>
> Key: GROOVY-12754
> URL: https://issues.apache.org/jira/browse/GROOVY-12754
> Project: Groovy
> Issue Type: Bug
> Components: Static Type Checker
> Affects Versions: 6.0.0
> Reporter: Scott Murphy Heiberg
> Priority: Major
>
> Static type checking rejects a call that passes an upper-bounded wildcard,
> such as {{List<? extends Integer>}}, to a generic method whose type parameter
> is bounded by a supertype of the wildcard's bound. It accepts the call when
> the wildcard's bound is wider than the type parameter's. javac does the
> opposite in both cases.
> {code:groovy}
> @groovy.transform.CompileStatic
> class C {
> static <T extends Number> T first(List<T> list) { list.get(0) }
> static <T extends CharSequence> int len(Class<T> type) { 0 }
> static <T extends Integer> T narrow(List<T> list) { list.get(0) }
> static Object a(List<? extends Integer> ints) { first(ints) } //
> rejected, javac accepts
> static int b(Class<? extends String> type) { len(type) } //
> rejected, javac accepts
> static Object c(List<? extends Number> nums) { narrow(nums) } //
> accepted, javac rejects
> }
> {code}
> {noformat}
> [Static type checking] - Cannot call <T extends java.lang.Number>
> C#first(java.util.List<T>) with arguments [java.util.List<? extends
> java.lang.Integer>]
> [Static type checking] - Cannot call <T extends java.lang.CharSequence>
> C#len(java.lang.Class<T>) with arguments [java.lang.Class<? extends
> java.lang.String>]
> {noformat}
> The capture of {{? extends B}} is a subtype of {{B}} (JLS 5.1.10), so it is
> within the bound of {{T}} exactly when {{B}} is. javac reports "inference
> variable T has incompatible bounds" for {{c}}. Groovy compiles {{c}}, and
> {{c([1.5d])}} returns {{1}}.
> {{StaticTypeCheckingSupport#compatibleConnection}} tests a wildcard witness
> with {{connection.isCompatibleWith(bound)}}, which asks whether the type
> parameter's bound fits within {{? extends B}}. For a type argument {{B}}, it
> tests {{? super B}} against the bound. An upper-bounded wildcard should take
> the same test.
> PR: https://github.com/apache/groovy/pull/3285
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)