1 /*
2 * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package com.sun.tools.javac.comp;
27
28 import com.sun.tools.javac.code.*;
29 import com.sun.tools.javac.code.Attribute.Compound;
30 import com.sun.tools.javac.code.Attribute.TypeCompound;
31 import com.sun.tools.javac.code.Kinds.KindSelector;
32 import com.sun.tools.javac.code.Scope.WriteableScope;
33 import com.sun.tools.javac.code.Source.Feature;
34 import com.sun.tools.javac.code.Symbol.*;
35 import com.sun.tools.javac.code.TypeMetadata.Annotations;
36 import com.sun.tools.javac.comp.Check.CheckContext;
37 import com.sun.tools.javac.resources.CompilerProperties.Errors;
38 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
39 import com.sun.tools.javac.tree.JCTree;
40 import com.sun.tools.javac.tree.JCTree.*;
41 import com.sun.tools.javac.tree.TreeInfo;
42 import com.sun.tools.javac.tree.TreeMaker;
43 import com.sun.tools.javac.tree.TreeScanner;
44 import com.sun.tools.javac.util.*;
45 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
46 import com.sun.tools.javac.util.List;
47
48 import javax.tools.JavaFileObject;
49
50 import java.util.*;
51
52 import static com.sun.tools.javac.code.Flags.SYNTHETIC;
53 import static com.sun.tools.javac.code.Kinds.Kind.MDL;
54 import static com.sun.tools.javac.code.Kinds.Kind.MTH;
55 import static com.sun.tools.javac.code.Kinds.Kind.PCK;
56 import static com.sun.tools.javac.code.Kinds.Kind.TYP;
57 import static com.sun.tools.javac.code.Kinds.Kind.VAR;
58 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
59 import static com.sun.tools.javac.code.TypeTag.ARRAY;
60 import static com.sun.tools.javac.code.TypeTag.CLASS;
61 import static com.sun.tools.javac.tree.JCTree.Tag.ANNOTATION;
62 import static com.sun.tools.javac.tree.JCTree.Tag.ASSIGN;
63 import static com.sun.tools.javac.tree.JCTree.Tag.IDENT;
64 import static com.sun.tools.javac.tree.JCTree.Tag.NEWARRAY;
65
66 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
67
68
69 /** Enter annotations onto symbols and types (and trees).
70 *
71 * This is also a pseudo stage in the compiler taking care of scheduling when annotations are
72 * entered.
73 *
74 * <p><b>This is NOT part of any supported API.
75 * If you write code that depends on this, you do so at your own risk.
76 * This code and its internal interfaces are subject to change or
77 * deletion without notice.</b>
78 */
79 public class Annotate {
80 protected static final Context.Key<Annotate> annotateKey = new Context.Key<>();
81
82 public static Annotate instance(Context context) {
83 Annotate instance = context.get(annotateKey);
84 if (instance == null)
85 instance = new Annotate(context);
86 return instance;
87 }
88
89 private final Attr attr;
90 private final Check chk;
91 private final ConstFold cfolder;
92 private final Enter enter;
93 private final Log log;
94 private final Names names;
95 private final Resolve resolve;
96 private final TreeMaker make;
97 private final Symtab syms;
98 private final TypeEnvs typeEnvs;
99 private final Types types;
100 private final Preview preview;
101
102 private final Attribute theUnfinishedDefaultValue;
103 private final String sourceName;
104
105 @SuppressWarnings("this-escape")
106 protected Annotate(Context context) {
107 context.put(annotateKey, this);
108
109 attr = Attr.instance(context);
110 chk = Check.instance(context);
111 cfolder = ConstFold.instance(context);
112 enter = Enter.instance(context);
113 log = Log.instance(context);
114 make = TreeMaker.instance(context);
115 names = Names.instance(context);
116 resolve = Resolve.instance(context);
117 syms = Symtab.instance(context);
118 typeEnvs = TypeEnvs.instance(context);
119 types = Types.instance(context);
120 preview = Preview.instance(context);
121
122 theUnfinishedDefaultValue = new Attribute.Error(syms.errType);
123
124 Source source = Source.instance(context);
125 sourceName = source.name;
126
127 blockCount = 1;
128 }
129
130 /** Semaphore to delay annotation processing */
131 private int blockCount = 0;
132
133 /** Called when annotations processing needs to be postponed. */
134 public void blockAnnotations() {
135 blockCount++;
136 }
137
138 /** Called when annotation processing can be resumed. */
139 public void unblockAnnotations() {
140 blockCount--;
141 if (blockCount == 0)
142 flush();
143 }
144
145 /** Variant which allows for a delayed flush of annotations.
146 * Needed by ClassReader */
147 public void unblockAnnotationsNoFlush() {
148 blockCount--;
149 }
150
151 /** are we blocking annotation processing? */
152 public boolean annotationsBlocked() {return blockCount > 0; }
153
154 public void enterDone() {
155 unblockAnnotations();
156 }
157
158 public List<TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
159 if (annotations.isEmpty()) {
160 return List.nil();
161 }
162
163 ListBuffer<TypeCompound> buf = new ListBuffer<>();
164 for (JCAnnotation anno : annotations) {
165 Assert.checkNonNull(anno.attribute);
166 buf.append((TypeCompound) anno.attribute);
167 }
168 return buf.toList();
169 }
170
171 /** Annotate (used for everything else) */
172 public void normal(Runnable r) {
173 q.append(r);
174 }
175
176 /** Validate, triggers after 'normal' */
177 public void validate(Runnable a) {
178 validateQ.append(a);
179 }
180
181 /** Flush all annotation queues */
182 public void flush() {
183 if (annotationsBlocked()) return;
184 if (isFlushing()) return;
185
186 startFlushing();
187 try {
188 while (q.nonEmpty() ||
189 typesQ.nonEmpty() ||
190 afterTypesQ.nonEmpty() ||
191 validateQ.nonEmpty()) {
192 while (q.nonEmpty()) {
193 q.next().run();
194 }
195 while (typesQ.nonEmpty()) {
196 typesQ.next().run();
197 }
198 while (afterTypesQ.nonEmpty()) {
199 afterTypesQ.next().run();
200 }
201 while (validateQ.nonEmpty()) {
202 validateQ.next().run();
203 }
204 }
205 } finally {
206 doneFlushing();
207 }
208 }
209
210 private ListBuffer<Runnable> q = new ListBuffer<>();
211 private ListBuffer<Runnable> validateQ = new ListBuffer<>();
212
213 private int flushCount = 0;
214 private boolean isFlushing() { return flushCount > 0; }
215 private void startFlushing() { flushCount++; }
216 private void doneFlushing() { flushCount--; }
217
218 ListBuffer<Runnable> typesQ = new ListBuffer<>();
219 ListBuffer<Runnable> afterTypesQ = new ListBuffer<>();
220
221
222 public void typeAnnotation(Runnable a) {
223 typesQ.append(a);
224 }
225
226 public void afterTypes(Runnable a) {
227 afterTypesQ.append(a);
228 }
229
230 /**
231 * Queue annotations for later attribution and entering. This is probably the method you are looking for.
232 *
233 * @param annotations the list of JCAnnotations to attribute and enter
234 * @param localEnv the enclosing env
235 * @param s the Symbol on which to enter the annotations
236 */
237 public void annotateLater(List<JCAnnotation> annotations, Env<AttrContext> localEnv, Symbol s)
238 {
239 if (annotations.isEmpty()) {
240 return;
241 }
242
243 s.resetAnnotations(); // mark Annotations as incomplete for now
244
245 normal(() -> {
246 // Packages are unusual, in that they are the only type of declaration that can legally appear
247 // more than once in a compilation, and in all cases refer to the same underlying symbol.
248 // This means they are the only kind of declaration that syntactically may have multiple sets
249 // of annotations, each on a different package declaration, even though that is ultimately
250 // forbidden by JLS 8 section 7.4.
251 // The corollary here is that all of the annotations on a package symbol may have already
252 // been handled, meaning that the set of annotations pending completion is now empty.
253 Assert.check(s.kind == PCK || s.annotationsPendingCompletion());
254 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
255 try {
256 if (s.hasAnnotations() && annotations.nonEmpty())
257 log.error(annotations.head.pos, Errors.AlreadyAnnotated(Kinds.kindName(s), s));
258
259 Assert.checkNonNull(s, "Symbol argument to actualEnterAnnotations is null");
260
261 // false is passed as fifth parameter since annotateLater is
262 // never called for a type parameter
263 annotateNow(s, annotations, localEnv, false, false);
264 } finally {
265 log.useSource(prev);
266 }
267 });
268
269 validate(() -> { //validate annotations
270 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
271 try {
272 chk.validateAnnotations(annotations, TreeInfo.declarationFor(s, localEnv.tree), s);
273 } finally {
274 log.useSource(prev);
275 }
276 });
277 }
278
279
280 /** Queue processing of an attribute default value. */
281 public void annotateDefaultValueLater(JCExpression defaultValue, Env<AttrContext> localEnv, MethodSymbol m)
282 {
283 normal(() -> {
284 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
285 try {
286 enterDefaultValue(defaultValue, localEnv, m);
287 } finally {
288 log.useSource(prev);
289 }
290 });
291
292 validate(() -> { //validate annotations
293 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
294 try {
295 // if default value is an annotation, check it is a well-formed
296 // annotation value (e.g. no duplicate values, no missing values, etc.)
297 chk.validateAnnotationTree(defaultValue);
298 } finally {
299 log.useSource(prev);
300 }
301 });
302 }
303
304 /** Enter a default value for an annotation element. */
305 private void enterDefaultValue(JCExpression defaultValue,
306 Env<AttrContext> localEnv, MethodSymbol m) {
307 m.defaultValue = attributeAnnotationValue(m.type.getReturnType(), defaultValue, localEnv);
308 }
309
310 /**
311 * Gather up annotations into a map from type symbols to lists of Compound attributes,
312 * then continue on with repeating annotations processing.
313 */
314 private <T extends Attribute.Compound> void annotateNow(Symbol toAnnotate,
315 List<JCAnnotation> withAnnotations, Env<AttrContext> env, boolean typeAnnotations,
316 boolean isTypeParam)
317 {
318 Map<TypeSymbol, ListBuffer<T>> annotated = new LinkedHashMap<>();
319 Map<T, DiagnosticPosition> pos = new HashMap<>();
320
321 for (List<JCAnnotation> al = withAnnotations; !al.isEmpty(); al = al.tail) {
322 JCAnnotation a = al.head;
323
324 T c;
325 if (typeAnnotations) {
326 @SuppressWarnings("unchecked")
327 T tmp = (T)attributeTypeAnnotation(a, syms.annotationType, env);
328 c = tmp;
329 } else {
330 @SuppressWarnings("unchecked")
331 T tmp = (T)attributeAnnotation(a, syms.annotationType, env);
332 c = tmp;
333 }
334
335 Assert.checkNonNull(c, "Failed to create annotation");
336
337 if (env.info.isAnonymousNewClass) {
338 // Annotations on anonymous class instantiations should be attributed,
339 // but not attached to the enclosing element. They will be visited
340 // separately and attached to the synthetic class declaration.
341 continue;
342 }
343
344 if (a.type.isErroneous() || a.type.tsym.isAnnotationType()) {
345 if (annotated.containsKey(a.type.tsym)) {
346 ListBuffer<T> l = annotated.get(a.type.tsym);
347 l = l.append(c);
348 annotated.put(a.type.tsym, l);
349 pos.put(c, a.pos());
350 } else {
351 annotated.put(a.type.tsym, ListBuffer.of(c));
352 pos.put(c, a.pos());
353 }
354 }
355
356 // Note: @Deprecated has no effect on local variables and parameters
357 if (!c.type.isErroneous()
358 && (toAnnotate.kind == MDL || toAnnotate.owner.kind != MTH)
359 && types.isSameType(c.type, syms.deprecatedType)) {
360 toAnnotate.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION);
361 if (isAttributeTrue(c.member(names.forRemoval))) {
362 toAnnotate.flags_field |= Flags.DEPRECATED_REMOVAL;
363 }
364 }
365
366 if (!c.type.isErroneous()
367 && types.isSameType(c.type, syms.previewFeatureType)) {
368 toAnnotate.flags_field |= Flags.PREVIEW_API;
369 if (isAttributeTrue(c.member(names.reflective))) {
370 toAnnotate.flags_field |= Flags.PREVIEW_REFLECTIVE;
371 }
372 }
373
374 if (!c.type.isErroneous()
375 && toAnnotate.kind == TYP
376 && types.isSameType(c.type, syms.valueBasedType)) {
377 toAnnotate.flags_field |= Flags.VALUE_BASED;
378 }
379
380 if (!c.type.isErroneous()
381 && toAnnotate.kind == TYP
382 && types.isSameType(c.type, syms.migratedValueClassType)) {
383 toAnnotate.flags_field |= Flags.MIGRATED_VALUE_CLASS;
384 }
385
386 if (!c.type.isErroneous()
387 && toAnnotate.kind == VAR
388 && toAnnotate.owner.kind == TYP
389 && types.isSameType(c.type, syms.strictType)) {
390 preview.checkSourceLevel(pos.get(c), Feature.VALUE_CLASSES);
391 toAnnotate.flags_field |= Flags.STRICT;
392 // temporary hack to indicate that a class has at least one strict field
393 toAnnotate.owner.flags_field |= Flags.HAS_STRICT;
394 }
395
396 if (!c.type.isErroneous()
397 && types.isSameType(c.type, syms.restrictedType)) {
398 toAnnotate.flags_field |= Flags.RESTRICTED;
399 }
400
401 if (!c.type.isErroneous()
402 && toAnnotate.kind == VAR
403 && types.isSameType(c.type, syms.requiresIdentityType)) {
404 toAnnotate.flags_field |= Flags.REQUIRES_IDENTITY;
405 }
406 }
407
408 List<T> buf = List.nil();
409 for (ListBuffer<T> lb : annotated.values()) {
410 if (lb.size() == 1) {
411 buf = buf.prepend(lb.first());
412 } else {
413 AnnotationContext<T> ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations);
414 T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam);
415 if (res != null)
416 buf = buf.prepend(res);
417 }
418 }
419
420 if (typeAnnotations) {
421 @SuppressWarnings("unchecked")
422 List<TypeCompound> attrs = (List<TypeCompound>)buf.reverse();
423 toAnnotate.appendUniqueTypeAttributes(attrs);
424 } else {
425 @SuppressWarnings("unchecked")
426 List<Attribute.Compound> attrs = (List<Attribute.Compound>)buf.reverse();
427 toAnnotate.resetAnnotations();
428 toAnnotate.setDeclarationAttributes(attrs);
429 }
430 }
431 //where:
432 private boolean isAttributeTrue(Attribute attr) {
433 return (attr instanceof Attribute.Constant constant)
434 && constant.type == syms.booleanType
435 && ((Integer) constant.value) != 0;
436 }
437
438 /**
439 * Attribute and store a semantic representation of the annotation tree {@code tree} into the
440 * tree.attribute field.
441 *
442 * @param tree the tree representing an annotation
443 * @param expectedAnnotationType the expected (super)type of the annotation
444 * @param env the current env in where the annotation instance is found
445 */
446 public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType,
447 Env<AttrContext> env)
448 {
449 // The attribute might have been entered if it is Target or Repeatable
450 // Because TreeCopier does not copy type, redo this if type is null
451 if (tree.attribute != null && tree.type != null)
452 return tree.attribute;
453
454 List<Pair<MethodSymbol, Attribute>> elems = attributeAnnotationValues(tree, expectedAnnotationType, env);
455 Attribute.Compound ac = new Attribute.Compound(tree.type, elems);
456
457 return tree.attribute = ac;
458 }
459
460 /** Attribute and store a semantic representation of the type annotation tree {@code tree} into
461 * the tree.attribute field.
462 *
463 * @param a the tree representing an annotation
464 * @param expectedAnnotationType the expected (super)type of the annotation
465 * @param env the current env in where the annotation instance is found
466 */
467 public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType,
468 Env<AttrContext> env)
469 {
470 // The attribute might have been entered if it is Target or Repeatable
471 // Because TreeCopier does not copy type, redo this if type is null
472 if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound typeCompound)) {
473 // Create a new TypeCompound
474 List<Pair<MethodSymbol,Attribute>> elems =
475 attributeAnnotationValues(a, expectedAnnotationType, env);
476
477 Attribute.TypeCompound tc =
478 new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown);
479 a.attribute = tc;
480 return tc;
481 } else {
482 // Use an existing TypeCompound
483 return typeCompound;
484 }
485 }
486
487 /**
488 * Attribute annotation elements creating a list of pairs of the Symbol representing that
489 * element and the value of that element as an Attribute. */
490 private List<Pair<MethodSymbol, Attribute>> attributeAnnotationValues(JCAnnotation a,
491 Type expected, Env<AttrContext> env)
492 {
493 // The annotation might have had its type attributed (but not
494 // checked) by attr.attribAnnotationTypes during MemberEnter,
495 // in which case we do not need to do it again.
496 Type at = (a.annotationType.type != null ?
497 a.annotationType.type : attr.attribType(a.annotationType, env));
498 a.type = chk.checkType(a.annotationType.pos(), at, expected);
499
500 boolean isError = a.type.isErroneous();
501 if (!a.type.tsym.isAnnotationType() && !isError) {
502 log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type));
503 isError = true;
504 }
505
506 // List of name=value pairs (or implicit "value=" if size 1)
507 List<JCExpression> args = a.args;
508
509 boolean elidedValue = false;
510 // special case: elided "value=" assumed
511 if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
512 args.head = make.at(args.head.pos).
513 Assign(make.Ident(names.value), args.head);
514 elidedValue = true;
515 }
516
517 ListBuffer<Pair<MethodSymbol,Attribute>> buf = new ListBuffer<>();
518 for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
519 Pair<MethodSymbol, Attribute> p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue);
520 if (p != null && !p.fst.type.isErroneous())
521 buf.append(p);
522 }
523 return buf.toList();
524 }
525
526 // where
527 private Pair<MethodSymbol, Attribute> attributeAnnotationNameValuePair(JCExpression nameValuePair,
528 Type thisAnnotationType, boolean badAnnotation, Env<AttrContext> env, boolean elidedValue)
529 {
530 if (!nameValuePair.hasTag(ASSIGN)) {
531 log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue);
532 attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env);
533 return null;
534 }
535 JCAssign assign = (JCAssign)nameValuePair;
536 if (!assign.lhs.hasTag(IDENT)) {
537 log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue);
538 attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env);
539 return null;
540 }
541
542 // Resolve element to MethodSym
543 JCIdent left = (JCIdent)assign.lhs;
544 Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(),
545 env, thisAnnotationType,
546 left.name, List.nil(), null);
547 left.sym = method;
548 left.type = method.type;
549 chk.checkDeprecated(left, env.info.scope.owner, method);
550 if (method.owner != thisAnnotationType.tsym && !badAnnotation)
551 log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType));
552 Type resultType = method.type.getReturnType();
553
554 // Compute value part
555 Attribute value = attributeAnnotationValue(resultType, assign.rhs, env);
556 nameValuePair.type = resultType;
557
558 return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value);
559
560 }
561
562 /** Attribute an annotation element value */
563 private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree,
564 Env<AttrContext> env)
565 {
566 //first, try completing the symbol for the annotation value - if a completion
567 //error is thrown, we should recover gracefully, and display an
568 //ordinary resolution diagnostic.
569 try {
570 expectedElementType.tsym.complete();
571 } catch(CompletionFailure e) {
572 log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null));
573 expectedElementType = syms.errType;
574 }
575
576 if (expectedElementType.hasTag(ARRAY)) {
577 return getAnnotationArrayValue(expectedElementType, tree, env);
578 }
579
580 //error recovery
581 if (tree.hasTag(NEWARRAY)) {
582 if (!expectedElementType.isErroneous())
583 log.error(tree.pos(), Errors.AnnotationValueNotAllowableType);
584 JCNewArray na = (JCNewArray)tree;
585 if (na.elemtype != null) {
586 log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation);
587 }
588 for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
589 attributeAnnotationValue(syms.errType,
590 l.head,
591 env);
592 }
593 return new Attribute.Error(syms.errType);
594 }
595
596 if (expectedElementType.tsym.isAnnotationType()) {
597 if (tree.hasTag(ANNOTATION)) {
598 return attributeAnnotation((JCAnnotation)tree, expectedElementType, env);
599 } else {
600 log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation);
601 expectedElementType = syms.errType;
602 }
603 }
604
605 //error recovery
606 if (tree.hasTag(ANNOTATION)) {
607 if (!expectedElementType.isErroneous())
608 log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType));
609 attributeAnnotation((JCAnnotation)tree, syms.errType, env);
610 return new Attribute.Error(((JCAnnotation)tree).annotationType.type);
611 }
612
613 MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() {
614 // the methods below are added to allow class literals on top of constant expressions
615 @Override
616 public void visitTypeIdent(JCPrimitiveTypeTree that) {}
617
618 @Override
619 public void visitTypeArray(JCArrayTypeTree that) {}
620 };
621 tree.accept(initTreeVisitor);
622 if (!initTreeVisitor.result) {
623 log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue);
624 return new Attribute.Error(syms.errType);
625 }
626
627 if (expectedElementType.isPrimitive() ||
628 (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) {
629 return getAnnotationPrimitiveValue(expectedElementType, tree, env);
630 }
631
632 if (expectedElementType.tsym == syms.classType.tsym) {
633 return getAnnotationClassValue(expectedElementType, tree, env);
634 }
635
636 if (expectedElementType.hasTag(CLASS) &&
637 (expectedElementType.tsym.flags() & Flags.ENUM) != 0) {
638 return getAnnotationEnumValue(expectedElementType, tree, env);
639 }
640
641 //error recovery:
642 if (!expectedElementType.isErroneous())
643 log.error(tree.pos(), Errors.AnnotationValueNotAllowableType);
644 return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType));
645 }
646
647 private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
648 Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType));
649 Symbol sym = TreeInfo.symbol(tree);
650 if (sym == null ||
651 TreeInfo.nonstaticSelect(tree) ||
652 sym.kind != VAR ||
653 (sym.flags() & Flags.ENUM) == 0) {
654 log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant);
655 return new Attribute.Error(result.getOriginalType());
656 }
657 VarSymbol enumerator = (VarSymbol) sym;
658 return new Attribute.Enum(expectedElementType, enumerator);
659 }
660
661 private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
662 Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType));
663 if (result.isErroneous()) {
664 // Does it look like an unresolved class literal?
665 if (TreeInfo.name(tree) == names._class &&
666 ((JCFieldAccess) tree).selected.type.isErroneous()) {
667 Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName();
668 return new Attribute.UnresolvedClass(expectedElementType,
669 types.createErrorType(n,
670 syms.unknownSymbol, syms.classType));
671 } else {
672 return new Attribute.Error(result.getOriginalType());
673 }
674 }
675
676 // Class literals look like field accesses of a field named class
677 // at the tree level
678 if (TreeInfo.name(tree) != names._class) {
679 log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral);
680 return new Attribute.Error(syms.errType);
681 }
682
683 return new Attribute.Class(types,
684 (((JCFieldAccess) tree).selected).type);
685 }
686
687 private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
688 Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType));
689 if (result.isErroneous())
690 return new Attribute.Error(result.getOriginalType());
691 if (result.constValue() == null) {
692 log.error(tree.pos(), Errors.AttributeValueMustBeConstant);
693 return new Attribute.Error(expectedElementType);
694 }
695
696 // Scan the annotation element value and then attribute nested annotations if present
697 if (tree.type != null && tree.type.tsym != null) {
698 queueScanTreeAndTypeAnnotate(tree, env, tree.type.tsym);
699 }
700
701 result = cfolder.coerce(result, expectedElementType);
702 return new Attribute.Constant(expectedElementType, result.constValue());
703 }
704
705 private Attr.ResultInfo annotationValueInfo(Type pt) {
706 return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext));
707 }
708
709 class AnnotationValueContext extends Check.NestedCheckContext {
710 AnnotationValueContext(CheckContext enclosingContext) {
711 super(enclosingContext);
712 }
713
714 @Override
715 public boolean compatible(Type found, Type req, Warner warn) {
716 //handle non-final implicitly-typed vars (will be rejected later on)
717 return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn);
718 }
719 }
720
721 private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
722 // Special case, implicit array
723 if (!tree.hasTag(NEWARRAY)) {
724 tree = make.at(tree.pos).
725 NewArray(null, List.nil(), List.of(tree));
726 }
727
728 JCNewArray na = (JCNewArray)tree;
729 List<JCExpression> elems = na.elems;
730 if (na.elemtype != null) {
731 log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation);
732 if (elems == null) {
733 elems = List.nil();
734 }
735 }
736 ListBuffer<Attribute> buf = new ListBuffer<>();
737 for (List<JCExpression> l = elems; l.nonEmpty(); l = l.tail) {
738 buf.append(attributeAnnotationValue(types.elemtype(expectedElementType),
739 l.head,
740 env));
741 }
742 na.type = expectedElementType;
743 return new Attribute.
744 Array(expectedElementType, buf.toArray(new Attribute[buf.length()]));
745 }
746
747 /* *********************************
748 * Support for repeating annotations
749 ***********************************/
750
751 /**
752 * This context contains all the information needed to synthesize new
753 * annotations trees for repeating annotations.
754 */
755 private class AnnotationContext<T extends Attribute.Compound> {
756 public final Env<AttrContext> env;
757 public final Map<Symbol.TypeSymbol, ListBuffer<T>> annotated;
758 public final Map<T, JCDiagnostic.DiagnosticPosition> pos;
759 public final boolean isTypeCompound;
760
761 public AnnotationContext(Env<AttrContext> env,
762 Map<Symbol.TypeSymbol, ListBuffer<T>> annotated,
763 Map<T, JCDiagnostic.DiagnosticPosition> pos,
764 boolean isTypeCompound) {
765 Assert.checkNonNull(env);
766 Assert.checkNonNull(annotated);
767 Assert.checkNonNull(pos);
768
769 this.env = env;
770 this.annotated = annotated;
771 this.pos = pos;
772 this.isTypeCompound = isTypeCompound;
773 }
774 }
775
776 /* Process repeated annotations. This method returns the
777 * synthesized container annotation or null IFF all repeating
778 * annotation are invalid. This method reports errors/warnings.
779 */
780 private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
781 AnnotationContext<T> ctx, Symbol on, boolean isTypeParam)
782 {
783 T firstOccurrence = annotations.head;
784 List<Attribute> repeated = List.nil();
785 Type origAnnoType = null;
786 Type arrayOfOrigAnnoType = null;
787 Type targetContainerType = null;
788 MethodSymbol containerValueSymbol = null;
789
790 Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1
791
792 int count = 0;
793 for (List<T> al = annotations; !al.isEmpty(); al = al.tail) {
794 count++;
795
796 // There must be more than a single anno in the annotation list
797 Assert.check(count > 1 || !al.tail.isEmpty());
798
799 T currentAnno = al.head;
800
801 origAnnoType = currentAnno.type;
802 if (arrayOfOrigAnnoType == null) {
803 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
804 }
805
806 // Only report errors if this isn't the first occurrence I.E. count > 1
807 boolean reportError = count > 1;
808 Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError);
809 if (currentContainerType == null) {
810 continue;
811 }
812 // Assert that the target Container is == for all repeated
813 // annos of the same annotation type, the types should
814 // come from the same Symbol, i.e. be '=='
815 Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
816 targetContainerType = currentContainerType;
817
818 containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
819
820 if (containerValueSymbol == null) { // Check of CA type failed
821 // errors are already reported
822 continue;
823 }
824
825 repeated = repeated.prepend(currentAnno);
826 }
827
828 if (!repeated.isEmpty() && targetContainerType == null) {
829 log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType));
830 return null;
831 }
832
833 if (!repeated.isEmpty()) {
834 repeated = repeated.reverse();
835 DiagnosticPosition pos = ctx.pos.get(firstOccurrence);
836 TreeMaker m = make.at(pos);
837 Pair<MethodSymbol, Attribute> p =
838 new Pair<MethodSymbol, Attribute>(containerValueSymbol,
839 new Attribute.Array(arrayOfOrigAnnoType, repeated));
840 if (ctx.isTypeCompound) {
841 /* TODO: the following code would be cleaner:
842 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
843 ((Attribute.TypeCompound)annotations.head).position);
844 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
845 at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env);
846 */
847 // However, we directly construct the TypeCompound to keep the
848 // direct relation to the contained TypeCompounds.
849 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
850 ((Attribute.TypeCompound)annotations.head).position);
851
852 JCAnnotation annoTree = m.TypeAnnotation(at);
853 if (!chk.validateAnnotationDeferErrors(annoTree))
854 log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType));
855
856 if (!chk.isTypeAnnotation(annoTree, isTypeParam)) {
857 log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)
858 : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType));
859 }
860
861 at.setSynthesized(true);
862
863 @SuppressWarnings("unchecked")
864 T x = (T) at;
865 return x;
866 } else {
867 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
868 JCAnnotation annoTree = m.Annotation(c);
869
870 boolean isRecordMember = (on.flags_field & Flags.RECORD) != 0 || on.enclClass() != null && on.enclClass().isRecord();
871 /* if it is a record member we will not issue the error now and wait until annotations on records are
872 * checked at Check::validateAnnotation, which will issue it
873 */
874 if (!chk.annotationApplicable(annoTree, on) && (!isRecordMember || isRecordMember && (on.flags_field & Flags.GENERATED_MEMBER) == 0)) {
875 log.error(annoTree.pos(),
876 Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on));
877 }
878
879 if (!chk.validateAnnotationDeferErrors(annoTree))
880 log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType));
881
882 c = attributeAnnotation(annoTree, targetContainerType, ctx.env);
883 c.setSynthesized(true);
884
885 @SuppressWarnings("unchecked")
886 T x = (T) c;
887 return x;
888 }
889 } else {
890 return null; // errors should have been reported elsewhere
891 }
892 }
893
894 /**
895 * Fetches the actual Type that should be the containing annotation.
896 */
897 private Type getContainingType(Attribute.Compound currentAnno,
898 DiagnosticPosition pos,
899 boolean reportError)
900 {
901 Type origAnnoType = currentAnno.type;
902 TypeSymbol origAnnoDecl = origAnnoType.tsym;
903
904 // Fetch the Repeatable annotation from the current
905 // annotation's declaration, or null if it has none
906 Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable();
907 if (ca == null) { // has no Repeatable annotation
908 if (reportError)
909 log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType));
910 return null;
911 }
912
913 return filterSame(extractContainingType(ca, pos, origAnnoDecl),
914 origAnnoType);
915 }
916
917 // returns null if t is same as 's', returns 't' otherwise
918 private Type filterSame(Type t, Type s) {
919 if (t == null || s == null) {
920 return t;
921 }
922
923 return types.isSameType(t, s) ? null : t;
924 }
925
926 /** Extract the actual Type to be used for a containing annotation. */
927 private Type extractContainingType(Attribute.Compound ca,
928 DiagnosticPosition pos,
929 TypeSymbol annoDecl)
930 {
931 // The next three checks check that the Repeatable annotation
932 // on the declaration of the annotation type that is repeating is
933 // valid.
934
935 // Repeatable must have at least one element
936 if (ca.values.isEmpty()) {
937 log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
938 return null;
939 }
940 Pair<MethodSymbol,Attribute> p = ca.values.head;
941 Name name = p.fst.name;
942 if (name != names.value) { // should contain only one element, named "value"
943 log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
944 return null;
945 }
946 if (!(p.snd instanceof Attribute.Class attributeClass)) { // check that the value of "value" is an Attribute.Class
947 log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
948 return null;
949 }
950
951 return attributeClass.getValue();
952 }
953
954 /* Validate that the suggested targetContainerType Type is a valid
955 * container type for repeated instances of originalAnnoType
956 * annotations. Return null and report errors if this is not the
957 * case, return the MethodSymbol of the value element in
958 * targetContainerType if it is suitable (this is needed to
959 * synthesize the container). */
960 private MethodSymbol validateContainer(Type targetContainerType,
961 Type originalAnnoType,
962 DiagnosticPosition pos) {
963 MethodSymbol containerValueSymbol = null;
964 boolean fatalError = false;
965
966 // Validate that there is a (and only 1) value method
967 Scope scope = null;
968 try {
969 scope = targetContainerType.tsym.members();
970 } catch (CompletionFailure ex) {
971 chk.completionError(pos, ex);
972 return null;
973 }
974 int nr_value_elems = 0;
975 boolean error = false;
976 for(Symbol elm : scope.getSymbolsByName(names.value)) {
977 nr_value_elems++;
978
979 if (nr_value_elems == 1 &&
980 elm.kind == MTH) {
981 containerValueSymbol = (MethodSymbol)elm;
982 } else {
983 error = true;
984 }
985 }
986 if (error) {
987 log.error(pos,
988 Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType,
989 nr_value_elems));
990 return null;
991 } else if (nr_value_elems == 0) {
992 log.error(pos,
993 Errors.InvalidRepeatableAnnotationNoValue(targetContainerType));
994 return null;
995 }
996
997 // validate that the 'value' element is a method
998 // probably "impossible" to fail this
999 if (containerValueSymbol.kind != MTH) {
1000 log.error(pos,
1001 Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType));
1002 fatalError = true;
1003 }
1004
1005 // validate that the 'value' element has the correct return type
1006 // i.e. array of original anno
1007 Type valueRetType = containerValueSymbol.type.getReturnType();
1008 Type expectedType = types.makeArrayType(originalAnnoType);
1009 if (!(types.isArray(valueRetType) &&
1010 types.isSameType(expectedType, valueRetType))) {
1011 log.error(pos,
1012 Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType,
1013 valueRetType,
1014 expectedType));
1015 fatalError = true;
1016 }
1017
1018 return fatalError ? null : containerValueSymbol;
1019 }
1020
1021 private <T extends Attribute.Compound> T makeContainerAnnotation(List<T> toBeReplaced,
1022 AnnotationContext<T> ctx, Symbol sym, boolean isTypeParam)
1023 {
1024 // Process repeated annotations
1025 T validRepeated =
1026 processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam);
1027
1028 if (validRepeated != null) {
1029 // Check that the container isn't manually
1030 // present along with repeated instances of
1031 // its contained annotation.
1032 ListBuffer<T> manualContainer = ctx.annotated.get(validRepeated.type.tsym);
1033 if (manualContainer != null) {
1034 log.error(ctx.pos.get(manualContainer.first()),
1035 Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym));
1036 }
1037 }
1038
1039 // A null return will delete the Placeholder
1040 return validRepeated;
1041 }
1042
1043 /* ******************
1044 * Type annotations *
1045 ********************/
1046
1047 /**
1048 * Attribute the list of annotations and enter them onto s.
1049 */
1050 public void enterTypeAnnotations(List<JCAnnotation> annotations, Env<AttrContext> env, Symbol s, boolean isTypeParam)
1051 {
1052 Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/");
1053 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
1054
1055 try {
1056 annotateNow(s, annotations, env, true, isTypeParam);
1057 } finally {
1058 log.useSource(prev);
1059 }
1060 }
1061
1062 /**
1063 * Enqueue tree for scanning of type annotations, attaching to the Symbol sym.
1064 */
1065 public void queueScanTreeAndTypeAnnotate(JCTree tree, Env<AttrContext> env, Symbol sym)
1066 {
1067 Assert.checkNonNull(sym);
1068 normal(() -> tree.accept(new TypeAnnotate(env, sym)));
1069 }
1070
1071 /**
1072 * Apply the annotations to the particular type.
1073 */
1074 public void annotateTypeSecondStage(JCTree tree, List<JCAnnotation> annotations, Type storeAt) {
1075 typeAnnotation(() -> {
1076 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
1077 Assert.check(annotations.size() == compounds.size());
1078 // the type already has annotation metadata, but it's empty
1079 Annotations metadata = storeAt.getMetadata(Annotations.class);
1080 Assert.checkNonNull(metadata);
1081 Assert.check(metadata.annotationBuffer().isEmpty());
1082 metadata.annotationBuffer().appendList(compounds);
1083 });
1084 }
1085
1086 /**
1087 * Apply the annotations to the particular type.
1088 */
1089 public void annotateTypeParameterSecondStage(JCTree tree, List<JCAnnotation> annotations) {
1090 typeAnnotation(() -> {
1091 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
1092 Assert.check(annotations.size() == compounds.size());
1093 });
1094 }
1095
1096 /**
1097 * We need to use a TreeScanner, because it is not enough to visit the top-level
1098 * annotations. We also need to visit type arguments, etc.
1099 */
1100 private class TypeAnnotate extends TreeScanner {
1101 private final Env<AttrContext> env;
1102 private final Symbol sym;
1103
1104 public TypeAnnotate(Env<AttrContext> env, Symbol sym) {
1105
1106 this.env = env;
1107 this.sym = sym;
1108 }
1109
1110 @Override
1111 public void visitAnnotatedType(JCAnnotatedType tree) {
1112 enterTypeAnnotations(tree.annotations, env, sym, false);
1113 scan(tree.underlyingType);
1114 }
1115
1116 @Override
1117 public void visitTypeParameter(JCTypeParameter tree) {
1118 enterTypeAnnotations(tree.annotations, env, sym, true);
1119 scan(tree.bounds);
1120 }
1121
1122 @Override
1123 public void visitNewArray(JCNewArray tree) {
1124 enterTypeAnnotations(tree.annotations, env, sym, false);
1125 for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
1126 enterTypeAnnotations(dimAnnos, env, sym, false);
1127 scan(tree.elemtype);
1128 scan(tree.elems);
1129 }
1130
1131 @Override
1132 public void visitMethodDef(JCMethodDecl tree) {
1133 scan(tree.mods);
1134 scan(tree.restype);
1135 scan(tree.typarams);
1136 scan(tree.recvparam);
1137 scan(tree.params);
1138 scan(tree.thrown);
1139 scan(tree.defaultValue);
1140 // Do not annotate the body, just the signature.
1141 }
1142
1143 @Override
1144 public void visitVarDef(JCVariableDecl tree) {
1145 if (sym != null && sym.kind == VAR) {
1146 // Don't visit a parameter once when the sym is the method
1147 // and once when the sym is the parameter.
1148 scan(tree.mods);
1149 scan(tree.vartype);
1150 }
1151 scan(tree.init);
1152 }
1153
1154 @Override
1155 public void visitBindingPattern(JCTree.JCBindingPattern tree) {
1156 //type binding pattern's type will be annotated separately, avoid
1157 //adding its annotations into the owning method here (would clash
1158 //with repeatable annotations).
1159 }
1160
1161 @Override
1162 public void visitClassDef(JCClassDecl tree) {
1163 // We can only hit a classdef if it is declared within
1164 // a method. Ignore it - the class will be visited
1165 // separately later.
1166 }
1167
1168 @Override
1169 public void visitNewClass(JCNewClass tree) {
1170 scan(tree.encl);
1171 scan(tree.typeargs);
1172 try {
1173 env.info.isAnonymousNewClass = tree.def != null;
1174 scan(tree.clazz);
1175 } finally {
1176 env.info.isAnonymousNewClass = false;
1177 }
1178 scan(tree.args);
1179 // the anonymous class instantiation if any will be visited separately.
1180 }
1181
1182 @Override
1183 public void visitErroneous(JCErroneous tree) {
1184 if (tree.errs != null) {
1185 for (JCTree err : tree.errs) {
1186 scan(err);
1187 }
1188 }
1189 }
1190 }
1191
1192 /* *******************
1193 * Completer support *
1194 *********************/
1195
1196 private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() {
1197 @Override
1198 public void complete(ClassSymbol sym) throws CompletionFailure {
1199 Env<AttrContext> context = typeEnvs.get(sym);
1200 Annotate.this.attributeAnnotationType(context);
1201 }
1202 };
1203
1204 /* Last stage completer to enter just enough annotations to have a prototype annotation type.
1205 * This currently means entering @Target and @Repeatable.
1206 */
1207 public AnnotationTypeCompleter annotationTypeSourceCompleter() {
1208 return theSourceCompleter;
1209 }
1210
1211 private void attributeAnnotationType(Env<AttrContext> env) {
1212 Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(),
1213 "Trying to annotation type complete a non-annotation type");
1214
1215 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
1216 try {
1217 JCClassDecl tree = (JCClassDecl)env.tree;
1218 AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs);
1219 v.scanAnnotationType(tree);
1220 tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable);
1221 tree.sym.getAnnotationTypeMetadata().setTarget(v.target);
1222 } finally {
1223 log.useSource(prev);
1224 }
1225 }
1226
1227 public Attribute unfinishedDefaultValue() {
1228 return theUnfinishedDefaultValue;
1229 }
1230
1231 public static interface AnnotationTypeCompleter {
1232 void complete(ClassSymbol sym) throws CompletionFailure;
1233 }
1234
1235 /** Visitor to determine a prototype annotation type for a class declaring an annotation type.
1236 *
1237 * <p><b>This is NOT part of any supported API.
1238 * If you write code that depends on this, you do so at your own risk.
1239 * This code and its internal interfaces are subject to change or
1240 * deletion without notice.</b>
1241 */
1242 public class AnnotationTypeVisitor extends TreeScanner {
1243 private Env<AttrContext> env;
1244
1245 private final Attr attr;
1246 private final Check check;
1247 private final Symtab tab;
1248 private final TypeEnvs typeEnvs;
1249
1250 private Compound target;
1251 private Compound repeatable;
1252
1253 public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) {
1254 this.attr = attr;
1255 this.check = check;
1256 this.tab = tab;
1257 this.typeEnvs = typeEnvs;
1258 }
1259
1260 public Compound getRepeatable() {
1261 return repeatable;
1262 }
1263
1264 public Compound getTarget() {
1265 return target;
1266 }
1267
1268 public void scanAnnotationType(JCClassDecl decl) {
1269 visitClassDef(decl);
1270 }
1271
1272 @Override
1273 public void visitClassDef(JCClassDecl tree) {
1274 Env<AttrContext> prevEnv = env;
1275 env = typeEnvs.get(tree.sym);
1276 try {
1277 scan(tree.mods); // look for repeatable and target
1278 // don't descend into body
1279 } finally {
1280 env = prevEnv;
1281 }
1282 }
1283
1284 @Override
1285 public void visitAnnotation(JCAnnotation tree) {
1286 Type t = tree.annotationType.type;
1287 if (t == null) {
1288 t = attr.attribType(tree.annotationType, env);
1289 tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType);
1290 }
1291
1292 if (t == tab.annotationTargetType) {
1293 target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env);
1294 } else if (t == tab.repeatableType) {
1295 repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env);
1296 }
1297 }
1298 }
1299
1300 /** Represents the semantics of an Annotation Type.
1301 *
1302 * <p><b>This is NOT part of any supported API.
1303 * If you write code that depends on this, you do so at your own risk.
1304 * This code and its internal interfaces are subject to change or
1305 * deletion without notice.</b>
1306 */
1307 public static class AnnotationTypeMetadata {
1308 final ClassSymbol metaDataFor;
1309 private Compound target;
1310 private Compound repeatable;
1311 private AnnotationTypeCompleter annotationTypeCompleter;
1312
1313 public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) {
1314 this.metaDataFor = metaDataFor;
1315 this.annotationTypeCompleter = annotationTypeCompleter;
1316 }
1317
1318 private void init() {
1319 // Make sure metaDataFor is member entered
1320 while (!metaDataFor.isCompleted())
1321 metaDataFor.complete();
1322
1323 if (annotationTypeCompleter != null) {
1324 AnnotationTypeCompleter c = annotationTypeCompleter;
1325 annotationTypeCompleter = null;
1326 c.complete(metaDataFor);
1327 }
1328 }
1329
1330 public void complete() {
1331 init();
1332 }
1333
1334 public Compound getRepeatable() {
1335 init();
1336 return repeatable;
1337 }
1338
1339 public void setRepeatable(Compound repeatable) {
1340 Assert.checkNull(this.repeatable);
1341 this.repeatable = repeatable;
1342 }
1343
1344 public Compound getTarget() {
1345 init();
1346 return target;
1347 }
1348
1349 public void setTarget(Compound target) {
1350 Assert.checkNull(this.target);
1351 this.target = target;
1352 }
1353
1354 public Set<MethodSymbol> getAnnotationElements() {
1355 init();
1356 Set<MethodSymbol> members = new LinkedHashSet<>();
1357 WriteableScope s = metaDataFor.members();
1358 Iterable<Symbol> ss = s.getSymbols(NON_RECURSIVE);
1359 for (Symbol sym : ss)
1360 if (sym.kind == MTH &&
1361 sym.name != sym.name.table.names.clinit &&
1362 (sym.flags() & SYNTHETIC) == 0)
1363 members.add((MethodSymbol)sym);
1364 return members;
1365 }
1366
1367 public Set<MethodSymbol> getAnnotationElementsWithDefault() {
1368 init();
1369 Set<MethodSymbol> members = getAnnotationElements();
1370 Set<MethodSymbol> res = new LinkedHashSet<>();
1371 for (MethodSymbol m : members)
1372 if (m.defaultValue != null)
1373 res.add(m);
1374 return res;
1375 }
1376
1377 @Override
1378 public String toString() {
1379 return "Annotation type for: " + metaDataFor;
1380 }
1381
1382 public boolean isMetadataForAnnotationType() { return true; }
1383
1384 public static AnnotationTypeMetadata notAnAnnotationType() {
1385 return NOT_AN_ANNOTATION_TYPE;
1386 }
1387
1388 private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE =
1389 new AnnotationTypeMetadata(null, null) {
1390 @Override
1391 public void complete() {
1392 } // do nothing
1393
1394 @Override
1395 public String toString() {
1396 return "Not an annotation type";
1397 }
1398
1399 @Override
1400 public Set<MethodSymbol> getAnnotationElements() {
1401 return new LinkedHashSet<>(0);
1402 }
1403
1404 @Override
1405 public Set<MethodSymbol> getAnnotationElementsWithDefault() {
1406 return new LinkedHashSet<>(0);
1407 }
1408
1409 @Override
1410 public boolean isMetadataForAnnotationType() {
1411 return false;
1412 }
1413
1414 @Override
1415 public Compound getTarget() {
1416 return null;
1417 }
1418
1419 @Override
1420 public Compound getRepeatable() {
1421 return null;
1422 }
1423 };
1424 }
1425
1426 public void newRound() {
1427 blockCount = 1;
1428 }
1429
1430 public Queues setQueues(Queues nue) {
1431 Queues stored = new Queues(q, validateQ, typesQ, afterTypesQ);
1432 this.q = nue.q;
1433 this.typesQ = nue.typesQ;
1434 this.afterTypesQ = nue.afterTypesQ;
1435 this.validateQ = nue.validateQ;
1436 return stored;
1437 }
1438
1439 static class Queues {
1440 private final ListBuffer<Runnable> q;
1441 private final ListBuffer<Runnable> validateQ;
1442 private final ListBuffer<Runnable> typesQ;
1443 private final ListBuffer<Runnable> afterTypesQ;
1444
1445 public Queues() {
1446 this(new ListBuffer<Runnable>(), new ListBuffer<Runnable>(), new ListBuffer<Runnable>(), new ListBuffer<Runnable>());
1447 }
1448
1449 public Queues(ListBuffer<Runnable> q, ListBuffer<Runnable> validateQ, ListBuffer<Runnable> typesQ, ListBuffer<Runnable> afterTypesQ) {
1450 this.q = q;
1451 this.validateQ = validateQ;
1452 this.typesQ = typesQ;
1453 this.afterTypesQ = afterTypesQ;
1454 }
1455 }
1456 }