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

Fri, 05 Oct 2012 14:35:24 +0100

author
mcimadamore
date
Fri, 05 Oct 2012 14:35:24 +0100
changeset 1348
573ceb23beeb
parent 1347
1408af4cd8b0
child 1358
fc123bdeddb8
permissions
-rw-r--r--

7177385: Add attribution support for lambda expressions
Summary: Add support for function descriptor lookup, functional interface inference and lambda expression type-checking
Reviewed-by: jjg, dlsmith

     1 /*
     2  * Copyright (c) 1999, 2012, 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.main.Option.*;
    67 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    68 import static com.sun.tools.javac.util.ListBuffer.lb;
    71 /** This class could be the main entry point for GJC when GJC is used as a
    72  *  component in a larger software system. It provides operations to
    73  *  construct a new compiler, and to run a new compiler on a set of source
    74  *  files.
    75  *
    76  *  <p><b>This is NOT part of any supported API.
    77  *  If you write code that depends on this, you do so at your own risk.
    78  *  This code and its internal interfaces are subject to change or
    79  *  deletion without notice.</b>
    80  */
    81 public class JavaCompiler implements ClassReader.SourceCompleter {
    82     /** The context key for the compiler. */
    83     protected static final Context.Key<JavaCompiler> compilerKey =
    84         new Context.Key<JavaCompiler>();
    86     /** Get the JavaCompiler instance for this context. */
    87     public static JavaCompiler instance(Context context) {
    88         JavaCompiler instance = context.get(compilerKey);
    89         if (instance == null)
    90             instance = new JavaCompiler(context);
    91         return instance;
    92     }
    94     /** The current version number as a string.
    95      */
    96     public static String version() {
    97         return version("release");  // mm.nn.oo[-milestone]
    98     }
   100     /** The current full version number as a string.
   101      */
   102     public static String fullVersion() {
   103         return version("full"); // mm.mm.oo[-milestone]-build
   104     }
   106     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   107     private static ResourceBundle versionRB;
   109     private static String version(String key) {
   110         if (versionRB == null) {
   111             try {
   112                 versionRB = ResourceBundle.getBundle(versionRBName);
   113             } catch (MissingResourceException e) {
   114                 return Log.getLocalizedString("version.not.available");
   115             }
   116         }
   117         try {
   118             return versionRB.getString(key);
   119         }
   120         catch (MissingResourceException e) {
   121             return Log.getLocalizedString("version.not.available");
   122         }
   123     }
   125     /**
   126      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   127      * are connected. Each individual file is processed by each phase in turn,
   128      * but with different compile policies, you can control the order in which
   129      * each class is processed through its next phase.
   130      *
   131      * <p>Generally speaking, the compiler will "fail fast" in the face of
   132      * errors, although not aggressively so. flow, desugar, etc become no-ops
   133      * once any errors have occurred. No attempt is currently made to determine
   134      * if it might be safe to process a class through its next phase because
   135      * it does not depend on any unrelated errors that might have occurred.
   136      */
   137     protected static enum CompilePolicy {
   138         /**
   139          * Just attribute the parse trees.
   140          */
   141         ATTR_ONLY,
   143         /**
   144          * Just attribute and do flow analysis on the parse trees.
   145          * This should catch most user errors.
   146          */
   147         CHECK_ONLY,
   149         /**
   150          * Attribute everything, then do flow analysis for everything,
   151          * then desugar everything, and only then generate output.
   152          * This means no output will be generated if there are any
   153          * errors in any classes.
   154          */
   155         SIMPLE,
   157         /**
   158          * Groups the classes for each source file together, then process
   159          * each group in a manner equivalent to the {@code SIMPLE} policy.
   160          * This means no output will be generated if there are any
   161          * errors in any of the classes in a source file.
   162          */
   163         BY_FILE,
   165         /**
   166          * Completely process each entry on the todo list in turn.
   167          * -- this is the same for 1.5.
   168          * Means output might be generated for some classes in a compilation unit
   169          * and not others.
   170          */
   171         BY_TODO;
   173         static CompilePolicy decode(String option) {
   174             if (option == null)
   175                 return DEFAULT_COMPILE_POLICY;
   176             else if (option.equals("attr"))
   177                 return ATTR_ONLY;
   178             else if (option.equals("check"))
   179                 return CHECK_ONLY;
   180             else if (option.equals("simple"))
   181                 return SIMPLE;
   182             else if (option.equals("byfile"))
   183                 return BY_FILE;
   184             else if (option.equals("bytodo"))
   185                 return BY_TODO;
   186             else
   187                 return DEFAULT_COMPILE_POLICY;
   188         }
   189     }
   191     private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   193     protected static enum ImplicitSourcePolicy {
   194         /** Don't generate or process implicitly read source files. */
   195         NONE,
   196         /** Generate classes for implicitly read source files. */
   197         CLASS,
   198         /** Like CLASS, but generate warnings if annotation processing occurs */
   199         UNSET;
   201         static ImplicitSourcePolicy decode(String option) {
   202             if (option == null)
   203                 return UNSET;
   204             else if (option.equals("none"))
   205                 return NONE;
   206             else if (option.equals("class"))
   207                 return CLASS;
   208             else
   209                 return UNSET;
   210         }
   211     }
   213     /** The log to be used for error reporting.
   214      */
   215     public Log log;
   217     /** Factory for creating diagnostic objects
   218      */
   219     JCDiagnostic.Factory diagFactory;
   221     /** The tree factory module.
   222      */
   223     protected TreeMaker make;
   225     /** The class reader.
   226      */
   227     protected ClassReader reader;
   229     /** The class writer.
   230      */
   231     protected ClassWriter writer;
   233     /** The native header writer.
   234      */
   235     protected JNIWriter jniWriter;
   237     /** The module for the symbol table entry phases.
   238      */
   239     protected Enter enter;
   241     /** The symbol table.
   242      */
   243     protected Symtab syms;
   245     /** The language version.
   246      */
   247     protected Source source;
   249     /** The module for code generation.
   250      */
   251     protected Gen gen;
   253     /** The name table.
   254      */
   255     protected Names names;
   257     /** The attributor.
   258      */
   259     protected Attr attr;
   261     /** The attributor.
   262      */
   263     protected Check chk;
   265     /** The flow analyzer.
   266      */
   267     protected Flow flow;
   269     /** The type eraser.
   270      */
   271     protected TransTypes transTypes;
   273     /** The syntactic sugar desweetener.
   274      */
   275     protected Lower lower;
   277     /** The annotation annotator.
   278      */
   279     protected Annotate annotate;
   281     /** Force a completion failure on this name
   282      */
   283     protected final Name completionFailureName;
   285     /** Type utilities.
   286      */
   287     protected Types types;
   289     /** Access to file objects.
   290      */
   291     protected JavaFileManager fileManager;
   293     /** Factory for parsers.
   294      */
   295     protected ParserFactory parserFactory;
   297     /** Broadcasting listener for progress events
   298      */
   299     protected MultiTaskListener taskListener;
   301     /**
   302      * Annotation processing may require and provide a new instance
   303      * of the compiler to be used for the analyze and generate phases.
   304      */
   305     protected JavaCompiler delegateCompiler;
   307     /**
   308      * Command line options.
   309      */
   310     protected Options options;
   312     protected Context context;
   314     /**
   315      * Flag set if any annotation processing occurred.
   316      **/
   317     protected boolean annotationProcessingOccurred;
   319     /**
   320      * Flag set if any implicit source files read.
   321      **/
   322     protected boolean implicitSourceFilesRead;
   324     /** Construct a new compiler using a shared context.
   325      */
   326     public JavaCompiler(Context context) {
   327         this.context = context;
   328         context.put(compilerKey, this);
   330         // if fileManager not already set, register the JavacFileManager to be used
   331         if (context.get(JavaFileManager.class) == null)
   332             JavacFileManager.preRegister(context);
   334         names = Names.instance(context);
   335         log = Log.instance(context);
   336         diagFactory = JCDiagnostic.Factory.instance(context);
   337         reader = ClassReader.instance(context);
   338         make = TreeMaker.instance(context);
   339         writer = ClassWriter.instance(context);
   340         jniWriter = JNIWriter.instance(context);
   341         enter = Enter.instance(context);
   342         todo = Todo.instance(context);
   344         fileManager = context.get(JavaFileManager.class);
   345         parserFactory = ParserFactory.instance(context);
   347         try {
   348             // catch completion problems with predefineds
   349             syms = Symtab.instance(context);
   350         } catch (CompletionFailure ex) {
   351             // inlined Check.completionError as it is not initialized yet
   352             log.error("cant.access", ex.sym, ex.getDetailValue());
   353             if (ex instanceof ClassReader.BadClassFile)
   354                 throw new Abort();
   355         }
   356         source = Source.instance(context);
   357         attr = Attr.instance(context);
   358         chk = Check.instance(context);
   359         gen = Gen.instance(context);
   360         flow = Flow.instance(context);
   361         transTypes = TransTypes.instance(context);
   362         lower = Lower.instance(context);
   363         annotate = Annotate.instance(context);
   364         types = Types.instance(context);
   365         taskListener = MultiTaskListener.instance(context);
   367         reader.sourceCompleter = this;
   369         options = Options.instance(context);
   371         verbose       = options.isSet(VERBOSE);
   372         sourceOutput  = options.isSet(PRINTSOURCE); // used to be -s
   373         stubOutput    = options.isSet("-stubs");
   374         relax         = options.isSet("-relax");
   375         printFlat     = options.isSet("-printflat");
   376         attrParseOnly = options.isSet("-attrparseonly");
   377         encoding      = options.get(ENCODING);
   378         lineDebugInfo = options.isUnset(G_CUSTOM) ||
   379                         options.isSet(G_CUSTOM, "lines");
   380         genEndPos     = options.isSet(XJCOV) ||
   381                         context.get(DiagnosticListener.class) != null;
   382         devVerbose    = options.isSet("dev");
   383         processPcks   = options.isSet("process.packages");
   384         werror        = options.isSet(WERROR);
   386         if (source.compareTo(Source.DEFAULT) < 0) {
   387             if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   388                 if (fileManager instanceof BaseFileManager) {
   389                     if (((BaseFileManager) fileManager).isDefaultBootClassPath())
   390                         log.warning(LintCategory.OPTIONS, "source.no.bootclasspath", source.name);
   391                 }
   392             }
   393         }
   395         verboseCompilePolicy = options.isSet("verboseCompilePolicy");
   397         if (attrParseOnly)
   398             compilePolicy = CompilePolicy.ATTR_ONLY;
   399         else
   400             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   402         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   404         completionFailureName =
   405             options.isSet("failcomplete")
   406             ? names.fromString(options.get("failcomplete"))
   407             : null;
   409         shouldStopPolicyIfError =
   410             options.isSet("shouldStopPolicy") // backwards compatible
   411             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   412             : options.isSet("shouldStopPolicyIfError")
   413             ? CompileState.valueOf(options.get("shouldStopPolicyIfError"))
   414             : CompileState.INIT;
   415         shouldStopPolicyIfNoError =
   416             options.isSet("shouldStopPolicyIfNoError")
   417             ? CompileState.valueOf(options.get("shouldStopPolicyIfNoError"))
   418             : CompileState.GENERATE;
   420         if (options.isUnset("oldDiags"))
   421             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   422     }
   424     /* Switches:
   425      */
   427     /** Verbose output.
   428      */
   429     public boolean verbose;
   431     /** Emit plain Java source files rather than class files.
   432      */
   433     public boolean sourceOutput;
   435     /** Emit stub source files rather than class files.
   436      */
   437     public boolean stubOutput;
   439     /** Generate attributed parse tree only.
   440      */
   441     public boolean attrParseOnly;
   443     /** Switch: relax some constraints for producing the jsr14 prototype.
   444      */
   445     boolean relax;
   447     /** Debug switch: Emit Java sources after inner class flattening.
   448      */
   449     public boolean printFlat;
   451     /** The encoding to be used for source input.
   452      */
   453     public String encoding;
   455     /** Generate code with the LineNumberTable attribute for debugging
   456      */
   457     public boolean lineDebugInfo;
   459     /** Switch: should we store the ending positions?
   460      */
   461     public boolean genEndPos;
   463     /** Switch: should we debug ignored exceptions
   464      */
   465     protected boolean devVerbose;
   467     /** Switch: should we (annotation) process packages as well
   468      */
   469     protected boolean processPcks;
   471     /** Switch: treat warnings as errors
   472      */
   473     protected boolean werror;
   475     /** Switch: is annotation processing requested explitly via
   476      * CompilationTask.setProcessors?
   477      */
   478     protected boolean explicitAnnotationProcessingRequested = false;
   480     /**
   481      * The policy for the order in which to perform the compilation
   482      */
   483     protected CompilePolicy compilePolicy;
   485     /**
   486      * The policy for what to do with implicitly read source files
   487      */
   488     protected ImplicitSourcePolicy implicitSourcePolicy;
   490     /**
   491      * Report activity related to compilePolicy
   492      */
   493     public boolean verboseCompilePolicy;
   495     /**
   496      * Policy of how far to continue compilation after errors have occurred.
   497      * Set this to minimum CompileState (INIT) to stop as soon as possible
   498      * after errors.
   499      */
   500     public CompileState shouldStopPolicyIfError;
   502     /**
   503      * Policy of how far to continue compilation when no errors have occurred.
   504      * Set this to maximum CompileState (GENERATE) to perform full compilation.
   505      * Set this lower to perform partial compilation, such as -proc:only.
   506      */
   507     public CompileState shouldStopPolicyIfNoError;
   509     /** A queue of all as yet unattributed classes.oLo
   510      */
   511     public Todo todo;
   513     /** A list of items to be closed when the compilation is complete.
   514      */
   515     public List<Closeable> closeables = List.nil();
   517     /** Ordered list of compiler phases for each compilation unit. */
   518     public enum CompileState {
   519         INIT(0),
   520         PARSE(1),
   521         ENTER(2),
   522         PROCESS(3),
   523         ATTR(4),
   524         FLOW(5),
   525         TRANSTYPES(6),
   526         LOWER(7),
   527         GENERATE(8);
   528         CompileState(int value) {
   529             this.value = value;
   530         }
   531         boolean isAfter(CompileState other) {
   532             return value > other.value;
   533         }
   534         public static CompileState max(CompileState a, CompileState b) {
   535             return a.value > b.value ? a : b;
   536         }
   537         private int value;
   538     };
   539     /** Partial map to record which compiler phases have been executed
   540      * for each compilation unit. Used for ATTR and FLOW phases.
   541      */
   542     protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
   543         private static final long serialVersionUID = 1812267524140424433L;
   544         boolean isDone(Env<AttrContext> env, CompileState cs) {
   545             CompileState ecs = get(env);
   546             return (ecs != null) && !cs.isAfter(ecs);
   547         }
   548     }
   549     private CompileStates compileStates = new CompileStates();
   551     /** The set of currently compiled inputfiles, needed to ensure
   552      *  we don't accidentally overwrite an input file when -s is set.
   553      *  initialized by `compile'.
   554      */
   555     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   557     protected boolean shouldStop(CompileState cs) {
   558         CompileState shouldStopPolicy = (errorCount() > 0 || unrecoverableError())
   559             ? shouldStopPolicyIfError
   560             : shouldStopPolicyIfNoError;
   561         return cs.isAfter(shouldStopPolicy);
   562     }
   564     /** The number of errors reported so far.
   565      */
   566     public int errorCount() {
   567         if (delegateCompiler != null && delegateCompiler != this)
   568             return delegateCompiler.errorCount();
   569         else {
   570             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   571                 log.error("warnings.and.werror");
   572             }
   573         }
   574         return log.nerrors;
   575     }
   577     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   578         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   579     }
   581     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   582         return shouldStop(cs) ? List.<T>nil() : list;
   583     }
   585     /** The number of warnings reported so far.
   586      */
   587     public int warningCount() {
   588         if (delegateCompiler != null && delegateCompiler != this)
   589             return delegateCompiler.warningCount();
   590         else
   591             return log.nwarnings;
   592     }
   594     /** Try to open input stream with given name.
   595      *  Report an error if this fails.
   596      *  @param filename   The file name of the input stream to be opened.
   597      */
   598     public CharSequence readSource(JavaFileObject filename) {
   599         try {
   600             inputFiles.add(filename);
   601             return filename.getCharContent(false);
   602         } catch (IOException e) {
   603             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   604             return null;
   605         }
   606     }
   608     /** Parse contents of input stream.
   609      *  @param filename     The name of the file from which input stream comes.
   610      *  @param input        The input stream to be parsed.
   611      */
   612     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   613         long msec = now();
   614         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   615                                       null, List.<JCTree>nil());
   616         if (content != null) {
   617             if (verbose) {
   618                 log.printVerbose("parsing.started", filename);
   619             }
   620             if (!taskListener.isEmpty()) {
   621                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   622                 taskListener.started(e);
   623             }
   624             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   625             tree = parser.parseCompilationUnit();
   626             if (verbose) {
   627                 log.printVerbose("parsing.done", Long.toString(elapsed(msec)));
   628             }
   629         }
   631         tree.sourcefile = filename;
   633         if (content != null && !taskListener.isEmpty()) {
   634             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   635             taskListener.finished(e);
   636         }
   638         return tree;
   639     }
   640     // where
   641         public boolean keepComments = false;
   642         protected boolean keepComments() {
   643             return keepComments || sourceOutput || stubOutput;
   644         }
   647     /** Parse contents of file.
   648      *  @param filename     The name of the file to be parsed.
   649      */
   650     @Deprecated
   651     public JCTree.JCCompilationUnit parse(String filename) {
   652         JavacFileManager fm = (JavacFileManager)fileManager;
   653         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   654     }
   656     /** Parse contents of file.
   657      *  @param filename     The name of the file to be parsed.
   658      */
   659     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   660         JavaFileObject prev = log.useSource(filename);
   661         try {
   662             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   663             if (t.endPositions != null)
   664                 log.setEndPosTable(filename, t.endPositions);
   665             return t;
   666         } finally {
   667             log.useSource(prev);
   668         }
   669     }
   671     /** Resolve an identifier which may be the binary name of a class or
   672      * the Java name of a class or package.
   673      * @param name      The name to resolve
   674      */
   675     public Symbol resolveBinaryNameOrIdent(String name) {
   676         try {
   677             Name flatname = names.fromString(name.replace("/", "."));
   678             return reader.loadClass(flatname);
   679         } catch (CompletionFailure ignore) {
   680             return resolveIdent(name);
   681         }
   682     }
   684     /** Resolve an identifier.
   685      * @param name      The identifier to resolve
   686      */
   687     public Symbol resolveIdent(String name) {
   688         if (name.equals(""))
   689             return syms.errSymbol;
   690         JavaFileObject prev = log.useSource(null);
   691         try {
   692             JCExpression tree = null;
   693             for (String s : name.split("\\.", -1)) {
   694                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   695                     return syms.errSymbol;
   696                 tree = (tree == null) ? make.Ident(names.fromString(s))
   697                                       : make.Select(tree, names.fromString(s));
   698             }
   699             JCCompilationUnit toplevel =
   700                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   701             toplevel.packge = syms.unnamedPackage;
   702             return attr.attribIdent(tree, toplevel);
   703         } finally {
   704             log.useSource(prev);
   705         }
   706     }
   708     /** Emit plain Java source for a class.
   709      *  @param env    The attribution environment of the outermost class
   710      *                containing this class.
   711      *  @param cdef   The class definition to be printed.
   712      */
   713     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   714         JavaFileObject outFile
   715             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   716                                                cdef.sym.flatname.toString(),
   717                                                JavaFileObject.Kind.SOURCE,
   718                                                null);
   719         if (inputFiles.contains(outFile)) {
   720             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   721             return null;
   722         } else {
   723             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   724             try {
   725                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   726                 if (verbose)
   727                     log.printVerbose("wrote.file", outFile);
   728             } finally {
   729                 out.close();
   730             }
   731             return outFile;
   732         }
   733     }
   735     /** Generate code and emit a class file for a given class
   736      *  @param env    The attribution environment of the outermost class
   737      *                containing this class.
   738      *  @param cdef   The class definition from which code is generated.
   739      */
   740     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   741         try {
   742             if (gen.genClass(env, cdef) && (errorCount() == 0))
   743                 return writer.writeClass(cdef.sym);
   744         } catch (ClassWriter.PoolOverflow ex) {
   745             log.error(cdef.pos(), "limit.pool");
   746         } catch (ClassWriter.StringOverflow ex) {
   747             log.error(cdef.pos(), "limit.string.overflow",
   748                       ex.value.substring(0, 20));
   749         } catch (CompletionFailure ex) {
   750             chk.completionError(cdef.pos(), ex);
   751         }
   752         return null;
   753     }
   755     /** Complete compiling a source file that has been accessed
   756      *  by the class file reader.
   757      *  @param c          The class the source file of which needs to be compiled.
   758      *  @param filename   The name of the source file.
   759      *  @param f          An input stream that reads the source file.
   760      */
   761     public void complete(ClassSymbol c) throws CompletionFailure {
   762 //      System.err.println("completing " + c);//DEBUG
   763         if (completionFailureName == c.fullname) {
   764             throw new CompletionFailure(c, "user-selected completion failure by class name");
   765         }
   766         JCCompilationUnit tree;
   767         JavaFileObject filename = c.classfile;
   768         JavaFileObject prev = log.useSource(filename);
   770         try {
   771             tree = parse(filename, filename.getCharContent(false));
   772         } catch (IOException e) {
   773             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   774             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   775         } finally {
   776             log.useSource(prev);
   777         }
   779         if (!taskListener.isEmpty()) {
   780             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   781             taskListener.started(e);
   782         }
   784         enter.complete(List.of(tree), c);
   786         if (!taskListener.isEmpty()) {
   787             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   788             taskListener.finished(e);
   789         }
   791         if (enter.getEnv(c) == null) {
   792             boolean isPkgInfo =
   793                 tree.sourcefile.isNameCompatible("package-info",
   794                                                  JavaFileObject.Kind.SOURCE);
   795             if (isPkgInfo) {
   796                 if (enter.getEnv(tree.packge) == null) {
   797                     JCDiagnostic diag =
   798                         diagFactory.fragment("file.does.not.contain.package",
   799                                                  c.location());
   800                     throw reader.new BadClassFile(c, filename, diag);
   801                 }
   802             } else {
   803                 JCDiagnostic diag =
   804                         diagFactory.fragment("file.doesnt.contain.class",
   805                                             c.getQualifiedName());
   806                 throw reader.new BadClassFile(c, filename, diag);
   807             }
   808         }
   810         implicitSourceFilesRead = true;
   811     }
   813     /** Track when the JavaCompiler has been used to compile something. */
   814     private boolean hasBeenUsed = false;
   815     private long start_msec = 0;
   816     public long elapsed_msec = 0;
   818     public void compile(List<JavaFileObject> sourceFileObject)
   819         throws Throwable {
   820         compile(sourceFileObject, List.<String>nil(), null);
   821     }
   823     /**
   824      * Main method: compile a list of files, return all compiled classes
   825      *
   826      * @param sourceFileObjects file objects to be compiled
   827      * @param classnames class names to process for annotations
   828      * @param processors user provided annotation processors to bypass
   829      * discovery, {@code null} means that no processors were provided
   830      */
   831     public void compile(List<JavaFileObject> sourceFileObjects,
   832                         List<String> classnames,
   833                         Iterable<? extends Processor> processors)
   834     {
   835         if (processors != null && processors.iterator().hasNext())
   836             explicitAnnotationProcessingRequested = true;
   837         // as a JavaCompiler can only be used once, throw an exception if
   838         // it has been used before.
   839         if (hasBeenUsed)
   840             throw new AssertionError("attempt to reuse JavaCompiler");
   841         hasBeenUsed = true;
   843         // forcibly set the equivalent of -Xlint:-options, so that no further
   844         // warnings about command line options are generated from this point on
   845         options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
   846         options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);
   848         start_msec = now();
   850         try {
   851             initProcessAnnotations(processors);
   853             // These method calls must be chained to avoid memory leaks
   854             delegateCompiler =
   855                 processAnnotations(
   856                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   857                     classnames);
   859             delegateCompiler.compile2();
   860             delegateCompiler.close();
   861             elapsed_msec = delegateCompiler.elapsed_msec;
   862         } catch (Abort ex) {
   863             if (devVerbose)
   864                 ex.printStackTrace(System.err);
   865         } finally {
   866             if (procEnvImpl != null)
   867                 procEnvImpl.close();
   868         }
   869     }
   871     /**
   872      * The phases following annotation processing: attribution,
   873      * desugar, and finally code generation.
   874      */
   875     private void compile2() {
   876         try {
   877             switch (compilePolicy) {
   878             case ATTR_ONLY:
   879                 attribute(todo);
   880                 break;
   882             case CHECK_ONLY:
   883                 flow(attribute(todo));
   884                 break;
   886             case SIMPLE:
   887                 generate(desugar(flow(attribute(todo))));
   888                 break;
   890             case BY_FILE: {
   891                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   892                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   893                         generate(desugar(flow(attribute(q.remove()))));
   894                     }
   895                 }
   896                 break;
   898             case BY_TODO:
   899                 while (!todo.isEmpty())
   900                     generate(desugar(flow(attribute(todo.remove()))));
   901                 break;
   903             default:
   904                 Assert.error("unknown compile policy");
   905             }
   906         } catch (Abort ex) {
   907             if (devVerbose)
   908                 ex.printStackTrace(System.err);
   909         }
   911         if (verbose) {
   912             elapsed_msec = elapsed(start_msec);
   913             log.printVerbose("total", Long.toString(elapsed_msec));
   914         }
   916         reportDeferredDiagnostics();
   918         if (!log.hasDiagnosticListener()) {
   919             printCount("error", errorCount());
   920             printCount("warn", warningCount());
   921         }
   922     }
   924     private List<JCClassDecl> rootClasses;
   926     /**
   927      * Parses a list of files.
   928      */
   929    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   930        if (shouldStop(CompileState.PARSE))
   931            return List.nil();
   933         //parse all files
   934         ListBuffer<JCCompilationUnit> trees = lb();
   935         Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
   936         for (JavaFileObject fileObject : fileObjects) {
   937             if (!filesSoFar.contains(fileObject)) {
   938                 filesSoFar.add(fileObject);
   939                 trees.append(parse(fileObject));
   940             }
   941         }
   942         return trees.toList();
   943     }
   945     /**
   946      * Enter the symbols found in a list of parse trees if the compilation
   947      * is expected to proceed beyond anno processing into attr.
   948      * As a side-effect, this puts elements on the "todo" list.
   949      * Also stores a list of all top level classes in rootClasses.
   950      */
   951     public List<JCCompilationUnit> enterTreesIfNeeded(List<JCCompilationUnit> roots) {
   952        if (shouldStop(CompileState.ATTR))
   953            return List.nil();
   954         return enterTrees(roots);
   955     }
   957     /**
   958      * Enter the symbols found in a list of parse trees.
   959      * As a side-effect, this puts elements on the "todo" list.
   960      * Also stores a list of all top level classes in rootClasses.
   961      */
   962     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   963         //enter symbols for all files
   964         if (!taskListener.isEmpty()) {
   965             for (JCCompilationUnit unit: roots) {
   966                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   967                 taskListener.started(e);
   968             }
   969         }
   971         enter.main(roots);
   973         if (!taskListener.isEmpty()) {
   974             for (JCCompilationUnit unit: roots) {
   975                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   976                 taskListener.finished(e);
   977             }
   978         }
   980         //If generating source, remember the classes declared in
   981         //the original compilation units listed on the command line.
   982         if (sourceOutput || stubOutput) {
   983             ListBuffer<JCClassDecl> cdefs = lb();
   984             for (JCCompilationUnit unit : roots) {
   985                 for (List<JCTree> defs = unit.defs;
   986                      defs.nonEmpty();
   987                      defs = defs.tail) {
   988                     if (defs.head instanceof JCClassDecl)
   989                         cdefs.append((JCClassDecl)defs.head);
   990                 }
   991             }
   992             rootClasses = cdefs.toList();
   993         }
   995         // Ensure the input files have been recorded. Although this is normally
   996         // done by readSource, it may not have been done if the trees were read
   997         // in a prior round of annotation processing, and the trees have been
   998         // cleaned and are being reused.
   999         for (JCCompilationUnit unit : roots) {
  1000             inputFiles.add(unit.sourcefile);
  1003         return roots;
  1006     /**
  1007      * Set to true to enable skeleton annotation processing code.
  1008      * Currently, we assume this variable will be replaced more
  1009      * advanced logic to figure out if annotation processing is
  1010      * needed.
  1011      */
  1012     boolean processAnnotations = false;
  1014     /**
  1015      * Object to handle annotation processing.
  1016      */
  1017     private JavacProcessingEnvironment procEnvImpl = null;
  1019     /**
  1020      * Check if we should process annotations.
  1021      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
  1022      * to catch doc comments, and set keepComments so the parser records them in
  1023      * the compilation unit.
  1025      * @param processors user provided annotation processors to bypass
  1026      * discovery, {@code null} means that no processors were provided
  1027      */
  1028     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
  1029         // Process annotations if processing is not disabled and there
  1030         // is at least one Processor available.
  1031         if (options.isSet(PROC, "none")) {
  1032             processAnnotations = false;
  1033         } else if (procEnvImpl == null) {
  1034             procEnvImpl = new JavacProcessingEnvironment(context, processors);
  1035             processAnnotations = procEnvImpl.atLeastOneProcessor();
  1037             if (processAnnotations) {
  1038                 options.put("save-parameter-names", "save-parameter-names");
  1039                 reader.saveParameterNames = true;
  1040                 keepComments = true;
  1041                 genEndPos = true;
  1042                 if (!taskListener.isEmpty())
  1043                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1044                 log.deferAll();
  1045             } else { // free resources
  1046                 procEnvImpl.close();
  1051     // TODO: called by JavacTaskImpl
  1052     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
  1053         return processAnnotations(roots, List.<String>nil());
  1056     /**
  1057      * Process any annotations found in the specified compilation units.
  1058      * @param roots a list of compilation units
  1059      * @return an instance of the compiler in which to complete the compilation
  1060      */
  1061     // Implementation note: when this method is called, log.deferredDiagnostics
  1062     // will have been set true by initProcessAnnotations, meaning that any diagnostics
  1063     // that are reported will go into the log.deferredDiagnostics queue.
  1064     // By the time this method exits, log.deferDiagnostics must be set back to false,
  1065     // and all deferredDiagnostics must have been handled: i.e. either reported
  1066     // or determined to be transient, and therefore suppressed.
  1067     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
  1068                                            List<String> classnames) {
  1069         if (shouldStop(CompileState.PROCESS)) {
  1070             // Errors were encountered.
  1071             // Unless all the errors are resolve errors, the errors were parse errors
  1072             // or other errors during enter which cannot be fixed by running
  1073             // any annotation processors.
  1074             if (unrecoverableError()) {
  1075                 log.reportDeferredDiagnostics();
  1076                 return this;
  1080         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1081         // by initProcessAnnotations
  1083         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1085         if (!processAnnotations) {
  1086             // If there are no annotation processors present, and
  1087             // annotation processing is to occur with compilation,
  1088             // emit a warning.
  1089             if (options.isSet(PROC, "only")) {
  1090                 log.warning("proc.proc-only.requested.no.procs");
  1091                 todo.clear();
  1093             // If not processing annotations, classnames must be empty
  1094             if (!classnames.isEmpty()) {
  1095                 log.error("proc.no.explicit.annotation.processing.requested",
  1096                           classnames);
  1098             log.reportDeferredDiagnostics();
  1099             return this; // continue regular compilation
  1102         try {
  1103             List<ClassSymbol> classSymbols = List.nil();
  1104             List<PackageSymbol> pckSymbols = List.nil();
  1105             if (!classnames.isEmpty()) {
  1106                  // Check for explicit request for annotation
  1107                  // processing
  1108                 if (!explicitAnnotationProcessingRequested()) {
  1109                     log.error("proc.no.explicit.annotation.processing.requested",
  1110                               classnames);
  1111                     log.reportDeferredDiagnostics();
  1112                     return this; // TODO: Will this halt compilation?
  1113                 } else {
  1114                     boolean errors = false;
  1115                     for (String nameStr : classnames) {
  1116                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
  1117                         if (sym == null ||
  1118                             (sym.kind == Kinds.PCK && !processPcks) ||
  1119                             sym.kind == Kinds.ABSENT_TYP) {
  1120                             log.error("proc.cant.find.class", nameStr);
  1121                             errors = true;
  1122                             continue;
  1124                         try {
  1125                             if (sym.kind == Kinds.PCK)
  1126                                 sym.complete();
  1127                             if (sym.exists()) {
  1128                                 if (sym.kind == Kinds.PCK)
  1129                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1130                                 else
  1131                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1132                                 continue;
  1134                             Assert.check(sym.kind == Kinds.PCK);
  1135                             log.warning("proc.package.does.not.exist", nameStr);
  1136                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1137                         } catch (CompletionFailure e) {
  1138                             log.error("proc.cant.find.class", nameStr);
  1139                             errors = true;
  1140                             continue;
  1143                     if (errors) {
  1144                         log.reportDeferredDiagnostics();
  1145                         return this;
  1149             try {
  1150                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
  1151                 if (c != this)
  1152                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1153                 // doProcessing will have handled deferred diagnostics
  1154                 Assert.check(c.log.deferredDiagFilter == null
  1155                         && c.log.deferredDiagnostics.size() == 0);
  1156                 return c;
  1157             } finally {
  1158                 procEnvImpl.close();
  1160         } catch (CompletionFailure ex) {
  1161             log.error("cant.access", ex.sym, ex.getDetailValue());
  1162             log.reportDeferredDiagnostics();
  1163             return this;
  1167     private boolean unrecoverableError() {
  1168         for (JCDiagnostic d: log.deferredDiagnostics) {
  1169             if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
  1170                 return true;
  1172         return false;
  1175     boolean explicitAnnotationProcessingRequested() {
  1176         return
  1177             explicitAnnotationProcessingRequested ||
  1178             explicitAnnotationProcessingRequested(options);
  1181     static boolean explicitAnnotationProcessingRequested(Options options) {
  1182         return
  1183             options.isSet(PROCESSOR) ||
  1184             options.isSet(PROCESSORPATH) ||
  1185             options.isSet(PROC, "only") ||
  1186             options.isSet(XPRINT);
  1189     /**
  1190      * Attribute a list of parse trees, such as found on the "todo" list.
  1191      * Note that attributing classes may cause additional files to be
  1192      * parsed and entered via the SourceCompleter.
  1193      * Attribution of the entries in the list does not stop if any errors occur.
  1194      * @returns a list of environments for attributd classes.
  1195      */
  1196     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1197         ListBuffer<Env<AttrContext>> results = lb();
  1198         while (!envs.isEmpty())
  1199             results.append(attribute(envs.remove()));
  1200         return stopIfError(CompileState.ATTR, results);
  1203     /**
  1204      * Attribute a parse tree.
  1205      * @returns the attributed parse tree
  1206      */
  1207     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1208         if (compileStates.isDone(env, CompileState.ATTR))
  1209             return env;
  1211         if (verboseCompilePolicy)
  1212             printNote("[attribute " + env.enclClass.sym + "]");
  1213         if (verbose)
  1214             log.printVerbose("checking.attribution", env.enclClass.sym);
  1216         if (!taskListener.isEmpty()) {
  1217             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1218             taskListener.started(e);
  1221         JavaFileObject prev = log.useSource(
  1222                                   env.enclClass.sym.sourcefile != null ?
  1223                                   env.enclClass.sym.sourcefile :
  1224                                   env.toplevel.sourcefile);
  1225         try {
  1226             attr.attrib(env);
  1227             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1228                 //if in fail-over mode, ensure that AST expression nodes
  1229                 //are correctly initialized (e.g. they have a type/symbol)
  1230                 attr.postAttr(env.tree);
  1232             compileStates.put(env, CompileState.ATTR);
  1234         finally {
  1235             log.useSource(prev);
  1238         return env;
  1241     /**
  1242      * Perform dataflow checks on attributed parse trees.
  1243      * These include checks for definite assignment and unreachable statements.
  1244      * If any errors occur, an empty list will be returned.
  1245      * @returns the list of attributed parse trees
  1246      */
  1247     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1248         ListBuffer<Env<AttrContext>> results = lb();
  1249         for (Env<AttrContext> env: envs) {
  1250             flow(env, results);
  1252         return stopIfError(CompileState.FLOW, results);
  1255     /**
  1256      * Perform dataflow checks on an attributed parse tree.
  1257      */
  1258     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1259         ListBuffer<Env<AttrContext>> results = lb();
  1260         flow(env, results);
  1261         return stopIfError(CompileState.FLOW, results);
  1264     /**
  1265      * Perform dataflow checks on an attributed parse tree.
  1266      */
  1267     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1268         try {
  1269             if (shouldStop(CompileState.FLOW))
  1270                 return;
  1272             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1273                 results.add(env);
  1274                 return;
  1277             if (verboseCompilePolicy)
  1278                 printNote("[flow " + env.enclClass.sym + "]");
  1279             JavaFileObject prev = log.useSource(
  1280                                                 env.enclClass.sym.sourcefile != null ?
  1281                                                 env.enclClass.sym.sourcefile :
  1282                                                 env.toplevel.sourcefile);
  1283             try {
  1284                 make.at(Position.FIRSTPOS);
  1285                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1286                 flow.analyzeTree(env, localMake);
  1287                 compileStates.put(env, CompileState.FLOW);
  1289                 if (shouldStop(CompileState.FLOW))
  1290                     return;
  1292                 results.add(env);
  1294             finally {
  1295                 log.useSource(prev);
  1298         finally {
  1299             if (!taskListener.isEmpty()) {
  1300                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1301                 taskListener.finished(e);
  1306     /**
  1307      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1308      * for source or code generation.
  1309      * If any errors occur, an empty list will be returned.
  1310      * @returns a list containing the classes to be generated
  1311      */
  1312     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1313         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1314         for (Env<AttrContext> env: envs)
  1315             desugar(env, results);
  1316         return stopIfError(CompileState.FLOW, results);
  1319     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1320             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1322     /**
  1323      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1324      * for source or code generation. If the file was not listed on the command line,
  1325      * the current implicitSourcePolicy is taken into account.
  1326      * The preparation stops as soon as an error is found.
  1327      */
  1328     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1329         if (shouldStop(CompileState.TRANSTYPES))
  1330             return;
  1332         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1333                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1334             return;
  1337         if (compileStates.isDone(env, CompileState.LOWER)) {
  1338             results.addAll(desugaredEnvs.get(env));
  1339             return;
  1342         /**
  1343          * Ensure that superclasses of C are desugared before C itself. This is
  1344          * required for two reasons: (i) as erasure (TransTypes) destroys
  1345          * information needed in flow analysis and (ii) as some checks carried
  1346          * out during lowering require that all synthetic fields/methods have
  1347          * already been added to C and its superclasses.
  1348          */
  1349         class ScanNested extends TreeScanner {
  1350             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1351             @Override
  1352             public void visitClassDef(JCClassDecl node) {
  1353                 Type st = types.supertype(node.sym.type);
  1354                 if (st.tag == TypeTags.CLASS) {
  1355                     ClassSymbol c = st.tsym.outermostClass();
  1356                     Env<AttrContext> stEnv = enter.getEnv(c);
  1357                     if (stEnv != null && env != stEnv) {
  1358                         if (dependencies.add(stEnv))
  1359                             scan(stEnv.tree);
  1362                 super.visitClassDef(node);
  1365         ScanNested scanner = new ScanNested();
  1366         scanner.scan(env.tree);
  1367         for (Env<AttrContext> dep: scanner.dependencies) {
  1368         if (!compileStates.isDone(dep, CompileState.FLOW))
  1369             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1372         //We need to check for error another time as more classes might
  1373         //have been attributed and analyzed at this stage
  1374         if (shouldStop(CompileState.TRANSTYPES))
  1375             return;
  1377         if (verboseCompilePolicy)
  1378             printNote("[desugar " + env.enclClass.sym + "]");
  1380         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1381                                   env.enclClass.sym.sourcefile :
  1382                                   env.toplevel.sourcefile);
  1383         try {
  1384             //save tree prior to rewriting
  1385             JCTree untranslated = env.tree;
  1387             make.at(Position.FIRSTPOS);
  1388             TreeMaker localMake = make.forToplevel(env.toplevel);
  1390             if (env.tree instanceof JCCompilationUnit) {
  1391                 if (!(stubOutput || sourceOutput || printFlat)) {
  1392                     if (shouldStop(CompileState.LOWER))
  1393                         return;
  1394                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1395                     if (pdef.head != null) {
  1396                         Assert.check(pdef.tail.isEmpty());
  1397                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1400                 return;
  1403             if (stubOutput) {
  1404                 //emit stub Java source file, only for compilation
  1405                 //units enumerated explicitly on the command line
  1406                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1407                 if (untranslated instanceof JCClassDecl &&
  1408                     rootClasses.contains((JCClassDecl)untranslated) &&
  1409                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1410                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1411                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1413                 return;
  1416             if (shouldStop(CompileState.TRANSTYPES))
  1417                 return;
  1419             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1420             compileStates.put(env, CompileState.TRANSTYPES);
  1422             if (shouldStop(CompileState.LOWER))
  1423                 return;
  1425             if (sourceOutput) {
  1426                 //emit standard Java source file, only for compilation
  1427                 //units enumerated explicitly on the command line
  1428                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1429                 if (untranslated instanceof JCClassDecl &&
  1430                     rootClasses.contains((JCClassDecl)untranslated)) {
  1431                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1433                 return;
  1436             //translate out inner classes
  1437             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1438             compileStates.put(env, CompileState.LOWER);
  1440             if (shouldStop(CompileState.LOWER))
  1441                 return;
  1443             //generate code for each class
  1444             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1445                 JCClassDecl cdef = (JCClassDecl)l.head;
  1446                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1449         finally {
  1450             log.useSource(prev);
  1455     /** Generates the source or class file for a list of classes.
  1456      * The decision to generate a source file or a class file is
  1457      * based upon the compiler's options.
  1458      * Generation stops if an error occurs while writing files.
  1459      */
  1460     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1461         generate(queue, null);
  1464     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1465         if (shouldStop(CompileState.GENERATE))
  1466             return;
  1468         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1470         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1471             Env<AttrContext> env = x.fst;
  1472             JCClassDecl cdef = x.snd;
  1474             if (verboseCompilePolicy) {
  1475                 printNote("[generate "
  1476                                + (usePrintSource ? " source" : "code")
  1477                                + " " + cdef.sym + "]");
  1480             if (!taskListener.isEmpty()) {
  1481                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1482                 taskListener.started(e);
  1485             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1486                                       env.enclClass.sym.sourcefile :
  1487                                       env.toplevel.sourcefile);
  1488             try {
  1489                 JavaFileObject file;
  1490                 if (usePrintSource)
  1491                     file = printSource(env, cdef);
  1492                 else {
  1493                     if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
  1494                             && jniWriter.needsHeader(cdef.sym)) {
  1495                         jniWriter.write(cdef.sym);
  1497                     file = genCode(env, cdef);
  1499                 if (results != null && file != null)
  1500                     results.add(file);
  1501             } catch (IOException ex) {
  1502                 log.error(cdef.pos(), "class.cant.write",
  1503                           cdef.sym, ex.getMessage());
  1504                 return;
  1505             } finally {
  1506                 log.useSource(prev);
  1509             if (!taskListener.isEmpty()) {
  1510                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1511                 taskListener.finished(e);
  1516         // where
  1517         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1518             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1519             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1520             for (Env<AttrContext> env: envs) {
  1521                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1522                 if (sublist == null) {
  1523                     sublist = new ListBuffer<Env<AttrContext>>();
  1524                     map.put(env.toplevel, sublist);
  1526                 sublist.add(env);
  1528             return map;
  1531         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1532             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1533             class MethodBodyRemover extends TreeTranslator {
  1534                 @Override
  1535                 public void visitMethodDef(JCMethodDecl tree) {
  1536                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1537                     for (JCVariableDecl vd : tree.params)
  1538                         vd.mods.flags &= ~Flags.FINAL;
  1539                     tree.body = null;
  1540                     super.visitMethodDef(tree);
  1542                 @Override
  1543                 public void visitVarDef(JCVariableDecl tree) {
  1544                     if (tree.init != null && tree.init.type.constValue() == null)
  1545                         tree.init = null;
  1546                     super.visitVarDef(tree);
  1548                 @Override
  1549                 public void visitClassDef(JCClassDecl tree) {
  1550                     ListBuffer<JCTree> newdefs = lb();
  1551                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1552                         JCTree t = it.head;
  1553                         switch (t.getTag()) {
  1554                         case CLASSDEF:
  1555                             if (isInterface ||
  1556                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1557                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1558                                 newdefs.append(t);
  1559                             break;
  1560                         case METHODDEF:
  1561                             if (isInterface ||
  1562                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1563                                 ((JCMethodDecl) t).sym.name == names.init ||
  1564                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1565                                 newdefs.append(t);
  1566                             break;
  1567                         case VARDEF:
  1568                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1569                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1570                                 newdefs.append(t);
  1571                             break;
  1572                         default:
  1573                             break;
  1576                     tree.defs = newdefs.toList();
  1577                     super.visitClassDef(tree);
  1580             MethodBodyRemover r = new MethodBodyRemover();
  1581             return r.translate(cdef);
  1584     public void reportDeferredDiagnostics() {
  1585         if (errorCount() == 0
  1586                 && annotationProcessingOccurred
  1587                 && implicitSourceFilesRead
  1588                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1589             if (explicitAnnotationProcessingRequested())
  1590                 log.warning("proc.use.implicit");
  1591             else
  1592                 log.warning("proc.use.proc.or.implicit");
  1594         chk.reportDeferredDiagnostics();
  1597     /** Close the compiler, flushing the logs
  1598      */
  1599     public void close() {
  1600         close(true);
  1603     public void close(boolean disposeNames) {
  1604         rootClasses = null;
  1605         reader = null;
  1606         make = null;
  1607         writer = null;
  1608         enter = null;
  1609         if (todo != null)
  1610             todo.clear();
  1611         todo = null;
  1612         parserFactory = null;
  1613         syms = null;
  1614         source = null;
  1615         attr = null;
  1616         chk = null;
  1617         gen = null;
  1618         flow = null;
  1619         transTypes = null;
  1620         lower = null;
  1621         annotate = null;
  1622         types = null;
  1624         log.flush();
  1625         try {
  1626             fileManager.flush();
  1627         } catch (IOException e) {
  1628             throw new Abort(e);
  1629         } finally {
  1630             if (names != null && disposeNames)
  1631                 names.dispose();
  1632             names = null;
  1634             for (Closeable c: closeables) {
  1635                 try {
  1636                     c.close();
  1637                 } catch (IOException e) {
  1638                     // When javac uses JDK 7 as a baseline, this code would be
  1639                     // better written to set any/all exceptions from all the
  1640                     // Closeables as suppressed exceptions on the FatalError
  1641                     // that is thrown.
  1642                     JCDiagnostic msg = diagFactory.fragment("fatal.err.cant.close");
  1643                     throw new FatalError(msg, e);
  1649     protected void printNote(String lines) {
  1650         log.printRawLines(Log.WriterKind.NOTICE, lines);
  1653     /** Print numbers of errors and warnings.
  1654      */
  1655     protected void printCount(String kind, int count) {
  1656         if (count != 0) {
  1657             String key;
  1658             if (count == 1)
  1659                 key = "count." + kind;
  1660             else
  1661                 key = "count." + kind + ".plural";
  1662             log.printLines(WriterKind.ERROR, key, String.valueOf(count));
  1663             log.flush(Log.WriterKind.ERROR);
  1667     private static long now() {
  1668         return System.currentTimeMillis();
  1671     private static long elapsed(long then) {
  1672         return now() - then;
  1675     public void initRound(JavaCompiler prev) {
  1676         genEndPos = prev.genEndPos;
  1677         keepComments = prev.keepComments;
  1678         start_msec = prev.start_msec;
  1679         hasBeenUsed = true;
  1680         closeables = prev.closeables;
  1681         prev.closeables = List.nil();
  1682         shouldStopPolicyIfError = prev.shouldStopPolicyIfError;
  1683         shouldStopPolicyIfNoError = prev.shouldStopPolicyIfNoError;
  1686     public static void enableLogging() {
  1687         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1688         logger.setLevel(Level.ALL);
  1689         for (Handler h : logger.getParent().getHandlers()) {
  1690             h.setLevel(Level.ALL);

mercurial