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

Wed, 06 Apr 2011 20:33:44 -0700

author
ohair
date
Wed, 06 Apr 2011 20:33:44 -0700
changeset 962
0ff2bbd38f10
parent 902
2a5c919f20b8
child 946
31e5cfc5a990
permissions
-rw-r--r--

7033660: Update copyright year to 2011 on any files changed in 2011
Reviewed-by: dholmes

     1 /*
     2  * Copyright (c) 1999, 2011, 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         // handle this here so it works even if no other options given
   288         String showClass = options.get("showClass");
   289         if (showClass != null) {
   290             if (showClass.equals("showClass")) // no value given for option
   291                 showClass = "com.sun.tools.javac.Main";
   292             showClass(showClass);
   293         }
   295         return filenames.toList();
   296     }
   297     // where
   298         private boolean checkDirectory(OptionName optName) {
   299             String value = options.get(optName);
   300             if (value == null)
   301                 return true;
   302             File file = new File(value);
   303             if (!file.exists()) {
   304                 error("err.dir.not.found", value);
   305                 return false;
   306             }
   307             if (!file.isDirectory()) {
   308                 error("err.file.not.directory", value);
   309                 return false;
   310             }
   311             return true;
   312         }
   314     /** Programmatic interface for main function.
   315      * @param args    The command line parameters.
   316      */
   317     public int compile(String[] args) {
   318         Context context = new Context();
   319         JavacFileManager.preRegister(context); // can't create it until Log has been set up
   320         int result = compile(args, context);
   321         if (fileManager instanceof JavacFileManager) {
   322             // A fresh context was created above, so jfm must be a JavacFileManager
   323             ((JavacFileManager)fileManager).close();
   324         }
   325         return result;
   326     }
   328     public int compile(String[] args, Context context) {
   329         return compile(args, context, List.<JavaFileObject>nil(), null);
   330     }
   332     /** Programmatic interface for main function.
   333      * @param args    The command line parameters.
   334      */
   335     public int compile(String[] args,
   336                        Context context,
   337                        List<JavaFileObject> fileObjects,
   338                        Iterable<? extends Processor> processors)
   339     {
   340         if (options == null)
   341             options = Options.instance(context); // creates a new one
   343         filenames = new ListBuffer<File>();
   344         classnames = new ListBuffer<String>();
   345         JavaCompiler comp = null;
   346         /*
   347          * TODO: Logic below about what is an acceptable command line
   348          * should be updated to take annotation processing semantics
   349          * into account.
   350          */
   351         try {
   352             if (args.length == 0 && fileObjects.isEmpty()) {
   353                 help();
   354                 return EXIT_CMDERR;
   355             }
   357             List<File> files;
   358             try {
   359                 files = processArgs(CommandLine.parse(args));
   360                 if (files == null) {
   361                     // null signals an error in options, abort
   362                     return EXIT_CMDERR;
   363                 } else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
   364                     // it is allowed to compile nothing if just asking for help or version info
   365                     if (options.isSet(HELP)
   366                         || options.isSet(X)
   367                         || options.isSet(VERSION)
   368                         || options.isSet(FULLVERSION))
   369                         return EXIT_OK;
   370                     if (JavaCompiler.explicitAnnotationProcessingRequested(options)) {
   371                         error("err.no.source.files.classes");
   372                     } else {
   373                         error("err.no.source.files");
   374                     }
   375                     return EXIT_CMDERR;
   376                 }
   377             } catch (java.io.FileNotFoundException e) {
   378                 Log.printLines(out, ownName + ": " +
   379                                getLocalizedString("err.file.not.found",
   380                                                   e.getMessage()));
   381                 return EXIT_SYSERR;
   382             }
   384             boolean forceStdOut = options.isSet("stdout");
   385             if (forceStdOut) {
   386                 out.flush();
   387                 out = new PrintWriter(System.out, true);
   388             }
   390             context.put(Log.outKey, out);
   392             // allow System property in following line as a Mustang legacy
   393             boolean batchMode = (options.isUnset("nonBatchMode")
   394                         && System.getProperty("nonBatchMode") == null);
   395             if (batchMode)
   396                 CacheFSInfo.preRegister(context);
   398             fileManager = context.get(JavaFileManager.class);
   400             comp = JavaCompiler.instance(context);
   401             if (comp == null) return EXIT_SYSERR;
   403             Log log = Log.instance(context);
   405             if (!files.isEmpty()) {
   406                 // add filenames to fileObjects
   407                 comp = JavaCompiler.instance(context);
   408                 List<JavaFileObject> otherFiles = List.nil();
   409                 JavacFileManager dfm = (JavacFileManager)fileManager;
   410                 for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(files))
   411                     otherFiles = otherFiles.prepend(fo);
   412                 for (JavaFileObject fo : otherFiles)
   413                     fileObjects = fileObjects.prepend(fo);
   414             }
   415             comp.compile(fileObjects,
   416                          classnames.toList(),
   417                          processors);
   419             if (log.expectDiagKeys != null) {
   420                 if (log.expectDiagKeys.isEmpty()) {
   421                     Log.printLines(log.noticeWriter, "all expected diagnostics found");
   422                     return EXIT_OK;
   423                 } else {
   424                     Log.printLines(log.noticeWriter, "expected diagnostic keys not found: " + log.expectDiagKeys);
   425                     return EXIT_ERROR;
   426                 }
   427             }
   429             if (comp.errorCount() != 0)
   430                 return EXIT_ERROR;
   431         } catch (IOException ex) {
   432             ioMessage(ex);
   433             return EXIT_SYSERR;
   434         } catch (OutOfMemoryError ex) {
   435             resourceMessage(ex);
   436             return EXIT_SYSERR;
   437         } catch (StackOverflowError ex) {
   438             resourceMessage(ex);
   439             return EXIT_SYSERR;
   440         } catch (FatalError ex) {
   441             feMessage(ex);
   442             return EXIT_SYSERR;
   443         } catch(AnnotationProcessingError ex) {
   444             apMessage(ex);
   445             return EXIT_SYSERR;
   446         } catch (ClientCodeException ex) {
   447             // as specified by javax.tools.JavaCompiler#getTask
   448             // and javax.tools.JavaCompiler.CompilationTask#call
   449             throw new RuntimeException(ex.getCause());
   450         } catch (PropagatedException ex) {
   451             throw ex.getCause();
   452         } catch (Throwable ex) {
   453             // Nasty.  If we've already reported an error, compensate
   454             // for buggy compiler error recovery by swallowing thrown
   455             // exceptions.
   456             if (comp == null || comp.errorCount() == 0 ||
   457                 options == null || options.isSet("dev"))
   458                 bugMessage(ex);
   459             return EXIT_ABNORMAL;
   460         } finally {
   461             if (comp != null) comp.close();
   462             filenames = null;
   463             options = null;
   464         }
   465         return EXIT_OK;
   466     }
   468     /** Print a message reporting an internal error.
   469      */
   470     void bugMessage(Throwable ex) {
   471         Log.printLines(out, getLocalizedString("msg.bug",
   472                                                JavaCompiler.version()));
   473         ex.printStackTrace(out);
   474     }
   476     /** Print a message reporting a fatal error.
   477      */
   478     void feMessage(Throwable ex) {
   479         Log.printLines(out, ex.getMessage());
   480         if (ex.getCause() != null && options.isSet("dev")) {
   481             ex.getCause().printStackTrace(out);
   482         }
   483     }
   485     /** Print a message reporting an input/output error.
   486      */
   487     void ioMessage(Throwable ex) {
   488         Log.printLines(out, getLocalizedString("msg.io"));
   489         ex.printStackTrace(out);
   490     }
   492     /** Print a message reporting an out-of-resources error.
   493      */
   494     void resourceMessage(Throwable ex) {
   495         Log.printLines(out, getLocalizedString("msg.resource"));
   496 //      System.out.println("(name buffer len = " + Name.names.length + " " + Name.nc);//DEBUG
   497         ex.printStackTrace(out);
   498     }
   500     /** Print a message reporting an uncaught exception from an
   501      * annotation processor.
   502      */
   503     void apMessage(AnnotationProcessingError ex) {
   504         Log.printLines(out,
   505                        getLocalizedString("msg.proc.annotation.uncaught.exception"));
   506         ex.getCause().printStackTrace(out);
   507     }
   509     /** Display the location and checksum of a class. */
   510     void showClass(String className) {
   511         out.println("javac: show class: " + className);
   512         URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
   513         if (url == null)
   514             out.println("  class not found");
   515         else {
   516             out.println("  " + url);
   517             try {
   518                 final String algorithm = "MD5";
   519                 byte[] digest;
   520                 MessageDigest md = MessageDigest.getInstance(algorithm);
   521                 DigestInputStream in = new DigestInputStream(url.openStream(), md);
   522                 try {
   523                     byte[] buf = new byte[8192];
   524                     int n;
   525                     do { n = in.read(buf); } while (n > 0);
   526                     digest = md.digest();
   527                 } finally {
   528                     in.close();
   529                 }
   530                 StringBuilder sb = new StringBuilder();
   531                 for (byte b: digest)
   532                     sb.append(String.format("%02x", b));
   533                 out.println("  " + algorithm + " checksum: " + sb);
   534             } catch (Exception e) {
   535                 out.println("  cannot compute digest: " + e);
   536             }
   537         }
   538     }
   540     private JavaFileManager fileManager;
   542     /* ************************************************************************
   543      * Internationalization
   544      *************************************************************************/
   546     /** Find a localized string in the resource bundle.
   547      *  @param key     The key for the localized string.
   548      */
   549     public static String getLocalizedString(String key, Object... args) { // FIXME sb private
   550         try {
   551             if (messages == null)
   552                 messages = new JavacMessages(javacBundleName);
   553             return messages.getLocalizedString("javac." + key, args);
   554         }
   555         catch (MissingResourceException e) {
   556             throw new Error("Fatal Error: Resource for javac is missing", e);
   557         }
   558     }
   560     public static void useRawMessages(boolean enable) {
   561         if (enable) {
   562             messages = new JavacMessages(javacBundleName) {
   563                     @Override
   564                     public String getLocalizedString(String key, Object... args) {
   565                         return key;
   566                     }
   567                 };
   568         } else {
   569             messages = new JavacMessages(javacBundleName);
   570         }
   571     }
   573     private static final String javacBundleName =
   574         "com.sun.tools.javac.resources.javac";
   576     private static JavacMessages messages;
   577 }

mercurial