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