src/share/classes/com/sun/tools/javac/api/JavacTrees.java

Thu, 16 Sep 2010 09:56:25 -0700

author
jjg
date
Thu, 16 Sep 2010 09:56:25 -0700
changeset 682
6e2ccba61117
parent 672
ea54372637a5
child 696
d4df3b6ee729
permissions
-rw-r--r--

6985181: Annotations lost from classfile
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright (c) 2005, 2008, 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.api;
    28 import java.io.IOException;
    29 import java.util.Map;
    30 import javax.annotation.processing.ProcessingEnvironment;
    31 import javax.lang.model.element.AnnotationMirror;
    32 import javax.lang.model.element.AnnotationValue;
    33 import javax.lang.model.element.Element;
    34 import javax.lang.model.element.ExecutableElement;
    35 import javax.lang.model.element.TypeElement;
    36 import javax.lang.model.type.DeclaredType;
    37 import javax.lang.model.type.TypeMirror;
    38 import javax.tools.Diagnostic;
    39 import javax.tools.JavaCompiler;
    40 import javax.tools.JavaFileObject;
    42 import com.sun.source.tree.CompilationUnitTree;
    43 import com.sun.source.tree.Scope;
    44 import com.sun.source.tree.Tree;
    45 import com.sun.source.util.SourcePositions;
    46 import com.sun.source.util.TreePath;
    47 import com.sun.source.util.Trees;
    48 import com.sun.tools.javac.code.Flags;
    49 import com.sun.tools.javac.code.Symbol.ClassSymbol;
    50 import com.sun.tools.javac.code.Symbol.TypeSymbol;
    51 import com.sun.tools.javac.code.Symbol;
    52 import com.sun.tools.javac.comp.Attr;
    53 import com.sun.tools.javac.comp.AttrContext;
    54 import com.sun.tools.javac.comp.Enter;
    55 import com.sun.tools.javac.comp.Env;
    56 import com.sun.tools.javac.comp.MemberEnter;
    57 import com.sun.tools.javac.comp.Resolve;
    58 import com.sun.tools.javac.model.JavacElements;
    59 import com.sun.tools.javac.processing.JavacMessager;
    60 import com.sun.tools.javac.processing.JavacProcessingEnvironment;
    61 import com.sun.tools.javac.tree.JCTree.*;
    62 import com.sun.tools.javac.tree.JCTree;
    63 import com.sun.tools.javac.tree.TreeCopier;
    64 import com.sun.tools.javac.tree.TreeInfo;
    65 import com.sun.tools.javac.tree.TreeMaker;
    66 import com.sun.tools.javac.util.Context;
    67 import com.sun.tools.javac.util.JCDiagnostic;
    68 import com.sun.tools.javac.util.List;
    69 import com.sun.tools.javac.util.Log;
    70 import com.sun.tools.javac.util.Pair;
    72 /**
    73  * Provides an implementation of Trees.
    74  *
    75  * <p><b>This is NOT part of any supported API.
    76  * If you write code that depends on this, you do so at your own
    77  * risk.  This code and its internal interfaces are subject to change
    78  * or deletion without notice.</b></p>
    79  *
    80  * @author Peter von der Ah&eacute;
    81  */
    82 public class JavacTrees extends Trees {
    84     private final Resolve resolve;
    85     private final Enter enter;
    86     private final Log log;
    87     private final MemberEnter memberEnter;
    88     private final Attr attr;
    89     private final TreeMaker treeMaker;
    90     private final JavacElements elements;
    91     private final JavacTaskImpl javacTaskImpl;
    93     public static JavacTrees instance(JavaCompiler.CompilationTask task) {
    94         if (!(task instanceof JavacTaskImpl))
    95             throw new IllegalArgumentException();
    96         return instance(((JavacTaskImpl)task).getContext());
    97     }
    99     public static JavacTrees instance(ProcessingEnvironment env) {
   100         if (!(env instanceof JavacProcessingEnvironment))
   101             throw new IllegalArgumentException();
   102         return instance(((JavacProcessingEnvironment)env).getContext());
   103     }
   105     public static JavacTrees instance(Context context) {
   106         JavacTrees instance = context.get(JavacTrees.class);
   107         if (instance == null)
   108             instance = new JavacTrees(context);
   109         return instance;
   110     }
   112     private JavacTrees(Context context) {
   113         context.put(JavacTrees.class, this);
   114         attr = Attr.instance(context);
   115         enter = Enter.instance(context);
   116         elements = JavacElements.instance(context);
   117         log = Log.instance(context);
   118         resolve = Resolve.instance(context);
   119         treeMaker = TreeMaker.instance(context);
   120         memberEnter = MemberEnter.instance(context);
   121         javacTaskImpl = context.get(JavacTaskImpl.class);
   122     }
   124     public SourcePositions getSourcePositions() {
   125         return new SourcePositions() {
   126                 public long getStartPosition(CompilationUnitTree file, Tree tree) {
   127                     return TreeInfo.getStartPos((JCTree) tree);
   128                 }
   130                 public long getEndPosition(CompilationUnitTree file, Tree tree) {
   131                     Map<JCTree,Integer> endPositions = ((JCCompilationUnit) file).endPositions;
   132                     return TreeInfo.getEndPos((JCTree) tree, endPositions);
   133                 }
   134             };
   135     }
   137     public JCClassDecl getTree(TypeElement element) {
   138         return (JCClassDecl) getTree((Element) element);
   139     }
   141     public JCMethodDecl getTree(ExecutableElement method) {
   142         return (JCMethodDecl) getTree((Element) method);
   143     }
   145     public JCTree getTree(Element element) {
   146         Symbol symbol = (Symbol) element;
   147         TypeSymbol enclosing = symbol.enclClass();
   148         Env<AttrContext> env = enter.getEnv(enclosing);
   149         if (env == null)
   150             return null;
   151         JCClassDecl classNode = env.enclClass;
   152         if (classNode != null) {
   153             if (TreeInfo.symbolFor(classNode) == element)
   154                 return classNode;
   155             for (JCTree node : classNode.getMembers())
   156                 if (TreeInfo.symbolFor(node) == element)
   157                     return node;
   158         }
   159         return null;
   160     }
   162     public JCTree getTree(Element e, AnnotationMirror a) {
   163         return getTree(e, a, null);
   164     }
   166     public JCTree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
   167         Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
   168         if (treeTopLevel == null)
   169             return null;
   170         return treeTopLevel.fst;
   171     }
   173     public TreePath getPath(CompilationUnitTree unit, Tree node) {
   174         return TreePath.getPath(unit, node);
   175     }
   177     public TreePath getPath(Element e) {
   178         return getPath(e, null, null);
   179     }
   181     public TreePath getPath(Element e, AnnotationMirror a) {
   182         return getPath(e, a, null);
   183     }
   185     public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
   186         final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
   187         if (treeTopLevel == null)
   188             return null;
   189         return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst);
   190     }
   192     public Element getElement(TreePath path) {
   193         JCTree tree = (JCTree) path.getLeaf();
   194         Symbol sym = TreeInfo.symbolFor(tree);
   195         if (sym == null && TreeInfo.isDeclaration(tree)) {
   196             for (TreePath p = path; p != null; p = p.getParentPath()) {
   197                 JCTree t = (JCTree) p.getLeaf();
   198                 if (t.getTag() == JCTree.CLASSDEF) {
   199                     JCClassDecl ct = (JCClassDecl) t;
   200                     if (ct.sym != null) {
   201                         if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
   202                             attr.attribClass(ct.pos(), ct.sym);
   203                             sym = TreeInfo.symbolFor(tree);
   204                         }
   205                         break;
   206                     }
   207                 }
   208             }
   209         }
   210         return sym;
   211     }
   213     public TypeMirror getTypeMirror(TreePath path) {
   214         Tree t = path.getLeaf();
   215         return ((JCTree)t).type;
   216     }
   218     public JavacScope getScope(TreePath path) {
   219         return new JavacScope(getAttrContext(path));
   220     }
   222     public boolean isAccessible(Scope scope, TypeElement type) {
   223         if (scope instanceof JavacScope && type instanceof ClassSymbol) {
   224             Env<AttrContext> env = ((JavacScope) scope).env;
   225             return resolve.isAccessible(env, (ClassSymbol)type);
   226         } else
   227             return false;
   228     }
   230     public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
   231         if (scope instanceof JavacScope
   232                 && member instanceof Symbol
   233                 && type instanceof com.sun.tools.javac.code.Type) {
   234             Env<AttrContext> env = ((JavacScope) scope).env;
   235             return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member);
   236         } else
   237             return false;
   238     }
   240     private Env<AttrContext> getAttrContext(TreePath path) {
   241         if (!(path.getLeaf() instanceof JCTree))  // implicit null-check
   242             throw new IllegalArgumentException();
   244         // if we're being invoked via from a JSR199 client, we need to make sure
   245         // all the classes have been entered; if we're being invoked from JSR269,
   246         // then the classes will already have been entered.
   247         if (javacTaskImpl != null) {
   248             try {
   249                 javacTaskImpl.enter(null);
   250             } catch (IOException e) {
   251                 throw new Error("unexpected error while entering symbols: " + e);
   252             }
   253         }
   256         JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
   257         Copier copier = new Copier(treeMaker.forToplevel(unit));
   259         Env<AttrContext> env = null;
   260         JCMethodDecl method = null;
   261         JCVariableDecl field = null;
   263         List<Tree> l = List.nil();
   264         TreePath p = path;
   265         while (p != null) {
   266             l = l.prepend(p.getLeaf());
   267             p = p.getParentPath();
   268         }
   270         for ( ; l.nonEmpty(); l = l.tail) {
   271             Tree tree = l.head;
   272             switch (tree.getKind()) {
   273                 case COMPILATION_UNIT:
   274 //                    System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
   275                     env = enter.getTopLevelEnv((JCCompilationUnit)tree);
   276                     break;
   277                 case CLASS:
   278                 case INTERFACE:
   279                 case ENUM:
   280 //                    System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
   281                     env = enter.getClassEnv(((JCClassDecl)tree).sym);
   282                     break;
   283                 case METHOD:
   284 //                    System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
   285                     method = (JCMethodDecl)tree;
   286                     break;
   287                 case VARIABLE:
   288 //                    System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
   289                     field = (JCVariableDecl)tree;
   290                     break;
   291                 case BLOCK: {
   292 //                    System.err.println("BLOCK: ");
   293                     if (method != null)
   294                         env = memberEnter.getMethodEnv(method, env);
   295                     JCTree body = copier.copy((JCTree)tree, (JCTree) path.getLeaf());
   296                     env = attribStatToTree(body, env, copier.leafCopy);
   297                     return env;
   298                 }
   299                 default:
   300 //                    System.err.println("DEFAULT: " + tree.getKind());
   301                     if (field != null && field.getInitializer() == tree) {
   302                         env = memberEnter.getInitEnv(field, env);
   303                         JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
   304                         env = attribExprToTree(expr, env, copier.leafCopy);
   305                         return env;
   306                     }
   307             }
   308         }
   309         return field != null ? memberEnter.getInitEnv(field, env) : env;
   310     }
   312     private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
   313         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   314         try {
   315             return attr.attribStatToTree(stat, env, tree);
   316         } finally {
   317             log.useSource(prev);
   318         }
   319     }
   321     private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
   322         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   323         try {
   324             return attr.attribExprToTree(expr, env, tree);
   325         } finally {
   326             log.useSource(prev);
   327         }
   328     }
   330     /**
   331      * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
   332      **/
   333     static class Copier extends TreeCopier<JCTree> {
   334         JCTree leafCopy = null;
   336         Copier(TreeMaker M) {
   337             super(M);
   338         }
   340         public <T extends JCTree> T copy(T t, JCTree leaf) {
   341             T t2 = super.copy(t, leaf);
   342             if (t == leaf)
   343                 leafCopy = t2;
   344             return t2;
   345         }
   346     }
   348     /**
   349      * Gets the original type from the ErrorType object.
   350      * @param errorType The errorType for which we want to get the original type.
   351      * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
   352      *          noType (type.tag == NONE) is returned if there is no original type.
   353      */
   354     public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
   355         if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
   356             return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
   357         }
   359         return com.sun.tools.javac.code.Type.noType;
   360     }
   362     /**
   363      * Prints a message of the specified kind at the location of the
   364      * tree within the provided compilation unit
   365      *
   366      * @param kind the kind of message
   367      * @param msg  the message, or an empty string if none
   368      * @param t    the tree to use as a position hint
   369      * @param root the compilation unit that contains tree
   370      */
   371     public void printMessage(Diagnostic.Kind kind, CharSequence msg,
   372             com.sun.source.tree.Tree t,
   373             com.sun.source.tree.CompilationUnitTree root) {
   374         JavaFileObject oldSource = null;
   375         JavaFileObject newSource = null;
   376         JCDiagnostic.DiagnosticPosition pos = null;
   378         newSource = root.getSourceFile();
   379         if (newSource != null) {
   380             oldSource = log.useSource(newSource);
   381             pos = ((JCTree) t).pos();
   382         }
   384         try {
   385             switch (kind) {
   386             case ERROR:
   387                 boolean prev = log.multipleErrors;
   388                 try {
   389                     log.error(pos, "proc.messager", msg.toString());
   390                 } finally {
   391                     log.multipleErrors = prev;
   392                 }
   393                 break;
   395             case WARNING:
   396                 log.warning(pos, "proc.messager", msg.toString());
   397                 break;
   399             case MANDATORY_WARNING:
   400                 log.mandatoryWarning(pos, "proc.messager", msg.toString());
   401                 break;
   403             default:
   404                 log.note(pos, "proc.messager", msg.toString());
   405             }
   406         } finally {
   407             if (oldSource != null)
   408                 log.useSource(oldSource);
   409         }
   410     }
   411 }

mercurial