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

Tue, 12 Mar 2013 17:39:34 +0100

author
jfranck
date
Tue, 12 Mar 2013 17:39:34 +0100
changeset 1629
f427043f8c65
parent 1521
71f35e4b93a5
child 1755
ddb4a2bfcd82
permissions
-rw-r--r--

7196531: Duplicate error messages on repeating annotations
Reviewed-by: jjg

     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.*;
    41 /** Enter annotations on symbols.  Annotations accumulate in a queue,
    42  *  which is processed at the top level of any set of recursive calls
    43  *  requesting it be processed.
    44  *
    45  *  <p><b>This is NOT part of any supported API.
    46  *  If you write code that depends on this, you do so at your own risk.
    47  *  This code and its internal interfaces are subject to change or
    48  *  deletion without notice.</b>
    49  */
    50 public class Annotate {
    51     protected static final Context.Key<Annotate> annotateKey =
    52         new Context.Key<Annotate>();
    54     public static Annotate instance(Context context) {
    55         Annotate instance = context.get(annotateKey);
    56         if (instance == null)
    57             instance = new Annotate(context);
    58         return instance;
    59     }
    61     final Attr attr;
    62     final TreeMaker make;
    63     final Log log;
    64     final Symtab syms;
    65     final Names names;
    66     final Resolve rs;
    67     final Types types;
    68     final ConstFold cfolder;
    69     final Check chk;
    71     protected Annotate(Context context) {
    72         context.put(annotateKey, this);
    73         attr = Attr.instance(context);
    74         make = TreeMaker.instance(context);
    75         log = Log.instance(context);
    76         syms = Symtab.instance(context);
    77         names = Names.instance(context);
    78         rs = Resolve.instance(context);
    79         types = Types.instance(context);
    80         cfolder = ConstFold.instance(context);
    81         chk = Check.instance(context);
    82     }
    84 /* ********************************************************************
    85  * Queue maintenance
    86  *********************************************************************/
    88     private int enterCount = 0;
    90     ListBuffer<Annotator> q = new ListBuffer<Annotator>();
    91     ListBuffer<Annotator> typesQ = new ListBuffer<Annotator>();
    92     ListBuffer<Annotator> repeatedQ = new ListBuffer<Annotator>();
    93     ListBuffer<Annotator> afterRepeatedQ = new ListBuffer<Annotator>();
    95     public void earlier(Annotator a) {
    96         q.prepend(a);
    97     }
    99     public void normal(Annotator a) {
   100         q.append(a);
   101     }
   103     public void typeAnnotation(Annotator a) {
   104         typesQ.append(a);
   105     }
   107     public void repeated(Annotator a) {
   108         repeatedQ.append(a);
   109     }
   111     public void afterRepeated(Annotator a) {
   112         afterRepeatedQ.append(a);
   113     }
   115     /** Called when the Enter phase starts. */
   116     public void enterStart() {
   117         enterCount++;
   118     }
   120     /** Called after the Enter phase completes. */
   121     public void enterDone() {
   122         enterCount--;
   123         flush();
   124     }
   126     public void flush() {
   127         if (enterCount != 0) return;
   128         enterCount++;
   129         try {
   130             while (q.nonEmpty()) {
   131                 q.next().enterAnnotation();
   132             }
   133             while (typesQ.nonEmpty()) {
   134                 typesQ.next().enterAnnotation();
   135             }
   136             while (repeatedQ.nonEmpty()) {
   137                 repeatedQ.next().enterAnnotation();
   138             }
   139             while (afterRepeatedQ.nonEmpty()) {
   140                 afterRepeatedQ.next().enterAnnotation();
   141             }
   142         } finally {
   143             enterCount--;
   144         }
   145     }
   147     /** A client that has annotations to add registers an annotator,
   148      *  the method it will use to add the annotation.  There are no
   149      *  parameters; any needed data should be captured by the
   150      *  Annotator.
   151      */
   152     public interface Annotator {
   153         void enterAnnotation();
   154         String toString();
   155     }
   157     /**
   158      * This context contains all the information needed to synthesize new
   159      * annotations trees by the completer for repeating annotations.
   160      */
   161     public class AnnotateRepeatedContext<T extends Attribute.Compound> {
   162         public final Env<AttrContext> env;
   163         public final Map<Symbol.TypeSymbol, ListBuffer<T>> annotated;
   164         public final Map<T, JCDiagnostic.DiagnosticPosition> pos;
   165         public final Log log;
   166         public final boolean isTypeCompound;
   168         public AnnotateRepeatedContext(Env<AttrContext> env,
   169                                        Map<Symbol.TypeSymbol, ListBuffer<T>> annotated,
   170                                        Map<T, JCDiagnostic.DiagnosticPosition> pos,
   171                                        Log log,
   172                                        boolean isTypeCompound) {
   173             Assert.checkNonNull(env);
   174             Assert.checkNonNull(annotated);
   175             Assert.checkNonNull(pos);
   176             Assert.checkNonNull(log);
   178             this.env = env;
   179             this.annotated = annotated;
   180             this.pos = pos;
   181             this.log = log;
   182             this.isTypeCompound = isTypeCompound;
   183         }
   185         /**
   186          * Process a list of repeating annotations returning a new
   187          * Attribute.Compound that is the attribute for the synthesized tree
   188          * for the container.
   189          *
   190          * @param repeatingAnnotations a List of repeating annotations
   191          * @return a new Attribute.Compound that is the container for the repeatingAnnotations
   192          */
   193         public T processRepeatedAnnotations(List<T> repeatingAnnotations, Symbol sym) {
   194             return Annotate.this.processRepeatedAnnotations(repeatingAnnotations, this, sym);
   195         }
   197         /**
   198          * Queue the Annotator a on the repeating annotations queue of the
   199          * Annotate instance this context belongs to.
   200          *
   201          * @param a the Annotator to enqueue for repeating annotation annotating
   202          */
   203         public void annotateRepeated(Annotator a) {
   204             Annotate.this.repeated(a);
   205         }
   206     }
   208 /* ********************************************************************
   209  * Compute an attribute from its annotation.
   210  *********************************************************************/
   212     /** Process a single compound annotation, returning its
   213      *  Attribute. Used from MemberEnter for attaching the attributes
   214      *  to the annotated symbol.
   215      */
   216     Attribute.Compound enterAnnotation(JCAnnotation a,
   217                                        Type expected,
   218                                        Env<AttrContext> env) {
   219         // The annotation might have had its type attributed (but not checked)
   220         // by attr.attribAnnotationTypes during MemberEnter, in which case we do not
   221         // need to do it again.
   222         Type at = (a.annotationType.type != null ? a.annotationType.type
   223                   : attr.attribType(a.annotationType, env));
   224         a.type = chk.checkType(a.annotationType.pos(), at, expected);
   225         if (a.type.isErroneous())
   226             return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
   227         if ((a.type.tsym.flags() & Flags.ANNOTATION) == 0) {
   228             log.error(a.annotationType.pos(),
   229                       "not.annotation.type", a.type.toString());
   230             return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
   231         }
   232         List<JCExpression> args = a.args;
   233         if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
   234             // special case: elided "value=" assumed
   235             args.head = make.at(args.head.pos).
   236                 Assign(make.Ident(names.value), args.head);
   237         }
   238         ListBuffer<Pair<MethodSymbol,Attribute>> buf =
   239             new ListBuffer<Pair<MethodSymbol,Attribute>>();
   240         for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
   241             JCExpression t = tl.head;
   242             if (!t.hasTag(ASSIGN)) {
   243                 log.error(t.pos(), "annotation.value.must.be.name.value");
   244                 continue;
   245             }
   246             JCAssign assign = (JCAssign)t;
   247             if (!assign.lhs.hasTag(IDENT)) {
   248                 log.error(t.pos(), "annotation.value.must.be.name.value");
   249                 continue;
   250             }
   251             JCIdent left = (JCIdent)assign.lhs;
   252             Symbol method = rs.resolveQualifiedMethod(left.pos(),
   253                                                           env,
   254                                                           a.type,
   255                                                           left.name,
   256                                                           List.<Type>nil(),
   257                                                           null);
   258             left.sym = method;
   259             left.type = method.type;
   260             if (method.owner != a.type.tsym)
   261                 log.error(left.pos(), "no.annotation.member", left.name, a.type);
   262             Type result = method.type.getReturnType();
   263             Attribute value = enterAttributeValue(result, assign.rhs, env);
   264             if (!method.type.isErroneous())
   265                 buf.append(new Pair<MethodSymbol,Attribute>
   266                            ((MethodSymbol)method, value));
   267             t.type = result;
   268         }
   269         // TODO: this should be a TypeCompound if "a" is a JCTypeAnnotation.
   270         // However, how do we find the correct position?
   271         Attribute.Compound ac = new Attribute.Compound(a.type, buf.toList());
   272         // TODO: is this something we want? Who would use it?
   273         // a.attribute = ac;
   274         return ac;
   275     }
   277     Attribute enterAttributeValue(Type expected,
   278                                   JCExpression tree,
   279                                   Env<AttrContext> env) {
   280         //first, try completing the attribution value sym - if a completion
   281         //error is thrown, we should recover gracefully, and display an
   282         //ordinary resolution diagnostic.
   283         try {
   284             expected.tsym.complete();
   285         } catch(CompletionFailure e) {
   286             log.error(tree.pos(), "cant.resolve", Kinds.kindName(e.sym), e.sym);
   287             return new Attribute.Error(expected);
   288         }
   289         if (expected.isPrimitive() || types.isSameType(expected, syms.stringType)) {
   290             Type result = attr.attribExpr(tree, env, expected);
   291             if (result.isErroneous())
   292                 return new Attribute.Error(expected);
   293             if (result.constValue() == null) {
   294                 log.error(tree.pos(), "attribute.value.must.be.constant");
   295                 return new Attribute.Error(expected);
   296             }
   297             result = cfolder.coerce(result, expected);
   298             return new Attribute.Constant(expected, result.constValue());
   299         }
   300         if (expected.tsym == syms.classType.tsym) {
   301             Type result = attr.attribExpr(tree, env, expected);
   302             if (result.isErroneous())
   303                 return new Attribute.Error(expected);
   304             if (TreeInfo.name(tree) != names._class) {
   305                 log.error(tree.pos(), "annotation.value.must.be.class.literal");
   306                 return new Attribute.Error(expected);
   307             }
   308             return new Attribute.Class(types,
   309                                        (((JCFieldAccess) tree).selected).type);
   310         }
   311         if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
   312             if (!tree.hasTag(ANNOTATION)) {
   313                 log.error(tree.pos(), "annotation.value.must.be.annotation");
   314                 expected = syms.errorType;
   315             }
   316             return enterAnnotation((JCAnnotation)tree, expected, env);
   317         }
   318         if (expected.hasTag(ARRAY)) { // should really be isArray()
   319             if (!tree.hasTag(NEWARRAY)) {
   320                 tree = make.at(tree.pos).
   321                     NewArray(null, List.<JCExpression>nil(), List.of(tree));
   322             }
   323             JCNewArray na = (JCNewArray)tree;
   324             if (na.elemtype != null) {
   325                 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
   326                 return new Attribute.Error(expected);
   327             }
   328             ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
   329             for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
   330                 buf.append(enterAttributeValue(types.elemtype(expected),
   331                                                l.head,
   332                                                env));
   333             }
   334             na.type = expected;
   335             return new Attribute.
   336                 Array(expected, buf.toArray(new Attribute[buf.length()]));
   337         }
   338         if (expected.hasTag(CLASS) &&
   339             (expected.tsym.flags() & Flags.ENUM) != 0) {
   340             attr.attribExpr(tree, env, expected);
   341             Symbol sym = TreeInfo.symbol(tree);
   342             if (sym == null ||
   343                 TreeInfo.nonstaticSelect(tree) ||
   344                 sym.kind != Kinds.VAR ||
   345                 (sym.flags() & Flags.ENUM) == 0) {
   346                 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
   347                 return new Attribute.Error(expected);
   348             }
   349             VarSymbol enumerator = (VarSymbol) sym;
   350             return new Attribute.Enum(expected, enumerator);
   351         }
   352         if (!expected.isErroneous())
   353             log.error(tree.pos(), "annotation.value.not.allowable.type");
   354         return new Attribute.Error(attr.attribExpr(tree, env, expected));
   355     }
   357     Attribute.TypeCompound enterTypeAnnotation(JCAnnotation a,
   358             Type expected,
   359             Env<AttrContext> env) {
   360         Attribute.Compound c = enterAnnotation(a, expected, env);
   361         Attribute.TypeCompound tc = new Attribute.TypeCompound(c.type, c.values, new TypeAnnotationPosition());
   362         a.attribute = tc;
   363         return tc;
   364     }
   366     /* *********************************
   367      * Support for repeating annotations
   368      ***********************************/
   370     /* Process repeated annotations. This method returns the
   371      * synthesized container annotation or null IFF all repeating
   372      * annotation are invalid.  This method reports errors/warnings.
   373      */
   374     private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
   375             AnnotateRepeatedContext<T> ctx,
   376             Symbol on) {
   377         T firstOccurrence = annotations.head;
   378         List<Attribute> repeated = List.nil();
   379         Type origAnnoType = null;
   380         Type arrayOfOrigAnnoType = null;
   381         Type targetContainerType = null;
   382         MethodSymbol containerValueSymbol = null;
   384         Assert.check(!annotations.isEmpty() &&
   385                      !annotations.tail.isEmpty()); // i.e. size() > 1
   387         int count = 0;
   388         for (List<T> al = annotations;
   389              !al.isEmpty();
   390              al = al.tail)
   391         {
   392             count++;
   394             // There must be more than a single anno in the annotation list
   395             Assert.check(count > 1 || !al.tail.isEmpty());
   397             T currentAnno = al.head;
   399             origAnnoType = currentAnno.type;
   400             if (arrayOfOrigAnnoType == null) {
   401                 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
   402             }
   404             // Only report errors if this isn't the first occurrence I.E. count > 1
   405             boolean reportError = count > 1;
   406             Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError);
   407             if (currentContainerType == null) {
   408                 continue;
   409             }
   410             // Assert that the target Container is == for all repeated
   411             // annos of the same annotation type, the types should
   412             // come from the same Symbol, i.e. be '=='
   413             Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
   414             targetContainerType = currentContainerType;
   416             containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
   418             if (containerValueSymbol == null) { // Check of CA type failed
   419                 // errors are already reported
   420                 continue;
   421             }
   423             repeated = repeated.prepend(currentAnno);
   424         }
   426         if (!repeated.isEmpty()) {
   427             repeated = repeated.reverse();
   428             TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
   429             Pair<MethodSymbol, Attribute> p =
   430                     new Pair<MethodSymbol, Attribute>(containerValueSymbol,
   431                                                       new Attribute.Array(arrayOfOrigAnnoType, repeated));
   432             if (ctx.isTypeCompound) {
   433                 /* TODO: the following code would be cleaner:
   434                 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
   435                         ((Attribute.TypeCompound)annotations.head).position);
   436                 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
   437                 at = enterTypeAnnotation(annoTree, targetContainerType, ctx.env);
   438                 */
   439                 // However, we directly construct the TypeCompound to keep the
   440                 // direct relation to the contained TypeCompounds.
   441                 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
   442                         ((Attribute.TypeCompound)annotations.head).position);
   444                 // TODO: annotation applicability checks from below?
   446                 at.setSynthesized(true);
   448                 @SuppressWarnings("unchecked")
   449                 T x = (T) at;
   450                 return x;
   451             } else {
   452                 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
   453                 JCAnnotation annoTree = m.Annotation(c);
   455                 if (!chk.annotationApplicable(annoTree, on))
   456                     log.error(annoTree.pos(), "invalid.repeatable.annotation.incompatible.target", targetContainerType, origAnnoType);
   458                 if (!chk.validateAnnotationDeferErrors(annoTree))
   459                     log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
   461                 c = enterAnnotation(annoTree, targetContainerType, ctx.env);
   462                 c.setSynthesized(true);
   464                 @SuppressWarnings("unchecked")
   465                 T x = (T) c;
   466                 return x;
   467             }
   468         } else {
   469             return null; // errors should have been reported elsewhere
   470         }
   471     }
   473     /** Fetches the actual Type that should be the containing annotation. */
   474     private Type getContainingType(Attribute.Compound currentAnno,
   475             DiagnosticPosition pos,
   476             boolean reportError)
   477     {
   478         Type origAnnoType = currentAnno.type;
   479         TypeSymbol origAnnoDecl = origAnnoType.tsym;
   481         // Fetch the Repeatable annotation from the current
   482         // annotation's declaration, or null if it has none
   483         Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym);
   484         if (ca == null) { // has no Repeatable annotation
   485             if (reportError)
   486                 log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType);
   487             return null;
   488         }
   490         return filterSame(extractContainingType(ca, pos, origAnnoDecl),
   491                           origAnnoType);
   492     }
   494     // returns null if t is same as 's', returns 't' otherwise
   495     private Type filterSame(Type t, Type s) {
   496         if (t == null || s == null) {
   497             return t;
   498         }
   500         return types.isSameType(t, s) ? null : t;
   501     }
   503     /** Extract the actual Type to be used for a containing annotation. */
   504     private Type extractContainingType(Attribute.Compound ca,
   505             DiagnosticPosition pos,
   506             TypeSymbol annoDecl)
   507     {
   508         // The next three checks check that the Repeatable annotation
   509         // on the declaration of the annotation type that is repeating is
   510         // valid.
   512         // Repeatable must have at least one element
   513         if (ca.values.isEmpty()) {
   514             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   515             return null;
   516         }
   517         Pair<MethodSymbol,Attribute> p = ca.values.head;
   518         Name name = p.fst.name;
   519         if (name != names.value) { // should contain only one element, named "value"
   520             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   521             return null;
   522         }
   523         if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
   524             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   525             return null;
   526         }
   528         return ((Attribute.Class)p.snd).getValue();
   529     }
   531     /* Validate that the suggested targetContainerType Type is a valid
   532      * container type for repeated instances of originalAnnoType
   533      * annotations. Return null and report errors if this is not the
   534      * case, return the MethodSymbol of the value element in
   535      * targetContainerType if it is suitable (this is needed to
   536      * synthesize the container). */
   537     private MethodSymbol validateContainer(Type targetContainerType,
   538                                            Type originalAnnoType,
   539                                            DiagnosticPosition pos) {
   540         MethodSymbol containerValueSymbol = null;
   541         boolean fatalError = false;
   543         // Validate that there is a (and only 1) value method
   544         Scope scope = targetContainerType.tsym.members();
   545         int nr_value_elems = 0;
   546         boolean error = false;
   547         for(Symbol elm : scope.getElementsByName(names.value)) {
   548             nr_value_elems++;
   550             if (nr_value_elems == 1 &&
   551                 elm.kind == Kinds.MTH) {
   552                 containerValueSymbol = (MethodSymbol)elm;
   553             } else {
   554                 error = true;
   555             }
   556         }
   557         if (error) {
   558             log.error(pos,
   559                       "invalid.repeatable.annotation.multiple.values",
   560                       targetContainerType,
   561                       nr_value_elems);
   562             return null;
   563         } else if (nr_value_elems == 0) {
   564             log.error(pos,
   565                       "invalid.repeatable.annotation.no.value",
   566                       targetContainerType);
   567             return null;
   568         }
   570         // validate that the 'value' element is a method
   571         // probably "impossible" to fail this
   572         if (containerValueSymbol.kind != Kinds.MTH) {
   573             log.error(pos,
   574                       "invalid.repeatable.annotation.invalid.value",
   575                       targetContainerType);
   576             fatalError = true;
   577         }
   579         // validate that the 'value' element has the correct return type
   580         // i.e. array of original anno
   581         Type valueRetType = containerValueSymbol.type.getReturnType();
   582         Type expectedType = types.makeArrayType(originalAnnoType);
   583         if (!(types.isArray(valueRetType) &&
   584               types.isSameType(expectedType, valueRetType))) {
   585             log.error(pos,
   586                       "invalid.repeatable.annotation.value.return",
   587                       targetContainerType,
   588                       valueRetType,
   589                       expectedType);
   590             fatalError = true;
   591         }
   592         if (error) {
   593             fatalError = true;
   594         }
   596         // The conditions for a valid containing annotation are made
   597         // in Check.validateRepeatedAnnotaton();
   599         return fatalError ? null : containerValueSymbol;
   600     }
   601 }

mercurial