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

Thu, 09 Dec 2010 15:50:34 +0000

author
mcimadamore
date
Thu, 09 Dec 2010 15:50:34 +0000
changeset 780
1d625fbe6c22
parent 741
58ceeff50af8
child 783
90914ac50868
permissions
-rw-r--r--

6476118: compiler bug causes runtime ClassCastException for generics overloading
Summary: compiler allows bridge methods to override unrelated method
Reviewed-by: jjg

     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 boolean isAccessible(Scope scope, TypeElement type) {
   232         if (scope instanceof JavacScope && type instanceof ClassSymbol) {
   233             Env<AttrContext> env = ((JavacScope) scope).env;
   234             return resolve.isAccessible(env, (ClassSymbol)type, true);
   235         } else
   236             return false;
   237     }
   239     public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
   240         if (scope instanceof JavacScope
   241                 && member instanceof Symbol
   242                 && type instanceof com.sun.tools.javac.code.Type) {
   243             Env<AttrContext> env = ((JavacScope) scope).env;
   244             return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member, true);
   245         } else
   246             return false;
   247     }
   249     private Env<AttrContext> getAttrContext(TreePath path) {
   250         if (!(path.getLeaf() instanceof JCTree))  // implicit null-check
   251             throw new IllegalArgumentException();
   253         // if we're being invoked via from a JSR199 client, we need to make sure
   254         // all the classes have been entered; if we're being invoked from JSR269,
   255         // then the classes will already have been entered.
   256         if (javacTaskImpl != null) {
   257             try {
   258                 javacTaskImpl.enter(null);
   259             } catch (IOException e) {
   260                 throw new Error("unexpected error while entering symbols: " + e);
   261             }
   262         }
   265         JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
   266         Copier copier = new Copier(treeMaker.forToplevel(unit));
   268         Env<AttrContext> env = null;
   269         JCMethodDecl method = null;
   270         JCVariableDecl field = null;
   272         List<Tree> l = List.nil();
   273         TreePath p = path;
   274         while (p != null) {
   275             l = l.prepend(p.getLeaf());
   276             p = p.getParentPath();
   277         }
   279         for ( ; l.nonEmpty(); l = l.tail) {
   280             Tree tree = l.head;
   281             switch (tree.getKind()) {
   282                 case COMPILATION_UNIT:
   283 //                    System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
   284                     env = enter.getTopLevelEnv((JCCompilationUnit)tree);
   285                     break;
   286                 case ANNOTATION_TYPE:
   287                 case CLASS:
   288                 case ENUM:
   289                 case INTERFACE:
   290 //                    System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
   291                     env = enter.getClassEnv(((JCClassDecl)tree).sym);
   292                     break;
   293                 case METHOD:
   294 //                    System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
   295                     method = (JCMethodDecl)tree;
   296                     break;
   297                 case VARIABLE:
   298 //                    System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
   299                     field = (JCVariableDecl)tree;
   300                     break;
   301                 case BLOCK: {
   302 //                    System.err.println("BLOCK: ");
   303                     if (method != null)
   304                         env = memberEnter.getMethodEnv(method, env);
   305                     JCTree body = copier.copy((JCTree)tree, (JCTree) path.getLeaf());
   306                     env = attribStatToTree(body, env, copier.leafCopy);
   307                     return env;
   308                 }
   309                 default:
   310 //                    System.err.println("DEFAULT: " + tree.getKind());
   311                     if (field != null && field.getInitializer() == tree) {
   312                         env = memberEnter.getInitEnv(field, env);
   313                         JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
   314                         env = attribExprToTree(expr, env, copier.leafCopy);
   315                         return env;
   316                     }
   317             }
   318         }
   319         return field != null ? memberEnter.getInitEnv(field, env) : env;
   320     }
   322     private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
   323         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   324         try {
   325             return attr.attribStatToTree(stat, env, tree);
   326         } finally {
   327             log.useSource(prev);
   328         }
   329     }
   331     private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
   332         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   333         try {
   334             return attr.attribExprToTree(expr, env, tree);
   335         } finally {
   336             log.useSource(prev);
   337         }
   338     }
   340     /**
   341      * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
   342      **/
   343     static class Copier extends TreeCopier<JCTree> {
   344         JCTree leafCopy = null;
   346         Copier(TreeMaker M) {
   347             super(M);
   348         }
   350         @Override
   351         public <T extends JCTree> T copy(T t, JCTree leaf) {
   352             T t2 = super.copy(t, leaf);
   353             if (t == leaf)
   354                 leafCopy = t2;
   355             return t2;
   356         }
   357     }
   359     /**
   360      * Gets the original type from the ErrorType object.
   361      * @param errorType The errorType for which we want to get the original type.
   362      * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
   363      *          noType (type.tag == NONE) is returned if there is no original type.
   364      */
   365     public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
   366         if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
   367             return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
   368         }
   370         return com.sun.tools.javac.code.Type.noType;
   371     }
   373     /**
   374      * Prints a message of the specified kind at the location of the
   375      * tree within the provided compilation unit
   376      *
   377      * @param kind the kind of message
   378      * @param msg  the message, or an empty string if none
   379      * @param t    the tree to use as a position hint
   380      * @param root the compilation unit that contains tree
   381      */
   382     public void printMessage(Diagnostic.Kind kind, CharSequence msg,
   383             com.sun.source.tree.Tree t,
   384             com.sun.source.tree.CompilationUnitTree root) {
   385         JavaFileObject oldSource = null;
   386         JavaFileObject newSource = null;
   387         JCDiagnostic.DiagnosticPosition pos = null;
   389         newSource = root.getSourceFile();
   390         if (newSource != null) {
   391             oldSource = log.useSource(newSource);
   392             pos = ((JCTree) t).pos();
   393         }
   395         try {
   396             switch (kind) {
   397             case ERROR:
   398                 boolean prev = log.multipleErrors;
   399                 try {
   400                     log.error(pos, "proc.messager", msg.toString());
   401                 } finally {
   402                     log.multipleErrors = prev;
   403                 }
   404                 break;
   406             case WARNING:
   407                 log.warning(pos, "proc.messager", msg.toString());
   408                 break;
   410             case MANDATORY_WARNING:
   411                 log.mandatoryWarning(pos, "proc.messager", msg.toString());
   412                 break;
   414             default:
   415                 log.note(pos, "proc.messager", msg.toString());
   416             }
   417         } finally {
   418             if (oldSource != null)
   419                 log.useSource(oldSource);
   420         }
   421     }
   422 }

mercurial