feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.main;
import java.io.IOException;
import java.io.Reader;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.StreamTokenizer;
import com.sun.tools.javac.util.ListBuffer;
/**
* Various utility methods for processing Java tool command line arguments.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class CommandLine {
/**
* Process Win32-style command files for the specified command line
* arguments and return the resulting arguments. A command file argument
* is of the form '@file' where 'file' is the name of the file whose
* contents are to be parsed for additional arguments. The contents of
* the command file are parsed using StreamTokenizer and the original
* '@file' argument replaced with the resulting tokens. Recursive command
* files are not supported. The '@' character itself can be quoted with
* the sequence '@@'.
*/
public static String[] parse(String[] args)
throws IOException
{
ListBuffer<String> newArgs = new ListBuffer<String>();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.length() > 1 && arg.charAt(0) == '@') {
arg = arg.substring(1);
if (arg.charAt(0) == '@') {
newArgs.append(arg);
} else {
loadCmdFile(arg, newArgs);
}
} else {
newArgs.append(arg);
}
}
return newArgs.toList().toArray(new String[newArgs.length()]);
}
private static void loadCmdFile(String name, ListBuffer<String> args)
throws IOException
{
Reader r = new BufferedReader(new FileReader(name));
StreamTokenizer st = new StreamTokenizer(r);
st.resetSyntax();
st.wordChars(' ', 255);
st.whitespaceChars(0, ' ');
st.commentChar('#');
st.quoteChar('"');
st.quoteChar('\'');
while (st.nextToken() != StreamTokenizer.TT_EOF) {
args.append(st.sval);
}
r.close();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,699 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.main;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.annotation.processing.Processor;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import com.sun.source.util.JavacTask;
import com.sun.source.util.Plugin;
import com.sun.tools.doclint.DocLint;
import com.sun.tools.javac.api.BasicJavacTask;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.file.CacheFSInfo;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.jvm.Profile;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.processing.AnnotationProcessingError;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.Log.PrefixKind;
import com.sun.tools.javac.util.Log.WriterKind;
import com.sun.tools.javac.util.ServiceLoader;
import static com.sun.tools.javac.main.Option.*;
/** This class provides a command line interface to the javac compiler.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Main {
/** The name of the compiler, for use in diagnostics.
*/
String ownName;
/** The writer to use for diagnostic output.
*/
PrintWriter out;
/** The log to use for diagnostic output.
*/
public Log log;
/**
* If true, certain errors will cause an exception, such as command line
* arg errors, or exceptions in user provided code.
*/
boolean apiMode;
/** Result codes.
*/
public enum Result {
OK(0), // Compilation completed with no errors.
ERROR(1), // Completed but reported errors.
CMDERR(2), // Bad command-line arguments
SYSERR(3), // System error or resource exhaustion.
ABNORMAL(4); // Compiler terminated abnormally
Result(int exitCode) {
this.exitCode = exitCode;
}
public boolean isOK() {
return (exitCode == 0);
}
public final int exitCode;
}
private Option[] recognizedOptions =
Option.getJavaCompilerOptions().toArray(new Option[0]);
private OptionHelper optionHelper = new OptionHelper() {
@Override
public String get(Option option) {
return options.get(option);
}
@Override
public void put(String name, String value) {
options.put(name, value);
}
@Override
public void remove(String name) {
options.remove(name);
}
@Override
public Log getLog() {
return log;
}
@Override
public String getOwnName() {
return ownName;
}
@Override
public void error(String key, Object... args) {
Main.this.error(key, args);
}
@Override
public void addFile(File f) {
filenames.add(f);
}
@Override
public void addClassName(String s) {
classnames.append(s);
}
};
/**
* Construct a compiler instance.
*/
public Main(String name) {
this(name, new PrintWriter(System.err, true));
}
/**
* Construct a compiler instance.
*/
public Main(String name, PrintWriter out) {
this.ownName = name;
this.out = out;
}
/** A table of all options that's passed to the JavaCompiler constructor. */
private Options options = null;
/** The list of source files to process
*/
public Set<File> filenames = null; // XXX sb protected
/** List of class files names passed on the command line
*/
public ListBuffer<String> classnames = null; // XXX sb protected
/** Report a usage error.
*/
void error(String key, Object... args) {
if (apiMode) {
String msg = log.localize(PrefixKind.JAVAC, key, args);
throw new PropagatedException(new IllegalStateException(msg));
}
warning(key, args);
log.printLines(PrefixKind.JAVAC, "msg.usage", ownName);
}
/** Report a warning.
*/
void warning(String key, Object... args) {
log.printRawLines(ownName + ": " + log.localize(PrefixKind.JAVAC, key, args));
}
public Option getOption(String flag) {
for (Option option : recognizedOptions) {
if (option.matches(flag))
return option;
}
return null;
}
public void setOptions(Options options) {
if (options == null)
throw new NullPointerException();
this.options = options;
}
public void setAPIMode(boolean apiMode) {
this.apiMode = apiMode;
}
/** Process command line arguments: store all command line options
* in `options' table and return all source filenames.
* @param flags The array of command line arguments.
*/
public Collection<File> processArgs(String[] flags) { // XXX sb protected
return processArgs(flags, null);
}
public Collection<File> processArgs(String[] flags, String[] classNames) { // XXX sb protected
int ac = 0;
while (ac < flags.length) {
String flag = flags[ac];
ac++;
Option option = null;
if (flag.length() > 0) {
// quick hack to speed up file processing:
// if the option does not begin with '-', there is no need to check
// most of the compiler options.
int firstOptionToCheck = flag.charAt(0) == '-' ? 0 : recognizedOptions.length-1;
for (int j=firstOptionToCheck; j<recognizedOptions.length; j++) {
if (recognizedOptions[j].matches(flag)) {
option = recognizedOptions[j];
break;
}
}
}
if (option == null) {
error("err.invalid.flag", flag);
return null;
}
if (option.hasArg()) {
if (ac == flags.length) {
error("err.req.arg", flag);
return null;
}
String operand = flags[ac];
ac++;
if (option.process(optionHelper, flag, operand))
return null;
} else {
if (option.process(optionHelper, flag))
return null;
}
}
if (options.get(PROFILE) != null && options.get(BOOTCLASSPATH) != null) {
error("err.profile.bootclasspath.conflict");
return null;
}
if (this.classnames != null && classNames != null) {
this.classnames.addAll(Arrays.asList(classNames));
}
if (!checkDirectory(D))
return null;
if (!checkDirectory(S))
return null;
String sourceString = options.get(SOURCE);
Source source = (sourceString != null)
? Source.lookup(sourceString)
: Source.DEFAULT;
String targetString = options.get(TARGET);
Target target = (targetString != null)
? Target.lookup(targetString)
: Target.DEFAULT;
// We don't check source/target consistency for CLDC, as J2ME
// profiles are not aligned with J2SE targets; moreover, a
// single CLDC target may have many profiles. In addition,
// this is needed for the continued functioning of the JSR14
// prototype.
if (Character.isDigit(target.name.charAt(0))) {
if (target.compareTo(source.requiredTarget()) < 0) {
if (targetString != null) {
if (sourceString == null) {
warning("warn.target.default.source.conflict",
targetString,
source.requiredTarget().name);
} else {
warning("warn.source.target.conflict",
sourceString,
source.requiredTarget().name);
}
return null;
} else {
target = source.requiredTarget();
options.put("-target", target.name);
}
} else {
if (targetString == null && !source.allowGenerics()) {
target = Target.JDK1_4;
options.put("-target", target.name);
}
}
}
String profileString = options.get(PROFILE);
if (profileString != null) {
Profile profile = Profile.lookup(profileString);
if (!profile.isValid(target)) {
warning("warn.profile.target.conflict", profileString, target.name);
return null;
}
}
// handle this here so it works even if no other options given
String showClass = options.get("showClass");
if (showClass != null) {
if (showClass.equals("showClass")) // no value given for option
showClass = "com.sun.tools.javac.Main";
showClass(showClass);
}
options.notifyListeners();
return filenames;
}
// where
private boolean checkDirectory(Option option) {
String value = options.get(option);
if (value == null)
return true;
File file = new File(value);
if (!file.exists()) {
error("err.dir.not.found", value);
return false;
}
if (!file.isDirectory()) {
error("err.file.not.directory", value);
return false;
}
return true;
}
/** Programmatic interface for main function.
* @param args The command line parameters.
*/
public Result compile(String[] args) {
Context context = new Context();
JavacFileManager.preRegister(context); // can't create it until Log has been set up
Result result = compile(args, context);
if (fileManager instanceof JavacFileManager) {
// A fresh context was created above, so jfm must be a JavacFileManager
((JavacFileManager)fileManager).close();
}
return result;
}
public Result compile(String[] args, Context context) {
return compile(args, context, List.<JavaFileObject>nil(), null);
}
/** Programmatic interface for main function.
* @param args The command line parameters.
*/
public Result compile(String[] args,
Context context,
List<JavaFileObject> fileObjects,
Iterable<? extends Processor> processors)
{
return compile(args, null, context, fileObjects, processors);
}
public Result compile(String[] args,
String[] classNames,
Context context,
List<JavaFileObject> fileObjects,
Iterable<? extends Processor> processors)
{
context.put(Log.outKey, out);
log = Log.instance(context);
if (options == null)
options = Options.instance(context); // creates a new one
filenames = new LinkedHashSet<File>();
classnames = new ListBuffer<String>();
JavaCompiler comp = null;
/*
* TODO: Logic below about what is an acceptable command line
* should be updated to take annotation processing semantics
* into account.
*/
try {
if (args.length == 0
&& (classNames == null || classNames.length == 0)
&& fileObjects.isEmpty()) {
Option.HELP.process(optionHelper, "-help");
return Result.CMDERR;
}
Collection<File> files;
try {
files = processArgs(CommandLine.parse(args), classNames);
if (files == null) {
// null signals an error in options, abort
return Result.CMDERR;
} else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
// it is allowed to compile nothing if just asking for help or version info
if (options.isSet(HELP)
|| options.isSet(X)
|| options.isSet(VERSION)
|| options.isSet(FULLVERSION))
return Result.OK;
if (JavaCompiler.explicitAnnotationProcessingRequested(options)) {
error("err.no.source.files.classes");
} else {
error("err.no.source.files");
}
return Result.CMDERR;
}
} catch (java.io.FileNotFoundException e) {
warning("err.file.not.found", e.getMessage());
return Result.SYSERR;
}
boolean forceStdOut = options.isSet("stdout");
if (forceStdOut) {
log.flush();
log.setWriters(new PrintWriter(System.out, true));
}
// allow System property in following line as a Mustang legacy
boolean batchMode = (options.isUnset("nonBatchMode")
&& System.getProperty("nonBatchMode") == null);
if (batchMode)
CacheFSInfo.preRegister(context);
// FIXME: this code will not be invoked if using JavacTask.parse/analyze/generate
// invoke any available plugins
String plugins = options.get(PLUGIN);
if (plugins != null) {
JavacProcessingEnvironment pEnv = JavacProcessingEnvironment.instance(context);
ClassLoader cl = pEnv.getProcessorClassLoader();
ServiceLoader<Plugin> sl = ServiceLoader.load(Plugin.class, cl);
Set<List<String>> pluginsToCall = new LinkedHashSet<List<String>>();
for (String plugin: plugins.split("\\x00")) {
pluginsToCall.add(List.from(plugin.split("\\s+")));
}
JavacTask task = null;
Iterator<Plugin> iter = sl.iterator();
while (iter.hasNext()) {
Plugin plugin = iter.next();
for (List<String> p: pluginsToCall) {
if (plugin.getName().equals(p.head)) {
pluginsToCall.remove(p);
try {
if (task == null)
task = JavacTask.instance(pEnv);
plugin.init(task, p.tail.toArray(new String[p.tail.size()]));
} catch (Throwable ex) {
if (apiMode)
throw new RuntimeException(ex);
pluginMessage(ex);
return Result.SYSERR;
}
}
}
}
for (List<String> p: pluginsToCall) {
log.printLines(PrefixKind.JAVAC, "msg.plugin.not.found", p.head);
}
}
comp = JavaCompiler.instance(context);
// FIXME: this code will not be invoked if using JavacTask.parse/analyze/generate
String xdoclint = options.get(XDOCLINT);
String xdoclintCustom = options.get(XDOCLINT_CUSTOM);
if (xdoclint != null || xdoclintCustom != null) {
Set<String> doclintOpts = new LinkedHashSet<String>();
if (xdoclint != null)
doclintOpts.add(DocLint.XMSGS_OPTION);
if (xdoclintCustom != null) {
for (String s: xdoclintCustom.split("\\s+")) {
if (s.isEmpty())
continue;
doclintOpts.add(s.replace(XDOCLINT_CUSTOM.text, DocLint.XMSGS_CUSTOM_PREFIX));
}
}
if (!(doclintOpts.size() == 1
&& doclintOpts.iterator().next().equals(DocLint.XMSGS_CUSTOM_PREFIX + "none"))) {
JavacTask t = BasicJavacTask.instance(context);
// standard doclet normally generates H1, H2
doclintOpts.add(DocLint.XIMPLICIT_HEADERS + "2");
new DocLint().init(t, doclintOpts.toArray(new String[doclintOpts.size()]));
comp.keepComments = true;
}
}
fileManager = context.get(JavaFileManager.class);
if (!files.isEmpty()) {
// add filenames to fileObjects
comp = JavaCompiler.instance(context);
List<JavaFileObject> otherFiles = List.nil();
JavacFileManager dfm = (JavacFileManager)fileManager;
for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(files))
otherFiles = otherFiles.prepend(fo);
for (JavaFileObject fo : otherFiles)
fileObjects = fileObjects.prepend(fo);
}
comp.compile(fileObjects,
classnames.toList(),
processors);
if (log.expectDiagKeys != null) {
if (log.expectDiagKeys.isEmpty()) {
log.printRawLines("all expected diagnostics found");
return Result.OK;
} else {
log.printRawLines("expected diagnostic keys not found: " + log.expectDiagKeys);
return Result.ERROR;
}
}
if (comp.errorCount() != 0)
return Result.ERROR;
} catch (IOException ex) {
ioMessage(ex);
return Result.SYSERR;
} catch (OutOfMemoryError ex) {
resourceMessage(ex);
return Result.SYSERR;
} catch (StackOverflowError ex) {
resourceMessage(ex);
return Result.SYSERR;
} catch (FatalError ex) {
feMessage(ex);
return Result.SYSERR;
} catch (AnnotationProcessingError ex) {
if (apiMode)
throw new RuntimeException(ex.getCause());
apMessage(ex);
return Result.SYSERR;
} catch (ClientCodeException ex) {
// as specified by javax.tools.JavaCompiler#getTask
// and javax.tools.JavaCompiler.CompilationTask#call
throw new RuntimeException(ex.getCause());
} catch (PropagatedException ex) {
throw ex.getCause();
} catch (Throwable ex) {
// Nasty. If we've already reported an error, compensate
// for buggy compiler error recovery by swallowing thrown
// exceptions.
if (comp == null || comp.errorCount() == 0 ||
options == null || options.isSet("dev"))
bugMessage(ex);
return Result.ABNORMAL;
} finally {
if (comp != null) {
try {
comp.close();
} catch (ClientCodeException ex) {
throw new RuntimeException(ex.getCause());
}
}
filenames = null;
options = null;
}
return Result.OK;
}
/** Print a message reporting an internal error.
*/
void bugMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.bug", JavaCompiler.version());
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Print a message reporting a fatal error.
*/
void feMessage(Throwable ex) {
log.printRawLines(ex.getMessage());
if (ex.getCause() != null && options.isSet("dev")) {
ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE));
}
}
/** Print a message reporting an input/output error.
*/
void ioMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.io");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Print a message reporting an out-of-resources error.
*/
void resourceMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.resource");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Print a message reporting an uncaught exception from an
* annotation processor.
*/
void apMessage(AnnotationProcessingError ex) {
log.printLines(PrefixKind.JAVAC, "msg.proc.annotation.uncaught.exception");
ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Print a message reporting an uncaught exception from an
* annotation processor.
*/
void pluginMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.plugin.uncaught.exception");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Display the location and checksum of a class. */
void showClass(String className) {
PrintWriter pw = log.getWriter(WriterKind.NOTICE);
pw.println("javac: show class: " + className);
URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
if (url == null)
pw.println(" class not found");
else {
pw.println(" " + url);
try {
final String algorithm = "MD5";
byte[] digest;
MessageDigest md = MessageDigest.getInstance(algorithm);
DigestInputStream in = new DigestInputStream(url.openStream(), md);
try {
byte[] buf = new byte[8192];
int n;
do { n = in.read(buf); } while (n > 0);
digest = md.digest();
} finally {
in.close();
}
StringBuilder sb = new StringBuilder();
for (byte b: digest)
sb.append(String.format("%02x", b));
pw.println(" " + algorithm + " checksum: " + sb);
} catch (Exception e) {
pw.println(" cannot compute digest: " + e);
}
}
}
private JavaFileManager fileManager;
/* ************************************************************************
* Internationalization
*************************************************************************/
// /** Find a localized string in the resource bundle.
// * @param key The key for the localized string.
// */
// public static String getLocalizedString(String key, Object... args) { // FIXME sb private
// try {
// if (messages == null)
// messages = new JavacMessages(javacBundleName);
// return messages.getLocalizedString("javac." + key, args);
// }
// catch (MissingResourceException e) {
// throw new Error("Fatal Error: Resource for javac is missing", e);
// }
// }
//
// public static void useRawMessages(boolean enable) {
// if (enable) {
// messages = new JavacMessages(javacBundleName) {
// @Override
// public String getLocalizedString(String key, Object... args) {
// return key;
// }
// };
// } else {
// messages = new JavacMessages(javacBundleName);
// }
// }
public static final String javacBundleName =
"com.sun.tools.javac.resources.javac";
//
// private static JavacMessages messages;
}

View File

@@ -0,0 +1,752 @@
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.main;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.lang.model.SourceVersion;
import com.sun.tools.doclint.DocLint;
import com.sun.tools.javac.code.Lint;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.jvm.Profile;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Log.PrefixKind;
import com.sun.tools.javac.util.Log.WriterKind;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.util.StringUtils;
import static com.sun.tools.javac.main.Option.ChoiceKind.*;
import static com.sun.tools.javac.main.Option.OptionGroup.*;
import static com.sun.tools.javac.main.Option.OptionKind.*;
/**
* Options for javac. The specific Option to handle a command-line option
* is identified by searching the members of this enum in order, looking
* the first {@link #matches match}. The action for an Option is performed
* by calling {@link #process process}, and by providing a suitable
* {@link OptionHelper} to provide access the compiler state.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
public enum Option {
G("-g", "opt.g", STANDARD, BASIC),
G_NONE("-g:none", "opt.g.none", STANDARD, BASIC) {
@Override
public boolean process(OptionHelper helper, String option) {
helper.put("-g:", "none");
return false;
}
},
G_CUSTOM("-g:", "opt.g.lines.vars.source",
STANDARD, BASIC, ANYOF, "lines", "vars", "source"),
XLINT("-Xlint", "opt.Xlint", EXTENDED, BASIC),
XLINT_CUSTOM("-Xlint:", "opt.Xlint.suboptlist",
EXTENDED, BASIC, ANYOF, getXLintChoices()),
XDOCLINT("-Xdoclint", "opt.Xdoclint", EXTENDED, BASIC),
XDOCLINT_CUSTOM("-Xdoclint:", "opt.Xdoclint.subopts", "opt.Xdoclint.custom", EXTENDED, BASIC) {
@Override
public boolean matches(String option) {
return DocLint.isValidOption(
option.replace(XDOCLINT_CUSTOM.text, DocLint.XMSGS_CUSTOM_PREFIX));
}
@Override
public boolean process(OptionHelper helper, String option) {
String prev = helper.get(XDOCLINT_CUSTOM);
String next = (prev == null) ? option : (prev + " " + option);
helper.put(XDOCLINT_CUSTOM.text, next);
return false;
}
},
// -nowarn is retained for command-line backward compatibility
NOWARN("-nowarn", "opt.nowarn", STANDARD, BASIC) {
@Override
public boolean process(OptionHelper helper, String option) {
helper.put("-Xlint:none", option);
return false;
}
},
VERBOSE("-verbose", "opt.verbose", STANDARD, BASIC),
// -deprecation is retained for command-line backward compatibility
DEPRECATION("-deprecation", "opt.deprecation", STANDARD, BASIC) {
@Override
public boolean process(OptionHelper helper, String option) {
helper.put("-Xlint:deprecation", option);
return false;
}
},
CLASSPATH("-classpath", "opt.arg.path", "opt.classpath", STANDARD, FILEMANAGER),
CP("-cp", "opt.arg.path", "opt.classpath", STANDARD, FILEMANAGER) {
@Override
public boolean process(OptionHelper helper, String option, String arg) {
return super.process(helper, "-classpath", arg);
}
},
SOURCEPATH("-sourcepath", "opt.arg.path", "opt.sourcepath", STANDARD, FILEMANAGER),
BOOTCLASSPATH("-bootclasspath", "opt.arg.path", "opt.bootclasspath", STANDARD, FILEMANAGER) {
@Override
public boolean process(OptionHelper helper, String option, String arg) {
helper.remove("-Xbootclasspath/p:");
helper.remove("-Xbootclasspath/a:");
return super.process(helper, option, arg);
}
},
XBOOTCLASSPATH_PREPEND("-Xbootclasspath/p:", "opt.arg.path", "opt.Xbootclasspath.p", EXTENDED, FILEMANAGER),
XBOOTCLASSPATH_APPEND("-Xbootclasspath/a:", "opt.arg.path", "opt.Xbootclasspath.a", EXTENDED, FILEMANAGER),
XBOOTCLASSPATH("-Xbootclasspath:", "opt.arg.path", "opt.bootclasspath", EXTENDED, FILEMANAGER) {
@Override
public boolean process(OptionHelper helper, String option, String arg) {
helper.remove("-Xbootclasspath/p:");
helper.remove("-Xbootclasspath/a:");
return super.process(helper, "-bootclasspath", arg);
}
},
EXTDIRS("-extdirs", "opt.arg.dirs", "opt.extdirs", STANDARD, FILEMANAGER),
DJAVA_EXT_DIRS("-Djava.ext.dirs=", "opt.arg.dirs", "opt.extdirs", EXTENDED, FILEMANAGER) {
@Override
public boolean process(OptionHelper helper, String option, String arg) {
return super.process(helper, "-extdirs", arg);
}
},
ENDORSEDDIRS("-endorseddirs", "opt.arg.dirs", "opt.endorseddirs", STANDARD, FILEMANAGER),
DJAVA_ENDORSED_DIRS("-Djava.endorsed.dirs=", "opt.arg.dirs", "opt.endorseddirs", EXTENDED, FILEMANAGER) {
@Override
public boolean process(OptionHelper helper, String option, String arg) {
return super.process(helper, "-endorseddirs", arg);
}
},
PROC("-proc:", "opt.proc.none.only", STANDARD, BASIC, ONEOF, "none", "only"),
PROCESSOR("-processor", "opt.arg.class.list", "opt.processor", STANDARD, BASIC),
PROCESSORPATH("-processorpath", "opt.arg.path", "opt.processorpath", STANDARD, FILEMANAGER),
PARAMETERS("-parameters","opt.parameters", STANDARD, BASIC),
D("-d", "opt.arg.directory", "opt.d", STANDARD, FILEMANAGER),
S("-s", "opt.arg.directory", "opt.sourceDest", STANDARD, FILEMANAGER),
H("-h", "opt.arg.directory", "opt.headerDest", STANDARD, FILEMANAGER),
IMPLICIT("-implicit:", "opt.implicit", STANDARD, BASIC, ONEOF, "none", "class"),
ENCODING("-encoding", "opt.arg.encoding", "opt.encoding", STANDARD, FILEMANAGER) {
@Override
public boolean process(OptionHelper helper, String option, String operand) {
return super.process(helper, option, operand);
}
},
SOURCE("-source", "opt.arg.release", "opt.source", STANDARD, BASIC) {
@Override
public boolean process(OptionHelper helper, String option, String operand) {
Source source = Source.lookup(operand);
if (source == null) {
helper.error("err.invalid.source", operand);
return true;
}
return super.process(helper, option, operand);
}
},
TARGET("-target", "opt.arg.release", "opt.target", STANDARD, BASIC) {
@Override
public boolean process(OptionHelper helper, String option, String operand) {
Target target = Target.lookup(operand);
if (target == null) {
helper.error("err.invalid.target", operand);
return true;
}
return super.process(helper, option, operand);
}
},
PROFILE("-profile", "opt.arg.profile", "opt.profile", STANDARD, BASIC) {
@Override
public boolean process(OptionHelper helper, String option, String operand) {
Profile profile = Profile.lookup(operand);
if (profile == null) {
helper.error("err.invalid.profile", operand);
return true;
}
return super.process(helper, option, operand);
}
},
VERSION("-version", "opt.version", STANDARD, INFO) {
@Override
public boolean process(OptionHelper helper, String option) {
Log log = helper.getLog();
String ownName = helper.getOwnName();
log.printLines(PrefixKind.JAVAC, "version", ownName, JavaCompiler.version());
return super.process(helper, option);
}
},
FULLVERSION("-fullversion", null, HIDDEN, INFO) {
@Override
public boolean process(OptionHelper helper, String option) {
Log log = helper.getLog();
String ownName = helper.getOwnName();
log.printLines(PrefixKind.JAVAC, "fullVersion", ownName, JavaCompiler.fullVersion());
return super.process(helper, option);
}
},
DIAGS("-XDdiags=", null, HIDDEN, INFO) {
@Override
public boolean process(OptionHelper helper, String option) {
option = option.substring(option.indexOf('=') + 1);
String diagsOption = option.contains("%") ?
"-XDdiagsFormat=" :
"-XDdiags=";
diagsOption += option;
if (XD.matches(diagsOption))
return XD.process(helper, diagsOption);
else
return false;
}
},
HELP("-help", "opt.help", STANDARD, INFO) {
@Override
public boolean process(OptionHelper helper, String option) {
Log log = helper.getLog();
String ownName = helper.getOwnName();
log.printLines(PrefixKind.JAVAC, "msg.usage.header", ownName);
for (Option o: getJavaCompilerOptions()) {
o.help(log, OptionKind.STANDARD);
}
log.printNewline();
return super.process(helper, option);
}
},
A("-A", "opt.arg.key.equals.value", "opt.A", STANDARD, BASIC, true) {
@Override
public boolean matches(String arg) {
return arg.startsWith("-A");
}
@Override
public boolean hasArg() {
return false;
}
// Mapping for processor options created in
// JavacProcessingEnvironment
@Override
public boolean process(OptionHelper helper, String option) {
int argLength = option.length();
if (argLength == 2) {
helper.error("err.empty.A.argument");
return true;
}
int sepIndex = option.indexOf('=');
String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) );
if (!JavacProcessingEnvironment.isValidOptionName(key)) {
helper.error("err.invalid.A.key", option);
return true;
}
return process(helper, option, option);
}
},
X("-X", "opt.X", STANDARD, INFO) {
@Override
public boolean process(OptionHelper helper, String option) {
Log log = helper.getLog();
for (Option o: getJavaCompilerOptions()) {
o.help(log, OptionKind.EXTENDED);
}
log.printNewline();
log.printLines(PrefixKind.JAVAC, "msg.usage.nonstandard.footer");
return super.process(helper, option);
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the launcher.
J("-J", "opt.arg.flag", "opt.J", STANDARD, INFO, true) {
@Override
public boolean process(OptionHelper helper, String option) {
throw new AssertionError
("the -J flag should be caught by the launcher.");
}
},
MOREINFO("-moreinfo", null, HIDDEN, BASIC) {
@Override
public boolean process(OptionHelper helper, String option) {
Type.moreInfo = true;
return super.process(helper, option);
}
},
// treat warnings as errors
WERROR("-Werror", "opt.Werror", STANDARD, BASIC),
// prompt after each error
// new Option("-prompt", "opt.prompt"),
PROMPT("-prompt", null, HIDDEN, BASIC),
// dump stack on error
DOE("-doe", null, HIDDEN, BASIC),
// output source after type erasure
PRINTSOURCE("-printsource", null, HIDDEN, BASIC),
// display warnings for generic unchecked operations
WARNUNCHECKED("-warnunchecked", null, HIDDEN, BASIC) {
@Override
public boolean process(OptionHelper helper, String option) {
helper.put("-Xlint:unchecked", option);
return false;
}
},
XMAXERRS("-Xmaxerrs", "opt.arg.number", "opt.maxerrs", EXTENDED, BASIC),
XMAXWARNS("-Xmaxwarns", "opt.arg.number", "opt.maxwarns", EXTENDED, BASIC),
XSTDOUT("-Xstdout", "opt.arg.file", "opt.Xstdout", EXTENDED, INFO) {
@Override
public boolean process(OptionHelper helper, String option, String arg) {
try {
Log log = helper.getLog();
// TODO: this file should be closed at the end of compilation
log.setWriters(new PrintWriter(new FileWriter(arg), true));
} catch (java.io.IOException e) {
helper.error("err.error.writing.file", arg, e);
return true;
}
return super.process(helper, option, arg);
}
},
XPRINT("-Xprint", "opt.print", EXTENDED, BASIC),
XPRINTROUNDS("-XprintRounds", "opt.printRounds", EXTENDED, BASIC),
XPRINTPROCESSORINFO("-XprintProcessorInfo", "opt.printProcessorInfo", EXTENDED, BASIC),
XPREFER("-Xprefer:", "opt.prefer", EXTENDED, BASIC, ONEOF, "source", "newer"),
// see enum PkgInfo
XPKGINFO("-Xpkginfo:", "opt.pkginfo", EXTENDED, BASIC, ONEOF, "always", "legacy", "nonempty"),
/* -O is a no-op, accepted for backward compatibility. */
O("-O", null, HIDDEN, BASIC),
/* -Xjcov produces tables to support the code coverage tool jcov. */
XJCOV("-Xjcov", null, HIDDEN, BASIC),
PLUGIN("-Xplugin:", "opt.arg.plugin", "opt.plugin", EXTENDED, BASIC) {
@Override
public boolean process(OptionHelper helper, String option) {
String p = option.substring(option.indexOf(':') + 1);
String prev = helper.get(PLUGIN);
helper.put(PLUGIN.text, (prev == null) ? p : prev + '\0' + p.trim());
return false;
}
},
XDIAGS("-Xdiags:", "opt.diags", EXTENDED, BASIC, ONEOF, "compact", "verbose"),
/* This is a back door to the compiler's option table.
* -XDx=y sets the option x to the value y.
* -XDx sets the option x to the value x.
*/
XD("-XD", null, HIDDEN, BASIC) {
@Override
public boolean matches(String s) {
return s.startsWith(text);
}
@Override
public boolean process(OptionHelper helper, String option) {
option = option.substring(text.length());
int eq = option.indexOf('=');
String key = (eq < 0) ? option : option.substring(0, eq);
String value = (eq < 0) ? option : option.substring(eq+1);
helper.put(key, value);
return false;
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the CommandLine class.
AT("@", "opt.arg.file", "opt.AT", STANDARD, INFO, true) {
@Override
public boolean process(OptionHelper helper, String option) {
throw new AssertionError("the @ flag should be caught by CommandLine.");
}
},
/*
* TODO: With apt, the matches method accepts anything if
* -XclassAsDecls is used; code elsewhere does the lookup to
* see if the class name is both legal and found.
*
* In apt, the process method adds the candidate class file
* name to a separate list.
*/
SOURCEFILE("sourcefile", null, HIDDEN, INFO) {
@Override
public boolean matches(String s) {
return s.endsWith(".java") // Java source file
|| SourceVersion.isName(s); // Legal type name
}
@Override
public boolean process(OptionHelper helper, String option) {
if (option.endsWith(".java") ) {
File f = new File(option);
if (!f.exists()) {
helper.error("err.file.not.found", f);
return true;
}
if (!f.isFile()) {
helper.error("err.file.not.file", f);
return true;
}
helper.addFile(f);
} else {
helper.addClassName(option);
}
return false;
}
};
/** The kind of an Option. This is used by the -help and -X options. */
public enum OptionKind {
/** A standard option, documented by -help. */
STANDARD,
/** An extended option, documented by -X. */
EXTENDED,
/** A hidden option, not documented. */
HIDDEN,
}
/** The group for an Option. This determines the situations in which the
* option is applicable. */
enum OptionGroup {
/** A basic option, available for use on the command line or via the
* Compiler API. */
BASIC,
/** An option for javac's standard JavaFileManager. Other file managers
* may or may not support these options. */
FILEMANAGER,
/** A command-line option that requests information, such as -help. */
INFO,
/** A command-line "option" representing a file or class name. */
OPERAND
}
/** The kind of choice for "choice" options. */
enum ChoiceKind {
/** The expected value is exactly one of the set of choices. */
ONEOF,
/** The expected value is one of more of the set of choices. */
ANYOF
}
public final String text;
final OptionKind kind;
final OptionGroup group;
/** Documentation key for arguments.
*/
final String argsNameKey;
/** Documentation key for description.
*/
final String descrKey;
/** Suffix option (-foo=bar or -foo:bar)
*/
final boolean hasSuffix;
/** The kind of choices for this option, if any.
*/
final ChoiceKind choiceKind;
/** The choices for this option, if any, and whether or not the choices
* are hidden
*/
final Map<String,Boolean> choices;
Option(String text, String descrKey,
OptionKind kind, OptionGroup group) {
this(text, null, descrKey, kind, group, null, null, false);
}
Option(String text, String argsNameKey, String descrKey,
OptionKind kind, OptionGroup group) {
this(text, argsNameKey, descrKey, kind, group, null, null, false);
}
Option(String text, String argsNameKey, String descrKey,
OptionKind kind, OptionGroup group, boolean doHasSuffix) {
this(text, argsNameKey, descrKey, kind, group, null, null, doHasSuffix);
}
Option(String text, String descrKey,
OptionKind kind, OptionGroup group,
ChoiceKind choiceKind, Map<String,Boolean> choices) {
this(text, null, descrKey, kind, group, choiceKind, choices, false);
}
Option(String text, String descrKey,
OptionKind kind, OptionGroup group,
ChoiceKind choiceKind, String... choices) {
this(text, null, descrKey, kind, group, choiceKind,
createChoices(choices), false);
}
// where
private static Map<String,Boolean> createChoices(String... choices) {
Map<String,Boolean> map = new LinkedHashMap<String,Boolean>();
for (String c: choices)
map.put(c, false);
return map;
}
private Option(String text, String argsNameKey, String descrKey,
OptionKind kind, OptionGroup group,
ChoiceKind choiceKind, Map<String,Boolean> choices,
boolean doHasSuffix) {
this.text = text;
this.argsNameKey = argsNameKey;
this.descrKey = descrKey;
this.kind = kind;
this.group = group;
this.choiceKind = choiceKind;
this.choices = choices;
char lastChar = text.charAt(text.length()-1);
this.hasSuffix = doHasSuffix || lastChar == ':' || lastChar == '=';
}
public String getText() {
return text;
}
public OptionKind getKind() {
return kind;
}
public boolean hasArg() {
return argsNameKey != null && !hasSuffix;
}
public boolean matches(String option) {
if (!hasSuffix)
return option.equals(text);
if (!option.startsWith(text))
return false;
if (choices != null) {
String arg = option.substring(text.length());
if (choiceKind == ChoiceKind.ONEOF)
return choices.keySet().contains(arg);
else {
for (String a: arg.split(",+")) {
if (!choices.keySet().contains(a))
return false;
}
}
}
return true;
}
public boolean process(OptionHelper helper, String option, String arg) {
if (choices != null) {
if (choiceKind == ChoiceKind.ONEOF) {
// some clients like to see just one of option+choice set
for (String s: choices.keySet())
helper.remove(option + s);
String opt = option + arg;
helper.put(opt, opt);
// some clients like to see option (without trailing ":")
// set to arg
String nm = option.substring(0, option.length() - 1);
helper.put(nm, arg);
} else {
// set option+word for each word in arg
for (String a: arg.split(",+")) {
String opt = option + a;
helper.put(opt, opt);
}
}
}
helper.put(option, arg);
return false;
}
public boolean process(OptionHelper helper, String option) {
if (hasSuffix)
return process(helper, text, option.substring(text.length()));
else
return process(helper, option, option);
}
void help(Log log, OptionKind kind) {
if (this.kind != kind)
return;
log.printRawLines(WriterKind.NOTICE,
String.format(" %-26s %s",
helpSynopsis(log),
log.localize(PrefixKind.JAVAC, descrKey)));
}
private String helpSynopsis(Log log) {
StringBuilder sb = new StringBuilder();
sb.append(text);
if (argsNameKey == null) {
if (choices != null) {
String sep = "{";
for (Map.Entry<String,Boolean> e: choices.entrySet()) {
if (!e.getValue()) {
sb.append(sep);
sb.append(e.getKey());
sep = ",";
}
}
sb.append("}");
}
} else {
if (!hasSuffix)
sb.append(" ");
sb.append(log.localize(PrefixKind.JAVAC, argsNameKey));
}
return sb.toString();
}
// For -XpkgInfo:value
public enum PkgInfo {
/**
* Always generate package-info.class for every package-info.java file.
* The file may be empty if there annotations with a RetentionPolicy
* of CLASS or RUNTIME. This option may be useful in conjunction with
* build systems (such as Ant) that expect javac to generate at least
* one .class file for every .java file.
*/
ALWAYS,
/**
* Generate a package-info.class file if package-info.java contains
* annotations. The file may be empty if all the annotations have
* a RetentionPolicy of SOURCE.
* This value is just for backwards compatibility with earlier behavior.
* Either of the other two values are to be preferred to using this one.
*/
LEGACY,
/**
* Generate a package-info.class file if and only if there are annotations
* in package-info.java to be written into it.
*/
NONEMPTY;
public static PkgInfo get(Options options) {
String v = options.get(XPKGINFO);
return (v == null
? PkgInfo.LEGACY
: PkgInfo.valueOf(StringUtils.toUpperCase(v)));
}
}
private static Map<String,Boolean> getXLintChoices() {
Map<String,Boolean> choices = new LinkedHashMap<String,Boolean>();
choices.put("all", false);
for (Lint.LintCategory c : Lint.LintCategory.values())
choices.put(c.option, c.hidden);
for (Lint.LintCategory c : Lint.LintCategory.values())
choices.put("-" + c.option, c.hidden);
choices.put("none", false);
return choices;
}
static Set<Option> getJavaCompilerOptions() {
return EnumSet.allOf(Option.class);
}
public static Set<Option> getJavacFileManagerOptions() {
return getOptions(EnumSet.of(FILEMANAGER));
}
public static Set<Option> getJavacToolOptions() {
return getOptions(EnumSet.of(BASIC));
}
static Set<Option> getOptions(Set<OptionGroup> desired) {
Set<Option> options = EnumSet.noneOf(Option.class);
for (Option option : Option.values())
if (desired.contains(option.group))
options.add(option);
return Collections.unmodifiableSet(options);
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.main;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Log.PrefixKind;
import java.io.File;
/**
* Helper object to be used by {@link Option#process}, providing access to
* the compilation environment.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
public abstract class OptionHelper {
/** Get the current value of an option. */
public abstract String get(Option option);
/** Set the value of an option. */
public abstract void put(String name, String value);
/** Remove any prior value for an option. */
public abstract void remove(String name);
/** Get access to the Log for the compilation. */
public abstract Log getLog();
/** Get the name of the tool, such as "javac", to be used in info like -help. */
public abstract String getOwnName();
/** Report an error. */
abstract void error(String key, Object... args);
/** Record a file to be compiled. */
abstract void addFile(File f);
/** Record the name of a class for annotation processing. */
abstract void addClassName(String s);
/** An implementation of OptionHelper that mostly throws exceptions. */
public static class GrumpyHelper extends OptionHelper {
private final Log log;
public GrumpyHelper(Log log) {
this.log = log;
}
@Override
public Log getLog() {
return log;
}
@Override
public String getOwnName() {
throw new IllegalStateException();
}
@Override
public String get(Option option) {
throw new IllegalArgumentException();
}
@Override
public void put(String name, String value) {
throw new IllegalArgumentException();
}
@Override
public void remove(String name) {
throw new IllegalArgumentException();
}
@Override
void error(String key, Object... args) {
throw new IllegalArgumentException(log.localize(PrefixKind.JAVAC, key, args));
}
@Override
public void addFile(File f) {
throw new IllegalArgumentException(f.getPath());
}
@Override
public void addClassName(String s) {
throw new IllegalArgumentException(s);
}
}
}