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

Thu, 05 Sep 2013 11:27:27 +0200

author
jfranck
date
Thu, 05 Sep 2013 11:27:27 +0200
changeset 2007
a76c663a9cac
parent 1982
662a5188bded
child 2047
5f915a0c9615
permissions
-rw-r--r--

8023974: Drop 'implements Completer' and 'implements SourceCompleter' from ClassReader resp. JavaCompiler.
Reviewed-by: jjg, jfranck
Contributed-by: Andreas Lundblad <andreas.lundblad@oracle.com>

     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 {
    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      * SourceCompleter that delegates to the complete-method of this class.
   315      */
   316     protected final ClassReader.SourceCompleter thisCompleter =
   317             new ClassReader.SourceCompleter() {
   318                 @Override
   319                 public void complete(ClassSymbol sym) throws CompletionFailure {
   320                     JavaCompiler.this.complete(sym);
   321                 }
   322             };
   324     /**
   325      * Command line options.
   326      */
   327     protected Options options;
   329     protected Context context;
   331     /**
   332      * Flag set if any annotation processing occurred.
   333      **/
   334     protected boolean annotationProcessingOccurred;
   336     /**
   337      * Flag set if any implicit source files read.
   338      **/
   339     protected boolean implicitSourceFilesRead;
   341     protected CompileStates compileStates;
   343     /** Construct a new compiler using a shared context.
   344      */
   345     public JavaCompiler(Context context) {
   346         this.context = context;
   347         context.put(compilerKey, this);
   349         // if fileManager not already set, register the JavacFileManager to be used
   350         if (context.get(JavaFileManager.class) == null)
   351             JavacFileManager.preRegister(context);
   353         names = Names.instance(context);
   354         log = Log.instance(context);
   355         diagFactory = JCDiagnostic.Factory.instance(context);
   356         reader = ClassReader.instance(context);
   357         make = TreeMaker.instance(context);
   358         writer = ClassWriter.instance(context);
   359         jniWriter = JNIWriter.instance(context);
   360         enter = Enter.instance(context);
   361         todo = Todo.instance(context);
   363         fileManager = context.get(JavaFileManager.class);
   364         parserFactory = ParserFactory.instance(context);
   365         compileStates = CompileStates.instance(context);
   367         try {
   368             // catch completion problems with predefineds
   369             syms = Symtab.instance(context);
   370         } catch (CompletionFailure ex) {
   371             // inlined Check.completionError as it is not initialized yet
   372             log.error("cant.access", ex.sym, ex.getDetailValue());
   373             if (ex instanceof ClassReader.BadClassFile)
   374                 throw new Abort();
   375         }
   376         source = Source.instance(context);
   377         Target target = Target.instance(context);
   378         attr = Attr.instance(context);
   379         chk = Check.instance(context);
   380         gen = Gen.instance(context);
   381         flow = Flow.instance(context);
   382         transTypes = TransTypes.instance(context);
   383         lower = Lower.instance(context);
   384         annotate = Annotate.instance(context);
   385         types = Types.instance(context);
   386         taskListener = MultiTaskListener.instance(context);
   388         reader.sourceCompleter = thisCompleter;
   390         options = Options.instance(context);
   392         lambdaToMethod = LambdaToMethod.instance(context);
   394         verbose       = options.isSet(VERBOSE);
   395         sourceOutput  = options.isSet(PRINTSOURCE); // used to be -s
   396         stubOutput    = options.isSet("-stubs");
   397         relax         = options.isSet("-relax");
   398         printFlat     = options.isSet("-printflat");
   399         attrParseOnly = options.isSet("-attrparseonly");
   400         encoding      = options.get(ENCODING);
   401         lineDebugInfo = options.isUnset(G_CUSTOM) ||
   402                         options.isSet(G_CUSTOM, "lines");
   403         genEndPos     = options.isSet(XJCOV) ||
   404                         context.get(DiagnosticListener.class) != null;
   405         devVerbose    = options.isSet("dev");
   406         processPcks   = options.isSet("process.packages");
   407         werror        = options.isSet(WERROR);
   409         if (source.compareTo(Source.DEFAULT) < 0) {
   410             if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   411                 if (fileManager instanceof BaseFileManager) {
   412                     if (((BaseFileManager) fileManager).isDefaultBootClassPath())
   413                         log.warning(LintCategory.OPTIONS, "source.no.bootclasspath", source.name);
   414                 }
   415             }
   416         }
   418         checkForObsoleteOptions(target);
   420         verboseCompilePolicy = options.isSet("verboseCompilePolicy");
   422         if (attrParseOnly)
   423             compilePolicy = CompilePolicy.ATTR_ONLY;
   424         else
   425             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   427         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   429         completionFailureName =
   430             options.isSet("failcomplete")
   431             ? names.fromString(options.get("failcomplete"))
   432             : null;
   434         shouldStopPolicyIfError =
   435             options.isSet("shouldStopPolicy") // backwards compatible
   436             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   437             : options.isSet("shouldStopPolicyIfError")
   438             ? CompileState.valueOf(options.get("shouldStopPolicyIfError"))
   439             : CompileState.INIT;
   440         shouldStopPolicyIfNoError =
   441             options.isSet("shouldStopPolicyIfNoError")
   442             ? CompileState.valueOf(options.get("shouldStopPolicyIfNoError"))
   443             : CompileState.GENERATE;
   445         if (options.isUnset("oldDiags"))
   446             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   447     }
   449     private void checkForObsoleteOptions(Target target) {
   450         // Unless lint checking on options is disabled, check for
   451         // obsolete source and target options.
   452         boolean obsoleteOptionFound = false;
   453         if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   454             if (source.compareTo(Source.JDK1_5) <= 0) {
   455                 log.warning(LintCategory.OPTIONS, "option.obsolete.source", source.name);
   456                 obsoleteOptionFound = true;
   457             }
   459             if (target.compareTo(Target.JDK1_5) <= 0) {
   460                 log.warning(LintCategory.OPTIONS, "option.obsolete.target", target.name);
   461                 obsoleteOptionFound = true;
   462             }
   464             if (obsoleteOptionFound)
   465                 log.warning(LintCategory.OPTIONS, "option.obsolete.suppression");
   466         }
   467     }
   469     /* Switches:
   470      */
   472     /** Verbose output.
   473      */
   474     public boolean verbose;
   476     /** Emit plain Java source files rather than class files.
   477      */
   478     public boolean sourceOutput;
   480     /** Emit stub source files rather than class files.
   481      */
   482     public boolean stubOutput;
   484     /** Generate attributed parse tree only.
   485      */
   486     public boolean attrParseOnly;
   488     /** Switch: relax some constraints for producing the jsr14 prototype.
   489      */
   490     boolean relax;
   492     /** Debug switch: Emit Java sources after inner class flattening.
   493      */
   494     public boolean printFlat;
   496     /** The encoding to be used for source input.
   497      */
   498     public String encoding;
   500     /** Generate code with the LineNumberTable attribute for debugging
   501      */
   502     public boolean lineDebugInfo;
   504     /** Switch: should we store the ending positions?
   505      */
   506     public boolean genEndPos;
   508     /** Switch: should we debug ignored exceptions
   509      */
   510     protected boolean devVerbose;
   512     /** Switch: should we (annotation) process packages as well
   513      */
   514     protected boolean processPcks;
   516     /** Switch: treat warnings as errors
   517      */
   518     protected boolean werror;
   520     /** Switch: is annotation processing requested explicitly via
   521      * CompilationTask.setProcessors?
   522      */
   523     protected boolean explicitAnnotationProcessingRequested = false;
   525     /**
   526      * The policy for the order in which to perform the compilation
   527      */
   528     protected CompilePolicy compilePolicy;
   530     /**
   531      * The policy for what to do with implicitly read source files
   532      */
   533     protected ImplicitSourcePolicy implicitSourcePolicy;
   535     /**
   536      * Report activity related to compilePolicy
   537      */
   538     public boolean verboseCompilePolicy;
   540     /**
   541      * Policy of how far to continue compilation after errors have occurred.
   542      * Set this to minimum CompileState (INIT) to stop as soon as possible
   543      * after errors.
   544      */
   545     public CompileState shouldStopPolicyIfError;
   547     /**
   548      * Policy of how far to continue compilation when no errors have occurred.
   549      * Set this to maximum CompileState (GENERATE) to perform full compilation.
   550      * Set this lower to perform partial compilation, such as -proc:only.
   551      */
   552     public CompileState shouldStopPolicyIfNoError;
   554     /** A queue of all as yet unattributed classes.
   555      */
   556     public Todo todo;
   558     /** A list of items to be closed when the compilation is complete.
   559      */
   560     public List<Closeable> closeables = List.nil();
   562     /** The set of currently compiled inputfiles, needed to ensure
   563      *  we don't accidentally overwrite an input file when -s is set.
   564      *  initialized by `compile'.
   565      */
   566     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   568     protected boolean shouldStop(CompileState cs) {
   569         CompileState shouldStopPolicy = (errorCount() > 0 || unrecoverableError())
   570             ? shouldStopPolicyIfError
   571             : shouldStopPolicyIfNoError;
   572         return cs.isAfter(shouldStopPolicy);
   573     }
   575     /** The number of errors reported so far.
   576      */
   577     public int errorCount() {
   578         if (delegateCompiler != null && delegateCompiler != this)
   579             return delegateCompiler.errorCount();
   580         else {
   581             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   582                 log.error("warnings.and.werror");
   583             }
   584         }
   585         return log.nerrors;
   586     }
   588     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   589         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   590     }
   592     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   593         return shouldStop(cs) ? List.<T>nil() : list;
   594     }
   596     /** The number of warnings reported so far.
   597      */
   598     public int warningCount() {
   599         if (delegateCompiler != null && delegateCompiler != this)
   600             return delegateCompiler.warningCount();
   601         else
   602             return log.nwarnings;
   603     }
   605     /** Try to open input stream with given name.
   606      *  Report an error if this fails.
   607      *  @param filename   The file name of the input stream to be opened.
   608      */
   609     public CharSequence readSource(JavaFileObject filename) {
   610         try {
   611             inputFiles.add(filename);
   612             return filename.getCharContent(false);
   613         } catch (IOException e) {
   614             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   615             return null;
   616         }
   617     }
   619     /** Parse contents of input stream.
   620      *  @param filename     The name of the file from which input stream comes.
   621      *  @param content      The characters to be parsed.
   622      */
   623     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   624         long msec = now();
   625         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   626                                       null, List.<JCTree>nil());
   627         if (content != null) {
   628             if (verbose) {
   629                 log.printVerbose("parsing.started", filename);
   630             }
   631             if (!taskListener.isEmpty()) {
   632                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   633                 taskListener.started(e);
   634                 keepComments = true;
   635                 genEndPos = true;
   636             }
   637             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   638             tree = parser.parseCompilationUnit();
   639             if (verbose) {
   640                 log.printVerbose("parsing.done", Long.toString(elapsed(msec)));
   641             }
   642         }
   644         tree.sourcefile = filename;
   646         if (content != null && !taskListener.isEmpty()) {
   647             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   648             taskListener.finished(e);
   649         }
   651         return tree;
   652     }
   653     // where
   654         public boolean keepComments = false;
   655         protected boolean keepComments() {
   656             return keepComments || sourceOutput || stubOutput;
   657         }
   660     /** Parse contents of file.
   661      *  @param filename     The name of the file to be parsed.
   662      */
   663     @Deprecated
   664     public JCTree.JCCompilationUnit parse(String filename) {
   665         JavacFileManager fm = (JavacFileManager)fileManager;
   666         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   667     }
   669     /** Parse contents of file.
   670      *  @param filename     The name of the file to be parsed.
   671      */
   672     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   673         JavaFileObject prev = log.useSource(filename);
   674         try {
   675             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   676             if (t.endPositions != null)
   677                 log.setEndPosTable(filename, t.endPositions);
   678             return t;
   679         } finally {
   680             log.useSource(prev);
   681         }
   682     }
   684     /** Resolve an identifier which may be the binary name of a class or
   685      * the Java name of a class or package.
   686      * @param name      The name to resolve
   687      */
   688     public Symbol resolveBinaryNameOrIdent(String name) {
   689         try {
   690             Name flatname = names.fromString(name.replace("/", "."));
   691             return reader.loadClass(flatname);
   692         } catch (CompletionFailure ignore) {
   693             return resolveIdent(name);
   694         }
   695     }
   697     /** Resolve an identifier.
   698      * @param name      The identifier to resolve
   699      */
   700     public Symbol resolveIdent(String name) {
   701         if (name.equals(""))
   702             return syms.errSymbol;
   703         JavaFileObject prev = log.useSource(null);
   704         try {
   705             JCExpression tree = null;
   706             for (String s : name.split("\\.", -1)) {
   707                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   708                     return syms.errSymbol;
   709                 tree = (tree == null) ? make.Ident(names.fromString(s))
   710                                       : make.Select(tree, names.fromString(s));
   711             }
   712             JCCompilationUnit toplevel =
   713                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   714             toplevel.packge = syms.unnamedPackage;
   715             return attr.attribIdent(tree, toplevel);
   716         } finally {
   717             log.useSource(prev);
   718         }
   719     }
   721     /** Emit plain Java source for a class.
   722      *  @param env    The attribution environment of the outermost class
   723      *                containing this class.
   724      *  @param cdef   The class definition to be printed.
   725      */
   726     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   727         JavaFileObject outFile
   728             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   729                                                cdef.sym.flatname.toString(),
   730                                                JavaFileObject.Kind.SOURCE,
   731                                                null);
   732         if (inputFiles.contains(outFile)) {
   733             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   734             return null;
   735         } else {
   736             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   737             try {
   738                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   739                 if (verbose)
   740                     log.printVerbose("wrote.file", outFile);
   741             } finally {
   742                 out.close();
   743             }
   744             return outFile;
   745         }
   746     }
   748     /** Generate code and emit a class file for a given class
   749      *  @param env    The attribution environment of the outermost class
   750      *                containing this class.
   751      *  @param cdef   The class definition from which code is generated.
   752      */
   753     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   754         try {
   755             if (gen.genClass(env, cdef) && (errorCount() == 0))
   756                 return writer.writeClass(cdef.sym);
   757         } catch (ClassWriter.PoolOverflow ex) {
   758             log.error(cdef.pos(), "limit.pool");
   759         } catch (ClassWriter.StringOverflow ex) {
   760             log.error(cdef.pos(), "limit.string.overflow",
   761                       ex.value.substring(0, 20));
   762         } catch (CompletionFailure ex) {
   763             chk.completionError(cdef.pos(), ex);
   764         }
   765         return null;
   766     }
   768     /** Complete compiling a source file that has been accessed
   769      *  by the class file reader.
   770      *  @param c          The class the source file of which needs to be compiled.
   771      */
   772     public void complete(ClassSymbol c) throws CompletionFailure {
   773 //      System.err.println("completing " + c);//DEBUG
   774         if (completionFailureName == c.fullname) {
   775             throw new CompletionFailure(c, "user-selected completion failure by class name");
   776         }
   777         JCCompilationUnit tree;
   778         JavaFileObject filename = c.classfile;
   779         JavaFileObject prev = log.useSource(filename);
   781         try {
   782             tree = parse(filename, filename.getCharContent(false));
   783         } catch (IOException e) {
   784             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   785             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   786         } finally {
   787             log.useSource(prev);
   788         }
   790         if (!taskListener.isEmpty()) {
   791             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   792             taskListener.started(e);
   793         }
   795         enter.complete(List.of(tree), c);
   797         if (!taskListener.isEmpty()) {
   798             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   799             taskListener.finished(e);
   800         }
   802         if (enter.getEnv(c) == null) {
   803             boolean isPkgInfo =
   804                 tree.sourcefile.isNameCompatible("package-info",
   805                                                  JavaFileObject.Kind.SOURCE);
   806             if (isPkgInfo) {
   807                 if (enter.getEnv(tree.packge) == null) {
   808                     JCDiagnostic diag =
   809                         diagFactory.fragment("file.does.not.contain.package",
   810                                                  c.location());
   811                     throw reader.new BadClassFile(c, filename, diag);
   812                 }
   813             } else {
   814                 JCDiagnostic diag =
   815                         diagFactory.fragment("file.doesnt.contain.class",
   816                                             c.getQualifiedName());
   817                 throw reader.new BadClassFile(c, filename, diag);
   818             }
   819         }
   821         implicitSourceFilesRead = true;
   822     }
   824     /** Track when the JavaCompiler has been used to compile something. */
   825     private boolean hasBeenUsed = false;
   826     private long start_msec = 0;
   827     public long elapsed_msec = 0;
   829     public void compile(List<JavaFileObject> sourceFileObject)
   830         throws Throwable {
   831         compile(sourceFileObject, List.<String>nil(), null);
   832     }
   834     /**
   835      * Main method: compile a list of files, return all compiled classes
   836      *
   837      * @param sourceFileObjects file objects to be compiled
   838      * @param classnames class names to process for annotations
   839      * @param processors user provided annotation processors to bypass
   840      * discovery, {@code null} means that no processors were provided
   841      */
   842     public void compile(List<JavaFileObject> sourceFileObjects,
   843                         List<String> classnames,
   844                         Iterable<? extends Processor> processors)
   845     {
   846         if (processors != null && processors.iterator().hasNext())
   847             explicitAnnotationProcessingRequested = true;
   848         // as a JavaCompiler can only be used once, throw an exception if
   849         // it has been used before.
   850         if (hasBeenUsed)
   851             throw new AssertionError("attempt to reuse JavaCompiler");
   852         hasBeenUsed = true;
   854         // forcibly set the equivalent of -Xlint:-options, so that no further
   855         // warnings about command line options are generated from this point on
   856         options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
   857         options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);
   859         start_msec = now();
   861         try {
   862             initProcessAnnotations(processors);
   864             // These method calls must be chained to avoid memory leaks
   865             delegateCompiler =
   866                 processAnnotations(
   867                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   868                     classnames);
   870             delegateCompiler.compile2();
   871             delegateCompiler.close();
   872             elapsed_msec = delegateCompiler.elapsed_msec;
   873         } catch (Abort ex) {
   874             if (devVerbose)
   875                 ex.printStackTrace(System.err);
   876         } finally {
   877             if (procEnvImpl != null)
   878                 procEnvImpl.close();
   879         }
   880     }
   882     /**
   883      * The phases following annotation processing: attribution,
   884      * desugar, and finally code generation.
   885      */
   886     private void compile2() {
   887         try {
   888             switch (compilePolicy) {
   889             case ATTR_ONLY:
   890                 attribute(todo);
   891                 break;
   893             case CHECK_ONLY:
   894                 flow(attribute(todo));
   895                 break;
   897             case SIMPLE:
   898                 generate(desugar(flow(attribute(todo))));
   899                 break;
   901             case BY_FILE: {
   902                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   903                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   904                         generate(desugar(flow(attribute(q.remove()))));
   905                     }
   906                 }
   907                 break;
   909             case BY_TODO:
   910                 while (!todo.isEmpty())
   911                     generate(desugar(flow(attribute(todo.remove()))));
   912                 break;
   914             default:
   915                 Assert.error("unknown compile policy");
   916             }
   917         } catch (Abort ex) {
   918             if (devVerbose)
   919                 ex.printStackTrace(System.err);
   920         }
   922         if (verbose) {
   923             elapsed_msec = elapsed(start_msec);
   924             log.printVerbose("total", Long.toString(elapsed_msec));
   925         }
   927         reportDeferredDiagnostics();
   929         if (!log.hasDiagnosticListener()) {
   930             printCount("error", errorCount());
   931             printCount("warn", warningCount());
   932         }
   933     }
   935     /**
   936      * Set needRootClasses to true, in JavaCompiler subclass constructor
   937      * that want to collect public apis of classes supplied on the command line.
   938      */
   939     protected boolean needRootClasses = false;
   941     /**
   942      * The list of classes explicitly supplied on the command line for compilation.
   943      * Not always populated.
   944      */
   945     private List<JCClassDecl> rootClasses;
   947     /**
   948      * Parses a list of files.
   949      */
   950    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   951        if (shouldStop(CompileState.PARSE))
   952            return List.nil();
   954         //parse all files
   955         ListBuffer<JCCompilationUnit> trees = lb();
   956         Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
   957         for (JavaFileObject fileObject : fileObjects) {
   958             if (!filesSoFar.contains(fileObject)) {
   959                 filesSoFar.add(fileObject);
   960                 trees.append(parse(fileObject));
   961             }
   962         }
   963         return trees.toList();
   964     }
   966     /**
   967      * Enter the symbols found in a list of parse trees if the compilation
   968      * is expected to proceed beyond anno processing into attr.
   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> enterTreesIfNeeded(List<JCCompilationUnit> roots) {
   973        if (shouldStop(CompileState.ATTR))
   974            return List.nil();
   975         return enterTrees(roots);
   976     }
   978     /**
   979      * Enter the symbols found in a list of parse trees.
   980      * As a side-effect, this puts elements on the "todo" list.
   981      * Also stores a list of all top level classes in rootClasses.
   982      */
   983     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   984         //enter symbols for all files
   985         if (!taskListener.isEmpty()) {
   986             for (JCCompilationUnit unit: roots) {
   987                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   988                 taskListener.started(e);
   989             }
   990         }
   992         enter.main(roots);
   994         if (!taskListener.isEmpty()) {
   995             for (JCCompilationUnit unit: roots) {
   996                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   997                 taskListener.finished(e);
   998             }
   999         }
  1001         // If generating source, or if tracking public apis,
  1002         // then remember the classes declared in
  1003         // the original compilation units listed on the command line.
  1004         if (needRootClasses || sourceOutput || stubOutput) {
  1005             ListBuffer<JCClassDecl> cdefs = lb();
  1006             for (JCCompilationUnit unit : roots) {
  1007                 for (List<JCTree> defs = unit.defs;
  1008                      defs.nonEmpty();
  1009                      defs = defs.tail) {
  1010                     if (defs.head instanceof JCClassDecl)
  1011                         cdefs.append((JCClassDecl)defs.head);
  1014             rootClasses = cdefs.toList();
  1017         // Ensure the input files have been recorded. Although this is normally
  1018         // done by readSource, it may not have been done if the trees were read
  1019         // in a prior round of annotation processing, and the trees have been
  1020         // cleaned and are being reused.
  1021         for (JCCompilationUnit unit : roots) {
  1022             inputFiles.add(unit.sourcefile);
  1025         return roots;
  1028     /**
  1029      * Set to true to enable skeleton annotation processing code.
  1030      * Currently, we assume this variable will be replaced more
  1031      * advanced logic to figure out if annotation processing is
  1032      * needed.
  1033      */
  1034     boolean processAnnotations = false;
  1036     Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
  1038     /**
  1039      * Object to handle annotation processing.
  1040      */
  1041     private JavacProcessingEnvironment procEnvImpl = null;
  1043     /**
  1044      * Check if we should process annotations.
  1045      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
  1046      * to catch doc comments, and set keepComments so the parser records them in
  1047      * the compilation unit.
  1049      * @param processors user provided annotation processors to bypass
  1050      * discovery, {@code null} means that no processors were provided
  1051      */
  1052     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
  1053         // Process annotations if processing is not disabled and there
  1054         // is at least one Processor available.
  1055         if (options.isSet(PROC, "none")) {
  1056             processAnnotations = false;
  1057         } else if (procEnvImpl == null) {
  1058             procEnvImpl = JavacProcessingEnvironment.instance(context);
  1059             procEnvImpl.setProcessors(processors);
  1060             processAnnotations = procEnvImpl.atLeastOneProcessor();
  1062             if (processAnnotations) {
  1063                 options.put("save-parameter-names", "save-parameter-names");
  1064                 reader.saveParameterNames = true;
  1065                 keepComments = true;
  1066                 genEndPos = true;
  1067                 if (!taskListener.isEmpty())
  1068                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1069                 deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
  1070             } else { // free resources
  1071                 procEnvImpl.close();
  1076     // TODO: called by JavacTaskImpl
  1077     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
  1078         return processAnnotations(roots, List.<String>nil());
  1081     /**
  1082      * Process any annotations found in the specified compilation units.
  1083      * @param roots a list of compilation units
  1084      * @return an instance of the compiler in which to complete the compilation
  1085      */
  1086     // Implementation note: when this method is called, log.deferredDiagnostics
  1087     // will have been set true by initProcessAnnotations, meaning that any diagnostics
  1088     // that are reported will go into the log.deferredDiagnostics queue.
  1089     // By the time this method exits, log.deferDiagnostics must be set back to false,
  1090     // and all deferredDiagnostics must have been handled: i.e. either reported
  1091     // or determined to be transient, and therefore suppressed.
  1092     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
  1093                                            List<String> classnames) {
  1094         if (shouldStop(CompileState.PROCESS)) {
  1095             // Errors were encountered.
  1096             // Unless all the errors are resolve errors, the errors were parse errors
  1097             // or other errors during enter which cannot be fixed by running
  1098             // any annotation processors.
  1099             if (unrecoverableError()) {
  1100                 deferredDiagnosticHandler.reportDeferredDiagnostics();
  1101                 log.popDiagnosticHandler(deferredDiagnosticHandler);
  1102                 return this;
  1106         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1107         // by initProcessAnnotations
  1109         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1111         if (!processAnnotations) {
  1112             // If there are no annotation processors present, and
  1113             // annotation processing is to occur with compilation,
  1114             // emit a warning.
  1115             if (options.isSet(PROC, "only")) {
  1116                 log.warning("proc.proc-only.requested.no.procs");
  1117                 todo.clear();
  1119             // If not processing annotations, classnames must be empty
  1120             if (!classnames.isEmpty()) {
  1121                 log.error("proc.no.explicit.annotation.processing.requested",
  1122                           classnames);
  1124             Assert.checkNull(deferredDiagnosticHandler);
  1125             return this; // continue regular compilation
  1128         Assert.checkNonNull(deferredDiagnosticHandler);
  1130         try {
  1131             List<ClassSymbol> classSymbols = List.nil();
  1132             List<PackageSymbol> pckSymbols = List.nil();
  1133             if (!classnames.isEmpty()) {
  1134                  // Check for explicit request for annotation
  1135                  // processing
  1136                 if (!explicitAnnotationProcessingRequested()) {
  1137                     log.error("proc.no.explicit.annotation.processing.requested",
  1138                               classnames);
  1139                     deferredDiagnosticHandler.reportDeferredDiagnostics();
  1140                     log.popDiagnosticHandler(deferredDiagnosticHandler);
  1141                     return this; // TODO: Will this halt compilation?
  1142                 } else {
  1143                     boolean errors = false;
  1144                     for (String nameStr : classnames) {
  1145                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
  1146                         if (sym == null ||
  1147                             (sym.kind == Kinds.PCK && !processPcks) ||
  1148                             sym.kind == Kinds.ABSENT_TYP) {
  1149                             log.error("proc.cant.find.class", nameStr);
  1150                             errors = true;
  1151                             continue;
  1153                         try {
  1154                             if (sym.kind == Kinds.PCK)
  1155                                 sym.complete();
  1156                             if (sym.exists()) {
  1157                                 if (sym.kind == Kinds.PCK)
  1158                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1159                                 else
  1160                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1161                                 continue;
  1163                             Assert.check(sym.kind == Kinds.PCK);
  1164                             log.warning("proc.package.does.not.exist", nameStr);
  1165                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1166                         } catch (CompletionFailure e) {
  1167                             log.error("proc.cant.find.class", nameStr);
  1168                             errors = true;
  1169                             continue;
  1172                     if (errors) {
  1173                         deferredDiagnosticHandler.reportDeferredDiagnostics();
  1174                         log.popDiagnosticHandler(deferredDiagnosticHandler);
  1175                         return this;
  1179             try {
  1180                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols,
  1181                         deferredDiagnosticHandler);
  1182                 if (c != this)
  1183                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1184                 // doProcessing will have handled deferred diagnostics
  1185                 return c;
  1186             } finally {
  1187                 procEnvImpl.close();
  1189         } catch (CompletionFailure ex) {
  1190             log.error("cant.access", ex.sym, ex.getDetailValue());
  1191             deferredDiagnosticHandler.reportDeferredDiagnostics();
  1192             log.popDiagnosticHandler(deferredDiagnosticHandler);
  1193             return this;
  1197     private boolean unrecoverableError() {
  1198         if (deferredDiagnosticHandler != null) {
  1199             for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
  1200                 if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
  1201                     return true;
  1204         return false;
  1207     boolean explicitAnnotationProcessingRequested() {
  1208         return
  1209             explicitAnnotationProcessingRequested ||
  1210             explicitAnnotationProcessingRequested(options);
  1213     static boolean explicitAnnotationProcessingRequested(Options options) {
  1214         return
  1215             options.isSet(PROCESSOR) ||
  1216             options.isSet(PROCESSORPATH) ||
  1217             options.isSet(PROC, "only") ||
  1218             options.isSet(XPRINT);
  1221     /**
  1222      * Attribute a list of parse trees, such as found on the "todo" list.
  1223      * Note that attributing classes may cause additional files to be
  1224      * parsed and entered via the SourceCompleter.
  1225      * Attribution of the entries in the list does not stop if any errors occur.
  1226      * @returns a list of environments for attributd classes.
  1227      */
  1228     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1229         ListBuffer<Env<AttrContext>> results = lb();
  1230         while (!envs.isEmpty())
  1231             results.append(attribute(envs.remove()));
  1232         return stopIfError(CompileState.ATTR, results);
  1235     /**
  1236      * Attribute a parse tree.
  1237      * @returns the attributed parse tree
  1238      */
  1239     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1240         if (compileStates.isDone(env, CompileState.ATTR))
  1241             return env;
  1243         if (verboseCompilePolicy)
  1244             printNote("[attribute " + env.enclClass.sym + "]");
  1245         if (verbose)
  1246             log.printVerbose("checking.attribution", env.enclClass.sym);
  1248         if (!taskListener.isEmpty()) {
  1249             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1250             taskListener.started(e);
  1253         JavaFileObject prev = log.useSource(
  1254                                   env.enclClass.sym.sourcefile != null ?
  1255                                   env.enclClass.sym.sourcefile :
  1256                                   env.toplevel.sourcefile);
  1257         try {
  1258             attr.attrib(env);
  1259             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1260                 //if in fail-over mode, ensure that AST expression nodes
  1261                 //are correctly initialized (e.g. they have a type/symbol)
  1262                 attr.postAttr(env.tree);
  1264             compileStates.put(env, CompileState.ATTR);
  1265             if (rootClasses != null && rootClasses.contains(env.enclClass)) {
  1266                 // This was a class that was explicitly supplied for compilation.
  1267                 // If we want to capture the public api of this class,
  1268                 // then now is a good time to do it.
  1269                 reportPublicApi(env.enclClass.sym);
  1272         finally {
  1273             log.useSource(prev);
  1276         return env;
  1279     /** Report the public api of a class that was supplied explicitly for compilation,
  1280      *  for example on the command line to javac.
  1281      * @param sym The symbol of the class.
  1282      */
  1283     public void reportPublicApi(ClassSymbol sym) {
  1284        // Override to collect the reported public api.
  1287     /**
  1288      * Perform dataflow checks on attributed parse trees.
  1289      * These include checks for definite assignment and unreachable statements.
  1290      * If any errors occur, an empty list will be returned.
  1291      * @returns the list of attributed parse trees
  1292      */
  1293     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1294         ListBuffer<Env<AttrContext>> results = lb();
  1295         for (Env<AttrContext> env: envs) {
  1296             flow(env, results);
  1298         return stopIfError(CompileState.FLOW, results);
  1301     /**
  1302      * Perform dataflow checks on an attributed parse tree.
  1303      */
  1304     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1305         ListBuffer<Env<AttrContext>> results = lb();
  1306         flow(env, results);
  1307         return stopIfError(CompileState.FLOW, results);
  1310     /**
  1311      * Perform dataflow checks on an attributed parse tree.
  1312      */
  1313     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1314         try {
  1315             if (shouldStop(CompileState.FLOW))
  1316                 return;
  1318             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1319                 results.add(env);
  1320                 return;
  1323             if (verboseCompilePolicy)
  1324                 printNote("[flow " + env.enclClass.sym + "]");
  1325             JavaFileObject prev = log.useSource(
  1326                                                 env.enclClass.sym.sourcefile != null ?
  1327                                                 env.enclClass.sym.sourcefile :
  1328                                                 env.toplevel.sourcefile);
  1329             try {
  1330                 make.at(Position.FIRSTPOS);
  1331                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1332                 flow.analyzeTree(env, localMake);
  1333                 compileStates.put(env, CompileState.FLOW);
  1335                 if (shouldStop(CompileState.FLOW))
  1336                     return;
  1338                 results.add(env);
  1340             finally {
  1341                 log.useSource(prev);
  1344         finally {
  1345             if (!taskListener.isEmpty()) {
  1346                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1347                 taskListener.finished(e);
  1352     /**
  1353      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1354      * for source or code generation.
  1355      * If any errors occur, an empty list will be returned.
  1356      * @returns a list containing the classes to be generated
  1357      */
  1358     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1359         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1360         for (Env<AttrContext> env: envs)
  1361             desugar(env, results);
  1362         return stopIfError(CompileState.FLOW, results);
  1365     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1366             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1368     /**
  1369      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1370      * for source or code generation. If the file was not listed on the command line,
  1371      * the current implicitSourcePolicy is taken into account.
  1372      * The preparation stops as soon as an error is found.
  1373      */
  1374     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1375         if (shouldStop(CompileState.TRANSTYPES))
  1376             return;
  1378         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1379                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1380             return;
  1383         if (compileStates.isDone(env, CompileState.LOWER)) {
  1384             results.addAll(desugaredEnvs.get(env));
  1385             return;
  1388         /**
  1389          * Ensure that superclasses of C are desugared before C itself. This is
  1390          * required for two reasons: (i) as erasure (TransTypes) destroys
  1391          * information needed in flow analysis and (ii) as some checks carried
  1392          * out during lowering require that all synthetic fields/methods have
  1393          * already been added to C and its superclasses.
  1394          */
  1395         class ScanNested extends TreeScanner {
  1396             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1397             @Override
  1398             public void visitClassDef(JCClassDecl node) {
  1399                 Type st = types.supertype(node.sym.type);
  1400                 boolean envForSuperTypeFound = false;
  1401                 while (!envForSuperTypeFound && st.hasTag(CLASS)) {
  1402                     ClassSymbol c = st.tsym.outermostClass();
  1403                     Env<AttrContext> stEnv = enter.getEnv(c);
  1404                     if (stEnv != null && env != stEnv) {
  1405                         if (dependencies.add(stEnv)) {
  1406                             scan(stEnv.tree);
  1408                         envForSuperTypeFound = true;
  1410                     st = types.supertype(st);
  1412                 super.visitClassDef(node);
  1415         ScanNested scanner = new ScanNested();
  1416         scanner.scan(env.tree);
  1417         for (Env<AttrContext> dep: scanner.dependencies) {
  1418         if (!compileStates.isDone(dep, CompileState.FLOW))
  1419             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1422         //We need to check for error another time as more classes might
  1423         //have been attributed and analyzed at this stage
  1424         if (shouldStop(CompileState.TRANSTYPES))
  1425             return;
  1427         if (verboseCompilePolicy)
  1428             printNote("[desugar " + env.enclClass.sym + "]");
  1430         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1431                                   env.enclClass.sym.sourcefile :
  1432                                   env.toplevel.sourcefile);
  1433         try {
  1434             //save tree prior to rewriting
  1435             JCTree untranslated = env.tree;
  1437             make.at(Position.FIRSTPOS);
  1438             TreeMaker localMake = make.forToplevel(env.toplevel);
  1440             if (env.tree instanceof JCCompilationUnit) {
  1441                 if (!(stubOutput || sourceOutput || printFlat)) {
  1442                     if (shouldStop(CompileState.LOWER))
  1443                         return;
  1444                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1445                     if (pdef.head != null) {
  1446                         Assert.check(pdef.tail.isEmpty());
  1447                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1450                 return;
  1453             if (stubOutput) {
  1454                 //emit stub Java source file, only for compilation
  1455                 //units enumerated explicitly on the command line
  1456                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1457                 if (untranslated instanceof JCClassDecl &&
  1458                     rootClasses.contains((JCClassDecl)untranslated) &&
  1459                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1460                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1461                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1463                 return;
  1466             if (shouldStop(CompileState.TRANSTYPES))
  1467                 return;
  1469             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1470             compileStates.put(env, CompileState.TRANSTYPES);
  1472             if (source.allowLambda()) {
  1473                 if (shouldStop(CompileState.UNLAMBDA))
  1474                     return;
  1476                 env.tree = lambdaToMethod.translateTopLevelClass(env, env.tree, localMake);
  1477                 compileStates.put(env, CompileState.UNLAMBDA);
  1480             if (shouldStop(CompileState.LOWER))
  1481                 return;
  1483             if (sourceOutput) {
  1484                 //emit standard Java source file, only for compilation
  1485                 //units enumerated explicitly on the command line
  1486                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1487                 if (untranslated instanceof JCClassDecl &&
  1488                     rootClasses.contains((JCClassDecl)untranslated)) {
  1489                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1491                 return;
  1494             //translate out inner classes
  1495             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1496             compileStates.put(env, CompileState.LOWER);
  1498             if (shouldStop(CompileState.LOWER))
  1499                 return;
  1501             //generate code for each class
  1502             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1503                 JCClassDecl cdef = (JCClassDecl)l.head;
  1504                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1507         finally {
  1508             log.useSource(prev);
  1513     /** Generates the source or class file for a list of classes.
  1514      * The decision to generate a source file or a class file is
  1515      * based upon the compiler's options.
  1516      * Generation stops if an error occurs while writing files.
  1517      */
  1518     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1519         generate(queue, null);
  1522     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1523         if (shouldStop(CompileState.GENERATE))
  1524             return;
  1526         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1528         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1529             Env<AttrContext> env = x.fst;
  1530             JCClassDecl cdef = x.snd;
  1532             if (verboseCompilePolicy) {
  1533                 printNote("[generate "
  1534                                + (usePrintSource ? " source" : "code")
  1535                                + " " + cdef.sym + "]");
  1538             if (!taskListener.isEmpty()) {
  1539                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1540                 taskListener.started(e);
  1543             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1544                                       env.enclClass.sym.sourcefile :
  1545                                       env.toplevel.sourcefile);
  1546             try {
  1547                 JavaFileObject file;
  1548                 if (usePrintSource)
  1549                     file = printSource(env, cdef);
  1550                 else {
  1551                     if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
  1552                             && jniWriter.needsHeader(cdef.sym)) {
  1553                         jniWriter.write(cdef.sym);
  1555                     file = genCode(env, cdef);
  1557                 if (results != null && file != null)
  1558                     results.add(file);
  1559             } catch (IOException ex) {
  1560                 log.error(cdef.pos(), "class.cant.write",
  1561                           cdef.sym, ex.getMessage());
  1562                 return;
  1563             } finally {
  1564                 log.useSource(prev);
  1567             if (!taskListener.isEmpty()) {
  1568                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1569                 taskListener.finished(e);
  1574         // where
  1575         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1576             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1577             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1578             for (Env<AttrContext> env: envs) {
  1579                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1580                 if (sublist == null) {
  1581                     sublist = new ListBuffer<Env<AttrContext>>();
  1582                     map.put(env.toplevel, sublist);
  1584                 sublist.add(env);
  1586             return map;
  1589         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1590             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1591             class MethodBodyRemover extends TreeTranslator {
  1592                 @Override
  1593                 public void visitMethodDef(JCMethodDecl tree) {
  1594                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1595                     for (JCVariableDecl vd : tree.params)
  1596                         vd.mods.flags &= ~Flags.FINAL;
  1597                     tree.body = null;
  1598                     super.visitMethodDef(tree);
  1600                 @Override
  1601                 public void visitVarDef(JCVariableDecl tree) {
  1602                     if (tree.init != null && tree.init.type.constValue() == null)
  1603                         tree.init = null;
  1604                     super.visitVarDef(tree);
  1606                 @Override
  1607                 public void visitClassDef(JCClassDecl tree) {
  1608                     ListBuffer<JCTree> newdefs = lb();
  1609                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1610                         JCTree t = it.head;
  1611                         switch (t.getTag()) {
  1612                         case CLASSDEF:
  1613                             if (isInterface ||
  1614                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1615                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1616                                 newdefs.append(t);
  1617                             break;
  1618                         case METHODDEF:
  1619                             if (isInterface ||
  1620                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1621                                 ((JCMethodDecl) t).sym.name == names.init ||
  1622                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1623                                 newdefs.append(t);
  1624                             break;
  1625                         case VARDEF:
  1626                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1627                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1628                                 newdefs.append(t);
  1629                             break;
  1630                         default:
  1631                             break;
  1634                     tree.defs = newdefs.toList();
  1635                     super.visitClassDef(tree);
  1638             MethodBodyRemover r = new MethodBodyRemover();
  1639             return r.translate(cdef);
  1642     public void reportDeferredDiagnostics() {
  1643         if (errorCount() == 0
  1644                 && annotationProcessingOccurred
  1645                 && implicitSourceFilesRead
  1646                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1647             if (explicitAnnotationProcessingRequested())
  1648                 log.warning("proc.use.implicit");
  1649             else
  1650                 log.warning("proc.use.proc.or.implicit");
  1652         chk.reportDeferredDiagnostics();
  1653         if (log.compressedOutput) {
  1654             log.mandatoryNote(null, "compressed.diags");
  1658     /** Close the compiler, flushing the logs
  1659      */
  1660     public void close() {
  1661         close(true);
  1664     public void close(boolean disposeNames) {
  1665         rootClasses = null;
  1666         reader = null;
  1667         make = null;
  1668         writer = null;
  1669         enter = null;
  1670         if (todo != null)
  1671             todo.clear();
  1672         todo = null;
  1673         parserFactory = null;
  1674         syms = null;
  1675         source = null;
  1676         attr = null;
  1677         chk = null;
  1678         gen = null;
  1679         flow = null;
  1680         transTypes = null;
  1681         lower = null;
  1682         annotate = null;
  1683         types = null;
  1685         log.flush();
  1686         try {
  1687             fileManager.flush();
  1688         } catch (IOException e) {
  1689             throw new Abort(e);
  1690         } finally {
  1691             if (names != null && disposeNames)
  1692                 names.dispose();
  1693             names = null;
  1695             for (Closeable c: closeables) {
  1696                 try {
  1697                     c.close();
  1698                 } catch (IOException e) {
  1699                     // When javac uses JDK 7 as a baseline, this code would be
  1700                     // better written to set any/all exceptions from all the
  1701                     // Closeables as suppressed exceptions on the FatalError
  1702                     // that is thrown.
  1703                     JCDiagnostic msg = diagFactory.fragment("fatal.err.cant.close");
  1704                     throw new FatalError(msg, e);
  1707             closeables = List.nil();
  1711     protected void printNote(String lines) {
  1712         log.printRawLines(Log.WriterKind.NOTICE, lines);
  1715     /** Print numbers of errors and warnings.
  1716      */
  1717     public void printCount(String kind, int count) {
  1718         if (count != 0) {
  1719             String key;
  1720             if (count == 1)
  1721                 key = "count." + kind;
  1722             else
  1723                 key = "count." + kind + ".plural";
  1724             log.printLines(WriterKind.ERROR, key, String.valueOf(count));
  1725             log.flush(Log.WriterKind.ERROR);
  1729     private static long now() {
  1730         return System.currentTimeMillis();
  1733     private static long elapsed(long then) {
  1734         return now() - then;
  1737     public void initRound(JavaCompiler prev) {
  1738         genEndPos = prev.genEndPos;
  1739         keepComments = prev.keepComments;
  1740         start_msec = prev.start_msec;
  1741         hasBeenUsed = true;
  1742         closeables = prev.closeables;
  1743         prev.closeables = List.nil();
  1744         shouldStopPolicyIfError = prev.shouldStopPolicyIfError;
  1745         shouldStopPolicyIfNoError = prev.shouldStopPolicyIfNoError;
  1748     public static void enableLogging() {
  1749         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1750         logger.setLevel(Level.ALL);
  1751         for (Handler h : logger.getParent().getHandlers()) {
  1752             h.setLevel(Level.ALL);

mercurial