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

Tue, 08 Nov 2011 17:06:58 -0800

author
jjg
date
Tue, 08 Nov 2011 17:06:58 -0800
changeset 1136
ae361e7f435a
parent 1135
36553cb94345
child 1157
3809292620c9
permissions
-rw-r--r--

7108669: cleanup Log methods for direct printing to streams
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright (c) 1999, 2011, 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.LinkedHashSet;
    32 import java.util.LinkedHashMap;
    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.JavaFileManager;
    45 import javax.tools.JavaFileObject;
    46 import javax.tools.DiagnosticListener;
    48 import com.sun.source.util.TaskEvent;
    49 import com.sun.source.util.TaskListener;
    51 import com.sun.tools.javac.code.*;
    52 import com.sun.tools.javac.code.Lint.LintCategory;
    53 import com.sun.tools.javac.code.Symbol.*;
    54 import com.sun.tools.javac.comp.*;
    55 import com.sun.tools.javac.file.JavacFileManager;
    56 import com.sun.tools.javac.jvm.*;
    57 import com.sun.tools.javac.parser.*;
    58 import com.sun.tools.javac.processing.*;
    59 import com.sun.tools.javac.tree.*;
    60 import com.sun.tools.javac.tree.JCTree.*;
    61 import com.sun.tools.javac.util.*;
    62 import com.sun.tools.javac.util.Log.WriterKind;
    64 import static javax.tools.StandardLocation.CLASS_OUTPUT;
    65 import static com.sun.tools.javac.main.OptionName.*;
    66 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    67 import static com.sun.tools.javac.util.ListBuffer.lb;
    70 /** This class could be the main entry point for GJC when GJC is used as a
    71  *  component in a larger software system. It provides operations to
    72  *  construct a new compiler, and to run a new compiler on a set of source
    73  *  files.
    74  *
    75  *  <p><b>This is NOT part of any supported API.
    76  *  If you write code that depends on this, you do so at your own risk.
    77  *  This code and its internal interfaces are subject to change or
    78  *  deletion without notice.</b>
    79  */
    80 public class JavaCompiler implements ClassReader.SourceCompleter {
    81     /** The context key for the compiler. */
    82     protected static final Context.Key<JavaCompiler> compilerKey =
    83         new Context.Key<JavaCompiler>();
    85     /** Get the JavaCompiler instance for this context. */
    86     public static JavaCompiler instance(Context context) {
    87         JavaCompiler instance = context.get(compilerKey);
    88         if (instance == null)
    89             instance = new JavaCompiler(context);
    90         return instance;
    91     }
    93     /** The current version number as a string.
    94      */
    95     public static String version() {
    96         return version("release");  // mm.nn.oo[-milestone]
    97     }
    99     /** The current full version number as a string.
   100      */
   101     public static String fullVersion() {
   102         return version("full"); // mm.mm.oo[-milestone]-build
   103     }
   105     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   106     private static ResourceBundle versionRB;
   108     private static String version(String key) {
   109         if (versionRB == null) {
   110             try {
   111                 versionRB = ResourceBundle.getBundle(versionRBName);
   112             } catch (MissingResourceException e) {
   113                 return Log.getLocalizedString("version.not.available");
   114             }
   115         }
   116         try {
   117             return versionRB.getString(key);
   118         }
   119         catch (MissingResourceException e) {
   120             return Log.getLocalizedString("version.not.available");
   121         }
   122     }
   124     /**
   125      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   126      * are connected. Each individual file is processed by each phase in turn,
   127      * but with different compile policies, you can control the order in which
   128      * each class is processed through its next phase.
   129      *
   130      * <p>Generally speaking, the compiler will "fail fast" in the face of
   131      * errors, although not aggressively so. flow, desugar, etc become no-ops
   132      * once any errors have occurred. No attempt is currently made to determine
   133      * if it might be safe to process a class through its next phase because
   134      * it does not depend on any unrelated errors that might have occurred.
   135      */
   136     protected static enum CompilePolicy {
   137         /**
   138          * Just attribute the parse trees.
   139          */
   140         ATTR_ONLY,
   142         /**
   143          * Just attribute and do flow analysis on the parse trees.
   144          * This should catch most user errors.
   145          */
   146         CHECK_ONLY,
   148         /**
   149          * Attribute everything, then do flow analysis for everything,
   150          * then desugar everything, and only then generate output.
   151          * This means no output will be generated if there are any
   152          * errors in any classes.
   153          */
   154         SIMPLE,
   156         /**
   157          * Groups the classes for each source file together, then process
   158          * each group in a manner equivalent to the {@code SIMPLE} policy.
   159          * This means no output will be generated if there are any
   160          * errors in any of the classes in a source file.
   161          */
   162         BY_FILE,
   164         /**
   165          * Completely process each entry on the todo list in turn.
   166          * -- this is the same for 1.5.
   167          * Means output might be generated for some classes in a compilation unit
   168          * and not others.
   169          */
   170         BY_TODO;
   172         static CompilePolicy decode(String option) {
   173             if (option == null)
   174                 return DEFAULT_COMPILE_POLICY;
   175             else if (option.equals("attr"))
   176                 return ATTR_ONLY;
   177             else if (option.equals("check"))
   178                 return CHECK_ONLY;
   179             else if (option.equals("simple"))
   180                 return SIMPLE;
   181             else if (option.equals("byfile"))
   182                 return BY_FILE;
   183             else if (option.equals("bytodo"))
   184                 return BY_TODO;
   185             else
   186                 return DEFAULT_COMPILE_POLICY;
   187         }
   188     }
   190     private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   192     protected static enum ImplicitSourcePolicy {
   193         /** Don't generate or process implicitly read source files. */
   194         NONE,
   195         /** Generate classes for implicitly read source files. */
   196         CLASS,
   197         /** Like CLASS, but generate warnings if annotation processing occurs */
   198         UNSET;
   200         static ImplicitSourcePolicy decode(String option) {
   201             if (option == null)
   202                 return UNSET;
   203             else if (option.equals("none"))
   204                 return NONE;
   205             else if (option.equals("class"))
   206                 return CLASS;
   207             else
   208                 return UNSET;
   209         }
   210     }
   212     /** The log to be used for error reporting.
   213      */
   214     public Log log;
   216     /** Factory for creating diagnostic objects
   217      */
   218     JCDiagnostic.Factory diagFactory;
   220     /** The tree factory module.
   221      */
   222     protected TreeMaker make;
   224     /** The class reader.
   225      */
   226     protected ClassReader reader;
   228     /** The class writer.
   229      */
   230     protected ClassWriter writer;
   232     /** The module for the symbol table entry phases.
   233      */
   234     protected Enter enter;
   236     /** The symbol table.
   237      */
   238     protected Symtab syms;
   240     /** The language version.
   241      */
   242     protected Source source;
   244     /** The module for code generation.
   245      */
   246     protected Gen gen;
   248     /** The name table.
   249      */
   250     protected Names names;
   252     /** The attributor.
   253      */
   254     protected Attr attr;
   256     /** The attributor.
   257      */
   258     protected Check chk;
   260     /** The flow analyzer.
   261      */
   262     protected Flow flow;
   264     /** The type eraser.
   265      */
   266     protected TransTypes transTypes;
   268     /** The syntactic sugar desweetener.
   269      */
   270     protected Lower lower;
   272     /** The annotation annotator.
   273      */
   274     protected Annotate annotate;
   276     /** Force a completion failure on this name
   277      */
   278     protected final Name completionFailureName;
   280     /** Type utilities.
   281      */
   282     protected Types types;
   284     /** Access to file objects.
   285      */
   286     protected JavaFileManager fileManager;
   288     /** Factory for parsers.
   289      */
   290     protected ParserFactory parserFactory;
   292     /** Optional listener for progress events
   293      */
   294     protected TaskListener taskListener;
   296     /**
   297      * Annotation processing may require and provide a new instance
   298      * of the compiler to be used for the analyze and generate phases.
   299      */
   300     protected JavaCompiler delegateCompiler;
   302     /**
   303      * Command line options.
   304      */
   305     protected Options options;
   307     protected Context context;
   309     /**
   310      * Flag set if any annotation processing occurred.
   311      **/
   312     protected boolean annotationProcessingOccurred;
   314     /**
   315      * Flag set if any implicit source files read.
   316      **/
   317     protected boolean implicitSourceFilesRead;
   319     /** Construct a new compiler using a shared context.
   320      */
   321     public JavaCompiler(Context context) {
   322         this.context = context;
   323         context.put(compilerKey, this);
   325         // if fileManager not already set, register the JavacFileManager to be used
   326         if (context.get(JavaFileManager.class) == null)
   327             JavacFileManager.preRegister(context);
   329         names = Names.instance(context);
   330         log = Log.instance(context);
   331         diagFactory = JCDiagnostic.Factory.instance(context);
   332         reader = ClassReader.instance(context);
   333         make = TreeMaker.instance(context);
   334         writer = ClassWriter.instance(context);
   335         enter = Enter.instance(context);
   336         todo = Todo.instance(context);
   338         fileManager = context.get(JavaFileManager.class);
   339         parserFactory = ParserFactory.instance(context);
   341         try {
   342             // catch completion problems with predefineds
   343             syms = Symtab.instance(context);
   344         } catch (CompletionFailure ex) {
   345             // inlined Check.completionError as it is not initialized yet
   346             log.error("cant.access", ex.sym, ex.getDetailValue());
   347             if (ex instanceof ClassReader.BadClassFile)
   348                 throw new Abort();
   349         }
   350         source = Source.instance(context);
   351         attr = Attr.instance(context);
   352         chk = Check.instance(context);
   353         gen = Gen.instance(context);
   354         flow = Flow.instance(context);
   355         transTypes = TransTypes.instance(context);
   356         lower = Lower.instance(context);
   357         annotate = Annotate.instance(context);
   358         types = Types.instance(context);
   359         taskListener = context.get(TaskListener.class);
   361         reader.sourceCompleter = this;
   363         options = Options.instance(context);
   365         verbose       = options.isSet(VERBOSE);
   366         sourceOutput  = options.isSet(PRINTSOURCE); // used to be -s
   367         stubOutput    = options.isSet("-stubs");
   368         relax         = options.isSet("-relax");
   369         printFlat     = options.isSet("-printflat");
   370         attrParseOnly = options.isSet("-attrparseonly");
   371         encoding      = options.get(ENCODING);
   372         lineDebugInfo = options.isUnset(G_CUSTOM) ||
   373                         options.isSet(G_CUSTOM, "lines");
   374         genEndPos     = options.isSet(XJCOV) ||
   375                         context.get(DiagnosticListener.class) != null;
   376         devVerbose    = options.isSet("dev");
   377         processPcks   = options.isSet("process.packages");
   378         werror        = options.isSet(WERROR);
   380         if (source.compareTo(Source.DEFAULT) < 0) {
   381             if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   382                 if (fileManager instanceof BaseFileManager) {
   383                     if (((BaseFileManager) fileManager).isDefaultBootClassPath())
   384                         log.warning(LintCategory.OPTIONS, "source.no.bootclasspath", source.name);
   385                 }
   386             }
   387         }
   389         verboseCompilePolicy = options.isSet("verboseCompilePolicy");
   391         if (attrParseOnly)
   392             compilePolicy = CompilePolicy.ATTR_ONLY;
   393         else
   394             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   396         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   398         completionFailureName =
   399             options.isSet("failcomplete")
   400             ? names.fromString(options.get("failcomplete"))
   401             : null;
   403         shouldStopPolicy =
   404             options.isSet("shouldStopPolicy")
   405             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   406             : null;
   407         if (options.isUnset("oldDiags"))
   408             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   409     }
   411     /* Switches:
   412      */
   414     /** Verbose output.
   415      */
   416     public boolean verbose;
   418     /** Emit plain Java source files rather than class files.
   419      */
   420     public boolean sourceOutput;
   422     /** Emit stub source files rather than class files.
   423      */
   424     public boolean stubOutput;
   426     /** Generate attributed parse tree only.
   427      */
   428     public boolean attrParseOnly;
   430     /** Switch: relax some constraints for producing the jsr14 prototype.
   431      */
   432     boolean relax;
   434     /** Debug switch: Emit Java sources after inner class flattening.
   435      */
   436     public boolean printFlat;
   438     /** The encoding to be used for source input.
   439      */
   440     public String encoding;
   442     /** Generate code with the LineNumberTable attribute for debugging
   443      */
   444     public boolean lineDebugInfo;
   446     /** Switch: should we store the ending positions?
   447      */
   448     public boolean genEndPos;
   450     /** Switch: should we debug ignored exceptions
   451      */
   452     protected boolean devVerbose;
   454     /** Switch: should we (annotation) process packages as well
   455      */
   456     protected boolean processPcks;
   458     /** Switch: treat warnings as errors
   459      */
   460     protected boolean werror;
   462     /** Switch: is annotation processing requested explitly via
   463      * CompilationTask.setProcessors?
   464      */
   465     protected boolean explicitAnnotationProcessingRequested = false;
   467     /**
   468      * The policy for the order in which to perform the compilation
   469      */
   470     protected CompilePolicy compilePolicy;
   472     /**
   473      * The policy for what to do with implicitly read source files
   474      */
   475     protected ImplicitSourcePolicy implicitSourcePolicy;
   477     /**
   478      * Report activity related to compilePolicy
   479      */
   480     public boolean verboseCompilePolicy;
   482     /**
   483      * Policy of how far to continue processing. null means until first
   484      * error.
   485      */
   486     public CompileState shouldStopPolicy;
   488     /** A queue of all as yet unattributed classes.
   489      */
   490     public Todo todo;
   492     /** A list of items to be closed when the compilation is complete.
   493      */
   494     public List<Closeable> closeables = List.nil();
   496     /** Ordered list of compiler phases for each compilation unit. */
   497     public enum CompileState {
   498         PARSE(1),
   499         ENTER(2),
   500         PROCESS(3),
   501         ATTR(4),
   502         FLOW(5),
   503         TRANSTYPES(6),
   504         LOWER(7),
   505         GENERATE(8);
   506         CompileState(int value) {
   507             this.value = value;
   508         }
   509         boolean isDone(CompileState other) {
   510             return value >= other.value;
   511         }
   512         private int value;
   513     };
   514     /** Partial map to record which compiler phases have been executed
   515      * for each compilation unit. Used for ATTR and FLOW phases.
   516      */
   517     protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
   518         private static final long serialVersionUID = 1812267524140424433L;
   519         boolean isDone(Env<AttrContext> env, CompileState cs) {
   520             CompileState ecs = get(env);
   521             return ecs != null && ecs.isDone(cs);
   522         }
   523     }
   524     private CompileStates compileStates = new CompileStates();
   526     /** The set of currently compiled inputfiles, needed to ensure
   527      *  we don't accidentally overwrite an input file when -s is set.
   528      *  initialized by `compile'.
   529      */
   530     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   532     protected boolean shouldStop(CompileState cs) {
   533         if (shouldStopPolicy == null)
   534             return (errorCount() > 0 || unrecoverableError());
   535         else
   536             return cs.ordinal() > shouldStopPolicy.ordinal();
   537     }
   539     /** The number of errors reported so far.
   540      */
   541     public int errorCount() {
   542         if (delegateCompiler != null && delegateCompiler != this)
   543             return delegateCompiler.errorCount();
   544         else {
   545             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   546                 log.error("warnings.and.werror");
   547             }
   548         }
   549         return log.nerrors;
   550     }
   552     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   553         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   554     }
   556     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   557         return shouldStop(cs) ? List.<T>nil() : list;
   558     }
   560     /** The number of warnings reported so far.
   561      */
   562     public int warningCount() {
   563         if (delegateCompiler != null && delegateCompiler != this)
   564             return delegateCompiler.warningCount();
   565         else
   566             return log.nwarnings;
   567     }
   569     /** Try to open input stream with given name.
   570      *  Report an error if this fails.
   571      *  @param filename   The file name of the input stream to be opened.
   572      */
   573     public CharSequence readSource(JavaFileObject filename) {
   574         try {
   575             inputFiles.add(filename);
   576             return filename.getCharContent(false);
   577         } catch (IOException e) {
   578             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   579             return null;
   580         }
   581     }
   583     /** Parse contents of input stream.
   584      *  @param filename     The name of the file from which input stream comes.
   585      *  @param input        The input stream to be parsed.
   586      */
   587     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   588         long msec = now();
   589         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   590                                       null, List.<JCTree>nil());
   591         if (content != null) {
   592             if (verbose) {
   593                 log.printVerbose("parsing.started", filename);
   594             }
   595             if (taskListener != null) {
   596                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   597                 taskListener.started(e);
   598             }
   599             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   600             tree = parser.parseCompilationUnit();
   601             if (verbose) {
   602                 log.printVerbose("parsing.done", Long.toString(elapsed(msec)));
   603             }
   604         }
   606         tree.sourcefile = filename;
   608         if (content != null && taskListener != null) {
   609             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   610             taskListener.finished(e);
   611         }
   613         return tree;
   614     }
   615     // where
   616         public boolean keepComments = false;
   617         protected boolean keepComments() {
   618             return keepComments || sourceOutput || stubOutput;
   619         }
   622     /** Parse contents of file.
   623      *  @param filename     The name of the file to be parsed.
   624      */
   625     @Deprecated
   626     public JCTree.JCCompilationUnit parse(String filename) {
   627         JavacFileManager fm = (JavacFileManager)fileManager;
   628         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   629     }
   631     /** Parse contents of file.
   632      *  @param filename     The name of the file to be parsed.
   633      */
   634     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   635         JavaFileObject prev = log.useSource(filename);
   636         try {
   637             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   638             if (t.endPositions != null)
   639                 log.setEndPosTable(filename, t.endPositions);
   640             return t;
   641         } finally {
   642             log.useSource(prev);
   643         }
   644     }
   646     /** Resolve an identifier which may be the binary name of a class or
   647      * the Java name of a class or package.
   648      * @param name      The name to resolve
   649      */
   650     public Symbol resolveBinaryNameOrIdent(String name) {
   651         try {
   652             Name flatname = names.fromString(name.replace("/", "."));
   653             return reader.loadClass(flatname);
   654         } catch (CompletionFailure ignore) {
   655             return resolveIdent(name);
   656         }
   657     }
   659     /** Resolve an identifier.
   660      * @param name      The identifier to resolve
   661      */
   662     public Symbol resolveIdent(String name) {
   663         if (name.equals(""))
   664             return syms.errSymbol;
   665         JavaFileObject prev = log.useSource(null);
   666         try {
   667             JCExpression tree = null;
   668             for (String s : name.split("\\.", -1)) {
   669                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   670                     return syms.errSymbol;
   671                 tree = (tree == null) ? make.Ident(names.fromString(s))
   672                                       : make.Select(tree, names.fromString(s));
   673             }
   674             JCCompilationUnit toplevel =
   675                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   676             toplevel.packge = syms.unnamedPackage;
   677             return attr.attribIdent(tree, toplevel);
   678         } finally {
   679             log.useSource(prev);
   680         }
   681     }
   683     /** Emit plain Java source for a class.
   684      *  @param env    The attribution environment of the outermost class
   685      *                containing this class.
   686      *  @param cdef   The class definition to be printed.
   687      */
   688     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   689         JavaFileObject outFile
   690             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   691                                                cdef.sym.flatname.toString(),
   692                                                JavaFileObject.Kind.SOURCE,
   693                                                null);
   694         if (inputFiles.contains(outFile)) {
   695             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   696             return null;
   697         } else {
   698             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   699             try {
   700                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   701                 if (verbose)
   702                     log.printVerbose("wrote.file", outFile);
   703             } finally {
   704                 out.close();
   705             }
   706             return outFile;
   707         }
   708     }
   710     /** Generate code and emit a class file for a given class
   711      *  @param env    The attribution environment of the outermost class
   712      *                containing this class.
   713      *  @param cdef   The class definition from which code is generated.
   714      */
   715     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   716         try {
   717             if (gen.genClass(env, cdef) && (errorCount() == 0))
   718                 return writer.writeClass(cdef.sym);
   719         } catch (ClassWriter.PoolOverflow ex) {
   720             log.error(cdef.pos(), "limit.pool");
   721         } catch (ClassWriter.StringOverflow ex) {
   722             log.error(cdef.pos(), "limit.string.overflow",
   723                       ex.value.substring(0, 20));
   724         } catch (CompletionFailure ex) {
   725             chk.completionError(cdef.pos(), ex);
   726         }
   727         return null;
   728     }
   730     /** Complete compiling a source file that has been accessed
   731      *  by the class file reader.
   732      *  @param c          The class the source file of which needs to be compiled.
   733      *  @param filename   The name of the source file.
   734      *  @param f          An input stream that reads the source file.
   735      */
   736     public void complete(ClassSymbol c) throws CompletionFailure {
   737 //      System.err.println("completing " + c);//DEBUG
   738         if (completionFailureName == c.fullname) {
   739             throw new CompletionFailure(c, "user-selected completion failure by class name");
   740         }
   741         JCCompilationUnit tree;
   742         JavaFileObject filename = c.classfile;
   743         JavaFileObject prev = log.useSource(filename);
   745         try {
   746             tree = parse(filename, filename.getCharContent(false));
   747         } catch (IOException e) {
   748             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   749             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   750         } finally {
   751             log.useSource(prev);
   752         }
   754         if (taskListener != null) {
   755             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   756             taskListener.started(e);
   757         }
   759         enter.complete(List.of(tree), c);
   761         if (taskListener != null) {
   762             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   763             taskListener.finished(e);
   764         }
   766         if (enter.getEnv(c) == null) {
   767             boolean isPkgInfo =
   768                 tree.sourcefile.isNameCompatible("package-info",
   769                                                  JavaFileObject.Kind.SOURCE);
   770             if (isPkgInfo) {
   771                 if (enter.getEnv(tree.packge) == null) {
   772                     JCDiagnostic diag =
   773                         diagFactory.fragment("file.does.not.contain.package",
   774                                                  c.location());
   775                     throw reader.new BadClassFile(c, filename, diag);
   776                 }
   777             } else {
   778                 JCDiagnostic diag =
   779                         diagFactory.fragment("file.doesnt.contain.class",
   780                                             c.getQualifiedName());
   781                 throw reader.new BadClassFile(c, filename, diag);
   782             }
   783         }
   785         implicitSourceFilesRead = true;
   786     }
   788     /** Track when the JavaCompiler has been used to compile something. */
   789     private boolean hasBeenUsed = false;
   790     private long start_msec = 0;
   791     public long elapsed_msec = 0;
   793     public void compile(List<JavaFileObject> sourceFileObject)
   794         throws Throwable {
   795         compile(sourceFileObject, List.<String>nil(), null);
   796     }
   798     /**
   799      * Main method: compile a list of files, return all compiled classes
   800      *
   801      * @param sourceFileObjects file objects to be compiled
   802      * @param classnames class names to process for annotations
   803      * @param processors user provided annotation processors to bypass
   804      * discovery, {@code null} means that no processors were provided
   805      */
   806     public void compile(List<JavaFileObject> sourceFileObjects,
   807                         List<String> classnames,
   808                         Iterable<? extends Processor> processors)
   809     {
   810         if (processors != null && processors.iterator().hasNext())
   811             explicitAnnotationProcessingRequested = true;
   812         // as a JavaCompiler can only be used once, throw an exception if
   813         // it has been used before.
   814         if (hasBeenUsed)
   815             throw new AssertionError("attempt to reuse JavaCompiler");
   816         hasBeenUsed = true;
   818         // forcibly set the equivalent of -Xlint:-options, so that no further
   819         // warnings about command line options are generated from this point on
   820         options.put(XLINT_CUSTOM + "-" + LintCategory.OPTIONS.option, "true");
   821         options.remove(XLINT_CUSTOM + LintCategory.OPTIONS.option);
   823         start_msec = now();
   825         try {
   826             initProcessAnnotations(processors);
   828             // These method calls must be chained to avoid memory leaks
   829             delegateCompiler =
   830                 processAnnotations(
   831                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   832                     classnames);
   834             delegateCompiler.compile2();
   835             delegateCompiler.close();
   836             elapsed_msec = delegateCompiler.elapsed_msec;
   837         } catch (Abort ex) {
   838             if (devVerbose)
   839                 ex.printStackTrace(System.err);
   840         } finally {
   841             if (procEnvImpl != null)
   842                 procEnvImpl.close();
   843         }
   844     }
   846     /**
   847      * The phases following annotation processing: attribution,
   848      * desugar, and finally code generation.
   849      */
   850     private void compile2() {
   851         try {
   852             switch (compilePolicy) {
   853             case ATTR_ONLY:
   854                 attribute(todo);
   855                 break;
   857             case CHECK_ONLY:
   858                 flow(attribute(todo));
   859                 break;
   861             case SIMPLE:
   862                 generate(desugar(flow(attribute(todo))));
   863                 break;
   865             case BY_FILE: {
   866                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   867                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   868                         generate(desugar(flow(attribute(q.remove()))));
   869                     }
   870                 }
   871                 break;
   873             case BY_TODO:
   874                 while (!todo.isEmpty())
   875                     generate(desugar(flow(attribute(todo.remove()))));
   876                 break;
   878             default:
   879                 Assert.error("unknown compile policy");
   880             }
   881         } catch (Abort ex) {
   882             if (devVerbose)
   883                 ex.printStackTrace(System.err);
   884         }
   886         if (verbose) {
   887             elapsed_msec = elapsed(start_msec);
   888             log.printVerbose("total", Long.toString(elapsed_msec));
   889         }
   891         reportDeferredDiagnostics();
   893         if (!log.hasDiagnosticListener()) {
   894             printCount("error", errorCount());
   895             printCount("warn", warningCount());
   896         }
   897     }
   899     private List<JCClassDecl> rootClasses;
   901     /**
   902      * Parses a list of files.
   903      */
   904    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   905        if (shouldStop(CompileState.PARSE))
   906            return List.nil();
   908         //parse all files
   909         ListBuffer<JCCompilationUnit> trees = lb();
   910         Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
   911         for (JavaFileObject fileObject : fileObjects) {
   912             if (!filesSoFar.contains(fileObject)) {
   913                 filesSoFar.add(fileObject);
   914                 trees.append(parse(fileObject));
   915             }
   916         }
   917         return trees.toList();
   918     }
   920     /**
   921      * Enter the symbols found in a list of parse trees.
   922      * As a side-effect, this puts elements on the "todo" list.
   923      * Also stores a list of all top level classes in rootClasses.
   924      */
   925     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   926         //enter symbols for all files
   927         if (taskListener != null) {
   928             for (JCCompilationUnit unit: roots) {
   929                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   930                 taskListener.started(e);
   931             }
   932         }
   934         enter.main(roots);
   936         if (taskListener != null) {
   937             for (JCCompilationUnit unit: roots) {
   938                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   939                 taskListener.finished(e);
   940             }
   941         }
   943         //If generating source, remember the classes declared in
   944         //the original compilation units listed on the command line.
   945         if (sourceOutput || stubOutput) {
   946             ListBuffer<JCClassDecl> cdefs = lb();
   947             for (JCCompilationUnit unit : roots) {
   948                 for (List<JCTree> defs = unit.defs;
   949                      defs.nonEmpty();
   950                      defs = defs.tail) {
   951                     if (defs.head instanceof JCClassDecl)
   952                         cdefs.append((JCClassDecl)defs.head);
   953                 }
   954             }
   955             rootClasses = cdefs.toList();
   956         }
   958         // Ensure the input files have been recorded. Although this is normally
   959         // done by readSource, it may not have been done if the trees were read
   960         // in a prior round of annotation processing, and the trees have been
   961         // cleaned and are being reused.
   962         for (JCCompilationUnit unit : roots) {
   963             inputFiles.add(unit.sourcefile);
   964         }
   966         return roots;
   967     }
   969     /**
   970      * Set to true to enable skeleton annotation processing code.
   971      * Currently, we assume this variable will be replaced more
   972      * advanced logic to figure out if annotation processing is
   973      * needed.
   974      */
   975     boolean processAnnotations = false;
   977     /**
   978      * Object to handle annotation processing.
   979      */
   980     private JavacProcessingEnvironment procEnvImpl = null;
   982     /**
   983      * Check if we should process annotations.
   984      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
   985      * to catch doc comments, and set keepComments so the parser records them in
   986      * the compilation unit.
   987      *
   988      * @param processors user provided annotation processors to bypass
   989      * discovery, {@code null} means that no processors were provided
   990      */
   991     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
   992         // Process annotations if processing is not disabled and there
   993         // is at least one Processor available.
   994         if (options.isSet(PROC, "none")) {
   995             processAnnotations = false;
   996         } else if (procEnvImpl == null) {
   997             procEnvImpl = new JavacProcessingEnvironment(context, processors);
   998             processAnnotations = procEnvImpl.atLeastOneProcessor();
  1000             if (processAnnotations) {
  1001                 options.put("save-parameter-names", "save-parameter-names");
  1002                 reader.saveParameterNames = true;
  1003                 keepComments = true;
  1004                 genEndPos = true;
  1005                 if (taskListener != null)
  1006                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1007                 log.deferDiagnostics = true;
  1008             } else { // free resources
  1009                 procEnvImpl.close();
  1014     // TODO: called by JavacTaskImpl
  1015     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
  1016         return processAnnotations(roots, List.<String>nil());
  1019     /**
  1020      * Process any anotations found in the specifed compilation units.
  1021      * @param roots a list of compilation units
  1022      * @return an instance of the compiler in which to complete the compilation
  1023      */
  1024     // Implementation note: when this method is called, log.deferredDiagnostics
  1025     // will have been set true by initProcessAnnotations, meaning that any diagnostics
  1026     // that are reported will go into the log.deferredDiagnostics queue.
  1027     // By the time this method exits, log.deferDiagnostics must be set back to false,
  1028     // and all deferredDiagnostics must have been handled: i.e. either reported
  1029     // or determined to be transient, and therefore suppressed.
  1030     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
  1031                                            List<String> classnames) {
  1032         if (shouldStop(CompileState.PROCESS)) {
  1033             // Errors were encountered.
  1034             // Unless all the errors are resolve errors, the errors were parse errors
  1035             // or other errors during enter which cannot be fixed by running
  1036             // any annotation processors.
  1037             if (unrecoverableError()) {
  1038                 log.reportDeferredDiagnostics();
  1039                 return this;
  1043         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1044         // by initProcessAnnotations
  1046         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1048         if (!processAnnotations) {
  1049             // If there are no annotation processors present, and
  1050             // annotation processing is to occur with compilation,
  1051             // emit a warning.
  1052             if (options.isSet(PROC, "only")) {
  1053                 log.warning("proc.proc-only.requested.no.procs");
  1054                 todo.clear();
  1056             // If not processing annotations, classnames must be empty
  1057             if (!classnames.isEmpty()) {
  1058                 log.error("proc.no.explicit.annotation.processing.requested",
  1059                           classnames);
  1061             log.reportDeferredDiagnostics();
  1062             return this; // continue regular compilation
  1065         try {
  1066             List<ClassSymbol> classSymbols = List.nil();
  1067             List<PackageSymbol> pckSymbols = List.nil();
  1068             if (!classnames.isEmpty()) {
  1069                  // Check for explicit request for annotation
  1070                  // processing
  1071                 if (!explicitAnnotationProcessingRequested()) {
  1072                     log.error("proc.no.explicit.annotation.processing.requested",
  1073                               classnames);
  1074                     log.reportDeferredDiagnostics();
  1075                     return this; // TODO: Will this halt compilation?
  1076                 } else {
  1077                     boolean errors = false;
  1078                     for (String nameStr : classnames) {
  1079                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
  1080                         if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
  1081                             log.error("proc.cant.find.class", nameStr);
  1082                             errors = true;
  1083                             continue;
  1085                         try {
  1086                             if (sym.kind == Kinds.PCK)
  1087                                 sym.complete();
  1088                             if (sym.exists()) {
  1089                                 if (sym.kind == Kinds.PCK)
  1090                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1091                                 else
  1092                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1093                                 continue;
  1095                             Assert.check(sym.kind == Kinds.PCK);
  1096                             log.warning("proc.package.does.not.exist", nameStr);
  1097                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1098                         } catch (CompletionFailure e) {
  1099                             log.error("proc.cant.find.class", nameStr);
  1100                             errors = true;
  1101                             continue;
  1104                     if (errors) {
  1105                         log.reportDeferredDiagnostics();
  1106                         return this;
  1110             try {
  1111                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
  1112                 if (c != this)
  1113                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1114                 // doProcessing will have handled deferred diagnostics
  1115                 Assert.check(c.log.deferDiagnostics == false
  1116                         && c.log.deferredDiagnostics.size() == 0);
  1117                 return c;
  1118             } finally {
  1119                 procEnvImpl.close();
  1121         } catch (CompletionFailure ex) {
  1122             log.error("cant.access", ex.sym, ex.getDetailValue());
  1123             log.reportDeferredDiagnostics();
  1124             return this;
  1128     private boolean unrecoverableError() {
  1129         for (JCDiagnostic d: log.deferredDiagnostics) {
  1130             if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
  1131                 return true;
  1133         return false;
  1136     boolean explicitAnnotationProcessingRequested() {
  1137         return
  1138             explicitAnnotationProcessingRequested ||
  1139             explicitAnnotationProcessingRequested(options);
  1142     static boolean explicitAnnotationProcessingRequested(Options options) {
  1143         return
  1144             options.isSet(PROCESSOR) ||
  1145             options.isSet(PROCESSORPATH) ||
  1146             options.isSet(PROC, "only") ||
  1147             options.isSet(XPRINT);
  1150     /**
  1151      * Attribute a list of parse trees, such as found on the "todo" list.
  1152      * Note that attributing classes may cause additional files to be
  1153      * parsed and entered via the SourceCompleter.
  1154      * Attribution of the entries in the list does not stop if any errors occur.
  1155      * @returns a list of environments for attributd classes.
  1156      */
  1157     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1158         ListBuffer<Env<AttrContext>> results = lb();
  1159         while (!envs.isEmpty())
  1160             results.append(attribute(envs.remove()));
  1161         return stopIfError(CompileState.ATTR, results);
  1164     /**
  1165      * Attribute a parse tree.
  1166      * @returns the attributed parse tree
  1167      */
  1168     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1169         if (compileStates.isDone(env, CompileState.ATTR))
  1170             return env;
  1172         if (verboseCompilePolicy)
  1173             printNote("[attribute " + env.enclClass.sym + "]");
  1174         if (verbose)
  1175             log.printVerbose("checking.attribution", env.enclClass.sym);
  1177         if (taskListener != null) {
  1178             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1179             taskListener.started(e);
  1182         JavaFileObject prev = log.useSource(
  1183                                   env.enclClass.sym.sourcefile != null ?
  1184                                   env.enclClass.sym.sourcefile :
  1185                                   env.toplevel.sourcefile);
  1186         try {
  1187             attr.attrib(env);
  1188             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1189                 //if in fail-over mode, ensure that AST expression nodes
  1190                 //are correctly initialized (e.g. they have a type/symbol)
  1191                 attr.postAttr(env);
  1193             compileStates.put(env, CompileState.ATTR);
  1195         finally {
  1196             log.useSource(prev);
  1199         return env;
  1202     /**
  1203      * Perform dataflow checks on attributed parse trees.
  1204      * These include checks for definite assignment and unreachable statements.
  1205      * If any errors occur, an empty list will be returned.
  1206      * @returns the list of attributed parse trees
  1207      */
  1208     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1209         ListBuffer<Env<AttrContext>> results = lb();
  1210         for (Env<AttrContext> env: envs) {
  1211             flow(env, results);
  1213         return stopIfError(CompileState.FLOW, results);
  1216     /**
  1217      * Perform dataflow checks on an attributed parse tree.
  1218      */
  1219     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1220         ListBuffer<Env<AttrContext>> results = lb();
  1221         flow(env, results);
  1222         return stopIfError(CompileState.FLOW, results);
  1225     /**
  1226      * Perform dataflow checks on an attributed parse tree.
  1227      */
  1228     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1229         try {
  1230             if (shouldStop(CompileState.FLOW))
  1231                 return;
  1233             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1234                 results.add(env);
  1235                 return;
  1238             if (verboseCompilePolicy)
  1239                 printNote("[flow " + env.enclClass.sym + "]");
  1240             JavaFileObject prev = log.useSource(
  1241                                                 env.enclClass.sym.sourcefile != null ?
  1242                                                 env.enclClass.sym.sourcefile :
  1243                                                 env.toplevel.sourcefile);
  1244             try {
  1245                 make.at(Position.FIRSTPOS);
  1246                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1247                 flow.analyzeTree(env, localMake);
  1248                 compileStates.put(env, CompileState.FLOW);
  1250                 if (shouldStop(CompileState.FLOW))
  1251                     return;
  1253                 results.add(env);
  1255             finally {
  1256                 log.useSource(prev);
  1259         finally {
  1260             if (taskListener != null) {
  1261                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1262                 taskListener.finished(e);
  1267     /**
  1268      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1269      * for source or code generation.
  1270      * If any errors occur, an empty list will be returned.
  1271      * @returns a list containing the classes to be generated
  1272      */
  1273     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1274         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1275         for (Env<AttrContext> env: envs)
  1276             desugar(env, results);
  1277         return stopIfError(CompileState.FLOW, results);
  1280     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1281             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1283     /**
  1284      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1285      * for source or code generation. If the file was not listed on the command line,
  1286      * the current implicitSourcePolicy is taken into account.
  1287      * The preparation stops as soon as an error is found.
  1288      */
  1289     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1290         if (shouldStop(CompileState.TRANSTYPES))
  1291             return;
  1293         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1294                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1295             return;
  1298         if (compileStates.isDone(env, CompileState.LOWER)) {
  1299             results.addAll(desugaredEnvs.get(env));
  1300             return;
  1303         /**
  1304          * Ensure that superclasses of C are desugared before C itself. This is
  1305          * required for two reasons: (i) as erasure (TransTypes) destroys
  1306          * information needed in flow analysis and (ii) as some checks carried
  1307          * out during lowering require that all synthetic fields/methods have
  1308          * already been added to C and its superclasses.
  1309          */
  1310         class ScanNested extends TreeScanner {
  1311             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1312             @Override
  1313             public void visitClassDef(JCClassDecl node) {
  1314                 Type st = types.supertype(node.sym.type);
  1315                 if (st.tag == TypeTags.CLASS) {
  1316                     ClassSymbol c = st.tsym.outermostClass();
  1317                     Env<AttrContext> stEnv = enter.getEnv(c);
  1318                     if (stEnv != null && env != stEnv) {
  1319                         if (dependencies.add(stEnv))
  1320                             scan(stEnv.tree);
  1323                 super.visitClassDef(node);
  1326         ScanNested scanner = new ScanNested();
  1327         scanner.scan(env.tree);
  1328         for (Env<AttrContext> dep: scanner.dependencies) {
  1329         if (!compileStates.isDone(dep, CompileState.FLOW))
  1330             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1333         //We need to check for error another time as more classes might
  1334         //have been attributed and analyzed at this stage
  1335         if (shouldStop(CompileState.TRANSTYPES))
  1336             return;
  1338         if (verboseCompilePolicy)
  1339             printNote("[desugar " + env.enclClass.sym + "]");
  1341         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1342                                   env.enclClass.sym.sourcefile :
  1343                                   env.toplevel.sourcefile);
  1344         try {
  1345             //save tree prior to rewriting
  1346             JCTree untranslated = env.tree;
  1348             make.at(Position.FIRSTPOS);
  1349             TreeMaker localMake = make.forToplevel(env.toplevel);
  1351             if (env.tree instanceof JCCompilationUnit) {
  1352                 if (!(stubOutput || sourceOutput || printFlat)) {
  1353                     if (shouldStop(CompileState.LOWER))
  1354                         return;
  1355                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1356                     if (pdef.head != null) {
  1357                         Assert.check(pdef.tail.isEmpty());
  1358                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1361                 return;
  1364             if (stubOutput) {
  1365                 //emit stub Java source file, only for compilation
  1366                 //units enumerated explicitly on the command line
  1367                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1368                 if (untranslated instanceof JCClassDecl &&
  1369                     rootClasses.contains((JCClassDecl)untranslated) &&
  1370                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1371                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1372                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1374                 return;
  1377             if (shouldStop(CompileState.TRANSTYPES))
  1378                 return;
  1380             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1381             compileStates.put(env, CompileState.TRANSTYPES);
  1383             if (shouldStop(CompileState.LOWER))
  1384                 return;
  1386             if (sourceOutput) {
  1387                 //emit standard Java source file, only for compilation
  1388                 //units enumerated explicitly on the command line
  1389                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1390                 if (untranslated instanceof JCClassDecl &&
  1391                     rootClasses.contains((JCClassDecl)untranslated)) {
  1392                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1394                 return;
  1397             //translate out inner classes
  1398             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1399             compileStates.put(env, CompileState.LOWER);
  1401             if (shouldStop(CompileState.LOWER))
  1402                 return;
  1404             //generate code for each class
  1405             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1406                 JCClassDecl cdef = (JCClassDecl)l.head;
  1407                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1410         finally {
  1411             log.useSource(prev);
  1416     /** Generates the source or class file for a list of classes.
  1417      * The decision to generate a source file or a class file is
  1418      * based upon the compiler's options.
  1419      * Generation stops if an error occurs while writing files.
  1420      */
  1421     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1422         generate(queue, null);
  1425     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1426         if (shouldStop(CompileState.GENERATE))
  1427             return;
  1429         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1431         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1432             Env<AttrContext> env = x.fst;
  1433             JCClassDecl cdef = x.snd;
  1435             if (verboseCompilePolicy) {
  1436                 printNote("[generate "
  1437                                + (usePrintSource ? " source" : "code")
  1438                                + " " + cdef.sym + "]");
  1441             if (taskListener != null) {
  1442                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1443                 taskListener.started(e);
  1446             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1447                                       env.enclClass.sym.sourcefile :
  1448                                       env.toplevel.sourcefile);
  1449             try {
  1450                 JavaFileObject file;
  1451                 if (usePrintSource)
  1452                     file = printSource(env, cdef);
  1453                 else
  1454                     file = genCode(env, cdef);
  1455                 if (results != null && file != null)
  1456                     results.add(file);
  1457             } catch (IOException ex) {
  1458                 log.error(cdef.pos(), "class.cant.write",
  1459                           cdef.sym, ex.getMessage());
  1460                 return;
  1461             } finally {
  1462                 log.useSource(prev);
  1465             if (taskListener != null) {
  1466                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1467                 taskListener.finished(e);
  1472         // where
  1473         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1474             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1475             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1476             for (Env<AttrContext> env: envs) {
  1477                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1478                 if (sublist == null) {
  1479                     sublist = new ListBuffer<Env<AttrContext>>();
  1480                     map.put(env.toplevel, sublist);
  1482                 sublist.add(env);
  1484             return map;
  1487         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1488             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1489             class MethodBodyRemover extends TreeTranslator {
  1490                 @Override
  1491                 public void visitMethodDef(JCMethodDecl tree) {
  1492                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1493                     for (JCVariableDecl vd : tree.params)
  1494                         vd.mods.flags &= ~Flags.FINAL;
  1495                     tree.body = null;
  1496                     super.visitMethodDef(tree);
  1498                 @Override
  1499                 public void visitVarDef(JCVariableDecl tree) {
  1500                     if (tree.init != null && tree.init.type.constValue() == null)
  1501                         tree.init = null;
  1502                     super.visitVarDef(tree);
  1504                 @Override
  1505                 public void visitClassDef(JCClassDecl tree) {
  1506                     ListBuffer<JCTree> newdefs = lb();
  1507                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1508                         JCTree t = it.head;
  1509                         switch (t.getTag()) {
  1510                         case CLASSDEF:
  1511                             if (isInterface ||
  1512                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1513                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1514                                 newdefs.append(t);
  1515                             break;
  1516                         case METHODDEF:
  1517                             if (isInterface ||
  1518                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1519                                 ((JCMethodDecl) t).sym.name == names.init ||
  1520                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1521                                 newdefs.append(t);
  1522                             break;
  1523                         case VARDEF:
  1524                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1525                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1526                                 newdefs.append(t);
  1527                             break;
  1528                         default:
  1529                             break;
  1532                     tree.defs = newdefs.toList();
  1533                     super.visitClassDef(tree);
  1536             MethodBodyRemover r = new MethodBodyRemover();
  1537             return r.translate(cdef);
  1540     public void reportDeferredDiagnostics() {
  1541         if (errorCount() == 0
  1542                 && annotationProcessingOccurred
  1543                 && implicitSourceFilesRead
  1544                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1545             if (explicitAnnotationProcessingRequested())
  1546                 log.warning("proc.use.implicit");
  1547             else
  1548                 log.warning("proc.use.proc.or.implicit");
  1550         chk.reportDeferredDiagnostics();
  1553     /** Close the compiler, flushing the logs
  1554      */
  1555     public void close() {
  1556         close(true);
  1559     public void close(boolean disposeNames) {
  1560         rootClasses = null;
  1561         reader = null;
  1562         make = null;
  1563         writer = null;
  1564         enter = null;
  1565         if (todo != null)
  1566             todo.clear();
  1567         todo = null;
  1568         parserFactory = null;
  1569         syms = null;
  1570         source = null;
  1571         attr = null;
  1572         chk = null;
  1573         gen = null;
  1574         flow = null;
  1575         transTypes = null;
  1576         lower = null;
  1577         annotate = null;
  1578         types = null;
  1580         log.flush();
  1581         try {
  1582             fileManager.flush();
  1583         } catch (IOException e) {
  1584             throw new Abort(e);
  1585         } finally {
  1586             if (names != null && disposeNames)
  1587                 names.dispose();
  1588             names = null;
  1590             for (Closeable c: closeables) {
  1591                 try {
  1592                     c.close();
  1593                 } catch (IOException e) {
  1594                     // When javac uses JDK 7 as a baseline, this code would be
  1595                     // better written to set any/all exceptions from all the
  1596                     // Closeables as suppressed exceptions on the FatalError
  1597                     // that is thrown.
  1598                     JCDiagnostic msg = diagFactory.fragment("fatal.err.cant.close");
  1599                     throw new FatalError(msg, e);
  1605     protected void printNote(String lines) {
  1606         log.printRawLines(Log.WriterKind.NOTICE, lines);
  1609     /** Print numbers of errors and warnings.
  1610      */
  1611     protected void printCount(String kind, int count) {
  1612         if (count != 0) {
  1613             String key;
  1614             if (count == 1)
  1615                 key = "count." + kind;
  1616             else
  1617                 key = "count." + kind + ".plural";
  1618             log.printLines(WriterKind.ERROR, key, String.valueOf(count));
  1619             log.flush(Log.WriterKind.ERROR);
  1623     private static long now() {
  1624         return System.currentTimeMillis();
  1627     private static long elapsed(long then) {
  1628         return now() - then;
  1631     public void initRound(JavaCompiler prev) {
  1632         genEndPos = prev.genEndPos;
  1633         keepComments = prev.keepComments;
  1634         start_msec = prev.start_msec;
  1635         hasBeenUsed = true;
  1636         closeables = prev.closeables;
  1637         prev.closeables = List.nil();
  1640     public static void enableLogging() {
  1641         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1642         logger.setLevel(Level.ALL);
  1643         for (Handler h : logger.getParent().getHandlers()) {
  1644             h.setLevel(Level.ALL);

mercurial