daniellansun commented on code in PR #3293:
URL: https://github.com/apache/groovy/pull/3293#discussion_r4580598528
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -3927,18 +4235,67 @@ private IntPredicate functorArity(final
MethodPointerExpression pointer) {
}
if (methods.isEmpty()) return null;
- BitSet counts = new BitSet();
- int varargsFrom = Integer.MAX_VALUE;
+ List<FunctorSignature> signatures = new ArrayList<>(methods.size());
for (MethodNode method : methods) {
- Parameter[] parameters = method.getParameters();
- int count = parameters.length + (typeReceiver &&
!method.isStatic() ? 1 : 0);
- counts.set(count);
- if (parameters.length > 0 && parameters[parameters.length -
1].getType().isArray()) {
- varargsFrom = Math.min(varargsFrom, count - 1);
+ ClassNode[] parameterTypes =
extractTypesFromParameters(method.getParameters());
+ boolean varargs = parameterTypes.length > 0 &&
parameterTypes[parameterTypes.length - 1].isArray();
+ if (typeReceiver && !method.isStatic()) {
+ ClassNode[] withReceiver = new ClassNode[parameterTypes.length
+ 1];
+ withReceiver[0] = receiverType;
+ System.arraycopy(parameterTypes, 0, withReceiver, 1,
parameterTypes.length);
+ parameterTypes = withReceiver;
}
+ signatures.add(new FunctorSignature(parameterTypes, varargs));
}
- int fromVarargs = varargsFrom;
- return n -> n >= fromVarargs || counts.get(n);
+ return signatures;
+ }
+
+ /**
+ * The parameter types a method reference or pointer can be called with,
and whether the
+ * last is a varargs parameter.
+ */
+ private record FunctorSignature(ClassNode[] parameterTypes, boolean
varargs) {
+ /**
+ * The type of the parameter that takes argument {@code i} of {@code
argumentTypes}:
+ * the component type of a varargs parameter, unless one array is
given for it.
+ */
+ ClassNode parameterTypeFor(final int i, final ClassNode[]
argumentTypes) {
+ int count = parameterTypes.length;
+ ClassNode parameterType = parameterTypes[Math.min(i, count - 1)];
+ if (varargs && i >= count - 1 && !(argumentTypes.length == count
+ && argumentTypes[i] != null &&
argumentTypes[i].isArray())) {
+ parameterType = parameterType.getComponentType();
+ }
+ return parameterType;
+ }
+ }
+
+ /**
+ * Returns the methods a method reference or pointer names that can be
called with the
+ * parameter types of a SAM: they take that many arguments, and each SAM
parameter type is
+ * assignable to the method's parameter, or to the component type of its
varargs parameter.
+ * A parameter type that is not resolved, on either side, is not checked.
Returns
+ * {@code null} if the functor's methods are not known.
+ */
+ private List<FunctorSignature> fittingSignatures(final
MethodPointerExpression pointer, final ClassNode[] samParameterTypes) {
+ List<FunctorSignature> signatures = functorSignatures(pointer);
+ if (signatures == null) return null;
+ int n = samParameterTypes.length;
+ List<FunctorSignature> fitting = new ArrayList<>();
+ for (FunctorSignature functor : signatures) {
+ int count = functor.parameterTypes().length;
+ if (n != count && !(functor.varargs() && n >= count - 1)) continue;
+ boolean fits = true;
+ for (int i = 0; i < n && fits; i += 1) {
+ ClassNode samParameterType = samParameterTypes[i];
+ ClassNode parameterType = functor.parameterTypeFor(i,
samParameterTypes);
+ if (samParameterType == null ||
GenericsUtils.hasUnresolvedGenerics(samParameterType)
+ || GenericsUtils.hasUnresolvedGenerics(parameterType))
continue;
Review Comment:
A parameter type that the target leaves unresolved is right not to check.
When it is the referenced method's parameter that is still a type variable,
though, this `continue` also skips a bound that is already known, so a target
of `Consumer<String>` accepts `<T extends Number> void takeNumber(T t)` and the
consumer then fails at run time (`ClassCastException` under `@CompileStatic`).
`javac` rejects the equivalent, and current master rejects the same Groovy
programme. A method whose parameter is already a `Number` is rejected here.
Would it be possible to instantiate the method's type parameters from the SAM —
as just below, when exactly one method fits — and then check the parameters,
including that bound?
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -2250,16 +2264,276 @@ 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;
+ 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);
Review Comment:
This is the acceptance that lets `Function<String, List<String>> f =
toFn(Arrays::asList)` through, which matches `javac` and the direct assignment
`Arrays::asList`. Under `@CompileStatic` the `toFn` form then fails at run time
(`String` cannot be cast to `Object[]`); `@TypeChecked` and the direct
assignment both run. I wonder whether the statically compiled call through the
generic identity still treats the argument as a `T[]` rather than as a varargs
element.
--
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]