src/share/classes/com/sun/tools/javac/model/JavacElements.java

Mon, 22 Apr 2013 10:24:19 +0200

author
jfranck
date
Mon, 22 Apr 2013 10:24:19 +0200
changeset 1709
bae8387d16aa
parent 1645
97f6839673d6
child 2525
2eb010b6cb22
permissions
-rw-r--r--

8011027: Type parameter annotations not passed through to javax.lang.model
Reviewed-by: jjg, darcy

     1 /*
     2  * Copyright (c) 2005, 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.model;
    28 import java.util.Map;
    30 import javax.lang.model.SourceVersion;
    31 import javax.lang.model.element.*;
    32 import javax.lang.model.type.DeclaredType;
    33 import javax.lang.model.util.Elements;
    34 import javax.tools.JavaFileObject;
    35 import static javax.lang.model.util.ElementFilter.methodsIn;
    37 import com.sun.tools.javac.code.*;
    38 import com.sun.tools.javac.code.Symbol.*;
    39 import com.sun.tools.javac.comp.AttrContext;
    40 import com.sun.tools.javac.comp.Enter;
    41 import com.sun.tools.javac.comp.Env;
    42 import com.sun.tools.javac.main.JavaCompiler;
    43 import com.sun.tools.javac.processing.PrintingProcessor;
    44 import com.sun.tools.javac.tree.JCTree;
    45 import com.sun.tools.javac.tree.JCTree.*;
    46 import com.sun.tools.javac.tree.TreeInfo;
    47 import com.sun.tools.javac.tree.TreeScanner;
    48 import com.sun.tools.javac.util.*;
    49 import com.sun.tools.javac.util.Name;
    50 import static com.sun.tools.javac.code.TypeTag.CLASS;
    51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    53 /**
    54  * Utility methods for operating on program elements.
    55  *
    56  * <p><b>This is NOT part of any supported API.
    57  * If you write code that depends on this, you do so at your own
    58  * risk.  This code and its internal interfaces are subject to change
    59  * or deletion without notice.</b></p>
    60  */
    61 public class JavacElements implements Elements {
    63     private JavaCompiler javaCompiler;
    64     private Symtab syms;
    65     private Names names;
    66     private Types types;
    67     private Enter enter;
    69     public static JavacElements instance(Context context) {
    70         JavacElements instance = context.get(JavacElements.class);
    71         if (instance == null)
    72             instance = new JavacElements(context);
    73         return instance;
    74     }
    76     /**
    77      * Public for use only by JavacProcessingEnvironment
    78      */
    79     protected JavacElements(Context context) {
    80         setContext(context);
    81     }
    83     /**
    84      * Use a new context.  May be called from outside to update
    85      * internal state for a new annotation-processing round.
    86      */
    87     public void setContext(Context context) {
    88         context.put(JavacElements.class, this);
    89         javaCompiler = JavaCompiler.instance(context);
    90         syms = Symtab.instance(context);
    91         names = Names.instance(context);
    92         types = Types.instance(context);
    93         enter = Enter.instance(context);
    94     }
    96     public PackageSymbol getPackageElement(CharSequence name) {
    97         String strName = name.toString();
    98         if (strName.equals(""))
    99             return syms.unnamedPackage;
   100         return SourceVersion.isName(strName)
   101             ? nameToSymbol(strName, PackageSymbol.class)
   102             : null;
   103     }
   105     public ClassSymbol getTypeElement(CharSequence name) {
   106         String strName = name.toString();
   107         return SourceVersion.isName(strName)
   108             ? nameToSymbol(strName, ClassSymbol.class)
   109             : null;
   110     }
   112     /**
   113      * Returns a symbol given the type's or packages's canonical name,
   114      * or null if the name isn't found.
   115      */
   116     private <S extends Symbol> S nameToSymbol(String nameStr, Class<S> clazz) {
   117         Name name = names.fromString(nameStr);
   118         // First check cache.
   119         Symbol sym = (clazz == ClassSymbol.class)
   120                     ? syms.classes.get(name)
   121                     : syms.packages.get(name);
   123         try {
   124             if (sym == null)
   125                 sym = javaCompiler.resolveIdent(nameStr);
   127             sym.complete();
   129             return (sym.kind != Kinds.ERR &&
   130                     sym.exists() &&
   131                     clazz.isInstance(sym) &&
   132                     name.equals(sym.getQualifiedName()))
   133                 ? clazz.cast(sym)
   134                 : null;
   135         } catch (CompletionFailure e) {
   136             return null;
   137         }
   138     }
   140     public JavacSourcePosition getSourcePosition(Element e) {
   141         Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e);
   142         if (treeTop == null)
   143             return null;
   144         JCTree tree = treeTop.fst;
   145         JCCompilationUnit toplevel = treeTop.snd;
   146         JavaFileObject sourcefile = toplevel.sourcefile;
   147         if (sourcefile == null)
   148             return null;
   149         return new JavacSourcePosition(sourcefile, tree.pos, toplevel.lineMap);
   150     }
   152     public JavacSourcePosition getSourcePosition(Element e, AnnotationMirror a) {
   153         Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e);
   154         if (treeTop == null)
   155             return null;
   156         JCTree tree = treeTop.fst;
   157         JCCompilationUnit toplevel = treeTop.snd;
   158         JavaFileObject sourcefile = toplevel.sourcefile;
   159         if (sourcefile == null)
   160             return null;
   162         JCTree annoTree = matchAnnoToTree(a, e, tree);
   163         if (annoTree == null)
   164             return null;
   165         return new JavacSourcePosition(sourcefile, annoTree.pos,
   166                                        toplevel.lineMap);
   167     }
   169     public JavacSourcePosition getSourcePosition(Element e, AnnotationMirror a,
   170                                             AnnotationValue v) {
   171         // TODO: better accuracy in getSourcePosition(... AnnotationValue)
   172         return getSourcePosition(e, a);
   173     }
   175     /**
   176      * Returns the tree for an annotation given the annotated element
   177      * and the element's own tree.  Returns null if the tree cannot be found.
   178      */
   179     private JCTree matchAnnoToTree(AnnotationMirror findme,
   180                                    Element e, JCTree tree) {
   181         Symbol sym = cast(Symbol.class, e);
   182         class Vis extends JCTree.Visitor {
   183             List<JCAnnotation> result = null;
   184             public void visitTopLevel(JCCompilationUnit tree) {
   185                 result = tree.packageAnnotations;
   186             }
   187             public void visitClassDef(JCClassDecl tree) {
   188                 result = tree.mods.annotations;
   189             }
   190             public void visitMethodDef(JCMethodDecl tree) {
   191                 result = tree.mods.annotations;
   192             }
   193             public void visitVarDef(JCVariableDecl tree) {
   194                 result = tree.mods.annotations;
   195             }
   196         }
   197         Vis vis = new Vis();
   198         tree.accept(vis);
   199         if (vis.result == null)
   200             return null;
   202         List<Attribute.Compound> annos = sym.getRawAttributes();
   203         return matchAnnoToTree(cast(Attribute.Compound.class, findme),
   204                                annos,
   205                                vis.result);
   206     }
   208     /**
   209      * Returns the tree for an annotation given a list of annotations
   210      * in which to search (recursively) and their corresponding trees.
   211      * Returns null if the tree cannot be found.
   212      */
   213     private JCTree matchAnnoToTree(Attribute.Compound findme,
   214                                    List<Attribute.Compound> annos,
   215                                    List<JCAnnotation> trees) {
   216         for (Attribute.Compound anno : annos) {
   217             for (JCAnnotation tree : trees) {
   218                 JCTree match = matchAnnoToTree(findme, anno, tree);
   219                 if (match != null)
   220                     return match;
   221             }
   222         }
   223         return null;
   224     }
   226     /**
   227      * Returns the tree for an annotation given an Attribute to
   228      * search (recursively) and its corresponding tree.
   229      * Returns null if the tree cannot be found.
   230      */
   231     private JCTree matchAnnoToTree(final Attribute.Compound findme,
   232                                    final Attribute attr,
   233                                    final JCTree tree) {
   234         if (attr == findme)
   235             return (tree.type.tsym == findme.type.tsym) ? tree : null;
   237         class Vis implements Attribute.Visitor {
   238             JCTree result = null;
   239             public void visitConstant(Attribute.Constant value) {
   240             }
   241             public void visitClass(Attribute.Class clazz) {
   242             }
   243             public void visitCompound(Attribute.Compound anno) {
   244                 for (Pair<MethodSymbol, Attribute> pair : anno.values) {
   245                     JCExpression expr = scanForAssign(pair.fst, tree);
   246                     if (expr != null) {
   247                         JCTree match = matchAnnoToTree(findme, pair.snd, expr);
   248                         if (match != null) {
   249                             result = match;
   250                             return;
   251                         }
   252                     }
   253                 }
   254             }
   255             public void visitArray(Attribute.Array array) {
   256                 if (tree.hasTag(NEWARRAY) &&
   257                         types.elemtype(array.type).tsym == findme.type.tsym) {
   258                     List<JCExpression> elems = ((JCNewArray) tree).elems;
   259                     for (Attribute value : array.values) {
   260                         if (value == findme) {
   261                             result = elems.head;
   262                             return;
   263                         }
   264                         elems = elems.tail;
   265                     }
   266                 }
   267             }
   268             public void visitEnum(Attribute.Enum e) {
   269             }
   270             public void visitError(Attribute.Error e) {
   271             }
   272         }
   273         Vis vis = new Vis();
   274         attr.accept(vis);
   275         return vis.result;
   276     }
   278     /**
   279      * Scans for a JCAssign node with a LHS matching a given
   280      * symbol, and returns its RHS.  Does not scan nested JCAnnotations.
   281      */
   282     private JCExpression scanForAssign(final MethodSymbol sym,
   283                                        final JCTree tree) {
   284         class TS extends TreeScanner {
   285             JCExpression result = null;
   286             public void scan(JCTree t) {
   287                 if (t != null && result == null)
   288                     t.accept(this);
   289             }
   290             public void visitAnnotation(JCAnnotation t) {
   291                 if (t == tree)
   292                     scan(t.args);
   293             }
   294             public void visitAssign(JCAssign t) {
   295                 if (t.lhs.hasTag(IDENT)) {
   296                     JCIdent ident = (JCIdent) t.lhs;
   297                     if (ident.sym == sym)
   298                         result = t.rhs;
   299                 }
   300             }
   301         }
   302         TS scanner = new TS();
   303         tree.accept(scanner);
   304         return scanner.result;
   305     }
   307     /**
   308      * Returns the tree node corresponding to this element, or null
   309      * if none can be found.
   310      */
   311     public JCTree getTree(Element e) {
   312         Pair<JCTree, ?> treeTop = getTreeAndTopLevel(e);
   313         return (treeTop != null) ? treeTop.fst : null;
   314     }
   316     public String getDocComment(Element e) {
   317         // Our doc comment is contained in a map in our toplevel,
   318         // indexed by our tree.  Find our enter environment, which gives
   319         // us our toplevel.  It also gives us a tree that contains our
   320         // tree:  walk it to find our tree.  This is painful.
   321         Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e);
   322         if (treeTop == null)
   323             return null;
   324         JCTree tree = treeTop.fst;
   325         JCCompilationUnit toplevel = treeTop.snd;
   326         if (toplevel.docComments == null)
   327             return null;
   328         return toplevel.docComments.getCommentText(tree);
   329     }
   331     public PackageElement getPackageOf(Element e) {
   332         return cast(Symbol.class, e).packge();
   333     }
   335     public boolean isDeprecated(Element e) {
   336         Symbol sym = cast(Symbol.class, e);
   337         return (sym.flags() & Flags.DEPRECATED) != 0;
   338     }
   340     public Name getBinaryName(TypeElement type) {
   341         return cast(TypeSymbol.class, type).flatName();
   342     }
   344     public Map<MethodSymbol, Attribute> getElementValuesWithDefaults(
   345                                                         AnnotationMirror a) {
   346         Attribute.Compound anno = cast(Attribute.Compound.class, a);
   347         DeclaredType annotype = a.getAnnotationType();
   348         Map<MethodSymbol, Attribute> valmap = anno.getElementValues();
   350         for (ExecutableElement ex :
   351                  methodsIn(annotype.asElement().getEnclosedElements())) {
   352             MethodSymbol meth = (MethodSymbol) ex;
   353             Attribute defaultValue = meth.getDefaultValue();
   354             if (defaultValue != null && !valmap.containsKey(meth)) {
   355                 valmap.put(meth, defaultValue);
   356             }
   357         }
   358         return valmap;
   359     }
   361     /**
   362      * {@inheritDoc}
   363      */
   364     public FilteredMemberList getAllMembers(TypeElement element) {
   365         Symbol sym = cast(Symbol.class, element);
   366         Scope scope = sym.members().dupUnshared();
   367         List<Type> closure = types.closure(sym.asType());
   368         for (Type t : closure)
   369             addMembers(scope, t);
   370         return new FilteredMemberList(scope);
   371     }
   372     // where
   373         private void addMembers(Scope scope, Type type) {
   374             members:
   375             for (Scope.Entry e = type.asElement().members().elems; e != null; e = e.sibling) {
   376                 Scope.Entry overrider = scope.lookup(e.sym.getSimpleName());
   377                 while (overrider.scope != null) {
   378                     if (overrider.sym.kind == e.sym.kind
   379                         && (overrider.sym.flags() & Flags.SYNTHETIC) == 0)
   380                     {
   381                         if (overrider.sym.getKind() == ElementKind.METHOD
   382                         && overrides((ExecutableElement)overrider.sym, (ExecutableElement)e.sym, (TypeElement)type.asElement())) {
   383                             continue members;
   384                         }
   385                     }
   386                     overrider = overrider.next();
   387                 }
   388                 boolean derived = e.sym.getEnclosingElement() != scope.owner;
   389                 ElementKind kind = e.sym.getKind();
   390                 boolean initializer = kind == ElementKind.CONSTRUCTOR
   391                     || kind == ElementKind.INSTANCE_INIT
   392                     || kind == ElementKind.STATIC_INIT;
   393                 if (!derived || (!initializer && e.sym.isInheritedIn(scope.owner, types)))
   394                     scope.enter(e.sym);
   395             }
   396         }
   398     /**
   399      * Returns all annotations of an element, whether
   400      * inherited or directly present.
   401      *
   402      * @param e  the element being examined
   403      * @return all annotations of the element
   404      */
   405     @Override
   406     public List<Attribute.Compound> getAllAnnotationMirrors(Element e) {
   407         Symbol sym = cast(Symbol.class, e);
   408         List<Attribute.Compound> annos = sym.getAnnotationMirrors();
   409         while (sym.getKind() == ElementKind.CLASS) {
   410             Type sup = ((ClassSymbol) sym).getSuperclass();
   411             if (!sup.hasTag(CLASS) || sup.isErroneous() ||
   412                     sup.tsym == syms.objectType.tsym) {
   413                 break;
   414             }
   415             sym = sup.tsym;
   416             List<Attribute.Compound> oldAnnos = annos;
   417             List<Attribute.Compound> newAnnos = sym.getAnnotationMirrors();
   418             for (Attribute.Compound anno : newAnnos) {
   419                 if (isInherited(anno.type) &&
   420                         !containsAnnoOfType(oldAnnos, anno.type)) {
   421                     annos = annos.prepend(anno);
   422                 }
   423             }
   424         }
   425         return annos;
   426     }
   428     /**
   429      * Tests whether an annotation type is @Inherited.
   430      */
   431     private boolean isInherited(Type annotype) {
   432         return annotype.tsym.attribute(syms.inheritedType.tsym) != null;
   433     }
   435     /**
   436      * Tests whether a list of annotations contains an annotation
   437      * of a given type.
   438      */
   439     private static boolean containsAnnoOfType(List<Attribute.Compound> annos,
   440                                               Type type) {
   441         for (Attribute.Compound anno : annos) {
   442             if (anno.type.tsym == type.tsym)
   443                 return true;
   444         }
   445         return false;
   446     }
   448     public boolean hides(Element hiderEl, Element hideeEl) {
   449         Symbol hider = cast(Symbol.class, hiderEl);
   450         Symbol hidee = cast(Symbol.class, hideeEl);
   452         // Fields only hide fields; methods only methods; types only types.
   453         // Names must match.  Nothing hides itself (just try it).
   454         if (hider == hidee ||
   455                 hider.kind != hidee.kind ||
   456                 hider.name != hidee.name) {
   457             return false;
   458         }
   460         // Only static methods can hide other methods.
   461         // Methods only hide methods with matching signatures.
   462         if (hider.kind == Kinds.MTH) {
   463             if (!hider.isStatic() ||
   464                         !types.isSubSignature(hider.type, hidee.type)) {
   465                 return false;
   466             }
   467         }
   469         // Hider must be in a subclass of hidee's class.
   470         // Note that if M1 hides M2, and M2 hides M3, and M3 is accessible
   471         // in M1's class, then M1 and M2 both hide M3.
   472         ClassSymbol hiderClass = hider.owner.enclClass();
   473         ClassSymbol hideeClass = hidee.owner.enclClass();
   474         if (hiderClass == null || hideeClass == null ||
   475                 !hiderClass.isSubClass(hideeClass, types)) {
   476             return false;
   477         }
   479         // Hidee must be accessible in hider's class.
   480         // The method isInheritedIn is poorly named:  it checks only access.
   481         return hidee.isInheritedIn(hiderClass, types);
   482     }
   484     public boolean overrides(ExecutableElement riderEl,
   485                              ExecutableElement rideeEl, TypeElement typeEl) {
   486         MethodSymbol rider = cast(MethodSymbol.class, riderEl);
   487         MethodSymbol ridee = cast(MethodSymbol.class, rideeEl);
   488         ClassSymbol origin = cast(ClassSymbol.class, typeEl);
   490         return rider.name == ridee.name &&
   492                // not reflexive as per JLS
   493                rider != ridee &&
   495                // we don't care if ridee is static, though that wouldn't
   496                // compile
   497                !rider.isStatic() &&
   499                // Symbol.overrides assumes the following
   500                ridee.isMemberOf(origin, types) &&
   502                // check access and signatures; don't check return types
   503                rider.overrides(ridee, origin, types, false);
   504     }
   506     public String getConstantExpression(Object value) {
   507         return Constants.format(value);
   508     }
   510     /**
   511      * Print a representation of the elements to the given writer in
   512      * the specified order.  The main purpose of this method is for
   513      * diagnostics.  The exact format of the output is <em>not</em>
   514      * specified and is subject to change.
   515      *
   516      * @param w the writer to print the output to
   517      * @param elements the elements to print
   518      */
   519     public void printElements(java.io.Writer w, Element... elements) {
   520         for (Element element : elements)
   521             (new PrintingProcessor.PrintingElementVisitor(w, this)).visit(element).flush();
   522     }
   524     public Name getName(CharSequence cs) {
   525         return names.fromString(cs.toString());
   526     }
   528     @Override
   529     public boolean isFunctionalInterface(TypeElement element) {
   530         if (element.getKind() != ElementKind.INTERFACE)
   531             return false;
   532         else {
   533             TypeSymbol tsym = cast(TypeSymbol.class, element);
   534             return types.isFunctionalInterface(tsym);
   535         }
   536     }
   538     /**
   539      * Returns the tree node and compilation unit corresponding to this
   540      * element, or null if they can't be found.
   541      */
   542     private Pair<JCTree, JCCompilationUnit> getTreeAndTopLevel(Element e) {
   543         Symbol sym = cast(Symbol.class, e);
   544         Env<AttrContext> enterEnv = getEnterEnv(sym);
   545         if (enterEnv == null)
   546             return null;
   547         JCTree tree = TreeInfo.declarationFor(sym, enterEnv.tree);
   548         if (tree == null || enterEnv.toplevel == null)
   549             return null;
   550         return new Pair<JCTree,JCCompilationUnit>(tree, enterEnv.toplevel);
   551     }
   553     /**
   554      * Returns the best approximation for the tree node and compilation unit
   555      * corresponding to the given element, annotation and value.
   556      * If the element is null, null is returned.
   557      * If the annotation is null or cannot be found, the tree node and
   558      * compilation unit for the element is returned.
   559      * If the annotation value is null or cannot be found, the tree node and
   560      * compilation unit for the annotation is returned.
   561      */
   562     public Pair<JCTree, JCCompilationUnit> getTreeAndTopLevel(
   563                       Element e, AnnotationMirror a, AnnotationValue v) {
   564         if (e == null)
   565             return null;
   567         Pair<JCTree, JCCompilationUnit> elemTreeTop = getTreeAndTopLevel(e);
   568         if (elemTreeTop == null)
   569             return null;
   571         if (a == null)
   572             return elemTreeTop;
   574         JCTree annoTree = matchAnnoToTree(a, e, elemTreeTop.fst);
   575         if (annoTree == null)
   576             return elemTreeTop;
   578         // 6388543: if v != null, we should search within annoTree to find
   579         // the tree matching v. For now, we ignore v and return the tree of
   580         // the annotation.
   581         return new Pair<JCTree, JCCompilationUnit>(annoTree, elemTreeTop.snd);
   582     }
   584     /**
   585      * Returns a symbol's enter environment, or null if it has none.
   586      */
   587     private Env<AttrContext> getEnterEnv(Symbol sym) {
   588         // Get enclosing class of sym, or sym itself if it is a class
   589         // or package.
   590         TypeSymbol ts = (sym.kind != Kinds.PCK)
   591                         ? sym.enclClass()
   592                         : (PackageSymbol) sym;
   593         return (ts != null)
   594                 ? enter.getEnv(ts)
   595                 : null;
   596     }
   598     /**
   599      * Returns an object cast to the specified type.
   600      * @throws NullPointerException if the object is {@code null}
   601      * @throws IllegalArgumentException if the object is of the wrong type
   602      */
   603     private static <T> T cast(Class<T> clazz, Object o) {
   604         if (! clazz.isInstance(o))
   605             throw new IllegalArgumentException(o.toString());
   606         return clazz.cast(o);
   607     }
   608 }

mercurial