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