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

Sun, 17 Feb 2013 16:44:55 -0500

author
dholmes
date
Sun, 17 Feb 2013 16:44:55 -0500
changeset 1571
af8417e590f4
parent 1539
0b1c88705568
child 1690
76537856a54e
permissions
-rw-r--r--

Merge

     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.file.JavacFileManager;
    58 import com.sun.tools.javac.jvm.*;
    59 import com.sun.tools.javac.parser.*;
    60 import com.sun.tools.javac.processing.*;
    61 import com.sun.tools.javac.tree.*;
    62 import com.sun.tools.javac.tree.JCTree.*;
    63 import com.sun.tools.javac.util.*;
    64 import com.sun.tools.javac.util.Log.WriterKind;
    66 import static com.sun.tools.javac.code.TypeTag.CLASS;
    67 import static com.sun.tools.javac.main.Option.*;
    68 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    69 import static com.sun.tools.javac.util.ListBuffer.lb;
    72 /** This class could be the main entry point for GJC when GJC is used as a
    73  *  component in a larger software system. It provides operations to
    74  *  construct a new compiler, and to run a new compiler on a set of source
    75  *  files.
    76  *
    77  *  <p><b>This is NOT part of any supported API.
    78  *  If you write code that depends on this, you do so at your own risk.
    79  *  This code and its internal interfaces are subject to change or
    80  *  deletion without notice.</b>
    81  */
    82 public class JavaCompiler implements ClassReader.SourceCompleter {
    83     /** The context key for the compiler. */
    84     protected static final Context.Key<JavaCompiler> compilerKey =
    85         new Context.Key<JavaCompiler>();
    87     /** Get the JavaCompiler instance for this context. */
    88     public static JavaCompiler instance(Context context) {
    89         JavaCompiler instance = context.get(compilerKey);
    90         if (instance == null)
    91             instance = new JavaCompiler(context);
    92         return instance;
    93     }
    95     /** The current version number as a string.
    96      */
    97     public static String version() {
    98         return version("release");  // mm.nn.oo[-milestone]
    99     }
   101     /** The current full version number as a string.
   102      */
   103     public static String fullVersion() {
   104         return version("full"); // mm.mm.oo[-milestone]-build
   105     }
   107     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   108     private static ResourceBundle versionRB;
   110     private static String version(String key) {
   111         if (versionRB == null) {
   112             try {
   113                 versionRB = ResourceBundle.getBundle(versionRBName);
   114             } catch (MissingResourceException e) {
   115                 return Log.getLocalizedString("version.not.available");
   116             }
   117         }
   118         try {
   119             return versionRB.getString(key);
   120         }
   121         catch (MissingResourceException e) {
   122             return Log.getLocalizedString("version.not.available");
   123         }
   124     }
   126     /**
   127      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   128      * are connected. Each individual file is processed by each phase in turn,
   129      * but with different compile policies, you can control the order in which
   130      * each class is processed through its next phase.
   131      *
   132      * <p>Generally speaking, the compiler will "fail fast" in the face of
   133      * errors, although not aggressively so. flow, desugar, etc become no-ops
   134      * once any errors have occurred. No attempt is currently made to determine
   135      * if it might be safe to process a class through its next phase because
   136      * it does not depend on any unrelated errors that might have occurred.
   137      */
   138     protected static enum CompilePolicy {
   139         /**
   140          * Just attribute the parse trees.
   141          */
   142         ATTR_ONLY,
   144         /**
   145          * Just attribute and do flow analysis on the parse trees.
   146          * This should catch most user errors.
   147          */
   148         CHECK_ONLY,
   150         /**
   151          * Attribute everything, then do flow analysis for everything,
   152          * then desugar everything, and only then generate output.
   153          * This means no output will be generated if there are any
   154          * errors in any classes.
   155          */
   156         SIMPLE,
   158         /**
   159          * Groups the classes for each source file together, then process
   160          * each group in a manner equivalent to the {@code SIMPLE} policy.
   161          * This means no output will be generated if there are any
   162          * errors in any of the classes in a source file.
   163          */
   164         BY_FILE,
   166         /**
   167          * Completely process each entry on the todo list in turn.
   168          * -- this is the same for 1.5.
   169          * Means output might be generated for some classes in a compilation unit
   170          * and not others.
   171          */
   172         BY_TODO;
   174         static CompilePolicy decode(String option) {
   175             if (option == null)
   176                 return DEFAULT_COMPILE_POLICY;
   177             else if (option.equals("attr"))
   178                 return ATTR_ONLY;
   179             else if (option.equals("check"))
   180                 return CHECK_ONLY;
   181             else if (option.equals("simple"))
   182                 return SIMPLE;
   183             else if (option.equals("byfile"))
   184                 return BY_FILE;
   185             else if (option.equals("bytodo"))
   186                 return BY_TODO;
   187             else
   188                 return DEFAULT_COMPILE_POLICY;
   189         }
   190     }
   192     private static final CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   194     protected static enum ImplicitSourcePolicy {
   195         /** Don't generate or process implicitly read source files. */
   196         NONE,
   197         /** Generate classes for implicitly read source files. */
   198         CLASS,
   199         /** Like CLASS, but generate warnings if annotation processing occurs */
   200         UNSET;
   202         static ImplicitSourcePolicy decode(String option) {
   203             if (option == null)
   204                 return UNSET;
   205             else if (option.equals("none"))
   206                 return NONE;
   207             else if (option.equals("class"))
   208                 return CLASS;
   209             else
   210                 return UNSET;
   211         }
   212     }
   214     /** The log to be used for error reporting.
   215      */
   216     public Log log;
   218     /** Factory for creating diagnostic objects
   219      */
   220     JCDiagnostic.Factory diagFactory;
   222     /** The tree factory module.
   223      */
   224     protected TreeMaker make;
   226     /** The class reader.
   227      */
   228     protected ClassReader reader;
   230     /** The class writer.
   231      */
   232     protected ClassWriter writer;
   234     /** The native header writer.
   235      */
   236     protected JNIWriter jniWriter;
   238     /** The module for the symbol table entry phases.
   239      */
   240     protected Enter enter;
   242     /** The symbol table.
   243      */
   244     protected Symtab syms;
   246     /** The language version.
   247      */
   248     protected Source source;
   250     /** The module for code generation.
   251      */
   252     protected Gen gen;
   254     /** The name table.
   255      */
   256     protected Names names;
   258     /** The attributor.
   259      */
   260     protected Attr attr;
   262     /** The attributor.
   263      */
   264     protected Check chk;
   266     /** The flow analyzer.
   267      */
   268     protected Flow flow;
   270     /** The type eraser.
   271      */
   272     protected TransTypes transTypes;
   274     /** The lambda translator.
   275      */
   276     protected LambdaToMethod lambdaToMethod;
   278     /** The syntactic sugar desweetener.
   279      */
   280     protected Lower lower;
   282     /** The annotation annotator.
   283      */
   284     protected Annotate annotate;
   286     /** Force a completion failure on this name
   287      */
   288     protected final Name completionFailureName;
   290     /** Type utilities.
   291      */
   292     protected Types types;
   294     /** Access to file objects.
   295      */
   296     protected JavaFileManager fileManager;
   298     /** Factory for parsers.
   299      */
   300     protected ParserFactory parserFactory;
   302     /** Broadcasting listener for progress events
   303      */
   304     protected MultiTaskListener taskListener;
   306     /**
   307      * Annotation processing may require and provide a new instance
   308      * of the compiler to be used for the analyze and generate phases.
   309      */
   310     protected JavaCompiler delegateCompiler;
   312     /**
   313      * Command line options.
   314      */
   315     protected Options options;
   317     protected Context context;
   319     /**
   320      * Flag set if any annotation processing occurred.
   321      **/
   322     protected boolean annotationProcessingOccurred;
   324     /**
   325      * Flag set if any implicit source files read.
   326      **/
   327     protected boolean implicitSourceFilesRead;
   329     /** Construct a new compiler using a shared context.
   330      */
   331     public JavaCompiler(Context context) {
   332         this.context = context;
   333         context.put(compilerKey, this);
   335         // if fileManager not already set, register the JavacFileManager to be used
   336         if (context.get(JavaFileManager.class) == null)
   337             JavacFileManager.preRegister(context);
   339         names = Names.instance(context);
   340         log = Log.instance(context);
   341         diagFactory = JCDiagnostic.Factory.instance(context);
   342         reader = ClassReader.instance(context);
   343         make = TreeMaker.instance(context);
   344         writer = ClassWriter.instance(context);
   345         jniWriter = JNIWriter.instance(context);
   346         enter = Enter.instance(context);
   347         todo = Todo.instance(context);
   349         fileManager = context.get(JavaFileManager.class);
   350         parserFactory = ParserFactory.instance(context);
   352         try {
   353             // catch completion problems with predefineds
   354             syms = Symtab.instance(context);
   355         } catch (CompletionFailure ex) {
   356             // inlined Check.completionError as it is not initialized yet
   357             log.error("cant.access", ex.sym, ex.getDetailValue());
   358             if (ex instanceof ClassReader.BadClassFile)
   359                 throw new Abort();
   360         }
   361         source = Source.instance(context);
   362         attr = Attr.instance(context);
   363         chk = Check.instance(context);
   364         gen = Gen.instance(context);
   365         flow = Flow.instance(context);
   366         transTypes = TransTypes.instance(context);
   367         lower = Lower.instance(context);
   368         annotate = Annotate.instance(context);
   369         types = Types.instance(context);
   370         taskListener = MultiTaskListener.instance(context);
   372         reader.sourceCompleter = this;
   374         options = Options.instance(context);
   376         lambdaToMethod = LambdaToMethod.instance(context);
   378         verbose       = options.isSet(VERBOSE);
   379         sourceOutput  = options.isSet(PRINTSOURCE); // used to be -s
   380         stubOutput    = options.isSet("-stubs");
   381         relax         = options.isSet("-relax");
   382         printFlat     = options.isSet("-printflat");
   383         attrParseOnly = options.isSet("-attrparseonly");
   384         encoding      = options.get(ENCODING);
   385         lineDebugInfo = options.isUnset(G_CUSTOM) ||
   386                         options.isSet(G_CUSTOM, "lines");
   387         genEndPos     = options.isSet(XJCOV) ||
   388                         context.get(DiagnosticListener.class) != null;
   389         devVerbose    = options.isSet("dev");
   390         processPcks   = options.isSet("process.packages");
   391         werror        = options.isSet(WERROR);
   393         if (source.compareTo(Source.DEFAULT) < 0) {
   394             if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   395                 if (fileManager instanceof BaseFileManager) {
   396                     if (((BaseFileManager) fileManager).isDefaultBootClassPath())
   397                         log.warning(LintCategory.OPTIONS, "source.no.bootclasspath", source.name);
   398                 }
   399             }
   400         }
   402         verboseCompilePolicy = options.isSet("verboseCompilePolicy");
   404         if (attrParseOnly)
   405             compilePolicy = CompilePolicy.ATTR_ONLY;
   406         else
   407             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   409         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   411         completionFailureName =
   412             options.isSet("failcomplete")
   413             ? names.fromString(options.get("failcomplete"))
   414             : null;
   416         shouldStopPolicyIfError =
   417             options.isSet("shouldStopPolicy") // backwards compatible
   418             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   419             : options.isSet("shouldStopPolicyIfError")
   420             ? CompileState.valueOf(options.get("shouldStopPolicyIfError"))
   421             : CompileState.INIT;
   422         shouldStopPolicyIfNoError =
   423             options.isSet("shouldStopPolicyIfNoError")
   424             ? CompileState.valueOf(options.get("shouldStopPolicyIfNoError"))
   425             : CompileState.GENERATE;
   427         if (options.isUnset("oldDiags"))
   428             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   429     }
   431     /* Switches:
   432      */
   434     /** Verbose output.
   435      */
   436     public boolean verbose;
   438     /** Emit plain Java source files rather than class files.
   439      */
   440     public boolean sourceOutput;
   442     /** Emit stub source files rather than class files.
   443      */
   444     public boolean stubOutput;
   446     /** Generate attributed parse tree only.
   447      */
   448     public boolean attrParseOnly;
   450     /** Switch: relax some constraints for producing the jsr14 prototype.
   451      */
   452     boolean relax;
   454     /** Debug switch: Emit Java sources after inner class flattening.
   455      */
   456     public boolean printFlat;
   458     /** The encoding to be used for source input.
   459      */
   460     public String encoding;
   462     /** Generate code with the LineNumberTable attribute for debugging
   463      */
   464     public boolean lineDebugInfo;
   466     /** Switch: should we store the ending positions?
   467      */
   468     public boolean genEndPos;
   470     /** Switch: should we debug ignored exceptions
   471      */
   472     protected boolean devVerbose;
   474     /** Switch: should we (annotation) process packages as well
   475      */
   476     protected boolean processPcks;
   478     /** Switch: treat warnings as errors
   479      */
   480     protected boolean werror;
   482     /** Switch: is annotation processing requested explitly via
   483      * CompilationTask.setProcessors?
   484      */
   485     protected boolean explicitAnnotationProcessingRequested = false;
   487     /**
   488      * The policy for the order in which to perform the compilation
   489      */
   490     protected CompilePolicy compilePolicy;
   492     /**
   493      * The policy for what to do with implicitly read source files
   494      */
   495     protected ImplicitSourcePolicy implicitSourcePolicy;
   497     /**
   498      * Report activity related to compilePolicy
   499      */
   500     public boolean verboseCompilePolicy;
   502     /**
   503      * Policy of how far to continue compilation after errors have occurred.
   504      * Set this to minimum CompileState (INIT) to stop as soon as possible
   505      * after errors.
   506      */
   507     public CompileState shouldStopPolicyIfError;
   509     /**
   510      * Policy of how far to continue compilation when no errors have occurred.
   511      * Set this to maximum CompileState (GENERATE) to perform full compilation.
   512      * Set this lower to perform partial compilation, such as -proc:only.
   513      */
   514     public CompileState shouldStopPolicyIfNoError;
   516     /** A queue of all as yet unattributed classes.
   517      */
   518     public Todo todo;
   520     /** A list of items to be closed when the compilation is complete.
   521      */
   522     public List<Closeable> closeables = List.nil();
   524     /** Ordered list of compiler phases for each compilation unit. */
   525     public enum CompileState {
   526         INIT(0),
   527         PARSE(1),
   528         ENTER(2),
   529         PROCESS(3),
   530         ATTR(4),
   531         FLOW(5),
   532         TRANSTYPES(6),
   533         UNLAMBDA(7),
   534         LOWER(8),
   535         GENERATE(9);
   537         CompileState(int value) {
   538             this.value = value;
   539         }
   540         boolean isAfter(CompileState other) {
   541             return value > other.value;
   542         }
   543         public static CompileState max(CompileState a, CompileState b) {
   544             return a.value > b.value ? a : b;
   545         }
   546         private final int value;
   547     };
   548     /** Partial map to record which compiler phases have been executed
   549      * for each compilation unit. Used for ATTR and FLOW phases.
   550      */
   551     protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
   552         private static final long serialVersionUID = 1812267524140424433L;
   553         boolean isDone(Env<AttrContext> env, CompileState cs) {
   554             CompileState ecs = get(env);
   555             return (ecs != null) && !cs.isAfter(ecs);
   556         }
   557     }
   558     private CompileStates compileStates = new CompileStates();
   560     /** The set of currently compiled inputfiles, needed to ensure
   561      *  we don't accidentally overwrite an input file when -s is set.
   562      *  initialized by `compile'.
   563      */
   564     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   566     protected boolean shouldStop(CompileState cs) {
   567         CompileState shouldStopPolicy = (errorCount() > 0 || unrecoverableError())
   568             ? shouldStopPolicyIfError
   569             : shouldStopPolicyIfNoError;
   570         return cs.isAfter(shouldStopPolicy);
   571     }
   573     /** The number of errors reported so far.
   574      */
   575     public int errorCount() {
   576         if (delegateCompiler != null && delegateCompiler != this)
   577             return delegateCompiler.errorCount();
   578         else {
   579             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   580                 log.error("warnings.and.werror");
   581             }
   582         }
   583         return log.nerrors;
   584     }
   586     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   587         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   588     }
   590     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   591         return shouldStop(cs) ? List.<T>nil() : list;
   592     }
   594     /** The number of warnings reported so far.
   595      */
   596     public int warningCount() {
   597         if (delegateCompiler != null && delegateCompiler != this)
   598             return delegateCompiler.warningCount();
   599         else
   600             return log.nwarnings;
   601     }
   603     /** Try to open input stream with given name.
   604      *  Report an error if this fails.
   605      *  @param filename   The file name of the input stream to be opened.
   606      */
   607     public CharSequence readSource(JavaFileObject filename) {
   608         try {
   609             inputFiles.add(filename);
   610             return filename.getCharContent(false);
   611         } catch (IOException e) {
   612             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   613             return null;
   614         }
   615     }
   617     /** Parse contents of input stream.
   618      *  @param filename     The name of the file from which input stream comes.
   619      *  @param content      The characters to be parsed.
   620      */
   621     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   622         long msec = now();
   623         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   624                                       null, List.<JCTree>nil());
   625         if (content != null) {
   626             if (verbose) {
   627                 log.printVerbose("parsing.started", filename);
   628             }
   629             if (!taskListener.isEmpty()) {
   630                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   631                 taskListener.started(e);
   632                 keepComments = true;
   633                 genEndPos = true;
   634             }
   635             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   636             tree = parser.parseCompilationUnit();
   637             if (verbose) {
   638                 log.printVerbose("parsing.done", Long.toString(elapsed(msec)));
   639             }
   640         }
   642         tree.sourcefile = filename;
   644         if (content != null && !taskListener.isEmpty()) {
   645             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   646             taskListener.finished(e);
   647         }
   649         return tree;
   650     }
   651     // where
   652         public boolean keepComments = false;
   653         protected boolean keepComments() {
   654             return keepComments || sourceOutput || stubOutput;
   655         }
   658     /** Parse contents of file.
   659      *  @param filename     The name of the file to be parsed.
   660      */
   661     @Deprecated
   662     public JCTree.JCCompilationUnit parse(String filename) {
   663         JavacFileManager fm = (JavacFileManager)fileManager;
   664         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   665     }
   667     /** Parse contents of file.
   668      *  @param filename     The name of the file to be parsed.
   669      */
   670     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   671         JavaFileObject prev = log.useSource(filename);
   672         try {
   673             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   674             if (t.endPositions != null)
   675                 log.setEndPosTable(filename, t.endPositions);
   676             return t;
   677         } finally {
   678             log.useSource(prev);
   679         }
   680     }
   682     /** Resolve an identifier which may be the binary name of a class or
   683      * the Java name of a class or package.
   684      * @param name      The name to resolve
   685      */
   686     public Symbol resolveBinaryNameOrIdent(String name) {
   687         try {
   688             Name flatname = names.fromString(name.replace("/", "."));
   689             return reader.loadClass(flatname);
   690         } catch (CompletionFailure ignore) {
   691             return resolveIdent(name);
   692         }
   693     }
   695     /** Resolve an identifier.
   696      * @param name      The identifier to resolve
   697      */
   698     public Symbol resolveIdent(String name) {
   699         if (name.equals(""))
   700             return syms.errSymbol;
   701         JavaFileObject prev = log.useSource(null);
   702         try {
   703             JCExpression tree = null;
   704             for (String s : name.split("\\.", -1)) {
   705                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   706                     return syms.errSymbol;
   707                 tree = (tree == null) ? make.Ident(names.fromString(s))
   708                                       : make.Select(tree, names.fromString(s));
   709             }
   710             JCCompilationUnit toplevel =
   711                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   712             toplevel.packge = syms.unnamedPackage;
   713             return attr.attribIdent(tree, toplevel);
   714         } finally {
   715             log.useSource(prev);
   716         }
   717     }
   719     /** Emit plain Java source for a class.
   720      *  @param env    The attribution environment of the outermost class
   721      *                containing this class.
   722      *  @param cdef   The class definition to be printed.
   723      */
   724     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   725         JavaFileObject outFile
   726             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   727                                                cdef.sym.flatname.toString(),
   728                                                JavaFileObject.Kind.SOURCE,
   729                                                null);
   730         if (inputFiles.contains(outFile)) {
   731             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   732             return null;
   733         } else {
   734             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   735             try {
   736                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   737                 if (verbose)
   738                     log.printVerbose("wrote.file", outFile);
   739             } finally {
   740                 out.close();
   741             }
   742             return outFile;
   743         }
   744     }
   746     /** Generate code and emit a class file for a given class
   747      *  @param env    The attribution environment of the outermost class
   748      *                containing this class.
   749      *  @param cdef   The class definition from which code is generated.
   750      */
   751     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   752         try {
   753             if (gen.genClass(env, cdef) && (errorCount() == 0))
   754                 return writer.writeClass(cdef.sym);
   755         } catch (ClassWriter.PoolOverflow ex) {
   756             log.error(cdef.pos(), "limit.pool");
   757         } catch (ClassWriter.StringOverflow ex) {
   758             log.error(cdef.pos(), "limit.string.overflow",
   759                       ex.value.substring(0, 20));
   760         } catch (CompletionFailure ex) {
   761             chk.completionError(cdef.pos(), ex);
   762         }
   763         return null;
   764     }
   766     /** Complete compiling a source file that has been accessed
   767      *  by the class file reader.
   768      *  @param c          The class the source file of which needs to be compiled.
   769      */
   770     public void complete(ClassSymbol c) throws CompletionFailure {
   771 //      System.err.println("completing " + c);//DEBUG
   772         if (completionFailureName == c.fullname) {
   773             throw new CompletionFailure(c, "user-selected completion failure by class name");
   774         }
   775         JCCompilationUnit tree;
   776         JavaFileObject filename = c.classfile;
   777         JavaFileObject prev = log.useSource(filename);
   779         try {
   780             tree = parse(filename, filename.getCharContent(false));
   781         } catch (IOException e) {
   782             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   783             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   784         } finally {
   785             log.useSource(prev);
   786         }
   788         if (!taskListener.isEmpty()) {
   789             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   790             taskListener.started(e);
   791         }
   793         enter.complete(List.of(tree), c);
   795         if (!taskListener.isEmpty()) {
   796             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   797             taskListener.finished(e);
   798         }
   800         if (enter.getEnv(c) == null) {
   801             boolean isPkgInfo =
   802                 tree.sourcefile.isNameCompatible("package-info",
   803                                                  JavaFileObject.Kind.SOURCE);
   804             if (isPkgInfo) {
   805                 if (enter.getEnv(tree.packge) == null) {
   806                     JCDiagnostic diag =
   807                         diagFactory.fragment("file.does.not.contain.package",
   808                                                  c.location());
   809                     throw reader.new BadClassFile(c, filename, diag);
   810                 }
   811             } else {
   812                 JCDiagnostic diag =
   813                         diagFactory.fragment("file.doesnt.contain.class",
   814                                             c.getQualifiedName());
   815                 throw reader.new BadClassFile(c, filename, diag);
   816             }
   817         }
   819         implicitSourceFilesRead = true;
   820     }
   822     /** Track when the JavaCompiler has been used to compile something. */
   823     private boolean hasBeenUsed = false;
   824     private long start_msec = 0;
   825     public long elapsed_msec = 0;
   827     public void compile(List<JavaFileObject> sourceFileObject)
   828         throws Throwable {
   829         compile(sourceFileObject, List.<String>nil(), null);
   830     }
   832     /**
   833      * Main method: compile a list of files, return all compiled classes
   834      *
   835      * @param sourceFileObjects file objects to be compiled
   836      * @param classnames class names to process for annotations
   837      * @param processors user provided annotation processors to bypass
   838      * discovery, {@code null} means that no processors were provided
   839      */
   840     public void compile(List<JavaFileObject> sourceFileObjects,
   841                         List<String> classnames,
   842                         Iterable<? extends Processor> processors)
   843     {
   844         if (processors != null && processors.iterator().hasNext())
   845             explicitAnnotationProcessingRequested = true;
   846         // as a JavaCompiler can only be used once, throw an exception if
   847         // it has been used before.
   848         if (hasBeenUsed)
   849             throw new AssertionError("attempt to reuse JavaCompiler");
   850         hasBeenUsed = true;
   852         // forcibly set the equivalent of -Xlint:-options, so that no further
   853         // warnings about command line options are generated from this point on
   854         options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
   855         options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);
   857         start_msec = now();
   859         try {
   860             initProcessAnnotations(processors);
   862             // These method calls must be chained to avoid memory leaks
   863             delegateCompiler =
   864                 processAnnotations(
   865                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   866                     classnames);
   868             delegateCompiler.compile2();
   869             delegateCompiler.close();
   870             elapsed_msec = delegateCompiler.elapsed_msec;
   871         } catch (Abort ex) {
   872             if (devVerbose)
   873                 ex.printStackTrace(System.err);
   874         } finally {
   875             if (procEnvImpl != null)
   876                 procEnvImpl.close();
   877         }
   878     }
   880     /**
   881      * The phases following annotation processing: attribution,
   882      * desugar, and finally code generation.
   883      */
   884     private void compile2() {
   885         try {
   886             switch (compilePolicy) {
   887             case ATTR_ONLY:
   888                 attribute(todo);
   889                 break;
   891             case CHECK_ONLY:
   892                 flow(attribute(todo));
   893                 break;
   895             case SIMPLE:
   896                 generate(desugar(flow(attribute(todo))));
   897                 break;
   899             case BY_FILE: {
   900                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   901                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   902                         generate(desugar(flow(attribute(q.remove()))));
   903                     }
   904                 }
   905                 break;
   907             case BY_TODO:
   908                 while (!todo.isEmpty())
   909                     generate(desugar(flow(attribute(todo.remove()))));
   910                 break;
   912             default:
   913                 Assert.error("unknown compile policy");
   914             }
   915         } catch (Abort ex) {
   916             if (devVerbose)
   917                 ex.printStackTrace(System.err);
   918         }
   920         if (verbose) {
   921             elapsed_msec = elapsed(start_msec);
   922             log.printVerbose("total", Long.toString(elapsed_msec));
   923         }
   925         reportDeferredDiagnostics();
   927         if (!log.hasDiagnosticListener()) {
   928             printCount("error", errorCount());
   929             printCount("warn", warningCount());
   930         }
   931     }
   933     /**
   934      * Set needRootClasses to true, in JavaCompiler subclass constructor
   935      * that want to collect public apis of classes supplied on the command line.
   936      */
   937     protected boolean needRootClasses = false;
   939     /**
   940      * The list of classes explicitly supplied on the command line for compilation.
   941      * Not always populated.
   942      */
   943     private List<JCClassDecl> rootClasses;
   945     /**
   946      * Parses a list of files.
   947      */
   948    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   949        if (shouldStop(CompileState.PARSE))
   950            return List.nil();
   952         //parse all files
   953         ListBuffer<JCCompilationUnit> trees = lb();
   954         Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
   955         for (JavaFileObject fileObject : fileObjects) {
   956             if (!filesSoFar.contains(fileObject)) {
   957                 filesSoFar.add(fileObject);
   958                 trees.append(parse(fileObject));
   959             }
   960         }
   961         return trees.toList();
   962     }
   964     /**
   965      * Enter the symbols found in a list of parse trees if the compilation
   966      * is expected to proceed beyond anno processing into attr.
   967      * As a side-effect, this puts elements on the "todo" list.
   968      * Also stores a list of all top level classes in rootClasses.
   969      */
   970     public List<JCCompilationUnit> enterTreesIfNeeded(List<JCCompilationUnit> roots) {
   971        if (shouldStop(CompileState.ATTR))
   972            return List.nil();
   973         return enterTrees(roots);
   974     }
   976     /**
   977      * Enter the symbols found in a list of parse trees.
   978      * As a side-effect, this puts elements on the "todo" list.
   979      * Also stores a list of all top level classes in rootClasses.
   980      */
   981     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   982         //enter symbols for all files
   983         if (!taskListener.isEmpty()) {
   984             for (JCCompilationUnit unit: roots) {
   985                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   986                 taskListener.started(e);
   987             }
   988         }
   990         enter.main(roots);
   992         if (!taskListener.isEmpty()) {
   993             for (JCCompilationUnit unit: roots) {
   994                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   995                 taskListener.finished(e);
   996             }
   997         }
   999         // If generating source, or if tracking public apis,
  1000         // then remember the classes declared in
  1001         // the original compilation units listed on the command line.
  1002         if (needRootClasses || sourceOutput || stubOutput) {
  1003             ListBuffer<JCClassDecl> cdefs = lb();
  1004             for (JCCompilationUnit unit : roots) {
  1005                 for (List<JCTree> defs = unit.defs;
  1006                      defs.nonEmpty();
  1007                      defs = defs.tail) {
  1008                     if (defs.head instanceof JCClassDecl)
  1009                         cdefs.append((JCClassDecl)defs.head);
  1012             rootClasses = cdefs.toList();
  1015         // Ensure the input files have been recorded. Although this is normally
  1016         // done by readSource, it may not have been done if the trees were read
  1017         // in a prior round of annotation processing, and the trees have been
  1018         // cleaned and are being reused.
  1019         for (JCCompilationUnit unit : roots) {
  1020             inputFiles.add(unit.sourcefile);
  1023         return roots;
  1026     /**
  1027      * Set to true to enable skeleton annotation processing code.
  1028      * Currently, we assume this variable will be replaced more
  1029      * advanced logic to figure out if annotation processing is
  1030      * needed.
  1031      */
  1032     boolean processAnnotations = false;
  1034     Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
  1036     /**
  1037      * Object to handle annotation processing.
  1038      */
  1039     private JavacProcessingEnvironment procEnvImpl = null;
  1041     /**
  1042      * Check if we should process annotations.
  1043      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
  1044      * to catch doc comments, and set keepComments so the parser records them in
  1045      * the compilation unit.
  1047      * @param processors user provided annotation processors to bypass
  1048      * discovery, {@code null} means that no processors were provided
  1049      */
  1050     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
  1051         // Process annotations if processing is not disabled and there
  1052         // is at least one Processor available.
  1053         if (options.isSet(PROC, "none")) {
  1054             processAnnotations = false;
  1055         } else if (procEnvImpl == null) {
  1056             procEnvImpl = JavacProcessingEnvironment.instance(context);
  1057             procEnvImpl.setProcessors(processors);
  1058             processAnnotations = procEnvImpl.atLeastOneProcessor();
  1060             if (processAnnotations) {
  1061                 options.put("save-parameter-names", "save-parameter-names");
  1062                 reader.saveParameterNames = true;
  1063                 keepComments = true;
  1064                 genEndPos = true;
  1065                 if (!taskListener.isEmpty())
  1066                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1067                 deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
  1068             } else { // free resources
  1069                 procEnvImpl.close();
  1074     // TODO: called by JavacTaskImpl
  1075     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
  1076         return processAnnotations(roots, List.<String>nil());
  1079     /**
  1080      * Process any annotations found in the specified compilation units.
  1081      * @param roots a list of compilation units
  1082      * @return an instance of the compiler in which to complete the compilation
  1083      */
  1084     // Implementation note: when this method is called, log.deferredDiagnostics
  1085     // will have been set true by initProcessAnnotations, meaning that any diagnostics
  1086     // that are reported will go into the log.deferredDiagnostics queue.
  1087     // By the time this method exits, log.deferDiagnostics must be set back to false,
  1088     // and all deferredDiagnostics must have been handled: i.e. either reported
  1089     // or determined to be transient, and therefore suppressed.
  1090     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
  1091                                            List<String> classnames) {
  1092         if (shouldStop(CompileState.PROCESS)) {
  1093             // Errors were encountered.
  1094             // Unless all the errors are resolve errors, the errors were parse errors
  1095             // or other errors during enter which cannot be fixed by running
  1096             // any annotation processors.
  1097             if (unrecoverableError()) {
  1098                 deferredDiagnosticHandler.reportDeferredDiagnostics();
  1099                 log.popDiagnosticHandler(deferredDiagnosticHandler);
  1100                 return this;
  1104         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1105         // by initProcessAnnotations
  1107         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1109         if (!processAnnotations) {
  1110             // If there are no annotation processors present, and
  1111             // annotation processing is to occur with compilation,
  1112             // emit a warning.
  1113             if (options.isSet(PROC, "only")) {
  1114                 log.warning("proc.proc-only.requested.no.procs");
  1115                 todo.clear();
  1117             // If not processing annotations, classnames must be empty
  1118             if (!classnames.isEmpty()) {
  1119                 log.error("proc.no.explicit.annotation.processing.requested",
  1120                           classnames);
  1122             Assert.checkNull(deferredDiagnosticHandler);
  1123             return this; // continue regular compilation
  1126         Assert.checkNonNull(deferredDiagnosticHandler);
  1128         try {
  1129             List<ClassSymbol> classSymbols = List.nil();
  1130             List<PackageSymbol> pckSymbols = List.nil();
  1131             if (!classnames.isEmpty()) {
  1132                  // Check for explicit request for annotation
  1133                  // processing
  1134                 if (!explicitAnnotationProcessingRequested()) {
  1135                     log.error("proc.no.explicit.annotation.processing.requested",
  1136                               classnames);
  1137                     deferredDiagnosticHandler.reportDeferredDiagnostics();
  1138                     log.popDiagnosticHandler(deferredDiagnosticHandler);
  1139                     return this; // TODO: Will this halt compilation?
  1140                 } else {
  1141                     boolean errors = false;
  1142                     for (String nameStr : classnames) {
  1143                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
  1144                         if (sym == null ||
  1145                             (sym.kind == Kinds.PCK && !processPcks) ||
  1146                             sym.kind == Kinds.ABSENT_TYP) {
  1147                             log.error("proc.cant.find.class", nameStr);
  1148                             errors = true;
  1149                             continue;
  1151                         try {
  1152                             if (sym.kind == Kinds.PCK)
  1153                                 sym.complete();
  1154                             if (sym.exists()) {
  1155                                 if (sym.kind == Kinds.PCK)
  1156                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1157                                 else
  1158                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1159                                 continue;
  1161                             Assert.check(sym.kind == Kinds.PCK);
  1162                             log.warning("proc.package.does.not.exist", nameStr);
  1163                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1164                         } catch (CompletionFailure e) {
  1165                             log.error("proc.cant.find.class", nameStr);
  1166                             errors = true;
  1167                             continue;
  1170                     if (errors) {
  1171                         deferredDiagnosticHandler.reportDeferredDiagnostics();
  1172                         log.popDiagnosticHandler(deferredDiagnosticHandler);
  1173                         return this;
  1177             try {
  1178                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols,
  1179                         deferredDiagnosticHandler);
  1180                 if (c != this)
  1181                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1182                 // doProcessing will have handled deferred diagnostics
  1183                 return c;
  1184             } finally {
  1185                 procEnvImpl.close();
  1187         } catch (CompletionFailure ex) {
  1188             log.error("cant.access", ex.sym, ex.getDetailValue());
  1189             deferredDiagnosticHandler.reportDeferredDiagnostics();
  1190             log.popDiagnosticHandler(deferredDiagnosticHandler);
  1191             return this;
  1195     private boolean unrecoverableError() {
  1196         if (deferredDiagnosticHandler != null) {
  1197             for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
  1198                 if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
  1199                     return true;
  1202         return false;
  1205     boolean explicitAnnotationProcessingRequested() {
  1206         return
  1207             explicitAnnotationProcessingRequested ||
  1208             explicitAnnotationProcessingRequested(options);
  1211     static boolean explicitAnnotationProcessingRequested(Options options) {
  1212         return
  1213             options.isSet(PROCESSOR) ||
  1214             options.isSet(PROCESSORPATH) ||
  1215             options.isSet(PROC, "only") ||
  1216             options.isSet(XPRINT);
  1219     /**
  1220      * Attribute a list of parse trees, such as found on the "todo" list.
  1221      * Note that attributing classes may cause additional files to be
  1222      * parsed and entered via the SourceCompleter.
  1223      * Attribution of the entries in the list does not stop if any errors occur.
  1224      * @returns a list of environments for attributd classes.
  1225      */
  1226     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1227         ListBuffer<Env<AttrContext>> results = lb();
  1228         while (!envs.isEmpty())
  1229             results.append(attribute(envs.remove()));
  1230         return stopIfError(CompileState.ATTR, results);
  1233     /**
  1234      * Attribute a parse tree.
  1235      * @returns the attributed parse tree
  1236      */
  1237     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1238         if (compileStates.isDone(env, CompileState.ATTR))
  1239             return env;
  1241         if (verboseCompilePolicy)
  1242             printNote("[attribute " + env.enclClass.sym + "]");
  1243         if (verbose)
  1244             log.printVerbose("checking.attribution", env.enclClass.sym);
  1246         if (!taskListener.isEmpty()) {
  1247             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1248             taskListener.started(e);
  1251         JavaFileObject prev = log.useSource(
  1252                                   env.enclClass.sym.sourcefile != null ?
  1253                                   env.enclClass.sym.sourcefile :
  1254                                   env.toplevel.sourcefile);
  1255         try {
  1256             attr.attrib(env);
  1257             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1258                 //if in fail-over mode, ensure that AST expression nodes
  1259                 //are correctly initialized (e.g. they have a type/symbol)
  1260                 attr.postAttr(env.tree);
  1262             compileStates.put(env, CompileState.ATTR);
  1263             if (rootClasses != null && rootClasses.contains(env.enclClass)) {
  1264                 // This was a class that was explicitly supplied for compilation.
  1265                 // If we want to capture the public api of this class,
  1266                 // then now is a good time to do it.
  1267                 reportPublicApi(env.enclClass.sym);
  1270         finally {
  1271             log.useSource(prev);
  1274         return env;
  1277     /** Report the public api of a class that was supplied explicitly for compilation,
  1278      *  for example on the command line to javac.
  1279      * @param sym The symbol of the class.
  1280      */
  1281     public void reportPublicApi(ClassSymbol sym) {
  1282        // Override to collect the reported public api.
  1285     /**
  1286      * Perform dataflow checks on attributed parse trees.
  1287      * These include checks for definite assignment and unreachable statements.
  1288      * If any errors occur, an empty list will be returned.
  1289      * @returns the list of attributed parse trees
  1290      */
  1291     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1292         ListBuffer<Env<AttrContext>> results = lb();
  1293         for (Env<AttrContext> env: envs) {
  1294             flow(env, results);
  1296         return stopIfError(CompileState.FLOW, results);
  1299     /**
  1300      * Perform dataflow checks on an attributed parse tree.
  1301      */
  1302     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1303         ListBuffer<Env<AttrContext>> results = lb();
  1304         flow(env, results);
  1305         return stopIfError(CompileState.FLOW, results);
  1308     /**
  1309      * Perform dataflow checks on an attributed parse tree.
  1310      */
  1311     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1312         try {
  1313             if (shouldStop(CompileState.FLOW))
  1314                 return;
  1316             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1317                 results.add(env);
  1318                 return;
  1321             if (verboseCompilePolicy)
  1322                 printNote("[flow " + env.enclClass.sym + "]");
  1323             JavaFileObject prev = log.useSource(
  1324                                                 env.enclClass.sym.sourcefile != null ?
  1325                                                 env.enclClass.sym.sourcefile :
  1326                                                 env.toplevel.sourcefile);
  1327             try {
  1328                 make.at(Position.FIRSTPOS);
  1329                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1330                 flow.analyzeTree(env, localMake);
  1331                 compileStates.put(env, CompileState.FLOW);
  1333                 if (shouldStop(CompileState.FLOW))
  1334                     return;
  1336                 results.add(env);
  1338             finally {
  1339                 log.useSource(prev);
  1342         finally {
  1343             if (!taskListener.isEmpty()) {
  1344                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1345                 taskListener.finished(e);
  1350     /**
  1351      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1352      * for source or code generation.
  1353      * If any errors occur, an empty list will be returned.
  1354      * @returns a list containing the classes to be generated
  1355      */
  1356     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1357         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1358         for (Env<AttrContext> env: envs)
  1359             desugar(env, results);
  1360         return stopIfError(CompileState.FLOW, results);
  1363     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1364             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1366     /**
  1367      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1368      * for source or code generation. If the file was not listed on the command line,
  1369      * the current implicitSourcePolicy is taken into account.
  1370      * The preparation stops as soon as an error is found.
  1371      */
  1372     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1373         if (shouldStop(CompileState.TRANSTYPES))
  1374             return;
  1376         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1377                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1378             return;
  1381         if (compileStates.isDone(env, CompileState.LOWER)) {
  1382             results.addAll(desugaredEnvs.get(env));
  1383             return;
  1386         /**
  1387          * Ensure that superclasses of C are desugared before C itself. This is
  1388          * required for two reasons: (i) as erasure (TransTypes) destroys
  1389          * information needed in flow analysis and (ii) as some checks carried
  1390          * out during lowering require that all synthetic fields/methods have
  1391          * already been added to C and its superclasses.
  1392          */
  1393         class ScanNested extends TreeScanner {
  1394             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1395             @Override
  1396             public void visitClassDef(JCClassDecl node) {
  1397                 Type st = types.supertype(node.sym.type);
  1398                 if (st.hasTag(CLASS)) {
  1399                     ClassSymbol c = st.tsym.outermostClass();
  1400                     Env<AttrContext> stEnv = enter.getEnv(c);
  1401                     if (stEnv != null && env != stEnv) {
  1402                         if (dependencies.add(stEnv))
  1403                             scan(stEnv.tree);
  1406                 super.visitClassDef(node);
  1409         ScanNested scanner = new ScanNested();
  1410         scanner.scan(env.tree);
  1411         for (Env<AttrContext> dep: scanner.dependencies) {
  1412         if (!compileStates.isDone(dep, CompileState.FLOW))
  1413             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1416         //We need to check for error another time as more classes might
  1417         //have been attributed and analyzed at this stage
  1418         if (shouldStop(CompileState.TRANSTYPES))
  1419             return;
  1421         if (verboseCompilePolicy)
  1422             printNote("[desugar " + env.enclClass.sym + "]");
  1424         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1425                                   env.enclClass.sym.sourcefile :
  1426                                   env.toplevel.sourcefile);
  1427         try {
  1428             //save tree prior to rewriting
  1429             JCTree untranslated = env.tree;
  1431             make.at(Position.FIRSTPOS);
  1432             TreeMaker localMake = make.forToplevel(env.toplevel);
  1434             if (env.tree instanceof JCCompilationUnit) {
  1435                 if (!(stubOutput || sourceOutput || printFlat)) {
  1436                     if (shouldStop(CompileState.LOWER))
  1437                         return;
  1438                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1439                     if (pdef.head != null) {
  1440                         Assert.check(pdef.tail.isEmpty());
  1441                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1444                 return;
  1447             if (stubOutput) {
  1448                 //emit stub Java source file, only for compilation
  1449                 //units enumerated explicitly on the command line
  1450                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1451                 if (untranslated instanceof JCClassDecl &&
  1452                     rootClasses.contains((JCClassDecl)untranslated) &&
  1453                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1454                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1455                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1457                 return;
  1460             if (shouldStop(CompileState.TRANSTYPES))
  1461                 return;
  1463             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1464             compileStates.put(env, CompileState.TRANSTYPES);
  1466             if (shouldStop(CompileState.UNLAMBDA))
  1467                 return;
  1469             env.tree = lambdaToMethod.translateTopLevelClass(env, env.tree, localMake);
  1470             compileStates.put(env, CompileState.UNLAMBDA);
  1472             if (shouldStop(CompileState.LOWER))
  1473                 return;
  1475             if (sourceOutput) {
  1476                 //emit standard Java source file, only for compilation
  1477                 //units enumerated explicitly on the command line
  1478                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1479                 if (untranslated instanceof JCClassDecl &&
  1480                     rootClasses.contains((JCClassDecl)untranslated)) {
  1481                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1483                 return;
  1486             //translate out inner classes
  1487             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1488             compileStates.put(env, CompileState.LOWER);
  1490             if (shouldStop(CompileState.LOWER))
  1491                 return;
  1493             //generate code for each class
  1494             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1495                 JCClassDecl cdef = (JCClassDecl)l.head;
  1496                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1499         finally {
  1500             log.useSource(prev);
  1505     /** Generates the source or class file for a list of classes.
  1506      * The decision to generate a source file or a class file is
  1507      * based upon the compiler's options.
  1508      * Generation stops if an error occurs while writing files.
  1509      */
  1510     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1511         generate(queue, null);
  1514     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1515         if (shouldStop(CompileState.GENERATE))
  1516             return;
  1518         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1520         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1521             Env<AttrContext> env = x.fst;
  1522             JCClassDecl cdef = x.snd;
  1524             if (verboseCompilePolicy) {
  1525                 printNote("[generate "
  1526                                + (usePrintSource ? " source" : "code")
  1527                                + " " + cdef.sym + "]");
  1530             if (!taskListener.isEmpty()) {
  1531                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1532                 taskListener.started(e);
  1535             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1536                                       env.enclClass.sym.sourcefile :
  1537                                       env.toplevel.sourcefile);
  1538             try {
  1539                 JavaFileObject file;
  1540                 if (usePrintSource)
  1541                     file = printSource(env, cdef);
  1542                 else {
  1543                     if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
  1544                             && jniWriter.needsHeader(cdef.sym)) {
  1545                         jniWriter.write(cdef.sym);
  1547                     file = genCode(env, cdef);
  1549                 if (results != null && file != null)
  1550                     results.add(file);
  1551             } catch (IOException ex) {
  1552                 log.error(cdef.pos(), "class.cant.write",
  1553                           cdef.sym, ex.getMessage());
  1554                 return;
  1555             } finally {
  1556                 log.useSource(prev);
  1559             if (!taskListener.isEmpty()) {
  1560                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1561                 taskListener.finished(e);
  1566         // where
  1567         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1568             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1569             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1570             for (Env<AttrContext> env: envs) {
  1571                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1572                 if (sublist == null) {
  1573                     sublist = new ListBuffer<Env<AttrContext>>();
  1574                     map.put(env.toplevel, sublist);
  1576                 sublist.add(env);
  1578             return map;
  1581         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1582             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1583             class MethodBodyRemover extends TreeTranslator {
  1584                 @Override
  1585                 public void visitMethodDef(JCMethodDecl tree) {
  1586                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1587                     for (JCVariableDecl vd : tree.params)
  1588                         vd.mods.flags &= ~Flags.FINAL;
  1589                     tree.body = null;
  1590                     super.visitMethodDef(tree);
  1592                 @Override
  1593                 public void visitVarDef(JCVariableDecl tree) {
  1594                     if (tree.init != null && tree.init.type.constValue() == null)
  1595                         tree.init = null;
  1596                     super.visitVarDef(tree);
  1598                 @Override
  1599                 public void visitClassDef(JCClassDecl tree) {
  1600                     ListBuffer<JCTree> newdefs = lb();
  1601                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1602                         JCTree t = it.head;
  1603                         switch (t.getTag()) {
  1604                         case CLASSDEF:
  1605                             if (isInterface ||
  1606                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1607                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1608                                 newdefs.append(t);
  1609                             break;
  1610                         case METHODDEF:
  1611                             if (isInterface ||
  1612                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1613                                 ((JCMethodDecl) t).sym.name == names.init ||
  1614                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1615                                 newdefs.append(t);
  1616                             break;
  1617                         case VARDEF:
  1618                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1619                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1620                                 newdefs.append(t);
  1621                             break;
  1622                         default:
  1623                             break;
  1626                     tree.defs = newdefs.toList();
  1627                     super.visitClassDef(tree);
  1630             MethodBodyRemover r = new MethodBodyRemover();
  1631             return r.translate(cdef);
  1634     public void reportDeferredDiagnostics() {
  1635         if (errorCount() == 0
  1636                 && annotationProcessingOccurred
  1637                 && implicitSourceFilesRead
  1638                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1639             if (explicitAnnotationProcessingRequested())
  1640                 log.warning("proc.use.implicit");
  1641             else
  1642                 log.warning("proc.use.proc.or.implicit");
  1644         chk.reportDeferredDiagnostics();
  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);
  1699     protected void printNote(String lines) {
  1700         log.printRawLines(Log.WriterKind.NOTICE, lines);
  1703     /** Print numbers of errors and warnings.
  1704      */
  1705     public void printCount(String kind, int count) {
  1706         if (count != 0) {
  1707             String key;
  1708             if (count == 1)
  1709                 key = "count." + kind;
  1710             else
  1711                 key = "count." + kind + ".plural";
  1712             log.printLines(WriterKind.ERROR, key, String.valueOf(count));
  1713             log.flush(Log.WriterKind.ERROR);
  1717     private static long now() {
  1718         return System.currentTimeMillis();
  1721     private static long elapsed(long then) {
  1722         return now() - then;
  1725     public void initRound(JavaCompiler prev) {
  1726         genEndPos = prev.genEndPos;
  1727         keepComments = prev.keepComments;
  1728         start_msec = prev.start_msec;
  1729         hasBeenUsed = true;
  1730         closeables = prev.closeables;
  1731         prev.closeables = List.nil();
  1732         shouldStopPolicyIfError = prev.shouldStopPolicyIfError;
  1733         shouldStopPolicyIfNoError = prev.shouldStopPolicyIfNoError;
  1736     public static void enableLogging() {
  1737         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1738         logger.setLevel(Level.ALL);
  1739         for (Handler h : logger.getParent().getHandlers()) {
  1740             h.setLevel(Level.ALL);

mercurial