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