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

Tue, 20 Aug 2013 12:15:19 -0700

author
darcy
date
Tue, 20 Aug 2013 12:15:19 -0700
changeset 1961
58da1296c6b3
parent 1825
e701af23a095
child 1982
662a5188bded
permissions
-rw-r--r--

8011043: Warn about use of 1.5 and earlier source and target values
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2013, 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.*;
    29 import java.util.HashMap;
    30 import java.util.HashSet;
    31 import java.util.LinkedHashMap;
    32 import java.util.LinkedHashSet;
    33 import java.util.Map;
    34 import java.util.MissingResourceException;
    35 import java.util.Queue;
    36 import java.util.ResourceBundle;
    37 import java.util.Set;
    38 import java.util.logging.Handler;
    39 import java.util.logging.Level;
    40 import java.util.logging.Logger;
    42 import javax.annotation.processing.Processor;
    43 import javax.lang.model.SourceVersion;
    44 import javax.tools.DiagnosticListener;
    45 import javax.tools.JavaFileManager;
    46 import javax.tools.JavaFileObject;
    47 import javax.tools.StandardLocation;
    49 import static javax.tools.StandardLocation.CLASS_OUTPUT;
    51 import com.sun.source.util.TaskEvent;
    52 import com.sun.tools.javac.api.MultiTaskListener;
    53 import com.sun.tools.javac.code.*;
    54 import com.sun.tools.javac.code.Lint.LintCategory;
    55 import com.sun.tools.javac.code.Symbol.*;
    56 import com.sun.tools.javac.comp.*;
    57 import com.sun.tools.javac.comp.CompileStates.CompileState;
    58 import com.sun.tools.javac.file.JavacFileManager;
    59 import com.sun.tools.javac.jvm.*;
    60 import com.sun.tools.javac.parser.*;
    61 import com.sun.tools.javac.processing.*;
    62 import com.sun.tools.javac.tree.*;
    63 import com.sun.tools.javac.tree.JCTree.*;
    64 import com.sun.tools.javac.util.*;
    65 import com.sun.tools.javac.util.Log.WriterKind;
    67 import static com.sun.tools.javac.code.TypeTag.CLASS;
    68 import static com.sun.tools.javac.main.Option.*;
    69 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    70 import static com.sun.tools.javac.util.ListBuffer.lb;
    73 /** This class could be the main entry point for GJC when GJC is used as a
    74  *  component in a larger software system. It provides operations to
    75  *  construct a new compiler, and to run a new compiler on a set of source
    76  *  files.
    77  *
    78  *  <p><b>This is NOT part of any supported API.
    79  *  If you write code that depends on this, you do so at your own risk.
    80  *  This code and its internal interfaces are subject to change or
    81  *  deletion without notice.</b>
    82  */
    83 public class JavaCompiler implements ClassReader.SourceCompleter {
    84     /** The context key for the compiler. */
    85     protected static final Context.Key<JavaCompiler> compilerKey =
    86         new Context.Key<JavaCompiler>();
    88     /** Get the JavaCompiler instance for this context. */
    89     public static JavaCompiler instance(Context context) {
    90         JavaCompiler instance = context.get(compilerKey);
    91         if (instance == null)
    92             instance = new JavaCompiler(context);
    93         return instance;
    94     }
    96     /** The current version number as a string.
    97      */
    98     public static String version() {
    99         return version("release");  // mm.nn.oo[-milestone]
   100     }
   102     /** The current full version number as a string.
   103      */
   104     public static String fullVersion() {
   105         return version("full"); // mm.mm.oo[-milestone]-build
   106     }
   108     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   109     private static ResourceBundle versionRB;
   111     private static String version(String key) {
   112         if (versionRB == null) {
   113             try {
   114                 versionRB = ResourceBundle.getBundle(versionRBName);
   115             } catch (MissingResourceException e) {
   116                 return Log.getLocalizedString("version.not.available");
   117             }
   118         }
   119         try {
   120             return versionRB.getString(key);
   121         }
   122         catch (MissingResourceException e) {
   123             return Log.getLocalizedString("version.not.available");
   124         }
   125     }
   127     /**
   128      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   129      * are connected. Each individual file is processed by each phase in turn,
   130      * but with different compile policies, you can control the order in which
   131      * each class is processed through its next phase.
   132      *
   133      * <p>Generally speaking, the compiler will "fail fast" in the face of
   134      * errors, although not aggressively so. flow, desugar, etc become no-ops
   135      * once any errors have occurred. No attempt is currently made to determine
   136      * if it might be safe to process a class through its next phase because
   137      * it does not depend on any unrelated errors that might have occurred.
   138      */
   139     protected static enum CompilePolicy {
   140         /**
   141          * Just attribute the parse trees.
   142          */
   143         ATTR_ONLY,
   145         /**
   146          * Just attribute and do flow analysis on the parse trees.
   147          * This should catch most user errors.
   148          */
   149         CHECK_ONLY,
   151         /**
   152          * Attribute everything, then do flow analysis for everything,
   153          * then desugar everything, and only then generate output.
   154          * This means no output will be generated if there are any
   155          * errors in any classes.
   156          */
   157         SIMPLE,
   159         /**
   160          * Groups the classes for each source file together, then process
   161          * each group in a manner equivalent to the {@code SIMPLE} policy.
   162          * This means no output will be generated if there are any
   163          * errors in any of the classes in a source file.
   164          */
   165         BY_FILE,
   167         /**
   168          * Completely process each entry on the todo list in turn.
   169          * -- this is the same for 1.5.
   170          * Means output might be generated for some classes in a compilation unit
   171          * and not others.
   172          */
   173         BY_TODO;
   175         static CompilePolicy decode(String option) {
   176             if (option == null)
   177                 return DEFAULT_COMPILE_POLICY;
   178             else if (option.equals("attr"))
   179                 return ATTR_ONLY;
   180             else if (option.equals("check"))
   181                 return CHECK_ONLY;
   182             else if (option.equals("simple"))
   183                 return SIMPLE;
   184             else if (option.equals("byfile"))
   185                 return BY_FILE;
   186             else if (option.equals("bytodo"))
   187                 return BY_TODO;
   188             else
   189                 return DEFAULT_COMPILE_POLICY;
   190         }
   191     }
   193     private static final CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   195     protected static enum ImplicitSourcePolicy {
   196         /** Don't generate or process implicitly read source files. */
   197         NONE,
   198         /** Generate classes for implicitly read source files. */
   199         CLASS,
   200         /** Like CLASS, but generate warnings if annotation processing occurs */
   201         UNSET;
   203         static ImplicitSourcePolicy decode(String option) {
   204             if (option == null)
   205                 return UNSET;
   206             else if (option.equals("none"))
   207                 return NONE;
   208             else if (option.equals("class"))
   209                 return CLASS;
   210             else
   211                 return UNSET;
   212         }
   213     }
   215     /** The log to be used for error reporting.
   216      */
   217     public Log log;
   219     /** Factory for creating diagnostic objects
   220      */
   221     JCDiagnostic.Factory diagFactory;
   223     /** The tree factory module.
   224      */
   225     protected TreeMaker make;
   227     /** The class reader.
   228      */
   229     protected ClassReader reader;
   231     /** The class writer.
   232      */
   233     protected ClassWriter writer;
   235     /** The native header writer.
   236      */
   237     protected JNIWriter jniWriter;
   239     /** The module for the symbol table entry phases.
   240      */
   241     protected Enter enter;
   243     /** The symbol table.
   244      */
   245     protected Symtab syms;
   247     /** The language version.
   248      */
   249     protected Source source;
   251     /** The module for code generation.
   252      */
   253     protected Gen gen;
   255     /** The name table.
   256      */
   257     protected Names names;
   259     /** The attributor.
   260      */
   261     protected Attr attr;
   263     /** The attributor.
   264      */
   265     protected Check chk;
   267     /** The flow analyzer.
   268      */
   269     protected Flow flow;
   271     /** The type eraser.
   272      */
   273     protected TransTypes transTypes;
   275     /** The lambda translator.
   276      */
   277     protected LambdaToMethod lambdaToMethod;
   279     /** The syntactic sugar desweetener.
   280      */
   281     protected Lower lower;
   283     /** The annotation annotator.
   284      */
   285     protected Annotate annotate;
   287     /** Force a completion failure on this name
   288      */
   289     protected final Name completionFailureName;
   291     /** Type utilities.
   292      */
   293     protected Types types;
   295     /** Access to file objects.
   296      */
   297     protected JavaFileManager fileManager;
   299     /** Factory for parsers.
   300      */
   301     protected ParserFactory parserFactory;
   303     /** Broadcasting listener for progress events
   304      */
   305     protected MultiTaskListener taskListener;
   307     /**
   308      * Annotation processing may require and provide a new instance
   309      * of the compiler to be used for the analyze and generate phases.
   310      */
   311     protected JavaCompiler delegateCompiler;
   313     /**
   314      * Command line options.
   315      */
   316     protected Options options;
   318     protected Context context;
   320     /**
   321      * Flag set if any annotation processing occurred.
   322      **/
   323     protected boolean annotationProcessingOccurred;
   325     /**
   326      * Flag set if any implicit source files read.
   327      **/
   328     protected boolean implicitSourceFilesRead;
   330     protected CompileStates compileStates;
   332     /** Construct a new compiler using a shared context.
   333      */
   334     public JavaCompiler(Context context) {
   335         this.context = context;
   336         context.put(compilerKey, this);
   338         // if fileManager not already set, register the JavacFileManager to be used
   339         if (context.get(JavaFileManager.class) == null)
   340             JavacFileManager.preRegister(context);
   342         names = Names.instance(context);
   343         log = Log.instance(context);
   344         diagFactory = JCDiagnostic.Factory.instance(context);
   345         reader = ClassReader.instance(context);
   346         make = TreeMaker.instance(context);
   347         writer = ClassWriter.instance(context);
   348         jniWriter = JNIWriter.instance(context);
   349         enter = Enter.instance(context);
   350         todo = Todo.instance(context);
   352         fileManager = context.get(JavaFileManager.class);
   353         parserFactory = ParserFactory.instance(context);
   354         compileStates = CompileStates.instance(context);
   356         try {
   357             // catch completion problems with predefineds
   358             syms = Symtab.instance(context);
   359         } catch (CompletionFailure ex) {
   360             // inlined Check.completionError as it is not initialized yet
   361             log.error("cant.access", ex.sym, ex.getDetailValue());
   362             if (ex instanceof ClassReader.BadClassFile)
   363                 throw new Abort();
   364         }
   365         source = Source.instance(context);
   366         Target target = Target.instance(context);
   367         attr = Attr.instance(context);
   368         chk = Check.instance(context);
   369         gen = Gen.instance(context);
   370         flow = Flow.instance(context);
   371         transTypes = TransTypes.instance(context);
   372         lower = Lower.instance(context);
   373         annotate = Annotate.instance(context);
   374         types = Types.instance(context);
   375         taskListener = MultiTaskListener.instance(context);
   377         reader.sourceCompleter = this;
   379         options = Options.instance(context);
   381         lambdaToMethod = LambdaToMethod.instance(context);
   383         verbose       = options.isSet(VERBOSE);
   384         sourceOutput  = options.isSet(PRINTSOURCE); // used to be -s
   385         stubOutput    = options.isSet("-stubs");
   386         relax         = options.isSet("-relax");
   387         printFlat     = options.isSet("-printflat");
   388         attrParseOnly = options.isSet("-attrparseonly");
   389         encoding      = options.get(ENCODING);
   390         lineDebugInfo = options.isUnset(G_CUSTOM) ||
   391                         options.isSet(G_CUSTOM, "lines");
   392         genEndPos     = options.isSet(XJCOV) ||
   393                         context.get(DiagnosticListener.class) != null;
   394         devVerbose    = options.isSet("dev");
   395         processPcks   = options.isSet("process.packages");
   396         werror        = options.isSet(WERROR);
   398         if (source.compareTo(Source.DEFAULT) < 0) {
   399             if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   400                 if (fileManager instanceof BaseFileManager) {
   401                     if (((BaseFileManager) fileManager).isDefaultBootClassPath())
   402                         log.warning(LintCategory.OPTIONS, "source.no.bootclasspath", source.name);
   403                 }
   404             }
   405         }
   407         checkForObsoleteOptions(target);
   409         verboseCompilePolicy = options.isSet("verboseCompilePolicy");
   411         if (attrParseOnly)
   412             compilePolicy = CompilePolicy.ATTR_ONLY;
   413         else
   414             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   416         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   418         completionFailureName =
   419             options.isSet("failcomplete")
   420             ? names.fromString(options.get("failcomplete"))
   421             : null;
   423         shouldStopPolicyIfError =
   424             options.isSet("shouldStopPolicy") // backwards compatible
   425             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   426             : options.isSet("shouldStopPolicyIfError")
   427             ? CompileState.valueOf(options.get("shouldStopPolicyIfError"))
   428             : CompileState.INIT;
   429         shouldStopPolicyIfNoError =
   430             options.isSet("shouldStopPolicyIfNoError")
   431             ? CompileState.valueOf(options.get("shouldStopPolicyIfNoError"))
   432             : CompileState.GENERATE;
   434         if (options.isUnset("oldDiags"))
   435             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   436     }
   438     private void checkForObsoleteOptions(Target target) {
   439         // Unless lint checking on options is disabled, check for
   440         // obsolete source and target options.
   441         boolean obsoleteOptionFound = false;
   442         if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   443             if (source.compareTo(Source.JDK1_5) <= 0) {
   444                 log.warning(LintCategory.OPTIONS, "option.obsolete.source", source.name);
   445                 obsoleteOptionFound = true;
   446             }
   448             if (target.compareTo(Target.JDK1_5) <= 0) {
   449                 log.warning(LintCategory.OPTIONS, "option.obsolete.target", source.name);
   450                 obsoleteOptionFound = true;
   451             }
   453             if (obsoleteOptionFound)
   454                 log.warning(LintCategory.OPTIONS, "option.obsolete.suppression");
   455         }
   456     }
   458     /* Switches:
   459      */
   461     /** Verbose output.
   462      */
   463     public boolean verbose;
   465     /** Emit plain Java source files rather than class files.
   466      */
   467     public boolean sourceOutput;
   469     /** Emit stub source files rather than class files.
   470      */
   471     public boolean stubOutput;
   473     /** Generate attributed parse tree only.
   474      */
   475     public boolean attrParseOnly;
   477     /** Switch: relax some constraints for producing the jsr14 prototype.
   478      */
   479     boolean relax;
   481     /** Debug switch: Emit Java sources after inner class flattening.
   482      */
   483     public boolean printFlat;
   485     /** The encoding to be used for source input.
   486      */
   487     public String encoding;
   489     /** Generate code with the LineNumberTable attribute for debugging
   490      */
   491     public boolean lineDebugInfo;
   493     /** Switch: should we store the ending positions?
   494      */
   495     public boolean genEndPos;
   497     /** Switch: should we debug ignored exceptions
   498      */
   499     protected boolean devVerbose;
   501     /** Switch: should we (annotation) process packages as well
   502      */
   503     protected boolean processPcks;
   505     /** Switch: treat warnings as errors
   506      */
   507     protected boolean werror;
   509     /** Switch: is annotation processing requested explicitly via
   510      * CompilationTask.setProcessors?
   511      */
   512     protected boolean explicitAnnotationProcessingRequested = false;
   514     /**
   515      * The policy for the order in which to perform the compilation
   516      */
   517     protected CompilePolicy compilePolicy;
   519     /**
   520      * The policy for what to do with implicitly read source files
   521      */
   522     protected ImplicitSourcePolicy implicitSourcePolicy;
   524     /**
   525      * Report activity related to compilePolicy
   526      */
   527     public boolean verboseCompilePolicy;
   529     /**
   530      * Policy of how far to continue compilation after errors have occurred.
   531      * Set this to minimum CompileState (INIT) to stop as soon as possible
   532      * after errors.
   533      */
   534     public CompileState shouldStopPolicyIfError;
   536     /**
   537      * Policy of how far to continue compilation when no errors have occurred.
   538      * Set this to maximum CompileState (GENERATE) to perform full compilation.
   539      * Set this lower to perform partial compilation, such as -proc:only.
   540      */
   541     public CompileState shouldStopPolicyIfNoError;
   543     /** A queue of all as yet unattributed classes.
   544      */
   545     public Todo todo;
   547     /** A list of items to be closed when the compilation is complete.
   548      */
   549     public List<Closeable> closeables = List.nil();
   551     /** The set of currently compiled inputfiles, needed to ensure
   552      *  we don't accidentally overwrite an input file when -s is set.
   553      *  initialized by `compile'.
   554      */
   555     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   557     protected boolean shouldStop(CompileState cs) {
   558         CompileState shouldStopPolicy = (errorCount() > 0 || unrecoverableError())
   559             ? shouldStopPolicyIfError
   560             : shouldStopPolicyIfNoError;
   561         return cs.isAfter(shouldStopPolicy);
   562     }
   564     /** The number of errors reported so far.
   565      */
   566     public int errorCount() {
   567         if (delegateCompiler != null && delegateCompiler != this)
   568             return delegateCompiler.errorCount();
   569         else {
   570             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   571                 log.error("warnings.and.werror");
   572             }
   573         }
   574         return log.nerrors;
   575     }
   577     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   578         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   579     }
   581     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   582         return shouldStop(cs) ? List.<T>nil() : list;
   583     }
   585     /** The number of warnings reported so far.
   586      */
   587     public int warningCount() {
   588         if (delegateCompiler != null && delegateCompiler != this)
   589             return delegateCompiler.warningCount();
   590         else
   591             return log.nwarnings;
   592     }
   594     /** Try to open input stream with given name.
   595      *  Report an error if this fails.
   596      *  @param filename   The file name of the input stream to be opened.
   597      */
   598     public CharSequence readSource(JavaFileObject filename) {
   599         try {
   600             inputFiles.add(filename);
   601             return filename.getCharContent(false);
   602         } catch (IOException e) {
   603             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   604             return null;
   605         }
   606     }
   608     /** Parse contents of input stream.
   609      *  @param filename     The name of the file from which input stream comes.
   610      *  @param content      The characters to be parsed.
   611      */
   612     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   613         long msec = now();
   614         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   615                                       null, List.<JCTree>nil());
   616         if (content != null) {
   617             if (verbose) {
   618                 log.printVerbose("parsing.started", filename);
   619             }
   620             if (!taskListener.isEmpty()) {
   621                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   622                 taskListener.started(e);
   623                 keepComments = true;
   624                 genEndPos = true;
   625             }
   626             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   627             tree = parser.parseCompilationUnit();
   628             if (verbose) {
   629                 log.printVerbose("parsing.done", Long.toString(elapsed(msec)));
   630             }
   631         }
   633         tree.sourcefile = filename;
   635         if (content != null && !taskListener.isEmpty()) {
   636             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   637             taskListener.finished(e);
   638         }
   640         return tree;
   641     }
   642     // where
   643         public boolean keepComments = false;
   644         protected boolean keepComments() {
   645             return keepComments || sourceOutput || stubOutput;
   646         }
   649     /** Parse contents of file.
   650      *  @param filename     The name of the file to be parsed.
   651      */
   652     @Deprecated
   653     public JCTree.JCCompilationUnit parse(String filename) {
   654         JavacFileManager fm = (JavacFileManager)fileManager;
   655         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   656     }
   658     /** Parse contents of file.
   659      *  @param filename     The name of the file to be parsed.
   660      */
   661     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   662         JavaFileObject prev = log.useSource(filename);
   663         try {
   664             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   665             if (t.endPositions != null)
   666                 log.setEndPosTable(filename, t.endPositions);
   667             return t;
   668         } finally {
   669             log.useSource(prev);
   670         }
   671     }
   673     /** Resolve an identifier which may be the binary name of a class or
   674      * the Java name of a class or package.
   675      * @param name      The name to resolve
   676      */
   677     public Symbol resolveBinaryNameOrIdent(String name) {
   678         try {
   679             Name flatname = names.fromString(name.replace("/", "."));
   680             return reader.loadClass(flatname);
   681         } catch (CompletionFailure ignore) {
   682             return resolveIdent(name);
   683         }
   684     }
   686     /** Resolve an identifier.
   687      * @param name      The identifier to resolve
   688      */
   689     public Symbol resolveIdent(String name) {
   690         if (name.equals(""))
   691             return syms.errSymbol;
   692         JavaFileObject prev = log.useSource(null);
   693         try {
   694             JCExpression tree = null;
   695             for (String s : name.split("\\.", -1)) {
   696                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   697                     return syms.errSymbol;
   698                 tree = (tree == null) ? make.Ident(names.fromString(s))
   699                                       : make.Select(tree, names.fromString(s));
   700             }
   701             JCCompilationUnit toplevel =
   702                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   703             toplevel.packge = syms.unnamedPackage;
   704             return attr.attribIdent(tree, toplevel);
   705         } finally {
   706             log.useSource(prev);
   707         }
   708     }
   710     /** Emit plain Java source for a class.
   711      *  @param env    The attribution environment of the outermost class
   712      *                containing this class.
   713      *  @param cdef   The class definition to be printed.
   714      */
   715     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   716         JavaFileObject outFile
   717             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   718                                                cdef.sym.flatname.toString(),
   719                                                JavaFileObject.Kind.SOURCE,
   720                                                null);
   721         if (inputFiles.contains(outFile)) {
   722             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   723             return null;
   724         } else {
   725             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   726             try {
   727                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   728                 if (verbose)
   729                     log.printVerbose("wrote.file", outFile);
   730             } finally {
   731                 out.close();
   732             }
   733             return outFile;
   734         }
   735     }
   737     /** Generate code and emit a class file for a given class
   738      *  @param env    The attribution environment of the outermost class
   739      *                containing this class.
   740      *  @param cdef   The class definition from which code is generated.
   741      */
   742     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   743         try {
   744             if (gen.genClass(env, cdef) && (errorCount() == 0))
   745                 return writer.writeClass(cdef.sym);
   746         } catch (ClassWriter.PoolOverflow ex) {
   747             log.error(cdef.pos(), "limit.pool");
   748         } catch (ClassWriter.StringOverflow ex) {
   749             log.error(cdef.pos(), "limit.string.overflow",
   750                       ex.value.substring(0, 20));
   751         } catch (CompletionFailure ex) {
   752             chk.completionError(cdef.pos(), ex);
   753         }
   754         return null;
   755     }
   757     /** Complete compiling a source file that has been accessed
   758      *  by the class file reader.
   759      *  @param c          The class the source file of which needs to be compiled.
   760      */
   761     public void complete(ClassSymbol c) throws CompletionFailure {
   762 //      System.err.println("completing " + c);//DEBUG
   763         if (completionFailureName == c.fullname) {
   764             throw new CompletionFailure(c, "user-selected completion failure by class name");
   765         }
   766         JCCompilationUnit tree;
   767         JavaFileObject filename = c.classfile;
   768         JavaFileObject prev = log.useSource(filename);
   770         try {
   771             tree = parse(filename, filename.getCharContent(false));
   772         } catch (IOException e) {
   773             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   774             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   775         } finally {
   776             log.useSource(prev);
   777         }
   779         if (!taskListener.isEmpty()) {
   780             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   781             taskListener.started(e);
   782         }
   784         enter.complete(List.of(tree), c);
   786         if (!taskListener.isEmpty()) {
   787             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   788             taskListener.finished(e);
   789         }
   791         if (enter.getEnv(c) == null) {
   792             boolean isPkgInfo =
   793                 tree.sourcefile.isNameCompatible("package-info",
   794                                                  JavaFileObject.Kind.SOURCE);
   795             if (isPkgInfo) {
   796                 if (enter.getEnv(tree.packge) == null) {
   797                     JCDiagnostic diag =
   798                         diagFactory.fragment("file.does.not.contain.package",
   799                                                  c.location());
   800                     throw reader.new BadClassFile(c, filename, diag);
   801                 }
   802             } else {
   803                 JCDiagnostic diag =
   804                         diagFactory.fragment("file.doesnt.contain.class",
   805                                             c.getQualifiedName());
   806                 throw reader.new BadClassFile(c, filename, diag);
   807             }
   808         }
   810         implicitSourceFilesRead = true;
   811     }
   813     /** Track when the JavaCompiler has been used to compile something. */
   814     private boolean hasBeenUsed = false;
   815     private long start_msec = 0;
   816     public long elapsed_msec = 0;
   818     public void compile(List<JavaFileObject> sourceFileObject)
   819         throws Throwable {
   820         compile(sourceFileObject, List.<String>nil(), null);
   821     }
   823     /**
   824      * Main method: compile a list of files, return all compiled classes
   825      *
   826      * @param sourceFileObjects file objects to be compiled
   827      * @param classnames class names to process for annotations
   828      * @param processors user provided annotation processors to bypass
   829      * discovery, {@code null} means that no processors were provided
   830      */
   831     public void compile(List<JavaFileObject> sourceFileObjects,
   832                         List<String> classnames,
   833                         Iterable<? extends Processor> processors)
   834     {
   835         if (processors != null && processors.iterator().hasNext())
   836             explicitAnnotationProcessingRequested = true;
   837         // as a JavaCompiler can only be used once, throw an exception if
   838         // it has been used before.
   839         if (hasBeenUsed)
   840             throw new AssertionError("attempt to reuse JavaCompiler");
   841         hasBeenUsed = true;
   843         // forcibly set the equivalent of -Xlint:-options, so that no further
   844         // warnings about command line options are generated from this point on
   845         options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
   846         options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);
   848         start_msec = now();
   850         try {
   851             initProcessAnnotations(processors);
   853             // These method calls must be chained to avoid memory leaks
   854             delegateCompiler =
   855                 processAnnotations(
   856                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   857                     classnames);
   859             delegateCompiler.compile2();
   860             delegateCompiler.close();
   861             elapsed_msec = delegateCompiler.elapsed_msec;
   862         } catch (Abort ex) {
   863             if (devVerbose)
   864                 ex.printStackTrace(System.err);
   865         } finally {
   866             if (procEnvImpl != null)
   867                 procEnvImpl.close();
   868         }
   869     }
   871     /**
   872      * The phases following annotation processing: attribution,
   873      * desugar, and finally code generation.
   874      */
   875     private void compile2() {
   876         try {
   877             switch (compilePolicy) {
   878             case ATTR_ONLY:
   879                 attribute(todo);
   880                 break;
   882             case CHECK_ONLY:
   883                 flow(attribute(todo));
   884                 break;
   886             case SIMPLE:
   887                 generate(desugar(flow(attribute(todo))));
   888                 break;
   890             case BY_FILE: {
   891                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   892                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   893                         generate(desugar(flow(attribute(q.remove()))));
   894                     }
   895                 }
   896                 break;
   898             case BY_TODO:
   899                 while (!todo.isEmpty())
   900                     generate(desugar(flow(attribute(todo.remove()))));
   901                 break;
   903             default:
   904                 Assert.error("unknown compile policy");
   905             }
   906         } catch (Abort ex) {
   907             if (devVerbose)
   908                 ex.printStackTrace(System.err);
   909         }
   911         if (verbose) {
   912             elapsed_msec = elapsed(start_msec);
   913             log.printVerbose("total", Long.toString(elapsed_msec));
   914         }
   916         reportDeferredDiagnostics();
   918         if (!log.hasDiagnosticListener()) {
   919             printCount("error", errorCount());
   920             printCount("warn", warningCount());
   921         }
   922     }
   924     /**
   925      * Set needRootClasses to true, in JavaCompiler subclass constructor
   926      * that want to collect public apis of classes supplied on the command line.
   927      */
   928     protected boolean needRootClasses = false;
   930     /**
   931      * The list of classes explicitly supplied on the command line for compilation.
   932      * Not always populated.
   933      */
   934     private List<JCClassDecl> rootClasses;
   936     /**
   937      * Parses a list of files.
   938      */
   939    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   940        if (shouldStop(CompileState.PARSE))
   941            return List.nil();
   943         //parse all files
   944         ListBuffer<JCCompilationUnit> trees = lb();
   945         Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
   946         for (JavaFileObject fileObject : fileObjects) {
   947             if (!filesSoFar.contains(fileObject)) {
   948                 filesSoFar.add(fileObject);
   949                 trees.append(parse(fileObject));
   950             }
   951         }
   952         return trees.toList();
   953     }
   955     /**
   956      * Enter the symbols found in a list of parse trees if the compilation
   957      * is expected to proceed beyond anno processing into attr.
   958      * As a side-effect, this puts elements on the "todo" list.
   959      * Also stores a list of all top level classes in rootClasses.
   960      */
   961     public List<JCCompilationUnit> enterTreesIfNeeded(List<JCCompilationUnit> roots) {
   962        if (shouldStop(CompileState.ATTR))
   963            return List.nil();
   964         return enterTrees(roots);
   965     }
   967     /**
   968      * Enter the symbols found in a list of parse trees.
   969      * As a side-effect, this puts elements on the "todo" list.
   970      * Also stores a list of all top level classes in rootClasses.
   971      */
   972     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   973         //enter symbols for all files
   974         if (!taskListener.isEmpty()) {
   975             for (JCCompilationUnit unit: roots) {
   976                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   977                 taskListener.started(e);
   978             }
   979         }
   981         enter.main(roots);
   983         if (!taskListener.isEmpty()) {
   984             for (JCCompilationUnit unit: roots) {
   985                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   986                 taskListener.finished(e);
   987             }
   988         }
   990         // If generating source, or if tracking public apis,
   991         // then remember the classes declared in
   992         // the original compilation units listed on the command line.
   993         if (needRootClasses || sourceOutput || stubOutput) {
   994             ListBuffer<JCClassDecl> cdefs = lb();
   995             for (JCCompilationUnit unit : roots) {
   996                 for (List<JCTree> defs = unit.defs;
   997                      defs.nonEmpty();
   998                      defs = defs.tail) {
   999                     if (defs.head instanceof JCClassDecl)
  1000                         cdefs.append((JCClassDecl)defs.head);
  1003             rootClasses = cdefs.toList();
  1006         // Ensure the input files have been recorded. Although this is normally
  1007         // done by readSource, it may not have been done if the trees were read
  1008         // in a prior round of annotation processing, and the trees have been
  1009         // cleaned and are being reused.
  1010         for (JCCompilationUnit unit : roots) {
  1011             inputFiles.add(unit.sourcefile);
  1014         return roots;
  1017     /**
  1018      * Set to true to enable skeleton annotation processing code.
  1019      * Currently, we assume this variable will be replaced more
  1020      * advanced logic to figure out if annotation processing is
  1021      * needed.
  1022      */
  1023     boolean processAnnotations = false;
  1025     Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
  1027     /**
  1028      * Object to handle annotation processing.
  1029      */
  1030     private JavacProcessingEnvironment procEnvImpl = null;
  1032     /**
  1033      * Check if we should process annotations.
  1034      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
  1035      * to catch doc comments, and set keepComments so the parser records them in
  1036      * the compilation unit.
  1038      * @param processors user provided annotation processors to bypass
  1039      * discovery, {@code null} means that no processors were provided
  1040      */
  1041     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
  1042         // Process annotations if processing is not disabled and there
  1043         // is at least one Processor available.
  1044         if (options.isSet(PROC, "none")) {
  1045             processAnnotations = false;
  1046         } else if (procEnvImpl == null) {
  1047             procEnvImpl = JavacProcessingEnvironment.instance(context);
  1048             procEnvImpl.setProcessors(processors);
  1049             processAnnotations = procEnvImpl.atLeastOneProcessor();
  1051             if (processAnnotations) {
  1052                 options.put("save-parameter-names", "save-parameter-names");
  1053                 reader.saveParameterNames = true;
  1054                 keepComments = true;
  1055                 genEndPos = true;
  1056                 if (!taskListener.isEmpty())
  1057                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1058                 deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
  1059             } else { // free resources
  1060                 procEnvImpl.close();
  1065     // TODO: called by JavacTaskImpl
  1066     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
  1067         return processAnnotations(roots, List.<String>nil());
  1070     /**
  1071      * Process any annotations found in the specified compilation units.
  1072      * @param roots a list of compilation units
  1073      * @return an instance of the compiler in which to complete the compilation
  1074      */
  1075     // Implementation note: when this method is called, log.deferredDiagnostics
  1076     // will have been set true by initProcessAnnotations, meaning that any diagnostics
  1077     // that are reported will go into the log.deferredDiagnostics queue.
  1078     // By the time this method exits, log.deferDiagnostics must be set back to false,
  1079     // and all deferredDiagnostics must have been handled: i.e. either reported
  1080     // or determined to be transient, and therefore suppressed.
  1081     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
  1082                                            List<String> classnames) {
  1083         if (shouldStop(CompileState.PROCESS)) {
  1084             // Errors were encountered.
  1085             // Unless all the errors are resolve errors, the errors were parse errors
  1086             // or other errors during enter which cannot be fixed by running
  1087             // any annotation processors.
  1088             if (unrecoverableError()) {
  1089                 deferredDiagnosticHandler.reportDeferredDiagnostics();
  1090                 log.popDiagnosticHandler(deferredDiagnosticHandler);
  1091                 return this;
  1095         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1096         // by initProcessAnnotations
  1098         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1100         if (!processAnnotations) {
  1101             // If there are no annotation processors present, and
  1102             // annotation processing is to occur with compilation,
  1103             // emit a warning.
  1104             if (options.isSet(PROC, "only")) {
  1105                 log.warning("proc.proc-only.requested.no.procs");
  1106                 todo.clear();
  1108             // If not processing annotations, classnames must be empty
  1109             if (!classnames.isEmpty()) {
  1110                 log.error("proc.no.explicit.annotation.processing.requested",
  1111                           classnames);
  1113             Assert.checkNull(deferredDiagnosticHandler);
  1114             return this; // continue regular compilation
  1117         Assert.checkNonNull(deferredDiagnosticHandler);
  1119         try {
  1120             List<ClassSymbol> classSymbols = List.nil();
  1121             List<PackageSymbol> pckSymbols = List.nil();
  1122             if (!classnames.isEmpty()) {
  1123                  // Check for explicit request for annotation
  1124                  // processing
  1125                 if (!explicitAnnotationProcessingRequested()) {
  1126                     log.error("proc.no.explicit.annotation.processing.requested",
  1127                               classnames);
  1128                     deferredDiagnosticHandler.reportDeferredDiagnostics();
  1129                     log.popDiagnosticHandler(deferredDiagnosticHandler);
  1130                     return this; // TODO: Will this halt compilation?
  1131                 } else {
  1132                     boolean errors = false;
  1133                     for (String nameStr : classnames) {
  1134                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
  1135                         if (sym == null ||
  1136                             (sym.kind == Kinds.PCK && !processPcks) ||
  1137                             sym.kind == Kinds.ABSENT_TYP) {
  1138                             log.error("proc.cant.find.class", nameStr);
  1139                             errors = true;
  1140                             continue;
  1142                         try {
  1143                             if (sym.kind == Kinds.PCK)
  1144                                 sym.complete();
  1145                             if (sym.exists()) {
  1146                                 if (sym.kind == Kinds.PCK)
  1147                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1148                                 else
  1149                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1150                                 continue;
  1152                             Assert.check(sym.kind == Kinds.PCK);
  1153                             log.warning("proc.package.does.not.exist", nameStr);
  1154                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1155                         } catch (CompletionFailure e) {
  1156                             log.error("proc.cant.find.class", nameStr);
  1157                             errors = true;
  1158                             continue;
  1161                     if (errors) {
  1162                         deferredDiagnosticHandler.reportDeferredDiagnostics();
  1163                         log.popDiagnosticHandler(deferredDiagnosticHandler);
  1164                         return this;
  1168             try {
  1169                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols,
  1170                         deferredDiagnosticHandler);
  1171                 if (c != this)
  1172                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1173                 // doProcessing will have handled deferred diagnostics
  1174                 return c;
  1175             } finally {
  1176                 procEnvImpl.close();
  1178         } catch (CompletionFailure ex) {
  1179             log.error("cant.access", ex.sym, ex.getDetailValue());
  1180             deferredDiagnosticHandler.reportDeferredDiagnostics();
  1181             log.popDiagnosticHandler(deferredDiagnosticHandler);
  1182             return this;
  1186     private boolean unrecoverableError() {
  1187         if (deferredDiagnosticHandler != null) {
  1188             for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
  1189                 if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
  1190                     return true;
  1193         return false;
  1196     boolean explicitAnnotationProcessingRequested() {
  1197         return
  1198             explicitAnnotationProcessingRequested ||
  1199             explicitAnnotationProcessingRequested(options);
  1202     static boolean explicitAnnotationProcessingRequested(Options options) {
  1203         return
  1204             options.isSet(PROCESSOR) ||
  1205             options.isSet(PROCESSORPATH) ||
  1206             options.isSet(PROC, "only") ||
  1207             options.isSet(XPRINT);
  1210     /**
  1211      * Attribute a list of parse trees, such as found on the "todo" list.
  1212      * Note that attributing classes may cause additional files to be
  1213      * parsed and entered via the SourceCompleter.
  1214      * Attribution of the entries in the list does not stop if any errors occur.
  1215      * @returns a list of environments for attributd classes.
  1216      */
  1217     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1218         ListBuffer<Env<AttrContext>> results = lb();
  1219         while (!envs.isEmpty())
  1220             results.append(attribute(envs.remove()));
  1221         return stopIfError(CompileState.ATTR, results);
  1224     /**
  1225      * Attribute a parse tree.
  1226      * @returns the attributed parse tree
  1227      */
  1228     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1229         if (compileStates.isDone(env, CompileState.ATTR))
  1230             return env;
  1232         if (verboseCompilePolicy)
  1233             printNote("[attribute " + env.enclClass.sym + "]");
  1234         if (verbose)
  1235             log.printVerbose("checking.attribution", env.enclClass.sym);
  1237         if (!taskListener.isEmpty()) {
  1238             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1239             taskListener.started(e);
  1242         JavaFileObject prev = log.useSource(
  1243                                   env.enclClass.sym.sourcefile != null ?
  1244                                   env.enclClass.sym.sourcefile :
  1245                                   env.toplevel.sourcefile);
  1246         try {
  1247             attr.attrib(env);
  1248             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1249                 //if in fail-over mode, ensure that AST expression nodes
  1250                 //are correctly initialized (e.g. they have a type/symbol)
  1251                 attr.postAttr(env.tree);
  1253             compileStates.put(env, CompileState.ATTR);
  1254             if (rootClasses != null && rootClasses.contains(env.enclClass)) {
  1255                 // This was a class that was explicitly supplied for compilation.
  1256                 // If we want to capture the public api of this class,
  1257                 // then now is a good time to do it.
  1258                 reportPublicApi(env.enclClass.sym);
  1261         finally {
  1262             log.useSource(prev);
  1265         return env;
  1268     /** Report the public api of a class that was supplied explicitly for compilation,
  1269      *  for example on the command line to javac.
  1270      * @param sym The symbol of the class.
  1271      */
  1272     public void reportPublicApi(ClassSymbol sym) {
  1273        // Override to collect the reported public api.
  1276     /**
  1277      * Perform dataflow checks on attributed parse trees.
  1278      * These include checks for definite assignment and unreachable statements.
  1279      * If any errors occur, an empty list will be returned.
  1280      * @returns the list of attributed parse trees
  1281      */
  1282     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1283         ListBuffer<Env<AttrContext>> results = lb();
  1284         for (Env<AttrContext> env: envs) {
  1285             flow(env, results);
  1287         return stopIfError(CompileState.FLOW, results);
  1290     /**
  1291      * Perform dataflow checks on an attributed parse tree.
  1292      */
  1293     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1294         ListBuffer<Env<AttrContext>> results = lb();
  1295         flow(env, results);
  1296         return stopIfError(CompileState.FLOW, results);
  1299     /**
  1300      * Perform dataflow checks on an attributed parse tree.
  1301      */
  1302     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1303         try {
  1304             if (shouldStop(CompileState.FLOW))
  1305                 return;
  1307             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1308                 results.add(env);
  1309                 return;
  1312             if (verboseCompilePolicy)
  1313                 printNote("[flow " + env.enclClass.sym + "]");
  1314             JavaFileObject prev = log.useSource(
  1315                                                 env.enclClass.sym.sourcefile != null ?
  1316                                                 env.enclClass.sym.sourcefile :
  1317                                                 env.toplevel.sourcefile);
  1318             try {
  1319                 make.at(Position.FIRSTPOS);
  1320                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1321                 flow.analyzeTree(env, localMake);
  1322                 compileStates.put(env, CompileState.FLOW);
  1324                 if (shouldStop(CompileState.FLOW))
  1325                     return;
  1327                 results.add(env);
  1329             finally {
  1330                 log.useSource(prev);
  1333         finally {
  1334             if (!taskListener.isEmpty()) {
  1335                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1336                 taskListener.finished(e);
  1341     /**
  1342      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1343      * for source or code generation.
  1344      * If any errors occur, an empty list will be returned.
  1345      * @returns a list containing the classes to be generated
  1346      */
  1347     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1348         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1349         for (Env<AttrContext> env: envs)
  1350             desugar(env, results);
  1351         return stopIfError(CompileState.FLOW, results);
  1354     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1355             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1357     /**
  1358      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1359      * for source or code generation. If the file was not listed on the command line,
  1360      * the current implicitSourcePolicy is taken into account.
  1361      * The preparation stops as soon as an error is found.
  1362      */
  1363     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1364         if (shouldStop(CompileState.TRANSTYPES))
  1365             return;
  1367         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1368                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1369             return;
  1372         if (compileStates.isDone(env, CompileState.LOWER)) {
  1373             results.addAll(desugaredEnvs.get(env));
  1374             return;
  1377         /**
  1378          * Ensure that superclasses of C are desugared before C itself. This is
  1379          * required for two reasons: (i) as erasure (TransTypes) destroys
  1380          * information needed in flow analysis and (ii) as some checks carried
  1381          * out during lowering require that all synthetic fields/methods have
  1382          * already been added to C and its superclasses.
  1383          */
  1384         class ScanNested extends TreeScanner {
  1385             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1386             @Override
  1387             public void visitClassDef(JCClassDecl node) {
  1388                 Type st = types.supertype(node.sym.type);
  1389                 boolean envForSuperTypeFound = false;
  1390                 while (!envForSuperTypeFound && st.hasTag(CLASS)) {
  1391                     ClassSymbol c = st.tsym.outermostClass();
  1392                     Env<AttrContext> stEnv = enter.getEnv(c);
  1393                     if (stEnv != null && env != stEnv) {
  1394                         if (dependencies.add(stEnv)) {
  1395                             scan(stEnv.tree);
  1397                         envForSuperTypeFound = true;
  1399                     st = types.supertype(st);
  1401                 super.visitClassDef(node);
  1404         ScanNested scanner = new ScanNested();
  1405         scanner.scan(env.tree);
  1406         for (Env<AttrContext> dep: scanner.dependencies) {
  1407         if (!compileStates.isDone(dep, CompileState.FLOW))
  1408             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1411         //We need to check for error another time as more classes might
  1412         //have been attributed and analyzed at this stage
  1413         if (shouldStop(CompileState.TRANSTYPES))
  1414             return;
  1416         if (verboseCompilePolicy)
  1417             printNote("[desugar " + env.enclClass.sym + "]");
  1419         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1420                                   env.enclClass.sym.sourcefile :
  1421                                   env.toplevel.sourcefile);
  1422         try {
  1423             //save tree prior to rewriting
  1424             JCTree untranslated = env.tree;
  1426             make.at(Position.FIRSTPOS);
  1427             TreeMaker localMake = make.forToplevel(env.toplevel);
  1429             if (env.tree instanceof JCCompilationUnit) {
  1430                 if (!(stubOutput || sourceOutput || printFlat)) {
  1431                     if (shouldStop(CompileState.LOWER))
  1432                         return;
  1433                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1434                     if (pdef.head != null) {
  1435                         Assert.check(pdef.tail.isEmpty());
  1436                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1439                 return;
  1442             if (stubOutput) {
  1443                 //emit stub Java source file, only for compilation
  1444                 //units enumerated explicitly on the command line
  1445                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1446                 if (untranslated instanceof JCClassDecl &&
  1447                     rootClasses.contains((JCClassDecl)untranslated) &&
  1448                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1449                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1450                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1452                 return;
  1455             if (shouldStop(CompileState.TRANSTYPES))
  1456                 return;
  1458             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1459             compileStates.put(env, CompileState.TRANSTYPES);
  1461             if (source.allowLambda()) {
  1462                 if (shouldStop(CompileState.UNLAMBDA))
  1463                     return;
  1465                 env.tree = lambdaToMethod.translateTopLevelClass(env, env.tree, localMake);
  1466                 compileStates.put(env, CompileState.UNLAMBDA);
  1469             if (shouldStop(CompileState.LOWER))
  1470                 return;
  1472             if (sourceOutput) {
  1473                 //emit standard Java source file, only for compilation
  1474                 //units enumerated explicitly on the command line
  1475                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1476                 if (untranslated instanceof JCClassDecl &&
  1477                     rootClasses.contains((JCClassDecl)untranslated)) {
  1478                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1480                 return;
  1483             //translate out inner classes
  1484             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1485             compileStates.put(env, CompileState.LOWER);
  1487             if (shouldStop(CompileState.LOWER))
  1488                 return;
  1490             //generate code for each class
  1491             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1492                 JCClassDecl cdef = (JCClassDecl)l.head;
  1493                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1496         finally {
  1497             log.useSource(prev);
  1502     /** Generates the source or class file for a list of classes.
  1503      * The decision to generate a source file or a class file is
  1504      * based upon the compiler's options.
  1505      * Generation stops if an error occurs while writing files.
  1506      */
  1507     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1508         generate(queue, null);
  1511     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1512         if (shouldStop(CompileState.GENERATE))
  1513             return;
  1515         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1517         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1518             Env<AttrContext> env = x.fst;
  1519             JCClassDecl cdef = x.snd;
  1521             if (verboseCompilePolicy) {
  1522                 printNote("[generate "
  1523                                + (usePrintSource ? " source" : "code")
  1524                                + " " + cdef.sym + "]");
  1527             if (!taskListener.isEmpty()) {
  1528                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1529                 taskListener.started(e);
  1532             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1533                                       env.enclClass.sym.sourcefile :
  1534                                       env.toplevel.sourcefile);
  1535             try {
  1536                 JavaFileObject file;
  1537                 if (usePrintSource)
  1538                     file = printSource(env, cdef);
  1539                 else {
  1540                     if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
  1541                             && jniWriter.needsHeader(cdef.sym)) {
  1542                         jniWriter.write(cdef.sym);
  1544                     file = genCode(env, cdef);
  1546                 if (results != null && file != null)
  1547                     results.add(file);
  1548             } catch (IOException ex) {
  1549                 log.error(cdef.pos(), "class.cant.write",
  1550                           cdef.sym, ex.getMessage());
  1551                 return;
  1552             } finally {
  1553                 log.useSource(prev);
  1556             if (!taskListener.isEmpty()) {
  1557                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1558                 taskListener.finished(e);
  1563         // where
  1564         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1565             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1566             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1567             for (Env<AttrContext> env: envs) {
  1568                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1569                 if (sublist == null) {
  1570                     sublist = new ListBuffer<Env<AttrContext>>();
  1571                     map.put(env.toplevel, sublist);
  1573                 sublist.add(env);
  1575             return map;
  1578         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1579             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1580             class MethodBodyRemover extends TreeTranslator {
  1581                 @Override
  1582                 public void visitMethodDef(JCMethodDecl tree) {
  1583                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1584                     for (JCVariableDecl vd : tree.params)
  1585                         vd.mods.flags &= ~Flags.FINAL;
  1586                     tree.body = null;
  1587                     super.visitMethodDef(tree);
  1589                 @Override
  1590                 public void visitVarDef(JCVariableDecl tree) {
  1591                     if (tree.init != null && tree.init.type.constValue() == null)
  1592                         tree.init = null;
  1593                     super.visitVarDef(tree);
  1595                 @Override
  1596                 public void visitClassDef(JCClassDecl tree) {
  1597                     ListBuffer<JCTree> newdefs = lb();
  1598                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1599                         JCTree t = it.head;
  1600                         switch (t.getTag()) {
  1601                         case CLASSDEF:
  1602                             if (isInterface ||
  1603                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1604                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1605                                 newdefs.append(t);
  1606                             break;
  1607                         case METHODDEF:
  1608                             if (isInterface ||
  1609                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1610                                 ((JCMethodDecl) t).sym.name == names.init ||
  1611                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1612                                 newdefs.append(t);
  1613                             break;
  1614                         case VARDEF:
  1615                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1616                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1617                                 newdefs.append(t);
  1618                             break;
  1619                         default:
  1620                             break;
  1623                     tree.defs = newdefs.toList();
  1624                     super.visitClassDef(tree);
  1627             MethodBodyRemover r = new MethodBodyRemover();
  1628             return r.translate(cdef);
  1631     public void reportDeferredDiagnostics() {
  1632         if (errorCount() == 0
  1633                 && annotationProcessingOccurred
  1634                 && implicitSourceFilesRead
  1635                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1636             if (explicitAnnotationProcessingRequested())
  1637                 log.warning("proc.use.implicit");
  1638             else
  1639                 log.warning("proc.use.proc.or.implicit");
  1641         chk.reportDeferredDiagnostics();
  1642         if (log.compressedOutput) {
  1643             log.mandatoryNote(null, "compressed.diags");
  1647     /** Close the compiler, flushing the logs
  1648      */
  1649     public void close() {
  1650         close(true);
  1653     public void close(boolean disposeNames) {
  1654         rootClasses = null;
  1655         reader = null;
  1656         make = null;
  1657         writer = null;
  1658         enter = null;
  1659         if (todo != null)
  1660             todo.clear();
  1661         todo = null;
  1662         parserFactory = null;
  1663         syms = null;
  1664         source = null;
  1665         attr = null;
  1666         chk = null;
  1667         gen = null;
  1668         flow = null;
  1669         transTypes = null;
  1670         lower = null;
  1671         annotate = null;
  1672         types = null;
  1674         log.flush();
  1675         try {
  1676             fileManager.flush();
  1677         } catch (IOException e) {
  1678             throw new Abort(e);
  1679         } finally {
  1680             if (names != null && disposeNames)
  1681                 names.dispose();
  1682             names = null;
  1684             for (Closeable c: closeables) {
  1685                 try {
  1686                     c.close();
  1687                 } catch (IOException e) {
  1688                     // When javac uses JDK 7 as a baseline, this code would be
  1689                     // better written to set any/all exceptions from all the
  1690                     // Closeables as suppressed exceptions on the FatalError
  1691                     // that is thrown.
  1692                     JCDiagnostic msg = diagFactory.fragment("fatal.err.cant.close");
  1693                     throw new FatalError(msg, e);
  1696             closeables = List.nil();
  1700     protected void printNote(String lines) {
  1701         log.printRawLines(Log.WriterKind.NOTICE, lines);
  1704     /** Print numbers of errors and warnings.
  1705      */
  1706     public void printCount(String kind, int count) {
  1707         if (count != 0) {
  1708             String key;
  1709             if (count == 1)
  1710                 key = "count." + kind;
  1711             else
  1712                 key = "count." + kind + ".plural";
  1713             log.printLines(WriterKind.ERROR, key, String.valueOf(count));
  1714             log.flush(Log.WriterKind.ERROR);
  1718     private static long now() {
  1719         return System.currentTimeMillis();
  1722     private static long elapsed(long then) {
  1723         return now() - then;
  1726     public void initRound(JavaCompiler prev) {
  1727         genEndPos = prev.genEndPos;
  1728         keepComments = prev.keepComments;
  1729         start_msec = prev.start_msec;
  1730         hasBeenUsed = true;
  1731         closeables = prev.closeables;
  1732         prev.closeables = List.nil();
  1733         shouldStopPolicyIfError = prev.shouldStopPolicyIfError;
  1734         shouldStopPolicyIfNoError = prev.shouldStopPolicyIfNoError;
  1737     public static void enableLogging() {
  1738         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1739         logger.setLevel(Level.ALL);
  1740         for (Handler h : logger.getParent().getHandlers()) {
  1741             h.setLevel(Level.ALL);

mercurial