1 /*
   2  * Copyright (c) 1999, 2018, 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 
  26 package jdk.javadoc.internal.doclets.toolkit.util;
  27 
  28 import java.lang.annotation.Documented;
  29 import java.lang.ref.SoftReference;
  30 import java.net.URI;
  31 import java.text.CollationKey;
  32 import java.text.Collator;
  33 import java.text.ParseException;
  34 import java.text.RuleBasedCollator;
  35 import java.util.*;
  36 import java.util.AbstractMap.SimpleEntry;
  37 import java.util.Map.Entry;
  38 import java.util.stream.Collectors;
  39 
  40 import javax.lang.model.SourceVersion;
  41 import javax.lang.model.element.AnnotationMirror;
  42 import javax.lang.model.element.AnnotationValue;
  43 import javax.lang.model.element.Element;
  44 import javax.lang.model.element.ElementKind;
  45 import javax.lang.model.element.ExecutableElement;
  46 import javax.lang.model.element.Modifier;
  47 import javax.lang.model.element.ModuleElement;
  48 import javax.lang.model.element.ModuleElement.RequiresDirective;
  49 import javax.lang.model.element.PackageElement;
  50 import javax.lang.model.element.TypeElement;
  51 import javax.lang.model.element.TypeParameterElement;
  52 import javax.lang.model.element.VariableElement;
  53 import javax.lang.model.type.ArrayType;
  54 import javax.lang.model.type.DeclaredType;
  55 import javax.lang.model.type.ErrorType;
  56 import javax.lang.model.type.ExecutableType;
  57 import javax.lang.model.type.NoType;
  58 import javax.lang.model.type.PrimitiveType;
  59 import javax.lang.model.type.TypeMirror;
  60 import javax.lang.model.type.TypeVariable;
  61 import javax.lang.model.type.WildcardType;
  62 import javax.lang.model.util.ElementFilter;
  63 import javax.lang.model.util.ElementKindVisitor9;
  64 import javax.lang.model.util.Elements;
  65 import javax.lang.model.util.SimpleElementVisitor9;
  66 import javax.lang.model.util.SimpleTypeVisitor9;
  67 import javax.lang.model.util.TypeKindVisitor9;
  68 import javax.lang.model.util.Types;
  69 import javax.tools.FileObject;
  70 import javax.tools.JavaFileManager;
  71 import javax.tools.JavaFileManager.Location;
  72 import javax.tools.StandardLocation;
  73 
  74 import com.sun.source.doctree.DocCommentTree;
  75 import com.sun.source.doctree.DocTree;
  76 import com.sun.source.doctree.DocTree.Kind;
  77 import com.sun.source.doctree.ParamTree;
  78 import com.sun.source.doctree.SerialFieldTree;
  79 import com.sun.source.tree.CompilationUnitTree;
  80 import com.sun.source.tree.LineMap;
  81 import com.sun.source.util.DocSourcePositions;
  82 import com.sun.source.util.DocTrees;
  83 import com.sun.source.util.TreePath;
  84 import com.sun.tools.javac.model.JavacTypes;
  85 import jdk.javadoc.internal.doclets.formats.html.SearchIndexItem;
  86 import jdk.javadoc.internal.doclets.toolkit.BaseConfiguration;
  87 import jdk.javadoc.internal.doclets.toolkit.CommentUtils.DocCommentDuo;
  88 import jdk.javadoc.internal.doclets.toolkit.Messages;
  89 import jdk.javadoc.internal.doclets.toolkit.Resources;
  90 import jdk.javadoc.internal.doclets.toolkit.WorkArounds;
  91 import jdk.javadoc.internal.tool.DocEnvImpl;
  92 
  93 import static javax.lang.model.element.ElementKind.*;
  94 import static javax.lang.model.element.Modifier.*;
  95 import static javax.lang.model.type.TypeKind.*;
  96 
  97 import static com.sun.source.doctree.DocTree.Kind.*;
  98 import static jdk.javadoc.internal.doclets.toolkit.builders.ConstantsSummaryBuilder.MAX_CONSTANT_VALUE_INDEX_LENGTH;
  99 
 100 /**
 101  * Utilities Class for Doclets.
 102  *
 103  *  <p><b>This is NOT part of any supported API.
 104  *  If you write code that depends on this, you do so at your own risk.
 105  *  This code and its internal interfaces are subject to change or
 106  *  deletion without notice.</b>
 107  *
 108  * @author Atul M Dambalkar
 109  * @author Jamie Ho
 110  */
 111 public class Utils {
 112     public final BaseConfiguration configuration;
 113     public final Messages messages;
 114     public final Resources resources;
 115     public final DocTrees docTrees;
 116     public final Elements elementUtils;
 117     public final Types typeUtils;
 118     public final JavaScriptScanner javaScriptScanner;
 119 
 120     public Utils(BaseConfiguration c) {
 121         configuration = c;
 122         messages = configuration.getMessages();
 123         resources = configuration.getResources();
 124         elementUtils = c.docEnv.getElementUtils();
 125         typeUtils = c.docEnv.getTypeUtils();
 126         docTrees = c.docEnv.getDocTrees();
 127         javaScriptScanner = c.isAllowScriptInComments() ? null : new JavaScriptScanner();
 128     }
 129 
 130     // our own little symbol table
 131     private HashMap<String, TypeMirror> symtab = new HashMap<>();
 132 
 133     public TypeMirror getSymbol(String signature) {
 134         TypeMirror type = symtab.get(signature);
 135         if (type == null) {
 136             TypeElement typeElement = elementUtils.getTypeElement(signature);
 137             if (typeElement == null)
 138                 return null;
 139             type = typeElement.asType();
 140             if (type == null)
 141                 return null;
 142             symtab.put(signature, type);
 143         }
 144         return type;
 145     }
 146 
 147     public TypeMirror getObjectType() {
 148         return getSymbol("java.lang.Object");
 149     }
 150 
 151     public TypeMirror getExceptionType() {
 152         return getSymbol("java.lang.Exception");
 153     }
 154 
 155     public TypeMirror getErrorType() {
 156         return getSymbol("java.lang.Error");
 157     }
 158 
 159     public TypeMirror getSerializableType() {
 160         return getSymbol("java.io.Serializable");
 161     }
 162 
 163     public TypeMirror getExternalizableType() {
 164         return getSymbol("java.io.Externalizable");
 165     }
 166 
 167     public TypeMirror getIllegalArgumentExceptionType() {
 168         return getSymbol("java.lang.IllegalArgumentException");
 169     }
 170 
 171     public TypeMirror getNullPointerExceptionType() {
 172         return getSymbol("java.lang.NullPointerException");
 173     }
 174 
 175     public TypeMirror getDeprecatedType() {
 176         return getSymbol("java.lang.Deprecated");
 177     }
 178 
 179     public TypeMirror getFunctionalInterface() {
 180         return getSymbol("java.lang.FunctionalInterface");
 181     }
 182 
 183     /**
 184      * Return array of class members whose documentation is to be generated.
 185      * If the member is deprecated do not include such a member in the
 186      * returned array.
 187      *
 188      * @param  members    Array of members to choose from.
 189      * @return List       List of eligible members for whom
 190      *                    documentation is getting generated.
 191      */
 192     public List<Element> excludeDeprecatedMembers(List<? extends Element> members) {
 193         List<Element> excludeList = members.stream()
 194                 .filter((member) -> (!isDeprecated(member)))
 195                 .sorted(makeGeneralPurposeComparator())
 196                 .collect(Collectors.<Element, List<Element>>toCollection(ArrayList::new));
 197         return excludeList;
 198     }
 199 
 200     /**
 201      * Search for the given method in the given class.
 202      *
 203      * @param  te        Class to search into.
 204      * @param  method    Method to be searched.
 205      * @return ExecutableElement Method found, null otherwise.
 206      */
 207     public ExecutableElement findMethod(TypeElement te, ExecutableElement method) {
 208         for (Element m : getMethods(te)) {
 209             if (executableMembersEqual(method, (ExecutableElement)m)) {
 210                 return (ExecutableElement)m;
 211             }
 212         }
 213         return null;
 214     }
 215 
 216     /**
 217      * Test whether a class is a subclass of another class.
 218      *
 219      * @param t1 the candidate superclass.
 220      * @param t2 the target
 221      * @return true if t1 is a superclass of t2.
 222      */
 223     public boolean isSubclassOf(TypeElement t1, TypeElement t2) {
 224         return typeUtils.isSubtype(t1.asType(), t2.asType());
 225     }
 226 
 227     /**
 228      * @param e1 the first method to compare.
 229      * @param e2 the second method to compare.
 230      * @return true if member1 overrides/hides or is overriden/hidden by member2.
 231      */
 232 
 233     public boolean executableMembersEqual(ExecutableElement e1, ExecutableElement e2) {
 234         // TODO: investigate if Elements.hides(..) will work here.
 235         if (isStatic(e1) && isStatic(e2)) {
 236             List<? extends VariableElement> parameters1 = e1.getParameters();
 237             List<? extends VariableElement> parameters2 = e2.getParameters();
 238             if (e1.getSimpleName().equals(e2.getSimpleName()) &&
 239                     parameters1.size() == parameters2.size()) {
 240                 int j;
 241                 for (j = 0 ; j < parameters1.size(); j++) {
 242                     VariableElement v1 = parameters1.get(j);
 243                     VariableElement v2 = parameters2.get(j);
 244                     String t1 = getTypeName(v1.asType(), true);
 245                     String t2 = getTypeName(v2.asType(), true);
 246                     if (!(t1.equals(t2) ||
 247                             isTypeVariable(v1.asType()) || isTypeVariable(v2.asType()))) {
 248                         break;
 249                     }
 250                 }
 251                 if (j == parameters1.size()) {
 252                 return true;
 253                 }
 254             }
 255             return false;
 256         } else {
 257             return elementUtils.overrides(e1, e2, getEnclosingTypeElement(e1)) ||
 258                     elementUtils.overrides(e2, e1, getEnclosingTypeElement(e2)) ||
 259                     e1.equals(e2);
 260         }
 261     }
 262 
 263     /**
 264      * According to
 265      * <cite>The Java&trade; Language Specification</cite>,
 266      * all the outer classes and static inner classes are core classes.
 267      */
 268     public boolean isCoreClass(TypeElement e) {
 269         return getEnclosingTypeElement(e) == null || isStatic(e);
 270     }
 271 
 272     public Location getLocationForPackage(PackageElement pd) {
 273         ModuleElement mdle = configuration.docEnv.getElementUtils().getModuleOf(pd);
 274 
 275         if (mdle == null)
 276             return defaultLocation();
 277 
 278         return getLocationForModule(mdle);
 279     }
 280 
 281     public Location getLocationForModule(ModuleElement mdle) {
 282         Location loc = configuration.workArounds.getLocationForModule(mdle);
 283         if (loc != null)
 284             return loc;
 285 
 286         return defaultLocation();
 287     }
 288 
 289     private Location defaultLocation() {
 290         JavaFileManager fm = configuration.docEnv.getJavaFileManager();
 291         return fm.hasLocation(StandardLocation.SOURCE_PATH)
 292                 ? StandardLocation.SOURCE_PATH
 293                 : StandardLocation.CLASS_PATH;
 294     }
 295 
 296     public boolean isAnnotated(TypeMirror e) {
 297         return !e.getAnnotationMirrors().isEmpty();
 298     }
 299 
 300     public boolean isAnnotated(Element e) {
 301         return !e.getAnnotationMirrors().isEmpty();
 302     }
 303 
 304     public boolean isAnnotationType(Element e) {
 305         return new SimpleElementVisitor9<Boolean, Void>() {
 306             @Override
 307             public Boolean visitExecutable(ExecutableElement e, Void p) {
 308                 return visit(e.getEnclosingElement());
 309             }
 310 
 311             @Override
 312             public Boolean visitUnknown(Element e, Void p) {
 313                 return false;
 314             }
 315 
 316             @Override
 317             protected Boolean defaultAction(Element e, Void p) {
 318                 return e.getKind() == ANNOTATION_TYPE;
 319             }
 320         }.visit(e);
 321     }
 322 
 323     /**
 324      * An Enum implementation is almost identical, thus this method returns if
 325      * this element represents a CLASS or an ENUM
 326      * @param e element
 327      * @return true if class or enum
 328      */
 329     public boolean isClass(Element e) {
 330         return e.getKind().isClass();
 331     }
 332 
 333     public boolean isConstructor(Element e) {
 334          return e.getKind() == CONSTRUCTOR;
 335     }
 336 
 337     public boolean isEnum(Element e) {
 338         return e.getKind() == ENUM;
 339     }
 340 
 341     boolean isEnumConstant(Element e) {
 342         return e.getKind() == ENUM_CONSTANT;
 343     }
 344 
 345     public boolean isField(Element e) {
 346         return e.getKind() == FIELD;
 347     }
 348 
 349     public boolean isInterface(Element e) {
 350         return e.getKind() == INTERFACE;
 351     }
 352 
 353     public boolean isMethod(Element e) {
 354         return e.getKind() == METHOD;
 355     }
 356 
 357     public boolean isModule(Element e) {
 358         return e.getKind() == ElementKind.MODULE;
 359     }
 360 
 361     public boolean isPackage(Element e) {
 362         return e.getKind() == ElementKind.PACKAGE;
 363     }
 364 
 365     public boolean isAbstract(Element e) {
 366         return e.getModifiers().contains(Modifier.ABSTRACT);
 367     }
 368 
 369     public boolean isDefault(Element e) {
 370         return e.getModifiers().contains(Modifier.DEFAULT);
 371     }
 372 
 373     public boolean isPackagePrivate(Element e) {
 374         return !(isPublic(e) || isPrivate(e) || isProtected(e));
 375     }
 376 
 377     public boolean isPrivate(Element e) {
 378         return e.getModifiers().contains(Modifier.PRIVATE);
 379     }
 380 
 381     public boolean isProtected(Element e) {
 382         return e.getModifiers().contains(Modifier.PROTECTED);
 383     }
 384 
 385     public boolean isPublic(Element e) {
 386         return e.getModifiers().contains(Modifier.PUBLIC);
 387     }
 388 
 389     public boolean isProperty(String name) {
 390         return configuration.javafx && name.endsWith("Property");
 391     }
 392 
 393     public String getPropertyName(String name) {
 394         return isProperty(name)
 395                 ? name.substring(0, name.length() - "Property".length())
 396                 : name;
 397     }
 398 
 399     public String getPropertyLabel(String name) {
 400         return name.substring(0, name.lastIndexOf("Property"));
 401     }
 402 
 403     public boolean isOverviewElement(Element e) {
 404         return e.getKind() == ElementKind.OTHER;
 405     }
 406 
 407     public boolean isStatic(Element e) {
 408         return e.getModifiers().contains(Modifier.STATIC);
 409     }
 410 
 411     public boolean isSerializable(TypeElement e) {
 412         return typeUtils.isSubtype(e.asType(), getSerializableType());
 413     }
 414 
 415     public boolean isExternalizable(TypeElement e) {
 416         return typeUtils.isSubtype(e.asType(), getExternalizableType());
 417     }
 418 
 419     public SortedSet<VariableElement> serializableFields(TypeElement aclass) {
 420         return configuration.workArounds.getSerializableFields(this, aclass);
 421     }
 422 
 423     public SortedSet<ExecutableElement> serializationMethods(TypeElement aclass) {
 424         return configuration.workArounds.getSerializationMethods(this, aclass);
 425     }
 426 
 427     public boolean definesSerializableFields(TypeElement aclass) {
 428         return configuration.workArounds.definesSerializableFields(this, aclass);
 429     }
 430 
 431     public String modifiersToString(Element e, boolean trailingSpace) {
 432         SortedSet<Modifier> set = new TreeSet<>(e.getModifiers());
 433         set.remove(Modifier.NATIVE);
 434         set.remove(Modifier.STRICTFP);
 435         set.remove(Modifier.SYNCHRONIZED);
 436 
 437         return new ElementKindVisitor9<String, SortedSet<Modifier>>() {
 438             final StringBuilder sb = new StringBuilder();
 439 
 440             void addVisibilityModifier(Set<Modifier> modifiers) {
 441                 if (modifiers.contains(PUBLIC)) {
 442                     sb.append("public").append(" ");
 443                 } else if (modifiers.contains(PROTECTED)) {
 444                     sb.append("protected").append(" ");
 445                 } else if (modifiers.contains(PRIVATE)) {
 446                     sb.append("private").append(" ");
 447                 }
 448             }
 449 
 450             void addStatic(Set<Modifier> modifiers) {
 451                 if (modifiers.contains(STATIC)) {
 452                     sb.append("static").append(" ");
 453                 }
 454             }
 455 
 456             void addModifers(Set<Modifier> modifiers) {
 457                 String s = set.stream().map(Modifier::toString).collect(Collectors.joining(" "));
 458                 sb.append(s);
 459                 if (!s.isEmpty())
 460                     sb.append(" ");
 461             }
 462 
 463             String finalString(String s) {
 464                 sb.append(s);
 465                 if (trailingSpace) {
 466                     if (sb.lastIndexOf(" ") == sb.length() - 1) {
 467                         return sb.toString();
 468                     } else {
 469                         return sb.append(" ").toString();
 470                     }
 471                 } else {
 472                     return sb.toString().trim();
 473                 }
 474             }
 475 
 476             @Override
 477             public String visitTypeAsInterface(TypeElement e, SortedSet<Modifier> p) {
 478                 addVisibilityModifier(p);
 479                 addStatic(p);
 480                 return finalString("interface");
 481             }
 482 
 483             @Override
 484             public String visitTypeAsEnum(TypeElement e, SortedSet<Modifier> p) {
 485                 addVisibilityModifier(p);
 486                 addStatic(p);
 487                 return finalString("enum");
 488             }
 489 
 490             @Override
 491             public String visitTypeAsAnnotationType(TypeElement e, SortedSet<Modifier> p) {
 492                 addVisibilityModifier(p);
 493                 addStatic(p);
 494                 return finalString("@interface");
 495             }
 496 
 497             @Override
 498             public String visitTypeAsClass(TypeElement e, SortedSet<Modifier> p) {
 499                 addModifers(p);
 500                 return finalString("class");
 501             }
 502 
 503             @Override
 504             protected String defaultAction(Element e, SortedSet<Modifier> p) {
 505                 addModifers(p);
 506                 return sb.toString().trim();
 507             }
 508 
 509         }.visit(e, set);
 510     }
 511 
 512     public boolean isFunctionalInterface(AnnotationMirror amirror) {
 513         return amirror.getAnnotationType().equals(getFunctionalInterface()) &&
 514                 configuration.docEnv.getSourceVersion()
 515                         .compareTo(SourceVersion.RELEASE_8) >= 0;
 516     }
 517 
 518     public boolean isNoType(TypeMirror t) {
 519         return t.getKind() == NONE;
 520     }
 521 
 522     public boolean isOrdinaryClass(TypeElement te) {
 523         if (isEnum(te) || isInterface(te) || isAnnotationType(te)) {
 524             return false;
 525         }
 526         if (isError(te) || isException(te)) {
 527             return false;
 528         }
 529         return true;
 530     }
 531 
 532     public boolean isError(TypeElement te) {
 533         if (isEnum(te) || isInterface(te) || isAnnotationType(te)) {
 534             return false;
 535         }
 536         return typeUtils.isSubtype(te.asType(), getErrorType());
 537     }
 538 
 539     public boolean isException(TypeElement te) {
 540         if (isEnum(te) || isInterface(te) || isAnnotationType(te)) {
 541             return false;
 542         }
 543         return typeUtils.isSubtype(te.asType(), getExceptionType());
 544     }
 545 
 546     public boolean isPrimitive(TypeMirror t) {
 547         return new SimpleTypeVisitor9<Boolean, Void>() {
 548 
 549             @Override
 550             public Boolean visitNoType(NoType t, Void p) {
 551                 return t.getKind() == VOID;
 552             }
 553             @Override
 554             public Boolean visitPrimitive(PrimitiveType t, Void p) {
 555                 return true;
 556             }
 557             @Override
 558             public Boolean visitArray(ArrayType t, Void p) {
 559                 return visit(t.getComponentType());
 560             }
 561             @Override
 562             protected Boolean defaultAction(TypeMirror e, Void p) {
 563                 return false;
 564             }
 565         }.visit(t);
 566     }
 567 
 568     public boolean isExecutableElement(Element e) {
 569         ElementKind kind = e.getKind();
 570         switch (kind) {
 571             case CONSTRUCTOR: case METHOD: case INSTANCE_INIT:
 572                 return true;
 573             default:
 574                 return false;
 575         }
 576     }
 577 
 578     public boolean isVariableElement(Element e) {
 579         ElementKind kind = e.getKind();
 580         switch(kind) {
 581               case ENUM_CONSTANT: case EXCEPTION_PARAMETER: case FIELD:
 582               case LOCAL_VARIABLE: case PARAMETER:
 583               case RESOURCE_VARIABLE:
 584                   return true;
 585               default:
 586                   return false;
 587         }
 588     }
 589 
 590     public boolean isTypeElement(Element e) {
 591         switch (e.getKind()) {
 592             case CLASS: case ENUM: case INTERFACE: case ANNOTATION_TYPE:
 593                 return true;
 594             default:
 595                 return false;
 596         }
 597     }
 598 
 599     /**
 600      * Get the signature. It is the parameter list, type is qualified.
 601      * For instance, for a method {@code mymethod(String x, int y)},
 602      * it will return {@code(java.lang.String,int)}.
 603      *
 604      * @param e
 605      * @return String
 606      */
 607     public String signature(ExecutableElement e) {
 608         return makeSignature(e, true);
 609     }
 610 
 611     /**
 612      * Get flat signature.  All types are not qualified.
 613      * Return a String, which is the flat signature of this member.
 614      * It is the parameter list, type is not qualified.
 615      * For instance, for a method {@code mymethod(String x, int y)},
 616      * it will return {@code (String, int)}.
 617      */
 618     public String flatSignature(ExecutableElement e) {
 619         return makeSignature(e, false);
 620     }
 621 
 622     public String makeSignature(ExecutableElement e, boolean full) {
 623         return makeSignature(e, full, false);
 624     }
 625 
 626     public String makeSignature(ExecutableElement e, boolean full, boolean ignoreTypeParameters) {
 627         StringBuilder result = new StringBuilder();
 628         result.append("(");
 629         Iterator<? extends VariableElement> iterator = e.getParameters().iterator();
 630         while (iterator.hasNext()) {
 631             VariableElement next = iterator.next();
 632             TypeMirror type = next.asType();
 633             result.append(getTypeSignature(type, full, ignoreTypeParameters));
 634             if (iterator.hasNext()) {
 635                 result.append(", ");
 636             }
 637         }
 638         if (e.isVarArgs()) {
 639             int len = result.length();
 640             result.replace(len - 2, len, "...");
 641         }
 642         result.append(")");
 643         return result.toString();
 644     }
 645 
 646     public String getTypeSignature(TypeMirror t, boolean qualifiedName, boolean noTypeParameters) {
 647         return new SimpleTypeVisitor9<StringBuilder, Void>() {
 648             final StringBuilder sb = new StringBuilder();
 649 
 650             @Override
 651             public StringBuilder visitArray(ArrayType t, Void p) {
 652                 TypeMirror componentType = t.getComponentType();
 653                 visit(componentType);
 654                 sb.append("[]");
 655                 return sb;
 656             }
 657 
 658             @Override
 659             public StringBuilder visitDeclared(DeclaredType t, Void p) {
 660                 Element e = t.asElement();
 661                 sb.append(qualifiedName ? getFullyQualifiedName(e) : getSimpleName(e));
 662                 List<? extends TypeMirror> typeArguments = t.getTypeArguments();
 663                 if (typeArguments.isEmpty() || noTypeParameters) {
 664                     return sb;
 665                 }
 666                 sb.append("<");
 667                 Iterator<? extends TypeMirror> iterator = typeArguments.iterator();
 668                 while (iterator.hasNext()) {
 669                     TypeMirror ta = iterator.next();
 670                     visit(ta);
 671                     if (iterator.hasNext()) {
 672                         sb.append(", ");
 673                     }
 674                 }
 675                 sb.append(">");
 676                 return sb;
 677             }
 678 
 679             @Override
 680             public StringBuilder visitTypeVariable(javax.lang.model.type.TypeVariable t, Void p) {
 681                 Element e = t.asElement();
 682                 sb.append(qualifiedName ? getFullyQualifiedName(e, false) : getSimpleName(e));
 683                 return sb;
 684             }
 685 
 686             @Override
 687             public StringBuilder visitWildcard(javax.lang.model.type.WildcardType t, Void p) {
 688                 sb.append("?");
 689                 TypeMirror upperBound = t.getExtendsBound();
 690                 if (upperBound != null) {
 691                     sb.append(" extends ");
 692                     visit(upperBound);
 693                 }
 694                 TypeMirror superBound = t.getSuperBound();
 695                 if (superBound != null) {
 696                     sb.append(" super ");
 697                     visit(superBound);
 698                 }
 699                 return sb;
 700             }
 701 
 702             @Override
 703             protected StringBuilder defaultAction(TypeMirror e, Void p) {
 704                 return sb.append(e);
 705             }
 706         }.visit(t).toString();
 707     }
 708 
 709     public boolean isArrayType(TypeMirror t) {
 710         return t.getKind() == ARRAY;
 711     }
 712 
 713     public boolean isDeclaredType(TypeMirror t) {
 714         return t.getKind() == DECLARED;
 715     }
 716 
 717     public boolean isErrorType(TypeMirror t) {
 718         return t.getKind() == ERROR;
 719     }
 720 
 721     public boolean isIntersectionType(TypeMirror t) {
 722         return t.getKind() == INTERSECTION;
 723     }
 724 
 725     public boolean isTypeParameterElement(Element e) {
 726         return e.getKind() == TYPE_PARAMETER;
 727     }
 728 
 729     public boolean isTypeVariable(TypeMirror t) {
 730         return t.getKind() == TYPEVAR;
 731     }
 732 
 733     public boolean isVoid(TypeMirror t) {
 734         return t.getKind() == VOID;
 735     }
 736 
 737     public boolean isWildCard(TypeMirror t) {
 738         return t.getKind() == WILDCARD;
 739     }
 740 
 741     public boolean ignoreBounds(TypeMirror bound) {
 742         return bound.equals(getObjectType()) && !isAnnotated(bound);
 743     }
 744 
 745     /*
 746      * a direct port of TypeVariable.getBounds
 747      */
 748     public List<? extends TypeMirror> getBounds(TypeParameterElement tpe) {
 749         List<? extends TypeMirror> bounds = tpe.getBounds();
 750         if (!bounds.isEmpty()) {
 751             TypeMirror upperBound = bounds.get(bounds.size() - 1);
 752             if (ignoreBounds(upperBound)) {
 753                 return Collections.emptyList();
 754             }
 755         }
 756         return bounds;
 757     }
 758 
 759     /**
 760      * Returns the TypeMirror of the ExecutableElement for all methods,
 761      * a null if constructor.
 762      * @param ee the ExecutableElement
 763      * @return
 764      */
 765     public TypeMirror getReturnType(ExecutableElement ee) {
 766         return ee.getKind() == CONSTRUCTOR ? null : ee.getReturnType();
 767     }
 768 
 769     /**
 770      * Return the type containing the method that this method overrides.
 771      * It may be a {@code TypeElement} or a {@code TypeParameterElement}.
 772      */
 773     public TypeMirror overriddenType(ExecutableElement method) {
 774         return configuration.workArounds.overriddenType(method);
 775     }
 776 
 777     private  TypeMirror getType(TypeMirror t) {
 778         return (isNoType(t)) ? getObjectType() : t;
 779     }
 780 
 781     public TypeMirror getSuperType(TypeElement te) {
 782         TypeMirror t = te.getSuperclass();
 783         return getType(t);
 784     }
 785 
 786     /**
 787      * Return the class that originally defined the method that
 788      * is overridden by the current definition, or null if no
 789      * such class exists.
 790      *
 791      * @return a TypeElement representing the superclass that
 792      * originally defined this method, null if this method does
 793      * not override a definition in a superclass.
 794      */
 795     public TypeElement overriddenClass(ExecutableElement ee) {
 796         TypeMirror type = overriddenType(ee);
 797         return (type != null) ? asTypeElement(type) : null;
 798     }
 799 
 800     public ExecutableElement overriddenMethod(ExecutableElement method) {
 801         if (isStatic(method)) {
 802             return null;
 803         }
 804         final TypeElement origin = getEnclosingTypeElement(method);
 805         for (TypeMirror t = getSuperType(origin);
 806                 t.getKind() == DECLARED;
 807                 t = getSuperType(asTypeElement(t))) {
 808             TypeElement te = asTypeElement(t);
 809             if (te == null) {
 810                 return null;
 811             }
 812             VisibleMemberTable vmt = configuration.getVisibleMemberTable(te);
 813             for (Element e : vmt.getMembers(VisibleMemberTable.Kind.METHODS)) {
 814                 ExecutableElement ee = (ExecutableElement)e;
 815                 if (configuration.workArounds.overrides(method, ee, origin) &&
 816                         !isSimpleOverride(ee)) {
 817                     return ee;
 818                 }
 819             }
 820             if (t.equals(getObjectType()))
 821                 return null;
 822         }
 823         return null;
 824     }
 825 
 826     public SortedSet<TypeElement> getTypeElementsAsSortedSet(Iterable<TypeElement> typeElements) {
 827         SortedSet<TypeElement> set = new TreeSet<>(makeGeneralPurposeComparator());
 828         for (TypeElement te : typeElements) {
 829             set.add(te);
 830         }
 831         return set;
 832     }
 833 
 834     public List<? extends DocTree> getSerialDataTrees(ExecutableElement member) {
 835         return getBlockTags(member, SERIAL_DATA);
 836     }
 837 
 838     public FileObject getFileObject(TypeElement te) {
 839         return docTrees.getPath(te).getCompilationUnit().getSourceFile();
 840     }
 841 
 842     public TypeMirror getDeclaredType(TypeElement enclosing, TypeMirror target) {
 843         return getDeclaredType(Collections.emptyList(), enclosing, target);
 844     }
 845 
 846     /**
 847      * Finds the declaration of the enclosing's type parameter.
 848      *
 849      * @param values
 850      * @param enclosing a TypeElement whose type arguments  we desire
 851      * @param target the TypeMirror of the type as described by the enclosing
 852      * @return
 853      */
 854     public TypeMirror getDeclaredType(Collection<TypeMirror> values,
 855             TypeElement enclosing, TypeMirror target) {
 856         TypeElement targetElement = asTypeElement(target);
 857         List<? extends TypeParameterElement> targetTypeArgs = targetElement.getTypeParameters();
 858         if (targetTypeArgs.isEmpty()) {
 859             return target;
 860         }
 861 
 862         List<? extends TypeParameterElement> enclosingTypeArgs = enclosing.getTypeParameters();
 863         List<TypeMirror> targetTypeArgTypes = new ArrayList<>(targetTypeArgs.size());
 864 
 865         if (enclosingTypeArgs.isEmpty()) {
 866             for (TypeMirror te : values) {
 867                 List<? extends TypeMirror> typeArguments = ((DeclaredType)te).getTypeArguments();
 868                 if (typeArguments.size() >= targetTypeArgs.size()) {
 869                     for (int i = 0 ; i < targetTypeArgs.size(); i++) {
 870                         targetTypeArgTypes.add(typeArguments.get(i));
 871                     }
 872                     break;
 873                 }
 874             }
 875             // we found no matches in the hierarchy
 876             if (targetTypeArgTypes.isEmpty()) {
 877                 return target;
 878             }
 879         } else {
 880             if (targetTypeArgs.size() > enclosingTypeArgs.size()) {
 881                 return target;
 882             }
 883             for (int i = 0; i < targetTypeArgs.size(); i++) {
 884                 TypeParameterElement tpe = enclosingTypeArgs.get(i);
 885                 targetTypeArgTypes.add(tpe.asType());
 886             }
 887         }
 888         TypeMirror dt = typeUtils.getDeclaredType(targetElement,
 889                 targetTypeArgTypes.toArray(new TypeMirror[targetTypeArgTypes.size()]));
 890         return dt;
 891     }
 892 
 893     /**
 894      * Returns all the implemented super-interfaces of a given type,
 895      * in the case of classes, include all the super-interfaces of
 896      * the supertype. The super-interfaces are collected before the
 897      * super-interfaces of the supertype.
 898      *
 899      * @param  te the type element to get the super-interfaces for.
 900      * @return the list of super-interfaces.
 901      */
 902     public Set<TypeMirror> getAllInterfaces(TypeElement te) {
 903         Set<TypeMirror> results = new LinkedHashSet<>();
 904         getAllInterfaces(te.asType(), results);
 905         return results;
 906     }
 907 
 908     private void getAllInterfaces(TypeMirror type, Set<TypeMirror> results) {
 909         List<? extends TypeMirror> intfacs = typeUtils.directSupertypes(type);
 910         TypeMirror superType = null;
 911         for (TypeMirror intfac : intfacs) {
 912             if (intfac == getObjectType())
 913                 continue;
 914             TypeElement e = asTypeElement(intfac);
 915             if (isInterface(e)) {
 916                 if (isPublic(e) || isLinkable(e))
 917                     results.add(intfac);
 918 
 919                 getAllInterfaces(intfac, results);
 920             } else {
 921                 // Save the supertype for later.
 922                 superType = intfac;
 923             }
 924         }
 925         // Collect the super-interfaces of the supertype.
 926         if (superType != null)
 927             getAllInterfaces(superType, results);
 928     }
 929 
 930     /**
 931      * Lookup for a class within this package.
 932      *
 933      * @return TypeElement of found class, or null if not found.
 934      */
 935     public TypeElement findClassInPackageElement(PackageElement pkg, String className) {
 936         for (TypeElement c : getAllClasses(pkg)) {
 937             if (getSimpleName(c).equals(className)) {
 938                 return c;
 939             }
 940         }
 941         return null;
 942     }
 943 
 944     /**
 945      * TODO: FIXME: port to javax.lang.model
 946      * Find a class within the context of this class. Search order: qualified name, in this class
 947      * (inner), in this package, in the class imports, in the package imports. Return the
 948      * TypeElement if found, null if not found.
 949      */
 950     //### The specified search order is not the normal rule the
 951     //### compiler would use.  Leave as specified or change it?
 952     public TypeElement findClass(Element element, String className) {
 953         TypeElement encl = getEnclosingTypeElement(element);
 954         TypeElement searchResult = configuration.workArounds.searchClass(encl, className);
 955         if (searchResult == null) {
 956             encl = getEnclosingTypeElement(encl);
 957             //Expand search space to include enclosing class.
 958             while (encl != null && getEnclosingTypeElement(encl) != null) {
 959                 encl = getEnclosingTypeElement(encl);
 960             }
 961             searchResult = encl == null
 962                     ? null
 963                     : configuration.workArounds.searchClass(encl, className);
 964         }
 965         return searchResult;
 966     }
 967 
 968     /**
 969      * Enclose in quotes, used for paths and filenames that contains spaces
 970      */
 971     public String quote(String filepath) {
 972         return ("\"" + filepath + "\"");
 973     }
 974 
 975     /**
 976      * Parse the package name.  We only want to display package name up to
 977      * 2 levels.
 978      */
 979     public String parsePackageName(PackageElement p) {
 980         String pkgname = p.isUnnamed() ? "" : getPackageName(p);
 981         int index = -1;
 982         for (int j = 0; j < MAX_CONSTANT_VALUE_INDEX_LENGTH; j++) {
 983             index = pkgname.indexOf(".", index + 1);
 984         }
 985         if (index != -1) {
 986             pkgname = pkgname.substring(0, index);
 987         }
 988         return pkgname;
 989     }
 990 
 991     /**
 992      * Given a string, replace all occurrences of 'newStr' with 'oldStr'.
 993      * @param originalStr the string to modify.
 994      * @param oldStr the string to replace.
 995      * @param newStr the string to insert in place of the old string.
 996      */
 997     public String replaceText(String originalStr, String oldStr,
 998             String newStr) {
 999         if (oldStr == null || newStr == null || oldStr.equals(newStr)) {
1000             return originalStr;
1001         }
1002         return originalStr.replace(oldStr, newStr);
1003     }
1004 
1005     /**
1006      * Given an annotation, return true if it should be documented and false
1007      * otherwise.
1008      *
1009      * @param annotation the annotation to check.
1010      *
1011      * @return true return true if it should be documented and false otherwise.
1012      */
1013     public boolean isDocumentedAnnotation(TypeElement annotation) {
1014         for (AnnotationMirror anno : annotation.getAnnotationMirrors()) {
1015             if (getFullyQualifiedName(anno.getAnnotationType().asElement()).equals(
1016                     Documented.class.getName())) {
1017                 return true;
1018             }
1019         }
1020         return false;
1021     }
1022 
1023     /**
1024      * Returns true if this class is linkable and false if we can't link to it.
1025      *
1026      * <p>
1027      * <b>NOTE:</b>  You can only link to external classes if they are public or
1028      * protected.
1029      *
1030      * @return true if this class is linkable and false if we can't link to the
1031      * desired class.
1032      */
1033     public boolean isLinkable(TypeElement typeElem) {
1034         return
1035             (typeElem != null &&
1036                 (isIncluded(typeElem) && configuration.isGeneratedDoc(typeElem))) ||
1037             (configuration.extern.isExternal(typeElem) &&
1038                 (isPublic(typeElem) || isProtected(typeElem)));
1039     }
1040 
1041     /**
1042      * Returns true if an element is linkable in the context of a given type element.
1043      *
1044      * If the element is a type element, it delegates to {@link #isLinkable(TypeElement)}.
1045      * Otherwise, the element is linkable if any of the following are true:
1046      * <ul>
1047      * <li>it is "included" (see {@link jdk.javadoc.doclet})
1048      * <li>it is inherited from an undocumented supertype
1049      * <li>it is a public or protected member of an external API
1050      * </ul>
1051      *
1052      * @param typeElem the type element
1053      * @param elem the element
1054      * @return whether or not the element is linkable
1055      */
1056     public boolean isLinkable(TypeElement typeElem, Element elem) {
1057         if (isTypeElement(elem)) {
1058             return isLinkable((TypeElement) elem); // defer to existing behavior
1059         }
1060 
1061         if (isIncluded(elem)) {
1062             return true;
1063         }
1064 
1065         // Allow for the behavior that members of undocumented supertypes
1066         // may be included in documented types
1067         TypeElement enclElem = getEnclosingTypeElement(elem);
1068         if (typeElem != enclElem && isSubclassOf(typeElem, enclElem)) {
1069             return true;
1070         }
1071 
1072         // Allow for external members
1073         return isLinkable(typeElem)
1074                     && configuration.extern.isExternal(typeElem)
1075                     && (isPublic(elem) || isProtected(elem));
1076     }
1077 
1078     /**
1079      * Return this type as a {@code TypeElement} if it represents a class
1080      * interface or annotation.  Array dimensions are ignored.
1081      * If this type {@code ParameterizedType} or {@code WildcardType}, return
1082      * the {@code TypeElement} of the type's erasure.  If this is an
1083      * annotation, return this as a {@code TypeElement}.
1084      * If this is a primitive type, return null.
1085      *
1086      * @return the {@code TypeElement} of this type,
1087      *         or null if it is a primitive type.
1088      */
1089     public TypeElement asTypeElement(TypeMirror t) {
1090         return new SimpleTypeVisitor9<TypeElement, Void>() {
1091 
1092             @Override
1093             public TypeElement visitDeclared(DeclaredType t, Void p) {
1094                 return (TypeElement) t.asElement();
1095             }
1096 
1097             @Override
1098             public TypeElement visitArray(ArrayType t, Void p) {
1099                 return visit(t.getComponentType());
1100             }
1101 
1102             @Override
1103             public TypeElement visitTypeVariable(TypeVariable t, Void p) {
1104                /* TODO, this may not be an optimimal fix.
1105                 * if we have an annotated type @DA T, then erasure returns a
1106                 * none, in this case we use asElement instead.
1107                 */
1108                 if (isAnnotated(t)) {
1109                     return visit(typeUtils.asElement(t).asType());
1110                 }
1111                 return visit(typeUtils.erasure(t));
1112             }
1113 
1114             @Override
1115             public TypeElement visitWildcard(WildcardType t, Void p) {
1116                 return visit(typeUtils.erasure(t));
1117             }
1118 
1119             @Override
1120             public TypeElement visitError(ErrorType t, Void p) {
1121                 return (TypeElement)t.asElement();
1122             }
1123 
1124             @Override
1125             protected TypeElement defaultAction(TypeMirror e, Void p) {
1126                 return super.defaultAction(e, p);
1127             }
1128         }.visit(t);
1129     }
1130 
1131     public TypeMirror getComponentType(TypeMirror t) {
1132         while (isArrayType(t)) {
1133             t = ((ArrayType) t).getComponentType();
1134         }
1135         return t;
1136     }
1137 
1138     /**
1139      * Return the type's dimension information, as a string.
1140      * <p>
1141      * For example, a two dimensional array of String returns "{@code [][]}".
1142      *
1143      * @return the type's dimension information as a string.
1144      */
1145     public String getDimension(TypeMirror t) {
1146         return new SimpleTypeVisitor9<String, Void>() {
1147             StringBuilder dimension = new StringBuilder("");
1148             @Override
1149             public String visitArray(ArrayType t, Void p) {
1150                 dimension.append("[]");
1151                 return visit(t.getComponentType());
1152             }
1153 
1154             @Override
1155             protected String defaultAction(TypeMirror e, Void p) {
1156                 return dimension.toString();
1157             }
1158 
1159         }.visit(t);
1160     }
1161 
1162     public TypeElement getSuperClass(TypeElement te) {
1163         if (isInterface(te) || isAnnotationType(te) ||
1164                 te.asType().equals(getObjectType())) {
1165             return null;
1166         }
1167         TypeMirror superclass = te.getSuperclass();
1168         if (isNoType(superclass) && isClass(te)) {
1169             superclass = getObjectType();
1170         }
1171         return asTypeElement(superclass);
1172     }
1173 
1174     public TypeElement getFirstVisibleSuperClassAsTypeElement(TypeElement te) {
1175         if (isAnnotationType(te) || isInterface(te) ||
1176                 te.asType().equals(getObjectType())) {
1177             return null;
1178         }
1179         TypeMirror firstVisibleSuperClass = getFirstVisibleSuperClass(te);
1180         return firstVisibleSuperClass == null ? null : asTypeElement(firstVisibleSuperClass);
1181     }
1182 
1183     /**
1184      * Given a class, return the closest visible super class.
1185      * @param type the TypeMirror to be interrogated
1186      * @return  the closest visible super class.  Return null if it cannot
1187      *          be found.
1188      */
1189 
1190     public TypeMirror getFirstVisibleSuperClass(TypeMirror type) {
1191         return getFirstVisibleSuperClass(asTypeElement(type));
1192     }
1193 
1194 
1195     /**
1196      * Given a class, return the closest visible super class.
1197      *
1198      * @param te the TypeElement to be interrogated
1199      * @return the closest visible super class.  Return null if it cannot
1200      *         be found..
1201      */
1202     public TypeMirror getFirstVisibleSuperClass(TypeElement te) {
1203         TypeMirror superType = te.getSuperclass();
1204         if (isNoType(superType)) {
1205             superType = getObjectType();
1206         }
1207         TypeElement superClass = asTypeElement(superType);
1208         // skip "hidden" classes
1209         while ((superClass != null && hasHiddenTag(superClass))
1210                 || (superClass != null &&  !isPublic(superClass) && !isLinkable(superClass))) {
1211             TypeMirror supersuperType = superClass.getSuperclass();
1212             TypeElement supersuperClass = asTypeElement(supersuperType);
1213             if (supersuperClass == null
1214                     || supersuperClass.getQualifiedName().equals(superClass.getQualifiedName())) {
1215                 break;
1216             }
1217             superType = supersuperType;
1218             superClass = supersuperClass;
1219         }
1220         if (te.asType().equals(superType)) {
1221             return null;
1222         }
1223         return superType;
1224     }
1225 
1226     /**
1227      * Given a TypeElement, return the name of its type (Class, Interface, etc.).
1228      *
1229      * @param te the TypeElement to check.
1230      * @param lowerCaseOnly true if you want the name returned in lower case.
1231      *                      If false, the first letter of the name is capitalized.
1232      * @return
1233      */
1234 
1235     public String getTypeElementName(TypeElement te, boolean lowerCaseOnly) {
1236         String typeName = "";
1237         if (isInterface(te)) {
1238             typeName = "doclet.Interface";
1239         } else if (isException(te)) {
1240             typeName = "doclet.Exception";
1241         } else if (isError(te)) {
1242             typeName = "doclet.Error";
1243         } else if (isAnnotationType(te)) {
1244             typeName = "doclet.AnnotationType";
1245         } else if (isEnum(te)) {
1246             typeName = "doclet.Enum";
1247         } else if (isOrdinaryClass(te)) {
1248             typeName = "doclet.Class";
1249         }
1250         typeName = lowerCaseOnly ? toLowerCase(typeName) : typeName;
1251         return typeNameMap.computeIfAbsent(typeName, resources::getText);
1252     }
1253 
1254     private final Map<String, String> typeNameMap = new HashMap<>();
1255 
1256     public String getTypeName(TypeMirror t, boolean fullyQualified) {
1257         return new SimpleTypeVisitor9<String, Void>() {
1258 
1259             @Override
1260             public String visitArray(ArrayType t, Void p) {
1261                 return visit(t.getComponentType());
1262             }
1263 
1264             @Override
1265             public String visitDeclared(DeclaredType t, Void p) {
1266                 TypeElement te = asTypeElement(t);
1267                 return fullyQualified
1268                         ? te.getQualifiedName().toString()
1269                         : getSimpleName(te);
1270             }
1271 
1272             @Override
1273             public String visitExecutable(ExecutableType t, Void p) {
1274                 return t.toString();
1275             }
1276 
1277             @Override
1278             public String visitPrimitive(PrimitiveType t, Void p) {
1279                 return t.toString();
1280             }
1281 
1282             @Override
1283             public String visitTypeVariable(javax.lang.model.type.TypeVariable t, Void p) {
1284                 return getSimpleName(t.asElement());
1285             }
1286 
1287             @Override
1288             public String visitWildcard(javax.lang.model.type.WildcardType t, Void p) {
1289                 return t.toString();
1290             }
1291 
1292             @Override
1293             protected String defaultAction(TypeMirror e, Void p) {
1294                 return e.toString();
1295             }
1296         }.visit(t);
1297     }
1298 
1299     /**
1300      * Replace all tabs in a string with the appropriate number of spaces.
1301      * The string may be a multi-line string.
1302      * @param text the text for which the tabs should be expanded
1303      * @return the text with all tabs expanded
1304      */
1305     public String replaceTabs(String text) {
1306         if (!text.contains("\t"))
1307             return text;
1308 
1309         final int tabLength = configuration.sourcetab;
1310         final String whitespace = configuration.tabSpaces;
1311         final int textLength = text.length();
1312         StringBuilder result = new StringBuilder(textLength);
1313         int pos = 0;
1314         int lineLength = 0;
1315         for (int i = 0; i < textLength; i++) {
1316             char ch = text.charAt(i);
1317             switch (ch) {
1318                 case '\n': case '\r':
1319                     lineLength = 0;
1320                     break;
1321                 case '\t':
1322                     result.append(text, pos, i);
1323                     int spaceCount = tabLength - lineLength % tabLength;
1324                     result.append(whitespace, 0, spaceCount);
1325                     lineLength += spaceCount;
1326                     pos = i + 1;
1327                     break;
1328                 default:
1329                     lineLength++;
1330             }
1331         }
1332         result.append(text, pos, textLength);
1333         return result.toString();
1334     }
1335 
1336     public CharSequence normalizeNewlines(CharSequence text) {
1337         StringBuilder sb = new StringBuilder();
1338         final int textLength = text.length();
1339         final String NL = DocletConstants.NL;
1340         int pos = 0;
1341         for (int i = 0; i < textLength; i++) {
1342             char ch = text.charAt(i);
1343             switch (ch) {
1344                 case '\n':
1345                     sb.append(text, pos, i);
1346                     sb.append(NL);
1347                     pos = i + 1;
1348                     break;
1349                 case '\r':
1350                     sb.append(text, pos, i);
1351                     sb.append(NL);
1352                     if (i + 1 < textLength && text.charAt(i + 1) == '\n')
1353                         i++;
1354                     pos = i + 1;
1355                     break;
1356             }
1357         }
1358         sb.append(text, pos, textLength);
1359         return sb;
1360     }
1361 
1362     /**
1363      * The documentation for values() and valueOf() in Enums are set by the
1364      * doclet only iff the user or overridden methods are missing.
1365      * @param elem
1366      */
1367     public void setEnumDocumentation(TypeElement elem) {
1368         for (Element e : getMethods(elem)) {
1369             ExecutableElement ee = (ExecutableElement)e;
1370             if (!getFullBody(e).isEmpty()) // ignore if already set
1371                 continue;
1372             if (ee.getSimpleName().contentEquals("values") && ee.getParameters().isEmpty()) {
1373                 removeCommentHelper(ee); // purge previous entry
1374                 configuration.cmtUtils.setEnumValuesTree(e);
1375             }
1376             if (ee.getSimpleName().contentEquals("valueOf") && ee.getParameters().size() == 1) {
1377                 removeCommentHelper(ee); // purge previous entry
1378                 configuration.cmtUtils.setEnumValueOfTree(e);
1379             }
1380         }
1381     }
1382 
1383     /**
1384      * Returns a locale independent upper cased String. That is, it
1385      * always uses US locale, this is a clone of the one in StringUtils.
1386      * @param s to convert
1387      * @return converted String
1388      */
1389     public static String toUpperCase(String s) {
1390         return s.toUpperCase(Locale.US);
1391     }
1392 
1393     /**
1394      * Returns a locale independent lower cased String. That is, it
1395      * always uses US locale, this is a clone of the one in StringUtils.
1396      * @param s to convert
1397      * @return converted String
1398      */
1399     public static String toLowerCase(String s) {
1400         return s.toLowerCase(Locale.US);
1401     }
1402 
1403     /**
1404      * Return true if the given Element is deprecated.
1405      *
1406      * @param e the Element to check.
1407      * @return true if the given Element is deprecated.
1408      */
1409     public boolean isDeprecated(Element e) {
1410         if (isPackage(e)) {
1411             return configuration.workArounds.isDeprecated0(e);
1412         }
1413         return elementUtils.isDeprecated(e);
1414     }
1415 
1416     /**
1417      * Return true if the given Element is deprecated for removal.
1418      *
1419      * @param e the Element to check.
1420      * @return true if the given Element is deprecated for removal.
1421      */
1422     public boolean isDeprecatedForRemoval(Element e) {
1423         List<? extends AnnotationMirror> annotationList = e.getAnnotationMirrors();
1424         JavacTypes jctypes = ((DocEnvImpl) configuration.docEnv).toolEnv.typeutils;
1425         for (AnnotationMirror anno : annotationList) {
1426             if (jctypes.isSameType(anno.getAnnotationType().asElement().asType(), getDeprecatedType())) {
1427                 Map<? extends ExecutableElement, ? extends AnnotationValue> pairs = anno.getElementValues();
1428                 if (!pairs.isEmpty()) {
1429                     for (ExecutableElement element : pairs.keySet()) {
1430                         if (element.getSimpleName().contentEquals("forRemoval")) {
1431                             return Boolean.parseBoolean((pairs.get(element)).toString());
1432                         }
1433                     }
1434                 }
1435             }
1436         }
1437         return false;
1438     }
1439 
1440     /**
1441      * A convenience method to get property name from the name of the
1442      * getter or setter method.
1443      * @param e the input method.
1444      * @return the name of the property of the given setter of getter.
1445      */
1446     public String propertyName(ExecutableElement e) {
1447         String name = getSimpleName(e);
1448         String propertyName = null;
1449         if (name.startsWith("get") || name.startsWith("set")) {
1450             propertyName = name.substring(3);
1451         } else if (name.startsWith("is")) {
1452             propertyName = name.substring(2);
1453         }
1454         if ((propertyName == null) || propertyName.isEmpty()){
1455             return "";
1456         }
1457         return propertyName.substring(0, 1).toLowerCase(configuration.getLocale())
1458                 + propertyName.substring(1);
1459     }
1460 
1461     /**
1462      * Returns true if the element is included, contains @hidden tag,
1463      * or if javafx flag is present and element contains @treatAsPrivate
1464      * tag.
1465      * @param e the queried element
1466      * @return true if it exists, false otherwise
1467      */
1468     public boolean hasHiddenTag(Element e) {
1469         // prevent needless tests on elements which are not included
1470         if (!isIncluded(e)) {
1471             return false;
1472         }
1473         if (configuration.javafx &&
1474                 hasBlockTag(e, DocTree.Kind.UNKNOWN_BLOCK_TAG, "treatAsPrivate")) {
1475             return true;
1476         }
1477         return hasBlockTag(e, DocTree.Kind.HIDDEN);
1478     }
1479 
1480     /**
1481      * Returns true if the method has no comments, or a lone &commat;inheritDoc.
1482      * @param m a method
1483      * @return true if there are no comments, false otherwise
1484      */
1485     public boolean isSimpleOverride(ExecutableElement m) {
1486         if (!configuration.summarizeOverriddenMethods ||
1487                 !isIncluded(m)) {
1488             return false;
1489         }
1490 
1491         if (!getBlockTags(m).isEmpty() || isDeprecated(m))
1492             return false;
1493 
1494         List<? extends DocTree> fullBody = getFullBody(m);
1495         return fullBody.isEmpty() ||
1496                 (fullBody.size() == 1 && fullBody.get(0).getKind().equals(Kind.INHERIT_DOC));
1497     }
1498 
1499     /**
1500      * In case of JavaFX mode on, filters out classes that are private,
1501      * package private, these are not documented in JavaFX mode, also
1502      * remove those classes that have @hidden or @treatAsPrivate comment tag.
1503      *
1504      * @param classlist a collection of TypeElements
1505      * @param javafx set to true if in JavaFX mode.
1506      * @return list of filtered classes.
1507      */
1508     public SortedSet<TypeElement> filterOutPrivateClasses(Iterable<TypeElement> classlist,
1509             boolean javafx) {
1510         SortedSet<TypeElement> filteredOutClasses =
1511                 new TreeSet<>(makeGeneralPurposeComparator());
1512         if (!javafx) {
1513             for (Element te : classlist) {
1514                 if (!hasHiddenTag(te)) {
1515                     filteredOutClasses.add((TypeElement)te);
1516                 }
1517             }
1518             return filteredOutClasses;
1519         }
1520         for (Element e : classlist) {
1521             if (isPrivate(e) || isPackagePrivate(e) || hasHiddenTag(e)) {
1522                 continue;
1523             }
1524             filteredOutClasses.add((TypeElement)e);
1525         }
1526         return filteredOutClasses;
1527     }
1528 
1529     /**
1530      * Compares two elements.
1531      * @param e1 first Element
1532      * @param e2 second Element
1533      * @return a true if they are the same, false otherwise.
1534      */
1535     public boolean elementsEqual(Element e1, Element e2) {
1536         if (e1.getKind() != e2.getKind()) {
1537             return false;
1538         }
1539         String s1 = getSimpleName(e1);
1540         String s2 = getSimpleName(e2);
1541         if (compareStrings(s1, s2) == 0) {
1542             String f1 = getFullyQualifiedName(e1, true);
1543             String f2 = getFullyQualifiedName(e2, true);
1544             return compareStrings(f1, f2) == 0;
1545         }
1546         return false;
1547     }
1548 
1549     /**
1550      * A general purpose case insensitive String comparator, which compares
1551      * two Strings using a Collator strength of "TERTIARY".
1552      *
1553      * @param s1 first String to compare.
1554      * @param s2 second String to compare.
1555      * @return a negative integer, zero, or a positive integer as the first
1556      *         argument is less than, equal to, or greater than the second.
1557      */
1558     public int compareStrings(String s1, String s2) {
1559         return compareStrings(true, s1, s2);
1560     }
1561 
1562     /**
1563      * A general purpose case sensitive String comparator, which
1564      * compares two Strings using a Collator strength of "SECONDARY".
1565      *
1566      * @param s1 first String to compare.
1567      * @param s2 second String to compare.
1568      * @return a negative integer, zero, or a positive integer as the first
1569      *         argument is less than, equal to, or greater than the second.
1570      */
1571     public int compareCaseCompare(String s1, String s2) {
1572         return compareStrings(false, s1, s2);
1573     }
1574 
1575     private DocCollator tertiaryCollator = null;
1576     private DocCollator secondaryCollator = null;
1577 
1578     private int compareStrings(boolean caseSensitive, String s1, String s2) {
1579         if (caseSensitive) {
1580             if (tertiaryCollator == null) {
1581                 tertiaryCollator = new DocCollator(configuration.locale, Collator.TERTIARY);
1582             }
1583             return tertiaryCollator.compare(s1, s2);
1584         }
1585         if (secondaryCollator == null) {
1586             secondaryCollator = new DocCollator(configuration.locale, Collator.SECONDARY);
1587         }
1588         return secondaryCollator.compare(s1, s2);
1589     }
1590 
1591     private static class DocCollator {
1592         private final Map<String, CollationKey> keys;
1593         private final Collator instance;
1594         private final int MAX_SIZE = 1000;
1595         private DocCollator(Locale locale, int strength) {
1596             instance = createCollator(locale);
1597             instance.setStrength(strength);
1598 
1599             keys = new LinkedHashMap<String, CollationKey>(MAX_SIZE + 1, 0.75f, true) {
1600                 private static final long serialVersionUID = 1L;
1601                 @Override
1602                 protected boolean removeEldestEntry(Entry<String, CollationKey> eldest) {
1603                     return size() > MAX_SIZE;
1604                 }
1605             };
1606         }
1607 
1608         CollationKey getKey(String s) {
1609             return keys.computeIfAbsent(s, instance :: getCollationKey);
1610         }
1611 
1612         public int compare(String s1, String s2) {
1613             return getKey(s1).compareTo(getKey(s2));
1614         }
1615 
1616         private Collator createCollator(Locale locale) {
1617             Collator baseCollator = Collator.getInstance(locale);
1618             if (baseCollator instanceof RuleBasedCollator) {
1619                 // Extend collator to sort signatures with additional args and var-args in a well-defined order:
1620                 // () < (int) < (int, int) < (int...)
1621                 try {
1622                     return new RuleBasedCollator(((RuleBasedCollator) baseCollator).getRules()
1623                             + "& ')' < ',' < '.','['");
1624                 } catch (ParseException e) {
1625                     throw new RuntimeException(e);
1626                 }
1627             }
1628             return baseCollator;
1629         }
1630     }
1631 
1632     private Comparator<Element> moduleComparator = null;
1633     /**
1634      * Comparator for ModuleElements, simply compares the fully qualified names
1635      * @return a Comparator
1636      */
1637     public Comparator<Element> makeModuleComparator() {
1638         if (moduleComparator == null) {
1639             moduleComparator = new Utils.ElementComparator() {
1640                 @Override
1641                 public int compare(Element mod1, Element mod2) {
1642                     return compareFullyQualifiedNames(mod1, mod2);
1643                 }
1644             };
1645         }
1646         return moduleComparator;
1647     }
1648 
1649     private Comparator<Element> allClassesComparator = null;
1650     /**
1651      * Returns a Comparator for all classes, compares the simple names of
1652      * TypeElement, if equal then the fully qualified names.
1653      *
1654      * @return Comparator
1655      */
1656     public Comparator<Element> makeAllClassesComparator() {
1657         if (allClassesComparator == null) {
1658             allClassesComparator = new Utils.ElementComparator() {
1659                 @Override
1660                 public int compare(Element e1, Element e2) {
1661                     int result = compareNames(e1, e2);
1662                     if (result == 0)
1663                         result = compareFullyQualifiedNames(e1, e2);
1664 
1665                     return result;
1666                 }
1667             };
1668         }
1669         return allClassesComparator;
1670     }
1671 
1672     private Comparator<Element> packageComparator = null;
1673     /**
1674      * Returns a Comparator for packages, by comparing the fully qualified names.
1675      *
1676      * @return a Comparator
1677      */
1678     public Comparator<Element> makePackageComparator() {
1679         if (packageComparator == null) {
1680             packageComparator = new Utils.ElementComparator() {
1681                 @Override
1682                 public int compare(Element pkg1, Element pkg2) {
1683                     return compareFullyQualifiedNames(pkg1, pkg2);
1684                 }
1685             };
1686         }
1687         return packageComparator;
1688     }
1689 
1690     private Comparator<Element> deprecatedComparator = null;
1691     /**
1692      * Returns a Comparator for deprecated items listed on deprecated list page, by comparing the
1693      * fully qualified names.
1694      *
1695      * @return a Comparator
1696      */
1697     public Comparator<Element> makeDeprecatedComparator() {
1698         if (deprecatedComparator == null) {
1699             deprecatedComparator = new Utils.ElementComparator() {
1700                 @Override
1701                 public int compare(Element e1, Element e2) {
1702                     return compareFullyQualifiedNames(e1, e2);
1703                 }
1704             };
1705         }
1706         return deprecatedComparator;
1707     }
1708 
1709     private Comparator<SerialFieldTree> serialFieldTreeComparator = null;
1710     /**
1711      * Returns a Comparator for SerialFieldTree.
1712      * @return a Comparator
1713      */
1714     public Comparator<SerialFieldTree> makeSerialFieldTreeComparator() {
1715         if (serialFieldTreeComparator == null) {
1716             serialFieldTreeComparator = (SerialFieldTree o1, SerialFieldTree o2) -> {
1717                 String s1 = o1.getName().toString();
1718                 String s2 = o2.getName().toString();
1719                 return s1.compareTo(s2);
1720             };
1721         }
1722         return serialFieldTreeComparator;
1723     }
1724 
1725     /**
1726      * Returns a general purpose comparator.
1727      * @return a Comparator
1728      */
1729     public Comparator<Element> makeGeneralPurposeComparator() {
1730         return makeClassUseComparator();
1731     }
1732 
1733     private Comparator<Element> overrideUseComparator = null;
1734     /**
1735      * Returns a Comparator for overrides and implements,
1736      * used primarily on methods, compares the name first,
1737      * then compares the simple names of the enclosing
1738      * TypeElement and the fully qualified name of the enclosing TypeElement.
1739      * @return a Comparator
1740      */
1741     public Comparator<Element> makeOverrideUseComparator() {
1742         if (overrideUseComparator == null) {
1743             overrideUseComparator = new Utils.ElementComparator() {
1744                 @Override
1745                 public int compare(Element o1, Element o2) {
1746                     int result = compareStrings(getSimpleName(o1), getSimpleName(o2));
1747                     if (result != 0) {
1748                         return result;
1749                     }
1750                     if (!isTypeElement(o1) && !isTypeElement(o2) && !isPackage(o1) && !isPackage(o2)) {
1751                         TypeElement t1 = getEnclosingTypeElement(o1);
1752                         TypeElement t2 = getEnclosingTypeElement(o2);
1753                         result = compareStrings(getSimpleName(t1), getSimpleName(t2));
1754                         if (result != 0)
1755                             return result;
1756                     }
1757                     result = compareStrings(getFullyQualifiedName(o1), getFullyQualifiedName(o2));
1758                     if (result != 0)
1759                         return result;
1760                     return compareElementTypeKinds(o1, o2);
1761                 }
1762             };
1763         }
1764         return overrideUseComparator;
1765     }
1766 
1767     private Comparator<Element> indexUseComparator = null;
1768     /**
1769      *  Returns a Comparator for index file presentations, and are sorted as follows.
1770      *  If comparing modules and/or packages then simply compare the qualified names,
1771      *  if comparing a module or a package with a type/member then compare the
1772      *  FullyQualifiedName of the module or a package with the SimpleName of the entity,
1773      *  otherwise:
1774      *  1. compare the ElementKind ex: Module, Package, Interface etc.
1775      *  2a. if equal and if the type is of ExecutableElement(Constructor, Methods),
1776      *      a case insensitive comparison of parameter the type signatures
1777      *  2b. if equal, case sensitive comparison of the type signatures
1778      *  3. finally, if equal, compare the FQNs of the entities
1779      * @return a comparator for index file use
1780      */
1781     public Comparator<Element> makeIndexUseComparator() {
1782         if (indexUseComparator == null) {
1783             indexUseComparator = new Utils.ElementComparator() {
1784                 /**
1785                  * Compares two elements.
1786                  *
1787                  * @param e1 - an element.
1788                  * @param e2 - an element.
1789                  * @return a negative integer, zero, or a positive integer as the first
1790                  * argument is less than, equal to, or greater than the second.
1791                  */
1792                 @Override
1793                 public int compare(Element e1, Element e2) {
1794                     int result;
1795                     // first, compare names as appropriate
1796                     if ((isModule(e1) || isPackage(e1)) && (isModule(e2) || isPackage(e2))) {
1797                         result = compareFullyQualifiedNames(e1, e2);
1798                     } else if (isModule(e1) || isPackage(e1)) {
1799                         result = compareStrings(getFullyQualifiedName(e1), getSimpleName(e2));
1800                     } else if (isModule(e2) || isPackage(e2)) {
1801                         result = compareStrings(getSimpleName(e1), getFullyQualifiedName(e2));
1802                     } else {
1803                         result = compareNames(e1, e2);
1804                     }
1805                     if (result != 0) {
1806                         return result;
1807                     }
1808                     // if names are the same, compare element kinds
1809                     result = compareElementTypeKinds(e1, e2);
1810                     if (result != 0) {
1811                         return result;
1812                     }
1813                     // if element kinds are the same, and are methods,
1814                     // compare the method parameters
1815                     if (hasParameters(e1)) {
1816                         List<? extends VariableElement> parameters1 = ((ExecutableElement)e1).getParameters();
1817                         List<? extends VariableElement> parameters2 = ((ExecutableElement)e2).getParameters();
1818                         result = compareParameters(false, parameters1, parameters2);
1819                         if (result != 0) {
1820                             return result;
1821                         }
1822                         result = compareParameters(true, parameters1, parameters2);
1823                         if (result != 0) {
1824                             return result;
1825                         }
1826                     }
1827                     // else fall back on fully qualified names
1828                     return compareFullyQualifiedNames(e1, e2);
1829                 }
1830             };
1831         }
1832         return indexUseComparator;
1833     }
1834 
1835     private Comparator<TypeMirror> typeMirrorClassUseComparator = null;
1836     /**
1837      * Compares the FullyQualifiedNames of two TypeMirrors
1838      * @return
1839      */
1840     public Comparator<TypeMirror> makeTypeMirrorClassUseComparator() {
1841         if (typeMirrorClassUseComparator == null) {
1842             typeMirrorClassUseComparator = (TypeMirror type1, TypeMirror type2) -> {
1843                 String s1 = getQualifiedTypeName(type1);
1844                 String s2 = getQualifiedTypeName(type2);
1845                 return compareStrings(s1, s2);
1846             };
1847         }
1848         return typeMirrorClassUseComparator;
1849     }
1850 
1851     private Comparator<TypeMirror> typeMirrorIndexUseComparator = null;
1852     /**
1853      * Compares the SimpleNames of TypeMirrors if equal then the
1854      * FullyQualifiedNames of TypeMirrors.
1855      *
1856      * @return
1857      */
1858     public Comparator<TypeMirror> makeTypeMirrorIndexUseComparator() {
1859         if (typeMirrorIndexUseComparator == null) {
1860             typeMirrorIndexUseComparator = (TypeMirror t1, TypeMirror t2) -> {
1861                 int result = compareStrings(getTypeName(t1, false), getTypeName(t2, false));
1862                 if (result != 0)
1863                     return result;
1864                 return compareStrings(getQualifiedTypeName(t1), getQualifiedTypeName(t2));
1865             };
1866         }
1867         return typeMirrorIndexUseComparator;
1868     }
1869 
1870     /**
1871      * Get the qualified type name of a TypeMiror compatible with the Element's
1872      * getQualified name, returns  the qualified name of the Reference type
1873      * otherwise the primitive name.
1874      * @param t the type whose name is to be obtained.
1875      * @return the fully qualified name of Reference type or the primitive name
1876      */
1877     public String getQualifiedTypeName(TypeMirror t) {
1878         return new SimpleTypeVisitor9<String, Void>() {
1879             @Override
1880             public String visitDeclared(DeclaredType t, Void p) {
1881                 return getFullyQualifiedName(t.asElement());
1882             }
1883 
1884             @Override
1885             public String visitArray(ArrayType t, Void p) {
1886                return visit(t.getComponentType());
1887             }
1888 
1889             @Override
1890             public String visitTypeVariable(javax.lang.model.type.TypeVariable t, Void p) {
1891                 // The knee jerk reaction is to do this but don't!, as we would like
1892                 // it to be compatible with the old world, now if we decide to do so
1893                 // care must be taken to avoid collisions.
1894                 // return getFullyQualifiedName(t.asElement());
1895                 return t.toString();
1896             }
1897 
1898             @Override
1899             protected String defaultAction(TypeMirror t, Void p) {
1900                 return t.toString();
1901             }
1902 
1903         }.visit(t);
1904     }
1905 
1906     /**
1907      * A generic utility which returns the fully qualified names of an entity,
1908      * if the entity is not qualifiable then its enclosing entity, it is upto
1909      * the caller to add the elements name as required.
1910      * @param e the element to get FQN for.
1911      * @return the name
1912      */
1913     public String getFullyQualifiedName(Element e) {
1914         return getFullyQualifiedName(e, true);
1915     }
1916 
1917     public String getFullyQualifiedName(Element e, final boolean outer) {
1918         return new SimpleElementVisitor9<String, Void>() {
1919             @Override
1920             public String visitModule(ModuleElement e, Void p) {
1921                 return e.getQualifiedName().toString();
1922             }
1923 
1924             @Override
1925             public String visitPackage(PackageElement e, Void p) {
1926                 return e.getQualifiedName().toString();
1927             }
1928 
1929             @Override
1930             public String visitType(TypeElement e, Void p) {
1931                 return e.getQualifiedName().toString();
1932             }
1933 
1934             @Override
1935             protected String defaultAction(Element e, Void p) {
1936                 return outer ? visit(e.getEnclosingElement()) : e.getSimpleName().toString();
1937             }
1938         }.visit(e);
1939     }
1940 
1941     private Comparator<Element> classUseComparator = null;
1942     /**
1943      * Comparator for ClassUse presentations, and sorts as follows:
1944      * 1. member names
1945      * 2. then fully qualified member names
1946      * 3. then parameter types if applicable
1947      * 4. finally the element kinds ie. package, class, interface etc.
1948      * @return a comparator to sort classes and members for class use
1949      */
1950     public Comparator<Element> makeClassUseComparator() {
1951         if (classUseComparator == null) {
1952             classUseComparator = new Utils.ElementComparator() {
1953                 /**
1954                  * Compares two Elements.
1955                  *
1956                  * @param e1 - an element.
1957                  * @param e2 - an element.
1958                  * @return a negative integer, zero, or a positive integer as the first
1959                  * argument is less than, equal to, or greater than the second.
1960                  */
1961                 @Override
1962                 public int compare(Element e1, Element e2) {
1963                     int result = compareNames(e1, e2);
1964                     if (result != 0) {
1965                         return result;
1966                     }
1967                     result = compareFullyQualifiedNames(e1, e2);
1968                     if (result != 0) {
1969                         return result;
1970                     }
1971                     if (hasParameters(e1) && hasParameters(e2)) {
1972                         @SuppressWarnings("unchecked")
1973                         List<VariableElement> parameters1 = (List<VariableElement>)((ExecutableElement)e1).getParameters();
1974                         @SuppressWarnings("unchecked")
1975                         List<VariableElement> parameters2 = (List<VariableElement>)((ExecutableElement)e2).getParameters();
1976                         result = compareParameters(false, parameters1, parameters2);
1977                         if (result != 0) {
1978                             return result;
1979                         }
1980                         result = compareParameters(true, parameters1, parameters2);
1981                     }
1982                     if (result != 0) {
1983                         return result;
1984                     }
1985                     return compareElementTypeKinds(e1, e2);
1986                 }
1987             };
1988         }
1989         return classUseComparator;
1990     }
1991 
1992     /**
1993      * A general purpose comparator to sort Element entities, basically provides the building blocks
1994      * for creating specific comparators for an use-case.
1995      */
1996     private abstract class ElementComparator implements Comparator<Element> {
1997         /**
1998          * compares two parameter arrays by first comparing the length of the arrays, and
1999          * then each Type of the parameter in the array.
2000          * @param params1 the first parameter array.
2001          * @param params2 the first parameter array.
2002          * @return a negative integer, zero, or a positive integer as the first
2003          *         argument is less than, equal to, or greater than the second.
2004          */
2005         final EnumMap<ElementKind, Integer> elementKindOrder;
2006         public ElementComparator() {
2007             elementKindOrder = new EnumMap<>(ElementKind.class);
2008             elementKindOrder.put(ElementKind.MODULE, 0);
2009             elementKindOrder.put(ElementKind.PACKAGE, 1);
2010             elementKindOrder.put(ElementKind.CLASS, 2);
2011             elementKindOrder.put(ElementKind.ENUM, 3);
2012             elementKindOrder.put(ElementKind.ENUM_CONSTANT, 4);
2013             elementKindOrder.put(ElementKind.INTERFACE, 5);
2014             elementKindOrder.put(ElementKind.ANNOTATION_TYPE, 6);
2015             elementKindOrder.put(ElementKind.FIELD, 7);
2016             elementKindOrder.put(ElementKind.CONSTRUCTOR, 8);
2017             elementKindOrder.put(ElementKind.METHOD, 9);
2018         }
2019 
2020         protected int compareParameters(boolean caseSensitive, List<? extends VariableElement> params1,
2021                                                                List<? extends VariableElement> params2) {
2022 
2023             return compareStrings(caseSensitive, getParametersAsString(params1),
2024                                                  getParametersAsString(params2));
2025         }
2026 
2027         String getParametersAsString(List<? extends VariableElement> params) {
2028             StringBuilder sb = new StringBuilder();
2029             for (VariableElement param : params) {
2030                 TypeMirror t = param.asType();
2031                 // prefix P for primitive and R for reference types, thus items will
2032                 // be ordered lexically and correctly.
2033                 sb.append(getTypeCode(t)).append("-").append(t).append("-");
2034             }
2035             return sb.toString();
2036         }
2037 
2038         private String getTypeCode(TypeMirror t) {
2039             return new SimpleTypeVisitor9<String, Void>() {
2040 
2041                 @Override
2042                 public String visitPrimitive(PrimitiveType t, Void p) {
2043                     return "P";
2044                 }
2045                 @Override
2046                 public String visitArray(ArrayType t, Void p) {
2047                     return visit(t.getComponentType());
2048                 }
2049                 @Override
2050                 protected String defaultAction(TypeMirror e, Void p) {
2051                     return "R";
2052                 }
2053 
2054             }.visit(t);
2055         }
2056 
2057         /**
2058          * Compares two Elements, typically the name of a method,
2059          * field or constructor.
2060          * @param e1 the first Element.
2061          * @param e2 the second Element.
2062          * @return a negative integer, zero, or a positive integer as the first
2063          *         argument is less than, equal to, or greater than the second.
2064          */
2065         protected int compareNames(Element e1, Element e2) {
2066             return compareStrings(getSimpleName(e1), getSimpleName(e2));
2067         }
2068 
2069         /**
2070          * Compares the fully qualified names of the entities
2071          * @param e1 the first Element.
2072          * @param e2 the first Element.
2073          * @return a negative integer, zero, or a positive integer as the first
2074          *         argument is less than, equal to, or greater than the second.
2075          */
2076         protected int compareFullyQualifiedNames(Element e1, Element e2) {
2077             // add simplename to be compatible
2078             String thisElement = getFullyQualifiedName(e1);
2079             String thatElement = getFullyQualifiedName(e2);
2080             return compareStrings(thisElement, thatElement);
2081         }
2082         protected int compareElementTypeKinds(Element e1, Element e2) {
2083             return Integer.compare(elementKindOrder.get(e1.getKind()),
2084                                    elementKindOrder.get(e2.getKind()));
2085         }
2086         boolean hasParameters(Element e) {
2087             return new SimpleElementVisitor9<Boolean, Void>() {
2088                 @Override
2089                 public Boolean visitExecutable(ExecutableElement e, Void p) {
2090                     return true;
2091                 }
2092 
2093                 @Override
2094                 protected Boolean defaultAction(Element e, Void p) {
2095                     return false;
2096                 }
2097 
2098             }.visit(e);
2099         }
2100 
2101         /**
2102          * The fully qualified names of the entities, used solely by the comparator.
2103          *
2104          * @return a negative integer, zero, or a positive integer as the first argument is less
2105          * than, equal to, or greater than the second.
2106          */
2107         private String getFullyQualifiedName(Element e) {
2108             return new SimpleElementVisitor9<String, Void>() {
2109                 @Override
2110                 public String visitModule(ModuleElement e, Void p) {
2111                     return e.getQualifiedName().toString();
2112                 }
2113 
2114                 @Override
2115                 public String visitPackage(PackageElement e, Void p) {
2116                     return e.getQualifiedName().toString();
2117                 }
2118 
2119                 @Override
2120                 public String visitExecutable(ExecutableElement e, Void p) {
2121                     // For backward compatibility
2122                     return getFullyQualifiedName(e.getEnclosingElement())
2123                             + "." + e.getSimpleName().toString();
2124                 }
2125 
2126                 @Override
2127                 public String visitType(TypeElement e, Void p) {
2128                     return e.getQualifiedName().toString();
2129                 }
2130 
2131                 @Override
2132                 protected String defaultAction(Element e, Void p) {
2133                     return getEnclosingTypeElement(e).getQualifiedName().toString()
2134                             + "." + e.getSimpleName().toString();
2135                 }
2136             }.visit(e);
2137         }
2138     }
2139 
2140     /**
2141      * Returns a Comparator for SearchIndexItems representing types. Items are
2142      * compared by short name, or full string representation if names are equal.
2143      *
2144      * @return a Comparator
2145      */
2146     public Comparator<SearchIndexItem> makeTypeSearchIndexComparator() {
2147         return (SearchIndexItem sii1, SearchIndexItem sii2) -> {
2148             int result = compareStrings(sii1.getSimpleName(), sii2.getSimpleName());
2149             if (result == 0) {
2150                 // TreeSet needs this to be consistent with equal so we do
2151                 // a plain comparison of string representations as fallback.
2152                 result = sii1.toString().compareTo(sii2.toString());
2153             }
2154             return result;
2155         };
2156     }
2157 
2158     private Comparator<SearchIndexItem> genericSearchIndexComparator = null;
2159     /**
2160      * Returns a Comparator for SearchIndexItems representing modules, packages, or members.
2161      * Items are compared by label (member name plus signature for members, package name for
2162      * packages, and module name for modules). If labels are equal then full string
2163      * representation is compared.
2164      *
2165      * @return a Comparator
2166      */
2167     public Comparator<SearchIndexItem> makeGenericSearchIndexComparator() {
2168         if (genericSearchIndexComparator == null) {
2169             genericSearchIndexComparator = (SearchIndexItem sii1, SearchIndexItem sii2) -> {
2170                 int result = compareStrings(sii1.getLabel(), sii2.getLabel());
2171                 if (result == 0) {
2172                     // TreeSet needs this to be consistent with equal so we do
2173                     // a plain comparison of string representations as fallback.
2174                     result = sii1.toString().compareTo(sii2.toString());
2175                 }
2176                 return result;
2177             };
2178         }
2179         return genericSearchIndexComparator;
2180     }
2181 
2182     public Iterable<TypeElement> getEnclosedTypeElements(PackageElement pkg) {
2183         List<TypeElement> out = getInterfaces(pkg);
2184         out.addAll(getClasses(pkg));
2185         out.addAll(getEnums(pkg));
2186         out.addAll(getAnnotationTypes(pkg));
2187         return out;
2188     }
2189 
2190     // Element related methods
2191     public List<Element> getAnnotationMembers(TypeElement aClass) {
2192         List<Element> members = getAnnotationFields(aClass);
2193         members.addAll(getAnnotationMethods(aClass));
2194         return members;
2195     }
2196 
2197     public List<Element> getAnnotationFields(TypeElement aClass) {
2198         return getItems0(aClass, true, FIELD);
2199     }
2200 
2201     List<Element> getAnnotationFieldsUnfiltered(TypeElement aClass) {
2202         return getItems0(aClass, true, FIELD);
2203     }
2204 
2205     public List<Element> getAnnotationMethods(TypeElement aClass) {
2206         return getItems0(aClass, true, METHOD);
2207     }
2208 
2209     public List<TypeElement> getAnnotationTypes(Element e) {
2210         return convertToTypeElement(getItems(e, true, ANNOTATION_TYPE));
2211     }
2212 
2213     public List<TypeElement> getAnnotationTypesUnfiltered(Element e) {
2214         return convertToTypeElement(getItems(e, false, ANNOTATION_TYPE));
2215     }
2216 
2217     public List<VariableElement> getFields(Element e) {
2218         return convertToVariableElement(getItems(e, true, FIELD));
2219     }
2220 
2221     public List<VariableElement> getFieldsUnfiltered(Element e) {
2222         return convertToVariableElement(getItems(e, false, FIELD));
2223     }
2224 
2225     public List<TypeElement> getClasses(Element e) {
2226        return convertToTypeElement(getItems(e, true, CLASS));
2227     }
2228 
2229     public List<TypeElement> getClassesUnfiltered(Element e) {
2230        return convertToTypeElement(getItems(e, false, CLASS));
2231     }
2232 
2233     public List<ExecutableElement> getConstructors(Element e) {
2234         return convertToExecutableElement(getItems(e, true, CONSTRUCTOR));
2235     }
2236 
2237     public List<ExecutableElement> getMethods(Element e) {
2238         return convertToExecutableElement(getItems(e, true, METHOD));
2239     }
2240 
2241     List<ExecutableElement> getMethodsUnfiltered(Element e) {
2242         return convertToExecutableElement(getItems(e, false, METHOD));
2243     }
2244 
2245     public int getOrdinalValue(VariableElement member) {
2246         if (member == null || member.getKind() != ENUM_CONSTANT) {
2247             throw new IllegalArgumentException("must be an enum constant: " + member);
2248         }
2249         return member.getEnclosingElement().getEnclosedElements().indexOf(member);
2250     }
2251 
2252     private Map<ModuleElement, Set<PackageElement>> modulePackageMap = null;
2253     public Map<ModuleElement, Set<PackageElement>> getModulePackageMap() {
2254         if (modulePackageMap == null) {
2255             modulePackageMap = new HashMap<>();
2256             Set<PackageElement> pkgs = configuration.getIncludedPackageElements();
2257             pkgs.forEach((pkg) -> {
2258                 ModuleElement mod = elementUtils.getModuleOf(pkg);
2259                 modulePackageMap.computeIfAbsent(mod, m -> new HashSet<>()).add(pkg);
2260             });
2261         }
2262         return modulePackageMap;
2263     }
2264 
2265     public Map<ModuleElement, String> getDependentModules(ModuleElement mdle) {
2266         Map<ModuleElement, String> result = new TreeMap<>(makeModuleComparator());
2267         Deque<ModuleElement> queue = new ArrayDeque<>();
2268         // get all the requires for the element in question
2269         for (RequiresDirective rd : ElementFilter.requiresIn(mdle.getDirectives())) {
2270             ModuleElement dep = rd.getDependency();
2271             // add the dependency to work queue
2272             if (!result.containsKey(dep)) {
2273                 if (rd.isTransitive()) {
2274                     queue.addLast(dep);
2275                 }
2276             }
2277             // add all exports for the primary module
2278             result.put(rd.getDependency(), getModifiers(rd));
2279         }
2280 
2281         // add only requires public for subsequent module dependencies
2282         for (ModuleElement m = queue.poll(); m != null; m = queue.poll()) {
2283             for (RequiresDirective rd : ElementFilter.requiresIn(m.getDirectives())) {
2284                 ModuleElement dep = rd.getDependency();
2285                 if (!result.containsKey(dep)) {
2286                     if (rd.isTransitive()) {
2287                         result.put(dep, getModifiers(rd));
2288                         queue.addLast(dep);
2289                     }
2290                 }
2291             }
2292         }
2293         return result;
2294     }
2295 
2296     public String getModifiers(RequiresDirective rd) {
2297         StringBuilder modifiers = new StringBuilder();
2298         String sep="";
2299         if (rd.isTransitive()) {
2300             modifiers.append("transitive");
2301             sep = " ";
2302         }
2303         if (rd.isStatic()) {
2304             modifiers.append(sep);
2305             modifiers.append("static");
2306         }
2307         return (modifiers.length() == 0) ? " " : modifiers.toString();
2308     }
2309 
2310     public long getLineNumber(Element e) {
2311         TreePath path = getTreePath(e);
2312         if (path == null) { // maybe null if synthesized
2313             TypeElement encl = getEnclosingTypeElement(e);
2314             path = getTreePath(encl);
2315         }
2316         CompilationUnitTree cu = path.getCompilationUnit();
2317         LineMap lineMap = cu.getLineMap();
2318         DocSourcePositions spos = docTrees.getSourcePositions();
2319         long pos = spos.getStartPosition(cu, path.getLeaf());
2320         return lineMap.getLineNumber(pos);
2321     }
2322 
2323     public List<ExecutableElement> convertToExecutableElement(List<Element> list) {
2324         List<ExecutableElement> out = new ArrayList<>(list.size());
2325         for (Element e : list) {
2326             out.add((ExecutableElement)e);
2327         }
2328         return out;
2329     }
2330 
2331     public List<TypeElement> convertToTypeElement(List<Element> list) {
2332         List<TypeElement> out = new ArrayList<>(list.size());
2333         for (Element e : list) {
2334             out.add((TypeElement)e);
2335         }
2336         return out;
2337     }
2338 
2339     public List<VariableElement> convertToVariableElement(List<Element> list) {
2340         List<VariableElement> out = new ArrayList<>(list.size());
2341         for (Element e : list) {
2342             out.add((VariableElement) e);
2343         }
2344         return out;
2345     }
2346 
2347     public List<TypeElement> getInterfaces(Element e)  {
2348         return convertToTypeElement(getItems(e, true, INTERFACE));
2349     }
2350 
2351     public List<TypeElement> getInterfacesUnfiltered(Element e)  {
2352         return convertToTypeElement(getItems(e, false, INTERFACE));
2353     }
2354 
2355     public List<Element> getEnumConstants(Element e) {
2356         return getItems(e, true, ENUM_CONSTANT);
2357     }
2358 
2359     public List<TypeElement> getEnums(Element e) {
2360         return convertToTypeElement(getItems(e, true, ENUM));
2361     }
2362 
2363     public List<TypeElement> getEnumsUnfiltered(Element e) {
2364         return convertToTypeElement(getItems(e, false, ENUM));
2365     }
2366 
2367     public SortedSet<TypeElement> getAllClassesUnfiltered(Element e) {
2368         List<TypeElement> clist = getClassesUnfiltered(e);
2369         clist.addAll(getInterfacesUnfiltered(e));
2370         clist.addAll(getAnnotationTypesUnfiltered(e));
2371         SortedSet<TypeElement> oset = new TreeSet<>(makeGeneralPurposeComparator());
2372         oset.addAll(clist);
2373         return oset;
2374     }
2375 
2376     private final HashMap<Element, SortedSet<TypeElement>> cachedClasses = new HashMap<>();
2377     /**
2378      * Returns a list containing classes and interfaces,
2379      * including annotation types.
2380      * @param e Element
2381      * @return List
2382      */
2383     public SortedSet<TypeElement> getAllClasses(Element e) {
2384         SortedSet<TypeElement> oset = cachedClasses.get(e);
2385         if (oset != null)
2386             return oset;
2387         List<TypeElement> clist = getClasses(e);
2388         clist.addAll(getInterfaces(e));
2389         clist.addAll(getAnnotationTypes(e));
2390         clist.addAll(getEnums(e));
2391         oset = new TreeSet<>(makeGeneralPurposeComparator());
2392         oset.addAll(clist);
2393         cachedClasses.put(e, oset);
2394         return oset;
2395     }
2396 
2397     /*
2398      * Get all the elements unfiltered and filter them finally based
2399      * on its visibility, this works differently from the other getters.
2400      */
2401     private List<TypeElement> getInnerClasses(Element e, boolean filter) {
2402         List<TypeElement> olist = new ArrayList<>();
2403         for (TypeElement te : getClassesUnfiltered(e)) {
2404             if (!filter || configuration.docEnv.isSelected(te)) {
2405                 olist.add(te);
2406             }
2407         }
2408         for (TypeElement te : getInterfacesUnfiltered(e)) {
2409             if (!filter || configuration.docEnv.isSelected(te)) {
2410                 olist.add(te);
2411             }
2412         }
2413         for (TypeElement te : getAnnotationTypesUnfiltered(e)) {
2414             if (!filter || configuration.docEnv.isSelected(te)) {
2415                 olist.add(te);
2416             }
2417         }
2418         for (TypeElement te : getEnumsUnfiltered(e)) {
2419             if (!filter || configuration.docEnv.isSelected(te)) {
2420                 olist.add(te);
2421             }
2422         }
2423         return olist;
2424     }
2425 
2426     public List<TypeElement> getInnerClasses(Element e) {
2427         return getInnerClasses(e, true);
2428     }
2429 
2430     public List<TypeElement> getInnerClassesUnfiltered(Element e) {
2431         return getInnerClasses(e, false);
2432     }
2433 
2434     /**
2435      * Returns a list of classes that are not errors or exceptions
2436      * @param e Element
2437      * @return List
2438      */
2439     public List<TypeElement> getOrdinaryClasses(Element e) {
2440         return getClasses(e).stream()
2441                 .filter(te -> (!isException(te) && !isError(te)))
2442                 .collect(Collectors.toList());
2443     }
2444 
2445     public List<TypeElement> getErrors(Element e) {
2446         return getClasses(e)
2447                 .stream()
2448                 .filter(this::isError)
2449                 .collect(Collectors.toList());
2450     }
2451 
2452     public List<TypeElement> getExceptions(Element e) {
2453         return getClasses(e)
2454                 .stream()
2455                 .filter(this::isException)
2456                 .collect(Collectors.toList());
2457     }
2458 
2459     List<Element> getItems(Element e, boolean filter, ElementKind select) {
2460         List<Element> elements = new ArrayList<>();
2461         return new SimpleElementVisitor9<List<Element>, Void>() {
2462 
2463             @Override
2464             public List<Element> visitPackage(PackageElement e, Void p) {
2465                 recursiveGetItems(elements, e, filter, select);
2466                 return elements;
2467             }
2468 
2469             @Override
2470             protected List<Element> defaultAction(Element e0, Void p) {
2471                 return getItems0(e0, filter, select);
2472             }
2473 
2474         }.visit(e);
2475     }
2476 
2477     EnumSet<ElementKind> nestedKinds = EnumSet.of(ANNOTATION_TYPE, CLASS, ENUM, INTERFACE);
2478     void recursiveGetItems(Collection<Element> list, Element e, boolean filter, ElementKind... select) {
2479         list.addAll(getItems0(e, filter, select));
2480         List<Element> classes = getItems0(e, filter, nestedKinds);
2481         for (Element c : classes) {
2482             list.addAll(getItems0(c, filter, select));
2483             if (isTypeElement(c)) {
2484                 recursiveGetItems(list, c, filter, select);
2485             }
2486         }
2487     }
2488 
2489     private List<Element> getItems0(Element te, boolean filter, ElementKind... select) {
2490         EnumSet<ElementKind> kinds = EnumSet.copyOf(Arrays.asList(select));
2491         return getItems0(te, filter, kinds);
2492     }
2493 
2494     private List<Element> getItems0(Element te, boolean filter, Set<ElementKind> kinds) {
2495         List<Element> elements = new ArrayList<>();
2496         for (Element e : te.getEnclosedElements()) {
2497             if (kinds.contains(e.getKind())) {
2498                 if (!filter || shouldDocument(e)) {
2499                     elements.add(e);
2500                 }
2501             }
2502         }
2503         return elements;
2504     }
2505 
2506     private SimpleElementVisitor9<Boolean, Void> shouldDocumentVisitor = null;
2507 
2508     protected boolean shouldDocument(Element e) {
2509         if (shouldDocumentVisitor == null) {
2510             shouldDocumentVisitor = new SimpleElementVisitor9<Boolean, Void>() {
2511                 private boolean hasSource(TypeElement e) {
2512                     return configuration.docEnv.getFileKind(e) ==
2513                             javax.tools.JavaFileObject.Kind.SOURCE;
2514                 }
2515 
2516                 // handle types
2517                 @Override
2518                 public Boolean visitType(TypeElement e, Void p) {
2519                     // treat inner classes etc as members
2520                     if (e.getNestingKind().isNested()) {
2521                         return defaultAction(e, p);
2522                     }
2523                     return configuration.docEnv.isSelected(e) && hasSource(e);
2524                 }
2525 
2526                 // handle everything else
2527                 @Override
2528                 protected Boolean defaultAction(Element e, Void p) {
2529                     return configuration.docEnv.isSelected(e);
2530                 }
2531 
2532                 @Override
2533                 public Boolean visitUnknown(Element e, Void p) {
2534                     throw new AssertionError("unkown element: " + p);
2535                 }
2536             };
2537         }
2538         return shouldDocumentVisitor.visit(e);
2539     }
2540 
2541     /*
2542      * nameCache is maintained for improving the comparator
2543      * performance, noting that the Collator used by the comparators
2544      * use Strings, as of this writing.
2545      * TODO: when those APIs handle charSequences, the use of
2546      * this nameCache must be re-investigated and removed.
2547      */
2548     private final Map<Element, String> nameCache = new LinkedHashMap<>();
2549 
2550     /**
2551      * Returns the name of the element after the last dot of the package name.
2552      * This emulates the behavior of the old doclet.
2553      * @param e an element whose name is required
2554      * @return the name
2555      */
2556     public String getSimpleName(Element e) {
2557         return nameCache.computeIfAbsent(e, this::getSimpleName0);
2558     }
2559 
2560     private SimpleElementVisitor9<String, Void> snvisitor = null;
2561 
2562     private String getSimpleName0(Element e) {
2563         if (snvisitor == null) {
2564             snvisitor = new SimpleElementVisitor9<String, Void>() {
2565                 @Override
2566                 public String visitModule(ModuleElement e, Void p) {
2567                     return e.getQualifiedName().toString();  // temp fix for 8182736
2568                 }
2569 
2570                 @Override
2571                 public String visitType(TypeElement e, Void p) {
2572                     StringBuilder sb = new StringBuilder(e.getSimpleName());
2573                     Element enclosed = e.getEnclosingElement();
2574                     while (enclosed != null
2575                             && (enclosed.getKind().isClass() || enclosed.getKind().isInterface())) {
2576                         sb.insert(0, enclosed.getSimpleName() + ".");
2577                         enclosed = enclosed.getEnclosingElement();
2578                     }
2579                     return sb.toString();
2580                 }
2581 
2582                 @Override
2583                 public String visitExecutable(ExecutableElement e, Void p) {
2584                     if (e.getKind() == CONSTRUCTOR || e.getKind() == STATIC_INIT) {
2585                         return e.getEnclosingElement().getSimpleName().toString();
2586                     }
2587                     return e.getSimpleName().toString();
2588                 }
2589 
2590                 @Override
2591                 protected String defaultAction(Element e, Void p) {
2592                     return e.getSimpleName().toString();
2593                 }
2594             };
2595         }
2596         return snvisitor.visit(e);
2597     }
2598 
2599     public TypeElement getEnclosingTypeElement(Element e) {
2600         if (e.getKind() == ElementKind.PACKAGE)
2601             return null;
2602         Element encl = e.getEnclosingElement();
2603         ElementKind kind = encl.getKind();
2604         if (kind == ElementKind.PACKAGE)
2605             return null;
2606         while (!(kind.isClass() || kind.isInterface())) {
2607             encl = encl.getEnclosingElement();
2608             kind = encl.getKind();
2609         }
2610         return (TypeElement)encl;
2611     }
2612 
2613     private ConstantValueExpression cve = null;
2614 
2615     public String constantValueExpresion(VariableElement ve) {
2616         if (cve == null)
2617             cve = new ConstantValueExpression();
2618         return cve.constantValueExpression(configuration.workArounds, ve);
2619     }
2620 
2621     private static class ConstantValueExpression {
2622         public String constantValueExpression(WorkArounds workArounds, VariableElement ve) {
2623             return new TypeKindVisitor9<String, Object>() {
2624                 /* TODO: we need to fix this correctly.
2625                  * we have a discrepancy here, note the use of getConstValue
2626                  * vs. getConstantValue, at some point we need to use
2627                  * getConstantValue.
2628                  * In the legacy world byte and char primitives appear as Integer values,
2629                  * thus a byte value of 127 will appear as 127, but in the new world,
2630                  * a byte value appears as Byte thus 0x7f will be printed, similarly
2631                  * chars will be  translated to \n, \r etc. however, in the new world,
2632                  * they will be printed as decimal values. The new world is correct,
2633                  * and we should fix this by using getConstantValue and the visitor to
2634                  * address this in the future.
2635                  */
2636                 @Override
2637                 public String visitPrimitiveAsBoolean(PrimitiveType t, Object val) {
2638                     return (int)val == 0 ? "false" : "true";
2639                 }
2640 
2641                 @Override
2642                 public String visitPrimitiveAsDouble(PrimitiveType t, Object val) {
2643                     return sourceForm(((Double)val), 'd');
2644                 }
2645 
2646                 @Override
2647                 public String visitPrimitiveAsFloat(PrimitiveType t, Object val) {
2648                     return sourceForm(((Float)val).doubleValue(), 'f');
2649                 }
2650 
2651                 @Override
2652                 public String visitPrimitiveAsLong(PrimitiveType t, Object val) {
2653                     return val + "L";
2654                 }
2655 
2656                 @Override
2657                 protected String defaultAction(TypeMirror e, Object val) {
2658                     if (val == null)
2659                         return null;
2660                     else if (val instanceof Character)
2661                         return sourceForm(((Character)val));
2662                     else if (val instanceof Byte)
2663                         return sourceForm(((Byte)val));
2664                     else if (val instanceof String)
2665                         return sourceForm((String)val);
2666                     return val.toString(); // covers int, short
2667                 }
2668             }.visit(ve.asType(), workArounds.getConstValue(ve));
2669         }
2670 
2671         // where
2672         private String sourceForm(double v, char suffix) {
2673             if (Double.isNaN(v))
2674                 return "0" + suffix + "/0" + suffix;
2675             if (v == Double.POSITIVE_INFINITY)
2676                 return "1" + suffix + "/0" + suffix;
2677             if (v == Double.NEGATIVE_INFINITY)
2678                 return "-1" + suffix + "/0" + suffix;
2679             return v + (suffix == 'f' || suffix == 'F' ? "" + suffix : "");
2680         }
2681 
2682         private  String sourceForm(char c) {
2683             StringBuilder buf = new StringBuilder(8);
2684             buf.append('\'');
2685             sourceChar(c, buf);
2686             buf.append('\'');
2687             return buf.toString();
2688         }
2689 
2690         private String sourceForm(byte c) {
2691             return "0x" + Integer.toString(c & 0xff, 16);
2692         }
2693 
2694         private String sourceForm(String s) {
2695             StringBuilder buf = new StringBuilder(s.length() + 5);
2696             buf.append('\"');
2697             for (int i=0; i<s.length(); i++) {
2698                 char c = s.charAt(i);
2699                 sourceChar(c, buf);
2700             }
2701             buf.append('\"');
2702             return buf.toString();
2703         }
2704 
2705         private void sourceChar(char c, StringBuilder buf) {
2706             switch (c) {
2707             case '\b': buf.append("\\b"); return;
2708             case '\t': buf.append("\\t"); return;
2709             case '\n': buf.append("\\n"); return;
2710             case '\f': buf.append("\\f"); return;
2711             case '\r': buf.append("\\r"); return;
2712             case '\"': buf.append("\\\""); return;
2713             case '\'': buf.append("\\\'"); return;
2714             case '\\': buf.append("\\\\"); return;
2715             default:
2716                 if (isPrintableAscii(c)) {
2717                     buf.append(c); return;
2718                 }
2719                 unicodeEscape(c, buf);
2720                 return;
2721             }
2722         }
2723 
2724         private void unicodeEscape(char c, StringBuilder buf) {
2725             final String chars = "0123456789abcdef";
2726             buf.append("\\u");
2727             buf.append(chars.charAt(15 & (c>>12)));
2728             buf.append(chars.charAt(15 & (c>>8)));
2729             buf.append(chars.charAt(15 & (c>>4)));
2730             buf.append(chars.charAt(15 & (c>>0)));
2731         }
2732         private boolean isPrintableAscii(char c) {
2733             return c >= ' ' && c <= '~';
2734         }
2735     }
2736 
2737     public boolean isEnclosingPackageIncluded(TypeElement te) {
2738         return isIncluded(containingPackage(te));
2739     }
2740 
2741     public boolean isIncluded(Element e) {
2742         return configuration.docEnv.isIncluded(e);
2743     }
2744 
2745     private SimpleElementVisitor9<Boolean, Void> specifiedVisitor = null;
2746     public boolean isSpecified(Element e) {
2747         if (specifiedVisitor == null) {
2748             specifiedVisitor = new SimpleElementVisitor9<Boolean, Void>() {
2749                 @Override
2750                 public Boolean visitModule(ModuleElement e, Void p) {
2751                     return configuration.getSpecifiedModuleElements().contains(e);
2752                 }
2753 
2754                 @Override
2755                 public Boolean visitPackage(PackageElement e, Void p) {
2756                     return configuration.getSpecifiedPackageElements().contains(e);
2757                 }
2758 
2759                 @Override
2760                 public Boolean visitType(TypeElement e, Void p) {
2761                     return configuration.getSpecifiedTypeElements().contains(e);
2762                 }
2763 
2764                 @Override
2765                 protected Boolean defaultAction(Element e, Void p) {
2766                     return false;
2767                 }
2768             };
2769         }
2770         return specifiedVisitor.visit(e);
2771     }
2772 
2773     /**
2774      * Get the package name for a given package element. An unnamed package is returned as &lt;Unnamed&gt;
2775      *
2776      * @param pkg
2777      * @return
2778      */
2779     public String getPackageName(PackageElement pkg) {
2780         if (pkg == null || pkg.isUnnamed()) {
2781             return DocletConstants.DEFAULT_PACKAGE_NAME;
2782         }
2783         return pkg.getQualifiedName().toString();
2784     }
2785 
2786     /**
2787      * Get the module name for a given module element. An unnamed module is returned as &lt;Unnamed&gt;
2788      *
2789      * @param mdle a ModuleElement
2790      * @return
2791      */
2792     public String getModuleName(ModuleElement mdle) {
2793         if (mdle == null || mdle.isUnnamed()) {
2794             return DocletConstants.DEFAULT_ELEMENT_NAME;
2795         }
2796         return mdle.getQualifiedName().toString();
2797     }
2798 
2799     public boolean isAttribute(DocTree doctree) {
2800         return isKind(doctree, ATTRIBUTE);
2801     }
2802 
2803     public boolean isAuthor(DocTree doctree) {
2804         return isKind(doctree, AUTHOR);
2805     }
2806 
2807     public boolean isComment(DocTree doctree) {
2808         return isKind(doctree, COMMENT);
2809     }
2810 
2811     public boolean isDeprecated(DocTree doctree) {
2812         return isKind(doctree, DEPRECATED);
2813     }
2814 
2815     public boolean isDocComment(DocTree doctree) {
2816         return isKind(doctree, DOC_COMMENT);
2817     }
2818 
2819     public boolean isDocRoot(DocTree doctree) {
2820         return isKind(doctree, DOC_ROOT);
2821     }
2822 
2823     public boolean isEndElement(DocTree doctree) {
2824         return isKind(doctree, END_ELEMENT);
2825     }
2826 
2827     public boolean isEntity(DocTree doctree) {
2828         return isKind(doctree, ENTITY);
2829     }
2830 
2831     public boolean isErroneous(DocTree doctree) {
2832         return isKind(doctree, ERRONEOUS);
2833     }
2834 
2835     public boolean isException(DocTree doctree) {
2836         return isKind(doctree, EXCEPTION);
2837     }
2838 
2839     public boolean isIdentifier(DocTree doctree) {
2840         return isKind(doctree, IDENTIFIER);
2841     }
2842 
2843     public boolean isInheritDoc(DocTree doctree) {
2844         return isKind(doctree, INHERIT_DOC);
2845     }
2846 
2847     public boolean isLink(DocTree doctree) {
2848         return isKind(doctree, LINK);
2849     }
2850 
2851     public boolean isLinkPlain(DocTree doctree) {
2852         return isKind(doctree, LINK_PLAIN);
2853     }
2854 
2855     public boolean isLiteral(DocTree doctree) {
2856         return isKind(doctree, LITERAL);
2857     }
2858 
2859     public boolean isOther(DocTree doctree) {
2860         return doctree.getKind() == DocTree.Kind.OTHER;
2861     }
2862 
2863     public boolean isParam(DocTree doctree) {
2864         return isKind(doctree, PARAM);
2865     }
2866 
2867     public boolean isReference(DocTree doctree) {
2868         return isKind(doctree, REFERENCE);
2869     }
2870 
2871     public boolean isReturn(DocTree doctree) {
2872         return isKind(doctree, RETURN);
2873     }
2874 
2875     public boolean isSee(DocTree doctree) {
2876         return isKind(doctree, SEE);
2877     }
2878 
2879     public boolean isSerial(DocTree doctree) {
2880         return isKind(doctree, SERIAL);
2881     }
2882 
2883     public boolean isSerialData(DocTree doctree) {
2884         return isKind(doctree, SERIAL_DATA);
2885     }
2886 
2887     public boolean isSerialField(DocTree doctree) {
2888         return isKind(doctree, SERIAL_FIELD);
2889     }
2890 
2891     public boolean isSince(DocTree doctree) {
2892         return isKind(doctree, SINCE);
2893     }
2894 
2895     public boolean isStartElement(DocTree doctree) {
2896         return isKind(doctree, START_ELEMENT);
2897     }
2898 
2899     public boolean isText(DocTree doctree) {
2900         return isKind(doctree, TEXT);
2901     }
2902 
2903     public boolean isThrows(DocTree doctree) {
2904         return isKind(doctree, THROWS);
2905     }
2906 
2907     public boolean isUnknownBlockTag(DocTree doctree) {
2908         return isKind(doctree, UNKNOWN_BLOCK_TAG);
2909     }
2910 
2911     public boolean isUnknownInlineTag(DocTree doctree) {
2912         return isKind(doctree, UNKNOWN_INLINE_TAG);
2913     }
2914 
2915     public boolean isValue(DocTree doctree) {
2916         return isKind(doctree, VALUE);
2917     }
2918 
2919     public boolean isVersion(DocTree doctree) {
2920         return isKind(doctree, VERSION);
2921     }
2922 
2923     private boolean isKind(DocTree doctree, DocTree.Kind match) {
2924         return  doctree.getKind() == match;
2925     }
2926 
2927     private final WeakSoftHashMap wksMap = new WeakSoftHashMap(this);
2928 
2929     public CommentHelper getCommentHelper(Element element) {
2930         return wksMap.computeIfAbsent(element);
2931     }
2932 
2933     public void removeCommentHelper(Element element) {
2934         wksMap.remove(element);
2935     }
2936 
2937     public List<? extends DocTree> filteredList(List<? extends DocTree> dlist, DocTree.Kind... select) {
2938         List<DocTree> list = new ArrayList<>(dlist.size());
2939         if (select == null)
2940             return dlist;
2941         for (DocTree dt : dlist) {
2942             if (dt.getKind() != ERRONEOUS) {
2943                 for (DocTree.Kind kind : select) {
2944                     if (dt.getKind() == kind) {
2945                         list.add(dt);
2946                     }
2947                 }
2948             }
2949         }
2950         return list;
2951     }
2952 
2953     private List<? extends DocTree> getBlockTags0(Element element, DocTree.Kind... kinds) {
2954         DocCommentTree dcTree = getDocCommentTree(element);
2955         if (dcTree == null)
2956             return Collections.emptyList();
2957 
2958         return filteredList(dcTree.getBlockTags(), kinds);
2959     }
2960 
2961     public List<? extends DocTree> getBlockTags(Element element) {
2962         return getBlockTags0(element, (Kind[]) null);
2963     }
2964 
2965     public List<? extends DocTree> getBlockTags(Element element, DocTree.Kind... kinds) {
2966         return getBlockTags0(element, kinds);
2967     }
2968 
2969     public List<? extends DocTree> getBlockTags(Element element, String tagName) {
2970         DocTree.Kind kind = null;
2971         switch (tagName) {
2972             case "author":
2973             case "deprecated":
2974             case "hidden":
2975             case "param":
2976             case "return":
2977             case "see":
2978             case "serial":
2979             case "since":
2980             case "throws":
2981             case "exception":
2982             case "version":
2983                 kind = DocTree.Kind.valueOf(toUpperCase(tagName));
2984                 return getBlockTags(element, kind);
2985             case "serialData":
2986                 kind = SERIAL_DATA;
2987                 return getBlockTags(element, kind);
2988             case "serialField":
2989                 kind = SERIAL_FIELD;
2990                 return getBlockTags(element, kind);
2991             default:
2992                 kind = DocTree.Kind.UNKNOWN_BLOCK_TAG;
2993                 break;
2994         }
2995         List<? extends DocTree> blockTags = getBlockTags(element, kind);
2996         List<DocTree> out = new ArrayList<>();
2997         String tname = tagName.startsWith("@") ? tagName.substring(1) : tagName;
2998         CommentHelper ch = getCommentHelper(element);
2999         for (DocTree dt : blockTags) {
3000             if (ch.getTagName(dt).equals(tname)) {
3001                 out.add(dt);
3002             }
3003         }
3004         return out;
3005     }
3006 
3007     public boolean hasBlockTag(Element element, DocTree.Kind kind) {
3008         return hasBlockTag(element, kind, null);
3009     }
3010 
3011     public boolean hasBlockTag(Element element, DocTree.Kind kind, final String tagName) {
3012         CommentHelper ch = getCommentHelper(element);
3013         String tname = tagName != null && tagName.startsWith("@")
3014                 ? tagName.substring(1)
3015                 : tagName;
3016         for (DocTree dt : getBlockTags(element, kind)) {
3017             if (dt.getKind() == kind) {
3018                 if (tname == null || ch.getTagName(dt).equals(tname)) {
3019                     return true;
3020                 }
3021             }
3022         }
3023         return false;
3024     }
3025 
3026     /**
3027      * Gets a TreePath for an Element. Note this method is called very
3028      * frequently, care must be taken to ensure this method is lithe
3029      * and efficient.
3030      * @param e an Element
3031      * @return TreePath
3032      */
3033     public TreePath getTreePath(Element e) {
3034         DocCommentDuo duo = dcTreeCache.get(e);
3035         if (duo != null && duo.treePath != null) {
3036             return duo.treePath;
3037         }
3038         duo = configuration.cmtUtils.getSyntheticCommentDuo(e);
3039         if (duo != null && duo.treePath != null) {
3040             return duo.treePath;
3041         }
3042         Map<Element, TreePath> elementToTreePath = configuration.workArounds.getElementToTreePath();
3043         TreePath path = elementToTreePath.get(e);
3044         if (path != null || elementToTreePath.containsKey(e)) {
3045             // expedite the path and one that is a null
3046             return path;
3047         }
3048         return elementToTreePath.computeIfAbsent(e, docTrees::getPath);
3049     }
3050 
3051     private final Map<Element, DocCommentDuo> dcTreeCache = new LinkedHashMap<>();
3052 
3053     /**
3054      * Retrieves the doc comments for a given element.
3055      * @param element
3056      * @return DocCommentTree for the Element
3057      */
3058     public DocCommentTree getDocCommentTree0(Element element) {
3059 
3060         DocCommentDuo duo = null;
3061 
3062         ElementKind kind = element.getKind();
3063         if (kind == ElementKind.PACKAGE || kind == ElementKind.OTHER) {
3064             duo = dcTreeCache.get(element); // local cache
3065             if (duo == null && kind == ElementKind.PACKAGE) {
3066                 // package-info.java
3067                 duo = getDocCommentTuple(element);
3068             }
3069             if (duo == null) {
3070                 // package.html or overview.html
3071                 duo = configuration.cmtUtils.getHtmlCommentDuo(element); // html source
3072             }
3073         } else {
3074             duo = configuration.cmtUtils.getSyntheticCommentDuo(element);
3075             if (duo == null) {
3076                 duo = dcTreeCache.get(element); // local cache
3077             }
3078             if (duo == null) {
3079                 duo = getDocCommentTuple(element); // get the real mccoy
3080             }
3081         }
3082 
3083         DocCommentTree docCommentTree = isValidDuo(duo) ? duo.dcTree : null;
3084         TreePath path = isValidDuo(duo) ? duo.treePath : null;
3085         if (!dcTreeCache.containsKey(element)) {
3086             if (docCommentTree != null && path != null) {
3087                 if (!configuration.isAllowScriptInComments()) {
3088                     try {
3089                         javaScriptScanner.scan(docCommentTree, path, p -> {
3090                             throw new JavaScriptScanner.Fault();
3091                         });
3092                     } catch (JavaScriptScanner.Fault jsf) {
3093                         String text = resources.getText("doclet.JavaScript_in_comment");
3094                         throw new UncheckedDocletException(new SimpleDocletException(text, jsf));
3095                     }
3096                 }
3097                 configuration.workArounds.runDocLint(path);
3098             }
3099             dcTreeCache.put(element, duo);
3100         }
3101         return docCommentTree;
3102     }
3103 
3104     private DocCommentDuo getDocCommentTuple(Element element) {
3105         // prevent nasty things downstream with overview element
3106         if (element.getKind() != ElementKind.OTHER) {
3107             TreePath path = getTreePath(element);
3108             if (path != null) {
3109                 DocCommentTree docCommentTree = docTrees.getDocCommentTree(path);
3110                 return new DocCommentDuo(path, docCommentTree);
3111             }
3112         }
3113         return null;
3114     }
3115 
3116     public void checkJavaScriptInOption(String name, String value) {
3117         if (!configuration.isAllowScriptInComments()) {
3118             DocCommentTree dct = configuration.cmtUtils.parse(
3119                     URI.create("option://" + name.replace("-", "")), "<body>" + value + "</body>");
3120 
3121             if (dct == null)
3122                 return;
3123 
3124             try {
3125                 javaScriptScanner.scan(dct, null, p -> {
3126                     throw new JavaScriptScanner.Fault();
3127                 });
3128             } catch (JavaScriptScanner.Fault jsf) {
3129                 String text = resources.getText("doclet.JavaScript_in_option", name);
3130                 throw new UncheckedDocletException(new SimpleDocletException(text, jsf));
3131             }
3132         }
3133     }
3134 
3135     boolean isValidDuo(DocCommentDuo duo) {
3136         return duo != null && duo.dcTree != null;
3137     }
3138 
3139     public DocCommentTree getDocCommentTree(Element element) {
3140         CommentHelper ch = wksMap.get(element);
3141         if (ch != null) {
3142             return ch.dctree;
3143         }
3144         DocCommentTree dcTree = getDocCommentTree0(element);
3145         if (dcTree != null) {
3146             wksMap.put(element, new CommentHelper(configuration, element, getTreePath(element), dcTree));
3147         }
3148         return dcTree;
3149     }
3150 
3151     public List<? extends DocTree> getPreamble(Element element) {
3152         DocCommentTree docCommentTree = getDocCommentTree(element);
3153         return docCommentTree == null
3154                 ? Collections.emptyList()
3155                 : docCommentTree.getPreamble();
3156     }
3157 
3158     public List<? extends DocTree> getFullBody(Element element) {
3159         DocCommentTree docCommentTree = getDocCommentTree(element);
3160             return (docCommentTree == null)
3161                     ? Collections.emptyList()
3162                     : docCommentTree.getFullBody();
3163     }
3164 
3165     public List<? extends DocTree> getBody(Element element) {
3166         DocCommentTree docCommentTree = getDocCommentTree(element);
3167         return (docCommentTree == null)
3168                 ? Collections.emptyList()
3169                 : docCommentTree.getFullBody();
3170     }
3171 
3172     public List<? extends DocTree> getDeprecatedTrees(Element element) {
3173         return getBlockTags(element, DEPRECATED);
3174     }
3175 
3176     public List<? extends DocTree> getProvidesTrees(Element element) {
3177         return getBlockTags(element, PROVIDES);
3178     }
3179 
3180     public List<? extends DocTree> getSeeTrees(Element element) {
3181         return getBlockTags(element, SEE);
3182     }
3183 
3184     public List<? extends DocTree> getSerialTrees(Element element) {
3185         return getBlockTags(element, SERIAL);
3186     }
3187 
3188     public List<? extends DocTree> getSerialFieldTrees(VariableElement field) {
3189         return getBlockTags(field, DocTree.Kind.SERIAL_FIELD);
3190     }
3191 
3192     public List<? extends DocTree> getThrowsTrees(Element element) {
3193         return getBlockTags(element, DocTree.Kind.EXCEPTION, DocTree.Kind.THROWS);
3194     }
3195 
3196     public List<? extends DocTree> getTypeParamTrees(Element element) {
3197         return getParamTrees(element, true);
3198     }
3199 
3200     public List<? extends DocTree> getParamTrees(Element element) {
3201         return getParamTrees(element, false);
3202     }
3203 
3204     private  List<? extends DocTree> getParamTrees(Element element, boolean isTypeParameters) {
3205         List<DocTree> out = new ArrayList<>();
3206         for (DocTree dt : getBlockTags(element, PARAM)) {
3207             ParamTree pt = (ParamTree) dt;
3208             if (pt.isTypeParameter() == isTypeParameters) {
3209                 out.add(dt);
3210             }
3211         }
3212         return out;
3213     }
3214 
3215     public  List<? extends DocTree> getReturnTrees(Element element) {
3216         List<DocTree> out = new ArrayList<>();
3217         for (DocTree dt : getBlockTags(element, RETURN)) {
3218             out.add(dt);
3219         }
3220         return out;
3221     }
3222 
3223     public List<? extends DocTree> getUsesTrees(Element element) {
3224         return getBlockTags(element, USES);
3225     }
3226 
3227     public List<? extends DocTree> getFirstSentenceTrees(Element element) {
3228         DocCommentTree dcTree = getDocCommentTree(element);
3229         if (dcTree == null) {
3230             return Collections.emptyList();
3231         }
3232         List<DocTree> out = new ArrayList<>();
3233         for (DocTree dt : dcTree.getFirstSentence()) {
3234             out.add(dt);
3235         }
3236         return out;
3237     }
3238 
3239     public ModuleElement containingModule(Element e) {
3240         return elementUtils.getModuleOf(e);
3241     }
3242 
3243     public PackageElement containingPackage(Element e) {
3244         return elementUtils.getPackageOf(e);
3245     }
3246 
3247     public TypeElement getTopMostContainingTypeElement(Element e) {
3248         if (isPackage(e)) {
3249             return null;
3250         }
3251         TypeElement outer = getEnclosingTypeElement(e);
3252         if (outer == null)
3253             return (TypeElement)e;
3254         while (outer != null && outer.getNestingKind().isNested()) {
3255             outer = getEnclosingTypeElement(outer);
3256         }
3257         return outer;
3258     }
3259 
3260     static class WeakSoftHashMap implements Map<Element, CommentHelper> {
3261 
3262         private final WeakHashMap<Element, SoftReference<CommentHelper>> wkMap;
3263         private final Utils utils;
3264         public WeakSoftHashMap(Utils utils) {
3265             wkMap = new WeakHashMap<>();
3266             this.utils = utils;
3267         }
3268 
3269         @Override
3270         public boolean containsKey(Object key) {
3271             return wkMap.containsKey(key);
3272         }
3273 
3274         @Override
3275         public Collection<CommentHelper> values() {
3276             Set<CommentHelper> out = new LinkedHashSet<>();
3277             for (SoftReference<CommentHelper> v : wkMap.values()) {
3278                 out.add(v.get());
3279             }
3280             return out;
3281         }
3282 
3283         @Override
3284         public boolean containsValue(Object value) {
3285             return wkMap.containsValue(new SoftReference<>((CommentHelper)value));
3286         }
3287 
3288         @Override
3289         public CommentHelper remove(Object key) {
3290             SoftReference<CommentHelper> value = wkMap.remove(key);
3291             return value == null ? null : value.get();
3292         }
3293 
3294 
3295         @Override
3296         public CommentHelper put(Element key, CommentHelper value) {
3297             SoftReference<CommentHelper> nvalue = wkMap.put(key, new SoftReference<>(value));
3298             return nvalue == null ? null : nvalue.get();
3299         }
3300 
3301         @Override
3302         public CommentHelper get(Object key) {
3303             SoftReference<CommentHelper> value = wkMap.get(key);
3304             return value == null ? null : value.get();
3305         }
3306 
3307         @Override
3308         public int size() {
3309             return wkMap.size();
3310         }
3311 
3312         @Override
3313         public boolean isEmpty() {
3314             return wkMap.isEmpty();
3315         }
3316 
3317         @Override
3318         public void clear() {
3319             wkMap.clear();
3320         }
3321 
3322         public CommentHelper computeIfAbsent(Element key) {
3323             if (wkMap.containsKey(key)) {
3324                 SoftReference<CommentHelper> value = wkMap.get(key);
3325                 if (value != null) {
3326                     CommentHelper cvalue = value.get();
3327                     if (cvalue != null) {
3328                         return cvalue;
3329                     }
3330                 }
3331             }
3332             CommentHelper newValue = new CommentHelper(utils.configuration, key, utils.getTreePath(key),
3333                     utils.getDocCommentTree(key));
3334             wkMap.put(key, new SoftReference<>(newValue));
3335             return newValue;
3336         }
3337 
3338 
3339         @Override
3340         public void putAll(Map<? extends Element, ? extends CommentHelper> map) {
3341             for (Map.Entry<? extends Element, ? extends CommentHelper> entry : map.entrySet()) {
3342                 put(entry.getKey(), entry.getValue());
3343             }
3344         }
3345 
3346         @Override
3347         public Set<Element> keySet() {
3348             return wkMap.keySet();
3349         }
3350 
3351         @Override
3352         public Set<Entry<Element, CommentHelper>> entrySet() {
3353             Set<Entry<Element, CommentHelper>> out = new LinkedHashSet<>();
3354             for (Element e : wkMap.keySet()) {
3355                 SimpleEntry<Element, CommentHelper> n = new SimpleEntry<>(e, get(e));
3356                 out.add(n);
3357             }
3358             return out;
3359         }
3360     }
3361 
3362     /**
3363      * A simple pair container.
3364      * @param <K> first a value
3365      * @param <L> second another value
3366      */
3367     public static class Pair<K, L> {
3368         public final K first;
3369         public final L second;
3370 
3371         public Pair(K first, L second) {
3372             this.first = first;
3373             this.second = second;
3374         }
3375 
3376         public String toString() {
3377             StringBuffer out = new StringBuffer();
3378             out.append(first + ":" + second);
3379             return out.toString();
3380         }
3381     }
3382 }