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