1 /*
   2  * Copyright (c) 2003, 2026, 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                     && types.isSameType(c.type, syms.restrictedType)) {
 388                 toAnnotate.flags_field |= Flags.RESTRICTED;
 389             }
 390 
 391             if (!c.type.isErroneous()
 392                     && toAnnotate.kind == VAR
 393                     && types.isSameType(c.type, syms.requiresIdentityType)) {
 394                 toAnnotate.flags_field |= Flags.REQUIRES_IDENTITY;
 395             }
 396         }
 397 
 398         List<T> buf = List.nil();
 399         for (ListBuffer<T> lb : annotated.values()) {
 400             if (lb.size() == 1) {
 401                 buf = buf.prepend(lb.first());
 402             } else {
 403                 AnnotationContext<T> ctx = new AnnotationContext<>(env, annotated, pos, typeAnnotations);
 404                 T res = makeContainerAnnotation(lb.toList(), ctx, toAnnotate, isTypeParam);
 405                 if (res != null)
 406                     buf = buf.prepend(res);
 407             }
 408         }
 409 
 410         if (typeAnnotations) {
 411             @SuppressWarnings("unchecked")
 412             List<TypeCompound> attrs = (List<TypeCompound>)buf.reverse();
 413             toAnnotate.appendUniqueTypeAttributes(attrs);
 414         } else {
 415             @SuppressWarnings("unchecked")
 416             List<Attribute.Compound> attrs =  (List<Attribute.Compound>)buf.reverse();
 417             toAnnotate.resetAnnotations();
 418             toAnnotate.setDeclarationAttributes(attrs);
 419         }
 420     }
 421     //where:
 422         private boolean isAttributeTrue(Attribute attr) {
 423             return (attr instanceof Attribute.Constant constant)
 424                     && constant.type == syms.booleanType
 425                     && ((Integer) constant.value) != 0;
 426         }
 427 
 428     /**
 429      * Attribute and store a semantic representation of the annotation tree {@code tree} into the
 430      * tree.attribute field.
 431      *
 432      * @param tree the tree representing an annotation
 433      * @param expectedAnnotationType the expected (super)type of the annotation
 434      * @param env the current env in where the annotation instance is found
 435      */
 436     public Attribute.Compound attributeAnnotation(JCAnnotation tree, Type expectedAnnotationType,
 437                                                   Env<AttrContext> env)
 438     {
 439         // The attribute might have been entered if it is Target or Repeatable
 440         // Because TreeCopier does not copy type, redo this if type is null
 441         if (tree.attribute != null && tree.type != null)
 442             return tree.attribute;
 443 
 444         List<Pair<MethodSymbol, Attribute>> elems = attributeAnnotationValues(tree, expectedAnnotationType, env);
 445         Attribute.Compound ac = new Attribute.Compound(tree.type, elems);
 446 
 447         return tree.attribute = ac;
 448     }
 449 
 450     /** Attribute and store a semantic representation of the type annotation tree {@code tree} into
 451      * the tree.attribute field.
 452      *
 453      * @param a the tree representing an annotation
 454      * @param expectedAnnotationType the expected (super)type of the annotation
 455      * @param env the current env in where the annotation instance is found
 456      */
 457     public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType,
 458                                                           Env<AttrContext> env)
 459     {
 460         // The attribute might have been entered if it is Target or Repeatable
 461         // Because TreeCopier does not copy type, redo this if type is null
 462         if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound typeCompound)) {
 463             // Create a new TypeCompound
 464             List<Pair<MethodSymbol,Attribute>> elems =
 465                     attributeAnnotationValues(a, expectedAnnotationType, env);
 466 
 467             Attribute.TypeCompound tc =
 468                     new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown);
 469             a.attribute = tc;
 470             return tc;
 471         } else {
 472             // Use an existing TypeCompound
 473             return typeCompound;
 474         }
 475     }
 476 
 477     /**
 478      *  Attribute annotation elements creating a list of pairs of the Symbol representing that
 479      *  element and the value of that element as an Attribute. */
 480     private List<Pair<MethodSymbol, Attribute>> attributeAnnotationValues(JCAnnotation a,
 481             Type expected, Env<AttrContext> env)
 482     {
 483         // The annotation might have had its type attributed (but not
 484         // checked) by attr.attribAnnotationTypes during MemberEnter,
 485         // in which case we do not need to do it again.
 486         Type at = (a.annotationType.type != null ?
 487                 a.annotationType.type : attr.attribType(a.annotationType, env));
 488         a.type = chk.checkType(a.annotationType.pos(), at, expected);
 489 
 490         boolean isError = a.type.isErroneous();
 491         if (!a.type.tsym.isAnnotationType() && !isError) {
 492             log.error(a.annotationType.pos(), Errors.NotAnnotationType(a.type));
 493             isError = true;
 494         }
 495 
 496         // List of name=value pairs (or implicit "value=" if size 1)
 497         List<JCExpression> args = a.args;
 498 
 499         boolean elidedValue = false;
 500         // special case: elided "value=" assumed
 501         if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
 502             args.head = make.at(args.head.pos).
 503                     Assign(make.Ident(names.value), args.head);
 504             elidedValue = true;
 505         }
 506 
 507         ListBuffer<Pair<MethodSymbol,Attribute>> buf = new ListBuffer<>();
 508         for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
 509             Pair<MethodSymbol, Attribute> p = attributeAnnotationNameValuePair(tl.head, a.type, isError, env, elidedValue);
 510             if (p != null && !p.fst.type.isErroneous())
 511                 buf.append(p);
 512         }
 513         return buf.toList();
 514     }
 515 
 516     // where
 517     private Pair<MethodSymbol, Attribute> attributeAnnotationNameValuePair(JCExpression nameValuePair,
 518             Type thisAnnotationType, boolean badAnnotation, Env<AttrContext> env, boolean elidedValue)
 519     {
 520         if (!nameValuePair.hasTag(ASSIGN)) {
 521             log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue);
 522             attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env);
 523             return null;
 524         }
 525         JCAssign assign = (JCAssign)nameValuePair;
 526         if (!assign.lhs.hasTag(IDENT)) {
 527             log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue);
 528             attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env);
 529             return null;
 530         }
 531 
 532         // Resolve element to MethodSym
 533         JCIdent left = (JCIdent)assign.lhs;
 534         Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(),
 535                 env, thisAnnotationType,
 536                 left.name, List.nil(), null);
 537         left.sym = method;
 538         left.type = method.type;
 539         chk.checkDeprecated(left, env.info.scope.owner, method);
 540         if (method.owner != thisAnnotationType.tsym && !badAnnotation)
 541             log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType));
 542         Type resultType = method.type.getReturnType();
 543 
 544         // Compute value part
 545         Attribute value = attributeAnnotationValue(resultType, assign.rhs, env);
 546         nameValuePair.type = resultType;
 547 
 548         return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value);
 549 
 550     }
 551 
 552     /** Attribute an annotation element value */
 553     private Attribute attributeAnnotationValue(Type expectedElementType, JCExpression tree,
 554             Env<AttrContext> env)
 555     {
 556         //first, try completing the symbol for the annotation value - if a completion
 557         //error is thrown, we should recover gracefully, and display an
 558         //ordinary resolution diagnostic.
 559         try {
 560             expectedElementType.tsym.complete();
 561         } catch(CompletionFailure e) {
 562             log.error(tree.pos(), Errors.CantResolve(Kinds.kindName(e.sym), e.sym.getQualifiedName(), null, null));
 563             expectedElementType = syms.errType;
 564         }
 565 
 566         if (expectedElementType.hasTag(ARRAY)) {
 567             return getAnnotationArrayValue(expectedElementType, tree, env);
 568         }
 569 
 570         //error recovery
 571         if (tree.hasTag(NEWARRAY)) {
 572             if (!expectedElementType.isErroneous())
 573                 log.error(tree.pos(), Errors.AnnotationValueNotAllowableType);
 574             JCNewArray na = (JCNewArray)tree;
 575             if (na.elemtype != null) {
 576                 log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation);
 577             }
 578             for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
 579                 attributeAnnotationValue(syms.errType,
 580                         l.head,
 581                         env);
 582             }
 583             return new Attribute.Error(syms.errType);
 584         }
 585 
 586         if (expectedElementType.tsym.isAnnotationType()) {
 587             if (tree.hasTag(ANNOTATION)) {
 588                 return attributeAnnotation((JCAnnotation)tree, expectedElementType, env);
 589             } else {
 590                 log.error(tree.pos(), Errors.AnnotationValueMustBeAnnotation);
 591                 expectedElementType = syms.errType;
 592             }
 593         }
 594 
 595         //error recovery
 596         if (tree.hasTag(ANNOTATION)) {
 597             if (!expectedElementType.isErroneous())
 598                 log.error(tree.pos(), Errors.AnnotationNotValidForType(expectedElementType));
 599             attributeAnnotation((JCAnnotation)tree, syms.errType, env);
 600             return new Attribute.Error(((JCAnnotation)tree).annotationType.type);
 601         }
 602 
 603         MemberEnter.InitTreeVisitor initTreeVisitor = new MemberEnter.InitTreeVisitor() {
 604             // the methods below are added to allow class literals on top of constant expressions
 605             @Override
 606             public void visitTypeIdent(JCPrimitiveTypeTree that) {}
 607 
 608             @Override
 609             public void visitTypeArray(JCArrayTypeTree that) {}
 610         };
 611         tree.accept(initTreeVisitor);
 612         if (!initTreeVisitor.result) {
 613             log.error(tree.pos(), Errors.ExpressionNotAllowableAsAnnotationValue);
 614             return new Attribute.Error(syms.errType);
 615         }
 616 
 617         if (expectedElementType.isPrimitive() ||
 618                 (types.isSameType(expectedElementType, syms.stringType) && !expectedElementType.hasTag(TypeTag.ERROR))) {
 619             return getAnnotationPrimitiveValue(expectedElementType, tree, env);
 620         }
 621 
 622         if (expectedElementType.tsym == syms.classType.tsym) {
 623             return getAnnotationClassValue(expectedElementType, tree, env);
 624         }
 625 
 626         if (expectedElementType.hasTag(CLASS) &&
 627                 (expectedElementType.tsym.flags() & Flags.ENUM) != 0) {
 628             return getAnnotationEnumValue(expectedElementType, tree, env);
 629         }
 630 
 631         //error recovery:
 632         if (!expectedElementType.isErroneous())
 633             log.error(tree.pos(), Errors.AnnotationValueNotAllowableType);
 634         return new Attribute.Error(attr.attribExpr(tree, env, expectedElementType));
 635     }
 636 
 637     private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
 638         Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType));
 639         Symbol sym = TreeInfo.symbol(tree);
 640         if (sym == null ||
 641                 TreeInfo.nonstaticSelect(tree) ||
 642                 sym.kind != VAR ||
 643                 (sym.flags() & Flags.ENUM) == 0) {
 644             log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant);
 645             return new Attribute.Error(result.getOriginalType());
 646         }
 647         VarSymbol enumerator = (VarSymbol) sym;
 648         return new Attribute.Enum(expectedElementType, enumerator);
 649     }
 650 
 651     private Attribute getAnnotationClassValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
 652         Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType));
 653         if (result.isErroneous()) {
 654             // Does it look like an unresolved class literal?
 655             if (TreeInfo.name(tree) == names._class &&
 656                     ((JCFieldAccess) tree).selected.type.isErroneous()) {
 657                 Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName();
 658                 return new Attribute.UnresolvedClass(expectedElementType,
 659                         types.createErrorType(n,
 660                                 syms.unknownSymbol, syms.classType));
 661             } else {
 662                 return new Attribute.Error(result.getOriginalType());
 663             }
 664         }
 665 
 666         // Class literals look like field accesses of a field named class
 667         // at the tree level
 668         if (TreeInfo.name(tree) != names._class) {
 669             log.error(tree.pos(), Errors.AnnotationValueMustBeClassLiteral);
 670             return new Attribute.Error(syms.errType);
 671         }
 672 
 673         return new Attribute.Class(types,
 674                 (((JCFieldAccess) tree).selected).type);
 675     }
 676 
 677     private Attribute getAnnotationPrimitiveValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
 678         Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType));
 679         if (result.isErroneous())
 680             return new Attribute.Error(result.getOriginalType());
 681         if (result.constValue() == null) {
 682             log.error(tree.pos(), Errors.AttributeValueMustBeConstant);
 683             return new Attribute.Error(expectedElementType);
 684         }
 685 
 686         // Scan the annotation element value and then attribute nested annotations if present
 687         if (tree.type != null && tree.type.tsym != null) {
 688             queueScanTreeAndTypeAnnotate(tree, env, tree.type.tsym);
 689         }
 690 
 691         result = cfolder.coerce(result, expectedElementType);
 692         return new Attribute.Constant(expectedElementType, result.constValue());
 693     }
 694 
 695     private Attr.ResultInfo annotationValueInfo(Type pt) {
 696         return attr.unknownExprInfo.dup(pt, new AnnotationValueContext(attr.unknownExprInfo.checkContext));
 697     }
 698 
 699     class AnnotationValueContext extends Check.NestedCheckContext {
 700         AnnotationValueContext(CheckContext enclosingContext) {
 701             super(enclosingContext);
 702         }
 703 
 704         @Override
 705         public boolean compatible(Type found, Type req, Warner warn) {
 706             //handle non-final implicitly-typed vars (will be rejected later on)
 707             return found.hasTag(TypeTag.NONE) || super.compatible(found, req, warn);
 708         }
 709     }
 710 
 711     private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
 712         // Special case, implicit array
 713         if (!tree.hasTag(NEWARRAY)) {
 714             tree = make.at(tree.pos).
 715                     NewArray(null, List.nil(), List.of(tree));
 716         }
 717 
 718         JCNewArray na = (JCNewArray)tree;
 719         List<JCExpression> elems = na.elems;
 720         if (na.elemtype != null) {
 721             log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation);
 722             if (elems == null) {
 723                 elems = List.nil();
 724             }
 725         }
 726         ListBuffer<Attribute> buf = new ListBuffer<>();
 727         for (List<JCExpression> l = elems; l.nonEmpty(); l = l.tail) {
 728             buf.append(attributeAnnotationValue(types.elemtype(expectedElementType),
 729                     l.head,
 730                     env));
 731         }
 732         na.type = expectedElementType;
 733         return new Attribute.
 734                 Array(expectedElementType, buf.toArray(new Attribute[buf.length()]));
 735     }
 736 
 737     /* *********************************
 738      * Support for repeating annotations
 739      ***********************************/
 740 
 741     /**
 742      * This context contains all the information needed to synthesize new
 743      * annotations trees for repeating annotations.
 744      */
 745     private class AnnotationContext<T extends Attribute.Compound> {
 746         public final Env<AttrContext> env;
 747         public final Map<Symbol.TypeSymbol, ListBuffer<T>> annotated;
 748         public final Map<T, JCDiagnostic.DiagnosticPosition> pos;
 749         public final boolean isTypeCompound;
 750 
 751         public AnnotationContext(Env<AttrContext> env,
 752                                  Map<Symbol.TypeSymbol, ListBuffer<T>> annotated,
 753                                  Map<T, JCDiagnostic.DiagnosticPosition> pos,
 754                                  boolean isTypeCompound) {
 755             Assert.checkNonNull(env);
 756             Assert.checkNonNull(annotated);
 757             Assert.checkNonNull(pos);
 758 
 759             this.env = env;
 760             this.annotated = annotated;
 761             this.pos = pos;
 762             this.isTypeCompound = isTypeCompound;
 763         }
 764     }
 765 
 766     /* Process repeated annotations. This method returns the
 767      * synthesized container annotation or null IFF all repeating
 768      * annotation are invalid.  This method reports errors/warnings.
 769      */
 770     private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
 771             AnnotationContext<T> ctx, Symbol on, boolean isTypeParam)
 772     {
 773         T firstOccurrence = annotations.head;
 774         List<Attribute> repeated = List.nil();
 775         Type origAnnoType = null;
 776         Type arrayOfOrigAnnoType = null;
 777         Type targetContainerType = null;
 778         MethodSymbol containerValueSymbol = null;
 779 
 780         Assert.check(!annotations.isEmpty() && !annotations.tail.isEmpty()); // i.e. size() > 1
 781 
 782         int count = 0;
 783         for (List<T> al = annotations; !al.isEmpty(); al = al.tail) {
 784             count++;
 785 
 786             // There must be more than a single anno in the annotation list
 787             Assert.check(count > 1 || !al.tail.isEmpty());
 788 
 789             T currentAnno = al.head;
 790 
 791             origAnnoType = currentAnno.type;
 792             if (arrayOfOrigAnnoType == null) {
 793                 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
 794             }
 795 
 796             // Only report errors if this isn't the first occurrence I.E. count > 1
 797             boolean reportError = count > 1;
 798             Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError);
 799             if (currentContainerType == null) {
 800                 continue;
 801             }
 802             // Assert that the target Container is == for all repeated
 803             // annos of the same annotation type, the types should
 804             // come from the same Symbol, i.e. be '=='
 805             Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
 806             targetContainerType = currentContainerType;
 807 
 808             containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
 809 
 810             if (containerValueSymbol == null) { // Check of CA type failed
 811                 // errors are already reported
 812                 continue;
 813             }
 814 
 815             repeated = repeated.prepend(currentAnno);
 816         }
 817 
 818         if (!repeated.isEmpty() && targetContainerType == null) {
 819             log.error(ctx.pos.get(annotations.head), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType));
 820             return null;
 821         }
 822 
 823         if (!repeated.isEmpty()) {
 824             repeated = repeated.reverse();
 825             DiagnosticPosition pos = ctx.pos.get(firstOccurrence);
 826             TreeMaker m = make.at(pos);
 827             Pair<MethodSymbol, Attribute> p =
 828                     new Pair<MethodSymbol, Attribute>(containerValueSymbol,
 829                             new Attribute.Array(arrayOfOrigAnnoType, repeated));
 830             if (ctx.isTypeCompound) {
 831                 /* TODO: the following code would be cleaner:
 832                 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
 833                         ((Attribute.TypeCompound)annotations.head).position);
 834                 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
 835                 at = attributeTypeAnnotation(annoTree, targetContainerType, ctx.env);
 836                 */
 837                 // However, we directly construct the TypeCompound to keep the
 838                 // direct relation to the contained TypeCompounds.
 839                 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
 840                         ((Attribute.TypeCompound)annotations.head).position);
 841 
 842                 JCAnnotation annoTree = m.TypeAnnotation(at);
 843                 if (!chk.validateAnnotationDeferErrors(annoTree))
 844                     log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType));
 845 
 846                 if (!chk.isTypeAnnotation(annoTree, isTypeParam)) {
 847                     log.error(pos, isTypeParam ? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)
 848                                                : Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType));
 849                 }
 850 
 851                 at.setSynthesized(true);
 852 
 853                 @SuppressWarnings("unchecked")
 854                 T x = (T) at;
 855                 return x;
 856             } else {
 857                 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
 858                 JCAnnotation annoTree = m.Annotation(c);
 859 
 860                 boolean isRecordMember = (on.flags_field & Flags.RECORD) != 0 || on.enclClass() != null && on.enclClass().isRecord();
 861                 /* if it is a record member we will not issue the error now and wait until annotations on records are
 862                  * checked at Check::validateAnnotation, which will issue it
 863                  */
 864                 if (!chk.annotationApplicable(annoTree, on) && (!isRecordMember || isRecordMember && (on.flags_field & Flags.GENERATED_MEMBER) == 0)) {
 865                     log.error(annoTree.pos(),
 866                               Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on));
 867                 }
 868 
 869                 if (!chk.validateAnnotationDeferErrors(annoTree))
 870                     log.error(annoTree.pos(), Errors.DuplicateAnnotationInvalidRepeated(origAnnoType));
 871 
 872                 c = attributeAnnotation(annoTree, targetContainerType, ctx.env);
 873                 c.setSynthesized(true);
 874 
 875                 @SuppressWarnings("unchecked")
 876                 T x = (T) c;
 877                 return x;
 878             }
 879         } else {
 880             return null; // errors should have been reported elsewhere
 881         }
 882     }
 883 
 884     /**
 885      * Fetches the actual Type that should be the containing annotation.
 886      */
 887     private Type getContainingType(Attribute.Compound currentAnno,
 888                                    DiagnosticPosition pos,
 889                                    boolean reportError)
 890     {
 891         Type origAnnoType = currentAnno.type;
 892         TypeSymbol origAnnoDecl = origAnnoType.tsym;
 893 
 894         // Fetch the Repeatable annotation from the current
 895         // annotation's declaration, or null if it has none
 896         Attribute.Compound ca = origAnnoDecl.getAnnotationTypeMetadata().getRepeatable();
 897         if (ca == null) { // has no Repeatable annotation
 898             if (reportError)
 899                 log.error(pos, Errors.DuplicateAnnotationMissingContainer(origAnnoType));
 900             return null;
 901         }
 902 
 903         return filterSame(extractContainingType(ca, pos, origAnnoDecl),
 904                 origAnnoType);
 905     }
 906 
 907     // returns null if t is same as 's', returns 't' otherwise
 908     private Type filterSame(Type t, Type s) {
 909         if (t == null || s == null) {
 910             return t;
 911         }
 912 
 913         return types.isSameType(t, s) ? null : t;
 914     }
 915 
 916     /** Extract the actual Type to be used for a containing annotation. */
 917     private Type extractContainingType(Attribute.Compound ca,
 918                                        DiagnosticPosition pos,
 919                                        TypeSymbol annoDecl)
 920     {
 921         // The next three checks check that the Repeatable annotation
 922         // on the declaration of the annotation type that is repeating is
 923         // valid.
 924 
 925         // Repeatable must have at least one element
 926         if (ca.values.isEmpty()) {
 927             log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
 928             return null;
 929         }
 930         Pair<MethodSymbol,Attribute> p = ca.values.head;
 931         Name name = p.fst.name;
 932         if (name != names.value) { // should contain only one element, named "value"
 933             log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
 934             return null;
 935         }
 936         if (!(p.snd instanceof Attribute.Class attributeClass)) { // check that the value of "value" is an Attribute.Class
 937             log.error(pos, Errors.InvalidRepeatableAnnotation(annoDecl));
 938             return null;
 939         }
 940 
 941         return attributeClass.getValue();
 942     }
 943 
 944     /* Validate that the suggested targetContainerType Type is a valid
 945      * container type for repeated instances of originalAnnoType
 946      * annotations. Return null and report errors if this is not the
 947      * case, return the MethodSymbol of the value element in
 948      * targetContainerType if it is suitable (this is needed to
 949      * synthesize the container). */
 950     private MethodSymbol validateContainer(Type targetContainerType,
 951                                            Type originalAnnoType,
 952                                            DiagnosticPosition pos) {
 953         MethodSymbol containerValueSymbol = null;
 954         boolean fatalError = false;
 955 
 956         // Validate that there is a (and only 1) value method
 957         Scope scope = null;
 958         try {
 959             scope = targetContainerType.tsym.members();
 960         } catch (CompletionFailure ex) {
 961             chk.completionError(pos, ex);
 962             return null;
 963         }
 964         int nr_value_elems = 0;
 965         boolean error = false;
 966         for(Symbol elm : scope.getSymbolsByName(names.value)) {
 967             nr_value_elems++;
 968 
 969             if (nr_value_elems == 1 &&
 970                     elm.kind == MTH) {
 971                 containerValueSymbol = (MethodSymbol)elm;
 972             } else {
 973                 error = true;
 974             }
 975         }
 976         if (error) {
 977             log.error(pos,
 978                       Errors.InvalidRepeatableAnnotationMultipleValues(targetContainerType,
 979                                                                        nr_value_elems));
 980             return null;
 981         } else if (nr_value_elems == 0) {
 982             log.error(pos,
 983                       Errors.InvalidRepeatableAnnotationNoValue(targetContainerType));
 984             return null;
 985         }
 986 
 987         // validate that the 'value' element is a method
 988         // probably "impossible" to fail this
 989         if (containerValueSymbol.kind != MTH) {
 990             log.error(pos,
 991                     Errors.InvalidRepeatableAnnotationInvalidValue(targetContainerType));
 992             fatalError = true;
 993         }
 994 
 995         // validate that the 'value' element has the correct return type
 996         // i.e. array of original anno
 997         Type valueRetType = containerValueSymbol.type.getReturnType();
 998         Type expectedType = types.makeArrayType(originalAnnoType);
 999         if (!(types.isArray(valueRetType) &&
1000                 types.isSameType(expectedType, valueRetType))) {
1001             log.error(pos,
1002                       Errors.InvalidRepeatableAnnotationValueReturn(targetContainerType,
1003                                                                     valueRetType,
1004                                                                     expectedType));
1005             fatalError = true;
1006         }
1007 
1008         return fatalError ? null : containerValueSymbol;
1009     }
1010 
1011     private <T extends Attribute.Compound> T makeContainerAnnotation(List<T> toBeReplaced,
1012             AnnotationContext<T> ctx, Symbol sym, boolean isTypeParam)
1013     {
1014         // Process repeated annotations
1015         T validRepeated =
1016                 processRepeatedAnnotations(toBeReplaced, ctx, sym, isTypeParam);
1017 
1018         if (validRepeated != null) {
1019             // Check that the container isn't manually
1020             // present along with repeated instances of
1021             // its contained annotation.
1022             ListBuffer<T> manualContainer = ctx.annotated.get(validRepeated.type.tsym);
1023             if (manualContainer != null) {
1024                 log.error(ctx.pos.get(manualContainer.first()),
1025                           Errors.InvalidRepeatableAnnotationRepeatedAndContainerPresent(manualContainer.first().type.tsym));
1026             }
1027         }
1028 
1029         // A null return will delete the Placeholder
1030         return validRepeated;
1031     }
1032 
1033     /* ******************
1034      * Type annotations *
1035      ********************/
1036 
1037     /**
1038      * Attribute the list of annotations and enter them onto s.
1039      */
1040     public void enterTypeAnnotations(List<JCAnnotation> annotations, Env<AttrContext> env, Symbol s, boolean isTypeParam)
1041     {
1042         Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/");
1043         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
1044 
1045         try {
1046             annotateNow(s, annotations, env, true, isTypeParam);
1047         } finally {
1048             log.useSource(prev);
1049         }
1050     }
1051 
1052     /**
1053      * Enqueue tree for scanning of type annotations, attaching to the Symbol sym.
1054      */
1055     public void queueScanTreeAndTypeAnnotate(JCTree tree, Env<AttrContext> env, Symbol sym)
1056     {
1057         Assert.checkNonNull(sym);
1058         normal(() -> tree.accept(new TypeAnnotate(env, sym)));
1059     }
1060 
1061     /**
1062      * Apply the annotations to the particular type.
1063      */
1064     public void annotateTypeSecondStage(JCTree tree, List<JCAnnotation> annotations, Type storeAt) {
1065         typeAnnotation(() -> {
1066             List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
1067             Assert.check(annotations.size() == compounds.size());
1068             // the type already has annotation metadata, but it's empty
1069             Annotations metadata = storeAt.getMetadata(Annotations.class);
1070             Assert.checkNonNull(metadata);
1071             Assert.check(metadata.annotationBuffer().isEmpty());
1072             metadata.annotationBuffer().appendList(compounds);
1073         });
1074     }
1075 
1076     /**
1077      * Apply the annotations to the particular type.
1078      */
1079     public void annotateTypeParameterSecondStage(JCTree tree, List<JCAnnotation> annotations) {
1080         typeAnnotation(() -> {
1081             List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
1082             Assert.check(annotations.size() == compounds.size());
1083         });
1084     }
1085 
1086     /**
1087      * We need to use a TreeScanner, because it is not enough to visit the top-level
1088      * annotations. We also need to visit type arguments, etc.
1089      */
1090     private class TypeAnnotate extends TreeScanner {
1091         private final Env<AttrContext> env;
1092         private final Symbol sym;
1093 
1094         public TypeAnnotate(Env<AttrContext> env, Symbol sym) {
1095 
1096             this.env = env;
1097             this.sym = sym;
1098         }
1099 
1100         @Override
1101         public void visitAnnotatedType(JCAnnotatedType tree) {
1102             enterTypeAnnotations(tree.annotations, env, sym, false);
1103             scan(tree.underlyingType);
1104         }
1105 
1106         @Override
1107         public void visitTypeParameter(JCTypeParameter tree) {
1108             enterTypeAnnotations(tree.annotations, env, sym, true);
1109             scan(tree.bounds);
1110         }
1111 
1112         @Override
1113         public void visitNewArray(JCNewArray tree) {
1114             enterTypeAnnotations(tree.annotations, env, sym, false);
1115             for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
1116                 enterTypeAnnotations(dimAnnos, env, sym, false);
1117             scan(tree.elemtype);
1118             scan(tree.dims);
1119             scan(tree.elems);
1120         }
1121 
1122         @Override
1123         public void visitMethodDef(JCMethodDecl tree) {
1124             scan(tree.mods);
1125             scan(tree.restype);
1126             scan(tree.typarams);
1127             scan(tree.recvparam);
1128             scan(tree.params);
1129             scan(tree.thrown);
1130             scan(tree.defaultValue);
1131             // Do not annotate the body, just the signature.
1132         }
1133 
1134         @Override
1135         public void visitVarDef(JCVariableDecl tree) {
1136             if (sym != null && sym.kind == VAR) {
1137                 // Don't visit a parameter once when the sym is the method
1138                 // and once when the sym is the parameter.
1139                 scan(tree.mods);
1140                 scan(tree.vartype);
1141             }
1142             scan(tree.init);
1143         }
1144 
1145         @Override
1146         public void visitBindingPattern(JCTree.JCBindingPattern tree) {
1147             //type binding pattern's type will be annotated separately, avoid
1148             //adding its annotations into the owning method here (would clash
1149             //with repeatable annotations).
1150         }
1151 
1152         @Override
1153         public void visitClassDef(JCClassDecl tree) {
1154             // We can only hit a classdef if it is declared within
1155             // a method. Ignore it - the class will be visited
1156             // separately later.
1157         }
1158 
1159         @Override
1160         public void visitNewClass(JCNewClass tree) {
1161             scan(tree.encl);
1162             scan(tree.typeargs);
1163             try {
1164                 env.info.isAnonymousNewClass = tree.def != null;
1165                 scan(tree.clazz);
1166             } finally {
1167                 env.info.isAnonymousNewClass = false;
1168             }
1169             scan(tree.args);
1170             // the anonymous class instantiation if any will be visited separately.
1171         }
1172 
1173         @Override
1174         public void visitErroneous(JCErroneous tree) {
1175             if (tree.errs != null) {
1176                 for (JCTree err : tree.errs) {
1177                     scan(err);
1178                 }
1179             }
1180         }
1181     }
1182 
1183     /* *******************
1184      * Completer support *
1185      *********************/
1186 
1187     private AnnotationTypeCompleter theSourceCompleter = new AnnotationTypeCompleter() {
1188         @Override
1189         public void complete(ClassSymbol sym) throws CompletionFailure {
1190             Env<AttrContext> context = typeEnvs.get(sym);
1191             Annotate.this.attributeAnnotationType(context);
1192         }
1193     };
1194 
1195     /* Last stage completer to enter just enough annotations to have a prototype annotation type.
1196      * This currently means entering @Target and @Repeatable.
1197      */
1198     public AnnotationTypeCompleter annotationTypeSourceCompleter() {
1199         return theSourceCompleter;
1200     }
1201 
1202     private void attributeAnnotationType(Env<AttrContext> env) {
1203         Assert.check(((JCClassDecl)env.tree).sym.isAnnotationType(),
1204                 "Trying to annotation type complete a non-annotation type");
1205 
1206         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
1207         try {
1208             JCClassDecl tree = (JCClassDecl)env.tree;
1209             AnnotationTypeVisitor v = new AnnotationTypeVisitor(attr, chk, syms, typeEnvs);
1210             v.scanAnnotationType(tree);
1211             tree.sym.getAnnotationTypeMetadata().setRepeatable(v.repeatable);
1212             tree.sym.getAnnotationTypeMetadata().setTarget(v.target);
1213         } finally {
1214             log.useSource(prev);
1215         }
1216     }
1217 
1218     public Attribute unfinishedDefaultValue() {
1219         return theUnfinishedDefaultValue;
1220     }
1221 
1222     public static interface AnnotationTypeCompleter {
1223         void complete(ClassSymbol sym) throws CompletionFailure;
1224     }
1225 
1226     /** Visitor to determine a prototype annotation type for a class declaring an annotation type.
1227      *
1228      *  <p><b>This is NOT part of any supported API.
1229      *  If you write code that depends on this, you do so at your own risk.
1230      *  This code and its internal interfaces are subject to change or
1231      *  deletion without notice.</b>
1232      */
1233     public class AnnotationTypeVisitor extends TreeScanner {
1234         private Env<AttrContext> env;
1235 
1236         private final Attr attr;
1237         private final Check check;
1238         private final Symtab tab;
1239         private final TypeEnvs typeEnvs;
1240 
1241         private Compound target;
1242         private Compound repeatable;
1243 
1244         public AnnotationTypeVisitor(Attr attr, Check check, Symtab tab, TypeEnvs typeEnvs) {
1245             this.attr = attr;
1246             this.check = check;
1247             this.tab = tab;
1248             this.typeEnvs = typeEnvs;
1249         }
1250 
1251         public Compound getRepeatable() {
1252             return repeatable;
1253         }
1254 
1255         public Compound getTarget() {
1256             return target;
1257         }
1258 
1259         public void scanAnnotationType(JCClassDecl decl) {
1260             visitClassDef(decl);
1261         }
1262 
1263         @Override
1264         public void visitClassDef(JCClassDecl tree) {
1265             Env<AttrContext> prevEnv = env;
1266             env = typeEnvs.get(tree.sym);
1267             try {
1268                 scan(tree.mods); // look for repeatable and target
1269                 // don't descend into body
1270             } finally {
1271                 env = prevEnv;
1272             }
1273         }
1274 
1275         @Override
1276         public void visitAnnotation(JCAnnotation tree) {
1277             Type t = tree.annotationType.type;
1278             if (t == null) {
1279                 t = attr.attribType(tree.annotationType, env);
1280                 tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType);
1281             }
1282 
1283             if (t == tab.annotationTargetType) {
1284                 target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env);
1285             } else if (t == tab.repeatableType) {
1286                 repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env);
1287             }
1288         }
1289     }
1290 
1291     /** Represents the semantics of an Annotation Type.
1292      *
1293      *  <p><b>This is NOT part of any supported API.
1294      *  If you write code that depends on this, you do so at your own risk.
1295      *  This code and its internal interfaces are subject to change or
1296      *  deletion without notice.</b>
1297      */
1298     public static class AnnotationTypeMetadata {
1299         final ClassSymbol metaDataFor;
1300         private Compound target;
1301         private Compound repeatable;
1302         private AnnotationTypeCompleter annotationTypeCompleter;
1303 
1304         public AnnotationTypeMetadata(ClassSymbol metaDataFor, AnnotationTypeCompleter annotationTypeCompleter) {
1305             this.metaDataFor = metaDataFor;
1306             this.annotationTypeCompleter = annotationTypeCompleter;
1307         }
1308 
1309         private void init() {
1310             // Make sure metaDataFor is member entered
1311             while (!metaDataFor.isCompleted())
1312                 metaDataFor.complete();
1313 
1314             if (annotationTypeCompleter != null) {
1315                 AnnotationTypeCompleter c = annotationTypeCompleter;
1316                 annotationTypeCompleter = null;
1317                 c.complete(metaDataFor);
1318             }
1319         }
1320 
1321         public void complete() {
1322             init();
1323         }
1324 
1325         public Compound getRepeatable() {
1326             init();
1327             return repeatable;
1328         }
1329 
1330         public void setRepeatable(Compound repeatable) {
1331             Assert.checkNull(this.repeatable);
1332             this.repeatable = repeatable;
1333         }
1334 
1335         public Compound getTarget() {
1336             init();
1337             return target;
1338         }
1339 
1340         public void setTarget(Compound target) {
1341             Assert.checkNull(this.target);
1342                 this.target = target;
1343         }
1344 
1345         public Set<MethodSymbol> getAnnotationElements() {
1346             init();
1347             Set<MethodSymbol> members = new LinkedHashSet<>();
1348             WriteableScope s = metaDataFor.members();
1349             Iterable<Symbol> ss = s.getSymbols(NON_RECURSIVE);
1350             for (Symbol sym : ss)
1351                 if (sym.kind == MTH &&
1352                         sym.name != sym.name.table.names.clinit &&
1353                         (sym.flags() & SYNTHETIC) == 0)
1354                     members.add((MethodSymbol)sym);
1355             return members;
1356         }
1357 
1358         public Set<MethodSymbol> getAnnotationElementsWithDefault() {
1359             init();
1360             Set<MethodSymbol> members = getAnnotationElements();
1361             Set<MethodSymbol> res = new LinkedHashSet<>();
1362             for (MethodSymbol m : members)
1363                 if (m.defaultValue != null)
1364                     res.add(m);
1365             return res;
1366         }
1367 
1368         @Override
1369         public String toString() {
1370             return "Annotation type for: " + metaDataFor;
1371         }
1372 
1373         public boolean isMetadataForAnnotationType() { return true; }
1374 
1375         public static AnnotationTypeMetadata notAnAnnotationType() {
1376             return NOT_AN_ANNOTATION_TYPE;
1377         }
1378 
1379         private static final AnnotationTypeMetadata NOT_AN_ANNOTATION_TYPE =
1380                 new AnnotationTypeMetadata(null, null) {
1381                     @Override
1382                     public void complete() {
1383                     } // do nothing
1384 
1385                     @Override
1386                     public String toString() {
1387                         return "Not an annotation type";
1388                     }
1389 
1390                     @Override
1391                     public Set<MethodSymbol> getAnnotationElements() {
1392                         return new LinkedHashSet<>(0);
1393                     }
1394 
1395                     @Override
1396                     public Set<MethodSymbol> getAnnotationElementsWithDefault() {
1397                         return new LinkedHashSet<>(0);
1398                     }
1399 
1400                     @Override
1401                     public boolean isMetadataForAnnotationType() {
1402                         return false;
1403                     }
1404 
1405                     @Override
1406                     public Compound getTarget() {
1407                         return null;
1408                     }
1409 
1410                     @Override
1411                     public Compound getRepeatable() {
1412                         return null;
1413                     }
1414                 };
1415     }
1416 
1417     public void newRound() {
1418         blockCount = 1;
1419     }
1420 
1421     public Queues setQueues(Queues nue) {
1422         Queues stored = new Queues(q, validateQ, typesQ, afterTypesQ);
1423         this.q = nue.q;
1424         this.typesQ = nue.typesQ;
1425         this.afterTypesQ = nue.afterTypesQ;
1426         this.validateQ = nue.validateQ;
1427         return stored;
1428     }
1429 
1430     static class Queues {
1431         private final ListBuffer<Runnable> q;
1432         private final ListBuffer<Runnable> validateQ;
1433         private final ListBuffer<Runnable> typesQ;
1434         private final ListBuffer<Runnable> afterTypesQ;
1435 
1436         public Queues() {
1437             this(new ListBuffer<Runnable>(), new ListBuffer<Runnable>(), new ListBuffer<Runnable>(), new ListBuffer<Runnable>());
1438         }
1439 
1440         public Queues(ListBuffer<Runnable> q, ListBuffer<Runnable> validateQ, ListBuffer<Runnable> typesQ, ListBuffer<Runnable> afterTypesQ) {
1441             this.q = q;
1442             this.validateQ = validateQ;
1443             this.typesQ = typesQ;
1444             this.afterTypesQ = afterTypesQ;
1445         }
1446     }
1447 }