📄 javacelements.java
字号:
/* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */package com.sun.tools.javac.model;import java.lang.annotation.Annotation;import java.lang.annotation.Inherited;import java.util.Map;import javax.lang.model.SourceVersion;import javax.lang.model.element.*;import javax.lang.model.type.DeclaredType;import javax.lang.model.util.Elements;import javax.tools.JavaFileObject;import com.sun.tools.javac.code.*;import com.sun.tools.javac.code.Symbol.*;import com.sun.tools.javac.code.TypeTags;import com.sun.tools.javac.comp.AttrContext;import com.sun.tools.javac.comp.Enter;import com.sun.tools.javac.comp.Env;import com.sun.tools.javac.jvm.ClassReader;import com.sun.tools.javac.main.JavaCompiler;import com.sun.tools.javac.processing.PrintingProcessor;import com.sun.tools.javac.tree.JCTree;import com.sun.tools.javac.tree.JCTree.*;import com.sun.tools.javac.tree.TreeInfo;import com.sun.tools.javac.tree.TreeScanner;import com.sun.tools.javac.util.Name;import com.sun.tools.javac.util.*;import static javax.lang.model.util.ElementFilter.methodsIn;/** * Utility methods for operating on program elements. * * <p><b>This is NOT part of any API supported by Sun Microsystems. * If you write code that depends on this, you do so at your own * risk. This code and its internal interfaces are subject to change * or deletion without notice.</b></p> */public class JavacElements implements Elements { private JavaCompiler javaCompiler; private Symtab syms; private Name.Table names; private Types types; private Enter enter; private ClassReader reader; private static final Context.Key<JavacElements> KEY = new Context.Key<JavacElements>(); public static JavacElements instance(Context context) { JavacElements instance = context.get(KEY); if (instance == null) { instance = new JavacElements(context); context.put(KEY, instance); } return instance; } /** * Public for use only by JavacProcessingEnvironment */ // TODO JavacElements constructor should be protected public JavacElements(Context context) { setContext(context); } /** * Use a new context. May be called from outside to update * internal state for a new annotation-processing round. * This instance is *not* then registered with the new context. */ public void setContext(Context context) { javaCompiler = JavaCompiler.instance(context); syms = Symtab.instance(context); names = Name.Table.instance(context); types = Types.instance(context); enter = Enter.instance(context); reader = ClassReader.instance(context); } /** * An internal-use utility that creates a reified annotation. */ public static <A extends Annotation> A getAnnotation(Symbol annotated, Class<A> annoType) { if (!annoType.isAnnotation()) throw new IllegalArgumentException("Not an annotation type: " + annoType); String name = annoType.getName(); for (Attribute.Compound anno : annotated.getAnnotationMirrors()) if (name.equals(anno.type.tsym.flatName().toString())) return AnnotationProxyMaker.generateAnnotation(anno, annoType); return null; } /** * An internal-use utility that creates a reified annotation. * This overloaded version take annotation inheritance into account. */ public static <A extends Annotation> A getAnnotation(ClassSymbol annotated, Class<A> annoType) { boolean inherited = annoType.isAnnotationPresent(Inherited.class); A result = null; while (annotated.name != annotated.name.table.java_lang_Object) { result = getAnnotation((Symbol)annotated, annoType); if (result != null || !inherited) break; Type sup = annotated.getSuperclass(); if (sup.tag != TypeTags.CLASS || sup.isErroneous()) break; annotated = (ClassSymbol) sup.tsym; } return result; } public PackageSymbol getPackageElement(CharSequence name) { String strName = name.toString(); if (strName.equals("")) return syms.unnamedPackage; return SourceVersion.isName(strName) ? nameToSymbol(strName, PackageSymbol.class) : null; } public ClassSymbol getTypeElement(CharSequence name) { String strName = name.toString(); return SourceVersion.isName(strName) ? nameToSymbol(strName, ClassSymbol.class) : null; } /** * Returns a symbol given the type's or packages's canonical name, * or null if the name isn't found. */ private <S extends Symbol> S nameToSymbol(String nameStr, Class<S> clazz) { Name name = names.fromString(nameStr); // First check cache. Symbol sym = (clazz == ClassSymbol.class) ? syms.classes.get(name) : syms.packages.get(name); try { if (sym == null) sym = javaCompiler.resolveIdent(nameStr); sym.complete(); return (sym.kind != Kinds.ERR && sym.exists() && clazz.isInstance(sym) && name.equals(sym.getQualifiedName())) ? clazz.cast(sym) : null; } catch (CompletionFailure e) { return null; } } public JavacSourcePosition getSourcePosition(Element e) { Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e); if (treeTop == null) return null; JCTree tree = treeTop.fst; JCCompilationUnit toplevel = treeTop.snd; JavaFileObject sourcefile = toplevel.sourcefile; if (sourcefile == null) return null; return new JavacSourcePosition(sourcefile, tree.pos, toplevel.lineMap); } public JavacSourcePosition getSourcePosition(Element e, AnnotationMirror a) { Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e); if (treeTop == null) return null; JCTree tree = treeTop.fst; JCCompilationUnit toplevel = treeTop.snd; JavaFileObject sourcefile = toplevel.sourcefile; if (sourcefile == null) return null; JCTree annoTree = matchAnnoToTree(a, e, tree); if (annoTree == null) return null; return new JavacSourcePosition(sourcefile, annoTree.pos, toplevel.lineMap); } public JavacSourcePosition getSourcePosition(Element e, AnnotationMirror a, AnnotationValue v) { // TODO: better accuracy in getSourcePosition(... AnnotationValue) return getSourcePosition(e, a); } /** * Returns the tree for an annotation given the annotated element * and the element's own tree. Returns null if the tree cannot be found. */ private JCTree matchAnnoToTree(AnnotationMirror findme, Element e, JCTree tree) { Symbol sym = cast(Symbol.class, e); class Vis extends JCTree.Visitor { List<JCAnnotation> result = null; public void visitTopLevel(JCCompilationUnit tree) { result = tree.packageAnnotations; } public void visitClassDef(JCClassDecl tree) { result = tree.mods.annotations; } public void visitMethodDef(JCMethodDecl tree) { result = tree.mods.annotations; } public void visitVarDef(JCVariableDecl tree) { result = tree.mods.annotations; } } Vis vis = new Vis(); tree.accept(vis); if (vis.result == null) return null; return matchAnnoToTree(cast(Attribute.Compound.class, findme), sym.getAnnotationMirrors(), vis.result); } /** * Returns the tree for an annotation given a list of annotations * in which to search (recursively) and their corresponding trees. * Returns null if the tree cannot be found. */ private JCTree matchAnnoToTree(Attribute.Compound findme, List<Attribute.Compound> annos, List<JCAnnotation> trees) { for (Attribute.Compound anno : annos) { for (JCAnnotation tree : trees) { JCTree match = matchAnnoToTree(findme, anno, tree); if (match != null) return match; } } return null; } /** * Returns the tree for an annotation given an Attribute to * search (recursively) and its corresponding tree. * Returns null if the tree cannot be found. */ private JCTree matchAnnoToTree(final Attribute.Compound findme, final Attribute attr, final JCTree tree) { if (attr == findme) return (tree.type.tsym == findme.type.tsym) ? tree : null; class Vis implements Attribute.Visitor { JCTree result = null; public void visitConstant(Attribute.Constant value) { } public void visitClass(Attribute.Class clazz) { } public void visitCompound(Attribute.Compound anno) { for (Pair<MethodSymbol, Attribute> pair : anno.values) { JCExpression expr = scanForAssign(pair.fst, tree); if (expr != null) { JCTree match = matchAnnoToTree(findme, pair.snd, expr); if (match != null) { result = match; return; } } } } public void visitArray(Attribute.Array array) { if (tree.getTag() == JCTree.NEWARRAY && types.elemtype(array.type).tsym == findme.type.tsym) { List<JCExpression> elems = ((JCNewArray) tree).elems; for (Attribute value : array.values) { if (value == findme) { result = elems.head; return; } elems = elems.tail; } } } public void visitEnum(Attribute.Enum e) { } public void visitError(Attribute.Error e) { } } Vis vis = new Vis(); attr.accept(vis); return vis.result; } /** * Scans for a JCAssign node with a LHS matching a given
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -