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