-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
JandexUtil.java
363 lines (327 loc) · 14.5 KB
/
JandexUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package io.quarkus.deployment.util;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ArrayType;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.ClassType;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.ParameterizedType;
import org.jboss.jandex.Type;
import org.jboss.jandex.Type.Kind;
import org.jboss.jandex.TypeVariable;
import io.quarkus.builder.BuildException;
/**
* A collection of Jandex utility methods.
*/
public final class JandexUtil {
public final static DotName DOTNAME_OBJECT = DotName.createSimple(Object.class.getName());
public final static DotName DOTNAME_RECORD = DotName.createSimple("java.lang.Record");
private JandexUtil() {
}
/**
* Returns the captured generic types of an interface given a class that at some point in the class
* hierarchy implements the interface.
*
* The list contains the types in the same order as they are generic parameters defined on the interface
*
* A result is only returned if and only if all the generics where captured. If any of them where not defined by the class
* an exception is thrown.
*
* Also note that all parts of the class/interface hierarchy must be in the supplied index
*
* As an example, imagine the following class:
*
* <pre>
*
* class MyList implements List<String> {
* ...
* }
*
* </pre>
*
* If we call
*
* <pre>
*
* JandexUtil.resolveTypeParameters(DotName.createSimple(MyList.class.getName()),
* DotName.createSimple(List.class.getName()), index)
*
* </pre>
*
* then the result will contain a single element of class ClassType whose name() would return a DotName for String
*/
public static List<Type> resolveTypeParameters(DotName input, DotName target, IndexView index) {
final ClassInfo inputClassInfo;
try {
inputClassInfo = fetchFromIndex(input, index);
} catch (Exception e) {
// keep compatibility with what clients already expect
throw new IllegalArgumentException("Couldn't fetch '" + input.toString() + "' class from index", e);
}
Type startingType = getType(inputClassInfo, index);
Set<DotName> unindexedClasses = new LinkedHashSet<>();
final List<Type> result = findParametersRecursively(startingType, target,
new HashSet<>(), index, unindexedClasses);
// null means not found
if (result == null) {
if (unindexedClasses.isEmpty()) {
// no un-indexed classes means that there were no problems traversing the class and interface hierarchies
return Collections.emptyList();
}
throw new IllegalArgumentException(
"The following classes were not part of the index and could be the reason that the captured generic type of '"
+ target + "' could not be determined: " + unindexedClasses);
}
return result;
}
/**
* Creates a type for a ClassInfo
*/
private static Type getType(ClassInfo inputClassInfo, IndexView index) {
List<TypeVariable> typeParameters = inputClassInfo.typeParameters();
if (typeParameters.isEmpty())
return ClassType.create(inputClassInfo.name(), Kind.CLASS);
Type owner = null;
// ignore owners for non-static classes
if (inputClassInfo.enclosingClass() != null && !Modifier.isStatic(inputClassInfo.flags())) {
owner = getType(fetchFromIndex(inputClassInfo.enclosingClass(), index), index);
}
return ParameterizedType.create(inputClassInfo.name(), typeParameters.toArray(new Type[0]), owner);
}
/**
* Finds the type arguments passed from the starting type to the given target type, mapping
* generics when found, on the way down. Returns null if not found.
*/
private static List<Type> findParametersRecursively(Type type, DotName target,
Set<DotName> visitedTypes, IndexView index, Set<DotName> unindexedClasses) {
DotName name = type.name();
// cache results first
if (!visitedTypes.add(name)) {
return null;
}
// always end at Object or Record
if (DOTNAME_OBJECT.equals(name) || DOTNAME_RECORD.equals(name)) {
return null;
}
final ClassInfo inputClassInfo = fetchFromIndex(name, index);
// look at the current type
if (target.equals(name)) {
Type thisType = getType(inputClassInfo, index);
if (thisType.kind() == Kind.CLASS)
return Collections.emptyList();
else
return thisType.asParameterizedType().arguments();
}
// superclasses first
Type superClassType = inputClassInfo.superClassType();
try {
List<Type> superResult = findParametersRecursively(superClassType, target, visitedTypes, index, unindexedClasses);
if (superResult != null) {
// map any returned type parameters to our type arguments on the way down
return mapTypeArguments(superClassType, superResult, index);
}
} catch (ClassNotIndexedException e) {
unindexedClasses.add(e.dotName);
}
// interfaces second
for (Type interfaceType : inputClassInfo.interfaceTypes()) {
try {
List<Type> ret = findParametersRecursively(interfaceType, target, visitedTypes, index, unindexedClasses);
if (ret != null) {
// map any returned type parameters to our type arguments on the way down
return mapTypeArguments(interfaceType, ret, index);
}
} catch (ClassNotIndexedException e) {
unindexedClasses.add(e.dotName);
}
}
// not found
return null;
}
/**
* Maps any type parameters in typeArgumentsFromSupertype from the type parameters declared in appliedType's declaration
* to the type arguments we passed in appliedType
*/
private static List<Type> mapTypeArguments(Type appliedType, List<Type> typeArgumentsFromSupertype, IndexView index) {
// no type arguments to map
if (typeArgumentsFromSupertype.isEmpty()) {
return typeArgumentsFromSupertype;
}
// extra easy if all the type args don't contain any type parameters
if (!containsTypeParameters(typeArgumentsFromSupertype)) {
return typeArgumentsFromSupertype;
}
// this can't fail since we got a result
ClassInfo superType = fetchFromIndex(appliedType.name(), index);
// if our supertype has no type parameters, we don't need any mapping
if (superType.typeParameters().isEmpty()) {
return typeArgumentsFromSupertype;
}
// figure out which arguments we passed to the supertype
List<Type> appliedArguments;
// we passed them explicitly
if (appliedType.kind() == Kind.PARAMETERIZED_TYPE) {
appliedArguments = appliedType.asParameterizedType().arguments();
} else {
// raw supertype: use bounds
appliedArguments = new ArrayList<>(superType.typeParameters().size());
for (TypeVariable typeVariable : superType.typeParameters()) {
if (!typeVariable.bounds().isEmpty()) {
appliedArguments.add(typeVariable.bounds().get(0));
} else {
appliedArguments.add(ClassType.create(DOTNAME_OBJECT, Kind.CLASS));
}
}
}
// it's a problem if we got different arguments to the parameters declared
if (appliedArguments.size() != superType.typeParameters().size()) {
throw new IllegalArgumentException("Our supertype instance " + appliedType
+ " does not match supertype declared arguments: " + superType.typeParameters());
}
// build the mapping
Map<String, Type> mapping = new HashMap<>();
for (int i = 0; i < superType.typeParameters().size(); i++) {
TypeVariable typeParameter = superType.typeParameters().get(i);
mapping.put(typeParameter.identifier(), appliedArguments.get(i));
}
// and map
return mapGenerics(typeArgumentsFromSupertype, mapping);
}
private static boolean containsTypeParameters(List<Type> typeArgumentsFromSupertype) {
for (Type type : typeArgumentsFromSupertype) {
if (containsTypeParameters(type)) {
return true;
}
}
return false;
}
private static boolean containsTypeParameters(Type type) {
switch (type.kind()) {
case ARRAY:
return containsTypeParameters(type.asArrayType().component());
case PARAMETERIZED_TYPE:
ParameterizedType parameterizedType = type.asParameterizedType();
if (parameterizedType.owner() != null
&& containsTypeParameters(parameterizedType.owner()))
return true;
return containsTypeParameters(parameterizedType.arguments());
case TYPE_VARIABLE:
return true;
default:
return false;
}
}
private static List<Type> mapGenerics(List<Type> types, Map<String, Type> mapping) {
List<Type> ret = new ArrayList<>(types.size());
for (Type type : types) {
ret.add(mapGenerics(type, mapping));
}
return ret;
}
private static Type mapGenerics(Type type, Map<String, Type> mapping) {
switch (type.kind()) {
case ARRAY:
ArrayType arrayType = type.asArrayType();
return ArrayType.create(mapGenerics(arrayType.component(), mapping), arrayType.dimensions());
case CLASS:
return type;
case PARAMETERIZED_TYPE:
ParameterizedType parameterizedType = type.asParameterizedType();
Type owner = null;
if (parameterizedType.owner() != null) {
owner = mapGenerics(parameterizedType.owner(), mapping);
}
return ParameterizedType.create(parameterizedType.name(),
mapGenerics(parameterizedType.arguments(), mapping).toArray(new Type[0]), owner);
case TYPE_VARIABLE:
Type ret = mapping.get(type.asTypeVariable().identifier());
if (ret == null) {
throw new IllegalArgumentException("Missing type argument mapping for " + type);
}
return ret;
default:
throw new IllegalArgumentException("Illegal type in hierarchy: " + type);
}
}
private static ClassInfo fetchFromIndex(DotName dotName, IndexView index) {
final ClassInfo classInfo = index.getClassByName(dotName);
if (classInfo == null) {
throw new ClassNotIndexedException(dotName);
}
return classInfo;
}
/**
* Returns the enclosing class of the given annotation instance. For field, method or record component annotations,
* this will return the enclosing class. For parameters, this will return the enclosing class of the enclosing
* method. For classes, it will return the class itself. For type annotations, it will return the class enclosing
* the annotated type usage.
*
* @param annotationInstance the annotation whose enclosing class to look up
* @return the enclosing class
*/
public static ClassInfo getEnclosingClass(AnnotationInstance annotationInstance) {
return getEnclosingClass(annotationInstance.target());
}
private static ClassInfo getEnclosingClass(AnnotationTarget annotationTarget) {
switch (annotationTarget.kind()) {
case FIELD:
return annotationTarget.asField().declaringClass();
case METHOD:
return annotationTarget.asMethod().declaringClass();
case METHOD_PARAMETER:
return annotationTarget.asMethodParameter().method().declaringClass();
case RECORD_COMPONENT:
return annotationTarget.asRecordComponent().declaringClass();
case CLASS:
return annotationTarget.asClass();
case TYPE:
return getEnclosingClass(annotationTarget.asType().enclosingTarget());
default:
throw new RuntimeException(); // this should not occur
}
}
/**
* Returns true if the given Jandex ClassInfo is a subclass of the given <tt>parentName</tt>. Note that this will
* not check interfaces.
*
* @param index the index to use to look up super classes.
* @param info the ClassInfo we want to check.
* @param parentName the name of the superclass we want to find.
* @return true if the given ClassInfo has <tt>parentName</tt> as a superclass.
* @throws BuildException if one of the superclasses is not indexed.
*/
public static boolean isSubclassOf(IndexView index, ClassInfo info, DotName parentName) throws BuildException {
if (info.superName().equals(DOTNAME_OBJECT) || info.superName().equals(DOTNAME_RECORD)) {
return false;
}
if (info.superName().equals(parentName)) {
return true;
}
// climb up the hierarchy of classes
Type superType = info.superClassType();
ClassInfo superClass = index.getClassByName(superType.name());
if (superClass == null) {
// this can happens if the parent is not inside the Jandex index
throw new BuildException("The class " + superType.name() + " is not inside the Jandex index",
Collections.emptyList());
}
return isSubclassOf(index, superClass, parentName);
}
private static class ClassNotIndexedException extends RuntimeException {
private final DotName dotName;
public ClassNotIndexedException(DotName dotName) {
super("'" + dotName.toString() + "' is not indexed");
this.dotName = dotName;
}
}
}