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