[
https://issues.apache.org/jira/browse/GROOVY-12754?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18144820#comment-18144820
]
ASF GitHub Bot commented on GROOVY-12754:
-----------------------------------------
daniellansun commented on code in PR #3293:
URL: https://github.com/apache/groovy/pull/3293#discussion_r4573655350
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java:
##########
@@ -1950,9 +2083,20 @@ private static boolean
typeCheckMethodsWithGenerics(final ClassNode receiver, fi
// that are not containment errors.
if (!GenericsUtils.hasUnresolvedGenerics(parameterType)
&& !GenericsUtils.hasUnresolvedGenerics(argumentType)
- && concreteArgumentContainsWildcard(parameterType,
argumentType)) {
+ && (concreteArgumentContainsWildcard(parameterType,
argumentType)
+ || upperBoundEscapes(parameterType, argumentType))) {
failure = true;
}
+ // a parameter typed by type variables in scope, not by the
method's own, is checked as an assignment;
+ // take its type before the argument is used to infer anything
+ if (!failure && !skipBecauseOfInnerClassNotReceiver &&
!isRawReceiver(receiver) && !isDiamondReceiver(receiver)
+ && !mentionsTypeParameterOf(parameterType,
candidateMethod)) {
+ ClassNode resolvedType =
applyGenericsContext(candidateGenerics, parameterType);
+ if (GenericsUtils.hasUnresolvedGenerics(resolvedType) &&
!GenericsUtils.hasUnresolvedGenerics(argumentType)
Review Comment:
Two gaps in `StaticTypeCheckingSupport`:
1. **Concretely parameterized receivers (`typeCheckMethodsWithGenerics`):**
For a call like `map.put('k', rawClassExtendsList)` on `Map<String, Class<?
extends List<String>>>` (or `box.set(...)` on `Box<Class<? extends
List<Number>>>`), the first `if` is skipped because `parameterType` (`V` / `T`)
has unresolved generics, and this second `if` is also skipped because
`resolvedType` (`Class<? extends List<String>>`) no longer has unresolved
generics. Dropping the `hasUnresolvedGenerics(resolvedType)` guard on
`upperBoundEscapes` and checking
`concreteArgumentContainsWildcard(resolvedType, argumentType)` when
`!GenericsUtils.hasUnresolvedGenerics(resolvedType)` closes that gap.
2. **`compatibleCapture` / `captureWithinBound`:**
- In `captureWithinBound`, `captureBounds` is an intersection (`glb`), so
returning `false` on the first `captureBound` whose raw type implements `bound`
skips remaining bounds in the intersection (e.g. `NumBox<? extends List<?>>`
for `class NumBox<C extends Collection<Number>> {}` fails on `List<?>` before
checking `Collection<Number>`, whereas `javac` accepts it). Only a matching
bound should `return true`; non-matching components should `continue`.
-
`GenericsUtils.buildWildcardType(target).isCompatibleWith(captureBound)` in
`captureWithinBound` also needs `&& !concreteArgumentContainsWildcard(target,
captureBound) && !upperBoundEscapes(target, captureBound)`.
- In `compatibleCapture`,
`isObjectType(capture.getUnresolvedSuperClass())` keeps the first class bound
(e.g. `Number`) and drops a narrower declared class bound (e.g. `Integer`);
refining whenever `bound.isDerivedFrom(capture.getUnresolvedSuperClass())`
preserves the narrower bound.
##########
src/main/java/org/codehaus/groovy/control/ResolveVisitor.java:
##########
@@ -453,6 +462,102 @@ private void resolveOrFail(final ClassNode type, final
String msg, final ASTNode
addError("unable to resolve class " + type.toString(false) + msg,
node);
}
+ /**
+ * JLS 6.5.5.1, 8.1.3, 8.5: within {@code Outer<T>}, the simple name
{@code Inner}
+ * of an inner class is the type {@code Outer<T>.Inner}, and within a
subclass that
+ * extends {@code Outer<String>} it is {@code Outer<String>.Inner}.
Neither is the
+ * raw type {@code Outer.Inner}. Records the enclosing type for such a
name. A name
+ * used where the type variables are out of scope, as in a static method,
stays raw.
+ */
+ private void setOuterClassTypeOfSimpleName(ClassNode type) {
+ while (type.isArray()) type = type.getComponentType();
+ if (!type.isRedirectNode() || type.isGenericsPlaceHolder() ||
type.getOuterClassType() != null) return;
+ String name = type.getUnresolvedName();
+ if (name.indexOf('.') != -1 || name.indexOf('$') != -1) return; //
Outer.Inner is the raw type
+ ClassNode inner = type.redirect(), outer = inner.getOuterClass();
+ if (outer == null || isStaticMember(inner)) return;
+ if (type.getGenericsTypes() == null && inner.getGenericsTypes() !=
null) return; // raw type
+
+ for (ClassNode cn = currentClass; cn != null; cn = cn.getOuterClass())
{
+ boolean declares = cn.equals(outer);
+ if (declares || inherits(cn, outer)) {
+ ClassNode outerType = typeOfThis(cn);
+ if (outerType != null && !declares) {
+ outerType = GenericsUtils.parameterizeType(outerType,
outer);
+ }
+ if (outerType != null && (outerType.getOuterClassType() != null
+ || (outerType.isRedirectNode() &&
outerType.getGenericsTypes() != null))) {
+ type.setOuterClassType(outerType);
+ }
+ return;
+ }
+ if (isRecord(cn)) return; // the type variables of its enclosing
classes are out of scope
Review Comment:
Within `class Sub extends Outer<String>` (where `Outer<String>` has no type
variables), static nested declarations currently resolve the simple name
`Inner` inconsistently:
- `static class Nested { Inner f }` walks past `Nested` to `Sub`,
`typeOfThis(Sub)` returns `Sub`, and `f` gets `Outer<String>.Inner` (matching
`javac`).
- `record Rec(Inner f) {}` stops at `if (isRecord(cn)) return;` on `Rec`
before reaching `Sub`, so `f` stays raw `Outer.Inner`.
- `class Sub<U> extends Outer<String> { static class Nested { Inner f } }`
fails `typeOfThis(Sub)` because `U` is out of scope in `Nested`, even though
`Outer<String>` does not mention `U`, so `f` also falls back to raw
`Outer.Inner`.
Per JLS §6.5.5 and §8.5, an inherited member type `Outer<String>.Inner` does
not depend on an enclosing instance or on `U`; only an `outerType` that still
references an out-of-scope type variable needs to be rejected/left raw.
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -2244,16 +2251,203 @@ 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;
+
+ return typeCheckMethodArgumentWithGenerics(expected.getType(),
wrapTypeIfNecessary(elementTypes[0].getType()), false);
Review Comment:
`typeCheckMethodArgumentWithGenerics` alone does not enforce
`upperBoundEscapes`, `concreteArgumentContainsWildcard`, or
`typeVariableArgumentGetsWildcard`. As a result, spread target-typing bypasses
the `t.getClass()` and raw-bound checks that direct assignment rejects:
```groovy
@groovy.transform.CompileStatic
static <T> List<Class<? extends T>> classesOf(List<T> items) {
List<Class<? extends T>> res = items*.getClass() // accepted, should be
rejected
res
}
@groovy.transform.CompileStatic
static List<Class<? extends List<String>>> rawSpread(List<List> rawLists) {
List<Class<? extends List<String>>> res = rawLists*.getClass() //
accepted, should be rejected
res
}
```
Checking `!hasIncompatibleGenerics(expected.getType(), actualElement)`
alongside `typeCheckMethodArgumentWithGenerics` closes this gap.
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -3637,6 +3834,14 @@ protected ClassNode checkReturnType(final
ReturnStatement statement) {
if (expression instanceof ConstructorCallExpression) {
inferDiamondType((ConstructorCallExpression) expression,
inferredReturnType != null ? inferredReturnType :
/*GROOVY-10080:*/dynamicType());
}
+ if (inferredReturnType != null
+ && inferredReturnType.equals(type)
Review Comment:
Thanks for adding `e72bb7a`. Requiring `inferredReturnType.equals(type)`
here checks raw class equality, whereas `isApplicableForTargetType` and
`isSpreadApplicableForTargetType` support supertype targets
(`implementsInterfaceOrIsSubclassOf`). As a result, a supertype target on
`Closure<V>` still fails on the closure return:
```groovy
static Collection<Class<?>> closureSuperTarget(String x) {
Closure<Collection<Class<?>>> c = { String s ->
Collections.singletonList(s.getClass()) }
c.call(x) // fails: Cannot return value of type List<Class<? extends
String>> for closure expecting Collection<Class<?>>
}
```
Relaxing `inferredReturnType.equals(type)` to
`implementsInterfaceOrIsSubclassOf(wrapTypeIfNecessary(type),
inferredReturnType)` fixes this. Also note the `allow simple covariance` branch
right below: when `!inferredReturnType.equals(type)` (e.g. returning
`ArrayList<Class<? extends List>>` for `List<Class<? extends List<String>>>`),
`isCompatibleWith` runs without `!hasIncompatibleGenerics(inferredReturnType,
wrapTypeIfNecessary(type))`.
Two minor `IntersectionTypeClassNode` points in this file as well:
- **`getResultType` (`!isClassType(right)`):** After `Serializable s =
String.class; if (s instanceof Class)`, `right` is
`IntersectionTypeClassNode(Serializable & Class)`, so `isClassType(right)` is
`false` and `Class<? extends Number> c = s` is accepted as a non-`Class`
conversion. Using `!implementsInterfaceOrIsSubclassOf(right, CLASS_Type)`
handles intersections with `Class`.
- **`erasureOf` (`intersection.getComponents()[0]`):** Taking
`components[0]` depends on declaration order in `instanceof` narrowing: for
`Comparable c = 42; if (c instanceof Number)`, `components[0]` is `Comparable`,
so `Class<? extends Number> cls = c.getClass()` is rejected inside the
`instanceof Number` branch. Preferring a non-`Object` class component ahead of
interfaces matches JLS §4.4 and §4.6.
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -2244,16 +2251,203 @@ 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;
+
+ return typeCheckMethodArgumentWithGenerics(expected.getType(),
wrapTypeIfNecessary(elementTypes[0].getType()), false);
+ }
+
+ /**
+ * 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;
+ }
+ }
+
+ 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)) {
+ expected =
GenericsUtils.parameterizeSAM(parameterType).getV2();
+ }
+ ClassNode actual = getInferredReturnType(argument);
+ if (expected == null || actual == null ||
GenericsUtils.hasUnresolvedGenerics(expected)) continue;
Review Comment:
Four soundness issues across this parameter loop (plus an unused
`List<ClassNode> argumentTypes` local at the top of
`isApplicableForTargetType`):
1. **Fail-open `continue` on unhandled functional arguments:**
`isApplicableForTargetType` rescues an assignment that already failed
`hasIncompatibleGenerics`, so unhandled cases must `return false`, not
`continue`:
- `visitMethodPointerExpression` stores `Closure<R>` via `storeType` and
never sets `INFERRED_RETURN_TYPE`, so `actual` is `null` and `List<Integer>
ints = ['a'].collect(String::toUpperCase)` compiles under `@CompileStatic`.
- When `expected` mentions an enclosing type variable `T`,
`hasUnresolvedGenerics(expected)` is `true`, so `<T> List<T> cast(List<String>
s) { List<T> r = s.collect { String x -> x }; r }` compiles under
`@CompileStatic`.
2. **SAM and closure parameter types are not checked against
`connections`:** `parameterizeSAM(parameterType)` inspects only `.getV2()`
(return type) and ignores `.getV1()` (parameter types):
```groovy
import java.util.function.Consumer
import java.util.function.Function
static <T> Consumer<T> toConsumer(Function<T, Object> fn) {
(T t) -> fn.apply(t)
}
static void test() {
Consumer<Object> c = toConsumer((String s) -> s.length())
c.accept(1) // ClassCastException: Integer cannot be cast to String
}
```
3. **Missing escape checks on closure return (`expected` vs `actual`):**
`isCompatibleWith` alone misses `concreteArgumentContainsWildcard`,
`typeVariableArgumentGetsWildcard`, and `upperBoundEscapes` (e.g. `List<Class<?
extends List<String>>> r = rawClassList.collect { it }`). Calling
`hasIncompatibleGenerics(wrapTypeIfNecessary(expected), actual)` covers all
three.
4. **Enclosing type variables in
`GenericsUtils.hasUnresolvedGenerics(parameterType)`:**
`hasUnresolvedGenerics(parameterType)` is also `true` when `connections`
substituted an enclosing type variable `U` from `targetType`. Falling back to
`isAssignableTo` skips `typeVariableArgumentGetsWildcard` and
`upperBoundEscapes`, bypassing `GROOVY-12755`:
```groovy
static <U> Class<? extends U> bypassClassOf(U u) {
List<Class<? extends U>> box = Collections.singletonList(u.getClass())
box[0]
}
static <U extends Number> Class<? extends U> bypassBound(Class<? extends
Number> c) {
List<Class<? extends U>> box = Collections.singletonList(c)
box[0]
}
```
Please check `mentionsTypeParameterOf(parameterType, method)` for
undetermined method type parameters, and run
`!hasIncompatibleGenerics(parameterType, argumentType)` when enclosing type
variables are present.
##########
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java:
##########
@@ -2244,16 +2251,203 @@ 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;
+
+ return typeCheckMethodArgumentWithGenerics(expected.getType(),
wrapTypeIfNecessary(elementTypes[0].getType()), false);
+ }
+
+ /**
+ * 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());
Review Comment:
Collapsing a wildcard in `connections` to its bound `B` is only sound if the
instantiated return type `applyGenericsContext(connections, returnType)` is
still compatible with `targetType` (JLS §18.5 `⟨Rθ → T⟩`). Because
`isApplicableForTargetType` returns `true` without checking the substituted
return type against `targetType`, any method where `T` appears inside an
invariant nested generic allows unsound variance widening and heap pollution
under `@CompileStatic`:
```groovy
@groovy.transform.CompileStatic
class NestedWildcardTargetTest {
static <T> List<List<T>> same(List<List<T>> x) { x }
static void test() {
List<List<Integer>> intsOnly = [new ArrayList<Integer>([42])]
List<List<? super Integer>> widened = same(intsOnly) // T -> ? super
Integer -> Integer
widened.add(new ArrayList<Object>(['boom']))
Integer i = intsOnly[1][0] // ClassCastException: String cannot be
cast to Integer
}
}
```
Before returning `true`, please verify that `ClassNode instantiatedReturn =
applyGenericsContext(connections, returnType)` is assignable to `targetType`
and `!hasIncompatibleGenerics(targetType,
wrapTypeIfNecessary(instantiatedReturn))`.
> 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)