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

Thu, 25 Feb 2010 12:26:39 -0800

author
jjg
date
Thu, 25 Feb 2010 12:26:39 -0800
changeset 507
dbcba45123cd
parent 504
6eca0895a644
child 510
72833a8a6086
permissions
-rw-r--r--

6929544: langtools source code uses statics qualified by instance variables
Reviewed-by: darcy

     1 /*
     2  * Copyright 1999-2009 Sun Microsystems, Inc.  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.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.main;
    28 import java.io.*;
    29 import java.util.HashSet;
    30 import java.util.LinkedHashSet;
    31 import java.util.LinkedHashMap;
    32 import java.util.Map;
    33 import java.util.MissingResourceException;
    34 import java.util.ResourceBundle;
    35 import java.util.Set;
    36 import java.util.logging.Handler;
    37 import java.util.logging.Level;
    38 import java.util.logging.Logger;
    40 import javax.tools.JavaFileManager;
    41 import javax.tools.JavaFileObject;
    42 import javax.tools.DiagnosticListener;
    44 import com.sun.tools.javac.file.JavacFileManager;
    45 import com.sun.source.util.TaskEvent;
    46 import com.sun.source.util.TaskListener;
    48 import com.sun.tools.javac.util.*;
    49 import com.sun.tools.javac.code.*;
    50 import com.sun.tools.javac.tree.*;
    51 import com.sun.tools.javac.parser.*;
    52 import com.sun.tools.javac.comp.*;
    53 import com.sun.tools.javac.jvm.*;
    55 import com.sun.tools.javac.code.Symbol.*;
    56 import com.sun.tools.javac.tree.JCTree.*;
    58 import com.sun.tools.javac.processing.*;
    59 import javax.annotation.processing.Processor;
    61 import static javax.tools.StandardLocation.CLASS_OUTPUT;
    62 import static com.sun.tools.javac.util.ListBuffer.lb;
    64 // TEMP, until we have a more efficient way to save doc comment info
    65 import com.sun.tools.javac.parser.DocCommentScanner;
    67 import java.util.HashMap;
    68 import java.util.Queue;
    69 import javax.lang.model.SourceVersion;
    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 API supported by Sun Microsystems.  If
    77  *  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.resource.missing", System.getProperty("java.version"));
   115             }
   116         }
   117         try {
   118             return versionRB.getString(key);
   119         }
   120         catch (MissingResourceException e) {
   121             return Log.getLocalizedString("version.unknown", System.getProperty("java.version"));
   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 module for the symbol table entry phases.
   234      */
   235     protected Enter enter;
   237     /** The symbol table.
   238      */
   239     protected Symtab syms;
   241     /** The language version.
   242      */
   243     protected Source source;
   245     /** The module for code generation.
   246      */
   247     protected Gen gen;
   249     /** The name table.
   250      */
   251     protected Names names;
   253     /** The attributor.
   254      */
   255     protected Attr attr;
   257     /** The attributor.
   258      */
   259     protected Check chk;
   261     /** The flow analyzer.
   262      */
   263     protected Flow flow;
   265     /** The type eraser.
   266      */
   267     protected TransTypes transTypes;
   269     /** The syntactic sugar desweetener.
   270      */
   271     protected Lower lower;
   273     /** The annotation annotator.
   274      */
   275     protected Annotate annotate;
   277     /** Force a completion failure on this name
   278      */
   279     protected final Name completionFailureName;
   281     /** Type utilities.
   282      */
   283     protected Types types;
   285     /** Access to file objects.
   286      */
   287     protected JavaFileManager fileManager;
   289     /** Factory for parsers.
   290      */
   291     protected ParserFactory parserFactory;
   293     /** Optional listener for progress events
   294      */
   295     protected TaskListener taskListener;
   297     /**
   298      * Annotation processing may require and provide a new instance
   299      * of the compiler to be used for the analyze and generate phases.
   300      */
   301     protected JavaCompiler delegateCompiler;
   303     /**
   304      * Flag set if any annotation processing occurred.
   305      **/
   306     protected boolean annotationProcessingOccurred;
   308     /**
   309      * Flag set if any implicit source files read.
   310      **/
   311     protected boolean implicitSourceFilesRead;
   313     protected Context context;
   315     /** Construct a new compiler using a shared context.
   316      */
   317     public JavaCompiler(final Context context) {
   318         this.context = context;
   319         context.put(compilerKey, this);
   321         // if fileManager not already set, register the JavacFileManager to be used
   322         if (context.get(JavaFileManager.class) == null)
   323             JavacFileManager.preRegister(context);
   325         names = Names.instance(context);
   326         log = Log.instance(context);
   327         diagFactory = JCDiagnostic.Factory.instance(context);
   328         reader = ClassReader.instance(context);
   329         make = TreeMaker.instance(context);
   330         writer = ClassWriter.instance(context);
   331         enter = Enter.instance(context);
   332         todo = Todo.instance(context);
   334         fileManager = context.get(JavaFileManager.class);
   335         parserFactory = ParserFactory.instance(context);
   337         try {
   338             // catch completion problems with predefineds
   339             syms = Symtab.instance(context);
   340         } catch (CompletionFailure ex) {
   341             // inlined Check.completionError as it is not initialized yet
   342             log.error("cant.access", ex.sym, ex.getDetailValue());
   343             if (ex instanceof ClassReader.BadClassFile)
   344                 throw new Abort();
   345         }
   346         source = Source.instance(context);
   347         attr = Attr.instance(context);
   348         chk = Check.instance(context);
   349         gen = Gen.instance(context);
   350         flow = Flow.instance(context);
   351         transTypes = TransTypes.instance(context);
   352         lower = Lower.instance(context);
   353         annotate = Annotate.instance(context);
   354         types = Types.instance(context);
   355         taskListener = context.get(TaskListener.class);
   357         reader.sourceCompleter = this;
   359         Options options = Options.instance(context);
   361         verbose       = options.get("-verbose")       != null;
   362         sourceOutput  = options.get("-printsource")   != null; // used to be -s
   363         stubOutput    = options.get("-stubs")         != null;
   364         relax         = options.get("-relax")         != null;
   365         printFlat     = options.get("-printflat")     != null;
   366         attrParseOnly = options.get("-attrparseonly") != null;
   367         encoding      = options.get("-encoding");
   368         lineDebugInfo = options.get("-g:")            == null ||
   369                         options.get("-g:lines")       != null;
   370         genEndPos     = options.get("-Xjcov")         != null ||
   371                         context.get(DiagnosticListener.class) != null;
   372         devVerbose    = options.get("dev") != null;
   373         processPcks   = options.get("process.packages") != null;
   374         werror        = options.get("-Werror")        != null;
   376         verboseCompilePolicy = options.get("verboseCompilePolicy") != null;
   378         if (attrParseOnly)
   379             compilePolicy = CompilePolicy.ATTR_ONLY;
   380         else
   381             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   383         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   385         completionFailureName =
   386             (options.get("failcomplete") != null)
   387             ? names.fromString(options.get("failcomplete"))
   388             : null;
   390         shouldStopPolicy =
   391             (options.get("shouldStopPolicy") != null)
   392             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   393             : null;
   394         if (options.get("oldDiags") == null)
   395             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   396     }
   398     /* Switches:
   399      */
   401     /** Verbose output.
   402      */
   403     public boolean verbose;
   405     /** Emit plain Java source files rather than class files.
   406      */
   407     public boolean sourceOutput;
   409     /** Emit stub source files rather than class files.
   410      */
   411     public boolean stubOutput;
   413     /** Generate attributed parse tree only.
   414      */
   415     public boolean attrParseOnly;
   417     /** Switch: relax some constraints for producing the jsr14 prototype.
   418      */
   419     boolean relax;
   421     /** Debug switch: Emit Java sources after inner class flattening.
   422      */
   423     public boolean printFlat;
   425     /** The encoding to be used for source input.
   426      */
   427     public String encoding;
   429     /** Generate code with the LineNumberTable attribute for debugging
   430      */
   431     public boolean lineDebugInfo;
   433     /** Switch: should we store the ending positions?
   434      */
   435     public boolean genEndPos;
   437     /** Switch: should we debug ignored exceptions
   438      */
   439     protected boolean devVerbose;
   441     /** Switch: should we (annotation) process packages as well
   442      */
   443     protected boolean processPcks;
   445     /** Switch: treat warnings as errors
   446      */
   447     protected boolean werror;
   449     /** Switch: is annotation processing requested explitly via
   450      * CompilationTask.setProcessors?
   451      */
   452     protected boolean explicitAnnotationProcessingRequested = false;
   454     /**
   455      * The policy for the order in which to perform the compilation
   456      */
   457     protected CompilePolicy compilePolicy;
   459     /**
   460      * The policy for what to do with implicitly read source files
   461      */
   462     protected ImplicitSourcePolicy implicitSourcePolicy;
   464     /**
   465      * Report activity related to compilePolicy
   466      */
   467     public boolean verboseCompilePolicy;
   469     /**
   470      * Policy of how far to continue processing. null means until first
   471      * error.
   472      */
   473     public CompileState shouldStopPolicy;
   475     /** A queue of all as yet unattributed classes.
   476      */
   477     public Todo todo;
   479     /** Ordered list of compiler phases for each compilation unit. */
   480     public enum CompileState {
   481         PARSE(1),
   482         ENTER(2),
   483         PROCESS(3),
   484         ATTR(4),
   485         FLOW(5),
   486         TRANSTYPES(6),
   487         LOWER(7),
   488         GENERATE(8);
   489         CompileState(int value) {
   490             this.value = value;
   491         }
   492         boolean isDone(CompileState other) {
   493             return value >= other.value;
   494         }
   495         private int value;
   496     };
   497     /** Partial map to record which compiler phases have been executed
   498      * for each compilation unit. Used for ATTR and FLOW phases.
   499      */
   500     protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
   501         private static final long serialVersionUID = 1812267524140424433L;
   502         boolean isDone(Env<AttrContext> env, CompileState cs) {
   503             CompileState ecs = get(env);
   504             return ecs != null && ecs.isDone(cs);
   505         }
   506     }
   507     private CompileStates compileStates = new CompileStates();
   509     /** The set of currently compiled inputfiles, needed to ensure
   510      *  we don't accidentally overwrite an input file when -s is set.
   511      *  initialized by `compile'.
   512      */
   513     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   515     protected boolean shouldStop(CompileState cs) {
   516         if (shouldStopPolicy == null)
   517             return (errorCount() > 0);
   518         else
   519             return cs.ordinal() > shouldStopPolicy.ordinal();
   520     }
   522     /** The number of errors reported so far.
   523      */
   524     public int errorCount() {
   525         if (delegateCompiler != null && delegateCompiler != this)
   526             return delegateCompiler.errorCount();
   527         else {
   528             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   529                 log.error("warnings.and.werror");
   530             }
   531         }
   532             return log.nerrors;
   533     }
   535     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   536         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   537     }
   539     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   540         return shouldStop(cs) ? List.<T>nil() : list;
   541     }
   543     /** The number of warnings reported so far.
   544      */
   545     public int warningCount() {
   546         if (delegateCompiler != null && delegateCompiler != this)
   547             return delegateCompiler.warningCount();
   548         else
   549             return log.nwarnings;
   550     }
   552     /** Try to open input stream with given name.
   553      *  Report an error if this fails.
   554      *  @param filename   The file name of the input stream to be opened.
   555      */
   556     public CharSequence readSource(JavaFileObject filename) {
   557         try {
   558             inputFiles.add(filename);
   559             return filename.getCharContent(false);
   560         } catch (IOException e) {
   561             log.error("error.reading.file", filename, e.getLocalizedMessage());
   562             return null;
   563         }
   564     }
   566     /** Parse contents of input stream.
   567      *  @param filename     The name of the file from which input stream comes.
   568      *  @param input        The input stream to be parsed.
   569      */
   570     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   571         long msec = now();
   572         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   573                                       null, List.<JCTree>nil());
   574         if (content != null) {
   575             if (verbose) {
   576                 printVerbose("parsing.started", filename);
   577             }
   578             if (taskListener != null) {
   579                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   580                 taskListener.started(e);
   581             }
   582             int initialErrorCount = log.nerrors;
   583             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   584             tree = parser.parseCompilationUnit();
   585             log.unrecoverableError |= (log.nerrors > initialErrorCount);
   586             if (verbose) {
   587                 printVerbose("parsing.done", Long.toString(elapsed(msec)));
   588             }
   589         }
   591         tree.sourcefile = filename;
   593         if (content != null && taskListener != null) {
   594             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   595             taskListener.finished(e);
   596         }
   598         return tree;
   599     }
   600     // where
   601         public boolean keepComments = false;
   602         protected boolean keepComments() {
   603             return keepComments || sourceOutput || stubOutput;
   604         }
   607     /** Parse contents of file.
   608      *  @param filename     The name of the file to be parsed.
   609      */
   610     @Deprecated
   611     public JCTree.JCCompilationUnit parse(String filename) throws IOException {
   612         JavacFileManager fm = (JavacFileManager)fileManager;
   613         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   614     }
   616     /** Parse contents of file.
   617      *  @param filename     The name of the file to be parsed.
   618      */
   619     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   620         JavaFileObject prev = log.useSource(filename);
   621         try {
   622             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   623             if (t.endPositions != null)
   624                 log.setEndPosTable(filename, t.endPositions);
   625             return t;
   626         } finally {
   627             log.useSource(prev);
   628         }
   629     }
   631     /** Resolve an identifier.
   632      * @param name      The identifier to resolve
   633      */
   634     public Symbol resolveIdent(String name) {
   635         if (name.equals(""))
   636             return syms.errSymbol;
   637         JavaFileObject prev = log.useSource(null);
   638         try {
   639             JCExpression tree = null;
   640             for (String s : name.split("\\.", -1)) {
   641                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   642                     return syms.errSymbol;
   643                 tree = (tree == null) ? make.Ident(names.fromString(s))
   644                                       : make.Select(tree, names.fromString(s));
   645             }
   646             JCCompilationUnit toplevel =
   647                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   648             toplevel.packge = syms.unnamedPackage;
   649             return attr.attribIdent(tree, toplevel);
   650         } finally {
   651             log.useSource(prev);
   652         }
   653     }
   655     /** Emit plain Java source for a class.
   656      *  @param env    The attribution environment of the outermost class
   657      *                containing this class.
   658      *  @param cdef   The class definition to be printed.
   659      */
   660     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   661         JavaFileObject outFile
   662             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   663                                                cdef.sym.flatname.toString(),
   664                                                JavaFileObject.Kind.SOURCE,
   665                                                null);
   666         if (inputFiles.contains(outFile)) {
   667             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   668             return null;
   669         } else {
   670             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   671             try {
   672                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   673                 if (verbose)
   674                     printVerbose("wrote.file", outFile);
   675             } finally {
   676                 out.close();
   677             }
   678             return outFile;
   679         }
   680     }
   682     /** Generate code and emit a class file for a given class
   683      *  @param env    The attribution environment of the outermost class
   684      *                containing this class.
   685      *  @param cdef   The class definition from which code is generated.
   686      */
   687     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   688         try {
   689             if (gen.genClass(env, cdef) && (errorCount() == 0))
   690                 return writer.writeClass(cdef.sym);
   691         } catch (ClassWriter.PoolOverflow ex) {
   692             log.error(cdef.pos(), "limit.pool");
   693         } catch (ClassWriter.StringOverflow ex) {
   694             log.error(cdef.pos(), "limit.string.overflow",
   695                       ex.value.substring(0, 20));
   696         } catch (CompletionFailure ex) {
   697             chk.completionError(cdef.pos(), ex);
   698         }
   699         return null;
   700     }
   702     /** Complete compiling a source file that has been accessed
   703      *  by the class file reader.
   704      *  @param c          The class the source file of which needs to be compiled.
   705      *  @param filename   The name of the source file.
   706      *  @param f          An input stream that reads the source file.
   707      */
   708     public void complete(ClassSymbol c) throws CompletionFailure {
   709 //      System.err.println("completing " + c);//DEBUG
   710         if (completionFailureName == c.fullname) {
   711             throw new CompletionFailure(c, "user-selected completion failure by class name");
   712         }
   713         JCCompilationUnit tree;
   714         JavaFileObject filename = c.classfile;
   715         JavaFileObject prev = log.useSource(filename);
   717         try {
   718             tree = parse(filename, filename.getCharContent(false));
   719         } catch (IOException e) {
   720             log.error("error.reading.file", filename, e);
   721             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   722         } finally {
   723             log.useSource(prev);
   724         }
   726         if (taskListener != null) {
   727             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   728             taskListener.started(e);
   729         }
   731         enter.complete(List.of(tree), c);
   733         if (taskListener != null) {
   734             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   735             taskListener.finished(e);
   736         }
   738         if (enter.getEnv(c) == null) {
   739             boolean isPkgInfo =
   740                 tree.sourcefile.isNameCompatible("package-info",
   741                                                  JavaFileObject.Kind.SOURCE);
   742             if (isPkgInfo) {
   743                 if (enter.getEnv(tree.packge) == null) {
   744                     JCDiagnostic diag =
   745                         diagFactory.fragment("file.does.not.contain.package",
   746                                                  c.location());
   747                     throw reader.new BadClassFile(c, filename, diag);
   748                 }
   749             } else {
   750                 JCDiagnostic diag =
   751                         diagFactory.fragment("file.doesnt.contain.class",
   752                                             c.getQualifiedName());
   753                 throw reader.new BadClassFile(c, filename, diag);
   754             }
   755         }
   757         implicitSourceFilesRead = true;
   758     }
   760     /** Track when the JavaCompiler has been used to compile something. */
   761     private boolean hasBeenUsed = false;
   762     private long start_msec = 0;
   763     public long elapsed_msec = 0;
   765     public void compile(List<JavaFileObject> sourceFileObject)
   766         throws Throwable {
   767         compile(sourceFileObject, List.<String>nil(), null);
   768     }
   770     /**
   771      * Main method: compile a list of files, return all compiled classes
   772      *
   773      * @param sourceFileObjects file objects to be compiled
   774      * @param classnames class names to process for annotations
   775      * @param processors user provided annotation processors to bypass
   776      * discovery, {@code null} means that no processors were provided
   777      */
   778     public void compile(List<JavaFileObject> sourceFileObjects,
   779                         List<String> classnames,
   780                         Iterable<? extends Processor> processors)
   781         throws IOException // TODO: temp, from JavacProcessingEnvironment
   782     {
   783         if (processors != null && processors.iterator().hasNext())
   784             explicitAnnotationProcessingRequested = true;
   785         // as a JavaCompiler can only be used once, throw an exception if
   786         // it has been used before.
   787         if (hasBeenUsed)
   788             throw new AssertionError("attempt to reuse JavaCompiler");
   789         hasBeenUsed = true;
   791         start_msec = now();
   792         try {
   793             initProcessAnnotations(processors);
   795             // These method calls must be chained to avoid memory leaks
   796             delegateCompiler =
   797                 processAnnotations(
   798                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   799                     classnames);
   801             delegateCompiler.compile2();
   802             delegateCompiler.close();
   803             elapsed_msec = delegateCompiler.elapsed_msec;
   804         } catch (Abort ex) {
   805             if (devVerbose)
   806                 ex.printStackTrace();
   807         } finally {
   808             if (procEnvImpl != null)
   809                 procEnvImpl.close();
   810         }
   811     }
   813     /**
   814      * The phases following annotation processing: attribution,
   815      * desugar, and finally code generation.
   816      */
   817     private void compile2() {
   818         try {
   819             switch (compilePolicy) {
   820             case ATTR_ONLY:
   821                 attribute(todo);
   822                 break;
   824             case CHECK_ONLY:
   825                 flow(attribute(todo));
   826                 break;
   828             case SIMPLE:
   829                 generate(desugar(flow(attribute(todo))));
   830                 break;
   832             case BY_FILE: {
   833                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   834                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   835                         generate(desugar(flow(attribute(q.remove()))));
   836                     }
   837                 }
   838                 break;
   840             case BY_TODO:
   841                 while (!todo.isEmpty())
   842                     generate(desugar(flow(attribute(todo.remove()))));
   843                 break;
   845             default:
   846                 assert false: "unknown compile policy";
   847             }
   848         } catch (Abort ex) {
   849             if (devVerbose)
   850                 ex.printStackTrace();
   851         }
   853         if (verbose) {
   854             elapsed_msec = elapsed(start_msec);
   855             printVerbose("total", Long.toString(elapsed_msec));
   856         }
   858         reportDeferredDiagnostics();
   860         if (!log.hasDiagnosticListener()) {
   861             printCount("error", errorCount());
   862             printCount("warn", warningCount());
   863         }
   864     }
   866     private List<JCClassDecl> rootClasses;
   868     /**
   869      * Parses a list of files.
   870      */
   871    public List<JCCompilationUnit> parseFiles(List<JavaFileObject> fileObjects) throws IOException {
   872        if (shouldStop(CompileState.PARSE))
   873            return List.nil();
   875         //parse all files
   876         ListBuffer<JCCompilationUnit> trees = lb();
   877         for (JavaFileObject fileObject : fileObjects)
   878             trees.append(parse(fileObject));
   879         return trees.toList();
   880     }
   882     /**
   883      * Enter the symbols found in a list of parse trees.
   884      * As a side-effect, this puts elements on the "todo" list.
   885      * Also stores a list of all top level classes in rootClasses.
   886      */
   887     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   888         //enter symbols for all files
   889         if (taskListener != null) {
   890             for (JCCompilationUnit unit: roots) {
   891                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   892                 taskListener.started(e);
   893             }
   894         }
   896         enter.main(roots);
   898         if (taskListener != null) {
   899             for (JCCompilationUnit unit: roots) {
   900                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   901                 taskListener.finished(e);
   902             }
   903         }
   905         //If generating source, remember the classes declared in
   906         //the original compilation units listed on the command line.
   907         if (sourceOutput || stubOutput) {
   908             ListBuffer<JCClassDecl> cdefs = lb();
   909             for (JCCompilationUnit unit : roots) {
   910                 for (List<JCTree> defs = unit.defs;
   911                      defs.nonEmpty();
   912                      defs = defs.tail) {
   913                     if (defs.head instanceof JCClassDecl)
   914                         cdefs.append((JCClassDecl)defs.head);
   915                 }
   916             }
   917             rootClasses = cdefs.toList();
   918         }
   919         return roots;
   920     }
   922     /**
   923      * Set to true to enable skeleton annotation processing code.
   924      * Currently, we assume this variable will be replaced more
   925      * advanced logic to figure out if annotation processing is
   926      * needed.
   927      */
   928     boolean processAnnotations = false;
   930     /**
   931      * Object to handle annotation processing.
   932      */
   933     private JavacProcessingEnvironment procEnvImpl = null;
   935     /**
   936      * Check if we should process annotations.
   937      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
   938      * to catch doc comments, and set keepComments so the parser records them in
   939      * the compilation unit.
   940      *
   941      * @param processors user provided annotation processors to bypass
   942      * discovery, {@code null} means that no processors were provided
   943      */
   944     public void initProcessAnnotations(Iterable<? extends Processor> processors)
   945                 throws IOException {
   946         // Process annotations if processing is not disabled and there
   947         // is at least one Processor available.
   948         Options options = Options.instance(context);
   949         if (options.get("-proc:none") != null) {
   950             processAnnotations = false;
   951         } else if (procEnvImpl == null) {
   952             procEnvImpl = new JavacProcessingEnvironment(context, processors);
   953             processAnnotations = procEnvImpl.atLeastOneProcessor();
   955             if (processAnnotations) {
   956                 if (context.get(Scanner.Factory.scannerFactoryKey) == null)
   957                     DocCommentScanner.Factory.preRegister(context);
   958                 options.put("save-parameter-names", "save-parameter-names");
   959                 reader.saveParameterNames = true;
   960                 keepComments = true;
   961                 if (taskListener != null)
   962                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
   965             } else { // free resources
   966                 procEnvImpl.close();
   967             }
   968         }
   969     }
   971     // TODO: called by JavacTaskImpl
   972     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots)
   973             throws IOException {
   974         return processAnnotations(roots, List.<String>nil());
   975     }
   977     /**
   978      * Process any anotations found in the specifed compilation units.
   979      * @param roots a list of compilation units
   980      * @return an instance of the compiler in which to complete the compilation
   981      */
   982     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
   983                                            List<String> classnames)
   984         throws IOException  { // TODO: see TEMP note in JavacProcessingEnvironment
   985         if (shouldStop(CompileState.PROCESS)) {
   986             // Errors were encountered.  If todo is empty, then the
   987             // encountered errors were parse errors.  Otherwise, the
   988             // errors were found during the enter phase which should
   989             // be ignored when processing annotations.
   991             if (todo.isEmpty())
   992                 return this;
   993         }
   995         // ASSERT: processAnnotations and procEnvImpl should have been set up by
   996         // by initProcessAnnotations
   998         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1000         if (!processAnnotations) {
  1001             // If there are no annotation processors present, and
  1002             // annotation processing is to occur with compilation,
  1003             // emit a warning.
  1004             Options options = Options.instance(context);
  1005             if (options.get("-proc:only") != null) {
  1006                 log.warning("proc.proc-only.requested.no.procs");
  1007                 todo.clear();
  1009             // If not processing annotations, classnames must be empty
  1010             if (!classnames.isEmpty()) {
  1011                 log.error("proc.no.explicit.annotation.processing.requested",
  1012                           classnames);
  1014             return this; // continue regular compilation
  1017         try {
  1018             List<ClassSymbol> classSymbols = List.nil();
  1019             List<PackageSymbol> pckSymbols = List.nil();
  1020             if (!classnames.isEmpty()) {
  1021                  // Check for explicit request for annotation
  1022                  // processing
  1023                 if (!explicitAnnotationProcessingRequested()) {
  1024                     log.error("proc.no.explicit.annotation.processing.requested",
  1025                               classnames);
  1026                     return this; // TODO: Will this halt compilation?
  1027                 } else {
  1028                     boolean errors = false;
  1029                     for (String nameStr : classnames) {
  1030                         Symbol sym = resolveIdent(nameStr);
  1031                         if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
  1032                             log.error("proc.cant.find.class", nameStr);
  1033                             errors = true;
  1034                             continue;
  1036                         try {
  1037                             if (sym.kind == Kinds.PCK)
  1038                                 sym.complete();
  1039                             if (sym.exists()) {
  1040                                 Name name = names.fromString(nameStr);
  1041                                 if (sym.kind == Kinds.PCK)
  1042                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1043                                 else
  1044                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1045                                 continue;
  1047                             assert sym.kind == Kinds.PCK;
  1048                             log.warning("proc.package.does.not.exist", nameStr);
  1049                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1050                         } catch (CompletionFailure e) {
  1051                             log.error("proc.cant.find.class", nameStr);
  1052                             errors = true;
  1053                             continue;
  1056                     if (errors)
  1057                         return this;
  1060             try {
  1061                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
  1062                 if (c != this)
  1063                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1064                 return c;
  1065             } finally {
  1066                 procEnvImpl.close();
  1068         } catch (CompletionFailure ex) {
  1069             log.error("cant.access", ex.sym, ex.getDetailValue());
  1070             return this;
  1075     boolean explicitAnnotationProcessingRequested() {
  1076         Options options = Options.instance(context);
  1077         return
  1078             explicitAnnotationProcessingRequested ||
  1079             options.get("-processor") != null ||
  1080             options.get("-processorpath") != null ||
  1081             options.get("-proc:only") != null ||
  1082             options.get("-Xprint") != null;
  1085     /**
  1086      * Attribute a list of parse trees, such as found on the "todo" list.
  1087      * Note that attributing classes may cause additional files to be
  1088      * parsed and entered via the SourceCompleter.
  1089      * Attribution of the entries in the list does not stop if any errors occur.
  1090      * @returns a list of environments for attributd classes.
  1091      */
  1092     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1093         ListBuffer<Env<AttrContext>> results = lb();
  1094         while (!envs.isEmpty())
  1095             results.append(attribute(envs.remove()));
  1096         return stopIfError(CompileState.ATTR, results);
  1099     /**
  1100      * Attribute a parse tree.
  1101      * @returns the attributed parse tree
  1102      */
  1103     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1104         if (compileStates.isDone(env, CompileState.ATTR))
  1105             return env;
  1107         if (verboseCompilePolicy)
  1108             Log.printLines(log.noticeWriter, "[attribute " + env.enclClass.sym + "]");
  1109         if (verbose)
  1110             printVerbose("checking.attribution", env.enclClass.sym);
  1112         if (taskListener != null) {
  1113             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1114             taskListener.started(e);
  1117         JavaFileObject prev = log.useSource(
  1118                                   env.enclClass.sym.sourcefile != null ?
  1119                                   env.enclClass.sym.sourcefile :
  1120                                   env.toplevel.sourcefile);
  1121         try {
  1122             attr.attribClass(env.tree.pos(), env.enclClass.sym);
  1123             compileStates.put(env, CompileState.ATTR);
  1125         finally {
  1126             log.useSource(prev);
  1129         return env;
  1132     /**
  1133      * Perform dataflow checks on attributed parse trees.
  1134      * These include checks for definite assignment and unreachable statements.
  1135      * If any errors occur, an empty list will be returned.
  1136      * @returns the list of attributed parse trees
  1137      */
  1138     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1139         ListBuffer<Env<AttrContext>> results = lb();
  1140         for (Env<AttrContext> env: envs) {
  1141             flow(env, results);
  1143         return stopIfError(CompileState.FLOW, results);
  1146     /**
  1147      * Perform dataflow checks on an attributed parse tree.
  1148      */
  1149     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1150         ListBuffer<Env<AttrContext>> results = lb();
  1151         flow(env, results);
  1152         return stopIfError(CompileState.FLOW, results);
  1155     /**
  1156      * Perform dataflow checks on an attributed parse tree.
  1157      */
  1158     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1159         try {
  1160             if (shouldStop(CompileState.FLOW))
  1161                 return;
  1163             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1164                 results.add(env);
  1165                 return;
  1168             if (verboseCompilePolicy)
  1169                 printNote("[flow " + env.enclClass.sym + "]");
  1170             JavaFileObject prev = log.useSource(
  1171                                                 env.enclClass.sym.sourcefile != null ?
  1172                                                 env.enclClass.sym.sourcefile :
  1173                                                 env.toplevel.sourcefile);
  1174             try {
  1175                 make.at(Position.FIRSTPOS);
  1176                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1177                 flow.analyzeTree(env.tree, localMake);
  1178                 compileStates.put(env, CompileState.FLOW);
  1180                 if (shouldStop(CompileState.FLOW))
  1181                     return;
  1183                 results.add(env);
  1185             finally {
  1186                 log.useSource(prev);
  1189         finally {
  1190             if (taskListener != null) {
  1191                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1192                 taskListener.finished(e);
  1197     /**
  1198      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1199      * for source or code generation.
  1200      * If any errors occur, an empty list will be returned.
  1201      * @returns a list containing the classes to be generated
  1202      */
  1203     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1204         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1205         for (Env<AttrContext> env: envs)
  1206             desugar(env, results);
  1207         return stopIfError(CompileState.FLOW, results);
  1210     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1211             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1213     /**
  1214      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1215      * for source or code generation. If the file was not listed on the command line,
  1216      * the current implicitSourcePolicy is taken into account.
  1217      * The preparation stops as soon as an error is found.
  1218      */
  1219     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1220         if (shouldStop(CompileState.TRANSTYPES))
  1221             return;
  1223         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1224                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1225             return;
  1228         if (compileStates.isDone(env, CompileState.LOWER)) {
  1229             results.addAll(desugaredEnvs.get(env));
  1230             return;
  1233         /**
  1234          * Ensure that superclasses of C are desugared before C itself. This is
  1235          * required for two reasons: (i) as erasure (TransTypes) destroys
  1236          * information needed in flow analysis and (ii) as some checks carried
  1237          * out during lowering require that all synthetic fields/methods have
  1238          * already been added to C and its superclasses.
  1239          */
  1240         class ScanNested extends TreeScanner {
  1241             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1242             @Override
  1243             public void visitClassDef(JCClassDecl node) {
  1244                 Type st = types.supertype(node.sym.type);
  1245                 if (st.tag == TypeTags.CLASS) {
  1246                     ClassSymbol c = st.tsym.outermostClass();
  1247                     Env<AttrContext> stEnv = enter.getEnv(c);
  1248                     if (stEnv != null && env != stEnv) {
  1249                         if (dependencies.add(stEnv))
  1250                             scan(stEnv.tree);
  1253                 super.visitClassDef(node);
  1256         ScanNested scanner = new ScanNested();
  1257         scanner.scan(env.tree);
  1258         for (Env<AttrContext> dep: scanner.dependencies) {
  1259         if (!compileStates.isDone(dep, CompileState.FLOW))
  1260             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1263         //We need to check for error another time as more classes might
  1264         //have been attributed and analyzed at this stage
  1265         if (shouldStop(CompileState.TRANSTYPES))
  1266             return;
  1268         if (verboseCompilePolicy)
  1269             printNote("[desugar " + env.enclClass.sym + "]");
  1271         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1272                                   env.enclClass.sym.sourcefile :
  1273                                   env.toplevel.sourcefile);
  1274         try {
  1275             //save tree prior to rewriting
  1276             JCTree untranslated = env.tree;
  1278             make.at(Position.FIRSTPOS);
  1279             TreeMaker localMake = make.forToplevel(env.toplevel);
  1281             if (env.tree instanceof JCCompilationUnit) {
  1282                 if (!(stubOutput || sourceOutput || printFlat)) {
  1283                     if (shouldStop(CompileState.LOWER))
  1284                         return;
  1285                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1286                     if (pdef.head != null) {
  1287                         assert pdef.tail.isEmpty();
  1288                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1291                 return;
  1294             if (stubOutput) {
  1295                 //emit stub Java source file, only for compilation
  1296                 //units enumerated explicitly on the command line
  1297                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1298                 if (untranslated instanceof JCClassDecl &&
  1299                     rootClasses.contains((JCClassDecl)untranslated) &&
  1300                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1301                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1302                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1304                 return;
  1307             if (shouldStop(CompileState.TRANSTYPES))
  1308                 return;
  1310             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1311             compileStates.put(env, CompileState.TRANSTYPES);
  1313             if (shouldStop(CompileState.LOWER))
  1314                 return;
  1316             if (sourceOutput) {
  1317                 //emit standard Java source file, only for compilation
  1318                 //units enumerated explicitly on the command line
  1319                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1320                 if (untranslated instanceof JCClassDecl &&
  1321                     rootClasses.contains((JCClassDecl)untranslated)) {
  1322                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1324                 return;
  1327             //translate out inner classes
  1328             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1329             compileStates.put(env, CompileState.LOWER);
  1331             if (shouldStop(CompileState.LOWER))
  1332                 return;
  1334             //generate code for each class
  1335             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1336                 JCClassDecl cdef = (JCClassDecl)l.head;
  1337                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1340         finally {
  1341             log.useSource(prev);
  1346     /** Generates the source or class file for a list of classes.
  1347      * The decision to generate a source file or a class file is
  1348      * based upon the compiler's options.
  1349      * Generation stops if an error occurs while writing files.
  1350      */
  1351     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1352         generate(queue, null);
  1355     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1356         if (shouldStop(CompileState.GENERATE))
  1357             return;
  1359         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1361         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1362             Env<AttrContext> env = x.fst;
  1363             JCClassDecl cdef = x.snd;
  1365             if (verboseCompilePolicy) {
  1366                 printNote("[generate "
  1367                                + (usePrintSource ? " source" : "code")
  1368                                + " " + cdef.sym + "]");
  1371             if (taskListener != null) {
  1372                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1373                 taskListener.started(e);
  1376             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1377                                       env.enclClass.sym.sourcefile :
  1378                                       env.toplevel.sourcefile);
  1379             try {
  1380                 JavaFileObject file;
  1381                 if (usePrintSource)
  1382                     file = printSource(env, cdef);
  1383                 else
  1384                     file = genCode(env, cdef);
  1385                 if (results != null && file != null)
  1386                     results.add(file);
  1387             } catch (IOException ex) {
  1388                 log.error(cdef.pos(), "class.cant.write",
  1389                           cdef.sym, ex.getMessage());
  1390                 return;
  1391             } finally {
  1392                 log.useSource(prev);
  1395             if (taskListener != null) {
  1396                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1397                 taskListener.finished(e);
  1402         // where
  1403         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1404             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1405             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1406             for (Env<AttrContext> env: envs) {
  1407                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1408                 if (sublist == null) {
  1409                     sublist = new ListBuffer<Env<AttrContext>>();
  1410                     map.put(env.toplevel, sublist);
  1412                 sublist.add(env);
  1414             return map;
  1417         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1418             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1419             class MethodBodyRemover extends TreeTranslator {
  1420                 @Override
  1421                 public void visitMethodDef(JCMethodDecl tree) {
  1422                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1423                     for (JCVariableDecl vd : tree.params)
  1424                         vd.mods.flags &= ~Flags.FINAL;
  1425                     tree.body = null;
  1426                     super.visitMethodDef(tree);
  1428                 @Override
  1429                 public void visitVarDef(JCVariableDecl tree) {
  1430                     if (tree.init != null && tree.init.type.constValue() == null)
  1431                         tree.init = null;
  1432                     super.visitVarDef(tree);
  1434                 @Override
  1435                 public void visitClassDef(JCClassDecl tree) {
  1436                     ListBuffer<JCTree> newdefs = lb();
  1437                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1438                         JCTree t = it.head;
  1439                         switch (t.getTag()) {
  1440                         case JCTree.CLASSDEF:
  1441                             if (isInterface ||
  1442                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1443                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1444                                 newdefs.append(t);
  1445                             break;
  1446                         case JCTree.METHODDEF:
  1447                             if (isInterface ||
  1448                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1449                                 ((JCMethodDecl) t).sym.name == names.init ||
  1450                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1451                                 newdefs.append(t);
  1452                             break;
  1453                         case JCTree.VARDEF:
  1454                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1455                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1456                                 newdefs.append(t);
  1457                             break;
  1458                         default:
  1459                             break;
  1462                     tree.defs = newdefs.toList();
  1463                     super.visitClassDef(tree);
  1466             MethodBodyRemover r = new MethodBodyRemover();
  1467             return r.translate(cdef);
  1470     public void reportDeferredDiagnostics() {
  1471         if (annotationProcessingOccurred
  1472                 && implicitSourceFilesRead
  1473                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1474             if (explicitAnnotationProcessingRequested())
  1475                 log.warning("proc.use.implicit");
  1476             else
  1477                 log.warning("proc.use.proc.or.implicit");
  1479         chk.reportDeferredDiagnostics();
  1482     /** Close the compiler, flushing the logs
  1483      */
  1484     public void close() {
  1485         close(true);
  1488     public void close(boolean disposeNames) {
  1489         rootClasses = null;
  1490         reader = null;
  1491         make = null;
  1492         writer = null;
  1493         enter = null;
  1494         if (todo != null)
  1495             todo.clear();
  1496         todo = null;
  1497         parserFactory = null;
  1498         syms = null;
  1499         source = null;
  1500         attr = null;
  1501         chk = null;
  1502         gen = null;
  1503         flow = null;
  1504         transTypes = null;
  1505         lower = null;
  1506         annotate = null;
  1507         types = null;
  1509         log.flush();
  1510         try {
  1511             fileManager.flush();
  1512         } catch (IOException e) {
  1513             throw new Abort(e);
  1514         } finally {
  1515             if (names != null && disposeNames)
  1516                 names.dispose();
  1517             names = null;
  1521     protected void printNote(String lines) {
  1522         Log.printLines(log.noticeWriter, lines);
  1525     /** Output for "-verbose" option.
  1526      *  @param key The key to look up the correct internationalized string.
  1527      *  @param arg An argument for substitution into the output string.
  1528      */
  1529     protected void printVerbose(String key, Object arg) {
  1530         Log.printLines(log.noticeWriter, Log.getLocalizedString("verbose." + key, arg));
  1533     /** Print numbers of errors and warnings.
  1534      */
  1535     protected void printCount(String kind, int count) {
  1536         if (count != 0) {
  1537             String text;
  1538             if (count == 1)
  1539                 text = Log.getLocalizedString("count." + kind, String.valueOf(count));
  1540             else
  1541                 text = Log.getLocalizedString("count." + kind + ".plural", String.valueOf(count));
  1542             Log.printLines(log.errWriter, text);
  1543             log.errWriter.flush();
  1547     private static long now() {
  1548         return System.currentTimeMillis();
  1551     private static long elapsed(long then) {
  1552         return now() - then;
  1555     public void initRound(JavaCompiler prev) {
  1556         keepComments = prev.keepComments;
  1557         start_msec = prev.start_msec;
  1558         hasBeenUsed = true;
  1561     public static void enableLogging() {
  1562         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1563         logger.setLevel(Level.ALL);
  1564         for (Handler h : logger.getParent().getHandlers()) {
  1565             h.setLevel(Level.ALL);

mercurial