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

Fri, 25 Feb 2011 12:09:33 -0800

author
jjg
date
Fri, 25 Feb 2011 12:09:33 -0800
changeset 893
8f0dcb9499db
parent 816
7c537f4298fb
child 897
9029f694e5df
permissions
-rw-r--r--

7021650: fix Context issues
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.main;
    28 import java.io.*;
    29 import java.util.HashMap;
    30 import java.util.HashSet;
    31 import java.util.LinkedHashSet;
    32 import java.util.LinkedHashMap;
    33 import java.util.Map;
    34 import java.util.MissingResourceException;
    35 import java.util.Queue;
    36 import java.util.ResourceBundle;
    37 import java.util.Set;
    38 import java.util.logging.Handler;
    39 import java.util.logging.Level;
    40 import java.util.logging.Logger;
    42 import javax.annotation.processing.Processor;
    43 import javax.lang.model.SourceVersion;
    44 import javax.tools.JavaFileManager;
    45 import javax.tools.JavaFileObject;
    46 import javax.tools.DiagnosticListener;
    48 import com.sun.source.util.TaskEvent;
    49 import com.sun.source.util.TaskListener;
    51 import com.sun.tools.javac.file.JavacFileManager;
    52 import com.sun.tools.javac.util.*;
    53 import com.sun.tools.javac.code.*;
    54 import com.sun.tools.javac.code.Lint.LintCategory;
    55 import com.sun.tools.javac.code.Symbol.*;
    56 import com.sun.tools.javac.tree.*;
    57 import com.sun.tools.javac.tree.JCTree.*;
    58 import com.sun.tools.javac.parser.*;
    59 import com.sun.tools.javac.comp.*;
    60 import com.sun.tools.javac.jvm.*;
    61 import com.sun.tools.javac.processing.*;
    63 import static javax.tools.StandardLocation.CLASS_OUTPUT;
    64 import static com.sun.tools.javac.main.OptionName.*;
    65 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    66 import static com.sun.tools.javac.util.ListBuffer.lb;
    69 /** This class could be the main entry point for GJC when GJC is used as a
    70  *  component in a larger software system. It provides operations to
    71  *  construct a new compiler, and to run a new compiler on a set of source
    72  *  files.
    73  *
    74  *  <p><b>This is NOT part of any supported API.
    75  *  If you write code that depends on this, you do so at your own risk.
    76  *  This code and its internal interfaces are subject to change or
    77  *  deletion without notice.</b>
    78  */
    79 public class JavaCompiler implements ClassReader.SourceCompleter {
    80     /** The context key for the compiler. */
    81     protected static final Context.Key<JavaCompiler> compilerKey =
    82         new Context.Key<JavaCompiler>();
    84     /** Get the JavaCompiler instance for this context. */
    85     public static JavaCompiler instance(Context context) {
    86         JavaCompiler instance = context.get(compilerKey);
    87         if (instance == null)
    88             instance = new JavaCompiler(context);
    89         return instance;
    90     }
    92     /** The current version number as a string.
    93      */
    94     public static String version() {
    95         return version("release");  // mm.nn.oo[-milestone]
    96     }
    98     /** The current full version number as a string.
    99      */
   100     public static String fullVersion() {
   101         return version("full"); // mm.mm.oo[-milestone]-build
   102     }
   104     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   105     private static ResourceBundle versionRB;
   107     private static String version(String key) {
   108         if (versionRB == null) {
   109             try {
   110                 versionRB = ResourceBundle.getBundle(versionRBName);
   111             } catch (MissingResourceException e) {
   112                 return Log.getLocalizedString("version.not.available");
   113             }
   114         }
   115         try {
   116             return versionRB.getString(key);
   117         }
   118         catch (MissingResourceException e) {
   119             return Log.getLocalizedString("version.not.available");
   120         }
   121     }
   123     /**
   124      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   125      * are connected. Each individual file is processed by each phase in turn,
   126      * but with different compile policies, you can control the order in which
   127      * each class is processed through its next phase.
   128      *
   129      * <p>Generally speaking, the compiler will "fail fast" in the face of
   130      * errors, although not aggressively so. flow, desugar, etc become no-ops
   131      * once any errors have occurred. No attempt is currently made to determine
   132      * if it might be safe to process a class through its next phase because
   133      * it does not depend on any unrelated errors that might have occurred.
   134      */
   135     protected static enum CompilePolicy {
   136         /**
   137          * Just attribute the parse trees.
   138          */
   139         ATTR_ONLY,
   141         /**
   142          * Just attribute and do flow analysis on the parse trees.
   143          * This should catch most user errors.
   144          */
   145         CHECK_ONLY,
   147         /**
   148          * Attribute everything, then do flow analysis for everything,
   149          * then desugar everything, and only then generate output.
   150          * This means no output will be generated if there are any
   151          * errors in any classes.
   152          */
   153         SIMPLE,
   155         /**
   156          * Groups the classes for each source file together, then process
   157          * each group in a manner equivalent to the {@code SIMPLE} policy.
   158          * This means no output will be generated if there are any
   159          * errors in any of the classes in a source file.
   160          */
   161         BY_FILE,
   163         /**
   164          * Completely process each entry on the todo list in turn.
   165          * -- this is the same for 1.5.
   166          * Means output might be generated for some classes in a compilation unit
   167          * and not others.
   168          */
   169         BY_TODO;
   171         static CompilePolicy decode(String option) {
   172             if (option == null)
   173                 return DEFAULT_COMPILE_POLICY;
   174             else if (option.equals("attr"))
   175                 return ATTR_ONLY;
   176             else if (option.equals("check"))
   177                 return CHECK_ONLY;
   178             else if (option.equals("simple"))
   179                 return SIMPLE;
   180             else if (option.equals("byfile"))
   181                 return BY_FILE;
   182             else if (option.equals("bytodo"))
   183                 return BY_TODO;
   184             else
   185                 return DEFAULT_COMPILE_POLICY;
   186         }
   187     }
   189     private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   191     protected static enum ImplicitSourcePolicy {
   192         /** Don't generate or process implicitly read source files. */
   193         NONE,
   194         /** Generate classes for implicitly read source files. */
   195         CLASS,
   196         /** Like CLASS, but generate warnings if annotation processing occurs */
   197         UNSET;
   199         static ImplicitSourcePolicy decode(String option) {
   200             if (option == null)
   201                 return UNSET;
   202             else if (option.equals("none"))
   203                 return NONE;
   204             else if (option.equals("class"))
   205                 return CLASS;
   206             else
   207                 return UNSET;
   208         }
   209     }
   211     /** The log to be used for error reporting.
   212      */
   213     public Log log;
   215     /** Factory for creating diagnostic objects
   216      */
   217     JCDiagnostic.Factory diagFactory;
   219     /** The tree factory module.
   220      */
   221     protected TreeMaker make;
   223     /** The class reader.
   224      */
   225     protected ClassReader reader;
   227     /** The class writer.
   228      */
   229     protected ClassWriter writer;
   231     /** The module for the symbol table entry phases.
   232      */
   233     protected Enter enter;
   235     /** The symbol table.
   236      */
   237     protected Symtab syms;
   239     /** The language version.
   240      */
   241     protected Source source;
   243     /** The module for code generation.
   244      */
   245     protected Gen gen;
   247     /** The name table.
   248      */
   249     protected Names names;
   251     /** The attributor.
   252      */
   253     protected Attr attr;
   255     /** The attributor.
   256      */
   257     protected Check chk;
   259     /** The flow analyzer.
   260      */
   261     protected Flow flow;
   263     /** The type eraser.
   264      */
   265     protected TransTypes transTypes;
   267     /** The syntactic sugar desweetener.
   268      */
   269     protected Lower lower;
   271     /** The annotation annotator.
   272      */
   273     protected Annotate annotate;
   275     /** Force a completion failure on this name
   276      */
   277     protected final Name completionFailureName;
   279     /** Type utilities.
   280      */
   281     protected Types types;
   283     /** Access to file objects.
   284      */
   285     protected JavaFileManager fileManager;
   287     /** Factory for parsers.
   288      */
   289     protected ParserFactory parserFactory;
   291     /** Optional listener for progress events
   292      */
   293     protected TaskListener taskListener;
   295     /**
   296      * Annotation processing may require and provide a new instance
   297      * of the compiler to be used for the analyze and generate phases.
   298      */
   299     protected JavaCompiler delegateCompiler;
   301     /**
   302      * Flag set if any annotation processing occurred.
   303      **/
   304     protected boolean annotationProcessingOccurred;
   306     /**
   307      * Flag set if any implicit source files read.
   308      **/
   309     protected boolean implicitSourceFilesRead;
   311     protected Context context;
   313     /** Construct a new compiler using a shared context.
   314      */
   315     public JavaCompiler(Context context) {
   316         this.context = context;
   317         context.put(compilerKey, this);
   319         // if fileManager not already set, register the JavacFileManager to be used
   320         if (context.get(JavaFileManager.class) == null)
   321             JavacFileManager.preRegister(context);
   323         names = Names.instance(context);
   324         log = Log.instance(context);
   325         diagFactory = JCDiagnostic.Factory.instance(context);
   326         reader = ClassReader.instance(context);
   327         make = TreeMaker.instance(context);
   328         writer = ClassWriter.instance(context);
   329         enter = Enter.instance(context);
   330         todo = Todo.instance(context);
   332         fileManager = context.get(JavaFileManager.class);
   333         parserFactory = ParserFactory.instance(context);
   335         try {
   336             // catch completion problems with predefineds
   337             syms = Symtab.instance(context);
   338         } catch (CompletionFailure ex) {
   339             // inlined Check.completionError as it is not initialized yet
   340             log.error("cant.access", ex.sym, ex.getDetailValue());
   341             if (ex instanceof ClassReader.BadClassFile)
   342                 throw new Abort();
   343         }
   344         source = Source.instance(context);
   345         attr = Attr.instance(context);
   346         chk = Check.instance(context);
   347         gen = Gen.instance(context);
   348         flow = Flow.instance(context);
   349         transTypes = TransTypes.instance(context);
   350         lower = Lower.instance(context);
   351         annotate = Annotate.instance(context);
   352         types = Types.instance(context);
   353         taskListener = context.get(TaskListener.class);
   355         reader.sourceCompleter = this;
   357         Options options = Options.instance(context);
   359         verbose       = options.isSet(VERBOSE);
   360         sourceOutput  = options.isSet(PRINTSOURCE); // used to be -s
   361         stubOutput    = options.isSet("-stubs");
   362         relax         = options.isSet("-relax");
   363         printFlat     = options.isSet("-printflat");
   364         attrParseOnly = options.isSet("-attrparseonly");
   365         encoding      = options.get(ENCODING);
   366         lineDebugInfo = options.isUnset(G_CUSTOM) ||
   367                         options.isSet(G_CUSTOM, "lines");
   368         genEndPos     = options.isSet(XJCOV) ||
   369                         context.get(DiagnosticListener.class) != null;
   370         devVerbose    = options.isSet("dev");
   371         processPcks   = options.isSet("process.packages");
   372         werror        = options.isSet(WERROR);
   374         if (source.compareTo(Source.DEFAULT) < 0) {
   375             if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   376                 if (fileManager instanceof BaseFileManager) {
   377                     if (((BaseFileManager) fileManager).isDefaultBootClassPath())
   378                         log.warning(LintCategory.OPTIONS, "source.no.bootclasspath", source.name);
   379                 }
   380             }
   381         }
   383         verboseCompilePolicy = options.isSet("verboseCompilePolicy");
   385         if (attrParseOnly)
   386             compilePolicy = CompilePolicy.ATTR_ONLY;
   387         else
   388             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   390         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   392         completionFailureName =
   393             options.isSet("failcomplete")
   394             ? names.fromString(options.get("failcomplete"))
   395             : null;
   397         shouldStopPolicy =
   398             options.isSet("shouldStopPolicy")
   399             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   400             : null;
   401         if (options.isUnset("oldDiags"))
   402             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   403     }
   405     /* Switches:
   406      */
   408     /** Verbose output.
   409      */
   410     public boolean verbose;
   412     /** Emit plain Java source files rather than class files.
   413      */
   414     public boolean sourceOutput;
   416     /** Emit stub source files rather than class files.
   417      */
   418     public boolean stubOutput;
   420     /** Generate attributed parse tree only.
   421      */
   422     public boolean attrParseOnly;
   424     /** Switch: relax some constraints for producing the jsr14 prototype.
   425      */
   426     boolean relax;
   428     /** Debug switch: Emit Java sources after inner class flattening.
   429      */
   430     public boolean printFlat;
   432     /** The encoding to be used for source input.
   433      */
   434     public String encoding;
   436     /** Generate code with the LineNumberTable attribute for debugging
   437      */
   438     public boolean lineDebugInfo;
   440     /** Switch: should we store the ending positions?
   441      */
   442     public boolean genEndPos;
   444     /** Switch: should we debug ignored exceptions
   445      */
   446     protected boolean devVerbose;
   448     /** Switch: should we (annotation) process packages as well
   449      */
   450     protected boolean processPcks;
   452     /** Switch: treat warnings as errors
   453      */
   454     protected boolean werror;
   456     /** Switch: is annotation processing requested explitly via
   457      * CompilationTask.setProcessors?
   458      */
   459     protected boolean explicitAnnotationProcessingRequested = false;
   461     /**
   462      * The policy for the order in which to perform the compilation
   463      */
   464     protected CompilePolicy compilePolicy;
   466     /**
   467      * The policy for what to do with implicitly read source files
   468      */
   469     protected ImplicitSourcePolicy implicitSourcePolicy;
   471     /**
   472      * Report activity related to compilePolicy
   473      */
   474     public boolean verboseCompilePolicy;
   476     /**
   477      * Policy of how far to continue processing. null means until first
   478      * error.
   479      */
   480     public CompileState shouldStopPolicy;
   482     /** A queue of all as yet unattributed classes.
   483      */
   484     public Todo todo;
   486     /** Ordered list of compiler phases for each compilation unit. */
   487     public enum CompileState {
   488         PARSE(1),
   489         ENTER(2),
   490         PROCESS(3),
   491         ATTR(4),
   492         FLOW(5),
   493         TRANSTYPES(6),
   494         LOWER(7),
   495         GENERATE(8);
   496         CompileState(int value) {
   497             this.value = value;
   498         }
   499         boolean isDone(CompileState other) {
   500             return value >= other.value;
   501         }
   502         private int value;
   503     };
   504     /** Partial map to record which compiler phases have been executed
   505      * for each compilation unit. Used for ATTR and FLOW phases.
   506      */
   507     protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
   508         private static final long serialVersionUID = 1812267524140424433L;
   509         boolean isDone(Env<AttrContext> env, CompileState cs) {
   510             CompileState ecs = get(env);
   511             return ecs != null && ecs.isDone(cs);
   512         }
   513     }
   514     private CompileStates compileStates = new CompileStates();
   516     /** The set of currently compiled inputfiles, needed to ensure
   517      *  we don't accidentally overwrite an input file when -s is set.
   518      *  initialized by `compile'.
   519      */
   520     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   522     protected boolean shouldStop(CompileState cs) {
   523         if (shouldStopPolicy == null)
   524             return (errorCount() > 0 || unrecoverableError());
   525         else
   526             return cs.ordinal() > shouldStopPolicy.ordinal();
   527     }
   529     /** The number of errors reported so far.
   530      */
   531     public int errorCount() {
   532         if (delegateCompiler != null && delegateCompiler != this)
   533             return delegateCompiler.errorCount();
   534         else {
   535             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   536                 log.error("warnings.and.werror");
   537             }
   538         }
   539         return log.nerrors;
   540     }
   542     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   543         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   544     }
   546     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   547         return shouldStop(cs) ? List.<T>nil() : list;
   548     }
   550     /** The number of warnings reported so far.
   551      */
   552     public int warningCount() {
   553         if (delegateCompiler != null && delegateCompiler != this)
   554             return delegateCompiler.warningCount();
   555         else
   556             return log.nwarnings;
   557     }
   559     /** Try to open input stream with given name.
   560      *  Report an error if this fails.
   561      *  @param filename   The file name of the input stream to be opened.
   562      */
   563     public CharSequence readSource(JavaFileObject filename) {
   564         try {
   565             inputFiles.add(filename);
   566             return filename.getCharContent(false);
   567         } catch (IOException e) {
   568             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   569             return null;
   570         }
   571     }
   573     /** Parse contents of input stream.
   574      *  @param filename     The name of the file from which input stream comes.
   575      *  @param input        The input stream to be parsed.
   576      */
   577     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   578         long msec = now();
   579         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   580                                       null, List.<JCTree>nil());
   581         if (content != null) {
   582             if (verbose) {
   583                 printVerbose("parsing.started", filename);
   584             }
   585             if (taskListener != null) {
   586                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   587                 taskListener.started(e);
   588             }
   589             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   590             tree = parser.parseCompilationUnit();
   591             if (verbose) {
   592                 printVerbose("parsing.done", Long.toString(elapsed(msec)));
   593             }
   594         }
   596         tree.sourcefile = filename;
   598         if (content != null && taskListener != null) {
   599             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   600             taskListener.finished(e);
   601         }
   603         return tree;
   604     }
   605     // where
   606         public boolean keepComments = false;
   607         protected boolean keepComments() {
   608             return keepComments || sourceOutput || stubOutput;
   609         }
   612     /** Parse contents of file.
   613      *  @param filename     The name of the file to be parsed.
   614      */
   615     @Deprecated
   616     public JCTree.JCCompilationUnit parse(String filename) {
   617         JavacFileManager fm = (JavacFileManager)fileManager;
   618         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   619     }
   621     /** Parse contents of file.
   622      *  @param filename     The name of the file to be parsed.
   623      */
   624     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   625         JavaFileObject prev = log.useSource(filename);
   626         try {
   627             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   628             if (t.endPositions != null)
   629                 log.setEndPosTable(filename, t.endPositions);
   630             return t;
   631         } finally {
   632             log.useSource(prev);
   633         }
   634     }
   636     /** Resolve an identifier.
   637      * @param name      The identifier to resolve
   638      */
   639     public Symbol resolveIdent(String name) {
   640         if (name.equals(""))
   641             return syms.errSymbol;
   642         JavaFileObject prev = log.useSource(null);
   643         try {
   644             JCExpression tree = null;
   645             for (String s : name.split("\\.", -1)) {
   646                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   647                     return syms.errSymbol;
   648                 tree = (tree == null) ? make.Ident(names.fromString(s))
   649                                       : make.Select(tree, names.fromString(s));
   650             }
   651             JCCompilationUnit toplevel =
   652                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   653             toplevel.packge = syms.unnamedPackage;
   654             return attr.attribIdent(tree, toplevel);
   655         } finally {
   656             log.useSource(prev);
   657         }
   658     }
   660     /** Emit plain Java source for a class.
   661      *  @param env    The attribution environment of the outermost class
   662      *                containing this class.
   663      *  @param cdef   The class definition to be printed.
   664      */
   665     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   666         JavaFileObject outFile
   667             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   668                                                cdef.sym.flatname.toString(),
   669                                                JavaFileObject.Kind.SOURCE,
   670                                                null);
   671         if (inputFiles.contains(outFile)) {
   672             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   673             return null;
   674         } else {
   675             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   676             try {
   677                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   678                 if (verbose)
   679                     printVerbose("wrote.file", outFile);
   680             } finally {
   681                 out.close();
   682             }
   683             return outFile;
   684         }
   685     }
   687     /** Generate code and emit a class file for a given class
   688      *  @param env    The attribution environment of the outermost class
   689      *                containing this class.
   690      *  @param cdef   The class definition from which code is generated.
   691      */
   692     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   693         try {
   694             if (gen.genClass(env, cdef) && (errorCount() == 0))
   695                 return writer.writeClass(cdef.sym);
   696         } catch (ClassWriter.PoolOverflow ex) {
   697             log.error(cdef.pos(), "limit.pool");
   698         } catch (ClassWriter.StringOverflow ex) {
   699             log.error(cdef.pos(), "limit.string.overflow",
   700                       ex.value.substring(0, 20));
   701         } catch (CompletionFailure ex) {
   702             chk.completionError(cdef.pos(), ex);
   703         }
   704         return null;
   705     }
   707     /** Complete compiling a source file that has been accessed
   708      *  by the class file reader.
   709      *  @param c          The class the source file of which needs to be compiled.
   710      *  @param filename   The name of the source file.
   711      *  @param f          An input stream that reads the source file.
   712      */
   713     public void complete(ClassSymbol c) throws CompletionFailure {
   714 //      System.err.println("completing " + c);//DEBUG
   715         if (completionFailureName == c.fullname) {
   716             throw new CompletionFailure(c, "user-selected completion failure by class name");
   717         }
   718         JCCompilationUnit tree;
   719         JavaFileObject filename = c.classfile;
   720         JavaFileObject prev = log.useSource(filename);
   722         try {
   723             tree = parse(filename, filename.getCharContent(false));
   724         } catch (IOException e) {
   725             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   726             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   727         } finally {
   728             log.useSource(prev);
   729         }
   731         if (taskListener != null) {
   732             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   733             taskListener.started(e);
   734         }
   736         enter.complete(List.of(tree), c);
   738         if (taskListener != null) {
   739             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   740             taskListener.finished(e);
   741         }
   743         if (enter.getEnv(c) == null) {
   744             boolean isPkgInfo =
   745                 tree.sourcefile.isNameCompatible("package-info",
   746                                                  JavaFileObject.Kind.SOURCE);
   747             if (isPkgInfo) {
   748                 if (enter.getEnv(tree.packge) == null) {
   749                     JCDiagnostic diag =
   750                         diagFactory.fragment("file.does.not.contain.package",
   751                                                  c.location());
   752                     throw reader.new BadClassFile(c, filename, diag);
   753                 }
   754             } else {
   755                 JCDiagnostic diag =
   756                         diagFactory.fragment("file.doesnt.contain.class",
   757                                             c.getQualifiedName());
   758                 throw reader.new BadClassFile(c, filename, diag);
   759             }
   760         }
   762         implicitSourceFilesRead = true;
   763     }
   765     /** Track when the JavaCompiler has been used to compile something. */
   766     private boolean hasBeenUsed = false;
   767     private long start_msec = 0;
   768     public long elapsed_msec = 0;
   770     public void compile(List<JavaFileObject> sourceFileObject)
   771         throws Throwable {
   772         compile(sourceFileObject, List.<String>nil(), null);
   773     }
   775     /**
   776      * Main method: compile a list of files, return all compiled classes
   777      *
   778      * @param sourceFileObjects file objects to be compiled
   779      * @param classnames class names to process for annotations
   780      * @param processors user provided annotation processors to bypass
   781      * discovery, {@code null} means that no processors were provided
   782      */
   783     public void compile(List<JavaFileObject> sourceFileObjects,
   784                         List<String> classnames,
   785                         Iterable<? extends Processor> processors)
   786     {
   787         if (processors != null && processors.iterator().hasNext())
   788             explicitAnnotationProcessingRequested = true;
   789         // as a JavaCompiler can only be used once, throw an exception if
   790         // it has been used before.
   791         if (hasBeenUsed)
   792             throw new AssertionError("attempt to reuse JavaCompiler");
   793         hasBeenUsed = true;
   795         start_msec = now();
   797         try {
   798             initProcessAnnotations(processors);
   800             // These method calls must be chained to avoid memory leaks
   801             delegateCompiler =
   802                 processAnnotations(
   803                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   804                     classnames);
   806             delegateCompiler.compile2();
   807             delegateCompiler.close();
   808             elapsed_msec = delegateCompiler.elapsed_msec;
   809         } catch (Abort ex) {
   810             if (devVerbose)
   811                 ex.printStackTrace(System.err);
   812         } finally {
   813             if (procEnvImpl != null)
   814                 procEnvImpl.close();
   815         }
   816     }
   818     /**
   819      * The phases following annotation processing: attribution,
   820      * desugar, and finally code generation.
   821      */
   822     private void compile2() {
   823         try {
   824             switch (compilePolicy) {
   825             case ATTR_ONLY:
   826                 attribute(todo);
   827                 break;
   829             case CHECK_ONLY:
   830                 flow(attribute(todo));
   831                 break;
   833             case SIMPLE:
   834                 generate(desugar(flow(attribute(todo))));
   835                 break;
   837             case BY_FILE: {
   838                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   839                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   840                         generate(desugar(flow(attribute(q.remove()))));
   841                     }
   842                 }
   843                 break;
   845             case BY_TODO:
   846                 while (!todo.isEmpty())
   847                     generate(desugar(flow(attribute(todo.remove()))));
   848                 break;
   850             default:
   851                 Assert.error("unknown compile policy");
   852             }
   853         } catch (Abort ex) {
   854             if (devVerbose)
   855                 ex.printStackTrace(System.err);
   856         }
   858         if (verbose) {
   859             elapsed_msec = elapsed(start_msec);
   860             printVerbose("total", Long.toString(elapsed_msec));
   861         }
   863         reportDeferredDiagnostics();
   865         if (!log.hasDiagnosticListener()) {
   866             printCount("error", errorCount());
   867             printCount("warn", warningCount());
   868         }
   869     }
   871     private List<JCClassDecl> rootClasses;
   873     /**
   874      * Parses a list of files.
   875      */
   876    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   877        if (shouldStop(CompileState.PARSE))
   878            return List.nil();
   880         //parse all files
   881         ListBuffer<JCCompilationUnit> trees = lb();
   882         Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
   883         for (JavaFileObject fileObject : fileObjects) {
   884             if (!filesSoFar.contains(fileObject)) {
   885                 filesSoFar.add(fileObject);
   886                 trees.append(parse(fileObject));
   887             }
   888         }
   889         return trees.toList();
   890     }
   892     /**
   893      * Enter the symbols found in a list of parse trees.
   894      * As a side-effect, this puts elements on the "todo" list.
   895      * Also stores a list of all top level classes in rootClasses.
   896      */
   897     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   898         //enter symbols for all files
   899         if (taskListener != null) {
   900             for (JCCompilationUnit unit: roots) {
   901                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   902                 taskListener.started(e);
   903             }
   904         }
   906         enter.main(roots);
   908         if (taskListener != null) {
   909             for (JCCompilationUnit unit: roots) {
   910                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   911                 taskListener.finished(e);
   912             }
   913         }
   915         //If generating source, remember the classes declared in
   916         //the original compilation units listed on the command line.
   917         if (sourceOutput || stubOutput) {
   918             ListBuffer<JCClassDecl> cdefs = lb();
   919             for (JCCompilationUnit unit : roots) {
   920                 for (List<JCTree> defs = unit.defs;
   921                      defs.nonEmpty();
   922                      defs = defs.tail) {
   923                     if (defs.head instanceof JCClassDecl)
   924                         cdefs.append((JCClassDecl)defs.head);
   925                 }
   926             }
   927             rootClasses = cdefs.toList();
   928         }
   930         // Ensure the input files have been recorded. Although this is normally
   931         // done by readSource, it may not have been done if the trees were read
   932         // in a prior round of annotation processing, and the trees have been
   933         // cleaned and are being reused.
   934         for (JCCompilationUnit unit : roots) {
   935             inputFiles.add(unit.sourcefile);
   936         }
   938         return roots;
   939     }
   941     /**
   942      * Set to true to enable skeleton annotation processing code.
   943      * Currently, we assume this variable will be replaced more
   944      * advanced logic to figure out if annotation processing is
   945      * needed.
   946      */
   947     boolean processAnnotations = false;
   949     /**
   950      * Object to handle annotation processing.
   951      */
   952     private JavacProcessingEnvironment procEnvImpl = null;
   954     /**
   955      * Check if we should process annotations.
   956      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
   957      * to catch doc comments, and set keepComments so the parser records them in
   958      * the compilation unit.
   959      *
   960      * @param processors user provided annotation processors to bypass
   961      * discovery, {@code null} means that no processors were provided
   962      */
   963     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
   964         // Process annotations if processing is not disabled and there
   965         // is at least one Processor available.
   966         Options options = Options.instance(context);
   967         if (options.isSet(PROC, "none")) {
   968             processAnnotations = false;
   969         } else if (procEnvImpl == null) {
   970             procEnvImpl = new JavacProcessingEnvironment(context, processors);
   971             processAnnotations = procEnvImpl.atLeastOneProcessor();
   973             if (processAnnotations) {
   974                 options.put("save-parameter-names", "save-parameter-names");
   975                 reader.saveParameterNames = true;
   976                 keepComments = true;
   977                 genEndPos = true;
   978                 if (taskListener != null)
   979                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
   980                 log.deferDiagnostics = true;
   981             } else { // free resources
   982                 procEnvImpl.close();
   983             }
   984         }
   985     }
   987     // TODO: called by JavacTaskImpl
   988     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
   989         return processAnnotations(roots, List.<String>nil());
   990     }
   992     /**
   993      * Process any anotations found in the specifed compilation units.
   994      * @param roots a list of compilation units
   995      * @return an instance of the compiler in which to complete the compilation
   996      */
   997     // Implementation note: when this method is called, log.deferredDiagnostics
   998     // will have been set true by initProcessAnnotations, meaning that any diagnostics
   999     // that are reported will go into the log.deferredDiagnostics queue.
  1000     // By the time this method exits, log.deferDiagnostics must be set back to false,
  1001     // and all deferredDiagnostics must have been handled: i.e. either reported
  1002     // or determined to be transient, and therefore suppressed.
  1003     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
  1004                                            List<String> classnames) {
  1005         if (shouldStop(CompileState.PROCESS)) {
  1006             // Errors were encountered.
  1007             // Unless all the errors are resolve errors, the errors were parse errors
  1008             // or other errors during enter which cannot be fixed by running
  1009             // any annotation processors.
  1010             if (unrecoverableError()) {
  1011                 log.reportDeferredDiagnostics();
  1012                 return this;
  1016         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1017         // by initProcessAnnotations
  1019         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1021         if (!processAnnotations) {
  1022             // If there are no annotation processors present, and
  1023             // annotation processing is to occur with compilation,
  1024             // emit a warning.
  1025             Options options = Options.instance(context);
  1026             if (options.isSet(PROC, "only")) {
  1027                 log.warning("proc.proc-only.requested.no.procs");
  1028                 todo.clear();
  1030             // If not processing annotations, classnames must be empty
  1031             if (!classnames.isEmpty()) {
  1032                 log.error("proc.no.explicit.annotation.processing.requested",
  1033                           classnames);
  1035             log.reportDeferredDiagnostics();
  1036             return this; // continue regular compilation
  1039         try {
  1040             List<ClassSymbol> classSymbols = List.nil();
  1041             List<PackageSymbol> pckSymbols = List.nil();
  1042             if (!classnames.isEmpty()) {
  1043                  // Check for explicit request for annotation
  1044                  // processing
  1045                 if (!explicitAnnotationProcessingRequested()) {
  1046                     log.error("proc.no.explicit.annotation.processing.requested",
  1047                               classnames);
  1048                     log.reportDeferredDiagnostics();
  1049                     return this; // TODO: Will this halt compilation?
  1050                 } else {
  1051                     boolean errors = false;
  1052                     for (String nameStr : classnames) {
  1053                         Symbol sym = resolveIdent(nameStr);
  1054                         if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
  1055                             log.error("proc.cant.find.class", nameStr);
  1056                             errors = true;
  1057                             continue;
  1059                         try {
  1060                             if (sym.kind == Kinds.PCK)
  1061                                 sym.complete();
  1062                             if (sym.exists()) {
  1063                                 if (sym.kind == Kinds.PCK)
  1064                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1065                                 else
  1066                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1067                                 continue;
  1069                             Assert.check(sym.kind == Kinds.PCK);
  1070                             log.warning("proc.package.does.not.exist", nameStr);
  1071                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1072                         } catch (CompletionFailure e) {
  1073                             log.error("proc.cant.find.class", nameStr);
  1074                             errors = true;
  1075                             continue;
  1078                     if (errors) {
  1079                         log.reportDeferredDiagnostics();
  1080                         return this;
  1084             try {
  1085                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
  1086                 if (c != this)
  1087                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1088                 // doProcessing will have handled deferred diagnostics
  1089                 Assert.check(c.log.deferDiagnostics == false
  1090                         && c.log.deferredDiagnostics.size() == 0);
  1091                 return c;
  1092             } finally {
  1093                 procEnvImpl.close();
  1095         } catch (CompletionFailure ex) {
  1096             log.error("cant.access", ex.sym, ex.getDetailValue());
  1097             log.reportDeferredDiagnostics();
  1098             return this;
  1102     private boolean unrecoverableError() {
  1103         for (JCDiagnostic d: log.deferredDiagnostics) {
  1104             if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
  1105                 return true;
  1107         return false;
  1110     boolean explicitAnnotationProcessingRequested() {
  1111         Options options = Options.instance(context);
  1112         return
  1113             explicitAnnotationProcessingRequested ||
  1114             options.isSet(PROCESSOR) ||
  1115             options.isSet(PROCESSORPATH) ||
  1116             options.isSet(PROC, "only") ||
  1117             options.isSet(XPRINT);
  1120     /**
  1121      * Attribute a list of parse trees, such as found on the "todo" list.
  1122      * Note that attributing classes may cause additional files to be
  1123      * parsed and entered via the SourceCompleter.
  1124      * Attribution of the entries in the list does not stop if any errors occur.
  1125      * @returns a list of environments for attributd classes.
  1126      */
  1127     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1128         ListBuffer<Env<AttrContext>> results = lb();
  1129         while (!envs.isEmpty())
  1130             results.append(attribute(envs.remove()));
  1131         return stopIfError(CompileState.ATTR, results);
  1134     /**
  1135      * Attribute a parse tree.
  1136      * @returns the attributed parse tree
  1137      */
  1138     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1139         if (compileStates.isDone(env, CompileState.ATTR))
  1140             return env;
  1142         if (verboseCompilePolicy)
  1143             printNote("[attribute " + env.enclClass.sym + "]");
  1144         if (verbose)
  1145             printVerbose("checking.attribution", env.enclClass.sym);
  1147         if (taskListener != null) {
  1148             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1149             taskListener.started(e);
  1152         JavaFileObject prev = log.useSource(
  1153                                   env.enclClass.sym.sourcefile != null ?
  1154                                   env.enclClass.sym.sourcefile :
  1155                                   env.toplevel.sourcefile);
  1156         try {
  1157             attr.attribClass(env.tree.pos(), env.enclClass.sym);
  1158             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1159                 //if in fail-over mode, ensure that AST expression nodes
  1160                 //are correctly initialized (e.g. they have a type/symbol)
  1161                 attr.postAttr(env);
  1163             compileStates.put(env, CompileState.ATTR);
  1165         finally {
  1166             log.useSource(prev);
  1169         return env;
  1172     /**
  1173      * Perform dataflow checks on attributed parse trees.
  1174      * These include checks for definite assignment and unreachable statements.
  1175      * If any errors occur, an empty list will be returned.
  1176      * @returns the list of attributed parse trees
  1177      */
  1178     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1179         ListBuffer<Env<AttrContext>> results = lb();
  1180         for (Env<AttrContext> env: envs) {
  1181             flow(env, results);
  1183         return stopIfError(CompileState.FLOW, results);
  1186     /**
  1187      * Perform dataflow checks on an attributed parse tree.
  1188      */
  1189     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1190         ListBuffer<Env<AttrContext>> results = lb();
  1191         flow(env, results);
  1192         return stopIfError(CompileState.FLOW, results);
  1195     /**
  1196      * Perform dataflow checks on an attributed parse tree.
  1197      */
  1198     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1199         try {
  1200             if (shouldStop(CompileState.FLOW))
  1201                 return;
  1203             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1204                 results.add(env);
  1205                 return;
  1208             if (verboseCompilePolicy)
  1209                 printNote("[flow " + env.enclClass.sym + "]");
  1210             JavaFileObject prev = log.useSource(
  1211                                                 env.enclClass.sym.sourcefile != null ?
  1212                                                 env.enclClass.sym.sourcefile :
  1213                                                 env.toplevel.sourcefile);
  1214             try {
  1215                 make.at(Position.FIRSTPOS);
  1216                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1217                 flow.analyzeTree(env, localMake);
  1218                 compileStates.put(env, CompileState.FLOW);
  1220                 if (shouldStop(CompileState.FLOW))
  1221                     return;
  1223                 results.add(env);
  1225             finally {
  1226                 log.useSource(prev);
  1229         finally {
  1230             if (taskListener != null) {
  1231                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1232                 taskListener.finished(e);
  1237     /**
  1238      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1239      * for source or code generation.
  1240      * If any errors occur, an empty list will be returned.
  1241      * @returns a list containing the classes to be generated
  1242      */
  1243     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1244         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1245         for (Env<AttrContext> env: envs)
  1246             desugar(env, results);
  1247         return stopIfError(CompileState.FLOW, results);
  1250     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1251             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1253     /**
  1254      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1255      * for source or code generation. If the file was not listed on the command line,
  1256      * the current implicitSourcePolicy is taken into account.
  1257      * The preparation stops as soon as an error is found.
  1258      */
  1259     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1260         if (shouldStop(CompileState.TRANSTYPES))
  1261             return;
  1263         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1264                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1265             return;
  1268         if (compileStates.isDone(env, CompileState.LOWER)) {
  1269             results.addAll(desugaredEnvs.get(env));
  1270             return;
  1273         /**
  1274          * Ensure that superclasses of C are desugared before C itself. This is
  1275          * required for two reasons: (i) as erasure (TransTypes) destroys
  1276          * information needed in flow analysis and (ii) as some checks carried
  1277          * out during lowering require that all synthetic fields/methods have
  1278          * already been added to C and its superclasses.
  1279          */
  1280         class ScanNested extends TreeScanner {
  1281             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1282             @Override
  1283             public void visitClassDef(JCClassDecl node) {
  1284                 Type st = types.supertype(node.sym.type);
  1285                 if (st.tag == TypeTags.CLASS) {
  1286                     ClassSymbol c = st.tsym.outermostClass();
  1287                     Env<AttrContext> stEnv = enter.getEnv(c);
  1288                     if (stEnv != null && env != stEnv) {
  1289                         if (dependencies.add(stEnv))
  1290                             scan(stEnv.tree);
  1293                 super.visitClassDef(node);
  1296         ScanNested scanner = new ScanNested();
  1297         scanner.scan(env.tree);
  1298         for (Env<AttrContext> dep: scanner.dependencies) {
  1299         if (!compileStates.isDone(dep, CompileState.FLOW))
  1300             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1303         //We need to check for error another time as more classes might
  1304         //have been attributed and analyzed at this stage
  1305         if (shouldStop(CompileState.TRANSTYPES))
  1306             return;
  1308         if (verboseCompilePolicy)
  1309             printNote("[desugar " + env.enclClass.sym + "]");
  1311         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1312                                   env.enclClass.sym.sourcefile :
  1313                                   env.toplevel.sourcefile);
  1314         try {
  1315             //save tree prior to rewriting
  1316             JCTree untranslated = env.tree;
  1318             make.at(Position.FIRSTPOS);
  1319             TreeMaker localMake = make.forToplevel(env.toplevel);
  1321             if (env.tree instanceof JCCompilationUnit) {
  1322                 if (!(stubOutput || sourceOutput || printFlat)) {
  1323                     if (shouldStop(CompileState.LOWER))
  1324                         return;
  1325                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1326                     if (pdef.head != null) {
  1327                         Assert.check(pdef.tail.isEmpty());
  1328                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1331                 return;
  1334             if (stubOutput) {
  1335                 //emit stub Java source file, only for compilation
  1336                 //units enumerated explicitly on the command line
  1337                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1338                 if (untranslated instanceof JCClassDecl &&
  1339                     rootClasses.contains((JCClassDecl)untranslated) &&
  1340                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1341                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1342                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1344                 return;
  1347             if (shouldStop(CompileState.TRANSTYPES))
  1348                 return;
  1350             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1351             compileStates.put(env, CompileState.TRANSTYPES);
  1353             if (shouldStop(CompileState.LOWER))
  1354                 return;
  1356             if (sourceOutput) {
  1357                 //emit standard Java source file, only for compilation
  1358                 //units enumerated explicitly on the command line
  1359                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1360                 if (untranslated instanceof JCClassDecl &&
  1361                     rootClasses.contains((JCClassDecl)untranslated)) {
  1362                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1364                 return;
  1367             //translate out inner classes
  1368             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1369             compileStates.put(env, CompileState.LOWER);
  1371             if (shouldStop(CompileState.LOWER))
  1372                 return;
  1374             //generate code for each class
  1375             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1376                 JCClassDecl cdef = (JCClassDecl)l.head;
  1377                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1380         finally {
  1381             log.useSource(prev);
  1386     /** Generates the source or class file for a list of classes.
  1387      * The decision to generate a source file or a class file is
  1388      * based upon the compiler's options.
  1389      * Generation stops if an error occurs while writing files.
  1390      */
  1391     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1392         generate(queue, null);
  1395     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1396         if (shouldStop(CompileState.GENERATE))
  1397             return;
  1399         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1401         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1402             Env<AttrContext> env = x.fst;
  1403             JCClassDecl cdef = x.snd;
  1405             if (verboseCompilePolicy) {
  1406                 printNote("[generate "
  1407                                + (usePrintSource ? " source" : "code")
  1408                                + " " + cdef.sym + "]");
  1411             if (taskListener != null) {
  1412                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1413                 taskListener.started(e);
  1416             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1417                                       env.enclClass.sym.sourcefile :
  1418                                       env.toplevel.sourcefile);
  1419             try {
  1420                 JavaFileObject file;
  1421                 if (usePrintSource)
  1422                     file = printSource(env, cdef);
  1423                 else
  1424                     file = genCode(env, cdef);
  1425                 if (results != null && file != null)
  1426                     results.add(file);
  1427             } catch (IOException ex) {
  1428                 log.error(cdef.pos(), "class.cant.write",
  1429                           cdef.sym, ex.getMessage());
  1430                 return;
  1431             } finally {
  1432                 log.useSource(prev);
  1435             if (taskListener != null) {
  1436                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1437                 taskListener.finished(e);
  1442         // where
  1443         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1444             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1445             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1446             for (Env<AttrContext> env: envs) {
  1447                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1448                 if (sublist == null) {
  1449                     sublist = new ListBuffer<Env<AttrContext>>();
  1450                     map.put(env.toplevel, sublist);
  1452                 sublist.add(env);
  1454             return map;
  1457         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1458             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1459             class MethodBodyRemover extends TreeTranslator {
  1460                 @Override
  1461                 public void visitMethodDef(JCMethodDecl tree) {
  1462                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1463                     for (JCVariableDecl vd : tree.params)
  1464                         vd.mods.flags &= ~Flags.FINAL;
  1465                     tree.body = null;
  1466                     super.visitMethodDef(tree);
  1468                 @Override
  1469                 public void visitVarDef(JCVariableDecl tree) {
  1470                     if (tree.init != null && tree.init.type.constValue() == null)
  1471                         tree.init = null;
  1472                     super.visitVarDef(tree);
  1474                 @Override
  1475                 public void visitClassDef(JCClassDecl tree) {
  1476                     ListBuffer<JCTree> newdefs = lb();
  1477                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1478                         JCTree t = it.head;
  1479                         switch (t.getTag()) {
  1480                         case JCTree.CLASSDEF:
  1481                             if (isInterface ||
  1482                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1483                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1484                                 newdefs.append(t);
  1485                             break;
  1486                         case JCTree.METHODDEF:
  1487                             if (isInterface ||
  1488                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1489                                 ((JCMethodDecl) t).sym.name == names.init ||
  1490                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1491                                 newdefs.append(t);
  1492                             break;
  1493                         case JCTree.VARDEF:
  1494                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1495                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1496                                 newdefs.append(t);
  1497                             break;
  1498                         default:
  1499                             break;
  1502                     tree.defs = newdefs.toList();
  1503                     super.visitClassDef(tree);
  1506             MethodBodyRemover r = new MethodBodyRemover();
  1507             return r.translate(cdef);
  1510     public void reportDeferredDiagnostics() {
  1511         if (annotationProcessingOccurred
  1512                 && implicitSourceFilesRead
  1513                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1514             if (explicitAnnotationProcessingRequested())
  1515                 log.warning("proc.use.implicit");
  1516             else
  1517                 log.warning("proc.use.proc.or.implicit");
  1519         chk.reportDeferredDiagnostics();
  1522     /** Close the compiler, flushing the logs
  1523      */
  1524     public void close() {
  1525         close(true);
  1528     public void close(boolean disposeNames) {
  1529         rootClasses = null;
  1530         reader = null;
  1531         make = null;
  1532         writer = null;
  1533         enter = null;
  1534         if (todo != null)
  1535             todo.clear();
  1536         todo = null;
  1537         parserFactory = null;
  1538         syms = null;
  1539         source = null;
  1540         attr = null;
  1541         chk = null;
  1542         gen = null;
  1543         flow = null;
  1544         transTypes = null;
  1545         lower = null;
  1546         annotate = null;
  1547         types = null;
  1549         log.flush();
  1550         try {
  1551             fileManager.flush();
  1552         } catch (IOException e) {
  1553             throw new Abort(e);
  1554         } finally {
  1555             if (names != null && disposeNames)
  1556                 names.dispose();
  1557             names = null;
  1561     protected void printNote(String lines) {
  1562         Log.printLines(log.noticeWriter, lines);
  1565     /** Output for "-verbose" option.
  1566      *  @param key The key to look up the correct internationalized string.
  1567      *  @param arg An argument for substitution into the output string.
  1568      */
  1569     protected void printVerbose(String key, Object arg) {
  1570         log.printNoteLines("verbose." + key, arg);
  1573     /** Print numbers of errors and warnings.
  1574      */
  1575     protected void printCount(String kind, int count) {
  1576         if (count != 0) {
  1577             String key;
  1578             if (count == 1)
  1579                 key = "count." + kind;
  1580             else
  1581                 key = "count." + kind + ".plural";
  1582             log.printErrLines(key, String.valueOf(count));
  1583             log.errWriter.flush();
  1587     private static long now() {
  1588         return System.currentTimeMillis();
  1591     private static long elapsed(long then) {
  1592         return now() - then;
  1595     public void initRound(JavaCompiler prev) {
  1596         genEndPos = prev.genEndPos;
  1597         keepComments = prev.keepComments;
  1598         start_msec = prev.start_msec;
  1599         hasBeenUsed = true;
  1602     public static void enableLogging() {
  1603         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1604         logger.setLevel(Level.ALL);
  1605         for (Handler h : logger.getParent().getHandlers()) {
  1606             h.setLevel(Level.ALL);

mercurial