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