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

Mon, 14 Jan 2013 13:50:01 -0800

author
jjg
date
Mon, 14 Jan 2013 13:50:01 -0800
changeset 1492
df694c775e8a
parent 1464
f72c9c5aeaef
child 1521
71f35e4b93a5
permissions
-rw-r--r--

8006119: update javac to follow latest spec for repeatable annotations
Reviewed-by: darcy

     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;
    29 import com.sun.tools.javac.util.*;
    30 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    31 import com.sun.tools.javac.code.*;
    32 import com.sun.tools.javac.code.Symbol.*;
    33 import com.sun.tools.javac.tree.*;
    34 import com.sun.tools.javac.tree.JCTree.*;
    36 import static com.sun.tools.javac.code.TypeTag.ARRAY;
    37 import static com.sun.tools.javac.code.TypeTag.CLASS;
    38 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    40 /** Enter annotations on symbols.  Annotations accumulate in a queue,
    41  *  which is processed at the top level of any set of recursive calls
    42  *  requesting it be processed.
    43  *
    44  *  <p><b>This is NOT part of any supported API.
    45  *  If you write code that depends on this, you do so at your own risk.
    46  *  This code and its internal interfaces are subject to change or
    47  *  deletion without notice.</b>
    48  */
    49 public class Annotate {
    50     protected static final Context.Key<Annotate> annotateKey =
    51         new Context.Key<Annotate>();
    53     public static Annotate instance(Context context) {
    54         Annotate instance = context.get(annotateKey);
    55         if (instance == null)
    56             instance = new Annotate(context);
    57         return instance;
    58     }
    60     final Attr attr;
    61     final TreeMaker make;
    62     final Log log;
    63     final Symtab syms;
    64     final Names names;
    65     final Resolve rs;
    66     final Types types;
    67     final ConstFold cfolder;
    68     final Check chk;
    70     protected Annotate(Context context) {
    71         context.put(annotateKey, this);
    72         attr = Attr.instance(context);
    73         make = TreeMaker.instance(context);
    74         log = Log.instance(context);
    75         syms = Symtab.instance(context);
    76         names = Names.instance(context);
    77         rs = Resolve.instance(context);
    78         types = Types.instance(context);
    79         cfolder = ConstFold.instance(context);
    80         chk = Check.instance(context);
    81     }
    83 /* ********************************************************************
    84  * Queue maintenance
    85  *********************************************************************/
    87     private int enterCount = 0;
    89     ListBuffer<Annotator> q = new ListBuffer<Annotator>();
    90     ListBuffer<Annotator> repeatedQ = new ListBuffer<Annotator>();
    92     public void normal(Annotator a) {
    93         q.append(a);
    94     }
    96     public void earlier(Annotator a) {
    97         q.prepend(a);
    98     }
   100     public void repeated(Annotator a) {
   101         repeatedQ.append(a);
   102     }
   104     /** Called when the Enter phase starts. */
   105     public void enterStart() {
   106         enterCount++;
   107     }
   109     /** Called after the Enter phase completes. */
   110     public void enterDone() {
   111         enterCount--;
   112         flush();
   113     }
   115     public void flush() {
   116         if (enterCount != 0) return;
   117         enterCount++;
   118         try {
   119             while (q.nonEmpty())
   120                 q.next().enterAnnotation();
   122             while (repeatedQ.nonEmpty()) {
   123                 repeatedQ.next().enterAnnotation();
   124             }
   125         } finally {
   126             enterCount--;
   127         }
   128     }
   130     /** A client that has annotations to add registers an annotator,
   131      *  the method it will use to add the annotation.  There are no
   132      *  parameters; any needed data should be captured by the
   133      *  Annotator.
   134      */
   135     public interface Annotator {
   136         void enterAnnotation();
   137         String toString();
   138     }
   140     /**
   141      * This context contains all the information needed to synthesize new
   142      * annotations trees by the completer for repeating annotations.
   143      */
   144     public class AnnotateRepeatedContext {
   145         public final Env<AttrContext> env;
   146         public final Map<Symbol.TypeSymbol, ListBuffer<Attribute.Compound>> annotated;
   147         public final Map<Attribute.Compound, JCDiagnostic.DiagnosticPosition> pos;
   148         public final Log log;
   150         public AnnotateRepeatedContext(Env<AttrContext> env,
   151                                        Map<Symbol.TypeSymbol, ListBuffer<Attribute.Compound>> annotated,
   152                                        Map<Attribute.Compound, JCDiagnostic.DiagnosticPosition> pos,
   153                                        Log log) {
   154             Assert.checkNonNull(env);
   155             Assert.checkNonNull(annotated);
   156             Assert.checkNonNull(pos);
   157             Assert.checkNonNull(log);
   159             this.env = env;
   160             this.annotated = annotated;
   161             this.pos = pos;
   162             this.log = log;
   163         }
   165         /**
   166          * Process a list of repeating annotations returning a new
   167          * Attribute.Compound that is the attribute for the synthesized tree
   168          * for the container.
   169          *
   170          * @param repeatingAnnotations a List of repeating annotations
   171          * @return a new Attribute.Compound that is the container for the repeatingAnnotations
   172          */
   173         public Attribute.Compound processRepeatedAnnotations(List<Attribute.Compound> repeatingAnnotations, Symbol sym) {
   174             return Annotate.this.processRepeatedAnnotations(repeatingAnnotations, this, sym);
   175         }
   177         /**
   178          * Queue the Annotator a on the repeating annotations queue of the
   179          * Annotate instance this context belongs to.
   180          *
   181          * @param a the Annotator to enqueue for repeating annotation annotating
   182          */
   183         public void annotateRepeated(Annotator a) {
   184             Annotate.this.repeated(a);
   185         }
   186     }
   188 /* ********************************************************************
   189  * Compute an attribute from its annotation.
   190  *********************************************************************/
   192     /** Process a single compound annotation, returning its
   193      *  Attribute. Used from MemberEnter for attaching the attributes
   194      *  to the annotated symbol.
   195      */
   196     Attribute.Compound enterAnnotation(JCAnnotation a,
   197                                        Type expected,
   198                                        Env<AttrContext> env) {
   199         // The annotation might have had its type attributed (but not checked)
   200         // by attr.attribAnnotationTypes during MemberEnter, in which case we do not
   201         // need to do it again.
   202         Type at = (a.annotationType.type != null ? a.annotationType.type
   203                   : attr.attribType(a.annotationType, env));
   204         a.type = chk.checkType(a.annotationType.pos(), at, expected);
   205         if (a.type.isErroneous())
   206             return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
   207         if ((a.type.tsym.flags() & Flags.ANNOTATION) == 0) {
   208             log.error(a.annotationType.pos(),
   209                       "not.annotation.type", a.type.toString());
   210             return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
   211         }
   212         List<JCExpression> args = a.args;
   213         if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
   214             // special case: elided "value=" assumed
   215             args.head = make.at(args.head.pos).
   216                 Assign(make.Ident(names.value), args.head);
   217         }
   218         ListBuffer<Pair<MethodSymbol,Attribute>> buf =
   219             new ListBuffer<Pair<MethodSymbol,Attribute>>();
   220         for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
   221             JCExpression t = tl.head;
   222             if (!t.hasTag(ASSIGN)) {
   223                 log.error(t.pos(), "annotation.value.must.be.name.value");
   224                 continue;
   225             }
   226             JCAssign assign = (JCAssign)t;
   227             if (!assign.lhs.hasTag(IDENT)) {
   228                 log.error(t.pos(), "annotation.value.must.be.name.value");
   229                 continue;
   230             }
   231             JCIdent left = (JCIdent)assign.lhs;
   232             Symbol method = rs.resolveQualifiedMethod(left.pos(),
   233                                                           env,
   234                                                           a.type,
   235                                                           left.name,
   236                                                           List.<Type>nil(),
   237                                                           null);
   238             left.sym = method;
   239             left.type = method.type;
   240             if (method.owner != a.type.tsym)
   241                 log.error(left.pos(), "no.annotation.member", left.name, a.type);
   242             Type result = method.type.getReturnType();
   243             Attribute value = enterAttributeValue(result, assign.rhs, env);
   244             if (!method.type.isErroneous())
   245                 buf.append(new Pair<MethodSymbol,Attribute>
   246                            ((MethodSymbol)method, value));
   247             t.type = result;
   248         }
   249         return new Attribute.Compound(a.type, buf.toList());
   250     }
   252     Attribute enterAttributeValue(Type expected,
   253                                   JCExpression tree,
   254                                   Env<AttrContext> env) {
   255         //first, try completing the attribution value sym - if a completion
   256         //error is thrown, we should recover gracefully, and display an
   257         //ordinary resolution diagnostic.
   258         try {
   259             expected.tsym.complete();
   260         } catch(CompletionFailure e) {
   261             log.error(tree.pos(), "cant.resolve", Kinds.kindName(e.sym), e.sym);
   262             return new Attribute.Error(expected);
   263         }
   264         if (expected.isPrimitive() || types.isSameType(expected, syms.stringType)) {
   265             Type result = attr.attribExpr(tree, env, expected);
   266             if (result.isErroneous())
   267                 return new Attribute.Error(expected);
   268             if (result.constValue() == null) {
   269                 log.error(tree.pos(), "attribute.value.must.be.constant");
   270                 return new Attribute.Error(expected);
   271             }
   272             result = cfolder.coerce(result, expected);
   273             return new Attribute.Constant(expected, result.constValue());
   274         }
   275         if (expected.tsym == syms.classType.tsym) {
   276             Type result = attr.attribExpr(tree, env, expected);
   277             if (result.isErroneous())
   278                 return new Attribute.Error(expected);
   279             if (TreeInfo.name(tree) != names._class) {
   280                 log.error(tree.pos(), "annotation.value.must.be.class.literal");
   281                 return new Attribute.Error(expected);
   282             }
   283             return new Attribute.Class(types,
   284                                        (((JCFieldAccess) tree).selected).type);
   285         }
   286         if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
   287             if (!tree.hasTag(ANNOTATION)) {
   288                 log.error(tree.pos(), "annotation.value.must.be.annotation");
   289                 expected = syms.errorType;
   290             }
   291             return enterAnnotation((JCAnnotation)tree, expected, env);
   292         }
   293         if (expected.hasTag(ARRAY)) { // should really be isArray()
   294             if (!tree.hasTag(NEWARRAY)) {
   295                 tree = make.at(tree.pos).
   296                     NewArray(null, List.<JCExpression>nil(), List.of(tree));
   297             }
   298             JCNewArray na = (JCNewArray)tree;
   299             if (na.elemtype != null) {
   300                 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
   301                 return new Attribute.Error(expected);
   302             }
   303             ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
   304             for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
   305                 buf.append(enterAttributeValue(types.elemtype(expected),
   306                                                l.head,
   307                                                env));
   308             }
   309             na.type = expected;
   310             return new Attribute.
   311                 Array(expected, buf.toArray(new Attribute[buf.length()]));
   312         }
   313         if (expected.hasTag(CLASS) &&
   314             (expected.tsym.flags() & Flags.ENUM) != 0) {
   315             attr.attribExpr(tree, env, expected);
   316             Symbol sym = TreeInfo.symbol(tree);
   317             if (sym == null ||
   318                 TreeInfo.nonstaticSelect(tree) ||
   319                 sym.kind != Kinds.VAR ||
   320                 (sym.flags() & Flags.ENUM) == 0) {
   321                 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
   322                 return new Attribute.Error(expected);
   323             }
   324             VarSymbol enumerator = (VarSymbol) sym;
   325             return new Attribute.Enum(expected, enumerator);
   326         }
   327         if (!expected.isErroneous())
   328             log.error(tree.pos(), "annotation.value.not.allowable.type");
   329         return new Attribute.Error(attr.attribExpr(tree, env, expected));
   330     }
   332     /* *********************************
   333      * Support for repeating annotations
   334      ***********************************/
   336     /* Process repeated annotations. This method returns the
   337      * synthesized container annotation or null IFF all repeating
   338      * annotation are invalid.  This method reports errors/warnings.
   339      */
   340     private Attribute.Compound processRepeatedAnnotations(List<Attribute.Compound> annotations,
   341                                                           AnnotateRepeatedContext ctx,
   342                                                           Symbol on) {
   343         Attribute.Compound firstOccurrence = annotations.head;
   344         List<Attribute> repeated = List.nil();
   345         Type origAnnoType = null;
   346         Type arrayOfOrigAnnoType = null;
   347         Type targetContainerType = null;
   348         MethodSymbol containerValueSymbol = null;
   350         Assert.check(!annotations.isEmpty() &&
   351                      !annotations.tail.isEmpty()); // i.e. size() > 1
   353         for (List<Attribute.Compound> al = annotations;
   354              !al.isEmpty();
   355              al = al.tail)
   356         {
   357             Attribute.Compound currentAnno = al.head;
   359             origAnnoType = currentAnno.type;
   360             if (arrayOfOrigAnnoType == null) {
   361                 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
   362 }
   364             Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno));
   365             if (currentContainerType == null) {
   366                 continue;
   367             }
   368             // Assert that the target Container is == for all repeated
   369             // annos of the same annotation type, the types should
   370             // come from the same Symbol, i.e. be '=='
   371             Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
   372             targetContainerType = currentContainerType;
   374             containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
   376             if (containerValueSymbol == null) { // Check of CA type failed
   377                 // errors are already reported
   378                 continue;
   379             }
   381             repeated = repeated.prepend(currentAnno);
   382         }
   384         if (!repeated.isEmpty()) {
   385             repeated = repeated.reverse();
   386             JCAnnotation annoTree;
   387             TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
   388             Pair<MethodSymbol, Attribute> p =
   389                     new Pair<MethodSymbol, Attribute>(containerValueSymbol,
   390                                                       new Attribute.Array(arrayOfOrigAnnoType, repeated));
   391             annoTree = m.Annotation(new Attribute.Compound(targetContainerType,
   392                     List.of(p)));
   394             if (!chk.annotationApplicable(annoTree, on))
   395                 log.error(annoTree.pos(), "invalid.repeatable.annotation.incompatible.target", targetContainerType, origAnnoType);
   397             if (!chk.validateAnnotationDeferErrors(annoTree))
   398                 log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
   400             Attribute.Compound c = enterAnnotation(annoTree,
   401                                                    targetContainerType,
   402                                                    ctx.env);
   403             c.setSynthesized(true);
   404             return c;
   405         } else {
   406             return null; // errors should have been reported elsewhere
   407         }
   408     }
   410     /** Fetches the actual Type that should be the containing annotation. */
   411     private Type getContainingType(Attribute.Compound currentAnno,
   412             DiagnosticPosition pos)
   413     {
   414         Type origAnnoType = currentAnno.type;
   415         TypeSymbol origAnnoDecl = origAnnoType.tsym;
   417         // Fetch the Repeatable annotation from the current
   418         // annotation's declaration, or null if it has none
   419         Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym);
   420         if (ca == null) { // has no Repeatable annotation
   421             log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType);
   422             return null;
   423         }
   425         return filterSame(extractContainingType(ca, pos, origAnnoDecl),
   426                           origAnnoType);
   427     }
   429     // returns null if t is same as 's', returns 't' otherwise
   430     private Type filterSame(Type t, Type s) {
   431         if (t == null || s == null) {
   432             return t;
   433         }
   435         return types.isSameType(t, s) ? null : t;
   436     }
   438     /** Extract the actual Type to be used for a containing annotation. */
   439     private Type extractContainingType(Attribute.Compound ca,
   440             DiagnosticPosition pos,
   441             TypeSymbol annoDecl)
   442     {
   443         // The next three checks check that the Repeatable annotation
   444         // on the declaration of the annotation type that is repeating is
   445         // valid.
   447         // Repeatable must have at least one element
   448         if (ca.values.isEmpty()) {
   449             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   450             return null;
   451         }
   452         Pair<MethodSymbol,Attribute> p = ca.values.head;
   453         Name name = p.fst.name;
   454         if (name != names.value) { // should contain only one element, named "value"
   455             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   456             return null;
   457         }
   458         if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
   459             log.error(pos, "invalid.repeatable.annotation", annoDecl);
   460             return null;
   461         }
   463         return ((Attribute.Class)p.snd).getValue();
   464     }
   466     /* Validate that the suggested targetContainerType Type is a valid
   467      * container type for repeated instances of originalAnnoType
   468      * annotations. Return null and report errors if this is not the
   469      * case, return the MethodSymbol of the value element in
   470      * targetContainerType if it is suitable (this is needed to
   471      * synthesize the container). */
   472     private MethodSymbol validateContainer(Type targetContainerType,
   473                                            Type originalAnnoType,
   474                                            DiagnosticPosition pos) {
   475         MethodSymbol containerValueSymbol = null;
   476         boolean fatalError = false;
   478         // Validate that there is a (and only 1) value method
   479         Scope scope = targetContainerType.tsym.members();
   480         int nr_value_elems = 0;
   481         boolean error = false;
   482         for(Symbol elm : scope.getElementsByName(names.value)) {
   483             nr_value_elems++;
   485             if (nr_value_elems == 1 &&
   486                 elm.kind == Kinds.MTH) {
   487                 containerValueSymbol = (MethodSymbol)elm;
   488             } else {
   489                 error = true;
   490             }
   491         }
   492         if (error) {
   493             log.error(pos,
   494                       "invalid.repeatable.annotation.multiple.values",
   495                       targetContainerType,
   496                       nr_value_elems);
   497             return null;
   498         } else if (nr_value_elems == 0) {
   499             log.error(pos,
   500                       "invalid.repeatable.annotation.no.value",
   501                       targetContainerType);
   502             return null;
   503         }
   505         // validate that the 'value' element is a method
   506         // probably "impossible" to fail this
   507         if (containerValueSymbol.kind != Kinds.MTH) {
   508             log.error(pos,
   509                       "invalid.repeatable.annotation.invalid.value",
   510                       targetContainerType);
   511             fatalError = true;
   512         }
   514         // validate that the 'value' element has the correct return type
   515         // i.e. array of original anno
   516         Type valueRetType = containerValueSymbol.type.getReturnType();
   517         Type expectedType = types.makeArrayType(originalAnnoType);
   518         if (!(types.isArray(valueRetType) &&
   519               types.isSameType(expectedType, valueRetType))) {
   520             log.error(pos,
   521                       "invalid.repeatable.annotation.value.return",
   522                       targetContainerType,
   523                       valueRetType,
   524                       expectedType);
   525             fatalError = true;
   526         }
   527         if (error) {
   528             fatalError = true;
   529         }
   531         // The conditions for a valid containing annotation are made
   532         // in Check.validateRepeatedAnnotaton();
   534         return fatalError ? null : containerValueSymbol;
   535     }
   536 }

mercurial