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

Thu, 01 Nov 2012 10:48:36 +0100

author
ohrstrom
date
Thu, 01 Nov 2012 10:48:36 +0100
changeset 1384
bf54daa9dcd8
parent 1374
c002fdee76fd
child 1491
9f42a06a49c0
permissions
-rw-r--r--

7153951: Add new lint option -Xlint:auxiliaryclass
Reviewed-by: jjg, mcimadamore, forax

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

mercurial