Thu, 04 Jul 2013 10:35:33 +0100
8009924: some langtools tools do not accept -cp as an alias for -classpath
Reviewed-by: jjg
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.TypeTag;
73 import com.sun.tools.javac.code.Types.TypeRelation;
74 import com.sun.tools.javac.comp.Attr;
75 import com.sun.tools.javac.comp.AttrContext;
76 import com.sun.tools.javac.comp.Enter;
77 import com.sun.tools.javac.comp.Env;
78 import com.sun.tools.javac.comp.MemberEnter;
79 import com.sun.tools.javac.comp.Resolve;
80 import com.sun.tools.javac.model.JavacElements;
81 import com.sun.tools.javac.processing.JavacProcessingEnvironment;
82 import com.sun.tools.javac.tree.DCTree;
83 import com.sun.tools.javac.tree.DCTree.DCBlockTag;
84 import com.sun.tools.javac.tree.DCTree.DCDocComment;
85 import com.sun.tools.javac.tree.DCTree.DCEndPosTree;
86 import com.sun.tools.javac.tree.DCTree.DCErroneous;
87 import com.sun.tools.javac.tree.DCTree.DCIdentifier;
88 import com.sun.tools.javac.tree.DCTree.DCParam;
89 import com.sun.tools.javac.tree.DCTree.DCReference;
90 import com.sun.tools.javac.tree.DCTree.DCText;
91 import com.sun.tools.javac.tree.EndPosTable;
92 import com.sun.tools.javac.tree.JCTree;
93 import com.sun.tools.javac.tree.JCTree.*;
94 import com.sun.tools.javac.tree.TreeCopier;
95 import com.sun.tools.javac.tree.TreeInfo;
96 import com.sun.tools.javac.tree.TreeMaker;
97 import com.sun.tools.javac.util.Abort;
98 import com.sun.tools.javac.util.Assert;
99 import com.sun.tools.javac.util.Context;
100 import com.sun.tools.javac.util.JCDiagnostic;
101 import com.sun.tools.javac.util.List;
102 import com.sun.tools.javac.util.ListBuffer;
103 import com.sun.tools.javac.util.Log;
104 import com.sun.tools.javac.util.Name;
105 import com.sun.tools.javac.util.Names;
106 import com.sun.tools.javac.util.Pair;
107 import com.sun.tools.javac.util.Position;
108 import static com.sun.tools.javac.code.TypeTag.*;
110 /**
111 * Provides an implementation of Trees.
112 *
113 * <p><b>This is NOT part of any supported API.
114 * If you write code that depends on this, you do so at your own
115 * risk. This code and its internal interfaces are subject to change
116 * or deletion without notice.</b></p>
117 *
118 * @author Peter von der Ahé
119 */
120 public class JavacTrees extends DocTrees {
122 // in a world of a single context per compilation, these would all be final
123 private Resolve resolve;
124 private Enter enter;
125 private Log log;
126 private MemberEnter memberEnter;
127 private Attr attr;
128 private TreeMaker treeMaker;
129 private JavacElements elements;
130 private JavacTaskImpl javacTaskImpl;
131 private Names names;
132 private Types types;
134 // called reflectively from Trees.instance(CompilationTask task)
135 public static JavacTrees instance(JavaCompiler.CompilationTask task) {
136 if (!(task instanceof BasicJavacTask))
137 throw new IllegalArgumentException();
138 return instance(((BasicJavacTask)task).getContext());
139 }
141 // called reflectively from Trees.instance(ProcessingEnvironment env)
142 public static JavacTrees instance(ProcessingEnvironment env) {
143 if (!(env instanceof JavacProcessingEnvironment))
144 throw new IllegalArgumentException();
145 return instance(((JavacProcessingEnvironment)env).getContext());
146 }
148 public static JavacTrees instance(Context context) {
149 JavacTrees instance = context.get(JavacTrees.class);
150 if (instance == null)
151 instance = new JavacTrees(context);
152 return instance;
153 }
155 protected JavacTrees(Context context) {
156 context.put(JavacTrees.class, this);
157 init(context);
158 }
160 public void updateContext(Context context) {
161 init(context);
162 }
164 private void init(Context context) {
165 attr = Attr.instance(context);
166 enter = Enter.instance(context);
167 elements = JavacElements.instance(context);
168 log = Log.instance(context);
169 resolve = Resolve.instance(context);
170 treeMaker = TreeMaker.instance(context);
171 memberEnter = MemberEnter.instance(context);
172 names = Names.instance(context);
173 types = Types.instance(context);
175 JavacTask t = context.get(JavacTask.class);
176 if (t instanceof JavacTaskImpl)
177 javacTaskImpl = (JavacTaskImpl) t;
178 }
180 public DocSourcePositions getSourcePositions() {
181 return new DocSourcePositions() {
182 public long getStartPosition(CompilationUnitTree file, Tree tree) {
183 return TreeInfo.getStartPos((JCTree) tree);
184 }
186 public long getEndPosition(CompilationUnitTree file, Tree tree) {
187 EndPosTable endPosTable = ((JCCompilationUnit) file).endPositions;
188 return TreeInfo.getEndPos((JCTree) tree, endPosTable);
189 }
191 public long getStartPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree) {
192 return ((DCTree) tree).getSourcePosition((DCDocComment) comment);
193 }
194 @SuppressWarnings("fallthrough")
195 public long getEndPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree) {
196 DCDocComment dcComment = (DCDocComment) comment;
197 if (tree instanceof DCEndPosTree) {
198 int endPos = ((DCEndPosTree) tree).getEndPos(dcComment);
200 if (endPos != Position.NOPOS) {
201 return endPos;
202 }
203 }
204 int correction = 0;
205 switch (tree.getKind()) {
206 case TEXT:
207 DCText text = (DCText) tree;
209 return dcComment.comment.getSourcePos(text.pos + text.text.length());
210 case ERRONEOUS:
211 DCErroneous err = (DCErroneous) tree;
213 return dcComment.comment.getSourcePos(err.pos + err.body.length());
214 case IDENTIFIER:
215 DCIdentifier ident = (DCIdentifier) tree;
217 return dcComment.comment.getSourcePos(ident.pos + (ident.name != names.error ? ident.name.length() : 0));
218 case PARAM:
219 DCParam param = (DCParam) tree;
221 if (param.isTypeParameter && param.getDescription().isEmpty()) {
222 correction = 1;
223 }
224 case AUTHOR: case DEPRECATED: case RETURN: case SEE:
225 case SERIAL: case SERIAL_DATA: case SERIAL_FIELD: case SINCE:
226 case THROWS: case UNKNOWN_BLOCK_TAG: case VERSION: {
227 DocTree last = getLastChild(tree);
229 if (last != null) {
230 return getEndPosition(file, comment, last) + correction;
231 }
233 DCBlockTag block = (DCBlockTag) tree;
235 return dcComment.comment.getSourcePos(block.pos + block.getTagName().length() + 1);
236 }
237 default:
238 DocTree last = getLastChild(tree);
240 if (last != null) {
241 return getEndPosition(file, comment, last);
242 }
243 break;
244 }
246 return Position.NOPOS;
247 }
248 };
249 }
251 private DocTree getLastChild(DocTree tree) {
252 final DocTree[] last = new DocTree[] {null};
254 tree.accept(new DocTreeScanner<Void, Void>() {
255 @Override public Void scan(DocTree node, Void p) {
256 if (node != null) last[0] = node;
257 return null;
258 }
259 }, null);
261 return last[0];
262 }
264 public JCClassDecl getTree(TypeElement element) {
265 return (JCClassDecl) getTree((Element) element);
266 }
268 public JCMethodDecl getTree(ExecutableElement method) {
269 return (JCMethodDecl) getTree((Element) method);
270 }
272 public JCTree getTree(Element element) {
273 Symbol symbol = (Symbol) element;
274 TypeSymbol enclosing = symbol.enclClass();
275 Env<AttrContext> env = enter.getEnv(enclosing);
276 if (env == null)
277 return null;
278 JCClassDecl classNode = env.enclClass;
279 if (classNode != null) {
280 if (TreeInfo.symbolFor(classNode) == element)
281 return classNode;
282 for (JCTree node : classNode.getMembers())
283 if (TreeInfo.symbolFor(node) == element)
284 return node;
285 }
286 return null;
287 }
289 public JCTree getTree(Element e, AnnotationMirror a) {
290 return getTree(e, a, null);
291 }
293 public JCTree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
294 Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
295 if (treeTopLevel == null)
296 return null;
297 return treeTopLevel.fst;
298 }
300 public TreePath getPath(CompilationUnitTree unit, Tree node) {
301 return TreePath.getPath(unit, node);
302 }
304 public TreePath getPath(Element e) {
305 return getPath(e, null, null);
306 }
308 public TreePath getPath(Element e, AnnotationMirror a) {
309 return getPath(e, a, null);
310 }
312 public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
313 final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
314 if (treeTopLevel == null)
315 return null;
316 return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst);
317 }
319 public Symbol getElement(TreePath path) {
320 JCTree tree = (JCTree) path.getLeaf();
321 Symbol sym = TreeInfo.symbolFor(tree);
322 if (sym == null) {
323 if (TreeInfo.isDeclaration(tree)) {
324 for (TreePath p = path; p != null; p = p.getParentPath()) {
325 JCTree t = (JCTree) p.getLeaf();
326 if (t.hasTag(JCTree.Tag.CLASSDEF)) {
327 JCClassDecl ct = (JCClassDecl) t;
328 if (ct.sym != null) {
329 if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
330 attr.attribClass(ct.pos(), ct.sym);
331 sym = TreeInfo.symbolFor(tree);
332 }
333 break;
334 }
335 }
336 }
337 }
338 }
339 return sym;
340 }
342 @Override
343 public Element getElement(DocTreePath path) {
344 DocTree forTree = path.getLeaf();
345 if (forTree instanceof DCReference)
346 return attributeDocReference(path.getTreePath(), ((DCReference) forTree));
347 if (forTree instanceof DCIdentifier) {
348 if (path.getParentPath().getLeaf() instanceof DCParam) {
349 return attributeParamIdentifier(path.getTreePath(), (DCParam) path.getParentPath().getLeaf());
350 }
351 }
352 return null;
353 }
355 private Symbol attributeDocReference(TreePath path, DCReference ref) {
356 Env<AttrContext> env = getAttrContext(path);
358 Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
359 new Log.DeferredDiagnosticHandler(log);
360 try {
361 final ClassSymbol tsym;
362 final Name memberName;
363 if (ref.qualifierExpression == null) {
364 tsym = env.enclClass.sym;
365 memberName = ref.memberName;
366 } else {
367 // See if the qualifierExpression is a type or package name.
368 // javac does not provide the exact method required, so
369 // we first check if qualifierExpression identifies a type,
370 // and if not, then we check to see if it identifies a package.
371 Type t = attr.attribType(ref.qualifierExpression, env);
372 if (t.isErroneous()) {
373 if (ref.memberName == null) {
374 // Attr/Resolve assume packages exist and create symbols as needed
375 // so use getPackageElement to restrict search to existing packages
376 PackageSymbol pck = elements.getPackageElement(ref.qualifierExpression.toString());
377 if (pck != null) {
378 return pck;
379 } else if (ref.qualifierExpression.hasTag(JCTree.Tag.IDENT)) {
380 // fixup: allow "identifier" instead of "#identifier"
381 // for compatibility with javadoc
382 tsym = env.enclClass.sym;
383 memberName = ((JCIdent) ref.qualifierExpression).name;
384 } else
385 return null;
386 } else {
387 return null;
388 }
389 } else {
390 tsym = (ClassSymbol) t.tsym;
391 memberName = ref.memberName;
392 }
393 }
395 if (memberName == null)
396 return tsym;
398 final List<Type> paramTypes;
399 if (ref.paramTypes == null)
400 paramTypes = null;
401 else {
402 ListBuffer<Type> lb = new ListBuffer<Type>();
403 for (List<JCTree> l = ref.paramTypes; l.nonEmpty(); l = l.tail) {
404 JCTree tree = l.head;
405 Type t = attr.attribType(tree, env);
406 lb.add(t);
407 }
408 paramTypes = lb.toList();
409 }
411 Symbol msym = (memberName == tsym.name)
412 ? findConstructor(tsym, paramTypes)
413 : findMethod(tsym, memberName, paramTypes);
414 if (paramTypes != null) {
415 // explicit (possibly empty) arg list given, so cannot be a field
416 return msym;
417 }
419 VarSymbol vsym = (ref.paramTypes != null) ? null : findField(tsym, memberName);
420 // prefer a field over a method with no parameters
421 if (vsym != null &&
422 (msym == null ||
423 types.isSubtypeUnchecked(vsym.enclClass().asType(), msym.enclClass().asType()))) {
424 return vsym;
425 } else {
426 return msym;
427 }
428 } catch (Abort e) { // may be thrown by Check.completionError in case of bad class file
429 return null;
430 } finally {
431 log.popDiagnosticHandler(deferredDiagnosticHandler);
432 }
433 }
435 private Symbol attributeParamIdentifier(TreePath path, DCParam ptag) {
436 Symbol javadocSymbol = getElement(path);
437 if (javadocSymbol == null)
438 return null;
439 ElementKind kind = javadocSymbol.getKind();
440 List<? extends Symbol> params = List.nil();
441 if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
442 MethodSymbol ee = (MethodSymbol) javadocSymbol;
443 params = ptag.isTypeParameter()
444 ? ee.getTypeParameters()
445 : ee.getParameters();
446 } else if (kind.isClass() || kind.isInterface()) {
447 ClassSymbol te = (ClassSymbol) javadocSymbol;
448 params = te.getTypeParameters();
449 }
451 for (Symbol param : params) {
452 if (param.getSimpleName() == ptag.getName().getName()) {
453 return param;
454 }
455 }
456 return null;
457 }
459 /** @see com.sun.tools.javadoc.ClassDocImpl#findField */
460 private VarSymbol findField(ClassSymbol tsym, Name fieldName) {
461 return searchField(tsym, fieldName, new HashSet<ClassSymbol>());
462 }
464 /** @see com.sun.tools.javadoc.ClassDocImpl#searchField */
465 private VarSymbol searchField(ClassSymbol tsym, Name fieldName, Set<ClassSymbol> searched) {
466 if (searched.contains(tsym)) {
467 return null;
468 }
469 searched.add(tsym);
471 for (com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(fieldName);
472 e.scope != null; e = e.next()) {
473 if (e.sym.kind == Kinds.VAR) {
474 return (VarSymbol)e.sym;
475 }
476 }
478 //### If we found a VarSymbol above, but which did not pass
479 //### the modifier filter, we should return failure here!
481 ClassSymbol encl = tsym.owner.enclClass();
482 if (encl != null) {
483 VarSymbol vsym = searchField(encl, fieldName, searched);
484 if (vsym != null) {
485 return vsym;
486 }
487 }
489 // search superclass
490 Type superclass = tsym.getSuperclass();
491 if (superclass.tsym != null) {
492 VarSymbol vsym = searchField((ClassSymbol) superclass.tsym, fieldName, searched);
493 if (vsym != null) {
494 return vsym;
495 }
496 }
498 // search interfaces
499 List<Type> intfs = tsym.getInterfaces();
500 for (List<Type> l = intfs; l.nonEmpty(); l = l.tail) {
501 Type intf = l.head;
502 if (intf.isErroneous()) continue;
503 VarSymbol vsym = searchField((ClassSymbol) intf.tsym, fieldName, searched);
504 if (vsym != null) {
505 return vsym;
506 }
507 }
509 return null;
510 }
512 /** @see com.sun.tools.javadoc.ClassDocImpl#findConstructor */
513 MethodSymbol findConstructor(ClassSymbol tsym, List<Type> paramTypes) {
514 for (com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(names.init);
515 e.scope != null; e = e.next()) {
516 if (e.sym.kind == Kinds.MTH) {
517 if (hasParameterTypes((MethodSymbol) e.sym, paramTypes)) {
518 return (MethodSymbol) e.sym;
519 }
520 }
521 }
522 return null;
523 }
525 /** @see com.sun.tools.javadoc.ClassDocImpl#findMethod */
526 private MethodSymbol findMethod(ClassSymbol tsym, Name methodName, List<Type> paramTypes) {
527 return searchMethod(tsym, methodName, paramTypes, new HashSet<ClassSymbol>());
528 }
530 /** @see com.sun.tools.javadoc.ClassDocImpl#searchMethod */
531 private MethodSymbol searchMethod(ClassSymbol tsym, Name methodName,
532 List<Type> paramTypes, Set<ClassSymbol> searched) {
533 //### Note that this search is not necessarily what the compiler would do!
535 // do not match constructors
536 if (methodName == names.init)
537 return null;
539 if (searched.contains(tsym))
540 return null;
541 searched.add(tsym);
543 // search current class
544 com.sun.tools.javac.code.Scope.Entry e = tsym.members().lookup(methodName);
546 //### Using modifier filter here isn't really correct,
547 //### but emulates the old behavior. Instead, we should
548 //### apply the normal rules of visibility and inheritance.
550 if (paramTypes == null) {
551 // If no parameters specified, we are allowed to return
552 // any method with a matching name. In practice, the old
553 // code returned the first method, which is now the last!
554 // In order to provide textually identical results, we
555 // attempt to emulate the old behavior.
556 MethodSymbol lastFound = null;
557 for (; e.scope != null; e = e.next()) {
558 if (e.sym.kind == Kinds.MTH) {
559 if (e.sym.name == methodName) {
560 lastFound = (MethodSymbol)e.sym;
561 }
562 }
563 }
564 if (lastFound != null) {
565 return lastFound;
566 }
567 } else {
568 for (; e.scope != null; e = e.next()) {
569 if (e.sym != null &&
570 e.sym.kind == Kinds.MTH) {
571 if (hasParameterTypes((MethodSymbol) e.sym, paramTypes)) {
572 return (MethodSymbol) e.sym;
573 }
574 }
575 }
576 }
578 //### If we found a MethodSymbol above, but which did not pass
579 //### the modifier filter, we should return failure here!
581 // search superclass
582 Type superclass = tsym.getSuperclass();
583 if (superclass.tsym != null) {
584 MethodSymbol msym = searchMethod((ClassSymbol) superclass.tsym, methodName, paramTypes, searched);
585 if (msym != null) {
586 return msym;
587 }
588 }
590 // search interfaces
591 List<Type> intfs = tsym.getInterfaces();
592 for (List<Type> l = intfs; l.nonEmpty(); l = l.tail) {
593 Type intf = l.head;
594 if (intf.isErroneous()) continue;
595 MethodSymbol msym = searchMethod((ClassSymbol) intf.tsym, methodName, paramTypes, searched);
596 if (msym != null) {
597 return msym;
598 }
599 }
601 // search enclosing class
602 ClassSymbol encl = tsym.owner.enclClass();
603 if (encl != null) {
604 MethodSymbol msym = searchMethod(encl, methodName, paramTypes, searched);
605 if (msym != null) {
606 return msym;
607 }
608 }
610 return null;
611 }
613 /** @see com.sun.tools.javadoc.ClassDocImpl */
614 private boolean hasParameterTypes(MethodSymbol method, List<Type> paramTypes) {
615 if (paramTypes == null)
616 return true;
618 if (method.params().size() != paramTypes.size())
619 return false;
621 List<Type> methodParamTypes = types.erasureRecursive(method.asType()).getParameterTypes();
623 return (Type.isErroneous(paramTypes))
624 ? fuzzyMatch(paramTypes, methodParamTypes)
625 : types.isSameTypes(paramTypes, methodParamTypes);
626 }
628 boolean fuzzyMatch(List<Type> paramTypes, List<Type> methodParamTypes) {
629 List<Type> l1 = paramTypes;
630 List<Type> l2 = methodParamTypes;
631 while (l1.nonEmpty()) {
632 if (!fuzzyMatch(l1.head, l2.head))
633 return false;
634 l1 = l1.tail;
635 l2 = l2.tail;
636 }
637 return true;
638 }
640 boolean fuzzyMatch(Type paramType, Type methodParamType) {
641 Boolean b = fuzzyMatcher.visit(paramType, methodParamType);
642 return (b == Boolean.TRUE);
643 }
645 TypeRelation fuzzyMatcher = new TypeRelation() {
646 @Override
647 public Boolean visitType(Type t, Type s) {
648 if (t == s)
649 return true;
651 if (s.isPartial())
652 return visit(s, t);
654 switch (t.getTag()) {
655 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
656 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
657 return t.hasTag(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.hasTag(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.hasTag(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 }