1 /*
   2  * Copyright (c) 1997, 2019, 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.tool;
  27 
  28 import java.io.File;
  29 import java.io.IOException;
  30 import java.io.PrintWriter;
  31 import java.text.BreakIterator;
  32 import java.text.Collator;
  33 import java.util.ArrayList;
  34 import java.util.Arrays;
  35 import java.util.Collections;
  36 import java.util.Comparator;
  37 import java.util.IllformedLocaleException;
  38 import java.util.List;
  39 import java.util.Locale;
  40 import java.util.MissingResourceException;
  41 import java.util.Objects;
  42 import java.util.ResourceBundle;
  43 import java.util.Set;
  44 import java.util.stream.Collectors;
  45 
  46 import javax.tools.JavaFileManager;
  47 import javax.tools.JavaFileObject;
  48 import javax.tools.StandardJavaFileManager;
  49 
  50 import com.sun.tools.javac.api.JavacTrees;
  51 import com.sun.tools.javac.file.BaseFileManager;
  52 import com.sun.tools.javac.file.JavacFileManager;
  53 import com.sun.tools.javac.jvm.Target;
  54 import com.sun.tools.javac.main.Arguments;
  55 import com.sun.tools.javac.main.CommandLine;
  56 import com.sun.tools.javac.util.ClientCodeException;
  57 import com.sun.tools.javac.util.Context;
  58 import com.sun.tools.javac.util.Log;
  59 import com.sun.tools.javac.util.StringUtils;
  60 
  61 import jdk.javadoc.doclet.Doclet;
  62 import jdk.javadoc.doclet.Doclet.Option;
  63 import jdk.javadoc.doclet.DocletEnvironment;
  64 import jdk.javadoc.doclet.StandardDoclet;
  65 import jdk.javadoc.internal.tool.Main.Result;
  66 import jdk.javadoc.internal.tool.ToolOptions.ToolOption;
  67 
  68 import static javax.tools.DocumentationTool.Location.*;
  69 
  70 import static com.sun.tools.javac.main.Option.*;
  71 import static jdk.javadoc.internal.tool.Main.Result.*;
  72 
  73 /**
  74  * Main program of Javadoc.
  75  * Previously named "Main".
  76  *
  77  *  <p><b>This is NOT part of any supported API.
  78  *  If you write code that depends on this, you do so at your own risk.
  79  *  This code and its internal interfaces are subject to change or
  80  *  deletion without notice.</b>
  81  */
  82 public class Start {
  83 
  84     /** Context for this invocation. */
  85     private final Context context;
  86 
  87     private static final String ProgramName = "javadoc";
  88 
  89     private Messager messager;
  90 
  91     private final String docletName;
  92 
  93     private final ClassLoader classLoader;
  94 
  95     private Class<?> docletClass;
  96 
  97     private Doclet doclet;
  98 
  99     // used to determine the locale for the messager
 100     private Locale locale;
 101 
 102 
 103     /**
 104      * In API mode, exceptions thrown while calling the doclet are
 105      * propagated using ClientCodeException.
 106      */
 107     private boolean apiMode;
 108 
 109     private JavaFileManager fileManager;
 110 
 111     private final ToolOptions options;
 112 
 113     Start() {
 114         this(null, null, null, null, null, null);
 115     }
 116 
 117     Start(PrintWriter outWriter, PrintWriter errWriter) {
 118         this(null, null, outWriter, errWriter, null, null);
 119     }
 120 
 121     Start(Context context, String programName,
 122             PrintWriter outWriter, PrintWriter errWriter,
 123             String docletName, ClassLoader classLoader) {
 124         this.context = context == null ? new Context() : context;
 125         String pname = programName == null ? ProgramName : programName;
 126         this.messager = (outWriter == null && errWriter == null)
 127                 ? new Messager(this.context, pname)
 128                 : new Messager(this.context, pname, outWriter, errWriter);
 129         this.docletName = docletName;
 130         this.classLoader = classLoader;
 131         this.docletClass = null;
 132         this.locale = Locale.getDefault();
 133 
 134         options = getToolOptions();
 135     }
 136 
 137     public Start(Context context) {
 138         this.docletClass = null;
 139         this.context = Objects.requireNonNull(context);
 140         this.apiMode = true;
 141         this.docletName = null;
 142         this.classLoader = null;
 143         this.locale = Locale.getDefault();
 144 
 145         Log log = context.get(Log.logKey);
 146         if (log instanceof Messager) {
 147             messager = (Messager) log;
 148         } else {
 149             PrintWriter out = context.get(Log.errKey);
 150             messager = (out == null)
 151                     ? new Messager(context, ProgramName)
 152                     : new Messager(context, ProgramName, out, out);
 153         }
 154 
 155         options = getToolOptions();
 156     }
 157 
 158     private ToolOptions getToolOptions() {
 159         ToolOptions.ShowHelper helper =  new ToolOptions.ShowHelper() {
 160             @Override
 161             public void usage() {
 162                 showUsage("main.usage", OptionKind.STANDARD, "main.usage.foot");
 163             }
 164 
 165             @Override
 166             public void Xusage() {
 167                 showUsage("main.Xusage", OptionKind.EXTENDED, "main.Xusage.foot");
 168             }
 169 
 170             @Override
 171             public void version() {
 172                 showVersion("javadoc.version", "release");
 173             }
 174 
 175             @Override
 176             public void fullVersion() {
 177                 showVersion("javadoc.fullversion", "full");
 178             }
 179         };
 180         return new ToolOptions(context, messager, helper);
 181     }
 182 
 183     private void showUsage() {
 184         showUsage("main.usage", OptionKind.STANDARD, "main.usage.foot");
 185     }
 186 
 187     private void showUsage(String headerKey, OptionKind kind, String footerKey) {
 188         messager.notice(headerKey);
 189         showToolOptions(kind);
 190 
 191         // let doclet print usage information
 192         if (docletClass != null) {
 193             String name = doclet.getName();
 194             messager.notice("main.doclet.usage.header", name);
 195             showDocletOptions(kind == OptionKind.EXTENDED
 196                     ? Option.Kind.EXTENDED
 197                     : Option.Kind.STANDARD);
 198         }
 199         if (footerKey != null)
 200             messager.notice(footerKey);
 201     }
 202 
 203     private static final String versionRBName = "jdk.javadoc.internal.tool.resources.version";
 204     private static ResourceBundle versionRB;
 205 
 206     private void showVersion(String labelKey, String versionKey) {
 207         messager.notice(labelKey, messager.programName, getVersion(versionKey));
 208     }
 209 
 210     private static String getVersion(String key) {
 211         if (versionRB == null) {
 212             try {
 213                 versionRB = ResourceBundle.getBundle(versionRBName);
 214             } catch (MissingResourceException e) {
 215                 return Log.getLocalizedString("version.not.available");
 216             }
 217         }
 218         try {
 219             return versionRB.getString(key);
 220         } catch (MissingResourceException e) {
 221             return Log.getLocalizedString("version.not.available");
 222         }
 223     }
 224 
 225     private void showToolOptions(OptionKind kind) {
 226         Comparator<ToolOption> comp = new Comparator<ToolOption>() {
 227             final Collator collator = Collator.getInstance(Locale.US);
 228             { collator.setStrength(Collator.PRIMARY); }
 229 
 230             @Override
 231             public int compare(ToolOption o1, ToolOption o2) {
 232                 return collator.compare(o1.primaryName, o2.primaryName);
 233             }
 234         };
 235 
 236         options.getSupportedOptions().stream()
 237                     .filter(opt -> opt.kind == kind)
 238                     .sorted(comp)
 239                     .forEach(this::showToolOption);
 240     }
 241 
 242     private void showToolOption(ToolOption option) {
 243         List<String> names = option.getNames();
 244         String primaryName = option.primaryName;
 245         String parameters;
 246         if (option.hasArg || primaryName.endsWith(":")) {
 247             String sep = primaryName.equals(ToolOptions.J) || primaryName.endsWith(":") ? "" : " ";
 248             parameters = sep + option.getParameters(messager);
 249         } else {
 250             parameters = "";
 251         }
 252         String description = option.getDescription(messager);
 253         showOption(names, parameters, description);
 254     }
 255 
 256     private void showDocletOptions(Option.Kind kind) {
 257         Comparator<Doclet.Option> comp = new Comparator<Doclet.Option>() {
 258             final Collator collator = Collator.getInstance(Locale.US);
 259             { collator.setStrength(Collator.PRIMARY); }
 260 
 261             @Override
 262             public int compare(Doclet.Option o1, Doclet.Option o2) {
 263                 return collator.compare(o1.getNames().get(0), o2.getNames().get(0));
 264             }
 265         };
 266 
 267         doclet.getSupportedOptions().stream()
 268                 .filter(opt -> opt.getKind() == kind)
 269                 .sorted(comp)
 270                 .forEach(this::showDocletOption);
 271     }
 272 
 273     private void showDocletOption(Doclet.Option option) {
 274         List<String> names = option.getNames();
 275         String parameters;
 276         String primaryName = names.get(0);
 277         if (option.getArgumentCount() > 0 || primaryName.endsWith(":")) {
 278             String sep = primaryName.endsWith(":") ? "" : " ";
 279             parameters = sep + option.getParameters();
 280         } else {
 281             parameters = "";
 282         }
 283         String description = option.getDescription();
 284         showOption(names, parameters, description);
 285     }
 286 
 287     // The following constants are intended to format the output to
 288     // be similar to that of the java launcher: i.e. "java -help".
 289 
 290     /** The indent for the option synopsis. */
 291     private static final String SMALL_INDENT = "    ";
 292     /** The automatic indent for the description. */
 293     private static final String LARGE_INDENT = "                  ";
 294     /** The space allowed for the synopsis, if the description is to be shown on the same line. */
 295     private static final int DEFAULT_SYNOPSIS_WIDTH = 13;
 296     /** The nominal maximum line length, when seeing if text will fit on a line. */
 297     private static final int DEFAULT_MAX_LINE_LENGTH = 80;
 298     /** The format for a single-line help entry. */
 299     private static final String COMPACT_FORMAT = SMALL_INDENT + "%-" + DEFAULT_SYNOPSIS_WIDTH + "s %s";
 300 
 301     void showOption(List<String> names, String parameters, String description) {
 302         String synopses = names.stream()
 303                 .map(s -> s + parameters)
 304                 .collect(Collectors.joining(", "));
 305         // If option synopses and description fit on a single line of reasonable length,
 306         // display using COMPACT_FORMAT
 307         if (synopses.length() < DEFAULT_SYNOPSIS_WIDTH
 308                 && !description.contains("\n")
 309                 && (SMALL_INDENT.length() + DEFAULT_SYNOPSIS_WIDTH + 1 + description.length() <= DEFAULT_MAX_LINE_LENGTH)) {
 310             messager.printNotice(String.format(COMPACT_FORMAT, synopses, description));
 311             return;
 312         }
 313 
 314         // If option synopses fit on a single line of reasonable length, show that;
 315         // otherwise, show 1 per line
 316         if (synopses.length() <= DEFAULT_MAX_LINE_LENGTH) {
 317             messager.printNotice(SMALL_INDENT + synopses);
 318         } else {
 319             for (String name: names) {
 320                 messager.printNotice(SMALL_INDENT + name + parameters);
 321             }
 322         }
 323 
 324         // Finally, show the description
 325         messager.printNotice(LARGE_INDENT + description.replace("\n", "\n" + LARGE_INDENT));
 326     }
 327 
 328 
 329     /**
 330      * Main program - external wrapper. In order to maintain backward
 331      * CLI compatibility, the execution is dispatched to the appropriate
 332      * Start mechanism, depending on the doclet variant.
 333      *
 334      * The doclet tests are performed in the begin method, further on,
 335      * this is to minimize argument processing and most importantly the impact
 336      * of class loader creation, needed to detect the doclet class variants.
 337      */
 338     @SuppressWarnings("deprecation")
 339     Result begin(String... argv) {
 340         // Preprocess @file arguments
 341         try {
 342             argv = CommandLine.parse(argv);
 343             return begin(Arrays.asList(argv), Collections.emptySet());
 344         } catch (IOException e) {
 345             error("main.cant.read", e.getMessage());
 346             return ERROR;
 347         }
 348     }
 349 
 350     // Called by 199 API.
 351     public boolean begin(Class<?> docletClass,
 352             Iterable<String> options,
 353             Iterable<? extends JavaFileObject> fileObjects) {
 354         this.docletClass = docletClass;
 355         List<String> opts = new ArrayList<>();
 356         for (String opt: options)
 357             opts.add(opt);
 358 
 359         return begin(opts, fileObjects).isOK();
 360     }
 361 
 362     @SuppressWarnings("removal")
 363     private Result begin(List<String> options, Iterable<? extends JavaFileObject> fileObjects) {
 364         fileManager = context.get(JavaFileManager.class);
 365         if (fileManager == null) {
 366             JavacFileManager.preRegister(context);
 367             fileManager = context.get(JavaFileManager.class);
 368             if (fileManager instanceof BaseFileManager) {
 369                 ((BaseFileManager) fileManager).autoClose = true;
 370             }
 371         }
 372 
 373         // locale, doclet and maybe taglet, needs to be determined first
 374         try {
 375             doclet = preprocess(fileManager, options);
 376         } catch (ToolException te) {
 377             if (!te.result.isOK()) {
 378                 if (te.message != null) {
 379                     messager.printError(te.message);
 380                 }
 381                 Throwable t = te.getCause();
 382                 dumpStack(t == null ? te : t);
 383             }
 384             return te.result;
 385         } catch (OptionException oe) {
 386             if (oe.message != null) {
 387                 messager.printError(oe.message);
 388             }
 389             oe.m.run();
 390             Throwable t = oe.getCause();
 391             dumpStack(t == null ? oe : t);
 392             return oe.result;
 393         }
 394 
 395         Result result = OK;
 396         try {
 397             result = parseAndExecute(options, fileObjects);
 398         } catch (com.sun.tools.javac.main.Option.InvalidValueException e) {
 399             messager.printError(e.getMessage());
 400             Throwable t = e.getCause();
 401             dumpStack(t == null ? e : t);
 402             return ERROR;
 403         } catch (OptionException toe) {
 404             if (toe.message != null)
 405                 messager.printError(toe.message);
 406 
 407             toe.m.run();
 408             Throwable t = toe.getCause();
 409             dumpStack(t == null ? toe : t);
 410             return toe.result;
 411         } catch (ToolException exc) {
 412             if (exc.message != null) {
 413                 messager.printError(exc.message);
 414             }
 415             Throwable t = exc.getCause();
 416             if (result == ABNORMAL) {
 417                 reportInternalError(t == null ? exc : t);
 418             } else {
 419                 dumpStack(t == null ? exc : t);
 420             }
 421             return exc.result;
 422         } catch (OutOfMemoryError ee) {
 423             error("main.out.of.memory");
 424             result = SYSERR;
 425             dumpStack(ee);
 426         } catch (ClientCodeException e) {
 427             // simply rethrow these exceptions, to be caught and handled by JavadocTaskImpl
 428             throw e;
 429         } catch (Error | Exception ee) {
 430             error("main.fatal.error", ee);
 431             reportInternalError(ee);
 432             result = ABNORMAL;
 433         } finally {
 434             if (fileManager != null
 435                     && fileManager instanceof BaseFileManager
 436                     && ((BaseFileManager) fileManager).autoClose) {
 437                 try {
 438                     fileManager.close();
 439                 } catch (IOException ignore) {}
 440             }
 441             boolean haveErrorWarnings = messager.hasErrors()
 442                     || (this.options.rejectWarnings() && messager.hasWarnings());
 443             if (!result.isOK() && !haveErrorWarnings) {
 444                 // the doclet failed, but nothing reported, flag it!.
 445                 error("main.unknown.error");
 446             }
 447             if (haveErrorWarnings && result.isOK()) {
 448                 result = ERROR;
 449             }
 450             messager.printErrorWarningCounts();
 451             messager.flush();
 452         }
 453         return result;
 454     }
 455 
 456     private void reportInternalError(Throwable t) {
 457         messager.printErrorUsingKey("doclet.internal.report.bug");
 458         dumpStack(true, t);
 459     }
 460 
 461     private void dumpStack(Throwable t) {
 462         dumpStack(false, t);
 463     }
 464 
 465     private void dumpStack(boolean enabled, Throwable t) {
 466         if (t != null && (enabled || options.dumpOnError())) {
 467             t.printStackTrace(System.err);
 468         }
 469     }
 470 
 471     /**
 472      * Main program - internal
 473      */
 474     @SuppressWarnings("unchecked")
 475     private Result parseAndExecute(List<String> argList, Iterable<? extends JavaFileObject> fileObjects)
 476             throws ToolException, OptionException, com.sun.tools.javac.main.Option.InvalidValueException {
 477         long tm = System.currentTimeMillis();
 478 
 479         List<String> javaNames = new ArrayList<>();
 480 
 481         // Make sure no obsolete source/target messages are reported
 482         try {
 483             options.processCompilerOption(com.sun.tools.javac.main.Option.XLINT_CUSTOM, "-Xlint:-options");
 484         } catch (com.sun.tools.javac.main.Option.InvalidValueException ignore) {
 485         }
 486 
 487         Arguments arguments = Arguments.instance(context);
 488         arguments.init(ProgramName);
 489         arguments.allowEmpty();
 490 
 491         doclet.init(locale, messager);
 492         parseArgs(argList, javaNames);
 493 
 494         if (!arguments.handleReleaseOptions(extra -> true)) {
 495             // Arguments does not always increase the error count in the
 496             // case of errors, so increment the error count only if it has
 497             // not been updated previously, preventing complaints by callers
 498             if (!messager.hasErrors() && !messager.hasWarnings())
 499                 messager.nerrors++;
 500             return CMDERR;
 501         }
 502 
 503         if (!arguments.validate()) {
 504             // Arguments does not always increase the error count in the
 505             // case of errors, so increment the error count only if it has
 506             // not been updated previously, preventing complaints by callers
 507             if (!messager.hasErrors() && !messager.hasWarnings())
 508                 messager.nerrors++;
 509             return CMDERR;
 510         }
 511 
 512         if (fileManager instanceof BaseFileManager) {
 513             ((BaseFileManager) fileManager).handleOptions(options.fileManagerOptions());
 514         }
 515 
 516         if (fileManager.isSupportedOption(MULTIRELEASE.primaryName) == 1) {
 517             Target target = Target.instance(context);
 518             List<String> list = List.of(target.multiReleaseValue());
 519             fileManager.handleOption(MULTIRELEASE.primaryName, list.iterator());
 520         }
 521         options.compilerOptions().notifyListeners();
 522 
 523         if (options.modules().isEmpty()) {
 524             if (options.subpackages().isEmpty()) {
 525                 if (javaNames.isEmpty() && isEmpty(fileObjects)) {
 526                     String text = messager.getText("main.No_modules_packages_or_classes_specified");
 527                     throw new ToolException(CMDERR, text);
 528                 }
 529             }
 530         }
 531 
 532         JavadocTool comp = JavadocTool.make0(context);
 533         if (comp == null) return ABNORMAL;
 534 
 535         DocletEnvironment docEnv = comp.getEnvironment(options, javaNames, fileObjects);
 536 
 537         // release resources
 538         comp = null;
 539 
 540         if (options.breakIterator() || !locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
 541             JavacTrees trees = JavacTrees.instance(context);
 542             trees.setBreakIterator(BreakIterator.getSentenceInstance(locale));
 543         }
 544         // pass off control to the doclet
 545         Result returnStatus = docEnv != null && doclet.run(docEnv)
 546                 ? OK
 547                 : ERROR;
 548 
 549         // We're done.
 550         if (options.verbose()) {
 551             tm = System.currentTimeMillis() - tm;
 552             messager.notice("main.done_in", Long.toString(tm));
 553         }
 554 
 555         return returnStatus;
 556     }
 557 
 558     boolean matches(List<String> names, String arg) {
 559         for (String name : names) {
 560             if (StringUtils.toLowerCase(name).equals(StringUtils.toLowerCase(arg)))
 561                 return true;
 562         }
 563         return false;
 564     }
 565 
 566     boolean matches(Doclet.Option option, String arg) {
 567         if (matches(option.getNames(), arg))
 568              return true;
 569         int sep = arg.indexOf(':');
 570         String targ = arg.substring(0, sep + 1);
 571         return matches(option.getNames(), targ);
 572     }
 573 
 574     private Set<? extends Doclet.Option> docletOptions = null;
 575     int handleDocletOption(int idx, List<String> args, boolean isToolOption)
 576             throws OptionException {
 577         if (docletOptions == null) {
 578             docletOptions = doclet.getSupportedOptions();
 579         }
 580         String arg = args.get(idx);
 581         String argBase, argVal;
 582         if (arg.startsWith("--") && arg.contains("=")) {
 583             int sep = arg.indexOf("=");
 584             argBase = arg.substring(0, sep);
 585             argVal = arg.substring(sep + 1);
 586         } else {
 587             argBase = arg;
 588             argVal = null;
 589         }
 590         String text = null;
 591         for (Doclet.Option opt : docletOptions) {
 592             if (matches(opt, argBase)) {
 593                 if (argVal != null) {
 594                     switch (opt.getArgumentCount()) {
 595                         case 0:
 596                             text = messager.getText("main.unnecessary_arg_provided", argBase);
 597                             throw new OptionException(ERROR, this::showUsage, text);
 598                         case 1:
 599                             opt.process(arg, Arrays.asList(argVal));
 600                             break;
 601                         default:
 602                             text = messager.getText("main.only_one_argument_with_equals", argBase);
 603                             throw new OptionException(ERROR, this::showUsage, text);
 604                     }
 605                 } else {
 606                     if (args.size() - idx -1 < opt.getArgumentCount()) {
 607                         text = messager.getText("main.requires_argument", arg);
 608                         throw new OptionException(ERROR, this::showUsage, text);
 609                     }
 610                     opt.process(arg, args.subList(idx + 1, args.size()));
 611                     idx += opt.getArgumentCount();
 612                 }
 613                 return idx;
 614             }
 615         }
 616         // check if arg is accepted by the tool before emitting error
 617         if (!isToolOption) {
 618             text = messager.getText("main.invalid_flag", arg);
 619             throw new OptionException(ERROR, this::showUsage, text);
 620         }
 621         return idx;
 622     }
 623 
 624     private Doclet preprocess(JavaFileManager jfm, List<String> argv)
 625             throws ToolException, OptionException {
 626         // doclet specifying arguments
 627         String userDocletPath = null;
 628         String userDocletName = null;
 629 
 630         // taglet specifying arguments, since tagletpath is a doclet
 631         // functionality, assume they are repeated and inspect all.
 632         List<File> userTagletPath = new ArrayList<>();
 633         List<String> userTagletNames = new ArrayList<>();
 634 
 635         // Step 1: loop through the args, set locale early on, if found.
 636         for (int i = 0 ; i < argv.size() ; i++) {
 637             String arg = argv.get(i);
 638             if (arg.equals(ToolOptions.DUMP_ON_ERROR)) {
 639                 options.setDumpOnError(true);
 640             } else if (arg.equals(ToolOptions.LOCALE)) {
 641                 checkOneArg(argv, i++);
 642                 String lname = argv.get(i);
 643                 locale = getLocale(lname);
 644             } else if (arg.equals(ToolOptions.DOCLET)) {
 645                 checkOneArg(argv, i++);
 646                 if (userDocletName != null) {
 647                     if (apiMode) {
 648                         throw new IllegalArgumentException("More than one doclet specified (" +
 649                                 userDocletName + " and " + argv.get(i) + ").");
 650                     }
 651                     String text = messager.getText("main.more_than_one_doclet_specified_0_and_1",
 652                             userDocletName, argv.get(i));
 653                     throw new ToolException(CMDERR, text);
 654                 }
 655                 if (docletName != null) {
 656                     if (apiMode) {
 657                         throw new IllegalArgumentException("More than one doclet specified (" +
 658                                 docletName + " and " + argv.get(i) + ").");
 659                     }
 660                     String text = messager.getText("main.more_than_one_doclet_specified_0_and_1",
 661                             docletName, argv.get(i));
 662                     throw new ToolException(CMDERR, text);
 663                 }
 664                 userDocletName = argv.get(i);
 665             } else if (arg.equals(ToolOptions.DOCLET_PATH)) {
 666                 checkOneArg(argv, i++);
 667                 if (userDocletPath == null) {
 668                     userDocletPath = argv.get(i);
 669                 } else {
 670                     userDocletPath += File.pathSeparator + argv.get(i);
 671                 }
 672             } else if ("-taglet".equals(arg)) {
 673                 userTagletNames.add(argv.get(i + 1));
 674             } else if ("-tagletpath".equals(arg)) {
 675                 for (String pathname : argv.get(i + 1).split(File.pathSeparator)) {
 676                     userTagletPath.add(new File(pathname));
 677                 }
 678             }
 679         }
 680 
 681         // Step 3: doclet name specified ? if so find a ClassLoader,
 682         // and load it.
 683         if (docletClass == null) {
 684             if (userDocletName != null) {
 685                 ClassLoader cl = classLoader;
 686                 if (cl == null) {
 687                     if (!fileManager.hasLocation(DOCLET_PATH)) {
 688                         List<File> paths = new ArrayList<>();
 689                         if (userDocletPath != null) {
 690                             for (String pathname : userDocletPath.split(File.pathSeparator)) {
 691                                 paths.add(new File(pathname));
 692                             }
 693                         }
 694                         try {
 695                             ((StandardJavaFileManager)fileManager).setLocation(DOCLET_PATH, paths);
 696                         } catch (IOException ioe) {
 697                             if (apiMode) {
 698                                 throw new IllegalArgumentException("Could not set location for " +
 699                                         userDocletPath, ioe);
 700                             }
 701                             String text = messager.getText("main.doclet_could_not_set_location",
 702                                     userDocletPath);
 703                             throw new ToolException(CMDERR, text, ioe);
 704                         }
 705                     }
 706                     cl = fileManager.getClassLoader(DOCLET_PATH);
 707                     if (cl == null) {
 708                         // despite doclet specified on cmdline no classloader found!
 709                         if (apiMode) {
 710                             throw new IllegalArgumentException("Could not obtain classloader to load "
 711 
 712                                     + userDocletPath);
 713                         }
 714                         String text = messager.getText("main.doclet_no_classloader_found",
 715                                 userDocletName);
 716                         throw new ToolException(CMDERR, text);
 717                     }
 718                 }
 719                 docletClass = loadDocletClass(userDocletName, cl);
 720             } else if (docletName != null){
 721                 docletClass = loadDocletClass(docletName, getClass().getClassLoader());
 722             } else {
 723                 docletClass = StandardDoclet.class;
 724             }
 725         }
 726 
 727         if (jdk.javadoc.doclet.Doclet.class.isAssignableFrom(docletClass)) {
 728             messager.setLocale(locale);
 729             try {
 730                 Object o = docletClass.getConstructor().newInstance();
 731                 doclet = (Doclet) o;
 732             } catch (ReflectiveOperationException exc) {
 733                 if (apiMode) {
 734                     throw new ClientCodeException(exc);
 735                 }
 736                 String text = messager.getText("main.could_not_instantiate_class", docletClass.getName());
 737                 throw new ToolException(ERROR, text);
 738             }
 739         } else {
 740             String text = messager.getText("main.not_a_doclet", docletClass.getName());
 741             throw new ToolException(ERROR, text);
 742         }
 743         return doclet;
 744     }
 745 
 746     private Class<?> loadDocletClass(String docletName, ClassLoader classLoader) throws ToolException {
 747         try {
 748             return classLoader == null ? Class.forName(docletName) : classLoader.loadClass(docletName);
 749         } catch (ClassNotFoundException cnfe) {
 750             if (apiMode) {
 751                 throw new IllegalArgumentException("Cannot find doclet class " + docletName);
 752             }
 753             String text = messager.getText("main.doclet_class_not_found", docletName);
 754             throw new ToolException(CMDERR, text, cnfe);
 755         }
 756     }
 757 
 758     private void parseArgs(List<String> args, List<String> javaNames) throws ToolException,
 759             OptionException, com.sun.tools.javac.main.Option.InvalidValueException {
 760         for (int i = 0 ; i < args.size() ; i++) {
 761             String arg = args.get(i);
 762             ToolOption o = options.getOption(arg);
 763             if (o != null) {
 764                 // handle a doclet argument that may be needed however
 765                 // don't increment the index, and allow the tool to consume args
 766                 handleDocletOption(i, args, true);
 767                 if (o.hasArg) {
 768                     if (arg.startsWith("--") && arg.contains("=")) {
 769                         o.process(arg.substring(arg.indexOf('=') + 1));
 770                     } else {
 771                         checkOneArg(args, i++);
 772                         o.process(args.get(i));
 773                     }
 774                 } else if (o.hasSuffix) {
 775                     o.process(arg);
 776                 } else {
 777                     o.process();
 778                 }
 779             } else if (arg.startsWith("-XD")) {
 780                 // hidden javac options
 781                 String s = arg.substring("-XD".length());
 782                 int eq = s.indexOf('=');
 783                 String key = (eq < 0) ? s : s.substring(0, eq);
 784                 String value = (eq < 0) ? s : s.substring(eq+1);
 785                 options.compilerOptions().put(key, value);
 786             } else if (arg.startsWith("-")) {
 787                 i = handleDocletOption(i, args, false);
 788             } else {
 789                 javaNames.add(arg);
 790             }
 791         }
 792     }
 793 
 794     private <T> boolean isEmpty(Iterable<T> iter) {
 795         return !iter.iterator().hasNext();
 796     }
 797 
 798     /**
 799      * Check the one arg option.
 800      * Error and exit if one argument is not provided.
 801      */
 802     private void checkOneArg(List<String> args, int index) throws OptionException {
 803         if ((index + 1) >= args.size() || args.get(index + 1).startsWith("-d")) {
 804             String text = messager.getText("main.requires_argument", args.get(index));
 805             throw new OptionException(CMDERR, this::showUsage, text);
 806         }
 807     }
 808 
 809     void error(String key, Object... args) {
 810         messager.printErrorUsingKey(key, args);
 811     }
 812 
 813     void warn(String key, Object... args)  {
 814         messager.printWarningUsingKey(key, args);
 815     }
 816 
 817     /**
 818      * Get the locale if specified on the command line
 819      * else return null and if locale option is not used
 820      * then return default locale.
 821      */
 822     private Locale getLocale(String localeName) throws ToolException {
 823         try {
 824             // Tolerate, at least for a while, the older syntax accepted by javadoc,
 825             // using _ as the separator
 826             localeName = localeName.replace("_", "-");
 827             Locale l =  new Locale.Builder().setLanguageTag(localeName).build();
 828             // Ensure that a non-empty language is available for the <HTML lang=...> element
 829             return (l.getLanguage().isEmpty()) ? Locale.ENGLISH : l;
 830         } catch (IllformedLocaleException e) {
 831             String text = messager.getText("main.malformed_locale_name", localeName);
 832             throw new ToolException(CMDERR, text);
 833         }
 834     }
 835 
 836     /**
 837      * Search the locale for specified language, specified country and
 838      * specified variant.
 839      */
 840     private Locale searchLocale(String language, String country,
 841                                 String variant) {
 842         for (Locale loc : Locale.getAvailableLocales()) {
 843             if (loc.getLanguage().equals(language) &&
 844                 (country == null || loc.getCountry().equals(country)) &&
 845                 (variant == null || loc.getVariant().equals(variant))) {
 846                 return loc;
 847             }
 848         }
 849         return null;
 850     }
 851 
 852 
 853 }