Tue, 28 Feb 2012 10:33:49 -0800
7093891: support multiple task listeners
Reviewed-by: darcy, 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.parser.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é
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 if (t instanceof JCTree.JCCompilationUnit) {
244 JCCompilationUnit cu = (JCCompilationUnit) t;
245 if (cu.docComments != null) {
246 return cu.docComments.get(path.getLeaf());
247 }
248 }
249 return null;
250 }
252 public boolean isAccessible(Scope scope, TypeElement type) {
253 if (scope instanceof JavacScope && type instanceof ClassSymbol) {
254 Env<AttrContext> env = ((JavacScope) scope).env;
255 return resolve.isAccessible(env, (ClassSymbol)type, true);
256 } else
257 return false;
258 }
260 public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
261 if (scope instanceof JavacScope
262 && member instanceof Symbol
263 && type instanceof com.sun.tools.javac.code.Type) {
264 Env<AttrContext> env = ((JavacScope) scope).env;
265 return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member, true);
266 } else
267 return false;
268 }
270 private Env<AttrContext> getAttrContext(TreePath path) {
271 if (!(path.getLeaf() instanceof JCTree)) // implicit null-check
272 throw new IllegalArgumentException();
274 // if we're being invoked from a Tree API client via parse/enter/analyze,
275 // we need to make sure all the classes have been entered;
276 // if we're being invoked from JSR 199 or JSR 269, then the classes
277 // will already have been entered.
278 if (javacTaskImpl != null) {
279 try {
280 javacTaskImpl.enter(null);
281 } catch (IOException e) {
282 throw new Error("unexpected error while entering symbols: " + e);
283 }
284 }
287 JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
288 Copier copier = new Copier(treeMaker.forToplevel(unit));
290 Env<AttrContext> env = null;
291 JCMethodDecl method = null;
292 JCVariableDecl field = null;
294 List<Tree> l = List.nil();
295 TreePath p = path;
296 while (p != null) {
297 l = l.prepend(p.getLeaf());
298 p = p.getParentPath();
299 }
301 for ( ; l.nonEmpty(); l = l.tail) {
302 Tree tree = l.head;
303 switch (tree.getKind()) {
304 case COMPILATION_UNIT:
305 // System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
306 env = enter.getTopLevelEnv((JCCompilationUnit)tree);
307 break;
308 case ANNOTATION_TYPE:
309 case CLASS:
310 case ENUM:
311 case INTERFACE:
312 // System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
313 env = enter.getClassEnv(((JCClassDecl)tree).sym);
314 break;
315 case METHOD:
316 // System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
317 method = (JCMethodDecl)tree;
318 break;
319 case VARIABLE:
320 // System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
321 field = (JCVariableDecl)tree;
322 break;
323 case BLOCK: {
324 // System.err.println("BLOCK: ");
325 if (method != null) {
326 try {
327 Assert.check(method.body == tree);
328 method.body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
329 env = memberEnter.getMethodEnv(method, env);
330 env = attribStatToTree(method.body, env, copier.leafCopy);
331 } finally {
332 method.body = (JCBlock) tree;
333 }
334 } else {
335 JCBlock body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
336 env = attribStatToTree(body, env, copier.leafCopy);
337 }
338 return env;
339 }
340 default:
341 // System.err.println("DEFAULT: " + tree.getKind());
342 if (field != null && field.getInitializer() == tree) {
343 env = memberEnter.getInitEnv(field, env);
344 JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
345 env = attribExprToTree(expr, env, copier.leafCopy);
346 return env;
347 }
348 }
349 }
350 return (field != null) ? memberEnter.getInitEnv(field, env) : env;
351 }
353 private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
354 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
355 try {
356 return attr.attribStatToTree(stat, env, tree);
357 } finally {
358 log.useSource(prev);
359 }
360 }
362 private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
363 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
364 try {
365 return attr.attribExprToTree(expr, env, tree);
366 } finally {
367 log.useSource(prev);
368 }
369 }
371 /**
372 * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
373 **/
374 static class Copier extends TreeCopier<JCTree> {
375 JCTree leafCopy = null;
377 Copier(TreeMaker M) {
378 super(M);
379 }
381 @Override
382 public <T extends JCTree> T copy(T t, JCTree leaf) {
383 T t2 = super.copy(t, leaf);
384 if (t == leaf)
385 leafCopy = t2;
386 return t2;
387 }
388 }
390 /**
391 * Gets the original type from the ErrorType object.
392 * @param errorType The errorType for which we want to get the original type.
393 * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
394 * noType (type.tag == NONE) is returned if there is no original type.
395 */
396 public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
397 if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
398 return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
399 }
401 return com.sun.tools.javac.code.Type.noType;
402 }
404 /**
405 * Prints a message of the specified kind at the location of the
406 * tree within the provided compilation unit
407 *
408 * @param kind the kind of message
409 * @param msg the message, or an empty string if none
410 * @param t the tree to use as a position hint
411 * @param root the compilation unit that contains tree
412 */
413 public void printMessage(Diagnostic.Kind kind, CharSequence msg,
414 com.sun.source.tree.Tree t,
415 com.sun.source.tree.CompilationUnitTree root) {
416 JavaFileObject oldSource = null;
417 JavaFileObject newSource = null;
418 JCDiagnostic.DiagnosticPosition pos = null;
420 newSource = root.getSourceFile();
421 if (newSource != null) {
422 oldSource = log.useSource(newSource);
423 pos = ((JCTree) t).pos();
424 }
426 try {
427 switch (kind) {
428 case ERROR:
429 boolean prev = log.multipleErrors;
430 try {
431 log.error(pos, "proc.messager", msg.toString());
432 } finally {
433 log.multipleErrors = prev;
434 }
435 break;
437 case WARNING:
438 log.warning(pos, "proc.messager", msg.toString());
439 break;
441 case MANDATORY_WARNING:
442 log.mandatoryWarning(pos, "proc.messager", msg.toString());
443 break;
445 default:
446 log.note(pos, "proc.messager", msg.toString());
447 }
448 } finally {
449 if (oldSource != null)
450 log.useSource(oldSource);
451 }
452 }
454 @Override
455 public TypeMirror getLub(CatchTree tree) {
456 JCCatch ct = (JCCatch) tree;
457 JCVariableDecl v = ct.param;
458 if (v.type != null && v.type.getKind() == TypeKind.UNION) {
459 UnionClassType ut = (UnionClassType) v.type;
460 return ut.getLub();
461 } else {
462 return v.type;
463 }
464 }
465 }