ClassDocImpl.java 43.9 KB
Newer Older
D
duke 已提交
1
/*
J
jjg 已提交
2
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27
 */

package com.sun.tools.javadoc;

28 29 30 31 32 33
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
J
jjg 已提交
34

35 36 37 38 39
import javax.tools.FileObject;
import javax.tools.JavaFileManager.Location;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;

D
duke 已提交
40
import com.sun.javadoc.*;
J
jjg 已提交
41
import com.sun.source.util.TreePath;
D
duke 已提交
42 43 44 45 46
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.*;
47 48
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
49
import com.sun.tools.javac.code.TypeTag;
D
duke 已提交
50 51 52 53 54 55
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.tree.TreeInfo;
56 57 58
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;
59
import com.sun.tools.javac.util.Names;
60
import com.sun.tools.javac.util.Position;
D
duke 已提交
61
import static com.sun.tools.javac.code.Kinds.*;
62
import static com.sun.tools.javac.code.TypeTag.CLASS;
63
import static com.sun.tools.javac.tree.JCTree.Tag.*;
D
duke 已提交
64 65 66 67 68 69 70 71 72 73

/**
 * Represents a java class and provides access to information
 * about the class, the class' comment and tags, and the
 * members of the class.  A ClassDocImpl only exists if it was
 * processed in this run of javadoc.  References to classes
 * which may or may not have been processed in this run are
 * referred to using Type (which can be converted to ClassDocImpl,
 * if possible).
 *
74 75 76 77 78
 *  <p><b>This is NOT part of any supported API.
 *  If you write code that depends on this, you do so at your own risk.
 *  This code and its internal interfaces are subject to change or
 *  deletion without notice.</b>
 *
D
duke 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
 * @see Type
 *
 * @since 1.2
 * @author Robert Field
 * @author Neal Gafter (rewrite)
 * @author Scott Seligman (generics, enums, annotations)
 */

public class ClassDocImpl extends ProgramElementDocImpl implements ClassDoc {

    public final ClassType type;        // protected->public for debugging
    protected final ClassSymbol tsym;

    boolean isIncluded = false;         // Set in RootDocImpl

    private SerializedForm serializedForm;

    /**
     * Constructor
     */
    public ClassDocImpl(DocEnv env, ClassSymbol sym) {
J
jjg 已提交
100
        this(env, sym, null);
D
duke 已提交
101 102 103 104 105
    }

    /**
     * Constructor
     */
J
jjg 已提交
106 107
    public ClassDocImpl(DocEnv env, ClassSymbol sym, TreePath treePath) {
        super(env, sym, treePath);
D
duke 已提交
108 109 110 111
        this.type = (ClassType)sym.type;
        this.tsym = sym;
    }

112 113 114 115
    public com.sun.javadoc.Type getElementType() {
        return null;
    }

D
duke 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    /**
     * Returns the flags in terms of javac's flags
     */
    protected long getFlags() {
        return getFlags(tsym);
    }

    /**
     * Returns the flags of a ClassSymbol in terms of javac's flags
     */
    static long getFlags(ClassSymbol clazz) {
        while (true) {
            try {
                return clazz.flags();
            } catch (CompletionFailure ex) {
131 132 133 134 135 136 137 138
                /* Quietly ignore completion failures.
                 * Note that a CompletionFailure can only
                 * occur as a result of calling complete(),
                 * which will always remove the current
                 * completer, leaving it to be null or
                 * follow-up completer. Thus the loop
                 * is guaranteed to eventually terminate.
                 */
D
duke 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
            }
        }
    }

    /**
     * Is a ClassSymbol an annotation type?
     */
    static boolean isAnnotationType(ClassSymbol clazz) {
        return (getFlags(clazz) & Flags.ANNOTATION) != 0;
    }

    /**
     * Identify the containing class
     */
    protected ClassSymbol getContainingClass() {
        return tsym.owner.enclClass();
    }

    /**
     * Return true if this is a class, not an interface.
     */
160
    @Override
D
duke 已提交
161 162 163 164 165 166 167 168
    public boolean isClass() {
        return !Modifier.isInterface(getModifiers());
    }

    /**
     * Return true if this is a ordinary class,
     * not an enumeration, exception, an error, or an interface.
     */
169
    @Override
D
duke 已提交
170 171 172 173
    public boolean isOrdinaryClass() {
        if (isEnum() || isInterface() || isAnnotationType()) {
            return false;
        }
174
        for (Type t = type; t.hasTag(CLASS); t = env.types.supertype(t)) {
D
duke 已提交
175 176 177 178 179 180 181 182 183 184 185 186
            if (t.tsym == env.syms.errorType.tsym ||
                t.tsym == env.syms.exceptionType.tsym) {
                return false;
            }
        }
        return true;
    }

    /**
     * Return true if this is an enumeration.
     * (For legacy doclets, return false.)
     */
187
    @Override
D
duke 已提交
188 189 190 191 192 193 194 195 196 197
    public boolean isEnum() {
        return (getFlags() & Flags.ENUM) != 0
               &&
               !env.legacyDoclet;
    }

    /**
     * Return true if this is an interface, but not an annotation type.
     * Overridden by AnnotationTypeDocImpl.
     */
198
    @Override
D
duke 已提交
199 200 201 202 203 204 205
    public boolean isInterface() {
        return Modifier.isInterface(getModifiers());
    }

    /**
     * Return true if this is an exception class
     */
206
    @Override
D
duke 已提交
207 208 209 210
    public boolean isException() {
        if (isEnum() || isInterface() || isAnnotationType()) {
            return false;
        }
211
        for (Type t = type; t.hasTag(CLASS); t = env.types.supertype(t)) {
D
duke 已提交
212 213 214 215 216 217 218 219 220 221
            if (t.tsym == env.syms.exceptionType.tsym) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return true if this is an error class
     */
222
    @Override
D
duke 已提交
223 224 225 226
    public boolean isError() {
        if (isEnum() || isInterface() || isAnnotationType()) {
            return false;
        }
227
        for (Type t = type; t.hasTag(CLASS); t = env.types.supertype(t)) {
D
duke 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241
            if (t.tsym == env.syms.errorType.tsym) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return true if this is a throwable class
     */
    public boolean isThrowable() {
        if (isEnum() || isInterface() || isAnnotationType()) {
            return false;
        }
242
        for (Type t = type; t.hasTag(CLASS); t = env.types.supertype(t)) {
D
duke 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
            if (t.tsym == env.syms.throwableType.tsym) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return true if this class is abstract
     */
    public boolean isAbstract() {
        return Modifier.isAbstract(getModifiers());
    }

    /**
     * Returns true if this class was synthesized by the compiler.
     */
    public boolean isSynthetic() {
        return (getFlags() & Flags.SYNTHETIC) != 0;
    }

    /**
     * Return true if this class is included in the active set.
     * A ClassDoc is included iff either it is specified on the
     * commandline, or if it's containing package is specified
     * on the command line, or if it is a member class of an
     * included class.
     */

    public boolean isIncluded() {
        if (isIncluded) {
            return true;
        }
        if (env.shouldDocument(tsym)) {
            // Class is nameable from top-level and
            // the class and all enclosing classes
            // pass the modifier filter.
            if (containingPackage().isIncluded()) {
                return isIncluded=true;
            }
            ClassDoc outer = containingClass();
            if (outer != null && outer.isIncluded()) {
                return isIncluded=true;
            }
        }
        return false;
    }

291
    public boolean isFunctionalInterface() {
292
        return env.types.isFunctionalInterface(tsym) && env.source.allowLambda();
293 294
    }

D
duke 已提交
295 296 297
    /**
     * Return the package that this class is contained in.
     */
298
    @Override
D
duke 已提交
299 300
    public PackageDoc containingPackage() {
        PackageDocImpl p = env.getPackageDoc(tsym.packge());
301 302 303 304 305 306 307 308 309 310
        if (p.setDocPath == false) {
            FileObject docPath;
            try {
                Location location = env.fileManager.hasLocation(StandardLocation.SOURCE_PATH)
                    ? StandardLocation.SOURCE_PATH : StandardLocation.CLASS_PATH;

                docPath = env.fileManager.getFileForInput(
                        location, p.qualifiedName(), "package.html");
            } catch (IOException e) {
                docPath = null;
D
duke 已提交
311
            }
312 313 314 315 316 317 318 319 320

            if (docPath == null) {
                // fall back on older semantics of looking in same directory as
                // source file for this class
                SourcePosition po = position();
                if (env.fileManager instanceof StandardJavaFileManager &&
                        po instanceof SourcePositionImpl) {
                    URI uri = ((SourcePositionImpl) po).filename.toUri();
                    if ("file".equals(uri.getScheme())) {
321
                        File f = new File(uri);
322 323 324 325 326 327 328 329 330 331 332 333 334 335
                        File dir = f.getParentFile();
                        if (dir != null) {
                            File pf = new File(dir, "package.html");
                            if (pf.exists()) {
                                StandardJavaFileManager sfm = (StandardJavaFileManager) env.fileManager;
                                docPath = sfm.getJavaFileObjects(pf).iterator().next();
                            }
                        }

                    }
                }
            }

            p.setDocPath(docPath);
D
duke 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
        }
        return p;
    }

    /**
     * Return the class name without package qualifier - but with
     * enclosing class qualifier - as a String.
     * <pre>
     * Examples:
     *  for java.util.Hashtable
     *  return Hashtable
     *  for java.util.Map.Entry
     *  return Map.Entry
     * </pre>
     */
    public String name() {
352 353 354 355
        if (name == null) {
            name = getClassName(tsym, false);
        }
        return name;
D
duke 已提交
356 357
    }

358 359
    private String name;

D
duke 已提交
360 361 362 363 364 365 366 367 368 369
    /**
     * Return the qualified class name as a String.
     * <pre>
     * Example:
     *  for java.util.Hashtable
     *  return java.util.Hashtable
     *  if no qualifier, just return flat name
     * </pre>
     */
    public String qualifiedName() {
370 371 372 373
        if (qualifiedName == null) {
            qualifiedName = getClassName(tsym, true);
        }
        return qualifiedName;
D
duke 已提交
374 375
    }

376 377
    private String qualifiedName;

D
duke 已提交
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    /**
     * Return unqualified name of type excluding any dimension information.
     * <p>
     * For example, a two dimensional array of String returns 'String'.
     */
    public String typeName() {
        return name();
    }

    /**
     * Return qualified name of type excluding any dimension information.
     *<p>
     * For example, a two dimensional array of String
     * returns 'java.lang.String'.
     */
    public String qualifiedTypeName() {
        return qualifiedName();
    }

    /**
     * Return the simple name of this type.
     */
    public String simpleTypeName() {
401 402 403 404
        if (simpleTypeName == null) {
            simpleTypeName = tsym.name.toString();
        }
        return simpleTypeName;
D
duke 已提交
405 406
    }

407 408
    private String simpleTypeName;

D
duke 已提交
409 410 411 412
    /**
     * Return the qualified name and any type parameters.
     * Each parameter is a type variable with optional bounds.
     */
413
    @Override
D
duke 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    public String toString() {
        return classToString(env, tsym, true);
    }

    /**
     * Return the class name as a string.  If "full" is true the name is
     * qualified, otherwise it is qualified by its enclosing class(es) only.
     */
    static String getClassName(ClassSymbol c, boolean full) {
        if (full) {
            return c.getQualifiedName().toString();
        } else {
            String n = "";
            for ( ; c != null; c = c.owner.enclClass()) {
                n = c.name + (n.equals("") ? "" : ".") + n;
            }
            return n;
        }
    }

    /**
     * Return the class name with any type parameters as a string.
     * Each parameter is a type variable with optional bounds.
     * If "full" is true all names are qualified, otherwise they are
     * qualified by their enclosing class(es) only.
     */
    static String classToString(DocEnv env, ClassSymbol c, boolean full) {
441
        StringBuilder s = new StringBuilder();
D
duke 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
        if (!c.isInner()) {             // if c is not an inner class
            s.append(getClassName(c, full));
        } else {
            // c is an inner class, so include type params of outer.
            ClassSymbol encl = c.owner.enclClass();
            s.append(classToString(env, encl, full))
             .append('.')
             .append(c.name);
        }
        s.append(TypeMaker.typeParametersString(env, c, full));
        return s.toString();
    }

    /**
     * Is this class (or any enclosing class) generic?  That is, does
     * it have type parameters?
     */
    static boolean isGeneric(ClassSymbol c) {
        return c.type.allparams().nonEmpty();
    }

    /**
     * Return the formal type parameters of this class or interface.
     * Return an empty array if there are none.
     */
    public TypeVariable[] typeParameters() {
        if (env.legacyDoclet) {
            return new TypeVariable[0];
        }
        TypeVariable res[] = new TypeVariable[type.getTypeArguments().length()];
        TypeMaker.getTypes(env, type.getTypeArguments(), res);
        return res;
    }

    /**
     * Return the type parameter tags of this class or interface.
     */
    public ParamTag[] typeParamTags() {
        return (env.legacyDoclet)
            ? new ParamTag[0]
            : comment().typeParamTags();
    }

    /**
     * Return the modifier string for this class. If it's an interface
     * exclude 'abstract' keyword from the modifier string
     */
489
    @Override
D
duke 已提交
490 491 492 493
    public String modifiers() {
        return Modifier.toString(modifierSpecifier());
    }

494
    @Override
D
duke 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    public int modifierSpecifier() {
        int modifiers = getModifiers();
        return (isInterface() || isAnnotationType())
                ? modifiers & ~Modifier.ABSTRACT
                : modifiers;
    }

    /**
     * Return the superclass of this class
     *
     * @return the ClassDocImpl for the superclass of this class, null
     * if there is no superclass.
     */
    public ClassDoc superclass() {
        if (isInterface() || isAnnotationType()) return null;
        if (tsym == env.syms.objectType.tsym) return null;
        ClassSymbol c = (ClassSymbol)env.types.supertype(type).tsym;
        if (c == null || c == tsym) c = (ClassSymbol)env.syms.objectType.tsym;
        return env.getClassDoc(c);
    }

    /**
     * Return the superclass of this class.  Return null if this is an
     * interface.  A superclass is represented by either a
     * <code>ClassDoc</code> or a <code>ParameterizedType</code>.
     */
    public com.sun.javadoc.Type superclassType() {
        if (isInterface() || isAnnotationType() ||
                (tsym == env.syms.objectType.tsym))
            return null;
        Type sup = env.types.supertype(type);
        return TypeMaker.getType(env,
527
                                 (sup.hasTag(TypeTag.NONE)) ? env.syms.objectType : sup);
D
duke 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    }

    /**
     * Test whether this class is a subclass of the specified class.
     *
     * @param cd the candidate superclass.
     * @return true if cd is a superclass of this class.
     */
    public boolean subclassOf(ClassDoc cd) {
        return tsym.isSubClass(((ClassDocImpl)cd).tsym, env.types);
    }

    /**
     * Return interfaces implemented by this class or interfaces
     * extended by this interface.
     *
     * @return An array of ClassDocImpl representing the interfaces.
     * Return an empty array if there are no interfaces.
     */
    public ClassDoc[] interfaces() {
        ListBuffer<ClassDocImpl> ta = new ListBuffer<ClassDocImpl>();
        for (Type t : env.types.interfaces(type)) {
            ta.append(env.getClassDoc((ClassSymbol)t.tsym));
        }
        //### Cache ta here?
        return ta.toArray(new ClassDocImpl[ta.length()]);
    }

    /**
     * Return interfaces implemented by this class or interfaces extended
     * by this interface. Includes only directly-declared interfaces, not
     * inherited interfaces.
     * Return an empty array if there are no interfaces.
     */
    public com.sun.javadoc.Type[] interfaceTypes() {
        //### Cache result here?
        return TypeMaker.getTypes(env, env.types.interfaces(type));
    }

    /**
     * Return fields in class.
     * @param filter include only the included fields if filter==true
     */
    public FieldDoc[] fields(boolean filter) {
        return fields(filter, false);
    }

    /**
     * Return included fields in class.
     */
    public FieldDoc[] fields() {
        return fields(true, false);
    }

    /**
     * Return the enum constants if this is an enum type.
     */
    public FieldDoc[] enumConstants() {
        return fields(false, true);
    }

    /**
     * Return fields in class.
     * @param filter  if true, return only the included fields
     * @param enumConstants  if true, return the enum constants instead
     */
    private FieldDoc[] fields(boolean filter, boolean enumConstants) {
        List<FieldDocImpl> fields = List.nil();
        for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
            if (e.sym != null && e.sym.kind == VAR) {
                VarSymbol s = (VarSymbol)e.sym;
                boolean isEnum = ((s.flags() & Flags.ENUM) != 0) &&
                                 !env.legacyDoclet;
                if (isEnum == enumConstants &&
                        (!filter || env.shouldDocument(s))) {
                    fields = fields.prepend(env.getFieldDoc(s));
                }
            }
        }
        return fields.toArray(new FieldDocImpl[fields.length()]);
    }

    /**
     * Return methods in class.
     * This method is overridden by AnnotationTypeDocImpl.
     *
     * @param filter include only the included methods if filter==true
     * @return an array of MethodDocImpl for representing the visible
     * methods in this class.  Does not include constructors.
     */
    public MethodDoc[] methods(boolean filter) {
619
        Names names = tsym.name.table.names;
D
duke 已提交
620 621
        List<MethodDocImpl> methods = List.nil();
        for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
622 623 624 625
            if (e.sym != null
                && e.sym.kind == Kinds.MTH
                && e.sym.name != names.init
                && e.sym.name != names.clinit) {
D
duke 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
                MethodSymbol s = (MethodSymbol)e.sym;
                if (!filter || env.shouldDocument(s)) {
                    methods = methods.prepend(env.getMethodDoc(s));
                }
            }
        }
        //### Cache methods here?
        return methods.toArray(new MethodDocImpl[methods.length()]);
    }

    /**
     * Return included methods in class.
     *
     * @return an array of MethodDocImpl for representing the visible
     * methods in this class.  Does not include constructors.
     */
    public MethodDoc[] methods() {
        return methods(true);
    }

    /**
     * Return constructors in class.
     *
     * @param filter include only the included constructors if filter==true
     * @return an array of ConstructorDocImpl for representing the visible
     * constructors in this class.
     */
    public ConstructorDoc[] constructors(boolean filter) {
654
        Names names = tsym.name.table.names;
D
duke 已提交
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
        List<ConstructorDocImpl> constructors = List.nil();
        for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
            if (e.sym != null &&
                e.sym.kind == Kinds.MTH && e.sym.name == names.init) {
                MethodSymbol s = (MethodSymbol)e.sym;
                if (!filter || env.shouldDocument(s)) {
                    constructors = constructors.prepend(env.getConstructorDoc(s));
                }
            }
        }
        //### Cache constructors here?
        return constructors.toArray(new ConstructorDocImpl[constructors.length()]);
    }

    /**
     * Return included constructors in class.
     *
     * @return an array of ConstructorDocImpl for representing the visible
     * constructors in this class.
     */
    public ConstructorDoc[] constructors() {
        return constructors(true);
    }

    /**
     * Adds all inner classes of this class, and their
     * inner classes recursively, to the list l.
     */
    void addAllClasses(ListBuffer<ClassDocImpl> l, boolean filtered) {
        try {
            if (isSynthetic()) return;
            // sometimes synthetic classes are not marked synthetic
            if (!JavadocTool.isValidClassName(tsym.name.toString())) return;
            if (filtered && !env.shouldDocument(tsym)) return;
            if (l.contains(this)) return;
            l.append(this);
            List<ClassDocImpl> more = List.nil();
            for (Scope.Entry e = tsym.members().elems; e != null;
                 e = e.sibling) {
                if (e.sym != null && e.sym.kind == Kinds.TYP) {
                    ClassSymbol s = (ClassSymbol)e.sym;
                    ClassDocImpl c = env.getClassDoc(s);
                    if (c.isSynthetic()) continue;
                    if (c != null) more = more.prepend(c);
                }
            }
            // this extra step preserves the ordering from oldjavadoc
            for (; more.nonEmpty(); more=more.tail) {
                more.head.addAllClasses(l, filtered);
            }
        } catch (CompletionFailure e) {
            // quietly ignore completion failures
        }
    }

    /**
     * Return inner classes within this class.
     *
     * @param filter include only the included inner classes if filter==true.
     * @return an array of ClassDocImpl for representing the visible
     * classes defined in this class. Anonymous and local classes
     * are not included.
     */
    public ClassDoc[] innerClasses(boolean filter) {
        ListBuffer<ClassDocImpl> innerClasses = new ListBuffer<ClassDocImpl>();
        for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
            if (e.sym != null && e.sym.kind == Kinds.TYP) {
                ClassSymbol s = (ClassSymbol)e.sym;
                if ((s.flags_field & Flags.SYNTHETIC) != 0) continue;
                if (!filter || env.isVisible(s)) {
                    innerClasses.prepend(env.getClassDoc(s));
                }
            }
        }
        //### Cache classes here?
        return innerClasses.toArray(new ClassDocImpl[innerClasses.length()]);
    }

    /**
     * Return included inner classes within this class.
     *
     * @return an array of ClassDocImpl for representing the visible
     * classes defined in this class. Anonymous and local classes
     * are not included.
     */
    public ClassDoc[] innerClasses() {
        return innerClasses(true);
    }

    /**
     * Find a class within the context of this class.
     * Search order: qualified name, in this class (inner),
     * in this package, in the class imports, in the package
     * imports.
     * Return the ClassDocImpl if found, null if not found.
     */
    //### The specified search order is not the normal rule the
    //### compiler would use.  Leave as specified or change it?
    public ClassDoc findClass(String className) {
        ClassDoc searchResult = searchClass(className);
        if (searchResult == null) {
            ClassDocImpl enclosingClass = (ClassDocImpl)containingClass();
            //Expand search space to include enclosing class.
            while (enclosingClass != null && enclosingClass.containingClass() != null) {
                enclosingClass = (ClassDocImpl)enclosingClass.containingClass();
            }
            searchResult = enclosingClass == null ?
                null : enclosingClass.searchClass(className);
        }
        return searchResult;
    }

    private ClassDoc searchClass(String className) {
768
        Names names = tsym.name.table.names;
D
duke 已提交
769 770 771 772 773 774 775 776 777 778

        // search by qualified name first
        ClassDoc cd = env.lookupClass(className);
        if (cd != null) {
            return cd;
        }

        // search inner classes
        //### Add private entry point to avoid creating array?
        //### Replicate code in innerClasses here to avoid consing?
779 780 781 782 783 784 785 786
        for (ClassDoc icd : innerClasses()) {
            if (icd.name().equals(className) ||
                    //### This is from original javadoc but it looks suspicious to me...
                    //### I believe it is attempting to compensate for the confused
                    //### convention of including the nested class qualifiers in the
                    //### 'name' of the inner class, rather than the true simple name.
                    icd.name().endsWith("." + className)) {
                return icd;
D
duke 已提交
787
            } else {
788
                ClassDoc innercd = ((ClassDocImpl) icd).searchClass(className);
D
duke 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
                if (innercd != null) {
                    return innercd;
                }
            }
        }

        // check in this package
        cd = containingPackage().findClass(className);
        if (cd != null) {
            return cd;
        }

        // make sure that this symbol has been completed
        if (tsym.completer != null) {
            tsym.complete();
        }

        // search imports

        if (tsym.sourcefile != null) {

            //### This information is available only for source classes.

            Env<AttrContext> compenv = env.enter.getEnv(tsym);
            if (compenv == null) return null;

            Scope s = compenv.toplevel.namedImportScope;
            for (Scope.Entry e = s.lookup(names.fromString(className)); e.scope != null; e = e.next()) {
                if (e.sym.kind == Kinds.TYP) {
                    ClassDoc c = env.getClassDoc((ClassSymbol)e.sym);
                    return c;
                }
            }

            s = compenv.toplevel.starImportScope;
            for (Scope.Entry e = s.lookup(names.fromString(className)); e.scope != null; e = e.next()) {
                if (e.sym.kind == Kinds.TYP) {
                    ClassDoc c = env.getClassDoc((ClassSymbol)e.sym);
                    return c;
                }
            }
        }

        return null; // not found
    }


    private boolean hasParameterTypes(MethodSymbol method, String[] argTypes) {

        if (argTypes == null) {
            // wildcard
            return true;
        }

        int i = 0;
        List<Type> types = method.type.getParameterTypes();

        if (argTypes.length != types.length()) {
            return false;
        }

        for (Type t : types) {
            String argType = argTypes[i++];
            // For vararg method, "T..." matches type T[].
            if (i == argTypes.length) {
                argType = argType.replace("...", "[]");
            }
            if (!hasTypeName(env.types.erasure(t), argType)) {  //###(gj)
                return false;
            }
        }
        return true;
    }
    // where
    private boolean hasTypeName(Type t, String name) {
        return
            name.equals(TypeMaker.getTypeName(t, true))
            ||
            name.equals(TypeMaker.getTypeName(t, false))
            ||
            (qualifiedName() + "." + name).equals(TypeMaker.getTypeName(t, true));
    }



    /**
     * Find a method in this class scope.
     * Search order: this class, interfaces, superclasses, outerclasses.
     * Note that this is not necessarily what the compiler would do!
     *
     * @param methodName the unqualified name to search for.
880
     * @param paramTypes the array of Strings for method parameter types.
D
duke 已提交
881 882 883 884 885 886 887 888 889 890 891 892
     * @return the first MethodDocImpl which matches, null if not found.
     */
    public MethodDocImpl findMethod(String methodName, String[] paramTypes) {
        // Use hash table 'searched' to avoid searching same class twice.
        //### It is not clear how this could happen.
        return searchMethod(methodName, paramTypes, new HashSet<ClassDocImpl>());
    }

    private MethodDocImpl searchMethod(String methodName,
                                       String[] paramTypes, Set<ClassDocImpl> searched) {
        //### Note that this search is not necessarily what the compiler would do!

893 894 895 896 897 898
        Names names = tsym.name.table.names;
        // do not match constructors
        if (names.init.contentEquals(methodName)) {
            return null;
        }

D
duke 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
        ClassDocImpl cdi;
        MethodDocImpl mdi;

        if (searched.contains(this)) {
            return null;
        }
        searched.add(this);

        //DEBUG
        /*---------------------------------*
         System.out.print("searching " + this + " for " + methodName);
         if (paramTypes == null) {
         System.out.println("()");
         } else {
         System.out.print("(");
         for (int k=0; k < paramTypes.length; k++) {
         System.out.print(paramTypes[k]);
         if ((k + 1) < paramTypes.length) {
         System.out.print(", ");
         }
         }
         System.out.println(")");
         }
         *---------------------------------*/

        // search current class
        Scope.Entry e = tsym.members().lookup(names.fromString(methodName));

        //### Using modifier filter here isn't really correct,
        //### but emulates the old behavior.  Instead, we should
        //### apply the normal rules of visibility and inheritance.

        if (paramTypes == null) {
            // If no parameters specified, we are allowed to return
            // any method with a matching name.  In practice, the old
            // code returned the first method, which is now the last!
            // In order to provide textually identical results, we
            // attempt to emulate the old behavior.
            MethodSymbol lastFound = null;
            for (; e.scope != null; e = e.next()) {
                if (e.sym.kind == Kinds.MTH) {
                    //### Should intern methodName as Name.
                    if (e.sym.name.toString().equals(methodName)) {
                        lastFound = (MethodSymbol)e.sym;
                    }
                }
            }
            if (lastFound != null) {
                return env.getMethodDoc(lastFound);
            }
        } else {
            for (; e.scope != null; e = e.next()) {
                if (e.sym != null &&
                    e.sym.kind == Kinds.MTH) {
                    //### Should intern methodName as Name.
                    if (hasParameterTypes((MethodSymbol)e.sym, paramTypes)) {
                        return env.getMethodDoc((MethodSymbol)e.sym);
                    }
                }
            }
        }

        //### If we found a MethodDoc above, but which did not pass
        //### the modifier filter, we should return failure here!

        // search superclass
        cdi = (ClassDocImpl)superclass();
        if (cdi != null) {
            mdi = cdi.searchMethod(methodName, paramTypes, searched);
            if (mdi != null) {
                return mdi;
            }
        }

        // search interfaces
        ClassDoc intf[] = interfaces();
        for (int i = 0; i < intf.length; i++) {
            cdi = (ClassDocImpl)intf[i];
            mdi = cdi.searchMethod(methodName, paramTypes, searched);
            if (mdi != null) {
                return mdi;
            }
        }

        // search enclosing class
        cdi = (ClassDocImpl)containingClass();
        if (cdi != null) {
            mdi = cdi.searchMethod(methodName, paramTypes, searched);
            if (mdi != null) {
                return mdi;
            }
        }

        //###(gj) As a temporary measure until type variables are better
        //### handled, try again without the parameter types.
        //### This should most often find the right method, and occassionally
        //### find the wrong one.
        //if (paramTypes != null) {
        //    return findMethod(methodName, null);
        //}

        return null;
    }

    /**
     * Find constructor in this class.
     *
     * @param constrName the unqualified name to search for.
1007
     * @param paramTypes the array of Strings for constructor parameters.
D
duke 已提交
1008 1009 1010 1011
     * @return the first ConstructorDocImpl which matches, null if not found.
     */
    public ConstructorDoc findConstructor(String constrName,
                                          String[] paramTypes) {
1012
        Names names = tsym.name.table.names;
D
duke 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
        for (Scope.Entry e = tsym.members().lookup(names.fromString("<init>")); e.scope != null; e = e.next()) {
            if (e.sym.kind == Kinds.MTH) {
                if (hasParameterTypes((MethodSymbol)e.sym, paramTypes)) {
                    return env.getConstructorDoc((MethodSymbol)e.sym);
                }
            }
        }

        //###(gj) As a temporary measure until type variables are better
        //### handled, try again without the parameter types.
        //### This will often find the right constructor, and occassionally
        //### find the wrong one.
        //if (paramTypes != null) {
        //    return findConstructor(constrName, null);
        //}

        return null;
    }

    /**
     * Find a field in this class scope.
     * Search order: this class, outerclasses, interfaces,
     * superclasses. IMP: If see tag is defined in an inner class,
     * which extends a super class and if outerclass and the super
     * class have a visible field in common then Java compiler cribs
     * about the ambiguity, but the following code will search in the
     * above given search order.
     *
     * @param fieldName the unqualified name to search for.
     * @return the first FieldDocImpl which matches, null if not found.
     */
    public FieldDoc findField(String fieldName) {
        return searchField(fieldName, new HashSet<ClassDocImpl>());
    }

    private FieldDocImpl searchField(String fieldName, Set<ClassDocImpl> searched) {
1049
        Names names = tsym.name.table.names;
D
duke 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        if (searched.contains(this)) {
            return null;
        }
        searched.add(this);

        for (Scope.Entry e = tsym.members().lookup(names.fromString(fieldName)); e.scope != null; e = e.next()) {
            if (e.sym.kind == Kinds.VAR) {
                //### Should intern fieldName as Name.
                return env.getFieldDoc((VarSymbol)e.sym);
            }
        }

        //### If we found a FieldDoc above, but which did not pass
        //### the modifier filter, we should return failure here!

        ClassDocImpl cdi = (ClassDocImpl)containingClass();
        if (cdi != null) {
            FieldDocImpl fdi = cdi.searchField(fieldName, searched);
            if (fdi != null) {
                return fdi;
            }
        }

        // search superclass
        cdi = (ClassDocImpl)superclass();
        if (cdi != null) {
            FieldDocImpl fdi = cdi.searchField(fieldName, searched);
            if (fdi != null) {
                return fdi;
            }
        }

        // search interfaces
        ClassDoc intf[] = interfaces();
        for (int i = 0; i < intf.length; i++) {
            cdi = (ClassDocImpl)intf[i];
            FieldDocImpl fdi = cdi.searchField(fieldName, searched);
            if (fdi != null) {
                return fdi;
            }
        }

        return null;
    }

    /**
     * Get the list of classes declared as imported.
     * These are called "single-type-import declarations" in the JLS.
     * This method is deprecated in the ClassDoc interface.
     *
     * @return an array of ClassDocImpl representing the imported classes.
     *
     * @deprecated  Import declarations are implementation details that
     *          should not be exposed here.  In addition, not all imported
     *          classes are imported through single-type-import declarations.
     */
    @Deprecated
    public ClassDoc[] importedClasses() {
        // information is not available for binary classfiles
        if (tsym.sourcefile == null) return new ClassDoc[0];

        ListBuffer<ClassDocImpl> importedClasses = new ListBuffer<ClassDocImpl>();

        Env<AttrContext> compenv = env.enter.getEnv(tsym);
        if (compenv == null) return new ClassDocImpl[0];

1116
        Name asterisk = tsym.name.table.names.asterisk;
D
duke 已提交
1117
        for (JCTree t : compenv.toplevel.defs) {
1118
            if (t.hasTag(IMPORT)) {
D
duke 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
                JCTree imp = ((JCImport) t).qualid;
                if ((TreeInfo.name(imp) != asterisk) &&
                        (imp.type.tsym.kind & Kinds.TYP) != 0) {
                    importedClasses.append(
                            env.getClassDoc((ClassSymbol)imp.type.tsym));
                }
            }
        }

        return importedClasses.toArray(new ClassDocImpl[importedClasses.length()]);
    }

    /**
     * Get the list of packages declared as imported.
     * These are called "type-import-on-demand declarations" in the JLS.
     * This method is deprecated in the ClassDoc interface.
     *
     * @return an array of PackageDocImpl representing the imported packages.
     *
     * ###NOTE: the syntax supports importing all inner classes from a class as well.
     * @deprecated  Import declarations are implementation details that
     *          should not be exposed here.  In addition, this method's
     *          return type does not allow for all type-import-on-demand
     *          declarations to be returned.
     */
    @Deprecated
    public PackageDoc[] importedPackages() {
        // information is not available for binary classfiles
        if (tsym.sourcefile == null) return new PackageDoc[0];

        ListBuffer<PackageDocImpl> importedPackages = new ListBuffer<PackageDocImpl>();

        //### Add the implicit "import java.lang.*" to the result
1152
        Names names = tsym.name.table.names;
D
duke 已提交
1153 1154 1155 1156 1157 1158
        importedPackages.append(env.getPackageDoc(env.reader.enterPackage(names.java_lang)));

        Env<AttrContext> compenv = env.enter.getEnv(tsym);
        if (compenv == null) return new PackageDocImpl[0];

        for (JCTree t : compenv.toplevel.defs) {
1159
            if (t.hasTag(IMPORT)) {
D
duke 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
                JCTree imp = ((JCImport) t).qualid;
                if (TreeInfo.name(imp) == names.asterisk) {
                    JCFieldAccess sel = (JCFieldAccess)imp;
                    Symbol s = sel.selected.type.tsym;
                    PackageDocImpl pdoc = env.getPackageDoc(s.packge());
                    if (!importedPackages.contains(pdoc))
                        importedPackages.append(pdoc);
                }
            }
        }

        return importedPackages.toArray(new PackageDocImpl[importedPackages.length()]);
    }

    /**
     * Return the type's dimension information.
     * Always return "", as this is not an array type.
     */
    public String dimension() {
        return "";
    }

    /**
     * Return this type as a class, which it already is.
     */
    public ClassDoc asClassDoc() {
        return this;
    }

    /**
     * Return null (unless overridden), as this is not an annotation type.
     */
    public AnnotationTypeDoc asAnnotationTypeDoc() {
        return null;
    }

    /**
     * Return null, as this is not a class instantiation.
     */
    public ParameterizedType asParameterizedType() {
        return null;
    }

    /**
     * Return null, as this is not a type variable.
     */
    public TypeVariable asTypeVariable() {
        return null;
    }

    /**
     * Return null, as this is not a wildcard type.
     */
    public WildcardType asWildcardType() {
        return null;
    }

J
jjg 已提交
1217 1218 1219 1220 1221 1222 1223
    /**
     * Returns null, as this is not an annotated type.
     */
    public AnnotatedType asAnnotatedType() {
        return null;
    }

D
duke 已提交
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
    /**
     * Return false, as this is not a primitive type.
     */
    public boolean isPrimitive() {
        return false;
    }

    //--- Serialization ---

    //### These methods ignore modifier filter.

    /**
     * Return true if this class implements <code>java.io.Serializable</code>.
     *
     * Since <code>java.io.Externalizable</code> extends
     * <code>java.io.Serializable</code>,
     * Externalizable objects are also Serializable.
     */
    public boolean isSerializable() {
        try {
            return env.types.isSubtype(type, env.syms.serializableType);
        } catch (CompletionFailure ex) {
            // quietly ignore completion failures
            return false;
        }
    }

    /**
     * Return true if this class implements
     * <code>java.io.Externalizable</code>.
     */
    public boolean isExternalizable() {
        try {
            return env.types.isSubtype(type, env.externalizableSym.type);
        } catch (CompletionFailure ex) {
            // quietly ignore completion failures
            return false;
        }
    }

    /**
     * Return the serialization methods for this class.
     *
     * @return an array of <code>MethodDocImpl</code> that represents
     * the serialization methods for this class.
     */
    public MethodDoc[] serializationMethods() {
        if (serializedForm == null) {
            serializedForm = new SerializedForm(env, tsym, this);
        }
        //### Clone this?
        return serializedForm.methods();
    }

    /**
     * Return the Serializable fields of class.<p>
     *
     * Return either a list of default fields documented by
     * <code>serial</code> tag<br>
     * or return a single <code>FieldDoc</code> for
     * <code>serialPersistentField</code> member.
     * There should be a <code>serialField</code> tag for
     * each Serializable field defined by an <code>ObjectStreamField</code>
     * array component of <code>serialPersistentField</code>.
     *
     * @returns an array of <code>FieldDoc</code> for the Serializable fields
     * of this class.
     *
     * @see #definesSerializableFields()
     * @see SerialFieldTagImpl
     */
    public FieldDoc[] serializableFields() {
        if (serializedForm == null) {
            serializedForm = new SerializedForm(env, tsym, this);
        }
        //### Clone this?
        return serializedForm.fields();
    }

    /**
     * Return true if Serializable fields are explicitly defined with
     * the special class member <code>serialPersistentFields</code>.
     *
     * @see #serializableFields()
     * @see SerialFieldTagImpl
     */
    public boolean definesSerializableFields() {
        if (!isSerializable() || isExternalizable()) {
            return false;
        } else {
            if (serializedForm == null) {
                serializedForm = new SerializedForm(env, tsym, this);
            }
            //### Clone this?
            return serializedForm.definesSerializableFields();
        }
    }

    /**
     * Determine if a class is a RuntimeException.
     * <p>
     * Used only by ThrowsTagImpl.
     */
    boolean isRuntimeException() {
        return tsym.isSubClass(env.syms.runtimeExceptionType.tsym, env.types);
    }

    /**
     * Return the source position of the entity, or null if
     * no position is available.
     */
1335
    @Override
D
duke 已提交
1336 1337
    public SourcePosition position() {
        if (tsym.sourcefile == null) return null;
1338
        return SourcePositionImpl.make(tsym.sourcefile,
D
duke 已提交
1339 1340 1341 1342
                                       (tree==null) ? Position.NOPOS : tree.pos,
                                       lineMap);
    }
}