You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/07/28 23:02:04 UTC
(groovy) branch master updated: GROOVY-12206: Ingest type-use annotations when reading compiled classes
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/master by this push:
new 2ea432993e GROOVY-12206: Ingest type-use annotations when reading compiled classes
2ea432993e is described below
commit 2ea432993e7b7da1fa52708244d050c535eed01b
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Jul 28 18:59:37 2026 +1000
GROOVY-12206: Ingest type-use annotations when reading compiled classes
---
.../groovy/ast/decompiled/Annotations.java | 153 ++++++++++++++++++---
.../groovy/ast/decompiled/AsmDecompiler.java | 27 +++-
.../ast/decompiled/ClassSignatureParser.java | 30 ++--
.../codehaus/groovy/ast/decompiled/ClassStub.java | 100 +++++++-------
.../ast/decompiled/MemberSignatureParser.java | 17 +++
.../org/codehaus/groovy/vmplugin/v16/Java16.java | 2 +-
.../org/codehaus/groovy/vmplugin/v8/Java8.java | 119 +++++++++++++++-
.../groovy/ast/decompiled/AsmDecompilerTest.groovy | 84 +++++++++++
.../ast/decompiled/AsmDecompilerTestData.java | 20 +++
.../ReflectionTypeAnnotationsTest.groovy | 104 ++++++++++++++
.../groovy/ast/decompiled/support/WhereAnno.java | 35 +++++
.../groovy/groovy/typecheckers/NullChecker.groovy | 28 +++-
.../src/spec/doc/typecheckers.adoc | 3 +
.../groovy/typecheckers/NullCheckerTest.groovy | 45 ++++++
.../typecheckers/support/JSpecifyExample.java | 38 +++++
15 files changed, 724 insertions(+), 81 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/ast/decompiled/Annotations.java b/src/main/java/org/codehaus/groovy/ast/decompiled/Annotations.java
index a1f9352e0f..e98e9d41fe 100644
--- a/src/main/java/org/codehaus/groovy/ast/decompiled/Annotations.java
+++ b/src/main/java/org/codehaus/groovy/ast/decompiled/Annotations.java
@@ -21,6 +21,7 @@ package org.codehaus.groovy.ast.decompiled;
import org.codehaus.groovy.ast.AnnotatedNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.expr.AnnotationConstantExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
@@ -29,6 +30,8 @@ import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.vmplugin.VMPluginFactory;
import org.objectweb.asm.Type;
+import org.objectweb.asm.TypePath;
+import org.objectweb.asm.TypeReference;
import java.lang.reflect.Array;
import java.util.List;
@@ -197,30 +200,148 @@ class Annotations {
}
/**
- * Applies type annotations (JSR 308) extracted from bytecode to a {@link ClassNode}.
- * Type annotations provide runtime metadata about generic type usages and are stored separately
- * from declaration annotations according to JVMS §4.7.20-4.7.21.
+ * Applies the type annotations (JSR 308) targeting the given position to the given type,
+ * walking each annotation's type path (JVMS §4.7.20.2) to locate the exact annotated type
+ * within the possibly generic or array type.
*
- * <p>Like regular annotations, type annotations whose classes cannot be resolved are silently skipped.
+ * <p>The returned node may differ from the input node: type annotations may only be attached
+ * to per-use redirect nodes, so shared (cached) nodes are replaced by an annotated
+ * {@link ClassNode#getPlainNodeReference(boolean) plain node reference} when required.
+ * A type annotation lands in {@link ClassNode#getTypeAnnotations()} of the per-use node at
+ * the exact JVMS position: an empty type path denotes the outermost type at the given site,
+ * so for {@code String @A []} the annotation ends up on the array node while for
+ * {@code @A String []} (type path "[") it ends up on the component node.
*
- * @param <T> the class node type parameter
- * @param stub the {@link AnnotatedTypeStub} containing bytecode type annotations
- * @param node the target {@link ClassNode} to attach type annotations to
+ * <p>Like regular annotations, type annotations whose classes cannot be resolved are silently
+ * skipped, as are annotations whose position cannot be mapped onto the AST (e.g. type
+ * arguments of a raw type use).
+ *
+ * @param stubs the type annotations of the enclosing class or member, or {@code null}
+ * @param sort the {@link TypeReference} sort identifying the targeted position
+ * @param index the position index (formal parameter, exception, supertype or type parameter
+ * index) or {@code -1} for positions without an index (fields, method return types,
+ * the superclass)
+ * @param type the resolved type at that position
* @param resolver the {@link AsmReferenceResolver} used to resolve annotation class types
- * @return the input node with type annotations applied (for method chaining)
- * @see org.codehaus.groovy.ast.ClassNode#addTypeAnnotation(AnnotationNode)
+ * @return the annotated type: either the input node or a per-use replacement for it
+ * @see ClassNode#addTypeAnnotation(AnnotationNode)
*/
- static <T extends ClassNode> T addTypeAnnotations(AnnotatedTypeStub stub, T node, AsmReferenceResolver resolver) {
- List<TypeAnnotationStub> annotations = stub.getTypeAnnotations();
- if (annotations != null) {
- for (TypeAnnotationStub annotation : annotations) {
- AnnotationNode annotationNode = createAnnotationNode(annotation, resolver);
+ static ClassNode applyTypeAnnotations(List<TypeAnnotationStub> stubs, int sort, int index, ClassNode type, AsmReferenceResolver resolver) {
+ if (stubs != null) {
+ for (TypeAnnotationStub stub : stubs) {
+ TypeReference reference = new TypeReference(stub.typeRef);
+ if (reference.getSort() != sort || positionIndex(reference) != index) continue;
+ AnnotationNode annotationNode = createAnnotationNode(stub, resolver);
if (annotationNode != null) {
- node.addTypeAnnotation(annotationNode);
+ TypePath typePath = stub.typePath == null ? null : TypePath.fromString(stub.typePath);
+ type = attach(type, typePath, 0, annotationNode);
}
}
}
- return node;
+ return type;
+ }
+
+ /**
+ * Extracts the position index from a type reference for sorts that carry one,
+ * mirroring the {@code index} parameter of
+ * {@link #applyTypeAnnotations(List, int, int, ClassNode, AsmReferenceResolver)}.
+ *
+ * @param reference the type reference
+ * @return the formal parameter, exception, supertype ({@code -1} for the superclass) or
+ * type parameter index, or {@code -1} for sorts without an index
+ */
+ private static int positionIndex(TypeReference reference) {
+ switch (reference.getSort()) {
+ case TypeReference.CLASS_EXTENDS:
+ return reference.getSuperTypeIndex();
+ case TypeReference.METHOD_FORMAL_PARAMETER:
+ return reference.getFormalParameterIndex();
+ case TypeReference.THROWS:
+ return reference.getExceptionIndex();
+ case TypeReference.CLASS_TYPE_PARAMETER:
+ case TypeReference.METHOD_TYPE_PARAMETER:
+ return reference.getTypeParameterIndex();
+ default:
+ return -1;
+ }
+ }
+
+ /**
+ * Walks the remaining type path steps into the structure of the given type and attaches
+ * the annotation to the addressed type. Steps that cannot be mapped onto the AST cause
+ * the annotation to be dropped silently, so that reading arbitrary bytecode never fails.
+ *
+ * @param type the type to walk into
+ * @param typePath the type path, or {@code null} for the type itself
+ * @param step the current step within the type path
+ * @param annotation the annotation to attach
+ * @return the annotated type: either the input node or a per-use replacement for it
+ */
+ private static ClassNode attach(ClassNode type, TypePath typePath, int step, AnnotationNode annotation) {
+ if (typePath == null || step >= typePath.getLength()) {
+ return annotate(type, annotation);
+ }
+ switch (typePath.getStep(step)) {
+ case TypePath.ARRAY_ELEMENT: {
+ if (!type.isArray()) return type;
+ ClassNode componentType = type.getComponentType();
+ ClassNode newComponentType = attach(componentType, typePath, step + 1, annotation);
+ if (newComponentType == componentType) return type;
+ ClassNode newType = newComponentType.makeArray();
+ for (AnnotationNode existing : type.getTypeAnnotations()) {
+ newType = annotate(newType, existing);
+ }
+ return newType;
+ }
+ case TypePath.TYPE_ARGUMENT: {
+ GenericsType[] genericsTypes = type.getGenericsTypes();
+ int i = typePath.getStepArgument(step);
+ if (genericsTypes == null || i >= genericsTypes.length) return type; // raw type use
+ GenericsType genericsType = genericsTypes[i];
+ if (step + 1 < typePath.getLength() && typePath.getStep(step + 1) == TypePath.WILDCARD_BOUND) {
+ ClassNode[] upperBounds = genericsType.getUpperBounds();
+ ClassNode lowerBound = genericsType.getLowerBound();
+ if (upperBounds != null && upperBounds.length > 0) {
+ upperBounds[0] = attach(upperBounds[0], typePath, step + 2, annotation);
+ } else if (lowerBound != null) {
+ ClassNode newLowerBound = attach(lowerBound, typePath, step + 2, annotation);
+ if (newLowerBound != lowerBound) {
+ GenericsType newGenericsType = new GenericsType(genericsType.getType(), null, newLowerBound);
+ newGenericsType.setWildcard(genericsType.isWildcard());
+ genericsTypes[i] = newGenericsType;
+ }
+ }
+ } else {
+ genericsType.setType(attach(genericsType.getType(), typePath, step + 1, annotation));
+ }
+ return type;
+ }
+ case TypePath.INNER_TYPE:
+ // Groovy models a nested type use with a single ClassNode, so annotations on
+ // the nested type are treated as annotations on the whole type
+ return attach(type, typePath, step + 1, annotation);
+ default: // WILDCARD_BOUND without a preceding TYPE_ARGUMENT step: malformed
+ return type;
+ }
+ }
+
+ /**
+ * Attaches the annotation to the given type, first substituting a per-use
+ * {@link ClassNode#getPlainNodeReference(boolean) plain node reference} if the type is a
+ * shared node: type annotations belong to a single use of a type and must never be attached
+ * to the globally shared (cached or resolved) nodes; see
+ * {@link ClassNode#addTypeAnnotation(AnnotationNode)}.
+ *
+ * @param type the type to annotate
+ * @param annotation the annotation to attach
+ * @return the annotated type: either the input node or a per-use replacement for it
+ */
+ private static ClassNode annotate(ClassNode type, AnnotationNode annotation) {
+ if (!type.isRedirectNode()) {
+ type = type.getPlainNodeReference(false);
+ }
+ type.addTypeAnnotation(annotation);
+ return type;
}
/**
diff --git a/src/main/java/org/codehaus/groovy/ast/decompiled/AsmDecompiler.java b/src/main/java/org/codehaus/groovy/ast/decompiled/AsmDecompiler.java
index a37e219ae8..5f3837f80a 100644
--- a/src/main/java/org/codehaus/groovy/ast/decompiled/AsmDecompiler.java
+++ b/src/main/java/org/codehaus/groovy/ast/decompiled/AsmDecompiler.java
@@ -218,6 +218,11 @@ public abstract class AsmDecompiler {
return readAnnotationMembers(stub.addAnnotation(desc));
}
+ @Override
+ public AnnotationVisitor visitTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) {
+ return readAnnotationMembers(stub.addTypeAnnotation(desc, typeRef, typePath));
+ }
+
@Override
public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) {
if (stub.parameterAnnotations == null) stub.parameterAnnotations = new HashMap<>(1);
@@ -257,6 +262,21 @@ public abstract class AsmDecompiler {
return readAnnotationMembers(result.addAnnotation(desc));
}
+ /**
+ * Visits class-level type annotations (JSR 308), such as annotations on the
+ * superclass, superinterfaces or type parameters of the class declaration.
+ *
+ * @param typeRef the annotated type position (ASM {@link org.objectweb.asm.TypeReference} value)
+ * @param typePath the path to the annotated type within the type given by {@code typeRef}, or {@code null}
+ * @param desc the annotation type descriptor
+ * @param visible {@code true} for runtime-visible annotations
+ * @return an annotation visitor to collect member values
+ */
+ @Override
+ public AnnotationVisitor visitTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) {
+ return readAnnotationMembers(result.addTypeAnnotation(desc, typeRef, typePath));
+ }
+
/**
* Visits permitted subclasses declared in a sealed class.
*
@@ -290,7 +310,7 @@ public abstract class AsmDecompiler {
@Override
public AnnotationVisitor visitTypeAnnotation(final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
- return readAnnotationMembers(recordComponentStub.addTypeAnnotation(descriptor));
+ return readAnnotationMembers(recordComponentStub.addTypeAnnotation(descriptor, typeRef, typePath));
}
};
}
@@ -316,6 +336,11 @@ public abstract class AsmDecompiler {
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
return readAnnotationMembers(stub.addAnnotation(desc));
}
+
+ @Override
+ public AnnotationVisitor visitTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) {
+ return readAnnotationMembers(stub.addTypeAnnotation(desc, typeRef, typePath));
+ }
};
}
}
diff --git a/src/main/java/org/codehaus/groovy/ast/decompiled/ClassSignatureParser.java b/src/main/java/org/codehaus/groovy/ast/decompiled/ClassSignatureParser.java
index 3a756eed29..3a45674272 100644
--- a/src/main/java/org/codehaus/groovy/ast/decompiled/ClassSignatureParser.java
+++ b/src/main/java/org/codehaus/groovy/ast/decompiled/ClassSignatureParser.java
@@ -22,6 +22,7 @@ import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.RecordComponentNode;
import org.objectweb.asm.Type;
+import org.objectweb.asm.TypeReference;
import org.objectweb.asm.signature.SignatureReader;
import org.objectweb.asm.signature.SignatureVisitor;
@@ -77,12 +78,13 @@ class ClassSignatureParser {
*/
static void configureClass(final ClassNode classNode, final ClassStub stub, final AsmReferenceResolver resolver) {
if (stub.signature != null) {
- parseClassSignature(classNode, stub.signature, resolver);
+ parseClassSignature(classNode, stub, resolver);
return;
}
if (stub.superName != null) {
ClassNode sc = resolver.resolveClass(AsmDecompiler.fromInternalName(stub.superName));
+ sc = Annotations.applyTypeAnnotations(stub.typeAnnotations, TypeReference.CLASS_EXTENDS, -1, sc, resolver);
classNode.setSuperClass(sc);
}
@@ -91,6 +93,7 @@ class ClassSignatureParser {
ClassNode[] interfaces = new ClassNode[nInterfaces];
for (int i = 0; i < nInterfaces; i += 1) { String name = stub.interfaceNames[i];
interfaces[i] = resolver.resolveClass(AsmDecompiler.fromInternalName(name));
+ interfaces[i] = Annotations.applyTypeAnnotations(stub.typeAnnotations, TypeReference.CLASS_EXTENDS, i, interfaces[i], resolver);
}
classNode.setInterfaces(interfaces);
}
@@ -119,9 +122,10 @@ class ClassSignatureParser {
type[0] = type[0].getPlainNodeReference();
}
+ type[0] = Annotations.applyTypeAnnotations(rc.typeAnnotations, TypeReference.FIELD, -1, type[0], resolver);
+
RecordComponentNode recordComponent = new RecordComponentNode(classNode, rc.name, type[0]);
Annotations.addAnnotations(rc, recordComponent, resolver);
- Annotations.addTypeAnnotations(rc, type[0], resolver);
recordComponents.add(recordComponent);
}
classNode.setRecordComponents(recordComponents);
@@ -143,7 +147,7 @@ class ClassSignatureParser {
* represents: {@code <T extends Number> extends AbstractList<T> implements Serializable}
*
* @param classNode the class node to configure (modified in place with superclass, interfaces, and generics)
- * @param signature the generic signature string from the class's Signature attribute, in JVMS format
+ * @param stub the ASM-derived class metadata containing the generic signature and type annotations
* @param resolver used to resolve class types from internal names to ClassNodes
*
* @see FormalParameterParser for parsing type parameter declarations
@@ -151,7 +155,7 @@ class ClassSignatureParser {
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se19/html/jvms-4.html#jvms-ClassSignature">
* JVMS §4.7.9.1 ClassSignature Production</a>
*/
- private static void parseClassSignature(final ClassNode classNode, final String signature, final AsmReferenceResolver resolver) {
+ private static void parseClassSignature(final ClassNode classNode, final ClassStub stub, final AsmReferenceResolver resolver) {
List<ClassNode> interfaces = new ArrayList<>();
FormalParameterParser parser = new FormalParameterParser(resolver) {
@@ -161,7 +165,8 @@ class ClassSignatureParser {
return new TypeSignatureParser(resolver) {
@Override
void finished(final ClassNode superClass) {
- classNode.setSuperClass(superClass);
+ classNode.setSuperClass(Annotations.applyTypeAnnotations(
+ stub.typeAnnotations, TypeReference.CLASS_EXTENDS, -1, superClass, resolver));
}
};
}
@@ -171,17 +176,26 @@ class ClassSignatureParser {
return new TypeSignatureParser(resolver) {
@Override
void finished(final ClassNode superInterface) {
- interfaces.add(superInterface);
+ interfaces.add(Annotations.applyTypeAnnotations(
+ stub.typeAnnotations, TypeReference.CLASS_EXTENDS, interfaces.size(), superInterface, resolver));
}
};
}
};
- new SignatureReader(signature).accept(parser);
+ new SignatureReader(stub.signature).accept(parser);
classNode.setInterfaces(interfaces.isEmpty() ? ClassNode.EMPTY_ARRAY :
interfaces.toArray(ClassNode.EMPTY_ARRAY));
GenericsType[] typeParameters = parser.getTypeParameters();
- if (typeParameters.length > 0) classNode.setGenericsTypes(typeParameters);
+ if (typeParameters.length > 0) {
+ if (stub.typeAnnotations != null) {
+ for (int i = 0, n = typeParameters.length; i < n; i += 1) {
+ typeParameters[i].setType(Annotations.applyTypeAnnotations(
+ stub.typeAnnotations, TypeReference.CLASS_TYPE_PARAMETER, i, typeParameters[i].getType(), resolver));
+ }
+ }
+ classNode.setGenericsTypes(typeParameters);
+ }
}
}
diff --git a/src/main/java/org/codehaus/groovy/ast/decompiled/ClassStub.java b/src/main/java/org/codehaus/groovy/ast/decompiled/ClassStub.java
index 94adeebe4e..89a4430959 100644
--- a/src/main/java/org/codehaus/groovy/ast/decompiled/ClassStub.java
+++ b/src/main/java/org/codehaus/groovy/ast/decompiled/ClassStub.java
@@ -18,6 +18,8 @@
*/
package org.codehaus.groovy.ast.decompiled;
+import org.objectweb.asm.TypePath;
+
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -162,14 +164,19 @@ interface AnnotatedTypeStub {
/**
* Bytecode stub for a class member carrying annotation metadata.
- * Base class for {@link MethodStub} and {@link FieldStub}.
+ * Base class for {@link ClassStub}, {@link MethodStub}, {@link FieldStub} and {@link RecordComponentStub}.
*/
-class MemberStub implements AnnotatedStub {
+class MemberStub implements AnnotatedStub, AnnotatedTypeStub {
/**
* List of annotations, lazily initialized when the first annotation is added.
*/
List<AnnotationStub> annotations = null;
+ /**
+ * List of type annotations (JSR 308), lazily initialized when the first type annotation is added.
+ */
+ List<TypeAnnotationStub> typeAnnotations = null;
+
/**
* Adds an annotation to this member stub.
*
@@ -183,10 +190,30 @@ class MemberStub implements AnnotatedStub {
return stub;
}
+ /**
+ * Adds a type annotation to this member stub, preserving its position information.
+ *
+ * @param desc the annotation descriptor (JVMS format)
+ * @param typeRef the ASM {@link org.objectweb.asm.TypeReference} value
+ * @param typePath the {@link org.objectweb.asm.TypePath} or {@code null} for the type itself
+ * @return the newly created {@link TypeAnnotationStub}
+ */
+ TypeAnnotationStub addTypeAnnotation(String desc, int typeRef, TypePath typePath) {
+ TypeAnnotationStub stub = new TypeAnnotationStub(desc, typeRef, typePath == null ? null : typePath.toString());
+ if (typeAnnotations == null) typeAnnotations = new ArrayList<TypeAnnotationStub>(1);
+ typeAnnotations.add(stub);
+ return stub;
+ }
+
@Override
public List<AnnotationStub> getAnnotations() {
return annotations;
}
+
+ @Override
+ public List<TypeAnnotationStub> getTypeAnnotations() {
+ return typeAnnotations;
+ }
}
/**
@@ -355,12 +382,29 @@ class AnnotationStub {
*/
class TypeAnnotationStub extends AnnotationStub {
/**
- * Creates a type annotation stub from its type.
+ * The annotated type position as an ASM {@link org.objectweb.asm.TypeReference} value
+ * (JVMS 4.7.20 target_type and target_info).
+ */
+ final int typeRef;
+
+ /**
+ * The path to the annotated type argument, wildcard bound, array element type or static
+ * inner type within the type given by {@link #typeRef}, in {@link org.objectweb.asm.TypePath}
+ * string format, or {@code null} if the annotation targets the type itself (JVMS 4.7.20.2).
+ */
+ final String typePath;
+
+ /**
+ * Creates a type annotation stub from its type and position information.
*
* @param className the fully qualified annotation class name
+ * @param typeRef the ASM {@link org.objectweb.asm.TypeReference} value
+ * @param typePath the type path in string format, or {@code null} for the type itself
*/
- public TypeAnnotationStub(String className) {
+ public TypeAnnotationStub(String className, int typeRef, String typePath) {
super(className);
+ this.typeRef = typeRef;
+ this.typePath = typePath;
}
}
@@ -417,7 +461,7 @@ class EnumConstantWrapper {
*
* @see RecordComponentNode
*/
-class RecordComponentStub implements AnnotatedStub, AnnotatedTypeStub {
+class RecordComponentStub extends MemberStub {
/**
* Component name, corresponding to both the field and the accessor method name.
*/
@@ -434,16 +478,6 @@ class RecordComponentStub implements AnnotatedStub, AnnotatedTypeStub {
*/
final String signature;
- /**
- * List of annotations attached to this record component, lazily initialized.
- */
- List<AnnotationStub> annotations;
-
- /**
- * List of type annotations (JSR 308) attached to this record component, lazily initialized.
- */
- List<TypeAnnotationStub> typeAnnotations;
-
/**
* Creates a record component stub from bytecode metadata.
*
@@ -456,40 +490,4 @@ class RecordComponentStub implements AnnotatedStub, AnnotatedTypeStub {
this.descriptor = descriptor;
this.signature = signature;
}
-
- /**
- * Adds an annotation to this record component.
- *
- * @param desc the annotation descriptor (JVMS format)
- * @return the newly created {@link AnnotationStub}
- */
- AnnotationStub addAnnotation(String desc) {
- AnnotationStub stub = new AnnotationStub(desc);
- if (annotations == null) annotations = new ArrayList<AnnotationStub>(1);
- annotations.add(stub);
- return stub;
- }
-
- @Override
- public List<AnnotationStub> getAnnotations() {
- return annotations;
- }
-
- /**
- * Adds a type annotation to this record component.
- *
- * @param desc the annotation descriptor (JVMS format)
- * @return the newly created {@link TypeAnnotationStub}
- */
- public TypeAnnotationStub addTypeAnnotation(String desc) {
- TypeAnnotationStub stub = new TypeAnnotationStub(desc);
- if (typeAnnotations == null) typeAnnotations = new ArrayList<TypeAnnotationStub>(1);
- typeAnnotations.add(stub);
- return stub;
- }
-
- @Override
- public List<TypeAnnotationStub> getTypeAnnotations() {
- return typeAnnotations;
- }
}
diff --git a/src/main/java/org/codehaus/groovy/ast/decompiled/MemberSignatureParser.java b/src/main/java/org/codehaus/groovy/ast/decompiled/MemberSignatureParser.java
index 7c7d162d4f..b8a21bf17e 100644
--- a/src/main/java/org/codehaus/groovy/ast/decompiled/MemberSignatureParser.java
+++ b/src/main/java/org/codehaus/groovy/ast/decompiled/MemberSignatureParser.java
@@ -29,6 +29,7 @@ import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.tools.GenericsUtils;
import org.objectweb.asm.Type;
+import org.objectweb.asm.TypeReference;
import org.objectweb.asm.signature.SignatureReader;
import org.objectweb.asm.signature.SignatureVisitor;
@@ -103,6 +104,7 @@ class MemberSignatureParser {
// ex: java.util.Collections#EMPTY_LIST/EMPTY_MAP/EMPTY_SET
type[0] = GenericsUtils.nonGeneric(type[0]);
}
+ type[0] = Annotations.applyTypeAnnotations(field.typeAnnotations, TypeReference.FIELD, -1, type[0], resolver);
return new FieldNode(field.fieldName, field.accessModifiers, type[0], owner, field.value != null ? new ConstantExpression(field.value, true) : null);
}
@@ -192,6 +194,21 @@ class MemberSignatureParser {
}
}
+ if (method.typeAnnotations != null) {
+ returnType[0] = Annotations.applyTypeAnnotations(method.typeAnnotations, TypeReference.METHOD_RETURN, -1, returnType[0], resolver);
+ for (int i = 0, n = parameterTypes.length; i < n; i += 1) {
+ parameterTypes[i] = Annotations.applyTypeAnnotations(method.typeAnnotations, TypeReference.METHOD_FORMAL_PARAMETER, i, parameterTypes[i], resolver);
+ }
+ for (int i = 0, n = exceptionTypes.length; i < n; i += 1) {
+ exceptionTypes[i] = Annotations.applyTypeAnnotations(method.typeAnnotations, TypeReference.THROWS, i, exceptionTypes[i], resolver);
+ }
+ if (typeParameters != null) {
+ for (int i = 0, n = typeParameters.length; i < n; i += 1) {
+ typeParameters[i].setType(Annotations.applyTypeAnnotations(method.typeAnnotations, TypeReference.METHOD_TYPE_PARAMETER, i, typeParameters[i].getType(), resolver));
+ }
+ }
+ }
+
int nParameters = parameterTypes.length;
Parameter[] parameters = new Parameter[nParameters];
List<String> parameterNames = method.parameterNames;
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v16/Java16.java b/src/main/java/org/codehaus/groovy/vmplugin/v16/Java16.java
index 3d599142d3..2cb8aaa924 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v16/Java16.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v16/Java16.java
@@ -104,7 +104,7 @@ public class Java16 extends Java10 {
protected void makeRecordComponents(final CompileUnit cu, final ClassNode cn, final Class<?> c) {
if (c.isRecord()) cn.setRecordComponents(Arrays.stream(c.getRecordComponents()).map(rc -> {
ClassNode type = makeClassNode(cu, rc.getGenericType(), rc.getType());
- type.addTypeAnnotations(Arrays.stream(rc.getAnnotatedType().getAnnotations()).map(this::toAnnotationNode).collect(Collectors.toList()));
+ type = applyTypeAnnotations(rc.getAnnotatedType(), type);
return new RecordComponentNode(cn, rc.getName(), type, Arrays.stream(rc.getAnnotations()).map(this::toAnnotationNode).collect(Collectors.toList()));
}).collect(Collectors.toList()));
}
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/Java8.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/Java8.java
index 124aa94fbd..524a78afde 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/Java8.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/Java8.java
@@ -52,6 +52,10 @@ import java.lang.annotation.Target;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.AnnotatedArrayType;
+import java.lang.reflect.AnnotatedParameterizedType;
+import java.lang.reflect.AnnotatedType;
+import java.lang.reflect.AnnotatedWildcardType;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
@@ -250,6 +254,9 @@ public class Java8 implements VMPlugin {
ClassNode t = configureTypeVariableReference(tp[i].getName());
ClassNode[] bounds = configureTypes(tp[i].getBounds());
gt[i] = configureTypeVariableDefinition(t, bounds);
+ for (Annotation annotation : tp[i].getAnnotations()) {
+ gt[i].setType(addTypeAnnotation(gt[i].getType(), annotation));
+ }
}
return gt;
}
@@ -348,6 +355,7 @@ public class Java8 implements VMPlugin {
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
ClassNode rt = makeClassNode(compileUnit, f.getGenericType(), f.getType());
+ rt = applyTypeAnnotations(f.getAnnotatedType(), rt);
FieldNode fn = new FieldNode(f.getName(), f.getModifiers(), rt, classNode, getValue(f));
setAnnotationMetaData(f.getAnnotations(), fn);
classNode.addField(fn);
@@ -355,8 +363,10 @@ public class Java8 implements VMPlugin {
Method[] methods = ReflectionUtils.getDeclaredMethodsSorted(clazz);
for (Method m : methods) {
ClassNode rt = makeClassNode(compileUnit, m.getGenericReturnType(), m.getReturnType());
+ rt = applyTypeAnnotations(m.getAnnotatedReturnType(), rt);
Parameter[] params = makeParameters(compileUnit, m.getGenericParameterTypes(), m.getParameterTypes(), m.getParameterAnnotations(), m);
ClassNode[] exceptions = makeClassNodes(compileUnit, m.getGenericExceptionTypes(), m.getExceptionTypes());
+ applyExceptionTypeAnnotations(m, exceptions);
MethodNode mn = new MethodNode(m.getName(), m.getModifiers(), rt, params, exceptions, null);
setAnnotationMetaData(m.getAnnotations(), mn);
if (m.getDefaultValue() != null) {
@@ -371,12 +381,18 @@ public class Java8 implements VMPlugin {
for (Constructor<?> c : constructors) {
Parameter[] params = makeParameters(compileUnit, c.getGenericParameterTypes(), c.getParameterTypes(), getConstructorParameterAnnotations(c), c);
ClassNode[] exceptions = makeClassNodes(compileUnit, c.getGenericExceptionTypes(), c.getExceptionTypes());
+ applyExceptionTypeAnnotations(c, exceptions);
ConstructorNode cn = classNode.addConstructor(c.getModifiers(), params, exceptions, null);
setAnnotationMetaData(c.getAnnotations(), cn);
}
Class<?> sc = clazz.getSuperclass();
- if (sc != null) classNode.setUnresolvedSuperClass(makeClassNode(compileUnit, clazz.getGenericSuperclass(), sc));
+ if (sc != null) {
+ ClassNode superClass = makeClassNode(compileUnit, clazz.getGenericSuperclass(), sc);
+ AnnotatedType annotatedSuperclass = clazz.getAnnotatedSuperclass();
+ if (annotatedSuperclass != null) superClass = applyTypeAnnotations(annotatedSuperclass, superClass);
+ classNode.setUnresolvedSuperClass(superClass);
+ }
makeInterfaceTypes(compileUnit, classNode, clazz);
makePermittedSubclasses(compileUnit, classNode, clazz);
makeRecordComponents(compileUnit, classNode, clazz);
@@ -498,6 +514,10 @@ public class Java8 implements VMPlugin {
}
ret[i] = makeClassNode(cu, interfaceTypes[i], (Class<?>) type);
}
+ AnnotatedType[] annotatedInterfaces = clazz.getAnnotatedInterfaces();
+ for (int i = 0, m = Math.min(annotatedInterfaces.length, n); i < m; i += 1) {
+ ret[i] = applyTypeAnnotations(annotatedInterfaces[i], ret[i]);
+ }
classNode.setInterfaces(ret);
}
}
@@ -531,6 +551,81 @@ public class Java8 implements VMPlugin {
return back.getPlainNodeReference();
}
+ /**
+ * Applies type-use annotations (JSR 308) of the given annotated type to the given class node,
+ * recursing into type arguments, wildcard bounds and array component types. The returned node
+ * may differ from the input node: type annotations may only be attached to per-use redirect
+ * nodes, so shared (cached) nodes are replaced by an annotated plain node reference.
+ *
+ * @param annotatedType the reflective annotated type at some position (e.g. a method return type)
+ * @param classNode the class node created for that position
+ * @return the annotated class node: either the input node or a per-use replacement for it
+ * @since 6.0.0
+ */
+ protected ClassNode applyTypeAnnotations(final AnnotatedType annotatedType, ClassNode classNode) {
+ for (Annotation annotation : annotatedType.getAnnotations()) {
+ classNode = addTypeAnnotation(classNode, annotation);
+ }
+ if (annotatedType instanceof AnnotatedParameterizedType) {
+ AnnotatedType[] typeArguments = ((AnnotatedParameterizedType) annotatedType).getAnnotatedActualTypeArguments();
+ GenericsType[] genericsTypes = classNode.getGenericsTypes();
+ if (genericsTypes != null) {
+ for (int i = 0, n = Math.min(typeArguments.length, genericsTypes.length); i < n; i += 1) {
+ if (typeArguments[i] instanceof AnnotatedWildcardType) {
+ applyWildcardTypeAnnotations((AnnotatedWildcardType) typeArguments[i], genericsTypes, i);
+ } else {
+ genericsTypes[i].setType(applyTypeAnnotations(typeArguments[i], genericsTypes[i].getType()));
+ }
+ }
+ }
+ } else if (annotatedType instanceof AnnotatedArrayType && classNode.isArray()) {
+ ClassNode componentType = classNode.getComponentType();
+ ClassNode newComponentType = applyTypeAnnotations(((AnnotatedArrayType) annotatedType).getAnnotatedGenericComponentType(), componentType);
+ if (newComponentType != componentType) {
+ ClassNode newClassNode = newComponentType.makeArray();
+ for (AnnotationNode annotationNode : classNode.getTypeAnnotations()) {
+ if (!newClassNode.isRedirectNode()) newClassNode = newClassNode.getPlainNodeReference(false);
+ newClassNode.addTypeAnnotation(annotationNode);
+ }
+ classNode = newClassNode;
+ }
+ }
+ return classNode;
+ }
+
+ private void applyWildcardTypeAnnotations(final AnnotatedWildcardType wildcardType, final GenericsType[] genericsTypes, final int i) {
+ GenericsType genericsType = genericsTypes[i];
+ for (Annotation annotation : wildcardType.getAnnotations()) {
+ genericsType.setType(addTypeAnnotation(genericsType.getType(), annotation));
+ }
+ AnnotatedType[] annotatedLowerBounds = wildcardType.getAnnotatedLowerBounds();
+ ClassNode lowerBound = genericsType.getLowerBound();
+ if (annotatedLowerBounds.length > 0 && lowerBound != null) {
+ ClassNode newLowerBound = applyTypeAnnotations(annotatedLowerBounds[0], lowerBound);
+ if (newLowerBound != lowerBound) {
+ GenericsType newGenericsType = new GenericsType(genericsType.getType(), null, newLowerBound);
+ newGenericsType.setWildcard(true);
+ genericsTypes[i] = newGenericsType;
+ }
+ } else {
+ ClassNode[] upperBounds = genericsType.getUpperBounds();
+ AnnotatedType[] annotatedUpperBounds = wildcardType.getAnnotatedUpperBounds();
+ if (upperBounds != null) {
+ for (int j = 0, m = Math.min(annotatedUpperBounds.length, upperBounds.length); j < m; j += 1) {
+ upperBounds[j] = applyTypeAnnotations(annotatedUpperBounds[j], upperBounds[j]);
+ }
+ }
+ }
+ }
+
+ private ClassNode addTypeAnnotation(ClassNode classNode, final Annotation annotation) {
+ // shared/cached nodes must not be mutated; substitute a per-use proxy,
+ // which is where type annotations belong
+ if (!classNode.isRedirectNode()) classNode = classNode.getPlainNodeReference(false);
+ classNode.addTypeAnnotation(toAnnotationNode(annotation));
+ return classNode;
+ }
+
private Parameter[] makeParameters(final CompileUnit cu, final Type[] types, final Class<?>[] cls, final Annotation[][] parameterAnnotations, final Member member) {
Parameter[] params = Parameter.EMPTY_ARRAY;
final int n = types.length;
@@ -542,10 +637,32 @@ public class Java8 implements VMPlugin {
setAnnotationMetaData(parameterAnnotations[i],
params[i] = new Parameter(makeClassNode(cu, types[i], cls[i]), names[i]));
}
+ // synthetic parameters (e.g. of inner class constructors) may not be
+ // included in the annotated parameter types; skip on length mismatch
+ AnnotatedType[] annotatedTypes = ((java.lang.reflect.Executable) member).getAnnotatedParameterTypes();
+ if (annotatedTypes.length == n) {
+ for (int i = 0; i < n; i += 1) {
+ params[i].setType(applyTypeAnnotations(annotatedTypes[i], params[i].getType()));
+ }
+ }
}
return params;
}
+ /**
+ * Applies type-use annotations on the {@code throws} clause of the given executable
+ * to the corresponding exception class nodes.
+ *
+ * @param member the reflective executable member
+ * @param exceptions the exception class nodes created for the member
+ */
+ private void applyExceptionTypeAnnotations(final java.lang.reflect.Executable member, final ClassNode[] exceptions) {
+ AnnotatedType[] annotatedTypes = member.getAnnotatedExceptionTypes();
+ for (int i = 0, n = Math.min(annotatedTypes.length, exceptions.length); i < n; i += 1) {
+ exceptions[i] = applyTypeAnnotations(annotatedTypes[i], exceptions[i]);
+ }
+ }
+
/**
* Populates parameter names from the supplied reflective executable member.
*
diff --git a/src/test/groovy/org/codehaus/groovy/ast/decompiled/AsmDecompilerTest.groovy b/src/test/groovy/org/codehaus/groovy/ast/decompiled/AsmDecompilerTest.groovy
index 37e32c0626..c73853f774 100644
--- a/src/test/groovy/org/codehaus/groovy/ast/decompiled/AsmDecompilerTest.groovy
+++ b/src/test/groovy/org/codehaus/groovy/ast/decompiled/AsmDecompilerTest.groovy
@@ -387,6 +387,90 @@ final class AsmDecompilerTest {
assert !ClassHelper.VOID_TYPE.annotated
}
+ // GROOVY-12206
+ @Test
+ void "type use annotations on member types"() {
+ def node = decompile(MoreTypeAnnotations)
+
+ assert annos(node.getDeclaredField('annotatedField').type) == ['field']
+ assert annos(node.getDeclaredField('genericField').type) == []
+ assert annos(node.getDeclaredField('genericField').type.genericsTypes[0].type) == ['fieldArg']
+ assert annos(node.getDeclaredField('nestedGenericField').type.genericsTypes[1].type.genericsTypes[0].type) == ['nested']
+
+ def method = node.getDeclaredMethods('returnAnnotated')[0]
+ assert annos(method.returnType) == ['return']
+ assert annos(node.getDeclaredMethods('returnGenericAnnotated')[0].returnType.genericsTypes[0].type) == ['returnArg']
+
+ def params = node.getDeclaredMethods('params')[0].parameters
+ assert annos(params[0].type) == ['p0']
+ assert annos(params[1].type) == []
+ assert annos(params[2].type.genericsTypes[0].type) == ['p2']
+
+ def exceptions = node.getDeclaredMethods('throwsAnnotated')[0].exceptions
+ assert annos(exceptions[0]) == []
+ assert annos(exceptions[1]) == ['ex']
+
+ assert annos(node.getDeclaredMethods('typeParamAnnotated')[0].genericsTypes[0].type) == ['mtp']
+ }
+
+ // GROOVY-12206
+ @Test
+ void "type use annotations on array member types"() {
+ def node = decompile(MoreTypeAnnotations)
+
+ def arrayType = node.getDeclaredField('arrayField').type
+ assert arrayType.array
+ assert annos(arrayType) == ['arr']
+ assert annos(arrayType.componentType) == ['elem']
+
+ def primitiveArrayType = node.getDeclaredField('primitiveArrayField').type
+ assert annos(primitiveArrayType) == ['primArr']
+ assert annos(primitiveArrayType.componentType) == []
+ assert primitiveArrayType.componentType == ClassHelper.int_TYPE
+
+ assert annos(node.getDeclaredField('genericArrayField').type.genericsTypes[0].type.componentType) == ['arrayArg']
+ }
+
+ // GROOVY-12206
+ @Test
+ void "type use annotations on wildcard bounds"() {
+ def node = decompile(MoreTypeAnnotations)
+
+ def upper = node.getDeclaredField('upperBoundField').type.genericsTypes[0]
+ assert upper.wildcard
+ assert annos(upper.upperBounds[0]) == ['upper']
+
+ def lower = node.getDeclaredField('lowerBoundField').type.genericsTypes[0]
+ assert lower.wildcard
+ assert annos(lower.lowerBound) == ['lower']
+
+ def wild = node.getDeclaredField('wildcardField').type.genericsTypes[0]
+ assert wild.wildcard
+ assert annos(wild.type) == ['wild']
+ }
+
+ // GROOVY-12206
+ @Test
+ void "type use annotations on supertypes and type parameters"() {
+ def node = decompile(MoreTypeAnnotations)
+
+ assert annos(node.unresolvedSuperClass) == ['super']
+ def intf = node.interfaces[0]
+ assert annos(intf) == ['intf']
+ assert annos(intf.genericsTypes[0].type) == ['intfArg']
+ assert annos(node.genericsTypes[0].type) == ['tp']
+
+ // shared nodes must not pick up the per-use annotations
+ assert !ClassHelper.STRING_TYPE.annotated
+ assert ClassHelper.STRING_TYPE.typeAnnotations.isEmpty()
+ assert ClassHelper.int_TYPE.typeAnnotations.isEmpty()
+ assert decompile(SuperClass).typeAnnotations.isEmpty()
+ }
+
+ private static List<String> annos(ClassNode type) {
+ type.typeAnnotations.collect { ((ConstantExpression) it.getMember('value')).text }
+ }
+
//--------------------------------------------------------------------------
private static ClassNode decompile(Class clazz = AsmDecompilerTestData) {
diff --git a/src/test/groovy/org/codehaus/groovy/ast/decompiled/AsmDecompilerTestData.java b/src/test/groovy/org/codehaus/groovy/ast/decompiled/AsmDecompilerTestData.java
index a4e639ba41..b52403b4f2 100644
--- a/src/test/groovy/org/codehaus/groovy/ast/decompiled/AsmDecompilerTestData.java
+++ b/src/test/groovy/org/codehaus/groovy/ast/decompiled/AsmDecompilerTestData.java
@@ -19,6 +19,7 @@
package org.codehaus.groovy.ast.decompiled;
import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.decompiled.support.WhereAnno;
import java.io.IOException;
import java.lang.annotation.ElementType;
@@ -125,3 +126,22 @@ abstract class WithTypeAnnotations extends @TypeAnno Object implements @TypeAnno
}
@TypeAnno Object field;
}
+
+@SuppressWarnings("unused")
+abstract class MoreTypeAnnotations<@WhereAnno("tp") T> extends @WhereAnno("super") SuperClass implements @WhereAnno("intf") Intf<@WhereAnno("intfArg") String> {
+ @WhereAnno("field") String annotatedField;
+ List<@WhereAnno("fieldArg") String> genericField;
+ Map<String, List<@WhereAnno("nested") Integer>> nestedGenericField;
+ @WhereAnno("elem") String @WhereAnno("arr") [] arrayField;
+ int @WhereAnno("primArr") [] primitiveArrayField;
+ List<? extends @WhereAnno("upper") Number> upperBoundField;
+ List<? super @WhereAnno("lower") Number> lowerBoundField;
+ List<@WhereAnno("wild") ?> wildcardField;
+ List<@WhereAnno("arrayArg") String[]> genericArrayField;
+
+ abstract @WhereAnno("return") String returnAnnotated();
+ abstract List<@WhereAnno("returnArg") String> returnGenericAnnotated();
+ abstract void params(@WhereAnno("p0") String p0, int i, List<@WhereAnno("p2") String> p2);
+ abstract void throwsAnnotated() throws IOException, @WhereAnno("ex") ClassNotFoundException;
+ abstract <@WhereAnno("mtp") M> M typeParamAnnotated(M m);
+}
diff --git a/src/test/groovy/org/codehaus/groovy/ast/decompiled/ReflectionTypeAnnotationsTest.groovy b/src/test/groovy/org/codehaus/groovy/ast/decompiled/ReflectionTypeAnnotationsTest.groovy
new file mode 100644
index 0000000000..b7eb64697e
--- /dev/null
+++ b/src/test/groovy/org/codehaus/groovy/ast/decompiled/ReflectionTypeAnnotationsTest.groovy
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.codehaus.groovy.ast.decompiled
+
+import org.codehaus.groovy.ast.ClassHelper
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.expr.ConstantExpression
+import org.junit.jupiter.api.Test
+
+/**
+ * Tests that the reflection path ({@code VMPlugin#configureClassNode}) ingests type-use
+ * annotations from {@code java.lang.reflect.AnnotatedType}, mirroring the checks that
+ * {@link AsmDecompilerTest} performs for the bytecode decompiler path (GROOVY-12206).
+ * The same fixture classes from {@code AsmDecompilerTestData.java} are used, but here
+ * they are loaded via reflection rather than decompiled from the class file.
+ */
+final class ReflectionTypeAnnotationsTest {
+
+ private static final ClassNode node = ClassHelper.make(MoreTypeAnnotations)
+
+ @Test
+ void "type use annotations on member types"() {
+ assert annos(node.getDeclaredField('annotatedField').type) == ['field']
+ assert annos(node.getDeclaredField('genericField').type) == []
+ assert annos(node.getDeclaredField('genericField').type.genericsTypes[0].type) == ['fieldArg']
+ assert annos(node.getDeclaredField('nestedGenericField').type.genericsTypes[1].type.genericsTypes[0].type) == ['nested']
+
+ assert annos(node.getDeclaredMethods('returnAnnotated')[0].returnType) == ['return']
+ assert annos(node.getDeclaredMethods('returnGenericAnnotated')[0].returnType.genericsTypes[0].type) == ['returnArg']
+
+ def params = node.getDeclaredMethods('params')[0].parameters
+ assert annos(params[0].type) == ['p0']
+ assert annos(params[1].type) == []
+ assert annos(params[2].type.genericsTypes[0].type) == ['p2']
+
+ def exceptions = node.getDeclaredMethods('throwsAnnotated')[0].exceptions
+ assert annos(exceptions[0]) == []
+ assert annos(exceptions[1]) == ['ex']
+
+ assert annos(node.getDeclaredMethods('typeParamAnnotated')[0].genericsTypes[0].type) == ['mtp']
+ }
+
+ @Test
+ void "type use annotations on array member types"() {
+ def arrayType = node.getDeclaredField('arrayField').type
+ assert arrayType.array
+ assert annos(arrayType) == ['arr']
+ assert annos(arrayType.componentType) == ['elem']
+
+ def primitiveArrayType = node.getDeclaredField('primitiveArrayField').type
+ assert annos(primitiveArrayType) == ['primArr']
+ assert annos(primitiveArrayType.componentType) == []
+
+ assert annos(node.getDeclaredField('genericArrayField').type.genericsTypes[0].type.componentType) == ['arrayArg']
+ }
+
+ @Test
+ void "type use annotations on wildcard bounds"() {
+ def upper = node.getDeclaredField('upperBoundField').type.genericsTypes[0]
+ assert upper.wildcard
+ assert annos(upper.upperBounds[0]) == ['upper']
+
+ def lower = node.getDeclaredField('lowerBoundField').type.genericsTypes[0]
+ assert lower.wildcard
+ assert annos(lower.lowerBound) == ['lower']
+
+ def wild = node.getDeclaredField('wildcardField').type.genericsTypes[0]
+ assert wild.wildcard
+ assert annos(wild.type) == ['wild']
+ }
+
+ @Test
+ void "type use annotations on supertypes and type parameters"() {
+ assert annos(node.unresolvedSuperClass) == ['super']
+ def intf = node.interfaces[0]
+ assert annos(intf) == ['intf']
+ assert annos(intf.genericsTypes[0].type) == ['intfArg']
+ assert annos(node.genericsTypes[0].type) == ['tp']
+
+ // shared nodes must not pick up the per-use annotations
+ assert ClassHelper.STRING_TYPE.typeAnnotations.isEmpty()
+ assert ClassHelper.int_TYPE.typeAnnotations.isEmpty()
+ }
+
+ private static List<String> annos(ClassNode type) {
+ type.typeAnnotations.collect { ((ConstantExpression) it.getMember('value')).text }
+ }
+}
diff --git a/src/test/groovy/org/codehaus/groovy/ast/decompiled/support/WhereAnno.java b/src/test/groovy/org/codehaus/groovy/ast/decompiled/support/WhereAnno.java
new file mode 100644
index 0000000000..b872fd503c
--- /dev/null
+++ b/src/test/groovy/org/codehaus/groovy/ast/decompiled/support/WhereAnno.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.codehaus.groovy.ast.decompiled.support;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Type-use annotation with a {@code value} member locating the annotated position,
+ * used by type annotation ingestion tests (GROOVY-12206). Public so that the
+ * reflection path can read its members.
+ */
+@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface WhereAnno {
+ String value();
+}
diff --git a/subprojects/groovy-typecheckers/src/main/groovy/groovy/typecheckers/NullChecker.groovy b/subprojects/groovy-typecheckers/src/main/groovy/groovy/typecheckers/NullChecker.groovy
index e7ebb5a9c9..a07306cfbb 100644
--- a/subprojects/groovy-typecheckers/src/main/groovy/groovy/typecheckers/NullChecker.groovy
+++ b/subprojects/groovy-typecheckers/src/main/groovy/groovy/typecheckers/NullChecker.groovy
@@ -21,8 +21,10 @@ package groovy.typecheckers
import org.apache.groovy.lang.annotation.Incubating
import org.apache.groovy.typecheckers.CheckingVisitor
import org.codehaus.groovy.ast.AnnotatedNode
+import org.codehaus.groovy.ast.ClassNode
import org.codehaus.groovy.ast.FieldNode
import org.codehaus.groovy.ast.MethodNode
+import org.codehaus.groovy.ast.Parameter
import org.codehaus.groovy.ast.Variable
import org.codehaus.groovy.ast.expr.BinaryExpression
import org.codehaus.groovy.ast.expr.CastExpression
@@ -355,16 +357,36 @@ class NullChecker extends GroovyTypeCheckingExtensionSupport.TypeCheckingDSL {
//--------------------------------------------------------------------------
private static boolean hasNullableAnno(AnnotatedNode node) {
- node.annotations?.any { it.classNode?.nameWithoutPackage in NULLABLE_ANNOS } ?: false
+ hasAnno(node, NULLABLE_ANNOS)
}
private static boolean hasNonNullAnno(AnnotatedNode node) {
if (node.getNodeMetaData(StaticTypesMarker.INFERRED_NON_NULL) == Boolean.TRUE) return true
- node.annotations?.any { it.classNode?.nameWithoutPackage in NONNULL_ANNOS } ?: false
+ hasAnno(node, NONNULL_ANNOS)
}
private static boolean hasMonotonicAnno(AnnotatedNode node) {
- node.annotations?.any { it.classNode?.nameWithoutPackage in MONOTONIC_ANNOS } ?: false
+ hasAnno(node, MONOTONIC_ANNOS)
+ }
+
+ /**
+ * Checks the node's declaration annotations and, for methods, parameters and fields,
+ * also the type-use annotations of the declared type. Type-use only annotations
+ * (e.g. JSpecify's) appear on the type rather than the declaration, in particular
+ * for classes read from bytecode or via reflection.
+ */
+ private static boolean hasAnno(AnnotatedNode node, Set<String> annoNames) {
+ if (node.annotations?.any { it.classNode?.nameWithoutPackage in annoNames }) return true
+ typeOf(node)?.typeAnnotations?.any { it.classNode?.nameWithoutPackage in annoNames } ?: false
+ }
+
+ private static ClassNode typeOf(AnnotatedNode node) {
+ switch (node) {
+ case MethodNode: return ((MethodNode) node).returnType
+ case Parameter: return ((Parameter) node).type
+ case FieldNode: return ((FieldNode) node).type
+ default: return null
+ }
}
private static boolean hasNullCheckAnno(AnnotatedNode node) {
diff --git a/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc b/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc
index 351feab070..7ce1fd4a2a 100644
--- a/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc
+++ b/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc
@@ -644,6 +644,9 @@ any package are supported. The following annotation names are recognized:
|===
The annotation classes must be on the compile classpath so the Groovy compiler can resolve them.
+Both declaration-targeted and type-use (`ElementType.TYPE_USE`) annotations are recognized,
+including type-use annotations found in already compiled Java or Groovy classes on the classpath,
+where they reside in type-annotation bytecode attributes rather than on the member declarations.
Since the checker matches by simple name, you are free to choose any annotation library:
* https://jspecify.dev/[JSpecify]: `@Nullable` / `@NullMarked` / `@NullUnmarked`
diff --git a/subprojects/groovy-typecheckers/src/test/groovy/groovy/typecheckers/NullCheckerTest.groovy b/subprojects/groovy-typecheckers/src/test/groovy/groovy/typecheckers/NullCheckerTest.groovy
index 1297733f11..22b2806eb0 100644
--- a/subprojects/groovy-typecheckers/src/test/groovy/groovy/typecheckers/NullCheckerTest.groovy
+++ b/subprojects/groovy-typecheckers/src/test/groovy/groovy/typecheckers/NullCheckerTest.groovy
@@ -644,6 +644,51 @@ final class NullCheckerTest {
'''
}
+ // === JSpecify annotations from precompiled Java (GROOVY-12206) ===
+
+ @Test
+ void testJSpecifyNullableReturnFromPrecompiledClass() {
+ def err = shouldFail shell, '''
+ import groovy.typecheckers.support.JSpecifyExample
+
+ class Foo {
+ static void bar() {
+ JSpecifyExample.findValue('missing').toUpperCase()
+ }
+ }
+ '''
+ assert err.message.contains("Potential null dereference: 'findValue()' may return null")
+ }
+
+ @Test
+ void testJSpecifyNonNullParameterOfPrecompiledClass() {
+ def err = shouldFail shell, '''
+ import groovy.typecheckers.support.JSpecifyExample
+
+ class Foo {
+ static void bar() {
+ JSpecifyExample.requireValue(null)
+ }
+ }
+ '''
+ assert err.message.contains('Cannot pass null to @NonNull parameter')
+ }
+
+ @Test
+ void testJSpecifyNullableResultPassedToNonNullParameterOfPrecompiledClass() {
+ def err = shouldFail strictShell, '''
+ import groovy.typecheckers.support.JSpecifyExample
+
+ class Foo {
+ static void bar() {
+ def v = JSpecifyExample.findValue('missing')
+ JSpecifyExample.requireValue(v)
+ }
+ }
+ '''
+ assert err.message.contains('Cannot pass @Nullable value to @NonNull parameter')
+ }
+
// === Unannotated code ===
@Test
diff --git a/subprojects/groovy-typecheckers/src/test/groovy/groovy/typecheckers/support/JSpecifyExample.java b/subprojects/groovy-typecheckers/src/test/groovy/groovy/typecheckers/support/JSpecifyExample.java
new file mode 100644
index 0000000000..6db2ab13a6
--- /dev/null
+++ b/subprojects/groovy-typecheckers/src/test/groovy/groovy/typecheckers/support/JSpecifyExample.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.typecheckers.support;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * Precompiled Java class using JSpecify's TYPE_USE nullness annotations, consumed by
+ * {@code NullCheckerTest} to verify that type-use annotations are ingested when reading
+ * compiled classes (GROOVY-12206). JSpecify annotations target {@code TYPE_USE} only,
+ * so they end up in type-annotation bytecode attributes rather than on the declarations.
+ */
+public class JSpecifyExample {
+ public static @Nullable String findValue(String key) {
+ return "example".equals(key) ? "value" : null;
+ }
+
+ public static @NonNull String requireValue(@NonNull String value) {
+ return value;
+ }
+}