src/share/classes/com/sun/tools/javac/comp/Annotate.java

Mon, 11 Nov 2013 09:47:46 -0500

author
emc
date
Mon, 11 Nov 2013 09:47:46 -0500
changeset 2187
4788eb38cac5
parent 2136
7f6481e5fe3a
child 2188
f3ca12d680f3
permissions
-rw-r--r--

8027439: Compile-time error in the case of ((Integer[] & Serializable)new Integer[1]).getClass()
8027253: javac illegally accepts array as bound
Summary: backing out change allowing arrays in intersection types
Reviewed-by: vromero

     1 /*
     2  * Copyright (c) 2003, 2013, 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  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.Map;
    30 import com.sun.tools.javac.util.*;
    31 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    32 import com.sun.tools.javac.code.*;
    33 import com.sun.tools.javac.code.Symbol.*;
    34 import com.sun.tools.javac.tree.*;
    35 import com.sun.tools.javac.tree.JCTree.*;
    37 import static com.sun.tools.javac.code.TypeTag.ARRAY;
    38 import static com.sun.tools.javac.code.TypeTag.CLASS;
    39 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    40 import javax.lang.model.type.ErrorType;
    42 /** Enter annotations on symbols.  Annotations accumulate in a queue,
    43  *  which is processed at the top level of any set of recursive calls
    44  *  requesting it be processed.
    45  *
    46  *  <p><b>This is NOT part of any supported API.
    47  *  If you write code that depends on this, you do so at your own risk.
    48  *  This code and its internal interfaces are subject to change or
    49  *  deletion without notice.</b>
    50  */
    51 public class Annotate {
    52     protected static final Context.Key<Annotate> annotateKey =
    53         new Context.Key<Annotate>();
    55     public static Annotate instance(Context context) {
    56         Annotate instance = context.get(annotateKey);
    57         if (instance == null)
    58             instance = new Annotate(context);
    59         return instance;
    60     }
    62     final Attr attr;
    63     final TreeMaker make;
    64     final Log log;
    65     final Symtab syms;
    66     final Names names;
    67     final Resolve rs;
    68     final Types types;
    69     final ConstFold cfolder;
    70     final Check chk;
    72     protected Annotate(Context context) {
    73         context.put(annotateKey, this);
    74         attr = Attr.instance(context);
    75         make = TreeMaker.instance(context);
    76         log = Log.instance(context);
    77         syms = Symtab.instance(context);
    78         names = Names.instance(context);
    79         rs = Resolve.instance(context);
    80         types = Types.instance(context);
    81         cfolder = ConstFold.instance(context);
    82         chk = Check.instance(context);
    83     }
    85 /* ********************************************************************
    86  * Queue maintenance
    87  *********************************************************************/
    89     private int enterCount = 0;
    91     ListBuffer<Worker> q = new ListBuffer<Worker>();
    92     ListBuffer<Worker> typesQ = new ListBuffer<Worker>();
    93     ListBuffer<Worker> repeatedQ = new ListBuffer<Worker>();
    94     ListBuffer<Worker> afterRepeatedQ = new ListBuffer<Worker>();
    95     ListBuffer<Worker> validateQ = new ListBuffer<Worker>();
    97     public void earlier(Worker a) {
    98         q.prepend(a);
    99     }
   101     public void normal(Worker a) {
   102         q.append(a);
   103     }
   105     public void typeAnnotation(Worker a) {
   106         typesQ.append(a);
   107     }
   109     public void repeated(Worker a) {
   110         repeatedQ.append(a);
   111     }
   113     public void afterRepeated(Worker a) {
   114         afterRepeatedQ.append(a);
   115     }
   117     public void validate(Worker a) {
   118         validateQ.append(a);
   119     }
   121     /** Called when the Enter phase starts. */
   122     public void enterStart() {
   123         enterCount++;
   124     }
   126     /** Called after the Enter phase completes. */
   127     public void enterDone() {
   128         enterCount--;
   129         flush();
   130     }
   132     /** Variant which allows for a delayed flush of annotations.
   133      * Needed by ClassReader */
   134     public void enterDoneWithoutFlush() {
   135         enterCount--;
   136     }
   138     public void flush() {
   139         if (enterCount != 0) return;
   140         enterCount++;
   141         try {
   142             while (q.nonEmpty()) {
   143                 q.next().run();
   144             }
   145             while (typesQ.nonEmpty()) {
   146                 typesQ.next().run();
   147             }
   148             while (repeatedQ.nonEmpty()) {
   149                 repeatedQ.next().run();
   150             }
   151             while (afterRepeatedQ.nonEmpty()) {
   152                 afterRepeatedQ.next().run();
   153             }
   154             while (validateQ.nonEmpty()) {
   155                 validateQ.next().run();
   156             }
   157         } finally {
   158             enterCount--;
   159         }
   160     }
   162     /** A client that needs to run during {@link #flush()} registers an worker
   163      *  into one of the queues defined in this class. The queues are: {@link #earlier(Worker)},
   164      *  {@link #normal(Worker)}, {@link #typeAnnotation(Worker)}, {@link #repeated(Worker)},
   165      *  {@link #afterRepeated(Worker)}, {@link #validate(Worker)}.
   166      *  The {@link Worker#run()} method will called inside the {@link #flush()}
   167      *  call. Queues are empties in the abovementioned order.
   168      */
   169     public interface Worker {
   170         void run();
   171         String toString();
   172     }
   174     /**
   175      * This context contains all the information needed to synthesize new
   176      * annotations trees by the completer for repeating annotations.
   177      */
   178     public class AnnotateRepeatedContext<T extends Attribute.Compound> {
   179         public final Env<AttrContext> env;
   180         public final Map<Symbol.TypeSymbol, ListBuffer<T>> annotated;
   181         public final Map<T, JCDiagnostic.DiagnosticPosition> pos;
   182         public final Log log;
   183         public final boolean isTypeCompound;
   185         public AnnotateRepeatedContext(Env<AttrContext> env,
   186                                        Map<Symbol.TypeSymbol, ListBuffer<T>> annotated,
   187                                        Map<T, JCDiagnostic.DiagnosticPosition> pos,
   188                                        Log log,
   189                                        boolean isTypeCompound) {
   190             Assert.checkNonNull(env);
   191             Assert.checkNonNull(annotated);
   192             Assert.checkNonNull(pos);
   193             Assert.checkNonNull(log);
   195             this.env = env;
   196             this.annotated = annotated;
   197             this.pos = pos;
   198             this.log = log;
   199             this.isTypeCompound = isTypeCompound;
   200         }
   202         /**
   203          * Process a list of repeating annotations returning a new
   204          * Attribute.Compound that is the attribute for the synthesized tree
   205          * for the container.
   206          *
   207          * @param repeatingAnnotations a List of repeating annotations
   208          * @return a new Attribute.Compound that is the container for the repeatingAnnotations
   209          */
   210         public T processRepeatedAnnotations(List<T> repeatingAnnotations, Symbol sym) {
   211             return Annotate.this.processRepeatedAnnotations(repeatingAnnotations, this, sym);
   212         }
   214         /**
   215          * Queue the Worker a on the repeating annotations queue of the
   216          * Annotate instance this context belongs to.
   217          *
   218          * @param a the Worker to enqueue for repeating annotation annotating
   219          */
   220         public void annotateRepeated(Worker a) {
   221             Annotate.this.repeated(a);
   222         }
   223     }
   225 /* ********************************************************************
   226  * Compute an attribute from its annotation.
   227  *********************************************************************/
   229     /** Process a single compound annotation, returning its
   230      *  Attribute. Used from MemberEnter for attaching the attributes
   231      *  to the annotated symbol.
   232      */
   233     Attribute.Compound enterAnnotation(JCAnnotation a,
   234                                        Type expected,
   235                                        Env<AttrContext> env) {
   236         return enterAnnotation(a, expected, env, false);
   237     }
   239     Attribute.TypeCompound enterTypeAnnotation(JCAnnotation a,
   240             Type expected,
   241             Env<AttrContext> env) {
   242         return (Attribute.TypeCompound) enterAnnotation(a, expected, env, true);
   243     }
   245     // boolean typeAnnotation determines whether the method returns
   246     // a Compound (false) or TypeCompound (true).
   247     Attribute.Compound enterAnnotation(JCAnnotation a,
   248             Type expected,
   249             Env<AttrContext> env,
   250             boolean typeAnnotation) {
   251         // The annotation might have had its type attributed (but not checked)
   252         // by attr.attribAnnotationTypes during MemberEnter, in which case we do not
   253         // need to do it again.
   254         Type at = (a.annotationType.type != null ? a.annotationType.type
   255                   : attr.attribType(a.annotationType, env));
   256         a.type = chk.checkType(a.annotationType.pos(), at, expected);
   257         if (a.type.isErroneous()) {
   258             if (typeAnnotation) {
   259                 return new Attribute.TypeCompound(a.type, List.<Pair<MethodSymbol,Attribute>>nil(),
   260                         new TypeAnnotationPosition());
   261             } else {
   262                 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
   263             }
   264         }
   265         if ((a.type.tsym.flags() & Flags.ANNOTATION) == 0) {
   266             log.error(a.annotationType.pos(),
   267                       "not.annotation.type", a.type.toString());
   268             if (typeAnnotation) {
   269                 return new Attribute.TypeCompound(a.type, List.<Pair<MethodSymbol,Attribute>>nil(), null);
   270             } else {
   271                 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
   272             }
   273         }
   274         List<JCExpression> args = a.args;
   275         if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
   276             // special case: elided "value=" assumed
   277             args.head = make.at(args.head.pos).
   278                 Assign(make.Ident(names.value), args.head);
   279         }
   280         ListBuffer<Pair<MethodSymbol,Attribute>> buf =
   281             new ListBuffer<Pair<MethodSymbol,Attribute>>();
   282         for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
   283             JCExpression t = tl.head;
   284             if (!t.hasTag(ASSIGN)) {
   285                 log.error(t.pos(), "annotation.value.must.be.name.value");
   286                 continue;
   287             }
   288             JCAssign assign = (JCAssign)t;
   289             if (!assign.lhs.hasTag(IDENT)) {
   290                 log.error(t.pos(), "annotation.value.must.be.name.value");
   291                 continue;
   292             }
   293             JCIdent left = (JCIdent)assign.lhs;
   294             Symbol method = rs.resolveQualifiedMethod(assign.rhs.pos(),
   295                                                           env,
   296                                                           a.type,
   297                                                           left.name,
   298                                                           List.<Type>nil(),
   299                                                           null);
   300             left.sym = method;
   301             left.type = method.type;
   302             if (method.owner != a.type.tsym)
   303                 log.error(left.pos(), "no.annotation.member", left.name, a.type);
   304             Type result = method.type.getReturnType();
   305             Attribute value = enterAttributeValue(result, assign.rhs, env);
   306             if (!method.type.isErroneous())
   307                 buf.append(new Pair<MethodSymbol,Attribute>
   308                            ((MethodSymbol)method, value));
   309             t.type = result;
   310         }
   311         if (typeAnnotation) {
   312             if (a.attribute == null || !(a.attribute instanceof Attribute.TypeCompound)) {
   313                 // Create a new TypeCompound
   314                 Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, buf.toList(), new TypeAnnotationPosition());
   315                 a.attribute = tc;
   316                 return tc;
   317             } else {
   318                 // Use an existing TypeCompound
   319                 return a.attribute;
   320             }
   321         } else {
   322             Attribute.Compound ac = new Attribute.Compound(a.type, buf.toList());
   323             a.attribute = ac;
   324             return ac;
   325         }
   326     }
   328     Attribute enterAttributeValue(Type expected,
   329                                   JCExpression tree,
   330                                   Env<AttrContext> env) {
   331         //first, try completing the attribution value sym - if a completion
   332         //error is thrown, we should recover gracefully, and display an
   333         //ordinary resolution diagnostic.
   334         try {
   335             expected.tsym.complete();
   336         } catch(CompletionFailure e) {
   337             log.error(tree.pos(), "cant.resolve", Kinds.kindName(e.sym), e.sym);
   338             expected = syms.errType;
   339         }
   340         if (expected.hasTag(ARRAY)) {
   341             if (!tree.hasTag(NEWARRAY)) {
   342                 tree = make.at(tree.pos).
   343                     NewArray(null, List.<JCExpression>nil(), List.of(tree));
   344             }
   345             JCNewArray na = (JCNewArray)tree;
   346             if (na.elemtype != null) {
   347                 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
   348             }
   349             ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
   350             for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
   351                 buf.append(enterAttributeValue(types.elemtype(expected),
   352                                                l.head,
   353                                                env));
   354             }
   355             na.type = expected;
   356             return new Attribute.
   357                 Array(expected, buf.toArray(new Attribute[buf.length()]));
   358         }
   359         if (tree.hasTag(NEWARRAY)) { //error recovery
   360             if (!expected.isErroneous())
   361                 log.error(tree.pos(), "annotation.value.not.allowable.type");
   362             JCNewArray na = (JCNewArray)tree;
   363             if (na.elemtype != null) {
   364                 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
   365             }
   366             for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
   367                 enterAttributeValue(syms.errType,
   368                                     l.head,
   369                                     env);
   370             }
   371             return new Attribute.Error(syms.errType);
   372         }
   373         if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
   374             if (tree.hasTag(ANNOTATION)) {
   375                 return enterAnnotation((JCAnnotation)tree, expected, env);
   376             } else {
   377                 log.error(tree.pos(), "annotation.value.must.be.annotation");
   378                 expected = syms.errType;
   379             }
   380         }
   381         if (tree.hasTag(ANNOTATION)) { //error recovery
   382             if (!expected.isErroneous())
   383                 log.error(tree.pos(), "annotation.not.valid.for.type", expected);
   384             enterAnnotation((JCAnnotation)tree, syms.errType, env);
   385             return new Attribute.Error(((JCAnnotation)tree).annotationType.type);
   386         }
   387         if (expected.isPrimitive() || types.isSameType(expected, syms.stringType)) {
   388             Type result = attr.attribExpr(tree, env, expected);
   389             if (result.isErroneous())
   390                 return new Attribute.Error(result.getOriginalType());
   391             if (result.constValue() == null) {
   392                 log.error(tree.pos(), "attribute.value.must.be.constant");
   393                 return new Attribute.Error(expected);
   394             }
   395             result = cfolder.coerce(result, expected);
   396             return new Attribute.Constant(expected, result.constValue());
   397         }
   398         if (expected.tsym == syms.classType.tsym) {
   399             Type result = attr.attribExpr(tree, env, expected);
   400             if (result.isErroneous()) {
   401                 // Does it look like an unresolved class literal?
   402                 if (TreeInfo.name(tree) == names._class &&
   403                     ((JCFieldAccess) tree).selected.type.isErroneous()) {
   404                     Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName();
   405                     return new Attribute.UnresolvedClass(expected,
   406                             types.createErrorType(n,
   407                                     syms.unknownSymbol, syms.classType));
   408                 } else {
   409                     return new Attribute.Error(result.getOriginalType());
   410                 }
   411             }
   413             // Class literals look like field accesses of a field named class
   414             // at the tree level
   415             if (TreeInfo.name(tree) != names._class) {
   416                 log.error(tree.pos(), "annotation.value.must.be.class.literal");
   417                 return new Attribute.Error(syms.errType);
   418             }
   419             return new Attribute.Class(types,
   420                                        (((JCFieldAccess) tree).selected).type);
   421         }
   422         if (expected.hasTag(CLASS) &&
   423             (expected.tsym.flags() & Flags.ENUM) != 0) {
   424             Type result = attr.attribExpr(tree, env, expected);
   425             Symbol sym = TreeInfo.symbol(tree);
   426             if (sym == null ||
   427                 TreeInfo.nonstaticSelect(tree) ||
   428                 sym.kind != Kinds.VAR ||
   429                 (sym.flags() & Flags.ENUM) == 0) {
   430                 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
   431                 return new Attribute.Error(result.getOriginalType());
   432             }
   433             VarSymbol enumerator = (VarSymbol) sym;
   434             return new Attribute.Enum(expected, enumerator);
   435         }
   436         //error recovery:
   437         if (!expected.isErroneous())
   438             log.error(tree.pos(), "annotation.value.not.allowable.type");
   439         return new Attribute.Error(attr.attribExpr(tree, env, expected));
   440     }
   442     /* *********************************
   443      * Support for repeating annotations
   444      ***********************************/
   446     /* Process repeated annotations. This method returns the
   447      * synthesized container annotation or null IFF all repeating
   448      * annotation are invalid.  This method reports errors/warnings.
   449      */
   450     private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
   451             AnnotateRepeatedContext<T> ctx,
   452             Symbol on) {
   453         T firstOccurrence = annotations.head;
   454         List<Attribute> repeated = List.nil();
   455         Type origAnnoType = null;
   456         Type arrayOfOrigAnnoType = null;
   457         Type targetContainerType = null;
   458         MethodSymbol containerValueSymbol = null;
   460         Assert.check(!annotations.isEmpty() &&
   461                      !annotations.tail.isEmpty()); // i.e. size() > 1
   463         int count = 0;
   464         for (List<T> al = annotations;
   465              !al.isEmpty();
   466              al = al.tail)
   467         {
   468             count++;
   470             // There must be more than a single anno in the annotation list
   471             Assert.check(count > 1 || !al.tail.isEmpty());
   473             T currentAnno = al.head;
   475             origAnnoType = currentAnno.type;
   476             if (arrayOfOrigAnnoType == null) {
   477                 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
   478             }
   480             // Only report errors if this isn't the first occurrence I.E. count > 1
   481             boolean reportError = count > 1;
   482             Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError);
   483             if (currentContainerType == null) {
   484                 continue;
   485             }
   486             // Assert that the target Container is == for all repeated
   487             // annos of the same annotation type, the types should
   488             // come from the same Symbol, i.e. be '=='
   489             Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
   490             targetContainerType = currentContainerType;
   492             containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
   494             if (containerValueSymbol == null) { // Check of CA type failed
   495                 // errors are already reported
   496                 continue;
   497             }
   499             repeated = repeated.prepend(currentAnno);
   500         }
   502         if (!repeated.isEmpty()) {
   503             repeated = repeated.reverse();
   504             TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
   505             Pair<MethodSymbol, Attribute> p =
   506                     new Pair<MethodSymbol, Attribute>(containerValueSymbol,
   507                                                       new Attribute.Array(arrayOfOrigAnnoType, repeated));
   508             if (ctx.isTypeCompound) {
   509                 /* TODO: the following code would be cleaner:
   510                 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
   511                         ((Attribute.TypeCompound)annotations.head).position);
   512                 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
   513                 at = enterTypeAnnotation(annoTree, targetContainerType, ctx.env);
   514                 */
   515                 // However, we directly construct the TypeCompound to keep the
   516                 // direct relation to the contained TypeCompounds.
   517                 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
   518                         ((Attribute.TypeCompound)annotations.head).position);
   520                 // TODO: annotation applicability checks from below?
   522                 at.setSynthesized(true);
   524                 @SuppressWarnings("unchecked")
   525                 T x = (T) at;
   526                 return x;
   527             } else {
   528                 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
   529                 JCAnnotation annoTree = m.Annotation(c);
   531                 if (!chk.annotationApplicable(annoTree, on))
   532                     log.error(annoTree.pos(), "invalid.repeatable.annotation.incompatible.target", targetContainerType, origAnnoType);
   534                 if (!chk.validateAnnotationDeferErrors(annoTree))
   535                     log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
   537                 c = enterAnnotation(annoTree, targetContainerType, ctx.env);
   538                 c.setSynthesized(true);
   540                 @SuppressWarnings("unchecked")
   541                 T x = (T) c;
   542                 return x;
   543             }
   544         } else {
   545             return null; // errors should have been reported elsewhere
   546         }
   547     }
   549     /** Fetches the actual Type that should be the containing annotation. */
   550     private Type getContainingType(Attribute.Compound currentAnno,
   551             DiagnosticPosition pos,
   552             boolean reportError)
   553     {
   554         Type origAnnoType = currentAnno.type;
   555         TypeSymbol origAnnoDecl = origAnnoType.tsym;
   557         // Fetch the Repeatable annotation from the current
   558         // annotation's declaration, or null if it has none
   559         Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym);
   560         if (ca == null) { // has no Repeatable annotation
   561             if (reportError)
   562                 log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType);
   563             return null;
   564         }
   566         return filterSame(extractContainingType(ca, pos, origAnnoDecl),
   567                           origAnnoType);
   568     }
   570     // returns null if t is same as 's', returns 't' otherwise
   571     private Type filterSame(Type t, Type s) {
   572         if (t == null || s == null) {
   573             return t;
   574         }
   576         return types.isSameType(t, s) ? null : t;
   577     }
   579     /** Extract the actual Type to be used for a containing annotation. */
   580     private Type extractContainingType(Attribute.Compound ca,
   581             DiagnosticPosition pos,
   582             TypeSymbol annoDecl)
   583     {
   584         // The next three checks check that the Repeatable annotation
   585         // on the declaration of the annotation type that is repeating is
   586         // valid.
   588         // Repeatable must have at least one element
   589         if (ca.values.isEmpty()) {
   590             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   591             return null;
   592         }
   593         Pair<MethodSymbol,Attribute> p = ca.values.head;
   594         Name name = p.fst.name;
   595         if (name != names.value) { // should contain only one element, named "value"
   596             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   597             return null;
   598         }
   599         if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
   600             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   601             return null;
   602         }
   604         return ((Attribute.Class)p.snd).getValue();
   605     }
   607     /* Validate that the suggested targetContainerType Type is a valid
   608      * container type for repeated instances of originalAnnoType
   609      * annotations. Return null and report errors if this is not the
   610      * case, return the MethodSymbol of the value element in
   611      * targetContainerType if it is suitable (this is needed to
   612      * synthesize the container). */
   613     private MethodSymbol validateContainer(Type targetContainerType,
   614                                            Type originalAnnoType,
   615                                            DiagnosticPosition pos) {
   616         MethodSymbol containerValueSymbol = null;
   617         boolean fatalError = false;
   619         // Validate that there is a (and only 1) value method
   620         Scope scope = targetContainerType.tsym.members();
   621         int nr_value_elems = 0;
   622         boolean error = false;
   623         for(Symbol elm : scope.getElementsByName(names.value)) {
   624             nr_value_elems++;
   626             if (nr_value_elems == 1 &&
   627                 elm.kind == Kinds.MTH) {
   628                 containerValueSymbol = (MethodSymbol)elm;
   629             } else {
   630                 error = true;
   631             }
   632         }
   633         if (error) {
   634             log.error(pos,
   635                       "invalid.repeatable.annotation.multiple.values",
   636                       targetContainerType,
   637                       nr_value_elems);
   638             return null;
   639         } else if (nr_value_elems == 0) {
   640             log.error(pos,
   641                       "invalid.repeatable.annotation.no.value",
   642                       targetContainerType);
   643             return null;
   644         }
   646         // validate that the 'value' element is a method
   647         // probably "impossible" to fail this
   648         if (containerValueSymbol.kind != Kinds.MTH) {
   649             log.error(pos,
   650                       "invalid.repeatable.annotation.invalid.value",
   651                       targetContainerType);
   652             fatalError = true;
   653         }
   655         // validate that the 'value' element has the correct return type
   656         // i.e. array of original anno
   657         Type valueRetType = containerValueSymbol.type.getReturnType();
   658         Type expectedType = types.makeArrayType(originalAnnoType);
   659         if (!(types.isArray(valueRetType) &&
   660               types.isSameType(expectedType, valueRetType))) {
   661             log.error(pos,
   662                       "invalid.repeatable.annotation.value.return",
   663                       targetContainerType,
   664                       valueRetType,
   665                       expectedType);
   666             fatalError = true;
   667         }
   668         if (error) {
   669             fatalError = true;
   670         }
   672         // The conditions for a valid containing annotation are made
   673         // in Check.validateRepeatedAnnotaton();
   675         return fatalError ? null : containerValueSymbol;
   676     }
   677 }

mercurial