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

Mon, 23 Aug 2010 11:56:53 -0700

author
jjg
date
Mon, 23 Aug 2010 11:56:53 -0700
changeset 642
6b95dd682538
parent 617
62f3f07002ea
child 654
e9d09e97d669
permissions
-rw-r--r--

6975005: improve JavacProcessingEnvironment.Round abstraction
Reviewed-by: darcy

     1 /*
     2  * Copyright (c) 1999, 2009, 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.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 supported API.
    77  *  If you write code that depends on this, you do so at your own risk.
    78  *  This code and its internal interfaces are subject to change or
    79  *  deletion without notice.</b>
    80  */
    81 public class JavaCompiler implements ClassReader.SourceCompleter {
    82     /** The context key for the compiler. */
    83     protected static final Context.Key<JavaCompiler> compilerKey =
    84         new Context.Key<JavaCompiler>();
    86     /** Get the JavaCompiler instance for this context. */
    87     public static JavaCompiler instance(Context context) {
    88         JavaCompiler instance = context.get(compilerKey);
    89         if (instance == null)
    90             instance = new JavaCompiler(context);
    91         return instance;
    92     }
    94     /** The current version number as a string.
    95      */
    96     public static String version() {
    97         return version("release");  // mm.nn.oo[-milestone]
    98     }
   100     /** The current full version number as a string.
   101      */
   102     public static String fullVersion() {
   103         return version("full"); // mm.mm.oo[-milestone]-build
   104     }
   106     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   107     private static ResourceBundle versionRB;
   109     private static String version(String key) {
   110         if (versionRB == null) {
   111             try {
   112                 versionRB = ResourceBundle.getBundle(versionRBName);
   113             } catch (MissingResourceException e) {
   114                 return Log.getLocalizedString("version.not.available");
   115             }
   116         }
   117         try {
   118             return versionRB.getString(key);
   119         }
   120         catch (MissingResourceException e) {
   121             return Log.getLocalizedString("version.not.available");
   122         }
   123     }
   125     /**
   126      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   127      * are connected. Each individual file is processed by each phase in turn,
   128      * but with different compile policies, you can control the order in which
   129      * each class is processed through its next phase.
   130      *
   131      * <p>Generally speaking, the compiler will "fail fast" in the face of
   132      * errors, although not aggressively so. flow, desugar, etc become no-ops
   133      * once any errors have occurred. No attempt is currently made to determine
   134      * if it might be safe to process a class through its next phase because
   135      * it does not depend on any unrelated errors that might have occurred.
   136      */
   137     protected static enum CompilePolicy {
   138         /**
   139          * Just attribute the parse trees.
   140          */
   141         ATTR_ONLY,
   143         /**
   144          * Just attribute and do flow analysis on the parse trees.
   145          * This should catch most user errors.
   146          */
   147         CHECK_ONLY,
   149         /**
   150          * Attribute everything, then do flow analysis for everything,
   151          * then desugar everything, and only then generate output.
   152          * This means no output will be generated if there are any
   153          * errors in any classes.
   154          */
   155         SIMPLE,
   157         /**
   158          * Groups the classes for each source file together, then process
   159          * each group in a manner equivalent to the {@code SIMPLE} policy.
   160          * This means no output will be generated if there are any
   161          * errors in any of the classes in a source file.
   162          */
   163         BY_FILE,
   165         /**
   166          * Completely process each entry on the todo list in turn.
   167          * -- this is the same for 1.5.
   168          * Means output might be generated for some classes in a compilation unit
   169          * and not others.
   170          */
   171         BY_TODO;
   173         static CompilePolicy decode(String option) {
   174             if (option == null)
   175                 return DEFAULT_COMPILE_POLICY;
   176             else if (option.equals("attr"))
   177                 return ATTR_ONLY;
   178             else if (option.equals("check"))
   179                 return CHECK_ONLY;
   180             else if (option.equals("simple"))
   181                 return SIMPLE;
   182             else if (option.equals("byfile"))
   183                 return BY_FILE;
   184             else if (option.equals("bytodo"))
   185                 return BY_TODO;
   186             else
   187                 return DEFAULT_COMPILE_POLICY;
   188         }
   189     }
   191     private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   193     protected static enum ImplicitSourcePolicy {
   194         /** Don't generate or process implicitly read source files. */
   195         NONE,
   196         /** Generate classes for implicitly read source files. */
   197         CLASS,
   198         /** Like CLASS, but generate warnings if annotation processing occurs */
   199         UNSET;
   201         static ImplicitSourcePolicy decode(String option) {
   202             if (option == null)
   203                 return UNSET;
   204             else if (option.equals("none"))
   205                 return NONE;
   206             else if (option.equals("class"))
   207                 return CLASS;
   208             else
   209                 return UNSET;
   210         }
   211     }
   213     /** The log to be used for error reporting.
   214      */
   215     public Log log;
   217     /** Factory for creating diagnostic objects
   218      */
   219     JCDiagnostic.Factory diagFactory;
   221     /** The tree factory module.
   222      */
   223     protected TreeMaker make;
   225     /** The class reader.
   226      */
   227     protected ClassReader reader;
   229     /** The class writer.
   230      */
   231     protected ClassWriter writer;
   233     /** The 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, JavacFileManager.getMessage(e));
   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, JavacFileManager.getMessage(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(Iterable<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.
   987             // If log.unrecoverableError is set, the errors were parse errors
   988             // or other errors during enter which cannot be fixed by running
   989             // any annotation processors.
   990             if (log.unrecoverableError)
   991                 return this;
   992         }
   994         // ASSERT: processAnnotations and procEnvImpl should have been set up by
   995         // by initProcessAnnotations
   997         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
   999         if (!processAnnotations) {
  1000             // If there are no annotation processors present, and
  1001             // annotation processing is to occur with compilation,
  1002             // emit a warning.
  1003             Options options = Options.instance(context);
  1004             if (options.get("-proc:only") != null) {
  1005                 log.warning("proc.proc-only.requested.no.procs");
  1006                 todo.clear();
  1008             // If not processing annotations, classnames must be empty
  1009             if (!classnames.isEmpty()) {
  1010                 log.error("proc.no.explicit.annotation.processing.requested",
  1011                           classnames);
  1013             return this; // continue regular compilation
  1016         try {
  1017             List<ClassSymbol> classSymbols = List.nil();
  1018             List<PackageSymbol> pckSymbols = List.nil();
  1019             if (!classnames.isEmpty()) {
  1020                  // Check for explicit request for annotation
  1021                  // processing
  1022                 if (!explicitAnnotationProcessingRequested()) {
  1023                     log.error("proc.no.explicit.annotation.processing.requested",
  1024                               classnames);
  1025                     return this; // TODO: Will this halt compilation?
  1026                 } else {
  1027                     boolean errors = false;
  1028                     for (String nameStr : classnames) {
  1029                         Symbol sym = resolveIdent(nameStr);
  1030                         if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
  1031                             log.error("proc.cant.find.class", nameStr);
  1032                             errors = true;
  1033                             continue;
  1035                         try {
  1036                             if (sym.kind == Kinds.PCK)
  1037                                 sym.complete();
  1038                             if (sym.exists()) {
  1039                                 Name name = names.fromString(nameStr);
  1040                                 if (sym.kind == Kinds.PCK)
  1041                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1042                                 else
  1043                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1044                                 continue;
  1046                             assert sym.kind == Kinds.PCK;
  1047                             log.warning("proc.package.does.not.exist", nameStr);
  1048                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1049                         } catch (CompletionFailure e) {
  1050                             log.error("proc.cant.find.class", nameStr);
  1051                             errors = true;
  1052                             continue;
  1055                     if (errors)
  1056                         return this;
  1059             try {
  1060                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
  1061                 if (c != this)
  1062                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1063                 return c;
  1064             } finally {
  1065                 procEnvImpl.close();
  1067         } catch (CompletionFailure ex) {
  1068             log.error("cant.access", ex.sym, ex.getDetailValue());
  1069             return this;
  1074     boolean explicitAnnotationProcessingRequested() {
  1075         Options options = Options.instance(context);
  1076         return
  1077             explicitAnnotationProcessingRequested ||
  1078             options.get("-processor") != null ||
  1079             options.get("-processorpath") != null ||
  1080             options.get("-proc:only") != null ||
  1081             options.get("-Xprint") != null;
  1084     /**
  1085      * Attribute a list of parse trees, such as found on the "todo" list.
  1086      * Note that attributing classes may cause additional files to be
  1087      * parsed and entered via the SourceCompleter.
  1088      * Attribution of the entries in the list does not stop if any errors occur.
  1089      * @returns a list of environments for attributd classes.
  1090      */
  1091     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1092         ListBuffer<Env<AttrContext>> results = lb();
  1093         while (!envs.isEmpty())
  1094             results.append(attribute(envs.remove()));
  1095         return stopIfError(CompileState.ATTR, results);
  1098     /**
  1099      * Attribute a parse tree.
  1100      * @returns the attributed parse tree
  1101      */
  1102     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1103         if (compileStates.isDone(env, CompileState.ATTR))
  1104             return env;
  1106         if (verboseCompilePolicy)
  1107             printNote("[attribute " + env.enclClass.sym + "]");
  1108         if (verbose)
  1109             printVerbose("checking.attribution", env.enclClass.sym);
  1111         if (taskListener != null) {
  1112             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1113             taskListener.started(e);
  1116         JavaFileObject prev = log.useSource(
  1117                                   env.enclClass.sym.sourcefile != null ?
  1118                                   env.enclClass.sym.sourcefile :
  1119                                   env.toplevel.sourcefile);
  1120         try {
  1121             attr.attribClass(env.tree.pos(), env.enclClass.sym);
  1122             compileStates.put(env, CompileState.ATTR);
  1124         finally {
  1125             log.useSource(prev);
  1128         return env;
  1131     /**
  1132      * Perform dataflow checks on attributed parse trees.
  1133      * These include checks for definite assignment and unreachable statements.
  1134      * If any errors occur, an empty list will be returned.
  1135      * @returns the list of attributed parse trees
  1136      */
  1137     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1138         ListBuffer<Env<AttrContext>> results = lb();
  1139         for (Env<AttrContext> env: envs) {
  1140             flow(env, results);
  1142         return stopIfError(CompileState.FLOW, results);
  1145     /**
  1146      * Perform dataflow checks on an attributed parse tree.
  1147      */
  1148     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1149         ListBuffer<Env<AttrContext>> results = lb();
  1150         flow(env, results);
  1151         return stopIfError(CompileState.FLOW, results);
  1154     /**
  1155      * Perform dataflow checks on an attributed parse tree.
  1156      */
  1157     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1158         try {
  1159             if (shouldStop(CompileState.FLOW))
  1160                 return;
  1162             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1163                 results.add(env);
  1164                 return;
  1167             if (verboseCompilePolicy)
  1168                 printNote("[flow " + env.enclClass.sym + "]");
  1169             JavaFileObject prev = log.useSource(
  1170                                                 env.enclClass.sym.sourcefile != null ?
  1171                                                 env.enclClass.sym.sourcefile :
  1172                                                 env.toplevel.sourcefile);
  1173             try {
  1174                 make.at(Position.FIRSTPOS);
  1175                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1176                 flow.analyzeTree(env, localMake);
  1177                 compileStates.put(env, CompileState.FLOW);
  1179                 if (shouldStop(CompileState.FLOW))
  1180                     return;
  1182                 results.add(env);
  1184             finally {
  1185                 log.useSource(prev);
  1188         finally {
  1189             if (taskListener != null) {
  1190                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1191                 taskListener.finished(e);
  1196     /**
  1197      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1198      * for source or code generation.
  1199      * If any errors occur, an empty list will be returned.
  1200      * @returns a list containing the classes to be generated
  1201      */
  1202     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1203         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1204         for (Env<AttrContext> env: envs)
  1205             desugar(env, results);
  1206         return stopIfError(CompileState.FLOW, results);
  1209     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1210             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1212     /**
  1213      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1214      * for source or code generation. If the file was not listed on the command line,
  1215      * the current implicitSourcePolicy is taken into account.
  1216      * The preparation stops as soon as an error is found.
  1217      */
  1218     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1219         if (shouldStop(CompileState.TRANSTYPES))
  1220             return;
  1222         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1223                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1224             return;
  1227         if (compileStates.isDone(env, CompileState.LOWER)) {
  1228             results.addAll(desugaredEnvs.get(env));
  1229             return;
  1232         /**
  1233          * Ensure that superclasses of C are desugared before C itself. This is
  1234          * required for two reasons: (i) as erasure (TransTypes) destroys
  1235          * information needed in flow analysis and (ii) as some checks carried
  1236          * out during lowering require that all synthetic fields/methods have
  1237          * already been added to C and its superclasses.
  1238          */
  1239         class ScanNested extends TreeScanner {
  1240             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1241             @Override
  1242             public void visitClassDef(JCClassDecl node) {
  1243                 Type st = types.supertype(node.sym.type);
  1244                 if (st.tag == TypeTags.CLASS) {
  1245                     ClassSymbol c = st.tsym.outermostClass();
  1246                     Env<AttrContext> stEnv = enter.getEnv(c);
  1247                     if (stEnv != null && env != stEnv) {
  1248                         if (dependencies.add(stEnv))
  1249                             scan(stEnv.tree);
  1252                 super.visitClassDef(node);
  1255         ScanNested scanner = new ScanNested();
  1256         scanner.scan(env.tree);
  1257         for (Env<AttrContext> dep: scanner.dependencies) {
  1258         if (!compileStates.isDone(dep, CompileState.FLOW))
  1259             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1262         //We need to check for error another time as more classes might
  1263         //have been attributed and analyzed at this stage
  1264         if (shouldStop(CompileState.TRANSTYPES))
  1265             return;
  1267         if (verboseCompilePolicy)
  1268             printNote("[desugar " + env.enclClass.sym + "]");
  1270         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1271                                   env.enclClass.sym.sourcefile :
  1272                                   env.toplevel.sourcefile);
  1273         try {
  1274             //save tree prior to rewriting
  1275             JCTree untranslated = env.tree;
  1277             make.at(Position.FIRSTPOS);
  1278             TreeMaker localMake = make.forToplevel(env.toplevel);
  1280             if (env.tree instanceof JCCompilationUnit) {
  1281                 if (!(stubOutput || sourceOutput || printFlat)) {
  1282                     if (shouldStop(CompileState.LOWER))
  1283                         return;
  1284                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1285                     if (pdef.head != null) {
  1286                         assert pdef.tail.isEmpty();
  1287                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1290                 return;
  1293             if (stubOutput) {
  1294                 //emit stub Java source file, only for compilation
  1295                 //units enumerated explicitly on the command line
  1296                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1297                 if (untranslated instanceof JCClassDecl &&
  1298                     rootClasses.contains((JCClassDecl)untranslated) &&
  1299                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1300                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1301                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1303                 return;
  1306             if (shouldStop(CompileState.TRANSTYPES))
  1307                 return;
  1309             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1310             compileStates.put(env, CompileState.TRANSTYPES);
  1312             if (shouldStop(CompileState.LOWER))
  1313                 return;
  1315             if (sourceOutput) {
  1316                 //emit standard Java source file, only for compilation
  1317                 //units enumerated explicitly on the command line
  1318                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1319                 if (untranslated instanceof JCClassDecl &&
  1320                     rootClasses.contains((JCClassDecl)untranslated)) {
  1321                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1323                 return;
  1326             //translate out inner classes
  1327             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1328             compileStates.put(env, CompileState.LOWER);
  1330             if (shouldStop(CompileState.LOWER))
  1331                 return;
  1333             //generate code for each class
  1334             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1335                 JCClassDecl cdef = (JCClassDecl)l.head;
  1336                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1339         finally {
  1340             log.useSource(prev);
  1345     /** Generates the source or class file for a list of classes.
  1346      * The decision to generate a source file or a class file is
  1347      * based upon the compiler's options.
  1348      * Generation stops if an error occurs while writing files.
  1349      */
  1350     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1351         generate(queue, null);
  1354     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1355         if (shouldStop(CompileState.GENERATE))
  1356             return;
  1358         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1360         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1361             Env<AttrContext> env = x.fst;
  1362             JCClassDecl cdef = x.snd;
  1364             if (verboseCompilePolicy) {
  1365                 printNote("[generate "
  1366                                + (usePrintSource ? " source" : "code")
  1367                                + " " + cdef.sym + "]");
  1370             if (taskListener != null) {
  1371                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1372                 taskListener.started(e);
  1375             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1376                                       env.enclClass.sym.sourcefile :
  1377                                       env.toplevel.sourcefile);
  1378             try {
  1379                 JavaFileObject file;
  1380                 if (usePrintSource)
  1381                     file = printSource(env, cdef);
  1382                 else
  1383                     file = genCode(env, cdef);
  1384                 if (results != null && file != null)
  1385                     results.add(file);
  1386             } catch (IOException ex) {
  1387                 log.error(cdef.pos(), "class.cant.write",
  1388                           cdef.sym, ex.getMessage());
  1389                 return;
  1390             } finally {
  1391                 log.useSource(prev);
  1394             if (taskListener != null) {
  1395                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1396                 taskListener.finished(e);
  1401         // where
  1402         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1403             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1404             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1405             for (Env<AttrContext> env: envs) {
  1406                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1407                 if (sublist == null) {
  1408                     sublist = new ListBuffer<Env<AttrContext>>();
  1409                     map.put(env.toplevel, sublist);
  1411                 sublist.add(env);
  1413             return map;
  1416         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1417             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1418             class MethodBodyRemover extends TreeTranslator {
  1419                 @Override
  1420                 public void visitMethodDef(JCMethodDecl tree) {
  1421                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1422                     for (JCVariableDecl vd : tree.params)
  1423                         vd.mods.flags &= ~Flags.FINAL;
  1424                     tree.body = null;
  1425                     super.visitMethodDef(tree);
  1427                 @Override
  1428                 public void visitVarDef(JCVariableDecl tree) {
  1429                     if (tree.init != null && tree.init.type.constValue() == null)
  1430                         tree.init = null;
  1431                     super.visitVarDef(tree);
  1433                 @Override
  1434                 public void visitClassDef(JCClassDecl tree) {
  1435                     ListBuffer<JCTree> newdefs = lb();
  1436                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1437                         JCTree t = it.head;
  1438                         switch (t.getTag()) {
  1439                         case JCTree.CLASSDEF:
  1440                             if (isInterface ||
  1441                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1442                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1443                                 newdefs.append(t);
  1444                             break;
  1445                         case JCTree.METHODDEF:
  1446                             if (isInterface ||
  1447                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1448                                 ((JCMethodDecl) t).sym.name == names.init ||
  1449                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1450                                 newdefs.append(t);
  1451                             break;
  1452                         case JCTree.VARDEF:
  1453                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1454                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1455                                 newdefs.append(t);
  1456                             break;
  1457                         default:
  1458                             break;
  1461                     tree.defs = newdefs.toList();
  1462                     super.visitClassDef(tree);
  1465             MethodBodyRemover r = new MethodBodyRemover();
  1466             return r.translate(cdef);
  1469     public void reportDeferredDiagnostics() {
  1470         if (annotationProcessingOccurred
  1471                 && implicitSourceFilesRead
  1472                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1473             if (explicitAnnotationProcessingRequested())
  1474                 log.warning("proc.use.implicit");
  1475             else
  1476                 log.warning("proc.use.proc.or.implicit");
  1478         chk.reportDeferredDiagnostics();
  1481     /** Close the compiler, flushing the logs
  1482      */
  1483     public void close() {
  1484         close(true);
  1487     public void close(boolean disposeNames) {
  1488         rootClasses = null;
  1489         reader = null;
  1490         make = null;
  1491         writer = null;
  1492         enter = null;
  1493         if (todo != null)
  1494             todo.clear();
  1495         todo = null;
  1496         parserFactory = null;
  1497         syms = null;
  1498         source = null;
  1499         attr = null;
  1500         chk = null;
  1501         gen = null;
  1502         flow = null;
  1503         transTypes = null;
  1504         lower = null;
  1505         annotate = null;
  1506         types = null;
  1508         log.flush();
  1509         try {
  1510             fileManager.flush();
  1511         } catch (IOException e) {
  1512             throw new Abort(e);
  1513         } finally {
  1514             if (names != null && disposeNames)
  1515                 names.dispose();
  1516             names = null;
  1520     protected void printNote(String lines) {
  1521         Log.printLines(log.noticeWriter, lines);
  1524     /** Output for "-verbose" option.
  1525      *  @param key The key to look up the correct internationalized string.
  1526      *  @param arg An argument for substitution into the output string.
  1527      */
  1528     protected void printVerbose(String key, Object arg) {
  1529         log.printNoteLines("verbose." + key, arg);
  1532     /** Print numbers of errors and warnings.
  1533      */
  1534     protected void printCount(String kind, int count) {
  1535         if (count != 0) {
  1536             String key;
  1537             if (count == 1)
  1538                 key = "count." + kind;
  1539             else
  1540                 key = "count." + kind + ".plural";
  1541             log.printErrLines(key, String.valueOf(count));
  1542             log.errWriter.flush();
  1546     private static long now() {
  1547         return System.currentTimeMillis();
  1550     private static long elapsed(long then) {
  1551         return now() - then;
  1554     public void initRound(JavaCompiler prev) {
  1555         keepComments = prev.keepComments;
  1556         start_msec = prev.start_msec;
  1557         hasBeenUsed = true;
  1560     public static void enableLogging() {
  1561         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1562         logger.setLevel(Level.ALL);
  1563         for (Handler h : logger.getParent().getHandlers()) {
  1564             h.setLevel(Level.ALL);

mercurial