Mon, 19 Nov 2012 11:38:49 -0800
8001098: Provide a simple light-weight "plug-in" mechanism for javac
Reviewed-by: 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;
29 import java.util.HashSet;
30 import java.util.Set;
32 import javax.annotation.processing.ProcessingEnvironment;
33 import javax.lang.model.element.AnnotationMirror;
34 import javax.lang.model.element.AnnotationValue;
35 import javax.lang.model.element.Element;
36 import javax.lang.model.element.ExecutableElement;
37 import javax.lang.model.element.TypeElement;
38 import javax.lang.model.type.DeclaredType;
39 import javax.lang.model.type.TypeKind;
40 import javax.lang.model.type.TypeMirror;
41 import javax.tools.Diagnostic;
42 import javax.tools.JavaCompiler;
43 import javax.tools.JavaFileObject;
45 import com.sun.source.doctree.DocCommentTree;
46 import com.sun.source.doctree.ReferenceTree;
47 import com.sun.source.tree.CatchTree;
48 import com.sun.source.tree.CompilationUnitTree;
49 import com.sun.source.tree.Scope;
50 import com.sun.source.tree.Tree;
51 import com.sun.source.util.DocTrees;
52 import com.sun.source.util.JavacTask;
53 import com.sun.source.util.SourcePositions;
54 import com.sun.source.util.TreePath;
55 import com.sun.tools.javac.code.Flags;
56 import com.sun.tools.javac.code.Kinds;
57 import com.sun.tools.javac.code.Symbol;
58 import com.sun.tools.javac.code.Symbol.ClassSymbol;
59 import com.sun.tools.javac.code.Symbol.MethodSymbol;
60 import com.sun.tools.javac.code.Symbol.PackageSymbol;
61 import com.sun.tools.javac.code.Symbol.TypeSymbol;
62 import com.sun.tools.javac.code.Symbol.VarSymbol;
63 import com.sun.tools.javac.code.Type;
64 import com.sun.tools.javac.code.Type.ArrayType;
65 import com.sun.tools.javac.code.Type.ClassType;
66 import com.sun.tools.javac.code.Type.ErrorType;
67 import com.sun.tools.javac.code.Type.UnionClassType;
68 import com.sun.tools.javac.code.Types;
69 import com.sun.tools.javac.code.Types.TypeRelation;
70 import com.sun.tools.javac.comp.Attr;
71 import com.sun.tools.javac.comp.AttrContext;
72 import com.sun.tools.javac.comp.Enter;
73 import com.sun.tools.javac.comp.Env;
74 import com.sun.tools.javac.comp.MemberEnter;
75 import com.sun.tools.javac.comp.Resolve;
76 import com.sun.tools.javac.model.JavacElements;
77 import com.sun.tools.javac.processing.JavacProcessingEnvironment;
78 import com.sun.tools.javac.tree.DCTree;
79 import com.sun.tools.javac.tree.DCTree.DCDocComment;
80 import com.sun.tools.javac.tree.DCTree.DCReference;
81 import com.sun.tools.javac.tree.EndPosTable;
82 import com.sun.tools.javac.tree.JCTree;
83 import com.sun.tools.javac.tree.JCTree.*;
84 import com.sun.tools.javac.tree.TreeCopier;
85 import com.sun.tools.javac.tree.TreeInfo;
86 import com.sun.tools.javac.tree.TreeMaker;
87 import com.sun.tools.javac.util.Assert;
88 import com.sun.tools.javac.util.Context;
89 import com.sun.tools.javac.util.JCDiagnostic;
90 import com.sun.tools.javac.util.List;
91 import com.sun.tools.javac.util.ListBuffer;
92 import com.sun.tools.javac.util.Log;
93 import com.sun.tools.javac.util.Name;
94 import com.sun.tools.javac.util.Names;
95 import com.sun.tools.javac.util.Pair;
96 import static com.sun.tools.javac.code.TypeTag.*;
98 /**
99 * Provides an implementation of Trees.
100 *
101 * <p><b>This is NOT part of any supported API.
102 * If you write code that depends on this, you do so at your own
103 * risk. This code and its internal interfaces are subject to change
104 * or deletion without notice.</b></p>
105 *
106 * @author Peter von der Ahé
107 */
108 public class JavacTrees extends DocTrees {
110 // in a world of a single context per compilation, these would all be final
111 private Resolve resolve;
112 private Enter enter;
113 private Log log;
114 private MemberEnter memberEnter;
115 private Attr attr;
116 private TreeMaker treeMaker;
117 private JavacElements elements;
118 private JavacTaskImpl javacTaskImpl;
119 private Names names;
120 private Types types;
122 // called reflectively from Trees.instance(CompilationTask task)
123 public static JavacTrees instance(JavaCompiler.CompilationTask task) {
124 if (!(task instanceof BasicJavacTask))
125 throw new IllegalArgumentException();
126 return instance(((BasicJavacTask)task).getContext());
127 }
129 // called reflectively from Trees.instance(ProcessingEnvironment env)
130 public static JavacTrees instance(ProcessingEnvironment env) {
131 if (!(env instanceof JavacProcessingEnvironment))
132 throw new IllegalArgumentException();
133 return instance(((JavacProcessingEnvironment)env).getContext());
134 }
136 public static JavacTrees instance(Context context) {
137 JavacTrees instance = context.get(JavacTrees.class);
138 if (instance == null)
139 instance = new JavacTrees(context);
140 return instance;
141 }
143 protected JavacTrees(Context context) {
144 context.put(JavacTrees.class, this);
145 init(context);
146 }
148 public void updateContext(Context context) {
149 init(context);
150 }
152 private void init(Context context) {
153 attr = Attr.instance(context);
154 enter = Enter.instance(context);
155 elements = JavacElements.instance(context);
156 log = Log.instance(context);
157 resolve = Resolve.instance(context);
158 treeMaker = TreeMaker.instance(context);
159 memberEnter = MemberEnter.instance(context);
160 names = Names.instance(context);
161 types = Types.instance(context);
163 JavacTask t = context.get(JavacTask.class);
164 if (t instanceof JavacTaskImpl)
165 javacTaskImpl = (JavacTaskImpl) t;
166 }
168 public SourcePositions getSourcePositions() {
169 return new SourcePositions() {
170 public long getStartPosition(CompilationUnitTree file, Tree tree) {
171 return TreeInfo.getStartPos((JCTree) tree);
172 }
174 public long getEndPosition(CompilationUnitTree file, Tree tree) {
175 EndPosTable endPosTable = ((JCCompilationUnit) file).endPositions;
176 return TreeInfo.getEndPos((JCTree) tree, endPosTable);
177 }
178 };
179 }
181 public JCClassDecl getTree(TypeElement element) {
182 return (JCClassDecl) getTree((Element) element);
183 }
185 public JCMethodDecl getTree(ExecutableElement method) {
186 return (JCMethodDecl) getTree((Element) method);
187 }
189 public JCTree getTree(Element element) {
190 Symbol symbol = (Symbol) element;
191 TypeSymbol enclosing = symbol.enclClass();
192 Env<AttrContext> env = enter.getEnv(enclosing);
193 if (env == null)
194 return null;
195 JCClassDecl classNode = env.enclClass;
196 if (classNode != null) {
197 if (TreeInfo.symbolFor(classNode) == element)
198 return classNode;
199 for (JCTree node : classNode.getMembers())
200 if (TreeInfo.symbolFor(node) == element)
201 return node;
202 }
203 return null;
204 }
206 public JCTree getTree(Element e, AnnotationMirror a) {
207 return getTree(e, a, null);
208 }
210 public JCTree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
211 Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
212 if (treeTopLevel == null)
213 return null;
214 return treeTopLevel.fst;
215 }
217 public TreePath getPath(CompilationUnitTree unit, Tree node) {
218 return TreePath.getPath(unit, node);
219 }
221 public TreePath getPath(Element e) {
222 return getPath(e, null, null);
223 }
225 public TreePath getPath(Element e, AnnotationMirror a) {
226 return getPath(e, a, null);
227 }
229 public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
230 final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
231 if (treeTopLevel == null)
232 return null;
233 return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst);
234 }
236 public Element getElement(TreePath path) {
237 JCTree tree = (JCTree) path.getLeaf();
238 Symbol sym = TreeInfo.symbolFor(tree);
239 if (sym == null && TreeInfo.isDeclaration(tree)) {
240 for (TreePath p = path; p != null; p = p.getParentPath()) {
241 JCTree t = (JCTree) p.getLeaf();
242 if (t.hasTag(JCTree.Tag.CLASSDEF)) {
243 JCClassDecl ct = (JCClassDecl) t;
244 if (ct.sym != null) {
245 if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
246 attr.attribClass(ct.pos(), ct.sym);
247 sym = TreeInfo.symbolFor(tree);
248 }
249 break;
250 }
251 }
252 }
253 }
254 return sym;
255 }
257 @Override
258 public Element getElement(TreePath path, ReferenceTree reference) {
259 if (!(reference instanceof DCReference))
260 return null;
261 DCReference ref = (DCReference) reference;
263 Env<AttrContext> env = getAttrContext(path);
265 Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
266 new Log.DeferredDiagnosticHandler(log);
267 try {
268 final ClassSymbol tsym;
269 final Name memberName;
270 if (ref.qualifierExpression == null) {
271 tsym = env.enclClass.sym;
272 memberName = ref.memberName;
273 } else {
274 // See if the qualifierExpression is a type or package name.
275 // javac does not provide the exact method required, so
276 // we first check if qualifierExpression identifies a type,
277 // and if not, then we check to see if it identifies a package.
278 Type t = attr.attribType(ref.qualifierExpression, env);
279 if (t.isErroneous()) {
280 if (ref.memberName == null) {
281 // Attr/Resolve assume packages exist and create symbols as needed
282 // so use getPackageElement to restrict search to existing packages
283 PackageSymbol pck = elements.getPackageElement(ref.qualifierExpression.toString());
284 if (pck != null) {
285 return pck;
286 } else if (ref.qualifierExpression.hasTag(JCTree.Tag.IDENT)) {
287 // fixup: allow "identifier" instead of "#identifier"
288 // for compatibility with javadoc
289 tsym = env.enclClass.sym;
290 memberName = ((JCIdent) ref.qualifierExpression).name;
291 } else
292 return null;
293 } else {
294 return null;
295 }
296 } else {
297 tsym = (ClassSymbol) t.tsym;
298 memberName = ref.memberName;
299 }
300 }
302 if (memberName == null)
303 return tsym;
305 final List<Type> paramTypes;
306 if (ref.paramTypes == null)
307 paramTypes = null;
308 else {
309 ListBuffer<Type> lb = new ListBuffer<Type>();
310 for (List<JCTree> l = ref.paramTypes; l.nonEmpty(); l = l.tail) {
311 JCTree tree = l.head;
312 Type t = attr.attribType(tree, env);
313 lb.add(t);
314 }
315 paramTypes = lb.toList();
316 }
318 Symbol msym = (memberName == tsym.name)
319 ? findConstructor(tsym, paramTypes)
320 : findMethod(tsym, memberName, paramTypes);
321 if (paramTypes != null) {
322 // explicit (possibly empty) arg list given, so cannot be a field
323 return msym;
324 }
326 VarSymbol vsym = (ref.paramTypes != null) ? null : findField(tsym, memberName);
327 // prefer a field over a method with no parameters
328 if (vsym != null &&
329 (msym == null ||
330 types.isSubtypeUnchecked(vsym.enclClass().asType(), msym.enclClass().asType()))) {
331 return vsym;
332 } else {
333 return msym;
334 }
335 } finally {
336 log.popDiagnosticHandler(deferredDiagnosticHandler);
337 }
338 }
340 /** @see com.sun.tools.javadoc.ClassDocImpl#findField */
341 private VarSymbol findField(ClassSymbol tsym, Name fieldName) {
342 return searchField(tsym, fieldName, new HashSet<ClassSymbol>());
343 }
345 /** @see com.sun.tools.javadoc.ClassDocImpl#searchField */
346 private VarSymbol searchField(ClassSymbol tsym, Name fieldName, Set<ClassSymbol> searched) {
347 if (searched.contains(tsym)) {
348 return null;
349 }
350 searched.add(tsym);
352 for (com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(fieldName);
353 e.scope != null; e = e.next()) {
354 if (e.sym.kind == Kinds.VAR) {
355 return (VarSymbol)e.sym;
356 }
357 }
359 //### If we found a VarSymbol above, but which did not pass
360 //### the modifier filter, we should return failure here!
362 ClassSymbol encl = tsym.owner.enclClass();
363 if (encl != null) {
364 VarSymbol vsym = searchField(encl, fieldName, searched);
365 if (vsym != null) {
366 return vsym;
367 }
368 }
370 // search superclass
371 Type superclass = tsym.getSuperclass();
372 if (superclass.tsym != null) {
373 VarSymbol vsym = searchField((ClassSymbol) superclass.tsym, fieldName, searched);
374 if (vsym != null) {
375 return vsym;
376 }
377 }
379 // search interfaces
380 List<Type> intfs = tsym.getInterfaces();
381 for (List<Type> l = intfs; l.nonEmpty(); l = l.tail) {
382 Type intf = l.head;
383 if (intf.isErroneous()) continue;
384 VarSymbol vsym = searchField((ClassSymbol) intf.tsym, fieldName, searched);
385 if (vsym != null) {
386 return vsym;
387 }
388 }
390 return null;
391 }
393 /** @see com.sun.tools.javadoc.ClassDocImpl#findConstructor */
394 MethodSymbol findConstructor(ClassSymbol tsym, List<Type> paramTypes) {
395 for (com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(names.init);
396 e.scope != null; e = e.next()) {
397 if (e.sym.kind == Kinds.MTH) {
398 if (hasParameterTypes((MethodSymbol) e.sym, paramTypes)) {
399 return (MethodSymbol) e.sym;
400 }
401 }
402 }
403 return null;
404 }
406 /** @see com.sun.tools.javadoc.ClassDocImpl#findMethod */
407 private MethodSymbol findMethod(ClassSymbol tsym, Name methodName, List<Type> paramTypes) {
408 return searchMethod(tsym, methodName, paramTypes, new HashSet<ClassSymbol>());
409 }
411 /** @see com.sun.tools.javadoc.ClassDocImpl#searchMethod */
412 private MethodSymbol searchMethod(ClassSymbol tsym, Name methodName,
413 List<Type> paramTypes, Set<ClassSymbol> searched) {
414 //### Note that this search is not necessarily what the compiler would do!
416 // do not match constructors
417 if (methodName == names.init)
418 return null;
420 if (searched.contains(tsym))
421 return null;
422 searched.add(tsym);
424 // search current class
425 com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(methodName);
427 //### Using modifier filter here isn't really correct,
428 //### but emulates the old behavior. Instead, we should
429 //### apply the normal rules of visibility and inheritance.
431 if (paramTypes == null) {
432 // If no parameters specified, we are allowed to return
433 // any method with a matching name. In practice, the old
434 // code returned the first method, which is now the last!
435 // In order to provide textually identical results, we
436 // attempt to emulate the old behavior.
437 MethodSymbol lastFound = null;
438 for (; e.scope != null; e = e.next()) {
439 if (e.sym.kind == Kinds.MTH) {
440 if (e.sym.name == methodName) {
441 lastFound = (MethodSymbol)e.sym;
442 }
443 }
444 }
445 if (lastFound != null) {
446 return lastFound;
447 }
448 } else {
449 for (; e.scope != null; e = e.next()) {
450 if (e.sym != null &&
451 e.sym.kind == Kinds.MTH) {
452 if (hasParameterTypes((MethodSymbol) e.sym, paramTypes)) {
453 return (MethodSymbol) e.sym;
454 }
455 }
456 }
457 }
459 //### If we found a MethodSymbol above, but which did not pass
460 //### the modifier filter, we should return failure here!
462 // search superclass
463 Type superclass = tsym.getSuperclass();
464 if (superclass.tsym != null) {
465 MethodSymbol msym = searchMethod((ClassSymbol) superclass.tsym, methodName, paramTypes, searched);
466 if (msym != null) {
467 return msym;
468 }
469 }
471 // search interfaces
472 List<Type> intfs = tsym.getInterfaces();
473 for (List<Type> l = intfs; l.nonEmpty(); l = l.tail) {
474 Type intf = l.head;
475 if (intf.isErroneous()) continue;
476 MethodSymbol msym = searchMethod((ClassSymbol) intf.tsym, methodName, paramTypes, searched);
477 if (msym != null) {
478 return msym;
479 }
480 }
482 // search enclosing class
483 ClassSymbol encl = tsym.owner.enclClass();
484 if (encl != null) {
485 MethodSymbol msym = searchMethod(encl, methodName, paramTypes, searched);
486 if (msym != null) {
487 return msym;
488 }
489 }
491 return null;
492 }
494 /** @see com.sun.tools.javadoc.ClassDocImpl */
495 private boolean hasParameterTypes(MethodSymbol method, List<Type> paramTypes) {
496 if (paramTypes == null)
497 return true;
499 if (method.params().size() != paramTypes.size())
500 return false;
502 List<Type> methodParamTypes = types.erasureRecursive(method.asType()).getParameterTypes();
504 return (Type.isErroneous(paramTypes))
505 ? fuzzyMatch(paramTypes, methodParamTypes)
506 : types.isSameTypes(paramTypes, methodParamTypes);
507 }
509 boolean fuzzyMatch(List<Type> paramTypes, List<Type> methodParamTypes) {
510 List<Type> l1 = paramTypes;
511 List<Type> l2 = methodParamTypes;
512 while (l1.nonEmpty()) {
513 if (!fuzzyMatch(l1.head, l2.head))
514 return false;
515 l1 = l1.tail;
516 l2 = l2.tail;
517 }
518 return true;
519 }
521 boolean fuzzyMatch(Type paramType, Type methodParamType) {
522 Boolean b = fuzzyMatcher.visit(paramType, methodParamType);
523 return (b == Boolean.TRUE);
524 }
526 TypeRelation fuzzyMatcher = new TypeRelation() {
527 @Override
528 public Boolean visitType(Type t, Type s) {
529 if (t == s)
530 return true;
532 if (s.isPartial())
533 return visit(s, t);
535 switch (t.getTag()) {
536 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
537 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
538 return t.getTag() == s.getTag();
540 default:
541 throw new AssertionError("fuzzyMatcher " + t.getTag());
542 }
543 }
545 @Override
546 public Boolean visitArrayType(ArrayType t, Type s) {
547 if (t == s)
548 return true;
550 if (s.isPartial())
551 return visit(s, t);
553 return s.getTag() == ARRAY
554 && visit(t.elemtype, types.elemtype(s));
555 }
557 @Override
558 public Boolean visitClassType(ClassType t, Type s) {
559 if (t == s)
560 return true;
562 if (s.isPartial())
563 return visit(s, t);
565 return t.tsym == s.tsym;
566 }
568 @Override
569 public Boolean visitErrorType(ErrorType t, Type s) {
570 return s.getTag() == CLASS
571 && t.tsym.name == ((ClassType) s).tsym.name;
572 }
573 };
575 public TypeMirror getTypeMirror(TreePath path) {
576 Tree t = path.getLeaf();
577 return ((JCTree)t).type;
578 }
580 public JavacScope getScope(TreePath path) {
581 return new JavacScope(getAttrContext(path));
582 }
584 public String getDocComment(TreePath path) {
585 CompilationUnitTree t = path.getCompilationUnit();
586 Tree leaf = path.getLeaf();
587 if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
588 JCCompilationUnit cu = (JCCompilationUnit) t;
589 if (cu.docComments != null) {
590 return cu.docComments.getCommentText((JCTree) leaf);
591 }
592 }
593 return null;
594 }
596 public DocCommentTree getDocCommentTree(TreePath path) {
597 CompilationUnitTree t = path.getCompilationUnit();
598 Tree leaf = path.getLeaf();
599 if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
600 JCCompilationUnit cu = (JCCompilationUnit) t;
601 if (cu.docComments != null) {
602 return cu.docComments.getCommentTree((JCTree) leaf);
603 }
604 }
605 return null;
606 }
608 public boolean isAccessible(Scope scope, TypeElement type) {
609 if (scope instanceof JavacScope && type instanceof ClassSymbol) {
610 Env<AttrContext> env = ((JavacScope) scope).env;
611 return resolve.isAccessible(env, (ClassSymbol)type, true);
612 } else
613 return false;
614 }
616 public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
617 if (scope instanceof JavacScope
618 && member instanceof Symbol
619 && type instanceof com.sun.tools.javac.code.Type) {
620 Env<AttrContext> env = ((JavacScope) scope).env;
621 return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member, true);
622 } else
623 return false;
624 }
626 private Env<AttrContext> getAttrContext(TreePath path) {
627 if (!(path.getLeaf() instanceof JCTree)) // implicit null-check
628 throw new IllegalArgumentException();
630 // if we're being invoked from a Tree API client via parse/enter/analyze,
631 // we need to make sure all the classes have been entered;
632 // if we're being invoked from JSR 199 or JSR 269, then the classes
633 // will already have been entered.
634 if (javacTaskImpl != null) {
635 try {
636 javacTaskImpl.enter(null);
637 } catch (IOException e) {
638 throw new Error("unexpected error while entering symbols: " + e);
639 }
640 }
643 JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
644 Copier copier = createCopier(treeMaker.forToplevel(unit));
646 Env<AttrContext> env = null;
647 JCMethodDecl method = null;
648 JCVariableDecl field = null;
650 List<Tree> l = List.nil();
651 TreePath p = path;
652 while (p != null) {
653 l = l.prepend(p.getLeaf());
654 p = p.getParentPath();
655 }
657 for ( ; l.nonEmpty(); l = l.tail) {
658 Tree tree = l.head;
659 switch (tree.getKind()) {
660 case COMPILATION_UNIT:
661 // System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
662 env = enter.getTopLevelEnv((JCCompilationUnit)tree);
663 break;
664 case ANNOTATION_TYPE:
665 case CLASS:
666 case ENUM:
667 case INTERFACE:
668 // System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
669 env = enter.getClassEnv(((JCClassDecl)tree).sym);
670 break;
671 case METHOD:
672 // System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
673 method = (JCMethodDecl)tree;
674 break;
675 case VARIABLE:
676 // System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
677 field = (JCVariableDecl)tree;
678 break;
679 case BLOCK: {
680 // System.err.println("BLOCK: ");
681 if (method != null) {
682 try {
683 Assert.check(method.body == tree);
684 method.body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
685 env = memberEnter.getMethodEnv(method, env);
686 env = attribStatToTree(method.body, env, copier.leafCopy);
687 } finally {
688 method.body = (JCBlock) tree;
689 }
690 } else {
691 JCBlock body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
692 env = attribStatToTree(body, env, copier.leafCopy);
693 }
694 return env;
695 }
696 default:
697 // System.err.println("DEFAULT: " + tree.getKind());
698 if (field != null && field.getInitializer() == tree) {
699 env = memberEnter.getInitEnv(field, env);
700 JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
701 env = attribExprToTree(expr, env, copier.leafCopy);
702 return env;
703 }
704 }
705 }
706 return (field != null) ? memberEnter.getInitEnv(field, env) : env;
707 }
709 private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
710 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
711 try {
712 return attr.attribStatToTree(stat, env, tree);
713 } finally {
714 log.useSource(prev);
715 }
716 }
718 private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
719 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
720 try {
721 return attr.attribExprToTree(expr, env, tree);
722 } finally {
723 log.useSource(prev);
724 }
725 }
727 /**
728 * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
729 **/
730 protected static class Copier extends TreeCopier<JCTree> {
731 JCTree leafCopy = null;
733 protected Copier(TreeMaker M) {
734 super(M);
735 }
737 @Override
738 public <T extends JCTree> T copy(T t, JCTree leaf) {
739 T t2 = super.copy(t, leaf);
740 if (t == leaf)
741 leafCopy = t2;
742 return t2;
743 }
744 }
746 protected Copier createCopier(TreeMaker maker) {
747 return new Copier(maker);
748 }
750 /**
751 * Gets the original type from the ErrorType object.
752 * @param errorType The errorType for which we want to get the original type.
753 * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
754 * noType (type.tag == NONE) is returned if there is no original type.
755 */
756 public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
757 if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
758 return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
759 }
761 return com.sun.tools.javac.code.Type.noType;
762 }
764 /**
765 * Prints a message of the specified kind at the location of the
766 * tree within the provided compilation unit
767 *
768 * @param kind the kind of message
769 * @param msg the message, or an empty string if none
770 * @param t the tree to use as a position hint
771 * @param root the compilation unit that contains tree
772 */
773 public void printMessage(Diagnostic.Kind kind, CharSequence msg,
774 com.sun.source.tree.Tree t,
775 com.sun.source.tree.CompilationUnitTree root) {
776 printMessage(kind, msg, ((JCTree) t).pos(), root);
777 }
779 public void printMessage(Diagnostic.Kind kind, CharSequence msg,
780 com.sun.source.doctree.DocTree t,
781 com.sun.source.doctree.DocCommentTree c,
782 com.sun.source.tree.CompilationUnitTree root) {
783 printMessage(kind, msg, ((DCTree) t).pos((DCDocComment) c), root);
784 }
786 private void printMessage(Diagnostic.Kind kind, CharSequence msg,
787 JCDiagnostic.DiagnosticPosition pos,
788 com.sun.source.tree.CompilationUnitTree root) {
789 JavaFileObject oldSource = null;
790 JavaFileObject newSource = null;
792 newSource = root.getSourceFile();
793 if (newSource == null) {
794 pos = null;
795 } else {
796 oldSource = log.useSource(newSource);
797 }
799 try {
800 switch (kind) {
801 case ERROR:
802 boolean prev = log.multipleErrors;
803 try {
804 log.error(pos, "proc.messager", msg.toString());
805 } finally {
806 log.multipleErrors = prev;
807 }
808 break;
810 case WARNING:
811 log.warning(pos, "proc.messager", msg.toString());
812 break;
814 case MANDATORY_WARNING:
815 log.mandatoryWarning(pos, "proc.messager", msg.toString());
816 break;
818 default:
819 log.note(pos, "proc.messager", msg.toString());
820 }
821 } finally {
822 if (oldSource != null)
823 log.useSource(oldSource);
824 }
825 }
827 @Override
828 public TypeMirror getLub(CatchTree tree) {
829 JCCatch ct = (JCCatch) tree;
830 JCVariableDecl v = ct.param;
831 if (v.type != null && v.type.getKind() == TypeKind.UNION) {
832 UnionClassType ut = (UnionClassType) v.type;
833 return ut.getLub();
834 } else {
835 return v.type;
836 }
837 }
838 }