You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2023/05/26 21:35:16 UTC
[groovy] branch GROOVY_4_0_X updated: GROOVY-11013, GROOVY-11072: apply type variable of SAM-type to `List`
This is an automated email from the ASF dual-hosted git repository.
emilles pushed a commit to branch GROOVY_4_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/GROOVY_4_0_X by this push:
new 01e8503d88 GROOVY-11013, GROOVY-11072: apply type variable of SAM-type to `List<T>`
01e8503d88 is described below
commit 01e8503d884d6547f0ec55ed3edd7180f1f0f3d5
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Fri May 26 15:47:55 2023 -0500
GROOVY-11013, GROOVY-11072: apply type variable of SAM-type to `List<T>`
---
.../codehaus/groovy/ast/tools/GenericsUtils.java | 24 ++++---
.../asm/sc/AbstractFunctionalInterfaceWriter.java | 78 +++++++---------------
...StaticTypesMethodReferenceExpressionWriter.java | 6 +-
.../transform/stc/StaticTypeCheckingSupport.java | 2 +-
src/test/groovy/transform/stc/LambdaTest.groovy | 44 +++++++++++-
5 files changed, 83 insertions(+), 71 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java b/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java
index 41b7f6cef8..ca75cf559c 100644
--- a/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java
+++ b/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java
@@ -59,6 +59,7 @@ import static org.apache.groovy.util.SystemUtil.getSystemPropertySafe;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.plus;
import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf;
import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isUnboundedWildcard;
+import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.resolveClassNodeGenerics;
/**
* Utility methods to deal with generic types.
@@ -972,18 +973,21 @@ public class GenericsUtils {
*/
public static Tuple2<ClassNode[], ClassNode> parameterizeSAM(final ClassNode samType) {
MethodNode abstractMethod = ClassHelper.findSAM(samType);
+ ClassNode declaringClass = abstractMethod.getDeclaringClass();
+ Map<GenericsType.GenericsTypeName, GenericsType> spec = extractPlaceholders(
+ samType.equals(declaringClass) ? samType : parameterizeType(samType, declaringClass));
- Map<GenericsType, GenericsType> generics = makeDeclaringAndActualGenericsTypeMapOfExactType(abstractMethod.getDeclaringClass(), samType);
- Function<ClassNode, ClassNode> resolver = t -> {
- if (t.isGenericsPlaceHolder()) {
- return findActualTypeByGenericsPlaceholderName(t.getUnresolvedName(), generics);
- }
- return t;
- };
+ if (spec.isEmpty() && declaringClass.getGenericsTypes() != null) {
+ for (GenericsType tp : declaringClass.getGenericsTypes()) // apply erasure
+ spec.put(new GenericsType.GenericsTypeName(tp.getName()), erasure(tp));
+ } else {
+ // resolveClassNodeGenerics converts "T=? super Type" to Object, so convert "T=? super Type" to "T=Type"
+ spec.replaceAll((name, type) -> type.isWildcard() && type.getLowerBound() != null ? type.getLowerBound().asGenericsType() : type);
+ }
- ClassNode[] parameterTypes = Arrays.stream(abstractMethod.getParameters()).map(Parameter::getType).map(resolver).toArray(ClassNode[]::new);
- ClassNode returnType = resolver.apply(abstractMethod.getReturnType());
- return tuple(parameterTypes, returnType);
+ ClassNode[] parameterTypes = Arrays.stream(abstractMethod.getParameters()).map(p -> resolveClassNodeGenerics(spec, null, p.getType())).toArray(ClassNode[]::new);
+ ClassNode returnType = resolveClassNodeGenerics(spec, null, abstractMethod.getReturnType());
+ return new Tuple2<>(parameterTypes, returnType);
}
/**
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/AbstractFunctionalInterfaceWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/AbstractFunctionalInterfaceWriter.java
index 57590433e0..d8fba26bc6 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/AbstractFunctionalInterfaceWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/AbstractFunctionalInterfaceWriter.java
@@ -25,6 +25,7 @@ import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.classgen.asm.BytecodeHelper;
import org.codehaus.groovy.syntax.RuntimeParserException;
+import org.codehaus.groovy.transform.stc.StaticTypesMarker;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
@@ -32,11 +33,6 @@ import org.objectweb.asm.Type;
import java.util.Arrays;
import java.util.List;
-import static org.codehaus.groovy.ast.ClassHelper.getUnwrapper;
-import static org.codehaus.groovy.ast.ClassHelper.getWrapper;
-import static org.codehaus.groovy.transform.stc.StaticTypesMarker.INFERRED_FUNCTIONAL_INTERFACE_TYPE;
-import static org.codehaus.groovy.transform.stc.StaticTypesMarker.PARAMETER_TYPE;
-
/**
* Represents functional interface writer which contains some common methods to complete generating bytecode
* @since 3.0.0
@@ -46,9 +42,9 @@ public interface AbstractFunctionalInterfaceWriter {
String ORIGINAL_PARAMETERS_WITH_EXACT_TYPE = "__ORIGINAL_PARAMETERS_WITH_EXACT_TYPE";
default ClassNode getFunctionalInterfaceType(final Expression expression) {
- ClassNode type = expression.getNodeMetaData(PARAMETER_TYPE);
+ ClassNode type = expression.getNodeMetaData(StaticTypesMarker.PARAMETER_TYPE);
if (type == null) {
- type = expression.getNodeMetaData(INFERRED_FUNCTIONAL_INTERFACE_TYPE);
+ type = expression.getNodeMetaData(StaticTypesMarker.INFERRED_FUNCTIONAL_INTERFACE_TYPE);
}
return type;
}
@@ -105,61 +101,37 @@ public interface AbstractFunctionalInterfaceWriter {
return arguments;
}
+ default ClassNode convertParameterType(final ClassNode parameterType, final ClassNode inferredType) {
+ return convertParameterType(parameterType, parameterType, inferredType);
+ }
+
default ClassNode convertParameterType(final ClassNode targetType, final ClassNode parameterType, final ClassNode inferredType) {
- if (!getWrapper(inferredType).isDerivedFrom(getWrapper(parameterType))) {
+ if (!ClassHelper.getWrapper(inferredType).isDerivedFrom(ClassHelper.getWrapper(parameterType))) {
throw new RuntimeParserException("The inferred type[" + inferredType.redirect() + "] is not compatible with the parameter type[" + parameterType.redirect() + "]", parameterType);
}
- ClassNode type;
- boolean isParameterTypePrimitive = ClassHelper.isPrimitiveType(parameterType);
- boolean isInferredTypePrimitive = ClassHelper.isPrimitiveType(inferredType);
- if (!isParameterTypePrimitive && isInferredTypePrimitive) {
- if (ClassHelper.isDynamicTyped(parameterType) && ClassHelper.isPrimitiveType(targetType) // (1)
- || !parameterType.equals(getUnwrapper(parameterType)) && !inferredType.equals(getWrapper(inferredType)) // (2)
- ) {
- // GROOVY-9790: bootstrap method initialization exception raised when lambda parameter type is wrong
- // (1) java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 0: class java.lang.Integer is not a subtype of int
- // (2) java.lang.BootstrapMethodError: bootstrap method initialization exception
- type = inferredType;
- } else {
+ ClassNode type = inferredType;
+ if (ClassHelper.isPrimitiveType(parameterType)) {
+ if (!ClassHelper.isPrimitiveType(inferredType)) {
+ // The non-primitive type and primitive type are not allowed to mix since Java 9+
+ // java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 0: class java.lang.Integer is not a subtype of int
+ type = ClassHelper.getUnwrapper(inferredType);
+ }
+ } else if (ClassHelper.isPrimitiveType(inferredType)) {
+ // GROOVY-9790: bootstrap method initialization exception raised when lambda parameter type is wrong
+ // (1) java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 0: class java.lang.Integer is not a subtype of int
+ // (2) java.lang.BootstrapMethodError: bootstrap method initialization exception
+ if (!(ClassHelper.isDynamicTyped(parameterType) && ClassHelper.isPrimitiveType(targetType)) // (1)
+ && (parameterType.equals(ClassHelper.getUnwrapper(parameterType)) || inferredType.equals(ClassHelper.getWrapper(inferredType)))) { // (2)
// The non-primitive type and primitive type are not allowed to mix since Java 9+
// java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 0: int is not a subtype of class java.lang.Object
- type = getWrapper(inferredType);
+ type = ClassHelper.getWrapper(inferredType);
}
- } else if (isParameterTypePrimitive && !isInferredTypePrimitive) {
- // The non-primitive type and primitive type are not allowed to mix since Java 9+
- // java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 0: class java.lang.Integer is not a subtype of int
- type = getUnwrapper(inferredType);
- } else {
- type = inferredType;
}
- return type;
- }
-
- /**
- * @deprecated use {@link #convertParameterType(ClassNode, ClassNode, ClassNode)} instead
- */
- @Deprecated
- default ClassNode convertParameterType(final ClassNode parameterType, final ClassNode inferredType) {
- if (!ClassHelper.getWrapper(inferredType.redirect()).isDerivedFrom(ClassHelper.getWrapper(parameterType.redirect()))) {
- throw new RuntimeParserException("The inferred type[" + inferredType.redirect() + "] is not compatible with the parameter type[" + parameterType.redirect() + "]", parameterType);
- } else {
- boolean isParameterTypePrimitive = ClassHelper.isPrimitiveType(parameterType);
- boolean isInferredTypePrimitive = ClassHelper.isPrimitiveType(inferredType);
- ClassNode type;
- if (!isParameterTypePrimitive && isInferredTypePrimitive) {
- if (parameterType != ClassHelper.getUnwrapper(parameterType) && inferredType != ClassHelper.getWrapper(inferredType)) {
- type = inferredType;
- } else {
- type = ClassHelper.getWrapper(inferredType);
- }
- } else if (isParameterTypePrimitive && !isInferredTypePrimitive) {
- type = ClassHelper.getUnwrapper(inferredType);
- } else {
- type = inferredType;
- }
- return type;
+ if (type.isGenericsPlaceHolder()) {
+ type = type.redirect();
}
+ return type;
}
default Parameter prependParameter(final List<Parameter> parameterList, final String parameterName, final ClassNode parameterType) {
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java
index 62f2d9c544..62a659af28 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java
@@ -302,13 +302,11 @@ public class StaticTypesMethodReferenceExpressionWriter extends MethodReferenceE
if (inferredParamTypes != null) {
for (int i = 0, n = parameters.length; i < n; i += 1) {
- ClassNode inferredParamType = inferredParamTypes[i];
+ ClassNode inferredParamType = i < inferredParamTypes.length ? inferredParamTypes[i] : parameters[i].getType();
if (inferredParamType == null) continue;
-
Parameter parameter = parameters[i];
- Parameter targetParameter = parameter;
- ClassNode type = convertParameterType(targetParameter.getType(), parameter.getType(), inferredParamType);
+ ClassNode type = convertParameterType(parameter.getType(), inferredParamType);
parameter.setOriginType(type);
parameter.setType(type);
}
diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
index fb413f5ed0..dd553a9091 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
@@ -1930,7 +1930,7 @@ public abstract class StaticTypeCheckingSupport {
}
if (type.getGenericsTypes()[0] != gt[0]) { // convert T to X
- ClassNode cn = make(gt[0].getName()) , erasure = getCombinedBoundType(gt[0]);
+ ClassNode cn = make(gt[0].getName()) , erasure = getCombinedBoundType(gt[0]).redirect();
cn.setGenericsPlaceHolder(true);
cn.setGenericsTypes(gt);
cn.setRedirect(erasure);
diff --git a/src/test/groovy/transform/stc/LambdaTest.groovy b/src/test/groovy/transform/stc/LambdaTest.groovy
index d3a2375d92..b172160945 100644
--- a/src/test/groovy/transform/stc/LambdaTest.groovy
+++ b/src/test/groovy/transform/stc/LambdaTest.groovy
@@ -778,17 +778,17 @@ final class LambdaTest {
void testFunctionalInterface4() {
assertScript shell, '''
class Value<V> {
- final V val
+ final V val;
Value(V v) {
this.val = v
}
String toString() {
val as String
}
- def <T> Value<T> replace(Supplier<T> supplier) {
+ def <Out> Value<Out> replace(Supplier<Out> supplier) {
new Value<>(supplier.get())
}
- def <T> Value<T> replace(Function<? super V, ? extends T> function) {
+ def <Out> Value<Out> replace(Function<? super V, ? extends Out> function) {
new Value<>(function.apply(val))
}
}
@@ -810,6 +810,44 @@ final class LambdaTest {
assert err =~ /Expected type java.util.List<java.lang.String> for lambda parameter: list/
}
+ @Test // GROOVY-11013
+ void testFunctionalInterface6() {
+ assertScript shell, '''
+ interface I<T> {
+ def m(List<T> list_of_t)
+ }
+
+ I<String> face = (List<String> list) -> null
+ '''
+ }
+
+ @Test // GROOVY-11072
+ void testFunctionalInterface7() {
+ assertScript shell, '''
+ class Model {
+ }
+ class Table<T extends Model> {
+ interface ChunkReader<T> {
+ void call(List<T> row)
+ }
+ void getAll(ChunkReader<T> reader) {
+ List<T> chunk = []
+ reader.call(chunk)
+ }
+ }
+ class TestModel extends Model {
+ int id = 0
+ }
+ class TestTable extends Table<TestModel> {
+ }
+
+ TestTable table = new TestTable()
+ table.getAll((List<TestModel> list) ->
+ list.each { TestModel tm -> println(tm.id) }
+ )
+ '''
+ }
+
@Test
void testFunctionWithUpdatingLocalVariable() {
assertScript shell, '''