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

Tue, 25 May 2010 15:54:51 -0700

author
ohair
date
Tue, 25 May 2010 15:54:51 -0700
changeset 554
9d9f26857129
parent 308
03944ee4fac4
child 581
f2fdd52e4e87
permissions
-rw-r--r--

6943119: Rebrand source copyright notices
Reviewed-by: darcy

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

mercurial