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

Tue, 07 Sep 2010 17:33:43 +0100

author
mcimadamore
date
Tue, 07 Sep 2010 17:33:43 +0100
changeset 676
bfdfc13fe641
parent 664
4124840b35fe
child 678
014cf6234586
permissions
-rw-r--r--

6970584: Flow.java should be more error-friendly
Summary: Added a post-attribution visitor that fixup uninitialized types/symbol in AST after erroneous attribution
Reviewed-by: jjg

     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.JCDiagnostic.DiagnosticFlag.*;
    63 import static com.sun.tools.javac.util.ListBuffer.lb;
    65 // TEMP, until we have a more efficient way to save doc comment info
    66 import com.sun.tools.javac.parser.DocCommentScanner;
    68 import java.util.HashMap;
    69 import java.util.Queue;
    70 import javax.lang.model.SourceVersion;
    72 /** This class could be the main entry point for GJC when GJC is used as a
    73  *  component in a larger software system. It provides operations to
    74  *  construct a new compiler, and to run a new compiler on a set of source
    75  *  files.
    76  *
    77  *  <p><b>This is NOT part of any supported API.
    78  *  If you write code that depends on this, you do so at your own risk.
    79  *  This code and its internal interfaces are subject to change or
    80  *  deletion without notice.</b>
    81  */
    82 public class JavaCompiler implements ClassReader.SourceCompleter {
    83     /** The context key for the compiler. */
    84     protected static final Context.Key<JavaCompiler> compilerKey =
    85         new Context.Key<JavaCompiler>();
    87     /** Get the JavaCompiler instance for this context. */
    88     public static JavaCompiler instance(Context context) {
    89         JavaCompiler instance = context.get(compilerKey);
    90         if (instance == null)
    91             instance = new JavaCompiler(context);
    92         return instance;
    93     }
    95     /** The current version number as a string.
    96      */
    97     public static String version() {
    98         return version("release");  // mm.nn.oo[-milestone]
    99     }
   101     /** The current full version number as a string.
   102      */
   103     public static String fullVersion() {
   104         return version("full"); // mm.mm.oo[-milestone]-build
   105     }
   107     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   108     private static ResourceBundle versionRB;
   110     private static String version(String key) {
   111         if (versionRB == null) {
   112             try {
   113                 versionRB = ResourceBundle.getBundle(versionRBName);
   114             } catch (MissingResourceException e) {
   115                 return Log.getLocalizedString("version.not.available");
   116             }
   117         }
   118         try {
   119             return versionRB.getString(key);
   120         }
   121         catch (MissingResourceException e) {
   122             return Log.getLocalizedString("version.not.available");
   123         }
   124     }
   126     /**
   127      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   128      * are connected. Each individual file is processed by each phase in turn,
   129      * but with different compile policies, you can control the order in which
   130      * each class is processed through its next phase.
   131      *
   132      * <p>Generally speaking, the compiler will "fail fast" in the face of
   133      * errors, although not aggressively so. flow, desugar, etc become no-ops
   134      * once any errors have occurred. No attempt is currently made to determine
   135      * if it might be safe to process a class through its next phase because
   136      * it does not depend on any unrelated errors that might have occurred.
   137      */
   138     protected static enum CompilePolicy {
   139         /**
   140          * Just attribute the parse trees.
   141          */
   142         ATTR_ONLY,
   144         /**
   145          * Just attribute and do flow analysis on the parse trees.
   146          * This should catch most user errors.
   147          */
   148         CHECK_ONLY,
   150         /**
   151          * Attribute everything, then do flow analysis for everything,
   152          * then desugar everything, and only then generate output.
   153          * This means no output will be generated if there are any
   154          * errors in any classes.
   155          */
   156         SIMPLE,
   158         /**
   159          * Groups the classes for each source file together, then process
   160          * each group in a manner equivalent to the {@code SIMPLE} policy.
   161          * This means no output will be generated if there are any
   162          * errors in any of the classes in a source file.
   163          */
   164         BY_FILE,
   166         /**
   167          * Completely process each entry on the todo list in turn.
   168          * -- this is the same for 1.5.
   169          * Means output might be generated for some classes in a compilation unit
   170          * and not others.
   171          */
   172         BY_TODO;
   174         static CompilePolicy decode(String option) {
   175             if (option == null)
   176                 return DEFAULT_COMPILE_POLICY;
   177             else if (option.equals("attr"))
   178                 return ATTR_ONLY;
   179             else if (option.equals("check"))
   180                 return CHECK_ONLY;
   181             else if (option.equals("simple"))
   182                 return SIMPLE;
   183             else if (option.equals("byfile"))
   184                 return BY_FILE;
   185             else if (option.equals("bytodo"))
   186                 return BY_TODO;
   187             else
   188                 return DEFAULT_COMPILE_POLICY;
   189         }
   190     }
   192     private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   194     protected static enum ImplicitSourcePolicy {
   195         /** Don't generate or process implicitly read source files. */
   196         NONE,
   197         /** Generate classes for implicitly read source files. */
   198         CLASS,
   199         /** Like CLASS, but generate warnings if annotation processing occurs */
   200         UNSET;
   202         static ImplicitSourcePolicy decode(String option) {
   203             if (option == null)
   204                 return UNSET;
   205             else if (option.equals("none"))
   206                 return NONE;
   207             else if (option.equals("class"))
   208                 return CLASS;
   209             else
   210                 return UNSET;
   211         }
   212     }
   214     /** The log to be used for error reporting.
   215      */
   216     public Log log;
   218     /** Factory for creating diagnostic objects
   219      */
   220     JCDiagnostic.Factory diagFactory;
   222     /** The tree factory module.
   223      */
   224     protected TreeMaker make;
   226     /** The class reader.
   227      */
   228     protected ClassReader reader;
   230     /** The class writer.
   231      */
   232     protected ClassWriter writer;
   234     /** The module for the symbol table entry phases.
   235      */
   236     protected Enter enter;
   238     /** The symbol table.
   239      */
   240     protected Symtab syms;
   242     /** The language version.
   243      */
   244     protected Source source;
   246     /** The module for code generation.
   247      */
   248     protected Gen gen;
   250     /** The name table.
   251      */
   252     protected Names names;
   254     /** The attributor.
   255      */
   256     protected Attr attr;
   258     /** The attributor.
   259      */
   260     protected Check chk;
   262     /** The flow analyzer.
   263      */
   264     protected Flow flow;
   266     /** The type eraser.
   267      */
   268     protected TransTypes transTypes;
   270     /** The syntactic sugar desweetener.
   271      */
   272     protected Lower lower;
   274     /** The annotation annotator.
   275      */
   276     protected Annotate annotate;
   278     /** Force a completion failure on this name
   279      */
   280     protected final Name completionFailureName;
   282     /** Type utilities.
   283      */
   284     protected Types types;
   286     /** Access to file objects.
   287      */
   288     protected JavaFileManager fileManager;
   290     /** Factory for parsers.
   291      */
   292     protected ParserFactory parserFactory;
   294     /** Optional listener for progress events
   295      */
   296     protected TaskListener taskListener;
   298     /**
   299      * Annotation processing may require and provide a new instance
   300      * of the compiler to be used for the analyze and generate phases.
   301      */
   302     protected JavaCompiler delegateCompiler;
   304     /**
   305      * Flag set if any annotation processing occurred.
   306      **/
   307     protected boolean annotationProcessingOccurred;
   309     /**
   310      * Flag set if any implicit source files read.
   311      **/
   312     protected boolean implicitSourceFilesRead;
   314     protected Context context;
   316     /** Construct a new compiler using a shared context.
   317      */
   318     public JavaCompiler(final Context context) {
   319         this.context = context;
   320         context.put(compilerKey, this);
   322         // if fileManager not already set, register the JavacFileManager to be used
   323         if (context.get(JavaFileManager.class) == null)
   324             JavacFileManager.preRegister(context);
   326         names = Names.instance(context);
   327         log = Log.instance(context);
   328         diagFactory = JCDiagnostic.Factory.instance(context);
   329         reader = ClassReader.instance(context);
   330         make = TreeMaker.instance(context);
   331         writer = ClassWriter.instance(context);
   332         enter = Enter.instance(context);
   333         todo = Todo.instance(context);
   335         fileManager = context.get(JavaFileManager.class);
   336         parserFactory = ParserFactory.instance(context);
   338         try {
   339             // catch completion problems with predefineds
   340             syms = Symtab.instance(context);
   341         } catch (CompletionFailure ex) {
   342             // inlined Check.completionError as it is not initialized yet
   343             log.error("cant.access", ex.sym, ex.getDetailValue());
   344             if (ex instanceof ClassReader.BadClassFile)
   345                 throw new Abort();
   346         }
   347         source = Source.instance(context);
   348         attr = Attr.instance(context);
   349         chk = Check.instance(context);
   350         gen = Gen.instance(context);
   351         flow = Flow.instance(context);
   352         transTypes = TransTypes.instance(context);
   353         lower = Lower.instance(context);
   354         annotate = Annotate.instance(context);
   355         types = Types.instance(context);
   356         taskListener = context.get(TaskListener.class);
   358         reader.sourceCompleter = this;
   360         Options options = Options.instance(context);
   362         verbose       = options.get("-verbose")       != null;
   363         sourceOutput  = options.get("-printsource")   != null; // used to be -s
   364         stubOutput    = options.get("-stubs")         != null;
   365         relax         = options.get("-relax")         != null;
   366         printFlat     = options.get("-printflat")     != null;
   367         attrParseOnly = options.get("-attrparseonly") != null;
   368         encoding      = options.get("-encoding");
   369         lineDebugInfo = options.get("-g:")            == null ||
   370                         options.get("-g:lines")       != null;
   371         genEndPos     = options.get("-Xjcov")         != null ||
   372                         context.get(DiagnosticListener.class) != null;
   373         devVerbose    = options.get("dev") != null;
   374         processPcks   = options.get("process.packages") != null;
   375         werror        = options.get("-Werror")        != null;
   377         verboseCompilePolicy = options.get("verboseCompilePolicy") != null;
   379         if (attrParseOnly)
   380             compilePolicy = CompilePolicy.ATTR_ONLY;
   381         else
   382             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   384         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   386         completionFailureName =
   387             (options.get("failcomplete") != null)
   388             ? names.fromString(options.get("failcomplete"))
   389             : null;
   391         shouldStopPolicy =
   392             (options.get("shouldStopPolicy") != null)
   393             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   394             : null;
   395         if (options.get("oldDiags") == null)
   396             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   397     }
   399     /* Switches:
   400      */
   402     /** Verbose output.
   403      */
   404     public boolean verbose;
   406     /** Emit plain Java source files rather than class files.
   407      */
   408     public boolean sourceOutput;
   410     /** Emit stub source files rather than class files.
   411      */
   412     public boolean stubOutput;
   414     /** Generate attributed parse tree only.
   415      */
   416     public boolean attrParseOnly;
   418     /** Switch: relax some constraints for producing the jsr14 prototype.
   419      */
   420     boolean relax;
   422     /** Debug switch: Emit Java sources after inner class flattening.
   423      */
   424     public boolean printFlat;
   426     /** The encoding to be used for source input.
   427      */
   428     public String encoding;
   430     /** Generate code with the LineNumberTable attribute for debugging
   431      */
   432     public boolean lineDebugInfo;
   434     /** Switch: should we store the ending positions?
   435      */
   436     public boolean genEndPos;
   438     /** Switch: should we debug ignored exceptions
   439      */
   440     protected boolean devVerbose;
   442     /** Switch: should we (annotation) process packages as well
   443      */
   444     protected boolean processPcks;
   446     /** Switch: treat warnings as errors
   447      */
   448     protected boolean werror;
   450     /** Switch: is annotation processing requested explitly via
   451      * CompilationTask.setProcessors?
   452      */
   453     protected boolean explicitAnnotationProcessingRequested = false;
   455     /**
   456      * The policy for the order in which to perform the compilation
   457      */
   458     protected CompilePolicy compilePolicy;
   460     /**
   461      * The policy for what to do with implicitly read source files
   462      */
   463     protected ImplicitSourcePolicy implicitSourcePolicy;
   465     /**
   466      * Report activity related to compilePolicy
   467      */
   468     public boolean verboseCompilePolicy;
   470     /**
   471      * Policy of how far to continue processing. null means until first
   472      * error.
   473      */
   474     public CompileState shouldStopPolicy;
   476     /** A queue of all as yet unattributed classes.
   477      */
   478     public Todo todo;
   480     /** Ordered list of compiler phases for each compilation unit. */
   481     public enum CompileState {
   482         PARSE(1),
   483         ENTER(2),
   484         PROCESS(3),
   485         ATTR(4),
   486         FLOW(5),
   487         TRANSTYPES(6),
   488         LOWER(7),
   489         GENERATE(8);
   490         CompileState(int value) {
   491             this.value = value;
   492         }
   493         boolean isDone(CompileState other) {
   494             return value >= other.value;
   495         }
   496         private int value;
   497     };
   498     /** Partial map to record which compiler phases have been executed
   499      * for each compilation unit. Used for ATTR and FLOW phases.
   500      */
   501     protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
   502         private static final long serialVersionUID = 1812267524140424433L;
   503         boolean isDone(Env<AttrContext> env, CompileState cs) {
   504             CompileState ecs = get(env);
   505             return ecs != null && ecs.isDone(cs);
   506         }
   507     }
   508     private CompileStates compileStates = new CompileStates();
   510     /** The set of currently compiled inputfiles, needed to ensure
   511      *  we don't accidentally overwrite an input file when -s is set.
   512      *  initialized by `compile'.
   513      */
   514     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   516     protected boolean shouldStop(CompileState cs) {
   517         if (shouldStopPolicy == null)
   518             return (errorCount() > 0);
   519         else
   520             return cs.ordinal() > shouldStopPolicy.ordinal();
   521     }
   523     /** The number of errors reported so far.
   524      */
   525     public int errorCount() {
   526         if (delegateCompiler != null && delegateCompiler != this)
   527             return delegateCompiler.errorCount();
   528         else {
   529             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   530                 log.error("warnings.and.werror");
   531             }
   532         }
   533         return log.nerrors;
   534     }
   536     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   537         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   538     }
   540     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   541         return shouldStop(cs) ? List.<T>nil() : list;
   542     }
   544     /** The number of warnings reported so far.
   545      */
   546     public int warningCount() {
   547         if (delegateCompiler != null && delegateCompiler != this)
   548             return delegateCompiler.warningCount();
   549         else
   550             return log.nwarnings;
   551     }
   553     /** Try to open input stream with given name.
   554      *  Report an error if this fails.
   555      *  @param filename   The file name of the input stream to be opened.
   556      */
   557     public CharSequence readSource(JavaFileObject filename) {
   558         try {
   559             inputFiles.add(filename);
   560             return filename.getCharContent(false);
   561         } catch (IOException e) {
   562             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   563             return null;
   564         }
   565     }
   567     /** Parse contents of input stream.
   568      *  @param filename     The name of the file from which input stream comes.
   569      *  @param input        The input stream to be parsed.
   570      */
   571     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   572         long msec = now();
   573         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   574                                       null, List.<JCTree>nil());
   575         if (content != null) {
   576             if (verbose) {
   577                 printVerbose("parsing.started", filename);
   578             }
   579             if (taskListener != null) {
   580                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   581                 taskListener.started(e);
   582             }
   583             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   584             tree = parser.parseCompilationUnit();
   585             if (verbose) {
   586                 printVerbose("parsing.done", Long.toString(elapsed(msec)));
   587             }
   588         }
   590         tree.sourcefile = filename;
   592         if (content != null && taskListener != null) {
   593             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   594             taskListener.finished(e);
   595         }
   597         return tree;
   598     }
   599     // where
   600         public boolean keepComments = false;
   601         protected boolean keepComments() {
   602             return keepComments || sourceOutput || stubOutput;
   603         }
   606     /** Parse contents of file.
   607      *  @param filename     The name of the file to be parsed.
   608      */
   609     @Deprecated
   610     public JCTree.JCCompilationUnit parse(String filename) {
   611         JavacFileManager fm = (JavacFileManager)fileManager;
   612         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   613     }
   615     /** Parse contents of file.
   616      *  @param filename     The name of the file to be parsed.
   617      */
   618     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   619         JavaFileObject prev = log.useSource(filename);
   620         try {
   621             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   622             if (t.endPositions != null)
   623                 log.setEndPosTable(filename, t.endPositions);
   624             return t;
   625         } finally {
   626             log.useSource(prev);
   627         }
   628     }
   630     /** Resolve an identifier.
   631      * @param name      The identifier to resolve
   632      */
   633     public Symbol resolveIdent(String name) {
   634         if (name.equals(""))
   635             return syms.errSymbol;
   636         JavaFileObject prev = log.useSource(null);
   637         try {
   638             JCExpression tree = null;
   639             for (String s : name.split("\\.", -1)) {
   640                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   641                     return syms.errSymbol;
   642                 tree = (tree == null) ? make.Ident(names.fromString(s))
   643                                       : make.Select(tree, names.fromString(s));
   644             }
   645             JCCompilationUnit toplevel =
   646                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   647             toplevel.packge = syms.unnamedPackage;
   648             return attr.attribIdent(tree, toplevel);
   649         } finally {
   650             log.useSource(prev);
   651         }
   652     }
   654     /** Emit plain Java source for a class.
   655      *  @param env    The attribution environment of the outermost class
   656      *                containing this class.
   657      *  @param cdef   The class definition to be printed.
   658      */
   659     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   660         JavaFileObject outFile
   661             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   662                                                cdef.sym.flatname.toString(),
   663                                                JavaFileObject.Kind.SOURCE,
   664                                                null);
   665         if (inputFiles.contains(outFile)) {
   666             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   667             return null;
   668         } else {
   669             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   670             try {
   671                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   672                 if (verbose)
   673                     printVerbose("wrote.file", outFile);
   674             } finally {
   675                 out.close();
   676             }
   677             return outFile;
   678         }
   679     }
   681     /** Generate code and emit a class file for a given class
   682      *  @param env    The attribution environment of the outermost class
   683      *                containing this class.
   684      *  @param cdef   The class definition from which code is generated.
   685      */
   686     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   687         try {
   688             if (gen.genClass(env, cdef) && (errorCount() == 0))
   689                 return writer.writeClass(cdef.sym);
   690         } catch (ClassWriter.PoolOverflow ex) {
   691             log.error(cdef.pos(), "limit.pool");
   692         } catch (ClassWriter.StringOverflow ex) {
   693             log.error(cdef.pos(), "limit.string.overflow",
   694                       ex.value.substring(0, 20));
   695         } catch (CompletionFailure ex) {
   696             chk.completionError(cdef.pos(), ex);
   697         }
   698         return null;
   699     }
   701     /** Complete compiling a source file that has been accessed
   702      *  by the class file reader.
   703      *  @param c          The class the source file of which needs to be compiled.
   704      *  @param filename   The name of the source file.
   705      *  @param f          An input stream that reads the source file.
   706      */
   707     public void complete(ClassSymbol c) throws CompletionFailure {
   708 //      System.err.println("completing " + c);//DEBUG
   709         if (completionFailureName == c.fullname) {
   710             throw new CompletionFailure(c, "user-selected completion failure by class name");
   711         }
   712         JCCompilationUnit tree;
   713         JavaFileObject filename = c.classfile;
   714         JavaFileObject prev = log.useSource(filename);
   716         try {
   717             tree = parse(filename, filename.getCharContent(false));
   718         } catch (IOException e) {
   719             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   720             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   721         } finally {
   722             log.useSource(prev);
   723         }
   725         if (taskListener != null) {
   726             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   727             taskListener.started(e);
   728         }
   730         enter.complete(List.of(tree), c);
   732         if (taskListener != null) {
   733             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   734             taskListener.finished(e);
   735         }
   737         if (enter.getEnv(c) == null) {
   738             boolean isPkgInfo =
   739                 tree.sourcefile.isNameCompatible("package-info",
   740                                                  JavaFileObject.Kind.SOURCE);
   741             if (isPkgInfo) {
   742                 if (enter.getEnv(tree.packge) == null) {
   743                     JCDiagnostic diag =
   744                         diagFactory.fragment("file.does.not.contain.package",
   745                                                  c.location());
   746                     throw reader.new BadClassFile(c, filename, diag);
   747                 }
   748             } else {
   749                 JCDiagnostic diag =
   750                         diagFactory.fragment("file.doesnt.contain.class",
   751                                             c.getQualifiedName());
   752                 throw reader.new BadClassFile(c, filename, diag);
   753             }
   754         }
   756         implicitSourceFilesRead = true;
   757     }
   759     /** Track when the JavaCompiler has been used to compile something. */
   760     private boolean hasBeenUsed = false;
   761     private long start_msec = 0;
   762     public long elapsed_msec = 0;
   764     public void compile(List<JavaFileObject> sourceFileObject)
   765         throws Throwable {
   766         compile(sourceFileObject, List.<String>nil(), null);
   767     }
   769     /**
   770      * Main method: compile a list of files, return all compiled classes
   771      *
   772      * @param sourceFileObjects file objects to be compiled
   773      * @param classnames class names to process for annotations
   774      * @param processors user provided annotation processors to bypass
   775      * discovery, {@code null} means that no processors were provided
   776      */
   777     public void compile(List<JavaFileObject> sourceFileObjects,
   778                         List<String> classnames,
   779                         Iterable<? extends Processor> processors)
   780     {
   781         if (processors != null && processors.iterator().hasNext())
   782             explicitAnnotationProcessingRequested = true;
   783         // as a JavaCompiler can only be used once, throw an exception if
   784         // it has been used before.
   785         if (hasBeenUsed)
   786             throw new AssertionError("attempt to reuse JavaCompiler");
   787         hasBeenUsed = true;
   789         start_msec = now();
   790         try {
   791             initProcessAnnotations(processors);
   793             // These method calls must be chained to avoid memory leaks
   794             delegateCompiler =
   795                 processAnnotations(
   796                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   797                     classnames);
   799             delegateCompiler.compile2();
   800             delegateCompiler.close();
   801             elapsed_msec = delegateCompiler.elapsed_msec;
   802         } catch (Abort ex) {
   803             if (devVerbose)
   804                 ex.printStackTrace();
   805         } finally {
   806             if (procEnvImpl != null)
   807                 procEnvImpl.close();
   808         }
   809     }
   811     /**
   812      * The phases following annotation processing: attribution,
   813      * desugar, and finally code generation.
   814      */
   815     private void compile2() {
   816         try {
   817             switch (compilePolicy) {
   818             case ATTR_ONLY:
   819                 attribute(todo);
   820                 break;
   822             case CHECK_ONLY:
   823                 flow(attribute(todo));
   824                 break;
   826             case SIMPLE:
   827                 generate(desugar(flow(attribute(todo))));
   828                 break;
   830             case BY_FILE: {
   831                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   832                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   833                         generate(desugar(flow(attribute(q.remove()))));
   834                     }
   835                 }
   836                 break;
   838             case BY_TODO:
   839                 while (!todo.isEmpty())
   840                     generate(desugar(flow(attribute(todo.remove()))));
   841                 break;
   843             default:
   844                 assert false: "unknown compile policy";
   845             }
   846         } catch (Abort ex) {
   847             if (devVerbose)
   848                 ex.printStackTrace();
   849         }
   851         if (verbose) {
   852             elapsed_msec = elapsed(start_msec);
   853             printVerbose("total", Long.toString(elapsed_msec));
   854         }
   856         reportDeferredDiagnostics();
   858         if (!log.hasDiagnosticListener()) {
   859             printCount("error", errorCount());
   860             printCount("warn", warningCount());
   861         }
   862     }
   864     private List<JCClassDecl> rootClasses;
   866     /**
   867      * Parses a list of files.
   868      */
   869    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   870        if (shouldStop(CompileState.PARSE))
   871            return List.nil();
   873         //parse all files
   874         ListBuffer<JCCompilationUnit> trees = lb();
   875         for (JavaFileObject fileObject : fileObjects)
   876             trees.append(parse(fileObject));
   877         return trees.toList();
   878     }
   880     /**
   881      * Enter the symbols found in a list of parse trees.
   882      * As a side-effect, this puts elements on the "todo" list.
   883      * Also stores a list of all top level classes in rootClasses.
   884      */
   885     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   886         //enter symbols for all files
   887         if (taskListener != null) {
   888             for (JCCompilationUnit unit: roots) {
   889                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   890                 taskListener.started(e);
   891             }
   892         }
   894         enter.main(roots);
   896         if (taskListener != null) {
   897             for (JCCompilationUnit unit: roots) {
   898                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   899                 taskListener.finished(e);
   900             }
   901         }
   903         //If generating source, remember the classes declared in
   904         //the original compilation units listed on the command line.
   905         if (sourceOutput || stubOutput) {
   906             ListBuffer<JCClassDecl> cdefs = lb();
   907             for (JCCompilationUnit unit : roots) {
   908                 for (List<JCTree> defs = unit.defs;
   909                      defs.nonEmpty();
   910                      defs = defs.tail) {
   911                     if (defs.head instanceof JCClassDecl)
   912                         cdefs.append((JCClassDecl)defs.head);
   913                 }
   914             }
   915             rootClasses = cdefs.toList();
   916         }
   918         // Ensure the input files have been recorded. Although this is normally
   919         // done by readSource, it may not have been done if the trees were read
   920         // in a prior round of annotation processing, and the trees have been
   921         // cleaned and are being reused.
   922         for (JCCompilationUnit unit : roots) {
   923             inputFiles.add(unit.sourcefile);
   924         }
   926         return roots;
   927     }
   929     /**
   930      * Set to true to enable skeleton annotation processing code.
   931      * Currently, we assume this variable will be replaced more
   932      * advanced logic to figure out if annotation processing is
   933      * needed.
   934      */
   935     boolean processAnnotations = false;
   937     /**
   938      * Object to handle annotation processing.
   939      */
   940     private JavacProcessingEnvironment procEnvImpl = null;
   942     /**
   943      * Check if we should process annotations.
   944      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
   945      * to catch doc comments, and set keepComments so the parser records them in
   946      * the compilation unit.
   947      *
   948      * @param processors user provided annotation processors to bypass
   949      * discovery, {@code null} means that no processors were provided
   950      */
   951     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
   952         // Process annotations if processing is not disabled and there
   953         // is at least one Processor available.
   954         Options options = Options.instance(context);
   955         if (options.get("-proc:none") != null) {
   956             processAnnotations = false;
   957         } else if (procEnvImpl == null) {
   958             procEnvImpl = new JavacProcessingEnvironment(context, processors);
   959             processAnnotations = procEnvImpl.atLeastOneProcessor();
   961             if (processAnnotations) {
   962                 if (context.get(Scanner.Factory.scannerFactoryKey) == null)
   963                     DocCommentScanner.Factory.preRegister(context);
   964                 options.put("save-parameter-names", "save-parameter-names");
   965                 reader.saveParameterNames = true;
   966                 keepComments = true;
   967                 if (taskListener != null)
   968                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
   969                 log.deferDiagnostics = true;
   970             } else { // free resources
   971                 procEnvImpl.close();
   972             }
   973         }
   974     }
   976     // TODO: called by JavacTaskImpl
   977     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
   978         return processAnnotations(roots, List.<String>nil());
   979     }
   981     /**
   982      * Process any anotations found in the specifed compilation units.
   983      * @param roots a list of compilation units
   984      * @return an instance of the compiler in which to complete the compilation
   985      */
   986     // Implementation note: when this method is called, log.deferredDiagnostics
   987     // will have been set true by initProcessAnnotations, meaning that any diagnostics
   988     // that are reported will go into the log.deferredDiagnostics queue.
   989     // By the time this method exits, log.deferDiagnostics must be set back to false,
   990     // and all deferredDiagnostics must have been handled: i.e. either reported
   991     // or determined to be transient, and therefore suppressed.
   992     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
   993                                            List<String> classnames) {
   994         if (shouldStop(CompileState.PROCESS)) {
   995             // Errors were encountered.
   996             // Unless all the errors are resolve errors, the errors were parse errors
   997             // or other errors during enter which cannot be fixed by running
   998             // any annotation processors.
   999             if (unrecoverableError()) {
  1000                 log.reportDeferredDiagnostics();
  1001                 return this;
  1005         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1006         // by initProcessAnnotations
  1008         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1010         if (!processAnnotations) {
  1011             // If there are no annotation processors present, and
  1012             // annotation processing is to occur with compilation,
  1013             // emit a warning.
  1014             Options options = Options.instance(context);
  1015             if (options.get("-proc:only") != null) {
  1016                 log.warning("proc.proc-only.requested.no.procs");
  1017                 todo.clear();
  1019             // If not processing annotations, classnames must be empty
  1020             if (!classnames.isEmpty()) {
  1021                 log.error("proc.no.explicit.annotation.processing.requested",
  1022                           classnames);
  1024             log.reportDeferredDiagnostics();
  1025             return this; // continue regular compilation
  1028         try {
  1029             List<ClassSymbol> classSymbols = List.nil();
  1030             List<PackageSymbol> pckSymbols = List.nil();
  1031             if (!classnames.isEmpty()) {
  1032                  // Check for explicit request for annotation
  1033                  // processing
  1034                 if (!explicitAnnotationProcessingRequested()) {
  1035                     log.error("proc.no.explicit.annotation.processing.requested",
  1036                               classnames);
  1037                     log.reportDeferredDiagnostics();
  1038                     return this; // TODO: Will this halt compilation?
  1039                 } else {
  1040                     boolean errors = false;
  1041                     for (String nameStr : classnames) {
  1042                         Symbol sym = resolveIdent(nameStr);
  1043                         if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
  1044                             log.error("proc.cant.find.class", nameStr);
  1045                             errors = true;
  1046                             continue;
  1048                         try {
  1049                             if (sym.kind == Kinds.PCK)
  1050                                 sym.complete();
  1051                             if (sym.exists()) {
  1052                                 if (sym.kind == Kinds.PCK)
  1053                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1054                                 else
  1055                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1056                                 continue;
  1058                             assert sym.kind == Kinds.PCK;
  1059                             log.warning("proc.package.does.not.exist", nameStr);
  1060                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1061                         } catch (CompletionFailure e) {
  1062                             log.error("proc.cant.find.class", nameStr);
  1063                             errors = true;
  1064                             continue;
  1067                     if (errors) {
  1068                         log.reportDeferredDiagnostics();
  1069                         return this;
  1073             try {
  1074                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
  1075                 if (c != this)
  1076                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1077                 // doProcessing will have handled deferred diagnostics
  1078                 assert c.log.deferDiagnostics == false;
  1079                 assert c.log.deferredDiagnostics.size() == 0;
  1080                 return c;
  1081             } finally {
  1082                 procEnvImpl.close();
  1084         } catch (CompletionFailure ex) {
  1085             log.error("cant.access", ex.sym, ex.getDetailValue());
  1086             log.reportDeferredDiagnostics();
  1087             return this;
  1091     private boolean unrecoverableError() {
  1092         for (JCDiagnostic d: log.deferredDiagnostics) {
  1093             if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RESOLVE_ERROR))
  1094                 return true;
  1096         return false;
  1099     boolean explicitAnnotationProcessingRequested() {
  1100         Options options = Options.instance(context);
  1101         return
  1102             explicitAnnotationProcessingRequested ||
  1103             options.get("-processor") != null ||
  1104             options.get("-processorpath") != null ||
  1105             options.get("-proc:only") != null ||
  1106             options.get("-Xprint") != null;
  1109     /**
  1110      * Attribute a list of parse trees, such as found on the "todo" list.
  1111      * Note that attributing classes may cause additional files to be
  1112      * parsed and entered via the SourceCompleter.
  1113      * Attribution of the entries in the list does not stop if any errors occur.
  1114      * @returns a list of environments for attributd classes.
  1115      */
  1116     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1117         ListBuffer<Env<AttrContext>> results = lb();
  1118         while (!envs.isEmpty())
  1119             results.append(attribute(envs.remove()));
  1120         return stopIfError(CompileState.ATTR, results);
  1123     /**
  1124      * Attribute a parse tree.
  1125      * @returns the attributed parse tree
  1126      */
  1127     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1128         if (compileStates.isDone(env, CompileState.ATTR))
  1129             return env;
  1131         if (verboseCompilePolicy)
  1132             printNote("[attribute " + env.enclClass.sym + "]");
  1133         if (verbose)
  1134             printVerbose("checking.attribution", env.enclClass.sym);
  1136         if (taskListener != null) {
  1137             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1138             taskListener.started(e);
  1141         JavaFileObject prev = log.useSource(
  1142                                   env.enclClass.sym.sourcefile != null ?
  1143                                   env.enclClass.sym.sourcefile :
  1144                                   env.toplevel.sourcefile);
  1145         try {
  1146             attr.attribClass(env.tree.pos(), env.enclClass.sym);
  1147             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1148                 //if in fail-over mode, ensure that AST expression nodes
  1149                 //are correctly initialized (e.g. they have a type/symbol)
  1150                 attr.postAttr(env);
  1152             compileStates.put(env, CompileState.ATTR);
  1154         finally {
  1155             log.useSource(prev);
  1158         return env;
  1161     /**
  1162      * Perform dataflow checks on attributed parse trees.
  1163      * These include checks for definite assignment and unreachable statements.
  1164      * If any errors occur, an empty list will be returned.
  1165      * @returns the list of attributed parse trees
  1166      */
  1167     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1168         ListBuffer<Env<AttrContext>> results = lb();
  1169         for (Env<AttrContext> env: envs) {
  1170             flow(env, results);
  1172         return stopIfError(CompileState.FLOW, results);
  1175     /**
  1176      * Perform dataflow checks on an attributed parse tree.
  1177      */
  1178     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1179         ListBuffer<Env<AttrContext>> results = lb();
  1180         flow(env, results);
  1181         return stopIfError(CompileState.FLOW, results);
  1184     /**
  1185      * Perform dataflow checks on an attributed parse tree.
  1186      */
  1187     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1188         try {
  1189             if (shouldStop(CompileState.FLOW))
  1190                 return;
  1192             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1193                 results.add(env);
  1194                 return;
  1197             if (verboseCompilePolicy)
  1198                 printNote("[flow " + env.enclClass.sym + "]");
  1199             JavaFileObject prev = log.useSource(
  1200                                                 env.enclClass.sym.sourcefile != null ?
  1201                                                 env.enclClass.sym.sourcefile :
  1202                                                 env.toplevel.sourcefile);
  1203             try {
  1204                 make.at(Position.FIRSTPOS);
  1205                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1206                 flow.analyzeTree(env, localMake);
  1207                 compileStates.put(env, CompileState.FLOW);
  1209                 if (shouldStop(CompileState.FLOW))
  1210                     return;
  1212                 results.add(env);
  1214             finally {
  1215                 log.useSource(prev);
  1218         finally {
  1219             if (taskListener != null) {
  1220                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1221                 taskListener.finished(e);
  1226     /**
  1227      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1228      * for source or code generation.
  1229      * If any errors occur, an empty list will be returned.
  1230      * @returns a list containing the classes to be generated
  1231      */
  1232     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1233         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1234         for (Env<AttrContext> env: envs)
  1235             desugar(env, results);
  1236         return stopIfError(CompileState.FLOW, results);
  1239     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1240             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1242     /**
  1243      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1244      * for source or code generation. If the file was not listed on the command line,
  1245      * the current implicitSourcePolicy is taken into account.
  1246      * The preparation stops as soon as an error is found.
  1247      */
  1248     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1249         if (shouldStop(CompileState.TRANSTYPES))
  1250             return;
  1252         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1253                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1254             return;
  1257         if (compileStates.isDone(env, CompileState.LOWER)) {
  1258             results.addAll(desugaredEnvs.get(env));
  1259             return;
  1262         /**
  1263          * Ensure that superclasses of C are desugared before C itself. This is
  1264          * required for two reasons: (i) as erasure (TransTypes) destroys
  1265          * information needed in flow analysis and (ii) as some checks carried
  1266          * out during lowering require that all synthetic fields/methods have
  1267          * already been added to C and its superclasses.
  1268          */
  1269         class ScanNested extends TreeScanner {
  1270             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1271             @Override
  1272             public void visitClassDef(JCClassDecl node) {
  1273                 Type st = types.supertype(node.sym.type);
  1274                 if (st.tag == TypeTags.CLASS) {
  1275                     ClassSymbol c = st.tsym.outermostClass();
  1276                     Env<AttrContext> stEnv = enter.getEnv(c);
  1277                     if (stEnv != null && env != stEnv) {
  1278                         if (dependencies.add(stEnv))
  1279                             scan(stEnv.tree);
  1282                 super.visitClassDef(node);
  1285         ScanNested scanner = new ScanNested();
  1286         scanner.scan(env.tree);
  1287         for (Env<AttrContext> dep: scanner.dependencies) {
  1288         if (!compileStates.isDone(dep, CompileState.FLOW))
  1289             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1292         //We need to check for error another time as more classes might
  1293         //have been attributed and analyzed at this stage
  1294         if (shouldStop(CompileState.TRANSTYPES))
  1295             return;
  1297         if (verboseCompilePolicy)
  1298             printNote("[desugar " + env.enclClass.sym + "]");
  1300         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1301                                   env.enclClass.sym.sourcefile :
  1302                                   env.toplevel.sourcefile);
  1303         try {
  1304             //save tree prior to rewriting
  1305             JCTree untranslated = env.tree;
  1307             make.at(Position.FIRSTPOS);
  1308             TreeMaker localMake = make.forToplevel(env.toplevel);
  1310             if (env.tree instanceof JCCompilationUnit) {
  1311                 if (!(stubOutput || sourceOutput || printFlat)) {
  1312                     if (shouldStop(CompileState.LOWER))
  1313                         return;
  1314                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1315                     if (pdef.head != null) {
  1316                         assert pdef.tail.isEmpty();
  1317                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1320                 return;
  1323             if (stubOutput) {
  1324                 //emit stub Java source file, only for compilation
  1325                 //units enumerated explicitly on the command line
  1326                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1327                 if (untranslated instanceof JCClassDecl &&
  1328                     rootClasses.contains((JCClassDecl)untranslated) &&
  1329                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1330                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1331                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1333                 return;
  1336             if (shouldStop(CompileState.TRANSTYPES))
  1337                 return;
  1339             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1340             compileStates.put(env, CompileState.TRANSTYPES);
  1342             if (shouldStop(CompileState.LOWER))
  1343                 return;
  1345             if (sourceOutput) {
  1346                 //emit standard Java source file, only for compilation
  1347                 //units enumerated explicitly on the command line
  1348                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1349                 if (untranslated instanceof JCClassDecl &&
  1350                     rootClasses.contains((JCClassDecl)untranslated)) {
  1351                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1353                 return;
  1356             //translate out inner classes
  1357             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1358             compileStates.put(env, CompileState.LOWER);
  1360             if (shouldStop(CompileState.LOWER))
  1361                 return;
  1363             //generate code for each class
  1364             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1365                 JCClassDecl cdef = (JCClassDecl)l.head;
  1366                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1369         finally {
  1370             log.useSource(prev);
  1375     /** Generates the source or class file for a list of classes.
  1376      * The decision to generate a source file or a class file is
  1377      * based upon the compiler's options.
  1378      * Generation stops if an error occurs while writing files.
  1379      */
  1380     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1381         generate(queue, null);
  1384     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1385         if (shouldStop(CompileState.GENERATE))
  1386             return;
  1388         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1390         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1391             Env<AttrContext> env = x.fst;
  1392             JCClassDecl cdef = x.snd;
  1394             if (verboseCompilePolicy) {
  1395                 printNote("[generate "
  1396                                + (usePrintSource ? " source" : "code")
  1397                                + " " + cdef.sym + "]");
  1400             if (taskListener != null) {
  1401                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1402                 taskListener.started(e);
  1405             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1406                                       env.enclClass.sym.sourcefile :
  1407                                       env.toplevel.sourcefile);
  1408             try {
  1409                 JavaFileObject file;
  1410                 if (usePrintSource)
  1411                     file = printSource(env, cdef);
  1412                 else
  1413                     file = genCode(env, cdef);
  1414                 if (results != null && file != null)
  1415                     results.add(file);
  1416             } catch (IOException ex) {
  1417                 log.error(cdef.pos(), "class.cant.write",
  1418                           cdef.sym, ex.getMessage());
  1419                 return;
  1420             } finally {
  1421                 log.useSource(prev);
  1424             if (taskListener != null) {
  1425                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1426                 taskListener.finished(e);
  1431         // where
  1432         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1433             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1434             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1435             for (Env<AttrContext> env: envs) {
  1436                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1437                 if (sublist == null) {
  1438                     sublist = new ListBuffer<Env<AttrContext>>();
  1439                     map.put(env.toplevel, sublist);
  1441                 sublist.add(env);
  1443             return map;
  1446         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1447             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1448             class MethodBodyRemover extends TreeTranslator {
  1449                 @Override
  1450                 public void visitMethodDef(JCMethodDecl tree) {
  1451                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1452                     for (JCVariableDecl vd : tree.params)
  1453                         vd.mods.flags &= ~Flags.FINAL;
  1454                     tree.body = null;
  1455                     super.visitMethodDef(tree);
  1457                 @Override
  1458                 public void visitVarDef(JCVariableDecl tree) {
  1459                     if (tree.init != null && tree.init.type.constValue() == null)
  1460                         tree.init = null;
  1461                     super.visitVarDef(tree);
  1463                 @Override
  1464                 public void visitClassDef(JCClassDecl tree) {
  1465                     ListBuffer<JCTree> newdefs = lb();
  1466                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1467                         JCTree t = it.head;
  1468                         switch (t.getTag()) {
  1469                         case JCTree.CLASSDEF:
  1470                             if (isInterface ||
  1471                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1472                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1473                                 newdefs.append(t);
  1474                             break;
  1475                         case JCTree.METHODDEF:
  1476                             if (isInterface ||
  1477                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1478                                 ((JCMethodDecl) t).sym.name == names.init ||
  1479                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1480                                 newdefs.append(t);
  1481                             break;
  1482                         case JCTree.VARDEF:
  1483                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1484                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1485                                 newdefs.append(t);
  1486                             break;
  1487                         default:
  1488                             break;
  1491                     tree.defs = newdefs.toList();
  1492                     super.visitClassDef(tree);
  1495             MethodBodyRemover r = new MethodBodyRemover();
  1496             return r.translate(cdef);
  1499     public void reportDeferredDiagnostics() {
  1500         if (annotationProcessingOccurred
  1501                 && implicitSourceFilesRead
  1502                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1503             if (explicitAnnotationProcessingRequested())
  1504                 log.warning("proc.use.implicit");
  1505             else
  1506                 log.warning("proc.use.proc.or.implicit");
  1508         chk.reportDeferredDiagnostics();
  1511     /** Close the compiler, flushing the logs
  1512      */
  1513     public void close() {
  1514         close(true);
  1517     public void close(boolean disposeNames) {
  1518         rootClasses = null;
  1519         reader = null;
  1520         make = null;
  1521         writer = null;
  1522         enter = null;
  1523         if (todo != null)
  1524             todo.clear();
  1525         todo = null;
  1526         parserFactory = null;
  1527         syms = null;
  1528         source = null;
  1529         attr = null;
  1530         chk = null;
  1531         gen = null;
  1532         flow = null;
  1533         transTypes = null;
  1534         lower = null;
  1535         annotate = null;
  1536         types = null;
  1538         log.flush();
  1539         try {
  1540             fileManager.flush();
  1541         } catch (IOException e) {
  1542             throw new Abort(e);
  1543         } finally {
  1544             if (names != null && disposeNames)
  1545                 names.dispose();
  1546             names = null;
  1550     protected void printNote(String lines) {
  1551         Log.printLines(log.noticeWriter, lines);
  1554     /** Output for "-verbose" option.
  1555      *  @param key The key to look up the correct internationalized string.
  1556      *  @param arg An argument for substitution into the output string.
  1557      */
  1558     protected void printVerbose(String key, Object arg) {
  1559         log.printNoteLines("verbose." + key, arg);
  1562     /** Print numbers of errors and warnings.
  1563      */
  1564     protected void printCount(String kind, int count) {
  1565         if (count != 0) {
  1566             String key;
  1567             if (count == 1)
  1568                 key = "count." + kind;
  1569             else
  1570                 key = "count." + kind + ".plural";
  1571             log.printErrLines(key, String.valueOf(count));
  1572             log.errWriter.flush();
  1576     private static long now() {
  1577         return System.currentTimeMillis();
  1580     private static long elapsed(long then) {
  1581         return now() - then;
  1584     public void initRound(JavaCompiler prev) {
  1585         keepComments = prev.keepComments;
  1586         start_msec = prev.start_msec;
  1587         hasBeenUsed = true;
  1590     public static void enableLogging() {
  1591         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1592         logger.setLevel(Level.ALL);
  1593         for (Handler h : logger.getParent().getHandlers()) {
  1594             h.setLevel(Level.ALL);

mercurial