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