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