Fri, 10 May 2013 15:15:50 +0200
8012929: Trees.getElement should work not only for declaration trees, but also for use-trees
Reviewed-by: jjg
Contributed-by: Dusan Balek <dbalek@netbeans.org>, Jan Lahoda <jlahoda@netbeans.org>
1 /*
2 * Copyright (c) 2005, 2013, 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.ElementKind;
37 import javax.lang.model.element.ExecutableElement;
38 import javax.lang.model.element.TypeElement;
39 import javax.lang.model.type.DeclaredType;
40 import javax.lang.model.type.TypeKind;
41 import javax.lang.model.type.TypeMirror;
42 import javax.tools.Diagnostic;
43 import javax.tools.JavaCompiler;
44 import javax.tools.JavaFileObject;
46 import com.sun.source.doctree.DocCommentTree;
47 import com.sun.source.doctree.DocTree;
48 import com.sun.source.tree.CatchTree;
49 import com.sun.source.tree.CompilationUnitTree;
50 import com.sun.source.tree.Scope;
51 import com.sun.source.tree.Tree;
52 import com.sun.source.util.DocSourcePositions;
53 import com.sun.source.util.DocTreePath;
54 import com.sun.source.util.DocTreeScanner;
55 import com.sun.source.util.DocTrees;
56 import com.sun.source.util.JavacTask;
57 import com.sun.source.util.TreePath;
58 import com.sun.tools.javac.code.Flags;
59 import com.sun.tools.javac.code.Kinds;
60 import com.sun.tools.javac.code.Symbol;
61 import com.sun.tools.javac.code.Symbol.ClassSymbol;
62 import com.sun.tools.javac.code.Symbol.MethodSymbol;
63 import com.sun.tools.javac.code.Symbol.PackageSymbol;
64 import com.sun.tools.javac.code.Symbol.TypeSymbol;
65 import com.sun.tools.javac.code.Symbol.VarSymbol;
66 import com.sun.tools.javac.code.Type;
67 import com.sun.tools.javac.code.Type.ArrayType;
68 import com.sun.tools.javac.code.Type.ClassType;
69 import com.sun.tools.javac.code.Type.ErrorType;
70 import com.sun.tools.javac.code.Type.UnionClassType;
71 import com.sun.tools.javac.code.Types;
72 import com.sun.tools.javac.code.Types.TypeRelation;
73 import com.sun.tools.javac.comp.Attr;
74 import com.sun.tools.javac.comp.AttrContext;
75 import com.sun.tools.javac.comp.Enter;
76 import com.sun.tools.javac.comp.Env;
77 import com.sun.tools.javac.comp.MemberEnter;
78 import com.sun.tools.javac.comp.Resolve;
79 import com.sun.tools.javac.model.JavacElements;
80 import com.sun.tools.javac.processing.JavacProcessingEnvironment;
81 import com.sun.tools.javac.tree.DCTree;
82 import com.sun.tools.javac.tree.DCTree.DCBlockTag;
83 import com.sun.tools.javac.tree.DCTree.DCDocComment;
84 import com.sun.tools.javac.tree.DCTree.DCEndPosTree;
85 import com.sun.tools.javac.tree.DCTree.DCErroneous;
86 import com.sun.tools.javac.tree.DCTree.DCIdentifier;
87 import com.sun.tools.javac.tree.DCTree.DCParam;
88 import com.sun.tools.javac.tree.DCTree.DCReference;
89 import com.sun.tools.javac.tree.DCTree.DCText;
90 import com.sun.tools.javac.tree.EndPosTable;
91 import com.sun.tools.javac.tree.JCTree;
92 import com.sun.tools.javac.tree.JCTree.*;
93 import com.sun.tools.javac.tree.TreeCopier;
94 import com.sun.tools.javac.tree.TreeInfo;
95 import com.sun.tools.javac.tree.TreeMaker;
96 import com.sun.tools.javac.util.Abort;
97 import com.sun.tools.javac.util.Assert;
98 import com.sun.tools.javac.util.Context;
99 import com.sun.tools.javac.util.JCDiagnostic;
100 import com.sun.tools.javac.util.List;
101 import com.sun.tools.javac.util.ListBuffer;
102 import com.sun.tools.javac.util.Log;
103 import com.sun.tools.javac.util.Name;
104 import com.sun.tools.javac.util.Names;
105 import com.sun.tools.javac.util.Pair;
106 import com.sun.tools.javac.util.Position;
107 import static com.sun.tools.javac.code.TypeTag.*;
109 /**
110 * Provides an implementation of Trees.
111 *
112 * <p><b>This is NOT part of any supported API.
113 * If you write code that depends on this, you do so at your own
114 * risk. This code and its internal interfaces are subject to change
115 * or deletion without notice.</b></p>
116 *
117 * @author Peter von der Ahé
118 */
119 public class JavacTrees extends DocTrees {
121 // in a world of a single context per compilation, these would all be final
122 private Resolve resolve;
123 private Enter enter;
124 private Log log;
125 private MemberEnter memberEnter;
126 private Attr attr;
127 private TreeMaker treeMaker;
128 private JavacElements elements;
129 private JavacTaskImpl javacTaskImpl;
130 private Names names;
131 private Types types;
133 // called reflectively from Trees.instance(CompilationTask task)
134 public static JavacTrees instance(JavaCompiler.CompilationTask task) {
135 if (!(task instanceof BasicJavacTask))
136 throw new IllegalArgumentException();
137 return instance(((BasicJavacTask)task).getContext());
138 }
140 // called reflectively from Trees.instance(ProcessingEnvironment env)
141 public static JavacTrees instance(ProcessingEnvironment env) {
142 if (!(env instanceof JavacProcessingEnvironment))
143 throw new IllegalArgumentException();
144 return instance(((JavacProcessingEnvironment)env).getContext());
145 }
147 public static JavacTrees instance(Context context) {
148 JavacTrees instance = context.get(JavacTrees.class);
149 if (instance == null)
150 instance = new JavacTrees(context);
151 return instance;
152 }
154 protected JavacTrees(Context context) {
155 context.put(JavacTrees.class, this);
156 init(context);
157 }
159 public void updateContext(Context context) {
160 init(context);
161 }
163 private void init(Context context) {
164 attr = Attr.instance(context);
165 enter = Enter.instance(context);
166 elements = JavacElements.instance(context);
167 log = Log.instance(context);
168 resolve = Resolve.instance(context);
169 treeMaker = TreeMaker.instance(context);
170 memberEnter = MemberEnter.instance(context);
171 names = Names.instance(context);
172 types = Types.instance(context);
174 JavacTask t = context.get(JavacTask.class);
175 if (t instanceof JavacTaskImpl)
176 javacTaskImpl = (JavacTaskImpl) t;
177 }
179 public DocSourcePositions getSourcePositions() {
180 return new DocSourcePositions() {
181 public long getStartPosition(CompilationUnitTree file, Tree tree) {
182 return TreeInfo.getStartPos((JCTree) tree);
183 }
185 public long getEndPosition(CompilationUnitTree file, Tree tree) {
186 EndPosTable endPosTable = ((JCCompilationUnit) file).endPositions;
187 return TreeInfo.getEndPos((JCTree) tree, endPosTable);
188 }
190 public long getStartPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree) {
191 return ((DCTree) tree).getSourcePosition((DCDocComment) comment);
192 }
193 @SuppressWarnings("fallthrough")
194 public long getEndPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree) {
195 DCDocComment dcComment = (DCDocComment) comment;
196 if (tree instanceof DCEndPosTree) {
197 int endPos = ((DCEndPosTree) tree).getEndPos(dcComment);
199 if (endPos != Position.NOPOS) {
200 return endPos;
201 }
202 }
203 int correction = 0;
204 switch (tree.getKind()) {
205 case TEXT:
206 DCText text = (DCText) tree;
208 return dcComment.comment.getSourcePos(text.pos + text.text.length());
209 case ERRONEOUS:
210 DCErroneous err = (DCErroneous) tree;
212 return dcComment.comment.getSourcePos(err.pos + err.body.length());
213 case IDENTIFIER:
214 DCIdentifier ident = (DCIdentifier) tree;
216 return dcComment.comment.getSourcePos(ident.pos + (ident.name != names.error ? ident.name.length() : 0));
217 case PARAM:
218 DCParam param = (DCParam) tree;
220 if (param.isTypeParameter && param.getDescription().isEmpty()) {
221 correction = 1;
222 }
223 case AUTHOR: case DEPRECATED: case RETURN: case SEE:
224 case SERIAL: case SERIAL_DATA: case SERIAL_FIELD: case SINCE:
225 case THROWS: case UNKNOWN_BLOCK_TAG: case VERSION: {
226 DocTree last = getLastChild(tree);
228 if (last != null) {
229 return getEndPosition(file, comment, last) + correction;
230 }
232 DCBlockTag block = (DCBlockTag) tree;
234 return dcComment.comment.getSourcePos(block.pos + block.getTagName().length() + 1);
235 }
236 default:
237 DocTree last = getLastChild(tree);
239 if (last != null) {
240 return getEndPosition(file, comment, last);
241 }
242 break;
243 }
245 return Position.NOPOS;
246 }
247 };
248 }
250 private DocTree getLastChild(DocTree tree) {
251 final DocTree[] last = new DocTree[] {null};
253 tree.accept(new DocTreeScanner<Void, Void>() {
254 @Override public Void scan(DocTree node, Void p) {
255 if (node != null) last[0] = node;
256 return null;
257 }
258 }, null);
260 return last[0];
261 }
263 public JCClassDecl getTree(TypeElement element) {
264 return (JCClassDecl) getTree((Element) element);
265 }
267 public JCMethodDecl getTree(ExecutableElement method) {
268 return (JCMethodDecl) getTree((Element) method);
269 }
271 public JCTree getTree(Element element) {
272 Symbol symbol = (Symbol) element;
273 TypeSymbol enclosing = symbol.enclClass();
274 Env<AttrContext> env = enter.getEnv(enclosing);
275 if (env == null)
276 return null;
277 JCClassDecl classNode = env.enclClass;
278 if (classNode != null) {
279 if (TreeInfo.symbolFor(classNode) == element)
280 return classNode;
281 for (JCTree node : classNode.getMembers())
282 if (TreeInfo.symbolFor(node) == element)
283 return node;
284 }
285 return null;
286 }
288 public JCTree getTree(Element e, AnnotationMirror a) {
289 return getTree(e, a, null);
290 }
292 public JCTree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
293 Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
294 if (treeTopLevel == null)
295 return null;
296 return treeTopLevel.fst;
297 }
299 public TreePath getPath(CompilationUnitTree unit, Tree node) {
300 return TreePath.getPath(unit, node);
301 }
303 public TreePath getPath(Element e) {
304 return getPath(e, null, null);
305 }
307 public TreePath getPath(Element e, AnnotationMirror a) {
308 return getPath(e, a, null);
309 }
311 public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
312 final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
313 if (treeTopLevel == null)
314 return null;
315 return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst);
316 }
318 public Symbol getElement(TreePath path) {
319 JCTree tree = (JCTree) path.getLeaf();
320 Symbol sym = TreeInfo.symbolFor(tree);
321 if (sym == null) {
322 if (TreeInfo.isDeclaration(tree)) {
323 for (TreePath p = path; p != null; p = p.getParentPath()) {
324 JCTree t = (JCTree) p.getLeaf();
325 if (t.hasTag(JCTree.Tag.CLASSDEF)) {
326 JCClassDecl ct = (JCClassDecl) t;
327 if (ct.sym != null) {
328 if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
329 attr.attribClass(ct.pos(), ct.sym);
330 sym = TreeInfo.symbolFor(tree);
331 }
332 break;
333 }
334 }
335 }
336 }
337 }
338 return sym;
339 }
341 @Override
342 public Element getElement(DocTreePath path) {
343 DocTree forTree = path.getLeaf();
344 if (forTree instanceof DCReference)
345 return attributeDocReference(path.getTreePath(), ((DCReference) forTree));
346 if (forTree instanceof DCIdentifier) {
347 if (path.getParentPath().getLeaf() instanceof DCParam) {
348 return attributeParamIdentifier(path.getTreePath(), (DCParam) path.getParentPath().getLeaf());
349 }
350 }
351 return null;
352 }
354 private Symbol attributeDocReference(TreePath path, DCReference ref) {
355 Env<AttrContext> env = getAttrContext(path);
357 Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
358 new Log.DeferredDiagnosticHandler(log);
359 try {
360 final ClassSymbol tsym;
361 final Name memberName;
362 if (ref.qualifierExpression == null) {
363 tsym = env.enclClass.sym;
364 memberName = ref.memberName;
365 } else {
366 // See if the qualifierExpression is a type or package name.
367 // javac does not provide the exact method required, so
368 // we first check if qualifierExpression identifies a type,
369 // and if not, then we check to see if it identifies a package.
370 Type t = attr.attribType(ref.qualifierExpression, env);
371 if (t.isErroneous()) {
372 if (ref.memberName == null) {
373 // Attr/Resolve assume packages exist and create symbols as needed
374 // so use getPackageElement to restrict search to existing packages
375 PackageSymbol pck = elements.getPackageElement(ref.qualifierExpression.toString());
376 if (pck != null) {
377 return pck;
378 } else if (ref.qualifierExpression.hasTag(JCTree.Tag.IDENT)) {
379 // fixup: allow "identifier" instead of "#identifier"
380 // for compatibility with javadoc
381 tsym = env.enclClass.sym;
382 memberName = ((JCIdent) ref.qualifierExpression).name;
383 } else
384 return null;
385 } else {
386 return null;
387 }
388 } else {
389 tsym = (ClassSymbol) t.tsym;
390 memberName = ref.memberName;
391 }
392 }
394 if (memberName == null)
395 return tsym;
397 final List<Type> paramTypes;
398 if (ref.paramTypes == null)
399 paramTypes = null;
400 else {
401 ListBuffer<Type> lb = new ListBuffer<Type>();
402 for (List<JCTree> l = ref.paramTypes; l.nonEmpty(); l = l.tail) {
403 JCTree tree = l.head;
404 Type t = attr.attribType(tree, env);
405 lb.add(t);
406 }
407 paramTypes = lb.toList();
408 }
410 Symbol msym = (memberName == tsym.name)
411 ? findConstructor(tsym, paramTypes)
412 : findMethod(tsym, memberName, paramTypes);
413 if (paramTypes != null) {
414 // explicit (possibly empty) arg list given, so cannot be a field
415 return msym;
416 }
418 VarSymbol vsym = (ref.paramTypes != null) ? null : findField(tsym, memberName);
419 // prefer a field over a method with no parameters
420 if (vsym != null &&
421 (msym == null ||
422 types.isSubtypeUnchecked(vsym.enclClass().asType(), msym.enclClass().asType()))) {
423 return vsym;
424 } else {
425 return msym;
426 }
427 } catch (Abort e) { // may be thrown by Check.completionError in case of bad class file
428 return null;
429 } finally {
430 log.popDiagnosticHandler(deferredDiagnosticHandler);
431 }
432 }
434 private Symbol attributeParamIdentifier(TreePath path, DCParam ptag) {
435 Symbol javadocSymbol = getElement(path);
436 if (javadocSymbol == null)
437 return null;
438 ElementKind kind = javadocSymbol.getKind();
439 List<? extends Symbol> params = List.nil();
440 if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
441 MethodSymbol ee = (MethodSymbol) javadocSymbol;
442 params = ptag.isTypeParameter()
443 ? ee.getTypeParameters()
444 : ee.getParameters();
445 } else if (kind.isClass() || kind.isInterface()) {
446 ClassSymbol te = (ClassSymbol) javadocSymbol;
447 params = te.getTypeParameters();
448 }
450 for (Symbol param : params) {
451 if (param.getSimpleName() == ptag.getName().getName()) {
452 return param;
453 }
454 }
455 return null;
456 }
458 /** @see com.sun.tools.javadoc.ClassDocImpl#findField */
459 private VarSymbol findField(ClassSymbol tsym, Name fieldName) {
460 return searchField(tsym, fieldName, new HashSet<ClassSymbol>());
461 }
463 /** @see com.sun.tools.javadoc.ClassDocImpl#searchField */
464 private VarSymbol searchField(ClassSymbol tsym, Name fieldName, Set<ClassSymbol> searched) {
465 if (searched.contains(tsym)) {
466 return null;
467 }
468 searched.add(tsym);
470 for (com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(fieldName);
471 e.scope != null; e = e.next()) {
472 if (e.sym.kind == Kinds.VAR) {
473 return (VarSymbol)e.sym;
474 }
475 }
477 //### If we found a VarSymbol above, but which did not pass
478 //### the modifier filter, we should return failure here!
480 ClassSymbol encl = tsym.owner.enclClass();
481 if (encl != null) {
482 VarSymbol vsym = searchField(encl, fieldName, searched);
483 if (vsym != null) {
484 return vsym;
485 }
486 }
488 // search superclass
489 Type superclass = tsym.getSuperclass();
490 if (superclass.tsym != null) {
491 VarSymbol vsym = searchField((ClassSymbol) superclass.tsym, fieldName, searched);
492 if (vsym != null) {
493 return vsym;
494 }
495 }
497 // search interfaces
498 List<Type> intfs = tsym.getInterfaces();
499 for (List<Type> l = intfs; l.nonEmpty(); l = l.tail) {
500 Type intf = l.head;
501 if (intf.isErroneous()) continue;
502 VarSymbol vsym = searchField((ClassSymbol) intf.tsym, fieldName, searched);
503 if (vsym != null) {
504 return vsym;
505 }
506 }
508 return null;
509 }
511 /** @see com.sun.tools.javadoc.ClassDocImpl#findConstructor */
512 MethodSymbol findConstructor(ClassSymbol tsym, List<Type> paramTypes) {
513 for (com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(names.init);
514 e.scope != null; e = e.next()) {
515 if (e.sym.kind == Kinds.MTH) {
516 if (hasParameterTypes((MethodSymbol) e.sym, paramTypes)) {
517 return (MethodSymbol) e.sym;
518 }
519 }
520 }
521 return null;
522 }
524 /** @see com.sun.tools.javadoc.ClassDocImpl#findMethod */
525 private MethodSymbol findMethod(ClassSymbol tsym, Name methodName, List<Type> paramTypes) {
526 return searchMethod(tsym, methodName, paramTypes, new HashSet<ClassSymbol>());
527 }
529 /** @see com.sun.tools.javadoc.ClassDocImpl#searchMethod */
530 private MethodSymbol searchMethod(ClassSymbol tsym, Name methodName,
531 List<Type> paramTypes, Set<ClassSymbol> searched) {
532 //### Note that this search is not necessarily what the compiler would do!
534 // do not match constructors
535 if (methodName == names.init)
536 return null;
538 if (searched.contains(tsym))
539 return null;
540 searched.add(tsym);
542 // search current class
543 com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(methodName);
545 //### Using modifier filter here isn't really correct,
546 //### but emulates the old behavior. Instead, we should
547 //### apply the normal rules of visibility and inheritance.
549 if (paramTypes == null) {
550 // If no parameters specified, we are allowed to return
551 // any method with a matching name. In practice, the old
552 // code returned the first method, which is now the last!
553 // In order to provide textually identical results, we
554 // attempt to emulate the old behavior.
555 MethodSymbol lastFound = null;
556 for (; e.scope != null; e = e.next()) {
557 if (e.sym.kind == Kinds.MTH) {
558 if (e.sym.name == methodName) {
559 lastFound = (MethodSymbol)e.sym;
560 }
561 }
562 }
563 if (lastFound != null) {
564 return lastFound;
565 }
566 } else {
567 for (; e.scope != null; e = e.next()) {
568 if (e.sym != null &&
569 e.sym.kind == Kinds.MTH) {
570 if (hasParameterTypes((MethodSymbol) e.sym, paramTypes)) {
571 return (MethodSymbol) e.sym;
572 }
573 }
574 }
575 }
577 //### If we found a MethodSymbol above, but which did not pass
578 //### the modifier filter, we should return failure here!
580 // search superclass
581 Type superclass = tsym.getSuperclass();
582 if (superclass.tsym != null) {
583 MethodSymbol msym = searchMethod((ClassSymbol) superclass.tsym, methodName, paramTypes, searched);
584 if (msym != null) {
585 return msym;
586 }
587 }
589 // search interfaces
590 List<Type> intfs = tsym.getInterfaces();
591 for (List<Type> l = intfs; l.nonEmpty(); l = l.tail) {
592 Type intf = l.head;
593 if (intf.isErroneous()) continue;
594 MethodSymbol msym = searchMethod((ClassSymbol) intf.tsym, methodName, paramTypes, searched);
595 if (msym != null) {
596 return msym;
597 }
598 }
600 // search enclosing class
601 ClassSymbol encl = tsym.owner.enclClass();
602 if (encl != null) {
603 MethodSymbol msym = searchMethod(encl, methodName, paramTypes, searched);
604 if (msym != null) {
605 return msym;
606 }
607 }
609 return null;
610 }
612 /** @see com.sun.tools.javadoc.ClassDocImpl */
613 private boolean hasParameterTypes(MethodSymbol method, List<Type> paramTypes) {
614 if (paramTypes == null)
615 return true;
617 if (method.params().size() != paramTypes.size())
618 return false;
620 List<Type> methodParamTypes = types.erasureRecursive(method.asType()).getParameterTypes();
622 return (Type.isErroneous(paramTypes))
623 ? fuzzyMatch(paramTypes, methodParamTypes)
624 : types.isSameTypes(paramTypes, methodParamTypes);
625 }
627 boolean fuzzyMatch(List<Type> paramTypes, List<Type> methodParamTypes) {
628 List<Type> l1 = paramTypes;
629 List<Type> l2 = methodParamTypes;
630 while (l1.nonEmpty()) {
631 if (!fuzzyMatch(l1.head, l2.head))
632 return false;
633 l1 = l1.tail;
634 l2 = l2.tail;
635 }
636 return true;
637 }
639 boolean fuzzyMatch(Type paramType, Type methodParamType) {
640 Boolean b = fuzzyMatcher.visit(paramType, methodParamType);
641 return (b == Boolean.TRUE);
642 }
644 TypeRelation fuzzyMatcher = new TypeRelation() {
645 @Override
646 public Boolean visitType(Type t, Type s) {
647 if (t == s)
648 return true;
650 if (s.isPartial())
651 return visit(s, t);
653 switch (t.getTag()) {
654 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
655 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
656 return t.getTag() == s.getTag();
658 default:
659 throw new AssertionError("fuzzyMatcher " + t.getTag());
660 }
661 }
663 @Override
664 public Boolean visitArrayType(ArrayType t, Type s) {
665 if (t == s)
666 return true;
668 if (s.isPartial())
669 return visit(s, t);
671 return s.getTag() == ARRAY
672 && visit(t.elemtype, types.elemtype(s));
673 }
675 @Override
676 public Boolean visitClassType(ClassType t, Type s) {
677 if (t == s)
678 return true;
680 if (s.isPartial())
681 return visit(s, t);
683 return t.tsym == s.tsym;
684 }
686 @Override
687 public Boolean visitErrorType(ErrorType t, Type s) {
688 return s.getTag() == CLASS
689 && t.tsym.name == ((ClassType) s).tsym.name;
690 }
691 };
693 public TypeMirror getTypeMirror(TreePath path) {
694 Tree t = path.getLeaf();
695 return ((JCTree)t).type;
696 }
698 public JavacScope getScope(TreePath path) {
699 return new JavacScope(getAttrContext(path));
700 }
702 public String getDocComment(TreePath path) {
703 CompilationUnitTree t = path.getCompilationUnit();
704 Tree leaf = path.getLeaf();
705 if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
706 JCCompilationUnit cu = (JCCompilationUnit) t;
707 if (cu.docComments != null) {
708 return cu.docComments.getCommentText((JCTree) leaf);
709 }
710 }
711 return null;
712 }
714 public DocCommentTree getDocCommentTree(TreePath path) {
715 CompilationUnitTree t = path.getCompilationUnit();
716 Tree leaf = path.getLeaf();
717 if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
718 JCCompilationUnit cu = (JCCompilationUnit) t;
719 if (cu.docComments != null) {
720 return cu.docComments.getCommentTree((JCTree) leaf);
721 }
722 }
723 return null;
724 }
726 public boolean isAccessible(Scope scope, TypeElement type) {
727 if (scope instanceof JavacScope && type instanceof ClassSymbol) {
728 Env<AttrContext> env = ((JavacScope) scope).env;
729 return resolve.isAccessible(env, (ClassSymbol)type, true);
730 } else
731 return false;
732 }
734 public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
735 if (scope instanceof JavacScope
736 && member instanceof Symbol
737 && type instanceof com.sun.tools.javac.code.Type) {
738 Env<AttrContext> env = ((JavacScope) scope).env;
739 return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member, true);
740 } else
741 return false;
742 }
744 private Env<AttrContext> getAttrContext(TreePath path) {
745 if (!(path.getLeaf() instanceof JCTree)) // implicit null-check
746 throw new IllegalArgumentException();
748 // if we're being invoked from a Tree API client via parse/enter/analyze,
749 // we need to make sure all the classes have been entered;
750 // if we're being invoked from JSR 199 or JSR 269, then the classes
751 // will already have been entered.
752 if (javacTaskImpl != null) {
753 try {
754 javacTaskImpl.enter(null);
755 } catch (IOException e) {
756 throw new Error("unexpected error while entering symbols: " + e);
757 }
758 }
761 JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
762 Copier copier = createCopier(treeMaker.forToplevel(unit));
764 Env<AttrContext> env = null;
765 JCMethodDecl method = null;
766 JCVariableDecl field = null;
768 List<Tree> l = List.nil();
769 TreePath p = path;
770 while (p != null) {
771 l = l.prepend(p.getLeaf());
772 p = p.getParentPath();
773 }
775 for ( ; l.nonEmpty(); l = l.tail) {
776 Tree tree = l.head;
777 switch (tree.getKind()) {
778 case COMPILATION_UNIT:
779 // System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
780 env = enter.getTopLevelEnv((JCCompilationUnit)tree);
781 break;
782 case ANNOTATION_TYPE:
783 case CLASS:
784 case ENUM:
785 case INTERFACE:
786 // System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
787 env = enter.getClassEnv(((JCClassDecl)tree).sym);
788 break;
789 case METHOD:
790 // System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
791 method = (JCMethodDecl)tree;
792 break;
793 case VARIABLE:
794 // System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
795 field = (JCVariableDecl)tree;
796 break;
797 case BLOCK: {
798 // System.err.println("BLOCK: ");
799 if (method != null) {
800 try {
801 Assert.check(method.body == tree);
802 method.body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
803 env = memberEnter.getMethodEnv(method, env);
804 env = attribStatToTree(method.body, env, copier.leafCopy);
805 } finally {
806 method.body = (JCBlock) tree;
807 }
808 } else {
809 JCBlock body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
810 env = attribStatToTree(body, env, copier.leafCopy);
811 }
812 return env;
813 }
814 default:
815 // System.err.println("DEFAULT: " + tree.getKind());
816 if (field != null && field.getInitializer() == tree) {
817 env = memberEnter.getInitEnv(field, env);
818 JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
819 env = attribExprToTree(expr, env, copier.leafCopy);
820 return env;
821 }
822 }
823 }
824 return (field != null) ? memberEnter.getInitEnv(field, env) : env;
825 }
827 private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
828 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
829 try {
830 return attr.attribStatToTree(stat, env, tree);
831 } finally {
832 log.useSource(prev);
833 }
834 }
836 private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
837 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
838 try {
839 return attr.attribExprToTree(expr, env, tree);
840 } finally {
841 log.useSource(prev);
842 }
843 }
845 /**
846 * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
847 **/
848 protected static class Copier extends TreeCopier<JCTree> {
849 JCTree leafCopy = null;
851 protected Copier(TreeMaker M) {
852 super(M);
853 }
855 @Override
856 public <T extends JCTree> T copy(T t, JCTree leaf) {
857 T t2 = super.copy(t, leaf);
858 if (t == leaf)
859 leafCopy = t2;
860 return t2;
861 }
862 }
864 protected Copier createCopier(TreeMaker maker) {
865 return new Copier(maker);
866 }
868 /**
869 * Gets the original type from the ErrorType object.
870 * @param errorType The errorType for which we want to get the original type.
871 * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
872 * noType (type.tag == NONE) is returned if there is no original type.
873 */
874 public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
875 if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
876 return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
877 }
879 return com.sun.tools.javac.code.Type.noType;
880 }
882 /**
883 * Prints a message of the specified kind at the location of the
884 * tree within the provided compilation unit
885 *
886 * @param kind the kind of message
887 * @param msg the message, or an empty string if none
888 * @param t the tree to use as a position hint
889 * @param root the compilation unit that contains tree
890 */
891 public void printMessage(Diagnostic.Kind kind, CharSequence msg,
892 com.sun.source.tree.Tree t,
893 com.sun.source.tree.CompilationUnitTree root) {
894 printMessage(kind, msg, ((JCTree) t).pos(), root);
895 }
897 public void printMessage(Diagnostic.Kind kind, CharSequence msg,
898 com.sun.source.doctree.DocTree t,
899 com.sun.source.doctree.DocCommentTree c,
900 com.sun.source.tree.CompilationUnitTree root) {
901 printMessage(kind, msg, ((DCTree) t).pos((DCDocComment) c), root);
902 }
904 private void printMessage(Diagnostic.Kind kind, CharSequence msg,
905 JCDiagnostic.DiagnosticPosition pos,
906 com.sun.source.tree.CompilationUnitTree root) {
907 JavaFileObject oldSource = null;
908 JavaFileObject newSource = null;
910 newSource = root.getSourceFile();
911 if (newSource == null) {
912 pos = null;
913 } else {
914 oldSource = log.useSource(newSource);
915 }
917 try {
918 switch (kind) {
919 case ERROR:
920 boolean prev = log.multipleErrors;
921 try {
922 log.error(pos, "proc.messager", msg.toString());
923 } finally {
924 log.multipleErrors = prev;
925 }
926 break;
928 case WARNING:
929 log.warning(pos, "proc.messager", msg.toString());
930 break;
932 case MANDATORY_WARNING:
933 log.mandatoryWarning(pos, "proc.messager", msg.toString());
934 break;
936 default:
937 log.note(pos, "proc.messager", msg.toString());
938 }
939 } finally {
940 if (oldSource != null)
941 log.useSource(oldSource);
942 }
943 }
945 @Override
946 public TypeMirror getLub(CatchTree tree) {
947 JCCatch ct = (JCCatch) tree;
948 JCVariableDecl v = ct.param;
949 if (v.type != null && v.type.getKind() == TypeKind.UNION) {
950 UnionClassType ut = (UnionClassType) v.type;
951 return ut.getLub();
952 } else {
953 return v.type;
954 }
955 }
956 }