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 2024/10/26 12:55:12 UTC
(groovy) branch GROOVY_3_0_X updated: GROOVY-5106, GROOVY-10439, GROOVY-11508: re-implement with new type args
This is an automated email from the ASF dual-hosted git repository.
emilles pushed a commit to branch GROOVY_3_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/GROOVY_3_0_X by this push:
new 09247dd06d GROOVY-5106, GROOVY-10439, GROOVY-11508: re-implement with new type args
09247dd06d is described below
commit 09247dd06ddf9047f21984bbdccbc9f40370e3c0
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Sat Oct 26 06:56:22 2024 -0500
GROOVY-5106, GROOVY-10439, GROOVY-11508: re-implement with new type args
3_0_X backport
---
.../org/codehaus/groovy/classgen/Verifier.java | 39 ++++++-
.../codehaus/groovy/control/ResolveVisitor.java | 125 ++++++++++++---------
src/test/groovy/InterfaceTest.groovy | 55 +++++++--
.../groovy/transform/DelegateTransformTest.groovy | 32 ++++++
.../groovy/transform/traitx/Groovy11508.groovy} | 31 ++---
.../groovy/transform/traitx/Groovy8864.groovy} | 21 ++--
6 files changed, 213 insertions(+), 90 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/classgen/Verifier.java b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
index f45b7a0893..34c2c962f7 100644
--- a/src/main/java/org/codehaus/groovy/classgen/Verifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
@@ -103,6 +103,7 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.constX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.ctorX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.declS;
import static org.codehaus.groovy.ast.tools.GeneralUtils.fieldX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.getInterfacesAndSuperInterfaces;
import static org.codehaus.groovy.ast.tools.GeneralUtils.localVarX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.param;
import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt;
@@ -272,6 +273,10 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
};
}
+ private static Set<ClassNode> getAllInterfaces(final ClassNode cn) {
+ return getInterfacesAndSuperInterfaces(cn);
+ }
+
private static void checkForDuplicateInterfaces(final ClassNode cn) {
ClassNode[] interfaces = cn.getInterfaces();
int nInterfaces = interfaces.length;
@@ -284,6 +289,38 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
throw new RuntimeParserException("Duplicate interfaces in implements list: " + interfaceNames, cn);
}
}
+
+ // GROOVY-5106: check for same interface with different type argument(s)
+ List< Set<ClassNode> > allInterfaces = new ArrayList<>(nInterfaces + 1);
+ for (ClassNode in : interfaces) allInterfaces.add(getAllInterfaces(in));
+ allInterfaces.add(getAllInterfaces(cn.getUnresolvedSuperClass()));
+ if (nInterfaces == 1 && allInterfaces.get(1).isEmpty())
+ return; // no peer interface(s) to verify
+
+ for (int i = 0; i < nInterfaces; i += 1) {
+ for (ClassNode in : allInterfaces.get(i)) {
+ if (in.redirect().getGenericsTypes() != null) {
+ for (int j = i + 1; j < nInterfaces + 1; j += 1) {
+ Set<ClassNode> set = allInterfaces.get(j);
+ if (set.contains(in)) {
+ for (ClassNode t : set) { // find match and check generics
+ if (t.equals(in)) {
+ String one = in.toString(false), two = t.toString(false);
+ if (!one.equals(two)) {
+ String warning = String.format(
+ "The %s %s is implemented more than once with different arguments: %s and %s",
+ (Traits.isTrait(in) ? "trait" : "interface"), in.getNameWithoutPackage(), one, two);
+ Token token = new Token(0, "", cn.getLineNumber(), cn.getColumnNumber()); // ASTNode to CSTNode
+ cn.getModule().getContext().getErrorCollector().addWarning(1, warning, token, cn.getModule().getContext());
+ }
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
}
private static void checkForDuplicateMethods(final ClassNode cn) {
@@ -622,7 +659,7 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
@Override
public void visitMethod(final MethodNode node) {
- // GROOVY-3712: if it's an MOP method, it's an error as they aren't supposed to exist before ACG is invoked
+ // GROOVY-3712: if it's a MOP method, it's an error as they aren't supposed to exist before ACG is invoked
if (MopWriter.isMopMethod(node.getName())) {
throw new RuntimeParserException("Found unexpected MOP methods in the class node for " + classNode.getName() + "(" + node.getName() + ")", classNode);
}
diff --git a/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java b/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
index fd1f1dfefe..e440d4ee8c 100644
--- a/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
+++ b/src/main/java/org/codehaus/groovy/control/ResolveVisitor.java
@@ -267,29 +267,67 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
return source;
}
+ @Override
+ public void visitField(final FieldNode node) {
+ Map<GenericsTypeName, GenericsType> oldNames = genericParameterNames;
+ if (!canSeeTypeVars(node.getModifiers(), node.getDeclaringClass())) {
+ genericParameterNames = Collections.emptyMap();
+ }
+
+ if (!fieldTypesChecked.contains(node)) {
+ resolveOrFail(node.getType(), node);
+ }
+ super.visitField(node);
+
+ genericParameterNames = oldNames;
+ }
+
+ @Override
+ public void visitProperty(final PropertyNode node) {
+ Map<GenericsTypeName, GenericsType> oldNames = genericParameterNames;
+ if (!canSeeTypeVars(node.getModifiers(), node.getDeclaringClass())) {
+ genericParameterNames = Collections.emptyMap();
+ }
+
+ resolveOrFail(node.getType(), node);
+ fieldTypesChecked.add(node.getField());
+
+ super.visitProperty(node);
+
+ genericParameterNames = oldNames;
+ }
+
+ private static boolean canSeeTypeVars(final int mods, final ClassNode node) {
+ return !Modifier.isStatic(mods) || Traits.isTrait(node); // GROOVY-8864, GROOVY-11508
+ }
+
@Override
protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
VariableScope oldScope = currentScope;
currentScope = node.getVariableScope();
Map<GenericsTypeName, GenericsType> oldNames = genericParameterNames;
- genericParameterNames = node.isStatic() && !Traits.isTrait(node.getDeclaringClass())
- ? new HashMap<>() : new HashMap<>(genericParameterNames);
+ genericParameterNames =
+ canSeeTypeVars(node.getModifiers(), node.getDeclaringClass())
+ ? new HashMap<>(genericParameterNames) : new HashMap<>();
resolveGenericsHeader(node.getGenericsTypes());
+ resolveOrFail(node.getReturnType(), node);
for (Parameter p : node.getParameters()) {
p.setInitialExpression(transform(p.getInitialExpression()));
- resolveOrFail(p.getType(), p.getType());
+ ClassNode t = p.getType();
+ resolveOrFail(t, t);
visitAnnotations(p);
}
- ClassNode[] exceptions = node.getExceptions();
- for (ClassNode t : exceptions) {
- resolveOrFail(t, node);
+ if (node.getExceptions() != null) {
+ for (ClassNode t : node.getExceptions()) {
+ resolveOrFail(t, t);
+ }
}
- resolveOrFail(node.getReturnType(), node);
MethodNode oldCurrentMethod = currentMethod;
currentMethod = node;
+
super.visitConstructorOrMethod(node, isConstructor);
currentMethod = oldCurrentMethod;
@@ -297,30 +335,6 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
currentScope = oldScope;
}
- @Override
- public void visitField(final FieldNode node) {
- ClassNode t = node.getType();
- if (!fieldTypesChecked.contains(node)) {
- resolveOrFail(t, node);
- }
- super.visitField(node);
- }
-
- @Override
- public void visitProperty(final PropertyNode node) {
- Map<GenericsTypeName, GenericsType> oldPNames = genericParameterNames;
- if (node.isStatic() && !Traits.isTrait(node.getDeclaringClass())) {
- genericParameterNames = new HashMap<>();
- }
-
- ClassNode t = node.getType();
- resolveOrFail(t, node);
- super.visitProperty(node);
- fieldTypesChecked.add(node.getField());
-
- genericParameterNames = oldPNames;
- }
-
private void resolveOrFail(final ClassNode type, final ASTNode node) {
resolveOrFail(type, "", node);
}
@@ -731,7 +745,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
if (importNode != null && importNode != currImportNode) {
// static alias only for inner classes and must be at end of chain
ClassNode tmp = new ConstructedNestedClass(importNode.getType(), importNode.getFieldName());
- if (resolve(tmp, false, false, true) && (tmp.getModifiers() & Opcodes.ACC_STATIC) != 0) {
+ if (resolve(tmp, false, false, true) && Modifier.isStatic(tmp.getModifiers())) {
type.setRedirect(tmp.redirect());
return true;
}
@@ -752,7 +766,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
// At this point we know that we have a match for pname. This may
// mean, that name[pname.length()..<-1] is a static inner class.
// For this the rest of the name does not need any dots in its name.
- // It is either completely a inner static class or it is not.
+ // It is either completely an inner static class or it is not.
// Since we do not want to have useless lookups we create the name
// completely and use a ConstructedClassWithPackage to prevent lookups against the package.
String className = aliasedNode.getNameWithoutPackage() + "$" + name.substring(pname.length() + 1).replace('.', '$');
@@ -813,7 +827,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
// check package this class is defined in. The usage of ConstructedClassWithPackage here
// means, that the module package will not be involved when the
// compiler tries to find an inner class.
- ClassNode tmp = new ConstructedClassWithPackage(module.getPackageName(), name);
+ ClassNode tmp = new ConstructedClassWithPackage(module.getPackageName(), name);
if (resolve(tmp, false, false, false)) {
ambiguousClass(type, tmp, name);
return true;
@@ -823,7 +837,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
for (ImportNode importNode : module.getStaticImports().values()) {
if (importNode.getFieldName().equals(name)) {
ClassNode tmp = new ConstructedNestedClass(importNode.getType(), name);
- if (resolve(tmp, false, false, true) && (tmp.getModifiers() & Opcodes.ACC_STATIC) != 0) {
+ if (resolve(tmp, false, false, true) && Modifier.isStatic(tmp.getModifiers())) {
type.setRedirect(tmp.redirect());
return true;
}
@@ -831,7 +845,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
}
for (ImportNode importNode : module.getStaticStarImports().values()) {
ClassNode tmp = new ConstructedNestedClass(importNode.getType(), name);
- if (resolve(tmp, false, false, true) && (tmp.getModifiers() & Opcodes.ACC_STATIC) != 0) {
+ if (resolve(tmp, false, false, true) && Modifier.isStatic(tmp.getModifiers())) {
ambiguousClass(type, tmp, name);
return true;
}
@@ -840,7 +854,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
for (ImportNode importNode : module.getStarImports()) {
if (importNode.getType() != null) {
ClassNode tmp = new ConstructedNestedClass(importNode.getType(), name);
- if (resolve(tmp, false, false, true) && (tmp.getModifiers() & Opcodes.ACC_STATIC) != 0) {
+ if (resolve(tmp, false, false, true) && Modifier.isStatic(tmp.getModifiers())) {
ambiguousClass(type, tmp, name);
return true;
}
@@ -862,7 +876,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
// We do not need to check instances of LowerCaseClass
// to be a Class, because unless there was an import for
- // for this we do not lookup these cases. This was a decision
+ // this we do not look up these cases. This was a decision
// made on the mailing list. To ensure we will not visit this
// method again we set a NO_CLASS for this name
if (type instanceof LowerCaseClass) {
@@ -951,7 +965,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
doInitialClassTest = classNameInfo.getV2();
}
- if (null == name || name.length() == 0) return null;
+ if (name == null || name.length() == 0) return null;
return name.toString();
}
@@ -1089,7 +1103,7 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
addError("The class '" + type.getName() + "' needs to be an outer class of '" +
currentClass.getName() + "' when using '.this' or '.super'.", expression);
}
- if ((currentClass.getModifiers() & Opcodes.ACC_STATIC) == 0) return;
+ if (!Modifier.isStatic(currentClass.getModifiers())) return;
if (currentScope != null && !currentScope.isInStaticContext()) return;
addError("The usage of 'Class.this' and 'Class.super' within static nested class '" +
currentClass.getName() + "' is not allowed in a static context.", expression);
@@ -1100,13 +1114,6 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
visitAnnotations(ve);
Variable v = ve.getAccessedVariable();
- if(!(v instanceof DynamicVariable) && !checkingVariableTypeInDeclaration) {
- /*
- * GROOVY-4009: when a normal variable is simply being used, there is no need to try to
- * resolve its type. Variable type resolve should proceed only if the variable is being declared.
- */
- return ve;
- }
if (v instanceof DynamicVariable) {
String name = ve.getName();
ClassNode t = ClassHelper.make(name);
@@ -1132,8 +1139,14 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
for (VariableScope scope = currentScope; scope != null && !scope.isRoot(); scope = scope.getParent()) {
if (scope.removeReferencedClassVariable(ve.getName()) == null) break;
}
- return new ClassExpression(t);
+ ClassExpression ce = new ClassExpression(t);
+ ce.setSourcePosition(ve);
+ return ce;
}
+ } else if (!checkingVariableTypeInDeclaration) {
+ // GROOVY-4009: When a normal variable is simply being used, there is no need to try to
+ // resolve its type. Variable type resolve should proceed only if the variable is being declared.
+ return ve;
}
resolveOrFail(ve.getType(), ve);
ClassNode origin = ve.getOriginType();
@@ -1206,14 +1219,14 @@ public class ResolveVisitor extends ClassCodeExpressionTransformer {
protected Expression transformClosureExpression(final ClosureExpression ce) {
boolean oldInClosure = inClosure;
inClosure = true;
- for (Parameter para : getParametersSafe(ce)) {
- ClassNode t = para.getType();
- resolveOrFail(t, ce);
- visitAnnotations(para);
- if (para.hasInitialExpression()) {
- para.setInitialExpression(transform(para.getInitialExpression()));
- }
- visitAnnotations(para);
+ for (Parameter p : getParametersSafe(ce)) {
+ ClassNode t = p.getType();
+ resolveOrFail(t, t);
+ visitAnnotations(p);
+ if (p.hasInitialExpression()) {
+ p.setInitialExpression(transform(p.getInitialExpression()));
+ }
+ visitAnnotations(p);
}
Statement code = ce.getCode();
diff --git a/src/test/groovy/InterfaceTest.groovy b/src/test/groovy/InterfaceTest.groovy
index 0a1d27e5d3..96dfd86b7d 100644
--- a/src/test/groovy/InterfaceTest.groovy
+++ b/src/test/groovy/InterfaceTest.groovy
@@ -19,21 +19,54 @@
package groovy
import gls.CompilableTestSupport
+import org.codehaus.groovy.control.CompilationUnit
-class InterfaceTest extends CompilableTestSupport {
+final class InterfaceTest extends CompilableTestSupport {
void testGenericsInInterfaceMembers() {
// control
- shouldCompile """
- interface I1 {
- public <T> T copy1(T arg)
- public <U extends CharSequence> U copy2(U arg)
- public <V, W> V copy3(W arg)
- public <N extends Number> void foo()
- }
- """
+ shouldCompile '''
+ interface I {
+ def <T> T m1(T x)
+ def <U extends CharSequence> U m2(U x)
+ def <V, W> V m3(W x)
+ def <N extends Number> void m4( )
+ }
+ '''
// erroneous
- shouldNotCompile "interface I2 { public <?> copy1(arg) }"
- shouldNotCompile "interface I3 { public <? extends CharSequence> copy1(arg) }"
+ shouldNotCompile 'interface I { def <?> m(x) }'
+ shouldNotCompile 'interface I { def <? extends CharSequence> m(x) }'
+ }
+
+ // GROOVY-5106
+ void testReImplementsInterface1() {
+ new CompilationUnit(new GroovyClassLoader(this.class.classLoader)).with {
+ addSource 'X', '''
+ interface I<T> {}
+ interface J<T> extends I<T> {}
+ class X implements I<String>, J<Number> {}
+ '''
+ compile()
+
+ assert errorCollector.errorCount == 0
+ assert errorCollector.warningCount == 1
+ assert errorCollector.warnings[0].message == 'The interface I is implemented more than once with different arguments: I <String> and I <java.lang.Number>'
+ }
+ }
+
+ // GROOVY-5106
+ void testReImplementsInterface2() {
+ new CompilationUnit(new GroovyClassLoader(this.class.classLoader)).with {
+ addSource 'X', '''
+ interface I<T> {}
+ class X implements I<Number> {}
+ class Y extends X implements I<String> {}
+ '''
+ compile()
+
+ assert errorCollector.errorCount == 0
+ assert errorCollector.warningCount == 1
+ assert errorCollector.warnings[0].message == 'The interface I is implemented more than once with different arguments: I <String> and I <java.lang.Number>'
+ }
}
}
diff --git a/src/test/org/codehaus/groovy/transform/DelegateTransformTest.groovy b/src/test/org/codehaus/groovy/transform/DelegateTransformTest.groovy
index a9c87f0bb1..c6144959e3 100644
--- a/src/test/org/codehaus/groovy/transform/DelegateTransformTest.groovy
+++ b/src/test/org/codehaus/groovy/transform/DelegateTransformTest.groovy
@@ -18,6 +18,7 @@
*/
package org.codehaus.groovy.transform
+import org.codehaus.groovy.control.CompilationUnit
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.MultipleCompilationErrorsException
import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit
@@ -63,6 +64,37 @@ final class DelegateTransformTest {
'''
}
+ @Test // GROOVY-10439
+ void testDelegateImplementingInterfaceWithDifferentTypeArgumentThanOwner1() {
+ new CompilationUnit(new GroovyClassLoader(this.class.classLoader)).with {
+ addSource 'C', '''
+ class C extends ArrayList<String> {
+ @Delegate List<Number> numbers // List<String> takes precedence
+ }
+ '''
+ compile()
+
+ assert errorCollector.errorCount == 0
+ assert errorCollector.warningCount == 0
+ }
+ }
+
+ @Test // GROOVY-10439
+ void testDelegateImplementingInterfaceWithDifferentTypeArgumentThanOwner2() {
+ new CompilationUnit(new GroovyClassLoader(this.class.classLoader)).with {
+ addSource 'C', '''
+ class C extends ArrayList<String> {
+ @Delegate HashSet<Number> numbers // Set<Number> added; Verifier checks
+ }
+ '''
+ compile()
+
+ assert errorCollector.errorCount == 0
+ assert errorCollector.warningCount > 0
+ assert errorCollector.warnings[0].message == 'The interface Collection is implemented more than once with different arguments: java.util.Collection <java.lang.Number> and java.util.Collection <java.lang.String>'
+ }
+ }
+
@Test // GROOVY-5974
void testDelegateExcludes() {
assertScript '''
diff --git a/src/test/groovy/bugs/Groovy8864Bug.groovy b/src/test/org/codehaus/groovy/transform/traitx/Groovy11508.groovy
similarity index 62%
copy from src/test/groovy/bugs/Groovy8864Bug.groovy
copy to src/test/org/codehaus/groovy/transform/traitx/Groovy11508.groovy
index 27d804f23c..ddf72729e5 100644
--- a/src/test/groovy/bugs/Groovy8864Bug.groovy
+++ b/src/test/org/codehaus/groovy/transform/traitx/Groovy11508.groovy
@@ -16,25 +16,30 @@
* specific language governing permissions and limitations
* under the License.
*/
-package groovy.bugs
+package org.codehaus.groovy.transform.traitx
-import groovy.test.GroovyTestCase
+import org.junit.Test
-class Groovy8864Bug extends GroovyTestCase {
+import static groovy.test.GroovyAssert.assertScript
+
+final class Groovy11508 {
+ @Test
void testGenericsAppliedToStaticMethodsForTraits() {
assertScript '''
- trait Foo<T> {
- static T INSTANCE
- static T get(T arg) {
- null
- }
+ trait T<U> {
+ static U getYou() {
+ }
+ }
+ class C implements T<C> {
}
+ class D extends C implements T<D> {
+ }
+
+ C c = C.you
+ D d = D.you
- class Bar implements Foo<Bar> {}
- assert Bar.getMethod("get", [Bar] as Class[]).returnType == Bar
- assert Bar.getDeclaredField("Foo__INSTANCE").type == Bar
- assert Bar.getMethod("setINSTANCE", [Bar] as Class[])
- assert Bar.getMethod("getINSTANCE").returnType == Bar
+ assert C.getMethod('getYou').returnType == C
+ assert D.getMethod('getYou').returnType == D
'''
}
}
diff --git a/src/test/groovy/bugs/Groovy8864Bug.groovy b/src/test/org/codehaus/groovy/transform/traitx/Groovy8864.groovy
similarity index 74%
rename from src/test/groovy/bugs/Groovy8864Bug.groovy
rename to src/test/org/codehaus/groovy/transform/traitx/Groovy8864.groovy
index 27d804f23c..b4429cdb75 100644
--- a/src/test/groovy/bugs/Groovy8864Bug.groovy
+++ b/src/test/org/codehaus/groovy/transform/traitx/Groovy8864.groovy
@@ -16,24 +16,27 @@
* specific language governing permissions and limitations
* under the License.
*/
-package groovy.bugs
+package org.codehaus.groovy.transform.traitx
-import groovy.test.GroovyTestCase
+import org.junit.Test
-class Groovy8864Bug extends GroovyTestCase {
+import static groovy.test.GroovyAssert.assertScript
+
+final class Groovy8864 {
+ @Test
void testGenericsAppliedToStaticMethodsForTraits() {
assertScript '''
trait Foo<T> {
static T INSTANCE
- static T get(T arg) {
- null
- }
+ static T get(T t) {
+ }
+ }
+ class Bar implements Foo<Bar> {
}
- class Bar implements Foo<Bar> {}
- assert Bar.getMethod("get", [Bar] as Class[]).returnType == Bar
+ assert Bar.getMethod("get", new Class[]{Bar}).returnType == Bar
assert Bar.getDeclaredField("Foo__INSTANCE").type == Bar
- assert Bar.getMethod("setINSTANCE", [Bar] as Class[])
+ assert Bar.getMethod("setINSTANCE", new Class[]{Bar})
assert Bar.getMethod("getINSTANCE").returnType == Bar
'''
}