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

Tue, 15 Oct 2013 15:57:13 -0700

author
jjg
date
Tue, 15 Oct 2013 15:57:13 -0700
changeset 2134
b0c086cd4520
parent 2133
19e8eebfbe52
child 2136
7f6481e5fe3a
permissions
-rw-r--r--

8026564: import changes from type-annotations forest
Reviewed-by: jjg
Contributed-by: wdietl@gmail.com, steve.sides@oracle.com

     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     public void flush() {
   133         if (enterCount != 0) return;
   134         enterCount++;
   135         try {
   136             while (q.nonEmpty()) {
   137                 q.next().run();
   138             }
   139             while (typesQ.nonEmpty()) {
   140                 typesQ.next().run();
   141             }
   142             while (repeatedQ.nonEmpty()) {
   143                 repeatedQ.next().run();
   144             }
   145             while (afterRepeatedQ.nonEmpty()) {
   146                 afterRepeatedQ.next().run();
   147             }
   148             while (validateQ.nonEmpty()) {
   149                 validateQ.next().run();
   150             }
   151         } finally {
   152             enterCount--;
   153         }
   154     }
   156     /** A client that needs to run during {@link #flush()} registers an worker
   157      *  into one of the queues defined in this class. The queues are: {@link #earlier(Worker)},
   158      *  {@link #normal(Worker)}, {@link #typeAnnotation(Worker)}, {@link #repeated(Worker)},
   159      *  {@link #afterRepeated(Worker)}, {@link #validate(Worker)}.
   160      *  The {@link Worker#run()} method will called inside the {@link #flush()}
   161      *  call. Queues are empties in the abovementioned order.
   162      */
   163     public interface Worker {
   164         void run();
   165         String toString();
   166     }
   168     /**
   169      * This context contains all the information needed to synthesize new
   170      * annotations trees by the completer for repeating annotations.
   171      */
   172     public class AnnotateRepeatedContext<T extends Attribute.Compound> {
   173         public final Env<AttrContext> env;
   174         public final Map<Symbol.TypeSymbol, ListBuffer<T>> annotated;
   175         public final Map<T, JCDiagnostic.DiagnosticPosition> pos;
   176         public final Log log;
   177         public final boolean isTypeCompound;
   179         public AnnotateRepeatedContext(Env<AttrContext> env,
   180                                        Map<Symbol.TypeSymbol, ListBuffer<T>> annotated,
   181                                        Map<T, JCDiagnostic.DiagnosticPosition> pos,
   182                                        Log log,
   183                                        boolean isTypeCompound) {
   184             Assert.checkNonNull(env);
   185             Assert.checkNonNull(annotated);
   186             Assert.checkNonNull(pos);
   187             Assert.checkNonNull(log);
   189             this.env = env;
   190             this.annotated = annotated;
   191             this.pos = pos;
   192             this.log = log;
   193             this.isTypeCompound = isTypeCompound;
   194         }
   196         /**
   197          * Process a list of repeating annotations returning a new
   198          * Attribute.Compound that is the attribute for the synthesized tree
   199          * for the container.
   200          *
   201          * @param repeatingAnnotations a List of repeating annotations
   202          * @return a new Attribute.Compound that is the container for the repeatingAnnotations
   203          */
   204         public T processRepeatedAnnotations(List<T> repeatingAnnotations, Symbol sym) {
   205             return Annotate.this.processRepeatedAnnotations(repeatingAnnotations, this, sym);
   206         }
   208         /**
   209          * Queue the Worker a on the repeating annotations queue of the
   210          * Annotate instance this context belongs to.
   211          *
   212          * @param a the Worker to enqueue for repeating annotation annotating
   213          */
   214         public void annotateRepeated(Worker a) {
   215             Annotate.this.repeated(a);
   216         }
   217     }
   219 /* ********************************************************************
   220  * Compute an attribute from its annotation.
   221  *********************************************************************/
   223     /** Process a single compound annotation, returning its
   224      *  Attribute. Used from MemberEnter for attaching the attributes
   225      *  to the annotated symbol.
   226      */
   227     Attribute.Compound enterAnnotation(JCAnnotation a,
   228                                        Type expected,
   229                                        Env<AttrContext> env) {
   230         return enterAnnotation(a, expected, env, false);
   231     }
   233     Attribute.TypeCompound enterTypeAnnotation(JCAnnotation a,
   234             Type expected,
   235             Env<AttrContext> env) {
   236         return (Attribute.TypeCompound) enterAnnotation(a, expected, env, true);
   237     }
   239     // boolean typeAnnotation determines whether the method returns
   240     // a Compound (false) or TypeCompound (true).
   241     Attribute.Compound enterAnnotation(JCAnnotation a,
   242             Type expected,
   243             Env<AttrContext> env,
   244             boolean typeAnnotation) {
   245         // The annotation might have had its type attributed (but not checked)
   246         // by attr.attribAnnotationTypes during MemberEnter, in which case we do not
   247         // need to do it again.
   248         Type at = (a.annotationType.type != null ? a.annotationType.type
   249                   : attr.attribType(a.annotationType, env));
   250         a.type = chk.checkType(a.annotationType.pos(), at, expected);
   251         if (a.type.isErroneous()) {
   252             if (typeAnnotation) {
   253                 return new Attribute.TypeCompound(a.type, List.<Pair<MethodSymbol,Attribute>>nil(),
   254                         new TypeAnnotationPosition());
   255             } else {
   256                 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
   257             }
   258         }
   259         if ((a.type.tsym.flags() & Flags.ANNOTATION) == 0) {
   260             log.error(a.annotationType.pos(),
   261                       "not.annotation.type", a.type.toString());
   262             if (typeAnnotation) {
   263                 return new Attribute.TypeCompound(a.type, List.<Pair<MethodSymbol,Attribute>>nil(), null);
   264             } else {
   265                 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
   266             }
   267         }
   268         List<JCExpression> args = a.args;
   269         if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
   270             // special case: elided "value=" assumed
   271             args.head = make.at(args.head.pos).
   272                 Assign(make.Ident(names.value), args.head);
   273         }
   274         ListBuffer<Pair<MethodSymbol,Attribute>> buf =
   275             new ListBuffer<Pair<MethodSymbol,Attribute>>();
   276         for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
   277             JCExpression t = tl.head;
   278             if (!t.hasTag(ASSIGN)) {
   279                 log.error(t.pos(), "annotation.value.must.be.name.value");
   280                 continue;
   281             }
   282             JCAssign assign = (JCAssign)t;
   283             if (!assign.lhs.hasTag(IDENT)) {
   284                 log.error(t.pos(), "annotation.value.must.be.name.value");
   285                 continue;
   286             }
   287             JCIdent left = (JCIdent)assign.lhs;
   288             Symbol method = rs.resolveQualifiedMethod(assign.rhs.pos(),
   289                                                           env,
   290                                                           a.type,
   291                                                           left.name,
   292                                                           List.<Type>nil(),
   293                                                           null);
   294             left.sym = method;
   295             left.type = method.type;
   296             if (method.owner != a.type.tsym)
   297                 log.error(left.pos(), "no.annotation.member", left.name, a.type);
   298             Type result = method.type.getReturnType();
   299             Attribute value = enterAttributeValue(result, assign.rhs, env);
   300             if (!method.type.isErroneous())
   301                 buf.append(new Pair<MethodSymbol,Attribute>
   302                            ((MethodSymbol)method, value));
   303             t.type = result;
   304         }
   305         if (typeAnnotation) {
   306             if (a.attribute == null || !(a.attribute instanceof Attribute.TypeCompound)) {
   307                 // Create a new TypeCompound
   308                 Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, buf.toList(), new TypeAnnotationPosition());
   309                 a.attribute = tc;
   310                 return tc;
   311             } else {
   312                 // Use an existing TypeCompound
   313                 return a.attribute;
   314             }
   315         } else {
   316             Attribute.Compound ac = new Attribute.Compound(a.type, buf.toList());
   317             a.attribute = ac;
   318             return ac;
   319         }
   320     }
   322     Attribute enterAttributeValue(Type expected,
   323                                   JCExpression tree,
   324                                   Env<AttrContext> env) {
   325         //first, try completing the attribution value sym - if a completion
   326         //error is thrown, we should recover gracefully, and display an
   327         //ordinary resolution diagnostic.
   328         try {
   329             expected.tsym.complete();
   330         } catch(CompletionFailure e) {
   331             log.error(tree.pos(), "cant.resolve", Kinds.kindName(e.sym), e.sym);
   332             expected = syms.errType;
   333         }
   334         if (expected.hasTag(ARRAY)) {
   335             if (!tree.hasTag(NEWARRAY)) {
   336                 tree = make.at(tree.pos).
   337                     NewArray(null, List.<JCExpression>nil(), List.of(tree));
   338             }
   339             JCNewArray na = (JCNewArray)tree;
   340             if (na.elemtype != null) {
   341                 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
   342             }
   343             ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
   344             for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
   345                 buf.append(enterAttributeValue(types.elemtype(expected),
   346                                                l.head,
   347                                                env));
   348             }
   349             na.type = expected;
   350             return new Attribute.
   351                 Array(expected, buf.toArray(new Attribute[buf.length()]));
   352         }
   353         if (tree.hasTag(NEWARRAY)) { //error recovery
   354             if (!expected.isErroneous())
   355                 log.error(tree.pos(), "annotation.value.not.allowable.type");
   356             JCNewArray na = (JCNewArray)tree;
   357             if (na.elemtype != null) {
   358                 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
   359             }
   360             for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
   361                 enterAttributeValue(syms.errType,
   362                                     l.head,
   363                                     env);
   364             }
   365             return new Attribute.Error(syms.errType);
   366         }
   367         if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
   368             if (tree.hasTag(ANNOTATION)) {
   369                 return enterAnnotation((JCAnnotation)tree, expected, env);
   370             } else {
   371                 log.error(tree.pos(), "annotation.value.must.be.annotation");
   372                 expected = syms.errType;
   373             }
   374         }
   375         if (tree.hasTag(ANNOTATION)) { //error recovery
   376             if (!expected.isErroneous())
   377                 log.error(tree.pos(), "annotation.not.valid.for.type", expected);
   378             enterAnnotation((JCAnnotation)tree, syms.errType, env);
   379             return new Attribute.Error(((JCAnnotation)tree).annotationType.type);
   380         }
   381         if (expected.isPrimitive() || types.isSameType(expected, syms.stringType)) {
   382             Type result = attr.attribExpr(tree, env, expected);
   383             if (result.isErroneous())
   384                 return new Attribute.Error(result.getOriginalType());
   385             if (result.constValue() == null) {
   386                 log.error(tree.pos(), "attribute.value.must.be.constant");
   387                 return new Attribute.Error(expected);
   388             }
   389             result = cfolder.coerce(result, expected);
   390             return new Attribute.Constant(expected, result.constValue());
   391         }
   392         if (expected.tsym == syms.classType.tsym) {
   393             Type result = attr.attribExpr(tree, env, expected);
   394             if (result.isErroneous()) {
   395                 // Does it look like an unresolved class literal?
   396                 if (TreeInfo.name(tree) == names._class &&
   397                     ((JCFieldAccess) tree).selected.type.isErroneous()) {
   398                     Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName();
   399                     return new Attribute.UnresolvedClass(expected,
   400                             types.createErrorType(n,
   401                                     syms.unknownSymbol, syms.classType));
   402                 } else {
   403                     return new Attribute.Error(result.getOriginalType());
   404                 }
   405             }
   407             // Class literals look like field accesses of a field named class
   408             // at the tree level
   409             if (TreeInfo.name(tree) != names._class) {
   410                 log.error(tree.pos(), "annotation.value.must.be.class.literal");
   411                 return new Attribute.Error(syms.errType);
   412             }
   413             return new Attribute.Class(types,
   414                                        (((JCFieldAccess) tree).selected).type);
   415         }
   416         if (expected.hasTag(CLASS) &&
   417             (expected.tsym.flags() & Flags.ENUM) != 0) {
   418             Type result = attr.attribExpr(tree, env, expected);
   419             Symbol sym = TreeInfo.symbol(tree);
   420             if (sym == null ||
   421                 TreeInfo.nonstaticSelect(tree) ||
   422                 sym.kind != Kinds.VAR ||
   423                 (sym.flags() & Flags.ENUM) == 0) {
   424                 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
   425                 return new Attribute.Error(result.getOriginalType());
   426             }
   427             VarSymbol enumerator = (VarSymbol) sym;
   428             return new Attribute.Enum(expected, enumerator);
   429         }
   430         //error recovery:
   431         if (!expected.isErroneous())
   432             log.error(tree.pos(), "annotation.value.not.allowable.type");
   433         return new Attribute.Error(attr.attribExpr(tree, env, expected));
   434     }
   436     /* *********************************
   437      * Support for repeating annotations
   438      ***********************************/
   440     /* Process repeated annotations. This method returns the
   441      * synthesized container annotation or null IFF all repeating
   442      * annotation are invalid.  This method reports errors/warnings.
   443      */
   444     private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
   445             AnnotateRepeatedContext<T> ctx,
   446             Symbol on) {
   447         T firstOccurrence = annotations.head;
   448         List<Attribute> repeated = List.nil();
   449         Type origAnnoType = null;
   450         Type arrayOfOrigAnnoType = null;
   451         Type targetContainerType = null;
   452         MethodSymbol containerValueSymbol = null;
   454         Assert.check(!annotations.isEmpty() &&
   455                      !annotations.tail.isEmpty()); // i.e. size() > 1
   457         int count = 0;
   458         for (List<T> al = annotations;
   459              !al.isEmpty();
   460              al = al.tail)
   461         {
   462             count++;
   464             // There must be more than a single anno in the annotation list
   465             Assert.check(count > 1 || !al.tail.isEmpty());
   467             T currentAnno = al.head;
   469             origAnnoType = currentAnno.type;
   470             if (arrayOfOrigAnnoType == null) {
   471                 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
   472             }
   474             // Only report errors if this isn't the first occurrence I.E. count > 1
   475             boolean reportError = count > 1;
   476             Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError);
   477             if (currentContainerType == null) {
   478                 continue;
   479             }
   480             // Assert that the target Container is == for all repeated
   481             // annos of the same annotation type, the types should
   482             // come from the same Symbol, i.e. be '=='
   483             Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
   484             targetContainerType = currentContainerType;
   486             containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
   488             if (containerValueSymbol == null) { // Check of CA type failed
   489                 // errors are already reported
   490                 continue;
   491             }
   493             repeated = repeated.prepend(currentAnno);
   494         }
   496         if (!repeated.isEmpty()) {
   497             repeated = repeated.reverse();
   498             TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
   499             Pair<MethodSymbol, Attribute> p =
   500                     new Pair<MethodSymbol, Attribute>(containerValueSymbol,
   501                                                       new Attribute.Array(arrayOfOrigAnnoType, repeated));
   502             if (ctx.isTypeCompound) {
   503                 /* TODO: the following code would be cleaner:
   504                 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
   505                         ((Attribute.TypeCompound)annotations.head).position);
   506                 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
   507                 at = enterTypeAnnotation(annoTree, targetContainerType, ctx.env);
   508                 */
   509                 // However, we directly construct the TypeCompound to keep the
   510                 // direct relation to the contained TypeCompounds.
   511                 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
   512                         ((Attribute.TypeCompound)annotations.head).position);
   514                 // TODO: annotation applicability checks from below?
   516                 at.setSynthesized(true);
   518                 @SuppressWarnings("unchecked")
   519                 T x = (T) at;
   520                 return x;
   521             } else {
   522                 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
   523                 JCAnnotation annoTree = m.Annotation(c);
   525                 if (!chk.annotationApplicable(annoTree, on))
   526                     log.error(annoTree.pos(), "invalid.repeatable.annotation.incompatible.target", targetContainerType, origAnnoType);
   528                 if (!chk.validateAnnotationDeferErrors(annoTree))
   529                     log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
   531                 c = enterAnnotation(annoTree, targetContainerType, ctx.env);
   532                 c.setSynthesized(true);
   534                 @SuppressWarnings("unchecked")
   535                 T x = (T) c;
   536                 return x;
   537             }
   538         } else {
   539             return null; // errors should have been reported elsewhere
   540         }
   541     }
   543     /** Fetches the actual Type that should be the containing annotation. */
   544     private Type getContainingType(Attribute.Compound currentAnno,
   545             DiagnosticPosition pos,
   546             boolean reportError)
   547     {
   548         Type origAnnoType = currentAnno.type;
   549         TypeSymbol origAnnoDecl = origAnnoType.tsym;
   551         // Fetch the Repeatable annotation from the current
   552         // annotation's declaration, or null if it has none
   553         Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym);
   554         if (ca == null) { // has no Repeatable annotation
   555             if (reportError)
   556                 log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType);
   557             return null;
   558         }
   560         return filterSame(extractContainingType(ca, pos, origAnnoDecl),
   561                           origAnnoType);
   562     }
   564     // returns null if t is same as 's', returns 't' otherwise
   565     private Type filterSame(Type t, Type s) {
   566         if (t == null || s == null) {
   567             return t;
   568         }
   570         return types.isSameType(t, s) ? null : t;
   571     }
   573     /** Extract the actual Type to be used for a containing annotation. */
   574     private Type extractContainingType(Attribute.Compound ca,
   575             DiagnosticPosition pos,
   576             TypeSymbol annoDecl)
   577     {
   578         // The next three checks check that the Repeatable annotation
   579         // on the declaration of the annotation type that is repeating is
   580         // valid.
   582         // Repeatable must have at least one element
   583         if (ca.values.isEmpty()) {
   584             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   585             return null;
   586         }
   587         Pair<MethodSymbol,Attribute> p = ca.values.head;
   588         Name name = p.fst.name;
   589         if (name != names.value) { // should contain only one element, named "value"
   590             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   591             return null;
   592         }
   593         if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
   594             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   595             return null;
   596         }
   598         return ((Attribute.Class)p.snd).getValue();
   599     }
   601     /* Validate that the suggested targetContainerType Type is a valid
   602      * container type for repeated instances of originalAnnoType
   603      * annotations. Return null and report errors if this is not the
   604      * case, return the MethodSymbol of the value element in
   605      * targetContainerType if it is suitable (this is needed to
   606      * synthesize the container). */
   607     private MethodSymbol validateContainer(Type targetContainerType,
   608                                            Type originalAnnoType,
   609                                            DiagnosticPosition pos) {
   610         MethodSymbol containerValueSymbol = null;
   611         boolean fatalError = false;
   613         // Validate that there is a (and only 1) value method
   614         Scope scope = targetContainerType.tsym.members();
   615         int nr_value_elems = 0;
   616         boolean error = false;
   617         for(Symbol elm : scope.getElementsByName(names.value)) {
   618             nr_value_elems++;
   620             if (nr_value_elems == 1 &&
   621                 elm.kind == Kinds.MTH) {
   622                 containerValueSymbol = (MethodSymbol)elm;
   623             } else {
   624                 error = true;
   625             }
   626         }
   627         if (error) {
   628             log.error(pos,
   629                       "invalid.repeatable.annotation.multiple.values",
   630                       targetContainerType,
   631                       nr_value_elems);
   632             return null;
   633         } else if (nr_value_elems == 0) {
   634             log.error(pos,
   635                       "invalid.repeatable.annotation.no.value",
   636                       targetContainerType);
   637             return null;
   638         }
   640         // validate that the 'value' element is a method
   641         // probably "impossible" to fail this
   642         if (containerValueSymbol.kind != Kinds.MTH) {
   643             log.error(pos,
   644                       "invalid.repeatable.annotation.invalid.value",
   645                       targetContainerType);
   646             fatalError = true;
   647         }
   649         // validate that the 'value' element has the correct return type
   650         // i.e. array of original anno
   651         Type valueRetType = containerValueSymbol.type.getReturnType();
   652         Type expectedType = types.makeArrayType(originalAnnoType);
   653         if (!(types.isArray(valueRetType) &&
   654               types.isSameType(expectedType, valueRetType))) {
   655             log.error(pos,
   656                       "invalid.repeatable.annotation.value.return",
   657                       targetContainerType,
   658                       valueRetType,
   659                       expectedType);
   660             fatalError = true;
   661         }
   662         if (error) {
   663             fatalError = true;
   664         }
   666         // The conditions for a valid containing annotation are made
   667         // in Check.validateRepeatedAnnotaton();
   669         return fatalError ? null : containerValueSymbol;
   670     }
   671 }

mercurial