Option.java revision 3926:86efeea0e59f
1/*
2 * Copyright (c) 2006, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.tools.javac.main;
27
28import java.io.FileWriter;
29import java.io.PrintWriter;
30import java.nio.file.Files;
31import java.nio.file.Path;
32import java.nio.file.Paths;
33import java.text.Collator;
34import java.util.Arrays;
35import java.util.Collections;
36import java.util.Comparator;
37import java.util.EnumSet;
38import java.util.Iterator;
39import java.util.LinkedHashSet;
40import java.util.Locale;
41import java.util.ServiceLoader;
42import java.util.Set;
43import java.util.TreeSet;
44import java.util.regex.Pattern;
45import java.util.stream.Collectors;
46import java.util.stream.StreamSupport;
47
48import javax.lang.model.SourceVersion;
49
50import com.sun.tools.doclint.DocLint;
51import com.sun.tools.javac.code.Lint;
52import com.sun.tools.javac.code.Lint.LintCategory;
53import com.sun.tools.javac.code.Source;
54import com.sun.tools.javac.code.Type;
55import com.sun.tools.javac.jvm.Profile;
56import com.sun.tools.javac.jvm.Target;
57import com.sun.tools.javac.platform.PlatformProvider;
58import com.sun.tools.javac.processing.JavacProcessingEnvironment;
59import com.sun.tools.javac.util.Assert;
60import com.sun.tools.javac.util.JDK9Wrappers;
61import com.sun.tools.javac.util.Log;
62import com.sun.tools.javac.util.Log.PrefixKind;
63import com.sun.tools.javac.util.Log.WriterKind;
64import com.sun.tools.javac.util.Options;
65import com.sun.tools.javac.util.StringUtils;
66
67import static com.sun.tools.javac.main.Option.ChoiceKind.*;
68import static com.sun.tools.javac.main.Option.OptionGroup.*;
69import static com.sun.tools.javac.main.Option.OptionKind.*;
70
71/**
72 * Options for javac.
73 * The specific Option to handle a command-line option can be found by calling
74 * {@link #lookup}, which search some or all of the members of this enum in order,
75 * looking for the first {@link #matches match}.
76 * The action for an Option is performed {@link #handleOption}, which determines
77 * whether an argument is needed and where to find it;
78 * {@code handleOption} then calls {@link #process process} providing a suitable
79 * {@link OptionHelper} to provide access the compiler state.
80 *
81 * <p><b>This is NOT part of any supported API.
82 * If you write code that depends on this, you do so at your own
83 * risk.  This code and its internal interfaces are subject to change
84 * or deletion without notice.</b></p>
85 */
86public enum Option {
87    G("-g", "opt.g", STANDARD, BASIC),
88
89    G_NONE("-g:none", "opt.g.none", STANDARD, BASIC) {
90        @Override
91        public void process(OptionHelper helper, String option) {
92            helper.put("-g:", "none");
93        }
94    },
95
96    G_CUSTOM("-g:",  "opt.g.lines.vars.source",
97            STANDARD, BASIC, ANYOF, "lines", "vars", "source"),
98
99    XLINT("-Xlint", "opt.Xlint", EXTENDED, BASIC),
100
101    XLINT_CUSTOM("-Xlint:", "opt.arg.Xlint", "opt.Xlint.custom", EXTENDED, BASIC, ANYOF, getXLintChoices()) {
102        private final String LINT_KEY_FORMAT = LARGE_INDENT + "  %-" +
103                (DEFAULT_SYNOPSIS_WIDTH + SMALL_INDENT.length() - LARGE_INDENT.length() - 2) + "s %s";
104        @Override
105        protected void help(Log log) {
106            super.help(log);
107            log.printRawLines(WriterKind.STDOUT,
108                              String.format(LINT_KEY_FORMAT,
109                                            "all",
110                                            log.localize(PrefixKind.JAVAC, "opt.Xlint.all")));
111            for (LintCategory lc : LintCategory.values()) {
112                log.printRawLines(WriterKind.STDOUT,
113                                  String.format(LINT_KEY_FORMAT,
114                                                lc.option,
115                                                log.localize(PrefixKind.JAVAC,
116                                                             "opt.Xlint.desc." + lc.option)));
117            }
118            log.printRawLines(WriterKind.STDOUT,
119                              String.format(LINT_KEY_FORMAT,
120                                            "none",
121                                            log.localize(PrefixKind.JAVAC, "opt.Xlint.none")));
122        }
123    },
124
125    XDOCLINT("-Xdoclint", "opt.Xdoclint", EXTENDED, BASIC),
126
127    XDOCLINT_CUSTOM("-Xdoclint:", "opt.Xdoclint.subopts", "opt.Xdoclint.custom", EXTENDED, BASIC) {
128        @Override
129        public boolean matches(String option) {
130            return DocLint.isValidOption(
131                    option.replace(XDOCLINT_CUSTOM.primaryName, DocLint.XMSGS_CUSTOM_PREFIX));
132        }
133
134        @Override
135        public void process(OptionHelper helper, String option) {
136            String prev = helper.get(XDOCLINT_CUSTOM);
137            String next = (prev == null) ? option : (prev + " " + option);
138            helper.put(XDOCLINT_CUSTOM.primaryName, next);
139        }
140    },
141
142    XDOCLINT_PACKAGE("-Xdoclint/package:", "opt.Xdoclint.package.args", "opt.Xdoclint.package.desc", EXTENDED, BASIC) {
143        @Override
144        public boolean matches(String option) {
145            return DocLint.isValidOption(
146                    option.replace(XDOCLINT_PACKAGE.primaryName, DocLint.XCHECK_PACKAGE));
147        }
148
149        @Override
150        public void process(OptionHelper helper, String option) {
151            String prev = helper.get(XDOCLINT_PACKAGE);
152            String next = (prev == null) ? option : (prev + " " + option);
153            helper.put(XDOCLINT_PACKAGE.primaryName, next);
154        }
155    },
156
157    DOCLINT_FORMAT("--doclint-format", "opt.doclint.format", EXTENDED, BASIC, ONEOF, "html4", "html5"),
158
159    // -nowarn is retained for command-line backward compatibility
160    NOWARN("-nowarn", "opt.nowarn", STANDARD, BASIC) {
161        @Override
162        public void process(OptionHelper helper, String option) {
163            helper.put("-Xlint:none", option);
164        }
165    },
166
167    VERBOSE("-verbose", "opt.verbose", STANDARD, BASIC),
168
169    // -deprecation is retained for command-line backward compatibility
170    DEPRECATION("-deprecation", "opt.deprecation", STANDARD, BASIC) {
171        @Override
172        public void process(OptionHelper helper, String option) {
173            helper.put("-Xlint:deprecation", option);
174        }
175    },
176
177    CLASS_PATH("--class-path -classpath -cp", "opt.arg.path", "opt.classpath", STANDARD, FILEMANAGER),
178
179    SOURCE_PATH("--source-path -sourcepath", "opt.arg.path", "opt.sourcepath", STANDARD, FILEMANAGER),
180
181    MODULE_SOURCE_PATH("--module-source-path", "opt.arg.mspath", "opt.modulesourcepath", STANDARD, FILEMANAGER),
182
183    MODULE_PATH("--module-path -p", "opt.arg.path", "opt.modulepath", STANDARD, FILEMANAGER),
184
185    UPGRADE_MODULE_PATH("--upgrade-module-path", "opt.arg.path", "opt.upgrademodulepath", STANDARD, FILEMANAGER),
186
187    SYSTEM("--system", "opt.arg.jdk", "opt.system", STANDARD, FILEMANAGER),
188
189    PATCH_MODULE("--patch-module", "opt.arg.patch", "opt.patch", EXTENDED, FILEMANAGER) {
190        // The deferred filemanager diagnostics mechanism assumes a single value per option,
191        // but --patch-module can be used multiple times, once per module. Therefore we compose
192        // a value for the option containing the last value specified for each module, and separate
193        // the the module=path pairs by an invalid path character, NULL.
194        // The standard file manager code knows to split apart the NULL-separated components.
195        @Override
196        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
197            if (arg.isEmpty()) {
198                throw helper.newInvalidValueException("err.no.value.for.option", option);
199            } else if (getPattern().matcher(arg).matches()) {
200                String prev = helper.get(PATCH_MODULE);
201                if (prev == null) {
202                    super.process(helper, option, arg);
203                } else {
204                    String argModulePackage = arg.substring(0, arg.indexOf('='));
205                    boolean isRepeated = Arrays.stream(prev.split("\0"))
206                            .map(s -> s.substring(0, s.indexOf('=')))
207                            .collect(Collectors.toSet())
208                            .contains(argModulePackage);
209                    if (isRepeated) {
210                        throw helper.newInvalidValueException("err.repeated.value.for.patch.module", argModulePackage);
211                    } else {
212                        super.process(helper, option, prev + '\0' + arg);
213                    }
214                }
215            } else {
216                throw helper.newInvalidValueException("err.bad.value.for.option", option, arg);
217            }
218        }
219
220        @Override
221        public Pattern getPattern() {
222            return Pattern.compile("([^/]+)=(,*[^,].*)");
223        }
224    },
225
226    BOOT_CLASS_PATH("--boot-class-path -bootclasspath", "opt.arg.path", "opt.bootclasspath", STANDARD, FILEMANAGER) {
227        @Override
228        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
229            helper.remove("-Xbootclasspath/p:");
230            helper.remove("-Xbootclasspath/a:");
231            super.process(helper, option, arg);
232        }
233    },
234
235    XBOOTCLASSPATH_PREPEND("-Xbootclasspath/p:", "opt.arg.path", "opt.Xbootclasspath.p", EXTENDED, FILEMANAGER),
236
237    XBOOTCLASSPATH_APPEND("-Xbootclasspath/a:", "opt.arg.path", "opt.Xbootclasspath.a", EXTENDED, FILEMANAGER),
238
239    XBOOTCLASSPATH("-Xbootclasspath:", "opt.arg.path", "opt.bootclasspath", EXTENDED, FILEMANAGER) {
240        @Override
241        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
242            helper.remove("-Xbootclasspath/p:");
243            helper.remove("-Xbootclasspath/a:");
244            super.process(helper, "-bootclasspath", arg);
245        }
246    },
247
248    EXTDIRS("-extdirs", "opt.arg.dirs", "opt.extdirs", STANDARD, FILEMANAGER),
249
250    DJAVA_EXT_DIRS("-Djava.ext.dirs=", "opt.arg.dirs", "opt.extdirs", EXTENDED, FILEMANAGER) {
251        @Override
252        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
253            EXTDIRS.process(helper, "-extdirs", arg);
254        }
255    },
256
257    ENDORSEDDIRS("-endorseddirs", "opt.arg.dirs", "opt.endorseddirs", STANDARD, FILEMANAGER),
258
259    DJAVA_ENDORSED_DIRS("-Djava.endorsed.dirs=", "opt.arg.dirs", "opt.endorseddirs", EXTENDED, FILEMANAGER) {
260        @Override
261        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
262            ENDORSEDDIRS.process(helper, "-endorseddirs", arg);
263        }
264    },
265
266    PROC("-proc:", "opt.proc.none.only", STANDARD, BASIC,  ONEOF, "none", "only"),
267
268    PROCESSOR("-processor", "opt.arg.class.list", "opt.processor", STANDARD, BASIC),
269
270    PROCESSOR_PATH("--processor-path -processorpath", "opt.arg.path", "opt.processorpath", STANDARD, FILEMANAGER),
271
272    PROCESSOR_MODULE_PATH("--processor-module-path", "opt.arg.path", "opt.processormodulepath", STANDARD, FILEMANAGER),
273
274    PARAMETERS("-parameters","opt.parameters", STANDARD, BASIC),
275
276    D("-d", "opt.arg.directory", "opt.d", STANDARD, FILEMANAGER),
277
278    S("-s", "opt.arg.directory", "opt.sourceDest", STANDARD, FILEMANAGER),
279
280    H("-h", "opt.arg.directory", "opt.headerDest", STANDARD, FILEMANAGER),
281
282    IMPLICIT("-implicit:", "opt.implicit", STANDARD, BASIC, ONEOF, "none", "class"),
283
284    ENCODING("-encoding", "opt.arg.encoding", "opt.encoding", STANDARD, FILEMANAGER),
285
286    SOURCE("-source", "opt.arg.release", "opt.source", STANDARD, BASIC) {
287        @Override
288        public void process(OptionHelper helper, String option, String operand) throws InvalidValueException {
289            Source source = Source.lookup(operand);
290            if (source == null) {
291                throw helper.newInvalidValueException("err.invalid.source", operand);
292            }
293            super.process(helper, option, operand);
294        }
295    },
296
297    TARGET("-target", "opt.arg.release", "opt.target", STANDARD, BASIC) {
298        @Override
299        public void process(OptionHelper helper, String option, String operand) throws InvalidValueException {
300            Target target = Target.lookup(operand);
301            if (target == null) {
302                throw helper.newInvalidValueException("err.invalid.target", operand);
303            }
304            super.process(helper, option, operand);
305        }
306    },
307
308    RELEASE("--release", "opt.arg.release", "opt.release", STANDARD, BASIC) {
309        @Override
310        protected void help(Log log) {
311            Iterable<PlatformProvider> providers =
312                    ServiceLoader.load(PlatformProvider.class, Arguments.class.getClassLoader());
313            Set<String> platforms = StreamSupport.stream(providers.spliterator(), false)
314                                                 .flatMap(provider -> StreamSupport.stream(provider.getSupportedPlatformNames()
315                                                                                                   .spliterator(),
316                                                                                           false))
317                                                 .collect(Collectors.toCollection(TreeSet :: new));
318
319            StringBuilder targets = new StringBuilder();
320            String delim = "";
321            for (String platform : platforms) {
322                targets.append(delim);
323                targets.append(platform);
324                delim = ", ";
325            }
326
327            super.help(log, log.localize(PrefixKind.JAVAC, descrKey, targets.toString()));
328        }
329    },
330
331    PROFILE("-profile", "opt.arg.profile", "opt.profile", STANDARD, BASIC) {
332        @Override
333        public void process(OptionHelper helper, String option, String operand) throws InvalidValueException {
334            Profile profile = Profile.lookup(operand);
335            if (profile == null) {
336                throw helper.newInvalidValueException("err.invalid.profile", operand);
337            }
338            super.process(helper, option, operand);
339        }
340    },
341
342    VERSION("--version -version", "opt.version", STANDARD, INFO) {
343        @Override
344        public void process(OptionHelper helper, String option) throws InvalidValueException {
345            Log log = helper.getLog();
346            String ownName = helper.getOwnName();
347            log.printLines(WriterKind.STDOUT, PrefixKind.JAVAC, "version", ownName,  JavaCompiler.version());
348            super.process(helper, option);
349        }
350    },
351
352    FULLVERSION("--full-version -fullversion", null, HIDDEN, INFO) {
353        @Override
354        public void process(OptionHelper helper, String option) throws InvalidValueException {
355            Log log = helper.getLog();
356            String ownName = helper.getOwnName();
357            log.printLines(WriterKind.STDOUT, PrefixKind.JAVAC, "fullVersion", ownName,  JavaCompiler.fullVersion());
358            super.process(helper, option);
359        }
360    },
361
362    // Note: -h is already taken for "native header output directory".
363    HELP("--help -help", "opt.help", STANDARD, INFO) {
364        @Override
365        public void process(OptionHelper helper, String option) throws InvalidValueException {
366            Log log = helper.getLog();
367            String ownName = helper.getOwnName();
368            log.printLines(WriterKind.STDOUT, PrefixKind.JAVAC, "msg.usage.header", ownName);
369            showHelp(log, OptionKind.STANDARD);
370            log.printNewline(WriterKind.STDOUT);
371            super.process(helper, option);
372        }
373    },
374
375    A("-A", "opt.arg.key.equals.value", "opt.A", STANDARD, BASIC, ArgKind.ADJACENT) {
376        @Override
377        public boolean matches(String arg) {
378            return arg.startsWith("-A");
379        }
380
381        @Override
382        public boolean hasArg() {
383            return false;
384        }
385        // Mapping for processor options created in
386        // JavacProcessingEnvironment
387        @Override
388        public void process(OptionHelper helper, String option) throws InvalidValueException {
389            int argLength = option.length();
390            if (argLength == 2) {
391                throw helper.newInvalidValueException("err.empty.A.argument");
392            }
393            int sepIndex = option.indexOf('=');
394            String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) );
395            if (!JavacProcessingEnvironment.isValidOptionName(key)) {
396                throw helper.newInvalidValueException("err.invalid.A.key", option);
397            }
398            helper.put(option, option);
399        }
400    },
401
402    X("--help-extra -X", "opt.X", STANDARD, INFO) {
403        @Override
404        public void process(OptionHelper helper, String option) throws InvalidValueException {
405            Log log = helper.getLog();
406            showHelp(log, OptionKind.EXTENDED);
407            log.printNewline(WriterKind.STDOUT);
408            log.printLines(WriterKind.STDOUT, PrefixKind.JAVAC, "msg.usage.nonstandard.footer");
409            super.process(helper, option);
410        }
411    },
412
413    // This option exists only for the purpose of documenting itself.
414    // It's actually implemented by the launcher.
415    J("-J", "opt.arg.flag", "opt.J", STANDARD, INFO, ArgKind.ADJACENT) {
416        @Override
417        public void process(OptionHelper helper, String option) {
418            throw new AssertionError("the -J flag should be caught by the launcher.");
419        }
420    },
421
422    MOREINFO("-moreinfo", null, HIDDEN, BASIC) {
423        @Override
424        public void process(OptionHelper helper, String option) throws InvalidValueException {
425            Type.moreInfo = true;
426            super.process(helper, option);
427        }
428    },
429
430    // treat warnings as errors
431    WERROR("-Werror", "opt.Werror", STANDARD, BASIC),
432
433    // prompt after each error
434    // new Option("-prompt",                                        "opt.prompt"),
435    PROMPT("-prompt", null, HIDDEN, BASIC),
436
437    // dump stack on error
438    DOE("-doe", null, HIDDEN, BASIC),
439
440    // output source after type erasure
441    PRINTSOURCE("-printsource", null, HIDDEN, BASIC),
442
443    // display warnings for generic unchecked operations
444    WARNUNCHECKED("-warnunchecked", null, HIDDEN, BASIC) {
445        @Override
446        public void process(OptionHelper helper, String option) {
447            helper.put("-Xlint:unchecked", option);
448        }
449    },
450
451    XMAXERRS("-Xmaxerrs", "opt.arg.number", "opt.maxerrs", EXTENDED, BASIC),
452
453    XMAXWARNS("-Xmaxwarns", "opt.arg.number", "opt.maxwarns", EXTENDED, BASIC),
454
455    XSTDOUT("-Xstdout", "opt.arg.file", "opt.Xstdout", EXTENDED, INFO) {
456        @Override
457        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
458            try {
459                Log log = helper.getLog();
460                log.setWriters(new PrintWriter(new FileWriter(arg), true));
461            } catch (java.io.IOException e) {
462                throw helper.newInvalidValueException("err.error.writing.file", arg, e);
463            }
464            super.process(helper, option, arg);
465        }
466    },
467
468    XPRINT("-Xprint", "opt.print", EXTENDED, BASIC),
469
470    XPRINTROUNDS("-XprintRounds", "opt.printRounds", EXTENDED, BASIC),
471
472    XPRINTPROCESSORINFO("-XprintProcessorInfo", "opt.printProcessorInfo", EXTENDED, BASIC),
473
474    XPREFER("-Xprefer:", "opt.prefer", EXTENDED, BASIC, ONEOF, "source", "newer"),
475
476    XXUSERPATHSFIRST("-XXuserPathsFirst", "opt.userpathsfirst", HIDDEN, BASIC),
477
478    // see enum PkgInfo
479    XPKGINFO("-Xpkginfo:", "opt.pkginfo", EXTENDED, BASIC, ONEOF, "always", "legacy", "nonempty"),
480
481    /* -O is a no-op, accepted for backward compatibility. */
482    O("-O", null, HIDDEN, BASIC),
483
484    /* -Xjcov produces tables to support the code coverage tool jcov. */
485    XJCOV("-Xjcov", null, HIDDEN, BASIC),
486
487    PLUGIN("-Xplugin:", "opt.arg.plugin", "opt.plugin", EXTENDED, BASIC) {
488        @Override
489        public void process(OptionHelper helper, String option) {
490            String p = option.substring(option.indexOf(':') + 1).trim();
491            String prev = helper.get(PLUGIN);
492            helper.put(PLUGIN.primaryName, (prev == null) ? p : prev + '\0' + p);
493        }
494    },
495
496    XDIAGS("-Xdiags:", "opt.diags", EXTENDED, BASIC, ONEOF, "compact", "verbose"),
497
498    DEBUG("--debug:", null, HIDDEN, BASIC) {
499        @Override
500        public void process(OptionHelper helper, String option) throws InvalidValueException {
501            HiddenGroup.DEBUG.process(helper, option);
502        }
503    },
504
505    SHOULDSTOP("--should-stop:", null, HIDDEN, BASIC) {
506        @Override
507        public void process(OptionHelper helper, String option) throws InvalidValueException {
508            HiddenGroup.SHOULDSTOP.process(helper, option);
509        }
510    },
511
512    DIAGS("--diags:", null, HIDDEN, BASIC) {
513        @Override
514        public void process(OptionHelper helper, String option) throws InvalidValueException {
515            HiddenGroup.DIAGS.process(helper, option);
516        }
517    },
518
519    /* This is a back door to the compiler's option table.
520     * -XDx=y sets the option x to the value y.
521     * -XDx sets the option x to the value x.
522     */
523    XD("-XD", null, HIDDEN, BASIC) {
524        @Override
525        public boolean matches(String s) {
526            return s.startsWith(primaryName);
527        }
528        @Override
529        public void process(OptionHelper helper, String option) {
530            process(helper, option, option.substring(primaryName.length()));
531        }
532
533        @Override
534        public void process(OptionHelper helper, String option, String arg) {
535            int eq = arg.indexOf('=');
536            String key = (eq < 0) ? arg : arg.substring(0, eq);
537            String value = (eq < 0) ? arg : arg.substring(eq+1);
538            helper.put(key, value);
539        }
540    },
541
542    ADD_EXPORTS("--add-exports", "opt.arg.addExports", "opt.addExports", EXTENDED, BASIC) {
543        @Override
544        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
545            if (arg.isEmpty()) {
546                throw helper.newInvalidValueException("err.no.value.for.option", option);
547            } else if (getPattern().matcher(arg).matches()) {
548                String prev = helper.get(ADD_EXPORTS);
549                helper.put(ADD_EXPORTS.primaryName, (prev == null) ? arg : prev + '\0' + arg);
550            } else {
551                throw helper.newInvalidValueException("err.bad.value.for.option", option, arg);
552            }
553        }
554
555        @Override
556        public Pattern getPattern() {
557            return Pattern.compile("([^/]+)/([^=]+)=(,*[^,].*)");
558        }
559    },
560
561    ADD_OPENS("--add-opens", null, null, HIDDEN, BASIC),
562
563    ADD_READS("--add-reads", "opt.arg.addReads", "opt.addReads", EXTENDED, BASIC) {
564        @Override
565        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
566            if (arg.isEmpty()) {
567                throw helper.newInvalidValueException("err.no.value.for.option", option);
568            } else if (getPattern().matcher(arg).matches()) {
569                String prev = helper.get(ADD_READS);
570                helper.put(ADD_READS.primaryName, (prev == null) ? arg : prev + '\0' + arg);
571            } else {
572                throw helper.newInvalidValueException("err.bad.value.for.option", option, arg);
573            }
574        }
575
576        @Override
577        public Pattern getPattern() {
578            return Pattern.compile("([^=]+)=(,*[^,].*)");
579        }
580    },
581
582    XMODULE("-Xmodule:", "opt.arg.module", "opt.module", EXTENDED, BASIC) {
583        @Override
584        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
585            String prev = helper.get(XMODULE);
586            if (prev != null) {
587                throw helper.newInvalidValueException("err.option.too.many", XMODULE.primaryName);
588            }
589            helper.put(XMODULE.primaryName, arg);
590        }
591    },
592
593    MODULE("--module -m", "opt.arg.m", "opt.m", STANDARD, BASIC),
594
595    ADD_MODULES("--add-modules", "opt.arg.addmods", "opt.addmods", STANDARD, BASIC) {
596        @Override
597        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
598            if (arg.isEmpty()) {
599                throw helper.newInvalidValueException("err.no.value.for.option", option);
600            } else if (getPattern().matcher(arg).matches()) {
601                String prev = helper.get(ADD_MODULES);
602                // since the individual values are simple names, we can simply join the
603                // values of multiple --add-modules options with ','
604                helper.put(ADD_MODULES.primaryName, (prev == null) ? arg : prev + ',' + arg);
605            } else {
606                throw helper.newInvalidValueException("err.bad.value.for.option", option, arg);
607            }
608        }
609
610        @Override
611        public Pattern getPattern() {
612            return Pattern.compile(",*[^,].*");
613        }
614    },
615
616    LIMIT_MODULES("--limit-modules", "opt.arg.limitmods", "opt.limitmods", STANDARD, BASIC) {
617        @Override
618        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
619            if (arg.isEmpty()) {
620                throw helper.newInvalidValueException("err.no.value.for.option", option);
621            } else if (getPattern().matcher(arg).matches()) {
622                helper.put(LIMIT_MODULES.primaryName, arg); // last one wins
623            } else {
624                throw helper.newInvalidValueException("err.bad.value.for.option", option, arg);
625            }
626        }
627
628        @Override
629        public Pattern getPattern() {
630            return Pattern.compile(",*[^,].*");
631        }
632    },
633
634    MODULE_VERSION("--module-version", "opt.arg.module.version", "opt.module.version", STANDARD, BASIC) {
635        @Override
636        public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
637            if (arg.isEmpty()) {
638                throw helper.newInvalidValueException("err.no.value.for.option", option);
639            } else {
640                try {
641                    Class.forName(JDK9Wrappers.ModuleDescriptor.Version.CLASSNAME);
642                    // use official parser if available
643                    try {
644                        JDK9Wrappers.ModuleDescriptor.Version.parse(arg);
645                    } catch (IllegalArgumentException e) {
646                        throw helper.newInvalidValueException("err.bad.value.for.option", option, arg);
647                    }
648                } catch (ClassNotFoundException ex) {
649                    // fall-back to simplistic rules when running on older platform
650                    if (!(arg.charAt(0) >= '0' && arg.charAt(0) <= '9') ||
651                        arg.endsWith("-") ||
652                        arg.endsWith("+")) {
653                        throw helper.newInvalidValueException("err.bad.value.for.option", option, arg);
654                    }
655                }
656            }
657            super.process(helper, option, arg);
658        }
659    },
660
661    // This option exists only for the purpose of documenting itself.
662    // It's actually implemented by the CommandLine class.
663    AT("@", "opt.arg.file", "opt.AT", STANDARD, INFO, ArgKind.ADJACENT) {
664        @Override
665        public void process(OptionHelper helper, String option) {
666            throw new AssertionError("the @ flag should be caught by CommandLine.");
667        }
668    },
669
670    // Standalone positional argument: source file or type name.
671    SOURCEFILE("sourcefile", null, HIDDEN, INFO) {
672        @Override
673        public boolean matches(String s) {
674            if (s.endsWith(".java"))  // Java source file
675                return true;
676            int sep = s.indexOf('/');
677            if (sep != -1) {
678                return SourceVersion.isName(s.substring(0, sep))
679                        && SourceVersion.isName(s.substring(sep + 1));
680            } else {
681                return SourceVersion.isName(s);   // Legal type name
682            }
683        }
684        @Override
685        public void process(OptionHelper helper, String option) throws InvalidValueException {
686            if (option.endsWith(".java") ) {
687                Path p = Paths.get(option);
688                if (!Files.exists(p)) {
689                    throw helper.newInvalidValueException("err.file.not.found", p);
690                }
691                if (!Files.isRegularFile(p)) {
692                    throw helper.newInvalidValueException("err.file.not.file", p);
693                }
694                helper.addFile(p);
695            } else {
696                helper.addClassName(option);
697            }
698        }
699    },
700
701    MULTIRELEASE("--multi-release", "opt.arg.multi-release", "opt.multi-release", HIDDEN, FILEMANAGER),
702
703    INHERIT_RUNTIME_ENVIRONMENT("--inherit-runtime-environment", "opt.inherit_runtime_environment",
704            HIDDEN, BASIC) {
705        @Override
706        public void process(OptionHelper helper, String option) throws InvalidValueException {
707            try {
708                Class.forName(JDK9Wrappers.VMHelper.CLASSNAME);
709                String[] runtimeArgs = JDK9Wrappers.VMHelper.getRuntimeArguments();
710                for (String arg : runtimeArgs) {
711                    // Handle any supported runtime options; ignore all others.
712                    // The runtime arguments always use the single token form, e.g. "--name=value".
713                    for (Option o : getSupportedRuntimeOptions()) {
714                        if (o.matches(arg)) {
715                            switch (o) {
716                                case ADD_MODULES:
717                                    int eq = arg.indexOf('=');
718                                    Assert.check(eq > 0, () -> ("invalid runtime option:" + arg));
719                                    // --add-modules=ALL-DEFAULT is not supported at compile-time
720                                    // so remove it from list, and only process the rest
721                                    // if the set is non-empty.
722                                    // Note that --add-modules=ALL-DEFAULT is automatically added
723                                    // by the standard javac launcher.
724                                    String mods = Arrays.stream(arg.substring(eq + 1).split(","))
725                                            .filter(s -> !s.isEmpty() && !s.equals("ALL-DEFAULT"))
726                                            .collect(Collectors.joining(","));
727                                    if (!mods.isEmpty()) {
728                                        String updatedArg = arg.substring(0, eq + 1) + mods;
729                                        o.handleOption(helper, updatedArg, Collections.emptyIterator());
730                                    }
731                                    break;
732                                default:
733                                    o.handleOption(helper, arg, Collections.emptyIterator());
734                                    break;
735                            }
736                            break;
737                        }
738                    }
739                }
740            } catch (ClassNotFoundException | SecurityException e) {
741                throw helper.newInvalidValueException("err.cannot.access.runtime.env");
742            }
743        }
744
745        private Option[] getSupportedRuntimeOptions() {
746            Option[] supportedRuntimeOptions = {
747                ADD_EXPORTS,
748                ADD_MODULES,
749                LIMIT_MODULES,
750                MODULE_PATH,
751                UPGRADE_MODULE_PATH,
752                PATCH_MODULE
753            };
754            return supportedRuntimeOptions;
755        }
756    };
757
758    /**
759     * This exception is thrown when an invalid value is given for an option.
760     * The detail string gives a detailed, localized message, suitable for use
761     * in error messages reported to the user.
762     */
763    public static class InvalidValueException extends Exception {
764        private static final long serialVersionUID = -1;
765
766        public InvalidValueException(String msg) {
767            super(msg);
768        }
769
770        public InvalidValueException(String msg, Throwable cause) {
771            super(msg, cause);
772        }
773    }
774
775    /**
776     * The kind of argument, if any, accepted by this option. The kind is augmented
777     * by characters in the name of the option.
778     */
779    public enum ArgKind {
780        /** This option does not take any argument. */
781        NONE,
782
783// Not currently supported
784//        /**
785//         * This option takes an optional argument, which may be provided directly after an '='
786//         * separator, or in the following argument position if that word does not itself appear
787//         * to be the name of an option.
788//         */
789//        OPTIONAL,
790
791        /**
792         * This option takes an argument.
793         * If the name of option ends with ':' or '=', the argument must be provided directly
794         * after that separator.
795         * Otherwise, it may appear after an '=' or in the following argument position.
796         */
797        REQUIRED,
798
799        /**
800         * This option takes an argument immediately after the option name, with no separator
801         * character.
802         */
803        ADJACENT
804    }
805
806    /**
807     * The kind of an Option. This is used by the -help and -X options.
808     */
809    public enum OptionKind {
810        /** A standard option, documented by -help. */
811        STANDARD,
812        /** An extended option, documented by -X. */
813        EXTENDED,
814        /** A hidden option, not documented. */
815        HIDDEN,
816    }
817
818    /**
819     * The group for an Option. This determines the situations in which the
820     * option is applicable.
821     */
822    enum OptionGroup {
823        /** A basic option, available for use on the command line or via the
824         *  Compiler API. */
825        BASIC,
826        /** An option for javac's standard JavaFileManager. Other file managers
827         *  may or may not support these options. */
828        FILEMANAGER,
829        /** A command-line option that requests information, such as -help. */
830        INFO,
831        /** A command-line "option" representing a file or class name. */
832        OPERAND
833    }
834
835    /**
836     * The kind of choice for "choice" options.
837     */
838    enum ChoiceKind {
839        /** The expected value is exactly one of the set of choices. */
840        ONEOF,
841        /** The expected value is one of more of the set of choices. */
842        ANYOF
843    }
844
845    enum HiddenGroup {
846        DIAGS("diags"),
847        DEBUG("debug"),
848        SHOULDSTOP("should-stop");
849
850        static final Set<String> skipSet = new java.util.HashSet<>(
851                Arrays.asList("--diags:", "--debug:", "--should-stop:"));
852
853        final String text;
854
855        HiddenGroup(String text) {
856            this.text = text;
857        }
858
859        public void process(OptionHelper helper, String option) throws InvalidValueException {
860            String p = option.substring(option.indexOf(':') + 1).trim();
861            String[] subOptions = p.split(";");
862            for (String subOption : subOptions) {
863                subOption = text + "." + subOption.trim();
864                XD.process(helper, subOption, subOption);
865            }
866        }
867
868        static boolean skip(String name) {
869            return skipSet.contains(name);
870        }
871    }
872
873    /**
874     * The "primary name" for this option.
875     * This is the name that is used to put values in the {@link Options} table.
876     */
877    public final String primaryName;
878
879    /**
880     * The set of names (primary name and aliases) for this option.
881     * Note that some names may end in a separator, to indicate that an argument must immediately
882     * follow the separator (and cannot appear in the following argument position.
883     */
884    public final String[] names;
885
886    /** Documentation key for arguments. */
887    protected final String argsNameKey;
888
889    /** Documentation key for description.
890     */
891    protected final String descrKey;
892
893    /** The kind of this option. */
894    private final OptionKind kind;
895
896    /** The group for this option. */
897    private final OptionGroup group;
898
899    /** The kind of argument for this option. */
900    private final ArgKind argKind;
901
902    /** The kind of choices for this option, if any. */
903    private final ChoiceKind choiceKind;
904
905    /** The choices for this option, if any. */
906    private final Set<String> choices;
907
908    /**
909     * Looks up the first option matching the given argument in the full set of options.
910     * @param arg the argument to be matches
911     * @return the first option that matches, or null if none.
912     */
913    public static Option lookup(String arg) {
914        return lookup(arg, EnumSet.allOf(Option.class));
915    }
916
917    /**
918     * Looks up the first option matching the given argument within a set of options.
919     * @param arg the argument to be matched
920     * @param options the set of possible options
921     * @return the first option that matches, or null if none.
922     */
923    public static Option lookup(String arg, Set<Option> options) {
924        for (Option option: options) {
925            if (option.matches(arg))
926                return option;
927        }
928        return null;
929    }
930
931    /**
932     * Writes the "command line help" for given kind of option to the log.
933     * @param log the log
934     * @param kind  the kind of options to select
935     */
936    private static void showHelp(Log log, OptionKind kind) {
937        Comparator<Option> comp = new Comparator<Option>() {
938            final Collator collator = Collator.getInstance(Locale.US);
939            { collator.setStrength(Collator.PRIMARY); }
940
941            @Override
942            public int compare(Option o1, Option o2) {
943                return collator.compare(o1.primaryName, o2.primaryName);
944            }
945        };
946
947        getJavaCompilerOptions()
948                .stream()
949                .filter(o -> o.kind == kind)
950                .sorted(comp)
951                .forEach(o -> {
952                    o.help(log);
953                });
954    }
955
956    Option(String text, String descrKey,
957            OptionKind kind, OptionGroup group) {
958        this(text, null, descrKey, kind, group, null, null, ArgKind.NONE);
959    }
960
961    Option(String text, String argsNameKey, String descrKey,
962            OptionKind kind, OptionGroup group) {
963        this(text, argsNameKey, descrKey, kind, group, null, null, ArgKind.REQUIRED);
964    }
965
966    Option(String text, String argsNameKey, String descrKey,
967            OptionKind kind, OptionGroup group, ArgKind ak) {
968        this(text, argsNameKey, descrKey, kind, group, null, null, ak);
969    }
970
971    Option(String text, String argsNameKey, String descrKey, OptionKind kind, OptionGroup group,
972            ChoiceKind choiceKind, Set<String> choices) {
973        this(text, argsNameKey, descrKey, kind, group, choiceKind, choices, ArgKind.REQUIRED);
974    }
975
976    Option(String text, String descrKey,
977            OptionKind kind, OptionGroup group,
978            ChoiceKind choiceKind, String... choices) {
979        this(text, null, descrKey, kind, group, choiceKind,
980                new LinkedHashSet<>(Arrays.asList(choices)), ArgKind.REQUIRED);
981    }
982
983    private Option(String text, String argsNameKey, String descrKey,
984            OptionKind kind, OptionGroup group,
985            ChoiceKind choiceKind, Set<String> choices,
986            ArgKind argKind) {
987        this.names = text.trim().split("\\s+");
988        Assert.check(names.length >= 1);
989        this.primaryName = names[0];
990        this.argsNameKey = argsNameKey;
991        this.descrKey = descrKey;
992        this.kind = kind;
993        this.group = group;
994        this.choiceKind = choiceKind;
995        this.choices = choices;
996        this.argKind = argKind;
997    }
998
999    public String getPrimaryName() {
1000        return primaryName;
1001    }
1002
1003    public OptionKind getKind() {
1004        return kind;
1005    }
1006
1007    public ArgKind getArgKind() {
1008        return argKind;
1009    }
1010
1011    public boolean hasArg() {
1012        return (argKind != ArgKind.NONE);
1013    }
1014
1015    public boolean matches(String option) {
1016        for (String name: names) {
1017            if (matches(option, name))
1018                return true;
1019        }
1020        return false;
1021    }
1022
1023    private boolean matches(String option, String name) {
1024        if (name.startsWith("--") && !HiddenGroup.skip(name)) {
1025            return option.equals(name)
1026                    || hasArg() && option.startsWith(name + "=");
1027        }
1028
1029        boolean hasSuffix = (argKind == ArgKind.ADJACENT)
1030                || name.endsWith(":") || name.endsWith("=");
1031
1032        if (!hasSuffix)
1033            return option.equals(name);
1034
1035        if (!option.startsWith(name))
1036            return false;
1037
1038        if (choices != null) {
1039            String arg = option.substring(name.length());
1040            if (choiceKind == ChoiceKind.ONEOF)
1041                return choices.contains(arg);
1042            else {
1043                for (String a: arg.split(",+")) {
1044                    if (!choices.contains(a))
1045                        return false;
1046                }
1047            }
1048        }
1049
1050        return true;
1051    }
1052
1053    /**
1054     * Handles an option.
1055     * If an argument for the option is required, depending on spec of the option, it will be found
1056     * as part of the current arg (following ':' or '=') or in the following argument.
1057     * This is the recommended way to handle an option directly, instead of calling the underlying
1058     * {@link #process process} methods.
1059     * @param helper a helper to provide access to the environment
1060     * @param arg the arg string that identified this option
1061     * @param rest the remaining strings to be analysed
1062     * @throws InvalidValueException if the value of the option was invalid
1063     * @implNote The return value is the opposite of that used by {@link #process}.
1064     */
1065    public void handleOption(OptionHelper helper, String arg, Iterator<String> rest) throws InvalidValueException {
1066        if (hasArg()) {
1067            String option;
1068            String operand;
1069            int sep = findSeparator(arg);
1070            if (getArgKind() == Option.ArgKind.ADJACENT) {
1071                option = primaryName; // aliases not supported
1072                operand = arg.substring(primaryName.length());
1073            } else if (sep > 0) {
1074                option = arg.substring(0, sep);
1075                operand = arg.substring(sep + 1);
1076            } else {
1077                if (!rest.hasNext()) {
1078                    throw helper.newInvalidValueException("err.req.arg", arg);
1079                }
1080                option = arg;
1081                operand = rest.next();
1082            }
1083            process(helper, option, operand);
1084        } else {
1085            process(helper, arg);
1086        }
1087    }
1088
1089    /**
1090     * Processes an option that either does not need an argument,
1091     * or which contains an argument within it, following a separator.
1092     * @param helper a helper to provide access to the environment
1093     * @param option the option to be processed
1094     * @throws InvalidValueException if an error occurred
1095     */
1096    public void process(OptionHelper helper, String option) throws InvalidValueException {
1097        if (argKind == ArgKind.NONE) {
1098            process(helper, primaryName, option);
1099        } else {
1100            int sep = findSeparator(option);
1101            process(helper, primaryName, option.substring(sep + 1));
1102        }
1103    }
1104
1105    /**
1106     * Processes an option by updating the environment via a helper object.
1107     * @param helper a helper to provide access to the environment
1108     * @param option the option to be processed
1109     * @param arg the value to associate with the option, or a default value
1110     *  to be used if the option does not otherwise take an argument.
1111     * @throws InvalidValueException if an error occurred
1112     */
1113    public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
1114        if (choices != null) {
1115            if (choiceKind == ChoiceKind.ONEOF) {
1116                // some clients like to see just one of option+choice set
1117                for (String s : choices)
1118                    helper.remove(primaryName + s);
1119                String opt = primaryName + arg;
1120                helper.put(opt, opt);
1121                // some clients like to see option (without trailing ":")
1122                // set to arg
1123                String nm = primaryName.substring(0, primaryName.length() - 1);
1124                helper.put(nm, arg);
1125            } else {
1126                // set option+word for each word in arg
1127                for (String a: arg.split(",+")) {
1128                    String opt = primaryName + a;
1129                    helper.put(opt, opt);
1130                }
1131            }
1132        }
1133        helper.put(primaryName, arg);
1134        if (group == OptionGroup.FILEMANAGER)
1135            helper.handleFileManagerOption(this, arg);
1136    }
1137
1138    /**
1139     * Returns a pattern to analyze the value for an option.
1140     * @return the pattern
1141     * @throws UnsupportedOperationException if an option does not provide a pattern.
1142     */
1143    public Pattern getPattern() {
1144        throw new UnsupportedOperationException();
1145    }
1146
1147    /**
1148     * Scans a word to find the first separator character, either colon or equals.
1149     * @param word the word to be scanned
1150     * @return the position of the first':' or '=' character in the word,
1151     *  or -1 if none found
1152     */
1153    private static int findSeparator(String word) {
1154        for (int i = 0; i < word.length(); i++) {
1155            switch (word.charAt(i)) {
1156                case ':': case '=':
1157                    return i;
1158            }
1159        }
1160        return -1;
1161    }
1162
1163    /** The indent for the option synopsis. */
1164    private static final String SMALL_INDENT = "  ";
1165    /** The automatic indent for the description. */
1166    private static final String LARGE_INDENT = "        ";
1167    /** The space allowed for the synopsis, if the description is to be shown on the same line. */
1168    private static final int DEFAULT_SYNOPSIS_WIDTH = 28;
1169    /** The nominal maximum line length, when seeing if text will fit on a line. */
1170    private static final int DEFAULT_MAX_LINE_LENGTH = 80;
1171    /** The format for a single-line help entry. */
1172    private static final String COMPACT_FORMAT = SMALL_INDENT + "%-" + DEFAULT_SYNOPSIS_WIDTH + "s %s";
1173
1174    /**
1175     * Writes help text for this option to the log.
1176     * @param log the log
1177     */
1178    protected void help(Log log) {
1179        help(log, log.localize(PrefixKind.JAVAC, descrKey));
1180    }
1181
1182    protected void help(Log log, String descr) {
1183        String synopses = Arrays.stream(names)
1184                .map(s -> helpSynopsis(s, log))
1185                .collect(Collectors.joining(", "));
1186
1187        // If option synopses and description fit on a single line of reasonable length,
1188        // display using COMPACT_FORMAT
1189        if (synopses.length() < DEFAULT_SYNOPSIS_WIDTH
1190                && !descr.contains("\n")
1191                && (SMALL_INDENT.length() + DEFAULT_SYNOPSIS_WIDTH + 1 + descr.length() <= DEFAULT_MAX_LINE_LENGTH)) {
1192            log.printRawLines(WriterKind.STDOUT, String.format(COMPACT_FORMAT, synopses, descr));
1193            return;
1194        }
1195
1196        // If option synopses fit on a single line of reasonable length, show that;
1197        // otherwise, show 1 per line
1198        if (synopses.length() <= DEFAULT_MAX_LINE_LENGTH) {
1199            log.printRawLines(WriterKind.STDOUT, SMALL_INDENT + synopses);
1200        } else {
1201            for (String name: names) {
1202                log.printRawLines(WriterKind.STDOUT, SMALL_INDENT + helpSynopsis(name, log));
1203            }
1204        }
1205
1206        // Finally, show the description
1207        log.printRawLines(WriterKind.STDOUT, LARGE_INDENT + descr.replace("\n", "\n" + LARGE_INDENT));
1208    }
1209
1210    /**
1211     * Composes the initial synopsis of one of the forms for this option.
1212     * @param name the name of this form of the option
1213     * @param log the log used to localize the description of the arguments
1214     * @return  the synopsis
1215     */
1216    private String helpSynopsis(String name, Log log) {
1217        StringBuilder sb = new StringBuilder();
1218        sb.append(name);
1219        if (argsNameKey == null) {
1220            if (choices != null) {
1221                if (!name.endsWith(":"))
1222                    sb.append(" ");
1223                String sep = "{";
1224                for (String choice : choices) {
1225                    sb.append(sep);
1226                    sb.append(choice);
1227                    sep = ",";
1228                }
1229                sb.append("}");
1230            }
1231        } else {
1232            if (!name.matches(".*[=:]$") && argKind != ArgKind.ADJACENT)
1233                sb.append(" ");
1234            sb.append(log.localize(PrefixKind.JAVAC, argsNameKey));
1235        }
1236
1237        return sb.toString();
1238    }
1239
1240    // For -XpkgInfo:value
1241    public enum PkgInfo {
1242        /**
1243         * Always generate package-info.class for every package-info.java file.
1244         * The file may be empty if there annotations with a RetentionPolicy
1245         * of CLASS or RUNTIME.  This option may be useful in conjunction with
1246         * build systems (such as Ant) that expect javac to generate at least
1247         * one .class file for every .java file.
1248         */
1249        ALWAYS,
1250        /**
1251         * Generate a package-info.class file if package-info.java contains
1252         * annotations. The file may be empty if all the annotations have
1253         * a RetentionPolicy of SOURCE.
1254         * This value is just for backwards compatibility with earlier behavior.
1255         * Either of the other two values are to be preferred to using this one.
1256         */
1257        LEGACY,
1258        /**
1259         * Generate a package-info.class file if and only if there are annotations
1260         * in package-info.java to be written into it.
1261         */
1262        NONEMPTY;
1263
1264        public static PkgInfo get(Options options) {
1265            String v = options.get(XPKGINFO);
1266            return (v == null
1267                    ? PkgInfo.LEGACY
1268                    : PkgInfo.valueOf(StringUtils.toUpperCase(v)));
1269        }
1270    }
1271
1272    private static Set<String> getXLintChoices() {
1273        Set<String> choices = new LinkedHashSet<>();
1274        choices.add("all");
1275        for (Lint.LintCategory c : Lint.LintCategory.values()) {
1276            choices.add(c.option);
1277            choices.add("-" + c.option);
1278        }
1279        choices.add("none");
1280        return choices;
1281    }
1282
1283    /**
1284     * Returns the set of options supported by the command line tool.
1285     * @return the set of options.
1286     */
1287    static Set<Option> getJavaCompilerOptions() {
1288        return EnumSet.allOf(Option.class);
1289    }
1290
1291    /**
1292     * Returns the set of options supported by the built-in file manager.
1293     * @return the set of options.
1294     */
1295    public static Set<Option> getJavacFileManagerOptions() {
1296        return getOptions(FILEMANAGER);
1297    }
1298
1299    /**
1300     * Returns the set of options supported by this implementation of
1301     * the JavaCompiler API, via {@link JavaCompiler#getTask}.
1302     * @return the set of options.
1303     */
1304    public static Set<Option> getJavacToolOptions() {
1305        return getOptions(BASIC);
1306    }
1307
1308    private static Set<Option> getOptions(OptionGroup group) {
1309        return Arrays.stream(Option.values())
1310                .filter(o -> o.group == group)
1311                .collect(Collectors.toCollection(() -> EnumSet.noneOf(Option.class)));
1312    }
1313
1314}
1315