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

Tue, 28 Feb 2012 10:33:49 -0800

author
jjg
date
Tue, 28 Feb 2012 10:33:49 -0800
changeset 1210
62e611704863
parent 1197
237198ef45f5
child 1230
b14d9583ce92
permissions
-rw-r--r--

7093891: support multiple task listeners
Reviewed-by: darcy, mcimadamore

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

mercurial