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

Wed, 20 Jun 2012 13:23:26 -0700

author
jjg
date
Wed, 20 Jun 2012 13:23:26 -0700
changeset 1280
5c0b3faeb0b0
parent 1210
62e611704863
child 1327
fabfd2710057
permissions
-rw-r--r--

7174143: encapsulate doc comment table
Reviewed-by: ksrini, mcimadamore

     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.api;
    28 import java.io.IOException;
    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.TypeKind;
    38 import javax.lang.model.type.TypeMirror;
    39 import javax.tools.Diagnostic;
    40 import javax.tools.JavaCompiler;
    41 import javax.tools.JavaFileObject;
    43 import com.sun.source.tree.CatchTree;
    44 import com.sun.source.tree.CompilationUnitTree;
    45 import com.sun.source.tree.Scope;
    46 import com.sun.source.tree.Tree;
    47 import com.sun.source.util.JavacTask;
    48 import com.sun.source.util.SourcePositions;
    49 import com.sun.source.util.TreePath;
    50 import com.sun.source.util.Trees;
    51 import com.sun.tools.javac.code.Flags;
    52 import com.sun.tools.javac.code.Symbol;
    53 import com.sun.tools.javac.code.Symbol.ClassSymbol;
    54 import com.sun.tools.javac.code.Symbol.TypeSymbol;
    55 import com.sun.tools.javac.code.Type.UnionClassType;
    56 import com.sun.tools.javac.comp.Attr;
    57 import com.sun.tools.javac.comp.AttrContext;
    58 import com.sun.tools.javac.comp.Enter;
    59 import com.sun.tools.javac.comp.Env;
    60 import com.sun.tools.javac.comp.MemberEnter;
    61 import com.sun.tools.javac.comp.Resolve;
    62 import com.sun.tools.javac.model.JavacElements;
    63 import com.sun.tools.javac.tree.EndPosTable;
    64 import com.sun.tools.javac.processing.JavacProcessingEnvironment;
    65 import com.sun.tools.javac.tree.JCTree;
    66 import com.sun.tools.javac.tree.JCTree.*;
    67 import com.sun.tools.javac.tree.TreeCopier;
    68 import com.sun.tools.javac.tree.TreeInfo;
    69 import com.sun.tools.javac.tree.TreeMaker;
    70 import com.sun.tools.javac.util.Assert;
    71 import com.sun.tools.javac.util.Context;
    72 import com.sun.tools.javac.util.JCDiagnostic;
    73 import com.sun.tools.javac.util.List;
    74 import com.sun.tools.javac.util.Log;
    75 import com.sun.tools.javac.util.Pair;
    77 /**
    78  * Provides an implementation of Trees.
    79  *
    80  * <p><b>This is NOT part of any supported API.
    81  * If you write code that depends on this, you do so at your own
    82  * risk.  This code and its internal interfaces are subject to change
    83  * or deletion without notice.</b></p>
    84  *
    85  * @author Peter von der Ah&eacute;
    86  */
    87 public class JavacTrees extends Trees {
    89     // in a world of a single context per compilation, these would all be final
    90     private Resolve resolve;
    91     private Enter enter;
    92     private Log log;
    93     private MemberEnter memberEnter;
    94     private Attr attr;
    95     private TreeMaker treeMaker;
    96     private JavacElements elements;
    97     private JavacTaskImpl javacTaskImpl;
    99     // called reflectively from Trees.instance(CompilationTask task)
   100     public static JavacTrees instance(JavaCompiler.CompilationTask task) {
   101         if (!(task instanceof JavacTaskImpl))
   102             throw new IllegalArgumentException();
   103         return instance(((JavacTaskImpl)task).getContext());
   104     }
   106     // called reflectively from Trees.instance(ProcessingEnvironment env)
   107     public static JavacTrees instance(ProcessingEnvironment env) {
   108         if (!(env instanceof JavacProcessingEnvironment))
   109             throw new IllegalArgumentException();
   110         return instance(((JavacProcessingEnvironment)env).getContext());
   111     }
   113     public static JavacTrees instance(Context context) {
   114         JavacTrees instance = context.get(JavacTrees.class);
   115         if (instance == null)
   116             instance = new JavacTrees(context);
   117         return instance;
   118     }
   120     private JavacTrees(Context context) {
   121         context.put(JavacTrees.class, this);
   122         init(context);
   123     }
   125     public void updateContext(Context context) {
   126         init(context);
   127     }
   129     private void init(Context context) {
   130         attr = Attr.instance(context);
   131         enter = Enter.instance(context);
   132         elements = JavacElements.instance(context);
   133         log = Log.instance(context);
   134         resolve = Resolve.instance(context);
   135         treeMaker = TreeMaker.instance(context);
   136         memberEnter = MemberEnter.instance(context);
   138         JavacTask t = context.get(JavacTask.class);
   139         if (t instanceof JavacTaskImpl)
   140             javacTaskImpl = (JavacTaskImpl) t;
   141     }
   143     public SourcePositions getSourcePositions() {
   144         return new SourcePositions() {
   145                 public long getStartPosition(CompilationUnitTree file, Tree tree) {
   146                     return TreeInfo.getStartPos((JCTree) tree);
   147                 }
   149                 public long getEndPosition(CompilationUnitTree file, Tree tree) {
   150                     EndPosTable endPosTable = ((JCCompilationUnit) file).endPositions;
   151                     return TreeInfo.getEndPos((JCTree) tree, endPosTable);
   152                 }
   153             };
   154     }
   156     public JCClassDecl getTree(TypeElement element) {
   157         return (JCClassDecl) getTree((Element) element);
   158     }
   160     public JCMethodDecl getTree(ExecutableElement method) {
   161         return (JCMethodDecl) getTree((Element) method);
   162     }
   164     public JCTree getTree(Element element) {
   165         Symbol symbol = (Symbol) element;
   166         TypeSymbol enclosing = symbol.enclClass();
   167         Env<AttrContext> env = enter.getEnv(enclosing);
   168         if (env == null)
   169             return null;
   170         JCClassDecl classNode = env.enclClass;
   171         if (classNode != null) {
   172             if (TreeInfo.symbolFor(classNode) == element)
   173                 return classNode;
   174             for (JCTree node : classNode.getMembers())
   175                 if (TreeInfo.symbolFor(node) == element)
   176                     return node;
   177         }
   178         return null;
   179     }
   181     public JCTree getTree(Element e, AnnotationMirror a) {
   182         return getTree(e, a, null);
   183     }
   185     public JCTree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
   186         Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
   187         if (treeTopLevel == null)
   188             return null;
   189         return treeTopLevel.fst;
   190     }
   192     public TreePath getPath(CompilationUnitTree unit, Tree node) {
   193         return TreePath.getPath(unit, node);
   194     }
   196     public TreePath getPath(Element e) {
   197         return getPath(e, null, null);
   198     }
   200     public TreePath getPath(Element e, AnnotationMirror a) {
   201         return getPath(e, a, null);
   202     }
   204     public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
   205         final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
   206         if (treeTopLevel == null)
   207             return null;
   208         return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst);
   209     }
   211     public Element getElement(TreePath path) {
   212         JCTree tree = (JCTree) path.getLeaf();
   213         Symbol sym = TreeInfo.symbolFor(tree);
   214         if (sym == null && TreeInfo.isDeclaration(tree)) {
   215             for (TreePath p = path; p != null; p = p.getParentPath()) {
   216                 JCTree t = (JCTree) p.getLeaf();
   217                 if (t.hasTag(JCTree.Tag.CLASSDEF)) {
   218                     JCClassDecl ct = (JCClassDecl) t;
   219                     if (ct.sym != null) {
   220                         if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
   221                             attr.attribClass(ct.pos(), ct.sym);
   222                             sym = TreeInfo.symbolFor(tree);
   223                         }
   224                         break;
   225                     }
   226                 }
   227             }
   228         }
   229         return sym;
   230     }
   232     public TypeMirror getTypeMirror(TreePath path) {
   233         Tree t = path.getLeaf();
   234         return ((JCTree)t).type;
   235     }
   237     public JavacScope getScope(TreePath path) {
   238         return new JavacScope(getAttrContext(path));
   239     }
   241     public String getDocComment(TreePath path) {
   242         CompilationUnitTree t = path.getCompilationUnit();
   243         Tree leaf = path.getLeaf();
   244         if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
   245             JCCompilationUnit cu = (JCCompilationUnit) t;
   246             if (cu.docComments != null) {
   247                 return cu.docComments.getCommentText((JCTree) leaf);
   248             }
   249         }
   250         return null;
   251     }
   253     public boolean isAccessible(Scope scope, TypeElement type) {
   254         if (scope instanceof JavacScope && type instanceof ClassSymbol) {
   255             Env<AttrContext> env = ((JavacScope) scope).env;
   256             return resolve.isAccessible(env, (ClassSymbol)type, true);
   257         } else
   258             return false;
   259     }
   261     public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
   262         if (scope instanceof JavacScope
   263                 && member instanceof Symbol
   264                 && type instanceof com.sun.tools.javac.code.Type) {
   265             Env<AttrContext> env = ((JavacScope) scope).env;
   266             return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member, true);
   267         } else
   268             return false;
   269     }
   271     private Env<AttrContext> getAttrContext(TreePath path) {
   272         if (!(path.getLeaf() instanceof JCTree))  // implicit null-check
   273             throw new IllegalArgumentException();
   275         // if we're being invoked from a Tree API client via parse/enter/analyze,
   276         // we need to make sure all the classes have been entered;
   277         // if we're being invoked from JSR 199 or JSR 269, then the classes
   278         // will already have been entered.
   279         if (javacTaskImpl != null) {
   280             try {
   281                 javacTaskImpl.enter(null);
   282             } catch (IOException e) {
   283                 throw new Error("unexpected error while entering symbols: " + e);
   284             }
   285         }
   288         JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
   289         Copier copier = new Copier(treeMaker.forToplevel(unit));
   291         Env<AttrContext> env = null;
   292         JCMethodDecl method = null;
   293         JCVariableDecl field = null;
   295         List<Tree> l = List.nil();
   296         TreePath p = path;
   297         while (p != null) {
   298             l = l.prepend(p.getLeaf());
   299             p = p.getParentPath();
   300         }
   302         for ( ; l.nonEmpty(); l = l.tail) {
   303             Tree tree = l.head;
   304             switch (tree.getKind()) {
   305                 case COMPILATION_UNIT:
   306 //                    System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
   307                     env = enter.getTopLevelEnv((JCCompilationUnit)tree);
   308                     break;
   309                 case ANNOTATION_TYPE:
   310                 case CLASS:
   311                 case ENUM:
   312                 case INTERFACE:
   313 //                    System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
   314                     env = enter.getClassEnv(((JCClassDecl)tree).sym);
   315                     break;
   316                 case METHOD:
   317 //                    System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
   318                     method = (JCMethodDecl)tree;
   319                     break;
   320                 case VARIABLE:
   321 //                    System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
   322                     field = (JCVariableDecl)tree;
   323                     break;
   324                 case BLOCK: {
   325 //                    System.err.println("BLOCK: ");
   326                     if (method != null) {
   327                         try {
   328                             Assert.check(method.body == tree);
   329                             method.body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
   330                             env = memberEnter.getMethodEnv(method, env);
   331                             env = attribStatToTree(method.body, env, copier.leafCopy);
   332                         } finally {
   333                             method.body = (JCBlock) tree;
   334                         }
   335                     } else {
   336                         JCBlock body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
   337                         env = attribStatToTree(body, env, copier.leafCopy);
   338                     }
   339                     return env;
   340                 }
   341                 default:
   342 //                    System.err.println("DEFAULT: " + tree.getKind());
   343                     if (field != null && field.getInitializer() == tree) {
   344                         env = memberEnter.getInitEnv(field, env);
   345                         JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
   346                         env = attribExprToTree(expr, env, copier.leafCopy);
   347                         return env;
   348                     }
   349             }
   350         }
   351         return (field != null) ? memberEnter.getInitEnv(field, env) : env;
   352     }
   354     private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
   355         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   356         try {
   357             return attr.attribStatToTree(stat, env, tree);
   358         } finally {
   359             log.useSource(prev);
   360         }
   361     }
   363     private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
   364         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   365         try {
   366             return attr.attribExprToTree(expr, env, tree);
   367         } finally {
   368             log.useSource(prev);
   369         }
   370     }
   372     /**
   373      * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
   374      **/
   375     static class Copier extends TreeCopier<JCTree> {
   376         JCTree leafCopy = null;
   378         Copier(TreeMaker M) {
   379             super(M);
   380         }
   382         @Override
   383         public <T extends JCTree> T copy(T t, JCTree leaf) {
   384             T t2 = super.copy(t, leaf);
   385             if (t == leaf)
   386                 leafCopy = t2;
   387             return t2;
   388         }
   389     }
   391     /**
   392      * Gets the original type from the ErrorType object.
   393      * @param errorType The errorType for which we want to get the original type.
   394      * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
   395      *          noType (type.tag == NONE) is returned if there is no original type.
   396      */
   397     public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
   398         if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
   399             return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
   400         }
   402         return com.sun.tools.javac.code.Type.noType;
   403     }
   405     /**
   406      * Prints a message of the specified kind at the location of the
   407      * tree within the provided compilation unit
   408      *
   409      * @param kind the kind of message
   410      * @param msg  the message, or an empty string if none
   411      * @param t    the tree to use as a position hint
   412      * @param root the compilation unit that contains tree
   413      */
   414     public void printMessage(Diagnostic.Kind kind, CharSequence msg,
   415             com.sun.source.tree.Tree t,
   416             com.sun.source.tree.CompilationUnitTree root) {
   417         JavaFileObject oldSource = null;
   418         JavaFileObject newSource = null;
   419         JCDiagnostic.DiagnosticPosition pos = null;
   421         newSource = root.getSourceFile();
   422         if (newSource != null) {
   423             oldSource = log.useSource(newSource);
   424             pos = ((JCTree) t).pos();
   425         }
   427         try {
   428             switch (kind) {
   429             case ERROR:
   430                 boolean prev = log.multipleErrors;
   431                 try {
   432                     log.error(pos, "proc.messager", msg.toString());
   433                 } finally {
   434                     log.multipleErrors = prev;
   435                 }
   436                 break;
   438             case WARNING:
   439                 log.warning(pos, "proc.messager", msg.toString());
   440                 break;
   442             case MANDATORY_WARNING:
   443                 log.mandatoryWarning(pos, "proc.messager", msg.toString());
   444                 break;
   446             default:
   447                 log.note(pos, "proc.messager", msg.toString());
   448             }
   449         } finally {
   450             if (oldSource != null)
   451                 log.useSource(oldSource);
   452         }
   453     }
   455     @Override
   456     public TypeMirror getLub(CatchTree tree) {
   457         JCCatch ct = (JCCatch) tree;
   458         JCVariableDecl v = ct.param;
   459         if (v.type != null && v.type.getKind() == TypeKind.UNION) {
   460             UnionClassType ut = (UnionClassType) v.type;
   461             return ut.getLub();
   462         } else {
   463             return v.type;
   464         }
   465     }
   466 }

mercurial