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