src/share/classes/com/sun/tools/javac/main/Main.java

Tue, 28 Dec 2010 15:54:52 -0800

author
ohair
date
Tue, 28 Dec 2010 15:54:52 -0800
changeset 798
4868a36f6fd8
parent 757
c44234f680da
child 820
2d5aff89aaa3
permissions
-rw-r--r--

6962318: Update copyright year
Reviewed-by: xdono

     1 /*
     2  * Copyright (c) 1999, 2010, 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  */
    26 package com.sun.tools.javac.main;
    28 import java.io.File;
    29 import java.io.IOException;
    30 import java.io.PrintWriter;
    31 import java.net.URL;
    32 import java.security.DigestInputStream;
    33 import java.security.MessageDigest;
    34 import java.util.MissingResourceException;
    35 import javax.tools.JavaFileManager;
    36 import javax.tools.JavaFileObject;
    37 import javax.annotation.processing.Processor;
    39 import com.sun.tools.javac.code.Source;
    40 import com.sun.tools.javac.file.CacheFSInfo;
    41 import com.sun.tools.javac.file.JavacFileManager;
    42 import com.sun.tools.javac.jvm.Target;
    43 import com.sun.tools.javac.main.JavacOption.Option;
    44 import com.sun.tools.javac.main.RecognizedOptions.OptionHelper;
    45 import com.sun.tools.javac.util.*;
    46 import com.sun.tools.javac.processing.AnnotationProcessingError;
    48 import static com.sun.tools.javac.main.OptionName.*;
    50 /** This class provides a commandline interface to the GJC compiler.
    51  *
    52  *  <p><b>This is NOT part of any supported API.
    53  *  If you write code that depends on this, you do so at your own risk.
    54  *  This code and its internal interfaces are subject to change or
    55  *  deletion without notice.</b>
    56  */
    57 public class Main {
    59     /** The name of the compiler, for use in diagnostics.
    60      */
    61     String ownName;
    63     /** The writer to use for diagnostic output.
    64      */
    65     PrintWriter out;
    67     /**
    68      * If true, any command line arg errors will cause an exception.
    69      */
    70     boolean fatalErrors;
    72     /** Result codes.
    73      */
    74     static final int
    75         EXIT_OK = 0,        // Compilation completed with no errors.
    76         EXIT_ERROR = 1,     // Completed but reported errors.
    77         EXIT_CMDERR = 2,    // Bad command-line arguments
    78         EXIT_SYSERR = 3,    // System error or resource exhaustion.
    79         EXIT_ABNORMAL = 4;  // Compiler terminated abnormally
    81     private Option[] recognizedOptions = RecognizedOptions.getJavaCompilerOptions(new OptionHelper() {
    83         public void setOut(PrintWriter out) {
    84             Main.this.out = out;
    85         }
    87         public void error(String key, Object... args) {
    88             Main.this.error(key, args);
    89         }
    91         public void printVersion() {
    92             Log.printLines(out, getLocalizedString("version", ownName,  JavaCompiler.version()));
    93         }
    95         public void printFullVersion() {
    96             Log.printLines(out, getLocalizedString("fullVersion", ownName,  JavaCompiler.fullVersion()));
    97         }
    99         public void printHelp() {
   100             help();
   101         }
   103         public void printXhelp() {
   104             xhelp();
   105         }
   107         public void addFile(File f) {
   108             if (!filenames.contains(f))
   109                 filenames.append(f);
   110         }
   112         public void addClassName(String s) {
   113             classnames.append(s);
   114         }
   116     });
   118     /**
   119      * Construct a compiler instance.
   120      */
   121     public Main(String name) {
   122         this(name, new PrintWriter(System.err, true));
   123     }
   125     /**
   126      * Construct a compiler instance.
   127      */
   128     public Main(String name, PrintWriter out) {
   129         this.ownName = name;
   130         this.out = out;
   131     }
   132     /** A table of all options that's passed to the JavaCompiler constructor.  */
   133     private Options options = null;
   135     /** The list of source files to process
   136      */
   137     public ListBuffer<File> filenames = null; // XXX sb protected
   139     /** List of class files names passed on the command line
   140      */
   141     public ListBuffer<String> classnames = null; // XXX sb protected
   143     /** Print a string that explains usage.
   144      */
   145     void help() {
   146         Log.printLines(out, getLocalizedString("msg.usage.header", ownName));
   147         for (int i=0; i<recognizedOptions.length; i++) {
   148             recognizedOptions[i].help(out);
   149         }
   150         out.println();
   151     }
   153     /** Print a string that explains usage for X options.
   154      */
   155     void xhelp() {
   156         for (int i=0; i<recognizedOptions.length; i++) {
   157             recognizedOptions[i].xhelp(out);
   158         }
   159         out.println();
   160         Log.printLines(out, getLocalizedString("msg.usage.nonstandard.footer"));
   161     }
   163     /** Report a usage error.
   164      */
   165     void error(String key, Object... args) {
   166         if (fatalErrors) {
   167             String msg = getLocalizedString(key, args);
   168             throw new PropagatedException(new IllegalStateException(msg));
   169         }
   170         warning(key, args);
   171         Log.printLines(out, getLocalizedString("msg.usage", ownName));
   172     }
   174     /** Report a warning.
   175      */
   176     void warning(String key, Object... args) {
   177         Log.printLines(out, ownName + ": "
   178                        + getLocalizedString(key, args));
   179     }
   181     public Option getOption(String flag) {
   182         for (Option option : recognizedOptions) {
   183             if (option.matches(flag))
   184                 return option;
   185         }
   186         return null;
   187     }
   189     public void setOptions(Options options) {
   190         if (options == null)
   191             throw new NullPointerException();
   192         this.options = options;
   193     }
   195     public void setFatalErrors(boolean fatalErrors) {
   196         this.fatalErrors = fatalErrors;
   197     }
   199     /** Process command line arguments: store all command line options
   200      *  in `options' table and return all source filenames.
   201      *  @param flags    The array of command line arguments.
   202      */
   203     public List<File> processArgs(String[] flags) { // XXX sb protected
   204         int ac = 0;
   205         while (ac < flags.length) {
   206             String flag = flags[ac];
   207             ac++;
   209             Option option = null;
   211             if (flag.length() > 0) {
   212                 // quick hack to speed up file processing:
   213                 // if the option does not begin with '-', there is no need to check
   214                 // most of the compiler options.
   215                 int firstOptionToCheck = flag.charAt(0) == '-' ? 0 : recognizedOptions.length-1;
   216                 for (int j=firstOptionToCheck; j<recognizedOptions.length; j++) {
   217                     if (recognizedOptions[j].matches(flag)) {
   218                         option = recognizedOptions[j];
   219                         break;
   220                     }
   221                 }
   222             }
   224             if (option == null) {
   225                 error("err.invalid.flag", flag);
   226                 return null;
   227             }
   229             if (option.hasArg()) {
   230                 if (ac == flags.length) {
   231                     error("err.req.arg", flag);
   232                     return null;
   233                 }
   234                 String operand = flags[ac];
   235                 ac++;
   236                 if (option.process(options, flag, operand))
   237                     return null;
   238             } else {
   239                 if (option.process(options, flag))
   240                     return null;
   241             }
   242         }
   244         if (!checkDirectory(D))
   245             return null;
   246         if (!checkDirectory(S))
   247             return null;
   249         String sourceString = options.get(SOURCE);
   250         Source source = (sourceString != null)
   251             ? Source.lookup(sourceString)
   252             : Source.DEFAULT;
   253         String targetString = options.get(TARGET);
   254         Target target = (targetString != null)
   255             ? Target.lookup(targetString)
   256             : Target.DEFAULT;
   257         // We don't check source/target consistency for CLDC, as J2ME
   258         // profiles are not aligned with J2SE targets; moreover, a
   259         // single CLDC target may have many profiles.  In addition,
   260         // this is needed for the continued functioning of the JSR14
   261         // prototype.
   262         if (Character.isDigit(target.name.charAt(0))) {
   263             if (target.compareTo(source.requiredTarget()) < 0) {
   264                 if (targetString != null) {
   265                     if (sourceString == null) {
   266                         warning("warn.target.default.source.conflict",
   267                                 targetString,
   268                                 source.requiredTarget().name);
   269                     } else {
   270                         warning("warn.source.target.conflict",
   271                                 sourceString,
   272                                 source.requiredTarget().name);
   273                     }
   274                     return null;
   275                 } else {
   276                     target = source.requiredTarget();
   277                     options.put("-target", target.name);
   278                 }
   279             } else {
   280                 if (targetString == null && !source.allowGenerics()) {
   281                     target = Target.JDK1_4;
   282                     options.put("-target", target.name);
   283                 }
   284             }
   285         }
   287         // phase this out with JSR 292 PFD
   288         if ("no".equals(options.get("allowTransitionalJSR292"))) {
   289             options.put("allowTransitionalJSR292", null);
   290         } else if (target.hasInvokedynamic() && options.isUnset("allowTransitionalJSR292")) {
   291             options.put("allowTransitionalJSR292", "allowTransitionalJSR292");
   292         }
   294         // handle this here so it works even if no other options given
   295         String showClass = options.get("showClass");
   296         if (showClass != null) {
   297             if (showClass.equals("showClass")) // no value given for option
   298                 showClass = "com.sun.tools.javac.Main";
   299             showClass(showClass);
   300         }
   302         return filenames.toList();
   303     }
   304     // where
   305         private boolean checkDirectory(OptionName optName) {
   306             String value = options.get(optName);
   307             if (value == null)
   308                 return true;
   309             File file = new File(value);
   310             if (!file.exists()) {
   311                 error("err.dir.not.found", value);
   312                 return false;
   313             }
   314             if (!file.isDirectory()) {
   315                 error("err.file.not.directory", value);
   316                 return false;
   317             }
   318             return true;
   319         }
   321     /** Programmatic interface for main function.
   322      * @param args    The command line parameters.
   323      */
   324     public int compile(String[] args) {
   325         Context context = new Context();
   326         JavacFileManager.preRegister(context); // can't create it until Log has been set up
   327         int result = compile(args, context);
   328         if (fileManager instanceof JavacFileManager) {
   329             // A fresh context was created above, so jfm must be a JavacFileManager
   330             ((JavacFileManager)fileManager).close();
   331         }
   332         return result;
   333     }
   335     public int compile(String[] args, Context context) {
   336         return compile(args, context, List.<JavaFileObject>nil(), null);
   337     }
   339     /** Programmatic interface for main function.
   340      * @param args    The command line parameters.
   341      */
   342     public int compile(String[] args,
   343                        Context context,
   344                        List<JavaFileObject> fileObjects,
   345                        Iterable<? extends Processor> processors)
   346     {
   347         if (options == null)
   348             options = Options.instance(context); // creates a new one
   350         filenames = new ListBuffer<File>();
   351         classnames = new ListBuffer<String>();
   352         JavaCompiler comp = null;
   353         /*
   354          * TODO: Logic below about what is an acceptable command line
   355          * should be updated to take annotation processing semantics
   356          * into account.
   357          */
   358         try {
   359             if (args.length == 0 && fileObjects.isEmpty()) {
   360                 help();
   361                 return EXIT_CMDERR;
   362             }
   364             List<File> files;
   365             try {
   366                 files = processArgs(CommandLine.parse(args));
   367                 if (files == null) {
   368                     // null signals an error in options, abort
   369                     return EXIT_CMDERR;
   370                 } else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
   371                     // it is allowed to compile nothing if just asking for help or version info
   372                     if (options.isSet(HELP)
   373                         || options.isSet(X)
   374                         || options.isSet(VERSION)
   375                         || options.isSet(FULLVERSION))
   376                         return EXIT_OK;
   377                     error("err.no.source.files");
   378                     return EXIT_CMDERR;
   379                 }
   380             } catch (java.io.FileNotFoundException e) {
   381                 Log.printLines(out, ownName + ": " +
   382                                getLocalizedString("err.file.not.found",
   383                                                   e.getMessage()));
   384                 return EXIT_SYSERR;
   385             }
   387             boolean forceStdOut = options.isSet("stdout");
   388             if (forceStdOut) {
   389                 out.flush();
   390                 out = new PrintWriter(System.out, true);
   391             }
   393             context.put(Log.outKey, out);
   395             // allow System property in following line as a Mustang legacy
   396             boolean batchMode = (options.isUnset("nonBatchMode")
   397                         && System.getProperty("nonBatchMode") == null);
   398             if (batchMode)
   399                 CacheFSInfo.preRegister(context);
   401             fileManager = context.get(JavaFileManager.class);
   403             comp = JavaCompiler.instance(context);
   404             if (comp == null) return EXIT_SYSERR;
   406             Log log = Log.instance(context);
   408             if (!files.isEmpty()) {
   409                 // add filenames to fileObjects
   410                 comp = JavaCompiler.instance(context);
   411                 List<JavaFileObject> otherFiles = List.nil();
   412                 JavacFileManager dfm = (JavacFileManager)fileManager;
   413                 for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(files))
   414                     otherFiles = otherFiles.prepend(fo);
   415                 for (JavaFileObject fo : otherFiles)
   416                     fileObjects = fileObjects.prepend(fo);
   417             }
   418             comp.compile(fileObjects,
   419                          classnames.toList(),
   420                          processors);
   422             if (log.expectDiagKeys != null) {
   423                 if (log.expectDiagKeys.isEmpty()) {
   424                     Log.printLines(log.noticeWriter, "all expected diagnostics found");
   425                     return EXIT_OK;
   426                 } else {
   427                     Log.printLines(log.noticeWriter, "expected diagnostic keys not found: " + log.expectDiagKeys);
   428                     return EXIT_ERROR;
   429                 }
   430             }
   432             if (comp.errorCount() != 0)
   433                 return EXIT_ERROR;
   434         } catch (IOException ex) {
   435             ioMessage(ex);
   436             return EXIT_SYSERR;
   437         } catch (OutOfMemoryError ex) {
   438             resourceMessage(ex);
   439             return EXIT_SYSERR;
   440         } catch (StackOverflowError ex) {
   441             resourceMessage(ex);
   442             return EXIT_SYSERR;
   443         } catch (FatalError ex) {
   444             feMessage(ex);
   445             return EXIT_SYSERR;
   446         } catch(AnnotationProcessingError ex) {
   447             apMessage(ex);
   448             return EXIT_SYSERR;
   449         } catch (ClientCodeException ex) {
   450             // as specified by javax.tools.JavaCompiler#getTask
   451             // and javax.tools.JavaCompiler.CompilationTask#call
   452             throw new RuntimeException(ex.getCause());
   453         } catch (PropagatedException ex) {
   454             throw ex.getCause();
   455         } catch (Throwable ex) {
   456             // Nasty.  If we've already reported an error, compensate
   457             // for buggy compiler error recovery by swallowing thrown
   458             // exceptions.
   459             if (comp == null || comp.errorCount() == 0 ||
   460                 options == null || options.isSet("dev"))
   461                 bugMessage(ex);
   462             return EXIT_ABNORMAL;
   463         } finally {
   464             if (comp != null) comp.close();
   465             filenames = null;
   466             options = null;
   467         }
   468         return EXIT_OK;
   469     }
   471     /** Print a message reporting an internal error.
   472      */
   473     void bugMessage(Throwable ex) {
   474         Log.printLines(out, getLocalizedString("msg.bug",
   475                                                JavaCompiler.version()));
   476         ex.printStackTrace(out);
   477     }
   479     /** Print a message reporting a fatal error.
   480      */
   481     void feMessage(Throwable ex) {
   482         Log.printLines(out, ex.getMessage());
   483         if (ex.getCause() != null && options.isSet("dev")) {
   484             ex.getCause().printStackTrace(out);
   485         }
   486     }
   488     /** Print a message reporting an input/output error.
   489      */
   490     void ioMessage(Throwable ex) {
   491         Log.printLines(out, getLocalizedString("msg.io"));
   492         ex.printStackTrace(out);
   493     }
   495     /** Print a message reporting an out-of-resources error.
   496      */
   497     void resourceMessage(Throwable ex) {
   498         Log.printLines(out, getLocalizedString("msg.resource"));
   499 //      System.out.println("(name buffer len = " + Name.names.length + " " + Name.nc);//DEBUG
   500         ex.printStackTrace(out);
   501     }
   503     /** Print a message reporting an uncaught exception from an
   504      * annotation processor.
   505      */
   506     void apMessage(AnnotationProcessingError ex) {
   507         Log.printLines(out,
   508                        getLocalizedString("msg.proc.annotation.uncaught.exception"));
   509         ex.getCause().printStackTrace(out);
   510     }
   512     /** Display the location and checksum of a class. */
   513     void showClass(String className) {
   514         out.println("javac: show class: " + className);
   515         URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
   516         if (url == null)
   517             out.println("  class not found");
   518         else {
   519             out.println("  " + url);
   520             try {
   521                 final String algorithm = "MD5";
   522                 byte[] digest;
   523                 MessageDigest md = MessageDigest.getInstance(algorithm);
   524                 DigestInputStream in = new DigestInputStream(url.openStream(), md);
   525                 try {
   526                     byte[] buf = new byte[8192];
   527                     int n;
   528                     do { n = in.read(buf); } while (n > 0);
   529                     digest = md.digest();
   530                 } finally {
   531                     in.close();
   532                 }
   533                 StringBuilder sb = new StringBuilder();
   534                 for (byte b: digest)
   535                     sb.append(String.format("%02x", b));
   536                 out.println("  " + algorithm + " checksum: " + sb);
   537             } catch (Exception e) {
   538                 out.println("  cannot compute digest: " + e);
   539             }
   540         }
   541     }
   543     private JavaFileManager fileManager;
   545     /* ************************************************************************
   546      * Internationalization
   547      *************************************************************************/
   549     /** Find a localized string in the resource bundle.
   550      *  @param key     The key for the localized string.
   551      */
   552     public static String getLocalizedString(String key, Object... args) { // FIXME sb private
   553         try {
   554             if (messages == null)
   555                 messages = new JavacMessages(javacBundleName);
   556             return messages.getLocalizedString("javac." + key, args);
   557         }
   558         catch (MissingResourceException e) {
   559             throw new Error("Fatal Error: Resource for javac is missing", e);
   560         }
   561     }
   563     public static void useRawMessages(boolean enable) {
   564         if (enable) {
   565             messages = new JavacMessages(javacBundleName) {
   566                     @Override
   567                     public String getLocalizedString(String key, Object... args) {
   568                         return key;
   569                     }
   570                 };
   571         } else {
   572             messages = new JavacMessages(javacBundleName);
   573         }
   574     }
   576     private static final String javacBundleName =
   577         "com.sun.tools.javac.resources.javac";
   579     private static JavacMessages messages;
   580 }

mercurial