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

Mon, 14 Mar 2011 11:48:41 -0700

author
jjg
date
Mon, 14 Mar 2011 11:48:41 -0700
changeset 930
cb119107aeea
parent 783
90914ac50868
child 988
7ae6c0fd479b
permissions
-rw-r--r--

7026509: Cannot use JavaCompiler to create multiple CompilationTasks for partial compilations
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright (c) 2005, 2010, 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.code.Type;
    53 import com.sun.tools.javac.comp.Attr;
    54 import com.sun.tools.javac.comp.AttrContext;
    55 import com.sun.tools.javac.comp.Enter;
    56 import com.sun.tools.javac.comp.Env;
    57 import com.sun.tools.javac.comp.MemberEnter;
    58 import com.sun.tools.javac.comp.Resolve;
    59 import com.sun.tools.javac.model.JavacElements;
    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     // in a world of a single context per compilation, these would all be final
    85     private Resolve resolve;
    86     private Enter enter;
    87     private Log log;
    88     private MemberEnter memberEnter;
    89     private Attr attr;
    90     private TreeMaker treeMaker;
    91     private JavacElements elements;
    92     private JavacTaskImpl javacTaskImpl;
    94     public static JavacTrees instance(JavaCompiler.CompilationTask task) {
    95         if (!(task instanceof JavacTaskImpl))
    96             throw new IllegalArgumentException();
    97         return instance(((JavacTaskImpl)task).getContext());
    98     }
   100     public static JavacTrees instance(ProcessingEnvironment env) {
   101         if (!(env instanceof JavacProcessingEnvironment))
   102             throw new IllegalArgumentException();
   103         return instance(((JavacProcessingEnvironment)env).getContext());
   104     }
   106     public static JavacTrees instance(Context context) {
   107         JavacTrees instance = context.get(JavacTrees.class);
   108         if (instance == null)
   109             instance = new JavacTrees(context);
   110         return instance;
   111     }
   113     private JavacTrees(Context context) {
   114         context.put(JavacTrees.class, this);
   115         init(context);
   116     }
   118     public void updateContext(Context context) {
   119         init(context);
   120     }
   122     private void init(Context context) {
   123         attr = Attr.instance(context);
   124         enter = Enter.instance(context);
   125         elements = JavacElements.instance(context);
   126         log = Log.instance(context);
   127         resolve = Resolve.instance(context);
   128         treeMaker = TreeMaker.instance(context);
   129         memberEnter = MemberEnter.instance(context);
   130         javacTaskImpl = context.get(JavacTaskImpl.class);
   131     }
   133     public SourcePositions getSourcePositions() {
   134         return new SourcePositions() {
   135                 public long getStartPosition(CompilationUnitTree file, Tree tree) {
   136                     return TreeInfo.getStartPos((JCTree) tree);
   137                 }
   139                 public long getEndPosition(CompilationUnitTree file, Tree tree) {
   140                     Map<JCTree,Integer> endPositions = ((JCCompilationUnit) file).endPositions;
   141                     return TreeInfo.getEndPos((JCTree) tree, endPositions);
   142                 }
   143             };
   144     }
   146     public JCClassDecl getTree(TypeElement element) {
   147         return (JCClassDecl) getTree((Element) element);
   148     }
   150     public JCMethodDecl getTree(ExecutableElement method) {
   151         return (JCMethodDecl) getTree((Element) method);
   152     }
   154     public JCTree getTree(Element element) {
   155         Symbol symbol = (Symbol) element;
   156         TypeSymbol enclosing = symbol.enclClass();
   157         Env<AttrContext> env = enter.getEnv(enclosing);
   158         if (env == null)
   159             return null;
   160         JCClassDecl classNode = env.enclClass;
   161         if (classNode != null) {
   162             if (TreeInfo.symbolFor(classNode) == element)
   163                 return classNode;
   164             for (JCTree node : classNode.getMembers())
   165                 if (TreeInfo.symbolFor(node) == element)
   166                     return node;
   167         }
   168         return null;
   169     }
   171     public JCTree getTree(Element e, AnnotationMirror a) {
   172         return getTree(e, a, null);
   173     }
   175     public JCTree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
   176         Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
   177         if (treeTopLevel == null)
   178             return null;
   179         return treeTopLevel.fst;
   180     }
   182     public TreePath getPath(CompilationUnitTree unit, Tree node) {
   183         return TreePath.getPath(unit, node);
   184     }
   186     public TreePath getPath(Element e) {
   187         return getPath(e, null, null);
   188     }
   190     public TreePath getPath(Element e, AnnotationMirror a) {
   191         return getPath(e, a, null);
   192     }
   194     public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
   195         final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
   196         if (treeTopLevel == null)
   197             return null;
   198         return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst);
   199     }
   201     public Element getElement(TreePath path) {
   202         JCTree tree = (JCTree) path.getLeaf();
   203         Symbol sym = TreeInfo.symbolFor(tree);
   204         if (sym == null && TreeInfo.isDeclaration(tree)) {
   205             for (TreePath p = path; p != null; p = p.getParentPath()) {
   206                 JCTree t = (JCTree) p.getLeaf();
   207                 if (t.getTag() == JCTree.CLASSDEF) {
   208                     JCClassDecl ct = (JCClassDecl) t;
   209                     if (ct.sym != null) {
   210                         if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
   211                             attr.attribClass(ct.pos(), ct.sym);
   212                             sym = TreeInfo.symbolFor(tree);
   213                         }
   214                         break;
   215                     }
   216                 }
   217             }
   218         }
   219         return sym;
   220     }
   222     public TypeMirror getTypeMirror(TreePath path) {
   223         Tree t = path.getLeaf();
   224         return ((JCTree)t).type;
   225     }
   227     public JavacScope getScope(TreePath path) {
   228         return new JavacScope(getAttrContext(path));
   229     }
   231     public String getDocComment(TreePath path) {
   232         CompilationUnitTree t = path.getCompilationUnit();
   233         if (t instanceof JCTree.JCCompilationUnit) {
   234             JCCompilationUnit cu = (JCCompilationUnit) t;
   235             if (cu.docComments != null) {
   236                 return cu.docComments.get(path.getLeaf());
   237             }
   238         }
   239         return null;
   240     }
   242     public boolean isAccessible(Scope scope, TypeElement type) {
   243         if (scope instanceof JavacScope && type instanceof ClassSymbol) {
   244             Env<AttrContext> env = ((JavacScope) scope).env;
   245             return resolve.isAccessible(env, (ClassSymbol)type, true);
   246         } else
   247             return false;
   248     }
   250     public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
   251         if (scope instanceof JavacScope
   252                 && member instanceof Symbol
   253                 && type instanceof com.sun.tools.javac.code.Type) {
   254             Env<AttrContext> env = ((JavacScope) scope).env;
   255             return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member, true);
   256         } else
   257             return false;
   258     }
   260     private Env<AttrContext> getAttrContext(TreePath path) {
   261         if (!(path.getLeaf() instanceof JCTree))  // implicit null-check
   262             throw new IllegalArgumentException();
   264         // if we're being invoked via from a JSR199 client, we need to make sure
   265         // all the classes have been entered; if we're being invoked from JSR269,
   266         // then the classes will already have been entered.
   267         if (javacTaskImpl != null) {
   268             try {
   269                 javacTaskImpl.enter(null);
   270             } catch (IOException e) {
   271                 throw new Error("unexpected error while entering symbols: " + e);
   272             }
   273         }
   276         JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
   277         Copier copier = new Copier(treeMaker.forToplevel(unit));
   279         Env<AttrContext> env = null;
   280         JCMethodDecl method = null;
   281         JCVariableDecl field = null;
   283         List<Tree> l = List.nil();
   284         TreePath p = path;
   285         while (p != null) {
   286             l = l.prepend(p.getLeaf());
   287             p = p.getParentPath();
   288         }
   290         for ( ; l.nonEmpty(); l = l.tail) {
   291             Tree tree = l.head;
   292             switch (tree.getKind()) {
   293                 case COMPILATION_UNIT:
   294 //                    System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
   295                     env = enter.getTopLevelEnv((JCCompilationUnit)tree);
   296                     break;
   297                 case ANNOTATION_TYPE:
   298                 case CLASS:
   299                 case ENUM:
   300                 case INTERFACE:
   301 //                    System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
   302                     env = enter.getClassEnv(((JCClassDecl)tree).sym);
   303                     break;
   304                 case METHOD:
   305 //                    System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
   306                     method = (JCMethodDecl)tree;
   307                     break;
   308                 case VARIABLE:
   309 //                    System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
   310                     field = (JCVariableDecl)tree;
   311                     break;
   312                 case BLOCK: {
   313 //                    System.err.println("BLOCK: ");
   314                     if (method != null)
   315                         env = memberEnter.getMethodEnv(method, env);
   316                     JCTree body = copier.copy((JCTree)tree, (JCTree) path.getLeaf());
   317                     env = attribStatToTree(body, env, copier.leafCopy);
   318                     return env;
   319                 }
   320                 default:
   321 //                    System.err.println("DEFAULT: " + tree.getKind());
   322                     if (field != null && field.getInitializer() == tree) {
   323                         env = memberEnter.getInitEnv(field, env);
   324                         JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
   325                         env = attribExprToTree(expr, env, copier.leafCopy);
   326                         return env;
   327                     }
   328             }
   329         }
   330         return field != null ? memberEnter.getInitEnv(field, env) : env;
   331     }
   333     private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
   334         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   335         try {
   336             return attr.attribStatToTree(stat, env, tree);
   337         } finally {
   338             log.useSource(prev);
   339         }
   340     }
   342     private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
   343         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   344         try {
   345             return attr.attribExprToTree(expr, env, tree);
   346         } finally {
   347             log.useSource(prev);
   348         }
   349     }
   351     /**
   352      * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
   353      **/
   354     static class Copier extends TreeCopier<JCTree> {
   355         JCTree leafCopy = null;
   357         Copier(TreeMaker M) {
   358             super(M);
   359         }
   361         @Override
   362         public <T extends JCTree> T copy(T t, JCTree leaf) {
   363             T t2 = super.copy(t, leaf);
   364             if (t == leaf)
   365                 leafCopy = t2;
   366             return t2;
   367         }
   368     }
   370     /**
   371      * Gets the original type from the ErrorType object.
   372      * @param errorType The errorType for which we want to get the original type.
   373      * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
   374      *          noType (type.tag == NONE) is returned if there is no original type.
   375      */
   376     public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
   377         if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
   378             return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
   379         }
   381         return com.sun.tools.javac.code.Type.noType;
   382     }
   384     /**
   385      * Prints a message of the specified kind at the location of the
   386      * tree within the provided compilation unit
   387      *
   388      * @param kind the kind of message
   389      * @param msg  the message, or an empty string if none
   390      * @param t    the tree to use as a position hint
   391      * @param root the compilation unit that contains tree
   392      */
   393     public void printMessage(Diagnostic.Kind kind, CharSequence msg,
   394             com.sun.source.tree.Tree t,
   395             com.sun.source.tree.CompilationUnitTree root) {
   396         JavaFileObject oldSource = null;
   397         JavaFileObject newSource = null;
   398         JCDiagnostic.DiagnosticPosition pos = null;
   400         newSource = root.getSourceFile();
   401         if (newSource != null) {
   402             oldSource = log.useSource(newSource);
   403             pos = ((JCTree) t).pos();
   404         }
   406         try {
   407             switch (kind) {
   408             case ERROR:
   409                 boolean prev = log.multipleErrors;
   410                 try {
   411                     log.error(pos, "proc.messager", msg.toString());
   412                 } finally {
   413                     log.multipleErrors = prev;
   414                 }
   415                 break;
   417             case WARNING:
   418                 log.warning(pos, "proc.messager", msg.toString());
   419                 break;
   421             case MANDATORY_WARNING:
   422                 log.mandatoryWarning(pos, "proc.messager", msg.toString());
   423                 break;
   425             default:
   426                 log.note(pos, "proc.messager", msg.toString());
   427             }
   428         } finally {
   429             if (oldSource != null)
   430                 log.useSource(oldSource);
   431         }
   432     }
   433 }

mercurial