-
Notifications
You must be signed in to change notification settings - Fork 1k
/
AbstractJavaElement.java
510 lines (466 loc) · 20.4 KB
/
AbstractJavaElement.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/*
* Copyright 2017-2020 original authors
*
* Licensed 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
*
* https://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 io.micronaut.annotation.processing.visitor;
import io.micronaut.annotation.processing.AnnotationUtils;
import io.micronaut.core.annotation.AnnotationMetadata;
import io.micronaut.core.annotation.AnnotationValue;
import io.micronaut.core.annotation.AnnotationValueBuilder;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.util.ArgumentUtils;
import io.micronaut.inject.annotation.AbstractAnnotationMetadataBuilder;
import io.micronaut.inject.ast.ClassElement;
import io.micronaut.inject.ast.ElementModifier;
import io.micronaut.inject.ast.MemberElement;
import io.micronaut.inject.ast.PrimitiveElement;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.IntersectionType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.UnionType;
import javax.lang.model.type.WildcardType;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PROTECTED;
import static javax.lang.model.element.Modifier.PUBLIC;
/**
* An abstract class for other elements to extend from.
*
* @author James Kleeh
* @author graemerocher
* @since 1.0
*/
public abstract class AbstractJavaElement implements io.micronaut.inject.ast.Element {
private final Element element;
private final JavaVisitorContext visitorContext;
private AnnotationMetadata annotationMetadata;
/**
* @param element The {@link Element}
* @param annotationMetadata The Annotation metadata
* @param visitorContext The Java visitor context
*/
AbstractJavaElement(Element element, AnnotationMetadata annotationMetadata, JavaVisitorContext visitorContext) {
this.element = element;
this.annotationMetadata = annotationMetadata;
this.visitorContext = visitorContext;
}
@NonNull
@Override
public <T extends Annotation> io.micronaut.inject.ast.Element annotate(@NonNull String annotationType, @NonNull Consumer<AnnotationValueBuilder<T>> consumer) {
ArgumentUtils.requireNonNull("annotationType", annotationType);
ArgumentUtils.requireNonNull("consumer", consumer);
final AnnotationValueBuilder<T> builder = AnnotationValue.builder(annotationType);
consumer.accept(builder);
final AnnotationValue<T> av = builder.build();
AnnotationUtils annotationUtils = visitorContext
.getAnnotationUtils();
annotationMetadata = annotationUtils
.newAnnotationBuilder()
.annotate(annotationMetadata, av);
updateMetadataCaches();
return this;
}
@Override
public <T extends Annotation> io.micronaut.inject.ast.Element annotate(AnnotationValue<T> annotationValue) {
ArgumentUtils.requireNonNull("annotationValue", annotationValue);
AnnotationUtils annotationUtils = visitorContext
.getAnnotationUtils();
annotationMetadata = annotationUtils
.newAnnotationBuilder()
.annotate(annotationMetadata, annotationValue);
updateMetadataCaches();
return this;
}
@Override
public io.micronaut.inject.ast.Element removeAnnotation(@NonNull String annotationType) {
ArgumentUtils.requireNonNull("annotationType", annotationType);
try {
AnnotationUtils annotationUtils = visitorContext
.getAnnotationUtils();
annotationMetadata = annotationUtils
.newAnnotationBuilder()
.removeAnnotation(annotationMetadata, annotationType);
return this;
} finally {
updateMetadataCaches();
}
}
@Override
public <T extends Annotation> io.micronaut.inject.ast.Element removeAnnotationIf(@NonNull Predicate<AnnotationValue<T>> predicate) {
//noinspection ConstantConditions
if (predicate != null) {
try {
AnnotationUtils annotationUtils = visitorContext
.getAnnotationUtils();
annotationMetadata = annotationUtils
.newAnnotationBuilder()
.removeAnnotationIf(annotationMetadata, predicate);
return this;
} finally {
updateMetadataCaches();
}
}
return this;
}
@Override
public io.micronaut.inject.ast.Element removeStereotype(@NonNull String annotationType) {
ArgumentUtils.requireNonNull("annotationType", annotationType);
try {
AnnotationUtils annotationUtils = visitorContext
.getAnnotationUtils();
annotationMetadata = annotationUtils
.newAnnotationBuilder()
.removeStereotype(annotationMetadata, annotationType);
return this;
} finally {
updateMetadataCaches();
}
}
private void updateMetadataCaches() {
String declaringTypeName = resolveDeclaringTypeName();
AbstractAnnotationMetadataBuilder.addMutatedMetadata(declaringTypeName, element, annotationMetadata);
AnnotationUtils.invalidateMetadata(element);
}
private String resolveDeclaringTypeName() {
String declaringTypeName;
if (this instanceof MemberElement) {
final ClassElement owningType = ((MemberElement) this).getOwningType();
final Element nativeType = (Element) owningType.getNativeType();
declaringTypeName = resolveCanonicalName(nativeType);
} else {
final Object nativeType = getNativeType();
if (nativeType instanceof TypeVariable) {
declaringTypeName = resolveCanonicalName(((TypeVariable) nativeType).asElement());
} else if (nativeType instanceof Element) {
declaringTypeName = resolveCanonicalName((Element) nativeType);
} else {
throw new IllegalStateException("Cannot determine type name from: " + nativeType);
}
}
return declaringTypeName;
}
private String resolveCanonicalName(Element nativeType) {
String declaringTypeName;
TypeElement typeElement = visitorContext.getModelUtils().classElementFor(nativeType);
if (typeElement == null) {
declaringTypeName = getName();
} else {
declaringTypeName = typeElement.getQualifiedName().toString();
}
return declaringTypeName;
}
@Override
public boolean isPackagePrivate() {
Set<Modifier> modifiers = element.getModifiers();
return !(modifiers.contains(PUBLIC)
|| modifiers.contains(PROTECTED)
|| modifiers.contains(PRIVATE));
}
@Override
public String getName() {
return element.getSimpleName().toString();
}
@Override
public Set<ElementModifier> getModifiers() {
return element
.getModifiers().stream()
.map(m -> ElementModifier.valueOf(m.name()))
.collect(Collectors.toSet());
}
@Override
public Optional<String> getDocumentation() {
String doc = visitorContext.getElements().getDocComment(element);
return Optional.ofNullable(doc != null ? doc.trim() : null);
}
@Override
public boolean isAbstract() {
return hasModifier(Modifier.ABSTRACT);
}
@Override
public boolean isStatic() {
return hasModifier(Modifier.STATIC);
}
@Override
public boolean isPublic() {
return hasModifier(Modifier.PUBLIC);
}
@Override
public boolean isPrivate() {
return hasModifier(Modifier.PRIVATE);
}
@Override
public boolean isFinal() {
return hasModifier(Modifier.FINAL);
}
@Override
public boolean isProtected() {
return hasModifier(Modifier.PROTECTED);
}
@Override
public Object getNativeType() {
return element;
}
@Override
public AnnotationMetadata getAnnotationMetadata() {
return annotationMetadata;
}
@Override
public String toString() {
return element.toString();
}
/**
* Returns a class element with aligned generic information.
* @param typeMirror The type mirror
* @param visitorContext The visitor context
* @param declaredGenericInfo The declared generic info
* @return The class element
*/
protected @NonNull ClassElement parameterizedClassElement(
TypeMirror typeMirror,
JavaVisitorContext visitorContext,
Map<String, Map<String, TypeMirror>> declaredGenericInfo) {
return mirrorToClassElement(
typeMirror,
visitorContext,
declaredGenericInfo,
true);
}
/**
* Obtain the ClassElement for the given mirror.
*
* @param returnType The return type
* @param visitorContext The visitor context
* @return The class element
*/
protected @NonNull ClassElement mirrorToClassElement(TypeMirror returnType, JavaVisitorContext visitorContext) {
return mirrorToClassElement(returnType, visitorContext, Collections.emptyMap(), true);
}
/**
* Obtain the ClassElement for the given mirror.
*
* @param returnType The return type
* @param visitorContext The visitor context
* @param genericsInfo The generic information.
* @return The class element
*/
protected @NonNull ClassElement mirrorToClassElement(TypeMirror returnType, JavaVisitorContext visitorContext, Map<String, Map<String, TypeMirror>> genericsInfo) {
return mirrorToClassElement(returnType, visitorContext, genericsInfo, true);
}
/**
* Obtain the ClassElement for the given mirror.
*
* @param returnType The return type
* @param visitorContext The visitor context
* @param genericsInfo The generic information.
* @param includeTypeAnnotations Whether to include type level annotations in the metadata for the element
* @return The class element
*/
protected @NonNull ClassElement mirrorToClassElement(TypeMirror returnType, JavaVisitorContext visitorContext, Map<String, Map<String, TypeMirror>> genericsInfo, boolean includeTypeAnnotations) {
return mirrorToClassElement(returnType, visitorContext, genericsInfo, includeTypeAnnotations, returnType instanceof TypeVariable);
}
/**
* Obtain the ClassElement for the given mirror.
*
* @param returnType The return type
* @param visitorContext The visitor context
* @param genericsInfo The generic information.
* @param includeTypeAnnotations Whether to include type level annotations in the metadata for the element
* @param isTypeVariable is the type a type variable
* @return The class element
*/
protected @NonNull ClassElement mirrorToClassElement(
TypeMirror returnType,
JavaVisitorContext visitorContext,
Map<String, Map<String, TypeMirror>> genericsInfo,
boolean includeTypeAnnotations,
boolean isTypeVariable) {
if (genericsInfo == null) {
genericsInfo = Collections.emptyMap();
}
if (returnType instanceof NoType) {
return PrimitiveElement.VOID;
} else if (returnType instanceof DeclaredType) {
DeclaredType dt = (DeclaredType) returnType;
Element e = dt.asElement();
//Declared types can wrap other types, like primitives
if (e.asType() instanceof DeclaredType) {
List<? extends TypeMirror> typeArguments = dt.getTypeArguments();
if (e instanceof TypeElement) {
TypeElement typeElement = (TypeElement) e;
Map<String, TypeMirror> boundGenerics = resolveBoundGenerics(visitorContext, genericsInfo);
AnnotationUtils annotationUtils = visitorContext
.getAnnotationUtils();
AnnotationMetadata newAnnotationMetadata;
List<? extends AnnotationMirror> annotationMirrors = dt.getAnnotationMirrors();
if (!annotationMirrors.isEmpty()) {
newAnnotationMetadata = annotationUtils.newAnnotationBuilder().buildDeclared(typeElement, annotationMirrors, includeTypeAnnotations);
} else {
newAnnotationMetadata = includeTypeAnnotations ? annotationUtils.getAnnotationMetadata(typeElement) : AnnotationMetadata.EMPTY_METADATA;
}
if (visitorContext.getModelUtils().resolveKind(typeElement, ElementKind.ENUM).isPresent()) {
return new JavaEnumElement(
typeElement,
newAnnotationMetadata,
visitorContext
);
} else {
genericsInfo = visitorContext.getGenericUtils().alignNewGenericsInfo(
typeElement,
typeArguments,
boundGenerics
);
return new JavaClassElement(
typeElement,
newAnnotationMetadata,
visitorContext,
typeArguments,
genericsInfo,
isTypeVariable
);
}
}
} else {
return mirrorToClassElement(e.asType(), visitorContext, genericsInfo, includeTypeAnnotations);
}
} else if (returnType instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) returnType;
return resolveTypeVariable(
visitorContext,
genericsInfo,
includeTypeAnnotations,
tv,
tv
);
} else if (returnType instanceof ArrayType) {
ArrayType at = (ArrayType) returnType;
TypeMirror componentType = at.getComponentType();
ClassElement arrayType;
if (componentType instanceof TypeVariable && componentType.getKind() == TypeKind.TYPEVAR) {
TypeVariable tv = (TypeVariable) componentType;
arrayType = resolveTypeVariable(visitorContext, genericsInfo, includeTypeAnnotations, tv, at);
} else {
arrayType = mirrorToClassElement(componentType, visitorContext, genericsInfo, includeTypeAnnotations);
}
return arrayType.toArray();
} else if (returnType instanceof PrimitiveType) {
PrimitiveType pt = (PrimitiveType) returnType;
return PrimitiveElement.valueOf(pt.getKind().name());
} else if (returnType instanceof WildcardType) {
WildcardType wt = (WildcardType) returnType;
Map<String, Map<String, TypeMirror>> finalGenericsInfo = genericsInfo;
TypeMirror superBound = wt.getSuperBound();
Stream<? extends TypeMirror> lowerBounds;
if (superBound instanceof UnionType) {
lowerBounds = ((UnionType) superBound).getAlternatives().stream();
} else if (superBound == null) {
lowerBounds = Stream.empty();
} else {
lowerBounds = Stream.of(superBound);
}
TypeMirror extendsBound = wt.getExtendsBound();
Stream<? extends TypeMirror> upperBounds;
if (extendsBound instanceof IntersectionType) {
upperBounds = ((IntersectionType) extendsBound).getBounds().stream();
} else if (extendsBound == null) {
upperBounds = Stream.of(visitorContext.getElements().getTypeElement("java.lang.Object").asType());
} else {
upperBounds = Stream.of(extendsBound);
}
return new JavaWildcardElement(
wt,
upperBounds
.map(tm -> (JavaClassElement) mirrorToClassElement(tm, visitorContext, finalGenericsInfo, includeTypeAnnotations))
.collect(Collectors.toList()),
lowerBounds
.map(tm -> (JavaClassElement) mirrorToClassElement(tm, visitorContext, finalGenericsInfo, includeTypeAnnotations))
.collect(Collectors.toList())
);
}
return PrimitiveElement.VOID;
}
private ClassElement resolveTypeVariable(JavaVisitorContext visitorContext,
Map<String, Map<String, TypeMirror>> genericsInfo,
boolean includeTypeAnnotations,
TypeVariable tv,
TypeMirror declaration) {
TypeMirror upperBound = tv.getUpperBound();
Map<String, TypeMirror> boundGenerics = resolveBoundGenerics(visitorContext, genericsInfo);
TypeMirror bound = boundGenerics.get(tv.toString());
if (bound != null && bound != declaration) {
return mirrorToClassElement(bound, visitorContext, genericsInfo, includeTypeAnnotations, true);
} else {
// type variable is still free.
List<? extends TypeMirror> boundsUnresolved = upperBound instanceof IntersectionType ?
((IntersectionType) upperBound).getBounds() :
Collections.singletonList(upperBound);
List<JavaClassElement> bounds = boundsUnresolved.stream()
.map(tm -> (JavaClassElement) mirrorToClassElement(tm,
visitorContext,
genericsInfo,
includeTypeAnnotations))
.collect(Collectors.toList());
return new JavaGenericPlaceholderElement(tv, bounds, 0);
}
}
private Map<String, TypeMirror> resolveBoundGenerics(JavaVisitorContext visitorContext, Map<String, Map<String, TypeMirror>> genericsInfo) {
String declaringTypeName = null;
TypeElement typeElement = visitorContext.getModelUtils().classElementFor(element);
if (typeElement != null) {
declaringTypeName = typeElement.getQualifiedName().toString();
}
Map<String, TypeMirror> boundGenerics = genericsInfo.get(declaringTypeName);
if (boundGenerics == null) {
boundGenerics = Collections.emptyMap();
}
return boundGenerics;
}
private boolean hasModifier(Modifier modifier) {
return element.getModifiers().contains(modifier);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractJavaElement that = (AbstractJavaElement) o;
return element.equals(that.element);
}
@Override
public int hashCode() {
return Objects.hash(element);
}
}