JavacTrees.java revision 3969:7729c633b9f1
1/*
2 * Copyright (c) 2005, 2017, 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 */
25
26package com.sun.tools.javac.api;
27
28import java.io.FileNotFoundException;
29import java.io.IOException;
30import java.text.BreakIterator;
31import java.util.HashMap;
32import java.util.HashSet;
33import java.util.Map;
34import java.util.Set;
35import java.util.regex.Matcher;
36import java.util.regex.Pattern;
37
38import javax.annotation.processing.ProcessingEnvironment;
39import javax.lang.model.element.AnnotationMirror;
40import javax.lang.model.element.AnnotationValue;
41import javax.lang.model.element.Element;
42import javax.lang.model.element.ElementKind;
43import javax.lang.model.element.ExecutableElement;
44import javax.lang.model.element.Modifier;
45import javax.lang.model.element.NestingKind;
46import javax.lang.model.element.PackageElement;
47import javax.lang.model.element.TypeElement;
48import javax.lang.model.type.DeclaredType;
49import javax.lang.model.type.TypeKind;
50import javax.lang.model.type.TypeMirror;
51import javax.tools.Diagnostic;
52import javax.tools.FileObject;
53import javax.tools.ForwardingFileObject;
54import javax.tools.JavaCompiler;
55import javax.tools.JavaFileManager;
56import javax.tools.JavaFileObject;
57import javax.tools.JavaFileObject.Kind;
58import javax.tools.StandardLocation;
59
60import com.sun.source.doctree.DocCommentTree;
61import com.sun.source.doctree.DocTree;
62import com.sun.source.tree.CatchTree;
63import com.sun.source.tree.CompilationUnitTree;
64import com.sun.source.tree.Scope;
65import com.sun.source.tree.Tree;
66import com.sun.source.util.DocSourcePositions;
67import com.sun.source.util.DocTreePath;
68import com.sun.source.util.DocTreeScanner;
69import com.sun.source.util.DocTrees;
70import com.sun.source.util.JavacTask;
71import com.sun.source.util.TreePath;
72import com.sun.tools.javac.code.Flags;
73import com.sun.tools.javac.code.Scope.NamedImportScope;
74import com.sun.tools.javac.code.Scope.StarImportScope;
75import com.sun.tools.javac.code.Scope.WriteableScope;
76import com.sun.tools.javac.code.Symbol;
77import com.sun.tools.javac.code.Symbol.ClassSymbol;
78import com.sun.tools.javac.code.Symbol.MethodSymbol;
79import com.sun.tools.javac.code.Symbol.ModuleSymbol;
80import com.sun.tools.javac.code.Symbol.PackageSymbol;
81import com.sun.tools.javac.code.Symbol.TypeSymbol;
82import com.sun.tools.javac.code.Symbol.VarSymbol;
83import com.sun.tools.javac.code.Symtab;
84import com.sun.tools.javac.code.Type;
85import com.sun.tools.javac.code.Type.ArrayType;
86import com.sun.tools.javac.code.Type.ClassType;
87import com.sun.tools.javac.code.Type.ErrorType;
88import com.sun.tools.javac.code.Type.UnionClassType;
89import com.sun.tools.javac.code.Types;
90import com.sun.tools.javac.code.Types.TypeRelation;
91import com.sun.tools.javac.comp.Attr;
92import com.sun.tools.javac.comp.AttrContext;
93import com.sun.tools.javac.comp.Enter;
94import com.sun.tools.javac.comp.Env;
95import com.sun.tools.javac.comp.MemberEnter;
96import com.sun.tools.javac.comp.Modules;
97import com.sun.tools.javac.comp.Resolve;
98import com.sun.tools.javac.file.BaseFileManager;
99import com.sun.tools.javac.model.JavacElements;
100import com.sun.tools.javac.parser.DocCommentParser;
101import com.sun.tools.javac.parser.ParserFactory;
102import com.sun.tools.javac.parser.Tokens.Comment;
103import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle;
104import com.sun.tools.javac.processing.JavacProcessingEnvironment;
105import com.sun.tools.javac.tree.DCTree;
106import com.sun.tools.javac.tree.DCTree.DCBlockTag;
107import com.sun.tools.javac.tree.DCTree.DCDocComment;
108import com.sun.tools.javac.tree.DCTree.DCEndPosTree;
109import com.sun.tools.javac.tree.DCTree.DCErroneous;
110import com.sun.tools.javac.tree.DCTree.DCIdentifier;
111import com.sun.tools.javac.tree.DCTree.DCParam;
112import com.sun.tools.javac.tree.DCTree.DCReference;
113import com.sun.tools.javac.tree.DCTree.DCText;
114import com.sun.tools.javac.tree.DocCommentTable;
115import com.sun.tools.javac.tree.DocTreeMaker;
116import com.sun.tools.javac.tree.EndPosTable;
117import com.sun.tools.javac.tree.JCTree;
118import com.sun.tools.javac.tree.JCTree.JCBlock;
119import com.sun.tools.javac.tree.JCTree.JCCatch;
120import com.sun.tools.javac.tree.JCTree.JCClassDecl;
121import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
122import com.sun.tools.javac.tree.JCTree.JCExpression;
123import com.sun.tools.javac.tree.JCTree.JCIdent;
124import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
125import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
126import com.sun.tools.javac.tree.TreeCopier;
127import com.sun.tools.javac.tree.TreeInfo;
128import com.sun.tools.javac.tree.TreeMaker;
129import com.sun.tools.javac.util.Abort;
130import com.sun.tools.javac.util.Assert;
131import com.sun.tools.javac.util.Context;
132import com.sun.tools.javac.util.DefinedBy;
133import com.sun.tools.javac.util.DefinedBy.Api;
134import com.sun.tools.javac.util.DiagnosticSource;
135import com.sun.tools.javac.util.JCDiagnostic;
136import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
137import com.sun.tools.javac.util.List;
138import com.sun.tools.javac.util.ListBuffer;
139import com.sun.tools.javac.util.Log;
140import com.sun.tools.javac.util.Name;
141import com.sun.tools.javac.util.Names;
142import com.sun.tools.javac.util.Pair;
143import com.sun.tools.javac.util.Position;
144
145import static com.sun.tools.javac.code.Kinds.Kind.*;
146import static com.sun.tools.javac.code.TypeTag.*;
147
148/**
149 * Provides an implementation of Trees.
150 *
151 * <p><b>This is NOT part of any supported API.
152 * If you write code that depends on this, you do so at your own
153 * risk.  This code and its internal interfaces are subject to change
154 * or deletion without notice.</b></p>
155 *
156 * @author Peter von der Ah&eacute;
157 */
158public class JavacTrees extends DocTrees {
159
160    // in a world of a single context per compilation, these would all be final
161    private Modules modules;
162    private Resolve resolve;
163    private Enter enter;
164    private Log log;
165    private MemberEnter memberEnter;
166    private Attr attr;
167    private TreeMaker treeMaker;
168    private JavacElements elements;
169    private JavacTaskImpl javacTaskImpl;
170    private Names names;
171    private Types types;
172    private DocTreeMaker docTreeMaker;
173    private BreakIterator breakIterator;
174    private JavaFileManager fileManager;
175    private ParserFactory parser;
176    private Symtab syms;
177
178    // called reflectively from Trees.instance(CompilationTask task)
179    public static JavacTrees instance(JavaCompiler.CompilationTask task) {
180        if (!(task instanceof BasicJavacTask))
181            throw new IllegalArgumentException();
182        return instance(((BasicJavacTask)task).getContext());
183    }
184
185    // called reflectively from Trees.instance(ProcessingEnvironment env)
186    public static JavacTrees instance(ProcessingEnvironment env) {
187        if (!(env instanceof JavacProcessingEnvironment))
188            throw new IllegalArgumentException();
189        return instance(((JavacProcessingEnvironment)env).getContext());
190    }
191
192    public static JavacTrees instance(Context context) {
193        JavacTrees instance = context.get(JavacTrees.class);
194        if (instance == null)
195            instance = new JavacTrees(context);
196        return instance;
197    }
198
199    protected JavacTrees(Context context) {
200        this.breakIterator = null;
201        context.put(JavacTrees.class, this);
202        init(context);
203    }
204
205    public void updateContext(Context context) {
206        init(context);
207    }
208
209    private void init(Context context) {
210        modules = Modules.instance(context);
211        attr = Attr.instance(context);
212        enter = Enter.instance(context);
213        elements = JavacElements.instance(context);
214        log = Log.instance(context);
215        resolve = Resolve.instance(context);
216        treeMaker = TreeMaker.instance(context);
217        memberEnter = MemberEnter.instance(context);
218        names = Names.instance(context);
219        types = Types.instance(context);
220        docTreeMaker = DocTreeMaker.instance(context);
221        parser = ParserFactory.instance(context);
222        syms = Symtab.instance(context);
223        fileManager = context.get(JavaFileManager.class);
224        JavacTask t = context.get(JavacTask.class);
225        if (t instanceof JavacTaskImpl)
226            javacTaskImpl = (JavacTaskImpl) t;
227    }
228
229    @Override @DefinedBy(Api.COMPILER_TREE)
230    public BreakIterator getBreakIterator() {
231        return breakIterator;
232    }
233
234    @Override @DefinedBy(Api.COMPILER_TREE)
235    public DocSourcePositions getSourcePositions() {
236        return new DocSourcePositions() {
237                @Override @DefinedBy(Api.COMPILER_TREE)
238                public long getStartPosition(CompilationUnitTree file, Tree tree) {
239                    return TreeInfo.getStartPos((JCTree) tree);
240                }
241
242                @Override @DefinedBy(Api.COMPILER_TREE)
243                public long getEndPosition(CompilationUnitTree file, Tree tree) {
244                    EndPosTable endPosTable = ((JCCompilationUnit) file).endPositions;
245                    return TreeInfo.getEndPos((JCTree) tree, endPosTable);
246                }
247
248                @Override @DefinedBy(Api.COMPILER_TREE)
249                public long getStartPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree) {
250                    return ((DCTree) tree).getSourcePosition((DCDocComment) comment);
251                }
252                @Override  @DefinedBy(Api.COMPILER_TREE) @SuppressWarnings("fallthrough")
253                public long getEndPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree) {
254                    DCDocComment dcComment = (DCDocComment) comment;
255                    if (tree instanceof DCEndPosTree) {
256                        int endPos = ((DCEndPosTree) tree).getEndPos(dcComment);
257
258                        if (endPos != Position.NOPOS) {
259                            return endPos;
260                        }
261                    }
262                    int correction = 0;
263                    switch (tree.getKind()) {
264                        case TEXT:
265                            DCText text = (DCText) tree;
266
267                            return dcComment.comment.getSourcePos(text.pos + text.text.length());
268                        case ERRONEOUS:
269                            DCErroneous err = (DCErroneous) tree;
270
271                            return dcComment.comment.getSourcePos(err.pos + err.body.length());
272                        case IDENTIFIER:
273                            DCIdentifier ident = (DCIdentifier) tree;
274
275                            return dcComment.comment.getSourcePos(ident.pos + (ident.name != names.error ? ident.name.length() : 0));
276                        case PARAM:
277                            DCParam param = (DCParam) tree;
278
279                            if (param.isTypeParameter && param.getDescription().isEmpty()) {
280                                correction = 1;
281                            }
282                        case AUTHOR: case DEPRECATED: case RETURN: case SEE:
283                        case SERIAL: case SERIAL_DATA: case SERIAL_FIELD: case SINCE:
284                        case THROWS: case UNKNOWN_BLOCK_TAG: case VERSION: {
285                            DocTree last = getLastChild(tree);
286
287                            if (last != null) {
288                                return getEndPosition(file, comment, last) + correction;
289                            }
290
291                            DCBlockTag block = (DCBlockTag) tree;
292
293                            return dcComment.comment.getSourcePos(block.pos + block.getTagName().length() + 1);
294                        }
295                        default:
296                            DocTree last = getLastChild(tree);
297
298                            if (last != null) {
299                                return getEndPosition(file, comment, last);
300                            }
301                            break;
302                    }
303
304                    return Position.NOPOS;
305                }
306            };
307    }
308
309    @Override @DefinedBy(Api.COMPILER_TREE)
310    public DocTreeMaker getDocTreeFactory() {
311        return docTreeMaker;
312    }
313
314    private DocTree getLastChild(DocTree tree) {
315        final DocTree[] last = new DocTree[] {null};
316
317        tree.accept(new DocTreeScanner<Void, Void>() {
318            @Override @DefinedBy(Api.COMPILER_TREE)
319            public Void scan(DocTree node, Void p) {
320                if (node != null) last[0] = node;
321                return null;
322            }
323        }, null);
324
325        return last[0];
326    }
327
328    @Override @DefinedBy(Api.COMPILER_TREE)
329    public JCClassDecl getTree(TypeElement element) {
330        return (JCClassDecl) getTree((Element) element);
331    }
332
333    @Override @DefinedBy(Api.COMPILER_TREE)
334    public JCMethodDecl getTree(ExecutableElement method) {
335        return (JCMethodDecl) getTree((Element) method);
336    }
337
338    @Override @DefinedBy(Api.COMPILER_TREE)
339    public JCTree getTree(Element element) {
340        return getTree(element, null);
341    }
342
343    @Override @DefinedBy(Api.COMPILER_TREE)
344    public JCTree getTree(Element e, AnnotationMirror a) {
345        return getTree(e, a, null);
346    }
347
348    @Override @DefinedBy(Api.COMPILER_TREE)
349    public JCTree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
350        Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
351        if (treeTopLevel == null)
352            return null;
353        return treeTopLevel.fst;
354    }
355
356    @Override @DefinedBy(Api.COMPILER_TREE)
357    public TreePath getPath(CompilationUnitTree unit, Tree node) {
358        return TreePath.getPath(unit, node);
359    }
360
361    @Override @DefinedBy(Api.COMPILER_TREE)
362    public TreePath getPath(Element e) {
363        return getPath(e, null, null);
364    }
365
366    @Override @DefinedBy(Api.COMPILER_TREE)
367    public TreePath getPath(Element e, AnnotationMirror a) {
368        return getPath(e, a, null);
369    }
370
371    @Override @DefinedBy(Api.COMPILER_TREE)
372    public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
373        final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v);
374        if (treeTopLevel == null)
375            return null;
376        return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst);
377    }
378
379    @Override @DefinedBy(Api.COMPILER_TREE)
380    public Symbol getElement(TreePath path) {
381        JCTree tree = (JCTree) path.getLeaf();
382        Symbol sym = TreeInfo.symbolFor(tree);
383        if (sym == null) {
384            for (TreePath p = path; p != null; p = p.getParentPath()) {
385                JCTree t = (JCTree) p.getLeaf();
386                if (t.hasTag(JCTree.Tag.CLASSDEF)) {
387                    JCClassDecl ct = (JCClassDecl) t;
388                    if (ct.sym != null) {
389                        if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
390                            attr.attribClass(ct.pos(), ct.sym);
391                            sym = TreeInfo.symbolFor(tree);
392                        }
393                        break;
394                    }
395                }
396            }
397        }
398        return sym;
399    }
400
401    @Override @DefinedBy(Api.COMPILER_TREE)
402    public Element getElement(DocTreePath path) {
403        DocTree forTree = path.getLeaf();
404        if (forTree instanceof DCReference)
405            return attributeDocReference(path.getTreePath(), ((DCReference) forTree));
406        if (forTree instanceof DCIdentifier) {
407            if (path.getParentPath().getLeaf() instanceof DCParam) {
408                return attributeParamIdentifier(path.getTreePath(), (DCParam) path.getParentPath().getLeaf());
409            }
410        }
411        return null;
412    }
413
414    @Override @DefinedBy(Api.COMPILER_TREE)
415    public java.util.List<DocTree> getFirstSentence(java.util.List<? extends DocTree> list) {
416        return docTreeMaker.getFirstSentence(list);
417    }
418
419    private Symbol attributeDocReference(TreePath path, DCReference ref) {
420        Env<AttrContext> env = getAttrContext(path);
421        if (env == null) return null;
422
423        Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
424                new Log.DeferredDiagnosticHandler(log);
425        try {
426            final TypeSymbol tsym;
427            final Name memberName;
428            if (ref.qualifierExpression == null) {
429                tsym = env.enclClass.sym;
430                memberName = (Name) ref.memberName;
431            } else {
432                // newSeeTree if the qualifierExpression is a type or package name.
433                // javac does not provide the exact method required, so
434                // we first check if qualifierExpression identifies a type,
435                // and if not, then we check to see if it identifies a package.
436                Type t = attr.attribType(ref.qualifierExpression, env);
437                if (t.isErroneous()) {
438                    JCCompilationUnit toplevel =
439                        treeMaker.TopLevel(List.nil());
440                    final ModuleSymbol msym = modules.getDefaultModule();
441                    toplevel.modle = msym;
442                    toplevel.packge = msym.unnamedPackage;
443                    Symbol sym = attr.attribIdent(ref.qualifierExpression, toplevel);
444
445                    sym.complete();
446
447                    if ((sym.kind == PCK || sym.kind == TYP) && sym.exists()) {
448                        tsym = (TypeSymbol) sym;
449                        memberName = (Name) ref.memberName;
450                        if (sym.kind == PCK && memberName != null) {
451                            //cannot refer to a package "member"
452                            return null;
453                        }
454                    } else {
455                        if (ref.qualifierExpression.hasTag(JCTree.Tag.IDENT)) {
456                            // fixup:  allow "identifier" instead of "#identifier"
457                            // for compatibility with javadoc
458                            tsym = env.enclClass.sym;
459                            memberName = ((JCIdent) ref.qualifierExpression).name;
460                        } else {
461                            return null;
462                        }
463                    }
464                } else {
465                    tsym = t.tsym;
466                    memberName = (Name) ref.memberName;
467                }
468            }
469
470            if (memberName == null)
471                return tsym;
472
473            final List<Type> paramTypes;
474            if (ref.paramTypes == null)
475                paramTypes = null;
476            else {
477                ListBuffer<Type> lb = new ListBuffer<>();
478                for (List<JCTree> l = (List<JCTree>) ref.paramTypes; l.nonEmpty(); l = l.tail) {
479                    JCTree tree = l.head;
480                    Type t = attr.attribType(tree, env);
481                    lb.add(t);
482                }
483                paramTypes = lb.toList();
484            }
485
486            ClassSymbol sym = (ClassSymbol) types.cvarUpperBound(tsym.type).tsym;
487
488            Symbol msym = (memberName == sym.name)
489                    ? findConstructor(sym, paramTypes)
490                    : findMethod(sym, memberName, paramTypes);
491            if (paramTypes != null) {
492                // explicit (possibly empty) arg list given, so cannot be a field
493                return msym;
494            }
495
496            VarSymbol vsym = (ref.paramTypes != null) ? null : findField(sym, memberName);
497            // prefer a field over a method with no parameters
498            if (vsym != null &&
499                    (msym == null ||
500                        types.isSubtypeUnchecked(vsym.enclClass().asType(), msym.enclClass().asType()))) {
501                return vsym;
502            } else {
503                return msym;
504            }
505        } catch (Abort e) { // may be thrown by Check.completionError in case of bad class file
506            return null;
507        } finally {
508            log.popDiagnosticHandler(deferredDiagnosticHandler);
509        }
510    }
511
512    private Symbol attributeParamIdentifier(TreePath path, DCParam ptag) {
513        Symbol javadocSymbol = getElement(path);
514        if (javadocSymbol == null)
515            return null;
516        ElementKind kind = javadocSymbol.getKind();
517        List<? extends Symbol> params = List.nil();
518        if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
519            MethodSymbol ee = (MethodSymbol) javadocSymbol;
520            params = ptag.isTypeParameter()
521                    ? ee.getTypeParameters()
522                    : ee.getParameters();
523        } else if (kind.isClass() || kind.isInterface()) {
524            ClassSymbol te = (ClassSymbol) javadocSymbol;
525            params = te.getTypeParameters();
526        }
527
528        for (Symbol param : params) {
529            if (param.getSimpleName() == ptag.getName().getName()) {
530                return param;
531            }
532        }
533        return null;
534    }
535
536    /** @see com.sun.tools.javadoc.ClassDocImpl#findField */
537    private VarSymbol findField(ClassSymbol tsym, Name fieldName) {
538        return searchField(tsym, fieldName, new HashSet<>());
539    }
540
541    /** @see com.sun.tools.javadoc.ClassDocImpl#searchField */
542    private VarSymbol searchField(ClassSymbol tsym, Name fieldName, Set<ClassSymbol> searched) {
543        if (searched.contains(tsym)) {
544            return null;
545        }
546        searched.add(tsym);
547
548        for (Symbol sym : tsym.members().getSymbolsByName(fieldName)) {
549            if (sym.kind == VAR) {
550                return (VarSymbol)sym;
551            }
552        }
553
554        //### If we found a VarSymbol above, but which did not pass
555        //### the modifier filter, we should return failure here!
556
557        ClassSymbol encl = tsym.owner.enclClass();
558        if (encl != null) {
559            VarSymbol vsym = searchField(encl, fieldName, searched);
560            if (vsym != null) {
561                return vsym;
562            }
563        }
564
565        // search superclass
566        Type superclass = tsym.getSuperclass();
567        if (superclass.tsym != null) {
568            VarSymbol vsym = searchField((ClassSymbol) superclass.tsym, fieldName, searched);
569            if (vsym != null) {
570                return vsym;
571            }
572        }
573
574        // search interfaces
575        List<Type> intfs = tsym.getInterfaces();
576        for (List<Type> l = intfs; l.nonEmpty(); l = l.tail) {
577            Type intf = l.head;
578            if (intf.isErroneous()) continue;
579            VarSymbol vsym = searchField((ClassSymbol) intf.tsym, fieldName, searched);
580            if (vsym != null) {
581                return vsym;
582            }
583        }
584
585        return null;
586    }
587
588    /** @see com.sun.tools.javadoc.ClassDocImpl#findConstructor */
589    MethodSymbol findConstructor(ClassSymbol tsym, List<Type> paramTypes) {
590        for (Symbol sym : tsym.members().getSymbolsByName(names.init)) {
591            if (sym.kind == MTH) {
592                if (hasParameterTypes((MethodSymbol) sym, paramTypes)) {
593                    return (MethodSymbol) sym;
594                }
595            }
596        }
597        return null;
598    }
599
600    /** @see com.sun.tools.javadoc.ClassDocImpl#findMethod */
601    private MethodSymbol findMethod(ClassSymbol tsym, Name methodName, List<Type> paramTypes) {
602        return searchMethod(tsym, methodName, paramTypes, new HashSet<>());
603    }
604
605    /** @see com.sun.tools.javadoc.ClassDocImpl#searchMethod */
606    private MethodSymbol searchMethod(ClassSymbol tsym, Name methodName,
607                                       List<Type> paramTypes, Set<ClassSymbol> searched) {
608        //### Note that this search is not necessarily what the compiler would do!
609
610        // do not match constructors
611        if (methodName == names.init)
612            return null;
613
614        if (searched.contains(tsym))
615            return null;
616        searched.add(tsym);
617
618        // search current class
619
620        //### Using modifier filter here isn't really correct,
621        //### but emulates the old behavior.  Instead, we should
622        //### apply the normal rules of visibility and inheritance.
623
624        if (paramTypes == null) {
625            // If no parameters specified, we are allowed to return
626            // any method with a matching name.  In practice, the old
627            // code returned the first method, which is now the last!
628            // In order to provide textually identical results, we
629            // attempt to emulate the old behavior.
630            MethodSymbol lastFound = null;
631            for (Symbol sym : tsym.members().getSymbolsByName(methodName)) {
632                if (sym.kind == MTH) {
633                    if (sym.name == methodName) {
634                        lastFound = (MethodSymbol)sym;
635                    }
636                }
637            }
638            if (lastFound != null) {
639                return lastFound;
640            }
641        } else {
642            for (Symbol sym : tsym.members().getSymbolsByName(methodName)) {
643                if (sym != null &&
644                    sym.kind == MTH) {
645                    if (hasParameterTypes((MethodSymbol) sym, paramTypes)) {
646                        return (MethodSymbol) sym;
647                    }
648                }
649            }
650        }
651
652        //### If we found a MethodSymbol above, but which did not pass
653        //### the modifier filter, we should return failure here!
654
655        // search superclass
656        Type superclass = tsym.getSuperclass();
657        if (superclass.tsym != null) {
658            MethodSymbol msym = searchMethod((ClassSymbol) superclass.tsym, methodName, paramTypes, searched);
659            if (msym != null) {
660                return msym;
661            }
662        }
663
664        // search interfaces
665        List<Type> intfs = tsym.getInterfaces();
666        for (List<Type> l = intfs; l.nonEmpty(); l = l.tail) {
667            Type intf = l.head;
668            if (intf.isErroneous()) continue;
669            MethodSymbol msym = searchMethod((ClassSymbol) intf.tsym, methodName, paramTypes, searched);
670            if (msym != null) {
671                return msym;
672            }
673        }
674
675        // search enclosing class
676        ClassSymbol encl = tsym.owner.enclClass();
677        if (encl != null) {
678            MethodSymbol msym = searchMethod(encl, methodName, paramTypes, searched);
679            if (msym != null) {
680                return msym;
681            }
682        }
683
684        return null;
685    }
686
687    /** @see com.sun.tools.javadoc.ClassDocImpl */
688    private boolean hasParameterTypes(MethodSymbol method, List<Type> paramTypes) {
689        if (paramTypes == null)
690            return true;
691
692        if (method.params().size() != paramTypes.size())
693            return false;
694
695        List<Type> methodParamTypes = types.erasureRecursive(method.asType()).getParameterTypes();
696
697        return (Type.isErroneous(paramTypes))
698            ? fuzzyMatch(paramTypes, methodParamTypes)
699            : types.isSameTypes(paramTypes, methodParamTypes);
700    }
701
702    boolean fuzzyMatch(List<Type> paramTypes, List<Type> methodParamTypes) {
703        List<Type> l1 = paramTypes;
704        List<Type> l2 = methodParamTypes;
705        while (l1.nonEmpty()) {
706            if (!fuzzyMatch(l1.head, l2.head))
707                return false;
708            l1 = l1.tail;
709            l2 = l2.tail;
710        }
711        return true;
712    }
713
714    boolean fuzzyMatch(Type paramType, Type methodParamType) {
715        Boolean b = fuzzyMatcher.visit(paramType, methodParamType);
716        return (b == Boolean.TRUE);
717    }
718
719    TypeRelation fuzzyMatcher = new TypeRelation() {
720        @Override
721        public Boolean visitType(Type t, Type s) {
722            if (t == s)
723                return true;
724
725            if (s.isPartial())
726                return visit(s, t);
727
728            switch (t.getTag()) {
729            case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
730            case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
731                return t.hasTag(s.getTag());
732            default:
733                throw new AssertionError("fuzzyMatcher " + t.getTag());
734            }
735        }
736
737        @Override
738        public Boolean visitArrayType(ArrayType t, Type s) {
739            if (t == s)
740                return true;
741
742            if (s.isPartial())
743                return visit(s, t);
744
745            return s.hasTag(ARRAY)
746                && visit(t.elemtype, types.elemtype(s));
747        }
748
749        @Override
750        public Boolean visitClassType(ClassType t, Type s) {
751            if (t == s)
752                return true;
753
754            if (s.isPartial())
755                return visit(s, t);
756
757            return t.tsym == s.tsym;
758        }
759
760        @Override
761        public Boolean visitErrorType(ErrorType t, Type s) {
762            return s.hasTag(CLASS)
763                    && t.tsym.name == ((ClassType) s).tsym.name;
764        }
765    };
766
767    @Override @DefinedBy(Api.COMPILER_TREE)
768    public TypeMirror getTypeMirror(TreePath path) {
769        Tree t = path.getLeaf();
770        Type ty = ((JCTree)t).type;
771        return ty == null ? null : ty.stripMetadataIfNeeded();
772    }
773
774    @Override @DefinedBy(Api.COMPILER_TREE)
775    public JavacScope getScope(TreePath path) {
776        return JavacScope.create(getAttrContext(path));
777    }
778
779    @Override @DefinedBy(Api.COMPILER_TREE)
780    public String getDocComment(TreePath path) {
781        CompilationUnitTree t = path.getCompilationUnit();
782        Tree leaf = path.getLeaf();
783        if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
784            JCCompilationUnit cu = (JCCompilationUnit) t;
785            if (cu.docComments != null) {
786                return cu.docComments.getCommentText((JCTree) leaf);
787            }
788        }
789        return null;
790    }
791
792    @Override @DefinedBy(Api.COMPILER_TREE)
793    public DocCommentTree getDocCommentTree(TreePath path) {
794        CompilationUnitTree t = path.getCompilationUnit();
795        Tree leaf = path.getLeaf();
796        if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
797            JCCompilationUnit cu = (JCCompilationUnit) t;
798            if (cu.docComments != null) {
799                return cu.docComments.getCommentTree((JCTree) leaf);
800            }
801        }
802        return null;
803    }
804
805    @Override @DefinedBy(Api.COMPILER_TREE)
806    public DocCommentTree getDocCommentTree(Element e) {
807        TreePath path = getPath(e);
808        if (path == null) {
809            return null;
810        }
811        return getDocCommentTree(path);
812    }
813
814    @Override @DefinedBy(Api.COMPILER_TREE)
815    public DocCommentTree getDocCommentTree(Element e, String relativeFileName) throws IOException {
816        PackageElement pkg = elements.getPackageOf(e);
817        FileObject fileForInput = fileManager.getFileForInput(StandardLocation.SOURCE_PATH,
818                pkg.getQualifiedName().toString(), relativeFileName);
819
820        if (fileForInput == null) {
821            throw new FileNotFoundException(relativeFileName);
822        }
823        return getDocCommentTree(fileForInput);
824    }
825
826    @Override @DefinedBy(Api.COMPILER_TREE)
827    public boolean isAccessible(Scope scope, TypeElement type) {
828        if (scope instanceof JavacScope && type instanceof ClassSymbol) {
829            Env<AttrContext> env = ((JavacScope) scope).env;
830            return resolve.isAccessible(env, (ClassSymbol)type, true);
831        } else
832            return false;
833    }
834
835    @Override @DefinedBy(Api.COMPILER_TREE)
836    public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
837        if (scope instanceof JavacScope
838                && member instanceof Symbol
839                && type instanceof com.sun.tools.javac.code.Type) {
840            Env<AttrContext> env = ((JavacScope) scope).env;
841            return resolve.isAccessible(env, (com.sun.tools.javac.code.Type)type, (Symbol)member, true);
842        } else
843            return false;
844    }
845
846    private Env<AttrContext> getAttrContext(TreePath path) {
847        if (!(path.getLeaf() instanceof JCTree))  // implicit null-check
848            throw new IllegalArgumentException();
849
850        // if we're being invoked from a Tree API client via parse/enter/analyze,
851        // we need to make sure all the classes have been entered;
852        // if we're being invoked from JSR 199 or JSR 269, then the classes
853        // will already have been entered.
854        if (javacTaskImpl != null) {
855            javacTaskImpl.enter(null);
856        }
857
858        JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
859        Copier copier = createCopier(treeMaker.forToplevel(unit));
860
861        Env<AttrContext> env = null;
862        JCMethodDecl method = null;
863        JCVariableDecl field = null;
864
865        List<Tree> l = List.nil();
866        TreePath p = path;
867        while (p != null) {
868            l = l.prepend(p.getLeaf());
869            p = p.getParentPath();
870        }
871
872        for ( ; l.nonEmpty(); l = l.tail) {
873            Tree tree = l.head;
874            switch (tree.getKind()) {
875                case COMPILATION_UNIT:
876//                    System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
877                    env = enter.getTopLevelEnv((JCCompilationUnit)tree);
878                    break;
879                case ANNOTATION_TYPE:
880                case CLASS:
881                case ENUM:
882                case INTERFACE:
883//                    System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
884                    env = enter.getClassEnv(((JCClassDecl)tree).sym);
885                    if (env == null) return null;
886                    break;
887                case METHOD:
888//                    System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
889                    method = (JCMethodDecl)tree;
890                    env = memberEnter.getMethodEnv(method, env);
891                    break;
892                case VARIABLE:
893//                    System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
894                    field = (JCVariableDecl)tree;
895                    break;
896                case BLOCK: {
897//                    System.err.println("BLOCK: ");
898                    if (method != null) {
899                        try {
900                            Assert.check(method.body == tree);
901                            method.body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
902                            env = attribStatToTree(method.body, env, copier.leafCopy);
903                        } finally {
904                            method.body = (JCBlock) tree;
905                        }
906                    } else {
907                        JCBlock body = copier.copy((JCBlock)tree, (JCTree) path.getLeaf());
908                        env = attribStatToTree(body, env, copier.leafCopy);
909                    }
910                    return env;
911                }
912                default:
913//                    System.err.println("DEFAULT: " + tree.getKind());
914                    if (field != null && field.getInitializer() == tree) {
915                        env = memberEnter.getInitEnv(field, env);
916                        JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
917                        env = attribExprToTree(expr, env, copier.leafCopy);
918                        return env;
919                    }
920            }
921        }
922        return (field != null) ? memberEnter.getInitEnv(field, env) : env;
923    }
924
925    private Env<AttrContext> attribStatToTree(JCTree stat, Env<AttrContext>env, JCTree tree) {
926        JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
927        try {
928            return attr.attribStatToTree(stat, env, tree);
929        } finally {
930            log.useSource(prev);
931        }
932    }
933
934    private Env<AttrContext> attribExprToTree(JCExpression expr, Env<AttrContext>env, JCTree tree) {
935        JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
936        try {
937            return attr.attribExprToTree(expr, env, tree);
938        } finally {
939            log.useSource(prev);
940        }
941    }
942
943    static JavaFileObject asJavaFileObject(FileObject fileObject) {
944        JavaFileObject jfo = null;
945
946        if (fileObject instanceof JavaFileObject) {
947            jfo = (JavaFileObject) fileObject;
948            checkHtmlKind(fileObject, Kind.HTML);
949            return jfo;
950        }
951
952        checkHtmlKind(fileObject);
953        jfo = new HtmlFileObject(fileObject);
954        return jfo;
955    }
956
957    private static void checkHtmlKind(FileObject fileObject) {
958        checkHtmlKind(fileObject, BaseFileManager.getKind(fileObject.getName()));
959    }
960
961    private static void checkHtmlKind(FileObject fileObject, JavaFileObject.Kind kind) {
962        if (kind != JavaFileObject.Kind.HTML) {
963            throw new IllegalArgumentException("HTML file expected:" + fileObject.getName());
964        }
965    }
966
967    private static class HtmlFileObject extends ForwardingFileObject<FileObject>
968            implements JavaFileObject {
969
970        public HtmlFileObject(FileObject fileObject) {
971            super(fileObject);
972        }
973
974        @Override @DefinedBy(Api.COMPILER)
975        public Kind getKind() {
976            return BaseFileManager.getKind(fileObject.getName());
977        }
978
979        @Override @DefinedBy(Api.COMPILER)
980        public boolean isNameCompatible(String simpleName, Kind kind) {
981            return false;
982        }
983
984        @Override @DefinedBy(Api.COMPILER)
985        public NestingKind getNestingKind() {
986            return null;
987        }
988
989        @Override @DefinedBy(Api.COMPILER)
990        public Modifier getAccessLevel() {
991            return null;
992        }
993    }
994
995    @Override @DefinedBy(Api.COMPILER_TREE)
996    public DocCommentTree getDocCommentTree(FileObject fileObject) {
997        JavaFileObject jfo = asJavaFileObject(fileObject);
998        DiagnosticSource diagSource = new DiagnosticSource(jfo, log);
999
1000        final Comment comment = new Comment() {
1001            int offset = 0;
1002            @Override
1003            public String getText() {
1004                try {
1005                    CharSequence rawDoc = fileObject.getCharContent(true);
1006                    Pattern bodyPat =
1007                            Pattern.compile("(?is).*?<body\\b[^>]*>(.*)</body\\b.*");
1008                    Matcher m = bodyPat.matcher(rawDoc);
1009                    if (m.matches()) {
1010                        offset = m.end(1);
1011                        return m.group(1);
1012                    } else {
1013                        // Assume doclint will do the right thing.
1014                        return "";
1015                    }
1016                } catch (IOException ignore) {
1017                    // do nothing
1018                }
1019                return "";
1020            }
1021
1022            @Override
1023            public int getSourcePos(int index) {
1024                return offset + index;
1025            }
1026
1027            @Override
1028            public CommentStyle getStyle() {
1029                throw new UnsupportedOperationException();
1030            }
1031
1032            @Override
1033            public boolean isDeprecated() {
1034                throw new UnsupportedOperationException();
1035            }
1036        };
1037
1038        return new DocCommentParser(parser, diagSource, comment).parse();
1039    }
1040
1041    @Override @DefinedBy(Api.COMPILER_TREE)
1042    public DocTreePath getDocTreePath(FileObject fileObject, PackageElement packageElement) {
1043        JavaFileObject jfo = asJavaFileObject(fileObject);
1044        DocCommentTree docCommentTree = getDocCommentTree(jfo);
1045        TreePath treePath = makeTreePath((PackageSymbol)packageElement, jfo, docCommentTree);
1046        return new DocTreePath(treePath, docCommentTree);
1047    }
1048
1049    @Override @DefinedBy(Api.COMPILER_TREE)
1050    public void setBreakIterator(BreakIterator breakiterator) {
1051        this.breakIterator = breakiterator;
1052    }
1053
1054    /**
1055     * Makes a copy of a tree, noting the value resulting from copying a particular leaf.
1056     **/
1057    protected static class Copier extends TreeCopier<JCTree> {
1058        JCTree leafCopy = null;
1059
1060        protected Copier(TreeMaker M) {
1061            super(M);
1062        }
1063
1064        @Override
1065        public <T extends JCTree> T copy(T t, JCTree leaf) {
1066            T t2 = super.copy(t, leaf);
1067            if (t == leaf)
1068                leafCopy = t2;
1069            return t2;
1070        }
1071    }
1072
1073    protected Copier createCopier(TreeMaker maker) {
1074        return new Copier(maker);
1075    }
1076
1077    /**
1078     * Returns the original type from the ErrorType object.
1079     * @param errorType The errorType for which we want to get the original type.
1080     * @return TypeMirror corresponding to the original type, replaced by the ErrorType.
1081     *         noType (type.tag == NONE) is returned if there is no original type.
1082     */
1083    @Override @DefinedBy(Api.COMPILER_TREE)
1084    public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
1085        if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
1086            return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
1087        }
1088
1089        return com.sun.tools.javac.code.Type.noType;
1090    }
1091
1092    /**
1093     * Prints a message of the specified kind at the location of the
1094     * tree within the provided compilation unit
1095     *
1096     * @param kind the kind of message
1097     * @param msg  the message, or an empty string if none
1098     * @param t    the tree to use as a position hint
1099     * @param root the compilation unit that contains tree
1100     */
1101    @Override @DefinedBy(Api.COMPILER_TREE)
1102    public void printMessage(Diagnostic.Kind kind, CharSequence msg,
1103            com.sun.source.tree.Tree t,
1104            com.sun.source.tree.CompilationUnitTree root) {
1105        printMessage(kind, msg, ((JCTree) t).pos(), root);
1106    }
1107
1108    @Override @DefinedBy(Api.COMPILER_TREE)
1109    public void printMessage(Diagnostic.Kind kind, CharSequence msg,
1110            com.sun.source.doctree.DocTree t,
1111            com.sun.source.doctree.DocCommentTree c,
1112            com.sun.source.tree.CompilationUnitTree root) {
1113        printMessage(kind, msg, ((DCTree) t).pos((DCDocComment) c), root);
1114    }
1115
1116    private void printMessage(Diagnostic.Kind kind, CharSequence msg,
1117            JCDiagnostic.DiagnosticPosition pos,
1118            com.sun.source.tree.CompilationUnitTree root) {
1119        JavaFileObject oldSource = null;
1120        JavaFileObject newSource = null;
1121
1122        newSource = root.getSourceFile();
1123        if (newSource == null) {
1124            pos = null;
1125        } else {
1126            oldSource = log.useSource(newSource);
1127        }
1128
1129        try {
1130            switch (kind) {
1131            case ERROR:
1132                log.error(DiagnosticFlag.MULTIPLE, pos, "proc.messager", msg.toString());
1133                break;
1134
1135            case WARNING:
1136                log.warning(pos, "proc.messager", msg.toString());
1137                break;
1138
1139            case MANDATORY_WARNING:
1140                log.mandatoryWarning(pos, "proc.messager", msg.toString());
1141                break;
1142
1143            default:
1144                log.note(pos, "proc.messager", msg.toString());
1145            }
1146        } finally {
1147            if (oldSource != null)
1148                log.useSource(oldSource);
1149        }
1150    }
1151
1152    @Override @DefinedBy(Api.COMPILER_TREE)
1153    public TypeMirror getLub(CatchTree tree) {
1154        JCCatch ct = (JCCatch) tree;
1155        JCVariableDecl v = ct.param;
1156        if (v.type != null && v.type.getKind() == TypeKind.UNION) {
1157            UnionClassType ut = (UnionClassType) v.type;
1158            return ut.getLub();
1159        } else {
1160            return v.type;
1161        }
1162    }
1163
1164    private TreePath makeTreePath(final PackageSymbol psym, final JavaFileObject jfo,
1165            DocCommentTree dcTree) {
1166        JCCompilationUnit jcCompilationUnit = new JCCompilationUnit(List.nil()) {
1167            public int getPos() {
1168                return Position.FIRSTPOS;
1169            }
1170
1171            public JavaFileObject getSourcefile() {
1172                return jfo;
1173            }
1174
1175            @Override @DefinedBy(Api.COMPILER_TREE)
1176            public Position.LineMap getLineMap() {
1177                try {
1178                    CharSequence content = jfo.getCharContent(true);
1179                    String s = content.toString();
1180                    return Position.makeLineMap(s.toCharArray(), s.length(), true);
1181                } catch (IOException ignore) {}
1182                return null;
1183            }
1184        };
1185
1186        jcCompilationUnit.docComments = new DocCommentTable() {
1187            @Override
1188            public boolean hasComment(JCTree tree) {
1189                return false;
1190            }
1191
1192            @Override
1193            public Comment getComment(JCTree tree) {
1194                throw new UnsupportedOperationException();
1195            }
1196
1197            @Override
1198            public String getCommentText(JCTree tree) {
1199                throw new UnsupportedOperationException();
1200            }
1201
1202            @Override
1203            public DCDocComment getCommentTree(JCTree tree) {
1204                return (DCDocComment)dcTree;
1205            }
1206
1207            @Override
1208            public void putComment(JCTree tree, Comment c) {
1209                throw new UnsupportedOperationException();
1210            }
1211
1212        };
1213        jcCompilationUnit.lineMap = jcCompilationUnit.getLineMap();
1214        jcCompilationUnit.modle = psym.modle;
1215        jcCompilationUnit.sourcefile = jfo;
1216        jcCompilationUnit.namedImportScope = new NamedImportScope(psym, jcCompilationUnit.toplevelScope);
1217        jcCompilationUnit.packge = psym;
1218        jcCompilationUnit.starImportScope = new StarImportScope(psym);
1219        jcCompilationUnit.toplevelScope = WriteableScope.create(psym);
1220        return new TreePath(jcCompilationUnit);
1221    }
1222}
1223