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

Fri, 18 Jun 2010 15:12:04 -0700

author
jrose
date
Fri, 18 Jun 2010 15:12:04 -0700
changeset 573
005bec70ca27
parent 554
9d9f26857129
parent 571
f0e3ec1f9d9f
child 591
d1d7595fa824
permissions
-rw-r--r--

Merge

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

mercurial