Mon, 27 Sep 2010 17:28:49 -0700
6986246: Trees object is round-specific
Reviewed-by: darcy
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.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.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 supported API.
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é
80 */
81 public class JavacTrees extends Trees {
83 // in a world of a single context per compilation, these would all be final
84 private Resolve resolve;
85 private Enter enter;
86 private Log log;
87 private MemberEnter memberEnter;
88 private Attr attr;
89 private TreeMaker treeMaker;
90 private JavacElements elements;
91 private 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 init(context);
115 }
117 public void updateContext(Context context) {
118 init(context);
119 }
121 private void init(Context context) {
122 attr = Attr.instance(context);
123 enter = Enter.instance(context);
124 elements = JavacElements.instance(context);
125 log = Log.instance(context);
126 resolve = Resolve.instance(context);
127 treeMaker = TreeMaker.instance(context);
128 memberEnter = MemberEnter.instance(context);
129 javacTaskImpl = context.get(JavacTaskImpl.class);
130 }
132 public SourcePositions getSourcePositions() {
133 return new SourcePositions() {
134 public long getStartPosition(CompilationUnitTree file, Tree tree) {
135 return TreeInfo.getStartPos((JCTree) tree);
136 }
138 public long getEndPosition(CompilationUnitTree file, Tree tree) {
139 Map<JCTree,Integer> endPositions = ((JCCompilationUnit) file).endPositions;
140 return TreeInfo.getEndPos((JCTree) tree, endPositions);
141 }
142 };
143 }
145 public JCClassDecl getTree(TypeElement element) {
146 return (JCClassDecl) getTree((Element) element);
147 }
149 public JCMethodDecl getTree(ExecutableElement method) {
150 return (JCMethodDecl) getTree((Element) method);
151 }
153 public JCTree getTree(Element element) {
154 Symbol symbol = (Symbol) element;
155 TypeSymbol enclosing = symbol.enclClass();
156 Env<AttrContext> env = enter.getEnv(enclosing);
157 if (env == null)
158 return null;
159 JCClassDecl classNode = env.enclClass;
160 if (classNode != null) {
161 if (TreeInfo.symbolFor(classNode) == element)
162 return classNode;
163 for (JCTree node : classNode.getMembers())
164 if (TreeInfo.symbolFor(node) == element)
165 return node;
166 }
167 return null;
168 }
170 public JCTree getTree(Element e, AnnotationMirror a) {
171 return getTree(e, a, null);
172 }
174 public JCTree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
175 Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
176 if (treeTopLevel == null)
177 return null;
178 return treeTopLevel.fst;
179 }
181 public TreePath getPath(CompilationUnitTree unit, Tree node) {
182 return TreePath.getPath(unit, node);
183 }
185 public TreePath getPath(Element e) {
186 return getPath(e, null, null);
187 }
189 public TreePath getPath(Element e, AnnotationMirror a) {
190 return getPath(e, a, null);
191 }
193 public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
194 final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
195 if (treeTopLevel == null)
196 return null;
197 return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst);
198 }
200 public Element getElement(TreePath path) {
201 JCTree tree = (JCTree) path.getLeaf();
202 Symbol sym = TreeInfo.symbolFor(tree);
203 if (sym == null && TreeInfo.isDeclaration(tree)) {
204 for (TreePath p = path; p != null; p = p.getParentPath()) {
205 JCTree t = (JCTree) p.getLeaf();
206 if (t.getTag() == JCTree.CLASSDEF) {
207 JCClassDecl ct = (JCClassDecl) t;
208 if (ct.sym != null) {
209 if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
210 attr.attribClass(ct.pos(), ct.sym);
211 sym = TreeInfo.symbolFor(tree);
212 }
213 break;
214 }
215 }
216 }
217 }
218 return sym;
219 }
221 public TypeMirror getTypeMirror(TreePath path) {
222 Tree t = path.getLeaf();
223 return ((JCTree)t).type;
224 }
226 public JavacScope getScope(TreePath path) {
227 return new JavacScope(getAttrContext(path));
228 }
230 public boolean isAccessible(Scope scope, TypeElement type) {
231 if (scope instanceof JavacScope && type instanceof ClassSymbol) {
232 Env<AttrContext> env = ((JavacScope) scope).env;
233 return resolve.isAccessible(env, (ClassSymbol)type);
234 } else
235 return false;
236 }
238 public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
239 if (scope instanceof JavacScope
240 && member instanceof Symbol
241 && type instanceof com.sun.tools.javac.code.Type) {
242 Env<AttrContext> env = ((JavacScope) scope).env;
243 return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member);
244 } else
245 return false;
246 }
248 private Env<AttrContext> getAttrContext(TreePath path) {
249 if (!(path.getLeaf() instanceof JCTree)) // implicit null-check
250 throw new IllegalArgumentException();
252 // if we're being invoked via from a JSR199 client, we need to make sure
253 // all the classes have been entered; if we're being invoked from JSR269,
254 // then the classes will already have been entered.
255 if (javacTaskImpl != null) {
256 try {
257 javacTaskImpl.enter(null);
258 } catch (IOException e) {
259 throw new Error("unexpected error while entering symbols: " + e);
260 }
261 }
264 JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
265 Copier copier = new Copier(treeMaker.forToplevel(unit));
267 Env<AttrContext> env = null;
268 JCMethodDecl method = null;
269 JCVariableDecl field = null;
271 List<Tree> l = List.nil();
272 TreePath p = path;
273 while (p != null) {
274 l = l.prepend(p.getLeaf());
275 p = p.getParentPath();
276 }
278 for ( ; l.nonEmpty(); l = l.tail) {
279 Tree tree = l.head;
280 switch (tree.getKind()) {
281 case COMPILATION_UNIT:
282 // System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
283 env = enter.getTopLevelEnv((JCCompilationUnit)tree);
284 break;
285 case CLASS:
286 case INTERFACE:
287 case ENUM:
288 // System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
289 env = enter.getClassEnv(((JCClassDecl)tree).sym);
290 break;
291 case METHOD:
292 // System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
293 method = (JCMethodDecl)tree;
294 break;
295 case VARIABLE:
296 // System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
297 field = (JCVariableDecl)tree;
298 break;
299 case BLOCK: {
300 // System.err.println("BLOCK: ");
301 if (method != null)
302 env = memberEnter.getMethodEnv(method, env);
303 JCTree body = copier.copy((JCTree)tree, (JCTree) path.getLeaf());
304 env = attribStatToTree(body, env, copier.leafCopy);
305 return env;
306 }
307 default:
308 // System.err.println("DEFAULT: " + tree.getKind());
309 if (field != null && field.getInitializer() == tree) {
310 env = memberEnter.getInitEnv(field, env);
311 JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
312 env = attribExprToTree(expr, env, copier.leafCopy);
313 return env;
314 }
315 }
316 }
317 return field != null ? memberEnter.getInitEnv(field, env) : env;
318 }
320 private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
321 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
322 try {
323 return attr.attribStatToTree(stat, env, tree);
324 } finally {
325 log.useSource(prev);
326 }
327 }
329 private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
330 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
331 try {
332 return attr.attribExprToTree(expr, env, tree);
333 } finally {
334 log.useSource(prev);
335 }
336 }
338 /**
339 * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
340 **/
341 static class Copier extends TreeCopier<JCTree> {
342 JCTree leafCopy = null;
344 Copier(TreeMaker M) {
345 super(M);
346 }
348 @Override
349 public <T extends JCTree> T copy(T t, JCTree leaf) {
350 T t2 = super.copy(t, leaf);
351 if (t == leaf)
352 leafCopy = t2;
353 return t2;
354 }
355 }
357 /**
358 * Gets the original type from the ErrorType object.
359 * @param errorType The errorType for which we want to get the original type.
360 * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
361 * noType (type.tag == NONE) is returned if there is no original type.
362 */
363 public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
364 if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
365 return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
366 }
368 return com.sun.tools.javac.code.Type.noType;
369 }
371 /**
372 * Prints a message of the specified kind at the location of the
373 * tree within the provided compilation unit
374 *
375 * @param kind the kind of message
376 * @param msg the message, or an empty string if none
377 * @param t the tree to use as a position hint
378 * @param root the compilation unit that contains tree
379 */
380 public void printMessage(Diagnostic.Kind kind, CharSequence msg,
381 com.sun.source.tree.Tree t,
382 com.sun.source.tree.CompilationUnitTree root) {
383 JavaFileObject oldSource = null;
384 JavaFileObject newSource = null;
385 JCDiagnostic.DiagnosticPosition pos = null;
387 newSource = root.getSourceFile();
388 if (newSource != null) {
389 oldSource = log.useSource(newSource);
390 pos = ((JCTree) t).pos();
391 }
393 try {
394 switch (kind) {
395 case ERROR:
396 boolean prev = log.multipleErrors;
397 try {
398 log.error(pos, "proc.messager", msg.toString());
399 } finally {
400 log.multipleErrors = prev;
401 }
402 break;
404 case WARNING:
405 log.warning(pos, "proc.messager", msg.toString());
406 break;
408 case MANDATORY_WARNING:
409 log.mandatoryWarning(pos, "proc.messager", msg.toString());
410 break;
412 default:
413 log.note(pos, "proc.messager", msg.toString());
414 }
415 } finally {
416 if (oldSource != null)
417 log.useSource(oldSource);
418 }
419 }
420 }