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

Tue, 24 Aug 2010 11:31:00 -0700

author
jjg
date
Tue, 24 Aug 2010 11:31:00 -0700
changeset 654
e9d09e97d669
parent 642
6b95dd682538
child 663
eb7c263aab73
permissions
-rw-r--r--

6935638: -implicit:none prevents compilation with annotation processing
Reviewed-by: darcy

     1 /*
     2  * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.main;
    28 import java.io.*;
    29 import java.util.HashSet;
    30 import java.util.LinkedHashSet;
    31 import java.util.LinkedHashMap;
    32 import java.util.Map;
    33 import java.util.MissingResourceException;
    34 import java.util.ResourceBundle;
    35 import java.util.Set;
    36 import java.util.logging.Handler;
    37 import java.util.logging.Level;
    38 import java.util.logging.Logger;
    40 import javax.tools.JavaFileManager;
    41 import javax.tools.JavaFileObject;
    42 import javax.tools.DiagnosticListener;
    44 import com.sun.tools.javac.file.JavacFileManager;
    45 import com.sun.source.util.TaskEvent;
    46 import com.sun.source.util.TaskListener;
    48 import com.sun.tools.javac.util.*;
    49 import com.sun.tools.javac.code.*;
    50 import com.sun.tools.javac.tree.*;
    51 import com.sun.tools.javac.parser.*;
    52 import com.sun.tools.javac.comp.*;
    53 import com.sun.tools.javac.jvm.*;
    55 import com.sun.tools.javac.code.Symbol.*;
    56 import com.sun.tools.javac.tree.JCTree.*;
    58 import com.sun.tools.javac.processing.*;
    59 import javax.annotation.processing.Processor;
    61 import static javax.tools.StandardLocation.CLASS_OUTPUT;
    62 import static com.sun.tools.javac.util.ListBuffer.lb;
    64 // TEMP, until we have a more efficient way to save doc comment info
    65 import com.sun.tools.javac.parser.DocCommentScanner;
    67 import java.util.HashMap;
    68 import java.util.Queue;
    69 import javax.lang.model.SourceVersion;
    71 /** This class could be the main entry point for GJC when GJC is used as a
    72  *  component in a larger software system. It provides operations to
    73  *  construct a new compiler, and to run a new compiler on a set of source
    74  *  files.
    75  *
    76  *  <p><b>This is NOT part of any supported API.
    77  *  If you write code that depends on this, you do so at your own risk.
    78  *  This code and its internal interfaces are subject to change or
    79  *  deletion without notice.</b>
    80  */
    81 public class JavaCompiler implements ClassReader.SourceCompleter {
    82     /** The context key for the compiler. */
    83     protected static final Context.Key<JavaCompiler> compilerKey =
    84         new Context.Key<JavaCompiler>();
    86     /** Get the JavaCompiler instance for this context. */
    87     public static JavaCompiler instance(Context context) {
    88         JavaCompiler instance = context.get(compilerKey);
    89         if (instance == null)
    90             instance = new JavaCompiler(context);
    91         return instance;
    92     }
    94     /** The current version number as a string.
    95      */
    96     public static String version() {
    97         return version("release");  // mm.nn.oo[-milestone]
    98     }
   100     /** The current full version number as a string.
   101      */
   102     public static String fullVersion() {
   103         return version("full"); // mm.mm.oo[-milestone]-build
   104     }
   106     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   107     private static ResourceBundle versionRB;
   109     private static String version(String key) {
   110         if (versionRB == null) {
   111             try {
   112                 versionRB = ResourceBundle.getBundle(versionRBName);
   113             } catch (MissingResourceException e) {
   114                 return Log.getLocalizedString("version.not.available");
   115             }
   116         }
   117         try {
   118             return versionRB.getString(key);
   119         }
   120         catch (MissingResourceException e) {
   121             return Log.getLocalizedString("version.not.available");
   122         }
   123     }
   125     /**
   126      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   127      * are connected. Each individual file is processed by each phase in turn,
   128      * but with different compile policies, you can control the order in which
   129      * each class is processed through its next phase.
   130      *
   131      * <p>Generally speaking, the compiler will "fail fast" in the face of
   132      * errors, although not aggressively so. flow, desugar, etc become no-ops
   133      * once any errors have occurred. No attempt is currently made to determine
   134      * if it might be safe to process a class through its next phase because
   135      * it does not depend on any unrelated errors that might have occurred.
   136      */
   137     protected static enum CompilePolicy {
   138         /**
   139          * Just attribute the parse trees.
   140          */
   141         ATTR_ONLY,
   143         /**
   144          * Just attribute and do flow analysis on the parse trees.
   145          * This should catch most user errors.
   146          */
   147         CHECK_ONLY,
   149         /**
   150          * Attribute everything, then do flow analysis for everything,
   151          * then desugar everything, and only then generate output.
   152          * This means no output will be generated if there are any
   153          * errors in any classes.
   154          */
   155         SIMPLE,
   157         /**
   158          * Groups the classes for each source file together, then process
   159          * each group in a manner equivalent to the {@code SIMPLE} policy.
   160          * This means no output will be generated if there are any
   161          * errors in any of the classes in a source file.
   162          */
   163         BY_FILE,
   165         /**
   166          * Completely process each entry on the todo list in turn.
   167          * -- this is the same for 1.5.
   168          * Means output might be generated for some classes in a compilation unit
   169          * and not others.
   170          */
   171         BY_TODO;
   173         static CompilePolicy decode(String option) {
   174             if (option == null)
   175                 return DEFAULT_COMPILE_POLICY;
   176             else if (option.equals("attr"))
   177                 return ATTR_ONLY;
   178             else if (option.equals("check"))
   179                 return CHECK_ONLY;
   180             else if (option.equals("simple"))
   181                 return SIMPLE;
   182             else if (option.equals("byfile"))
   183                 return BY_FILE;
   184             else if (option.equals("bytodo"))
   185                 return BY_TODO;
   186             else
   187                 return DEFAULT_COMPILE_POLICY;
   188         }
   189     }
   191     private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   193     protected static enum ImplicitSourcePolicy {
   194         /** Don't generate or process implicitly read source files. */
   195         NONE,
   196         /** Generate classes for implicitly read source files. */
   197         CLASS,
   198         /** Like CLASS, but generate warnings if annotation processing occurs */
   199         UNSET;
   201         static ImplicitSourcePolicy decode(String option) {
   202             if (option == null)
   203                 return UNSET;
   204             else if (option.equals("none"))
   205                 return NONE;
   206             else if (option.equals("class"))
   207                 return CLASS;
   208             else
   209                 return UNSET;
   210         }
   211     }
   213     /** The log to be used for error reporting.
   214      */
   215     public Log log;
   217     /** Factory for creating diagnostic objects
   218      */
   219     JCDiagnostic.Factory diagFactory;
   221     /** The tree factory module.
   222      */
   223     protected TreeMaker make;
   225     /** The class reader.
   226      */
   227     protected ClassReader reader;
   229     /** The class writer.
   230      */
   231     protected ClassWriter writer;
   233     /** The module for the symbol table entry phases.
   234      */
   235     protected Enter enter;
   237     /** The symbol table.
   238      */
   239     protected Symtab syms;
   241     /** The language version.
   242      */
   243     protected Source source;
   245     /** The module for code generation.
   246      */
   247     protected Gen gen;
   249     /** The name table.
   250      */
   251     protected Names names;
   253     /** The attributor.
   254      */
   255     protected Attr attr;
   257     /** The attributor.
   258      */
   259     protected Check chk;
   261     /** The flow analyzer.
   262      */
   263     protected Flow flow;
   265     /** The type eraser.
   266      */
   267     protected TransTypes transTypes;
   269     /** The syntactic sugar desweetener.
   270      */
   271     protected Lower lower;
   273     /** The annotation annotator.
   274      */
   275     protected Annotate annotate;
   277     /** Force a completion failure on this name
   278      */
   279     protected final Name completionFailureName;
   281     /** Type utilities.
   282      */
   283     protected Types types;
   285     /** Access to file objects.
   286      */
   287     protected JavaFileManager fileManager;
   289     /** Factory for parsers.
   290      */
   291     protected ParserFactory parserFactory;
   293     /** Optional listener for progress events
   294      */
   295     protected TaskListener taskListener;
   297     /**
   298      * Annotation processing may require and provide a new instance
   299      * of the compiler to be used for the analyze and generate phases.
   300      */
   301     protected JavaCompiler delegateCompiler;
   303     /**
   304      * Flag set if any annotation processing occurred.
   305      **/
   306     protected boolean annotationProcessingOccurred;
   308     /**
   309      * Flag set if any implicit source files read.
   310      **/
   311     protected boolean implicitSourceFilesRead;
   313     protected Context context;
   315     /** Construct a new compiler using a shared context.
   316      */
   317     public JavaCompiler(final Context context) {
   318         this.context = context;
   319         context.put(compilerKey, this);
   321         // if fileManager not already set, register the JavacFileManager to be used
   322         if (context.get(JavaFileManager.class) == null)
   323             JavacFileManager.preRegister(context);
   325         names = Names.instance(context);
   326         log = Log.instance(context);
   327         diagFactory = JCDiagnostic.Factory.instance(context);
   328         reader = ClassReader.instance(context);
   329         make = TreeMaker.instance(context);
   330         writer = ClassWriter.instance(context);
   331         enter = Enter.instance(context);
   332         todo = Todo.instance(context);
   334         fileManager = context.get(JavaFileManager.class);
   335         parserFactory = ParserFactory.instance(context);
   337         try {
   338             // catch completion problems with predefineds
   339             syms = Symtab.instance(context);
   340         } catch (CompletionFailure ex) {
   341             // inlined Check.completionError as it is not initialized yet
   342             log.error("cant.access", ex.sym, ex.getDetailValue());
   343             if (ex instanceof ClassReader.BadClassFile)
   344                 throw new Abort();
   345         }
   346         source = Source.instance(context);
   347         attr = Attr.instance(context);
   348         chk = Check.instance(context);
   349         gen = Gen.instance(context);
   350         flow = Flow.instance(context);
   351         transTypes = TransTypes.instance(context);
   352         lower = Lower.instance(context);
   353         annotate = Annotate.instance(context);
   354         types = Types.instance(context);
   355         taskListener = context.get(TaskListener.class);
   357         reader.sourceCompleter = this;
   359         Options options = Options.instance(context);
   361         verbose       = options.get("-verbose")       != null;
   362         sourceOutput  = options.get("-printsource")   != null; // used to be -s
   363         stubOutput    = options.get("-stubs")         != null;
   364         relax         = options.get("-relax")         != null;
   365         printFlat     = options.get("-printflat")     != null;
   366         attrParseOnly = options.get("-attrparseonly") != null;
   367         encoding      = options.get("-encoding");
   368         lineDebugInfo = options.get("-g:")            == null ||
   369                         options.get("-g:lines")       != null;
   370         genEndPos     = options.get("-Xjcov")         != null ||
   371                         context.get(DiagnosticListener.class) != null;
   372         devVerbose    = options.get("dev") != null;
   373         processPcks   = options.get("process.packages") != null;
   374         werror        = options.get("-Werror")        != null;
   376         verboseCompilePolicy = options.get("verboseCompilePolicy") != null;
   378         if (attrParseOnly)
   379             compilePolicy = CompilePolicy.ATTR_ONLY;
   380         else
   381             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   383         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   385         completionFailureName =
   386             (options.get("failcomplete") != null)
   387             ? names.fromString(options.get("failcomplete"))
   388             : null;
   390         shouldStopPolicy =
   391             (options.get("shouldStopPolicy") != null)
   392             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   393             : null;
   394         if (options.get("oldDiags") == null)
   395             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   396     }
   398     /* Switches:
   399      */
   401     /** Verbose output.
   402      */
   403     public boolean verbose;
   405     /** Emit plain Java source files rather than class files.
   406      */
   407     public boolean sourceOutput;
   409     /** Emit stub source files rather than class files.
   410      */
   411     public boolean stubOutput;
   413     /** Generate attributed parse tree only.
   414      */
   415     public boolean attrParseOnly;
   417     /** Switch: relax some constraints for producing the jsr14 prototype.
   418      */
   419     boolean relax;
   421     /** Debug switch: Emit Java sources after inner class flattening.
   422      */
   423     public boolean printFlat;
   425     /** The encoding to be used for source input.
   426      */
   427     public String encoding;
   429     /** Generate code with the LineNumberTable attribute for debugging
   430      */
   431     public boolean lineDebugInfo;
   433     /** Switch: should we store the ending positions?
   434      */
   435     public boolean genEndPos;
   437     /** Switch: should we debug ignored exceptions
   438      */
   439     protected boolean devVerbose;
   441     /** Switch: should we (annotation) process packages as well
   442      */
   443     protected boolean processPcks;
   445     /** Switch: treat warnings as errors
   446      */
   447     protected boolean werror;
   449     /** Switch: is annotation processing requested explitly via
   450      * CompilationTask.setProcessors?
   451      */
   452     protected boolean explicitAnnotationProcessingRequested = false;
   454     /**
   455      * The policy for the order in which to perform the compilation
   456      */
   457     protected CompilePolicy compilePolicy;
   459     /**
   460      * The policy for what to do with implicitly read source files
   461      */
   462     protected ImplicitSourcePolicy implicitSourcePolicy;
   464     /**
   465      * Report activity related to compilePolicy
   466      */
   467     public boolean verboseCompilePolicy;
   469     /**
   470      * Policy of how far to continue processing. null means until first
   471      * error.
   472      */
   473     public CompileState shouldStopPolicy;
   475     /** A queue of all as yet unattributed classes.
   476      */
   477     public Todo todo;
   479     /** Ordered list of compiler phases for each compilation unit. */
   480     public enum CompileState {
   481         PARSE(1),
   482         ENTER(2),
   483         PROCESS(3),
   484         ATTR(4),
   485         FLOW(5),
   486         TRANSTYPES(6),
   487         LOWER(7),
   488         GENERATE(8);
   489         CompileState(int value) {
   490             this.value = value;
   491         }
   492         boolean isDone(CompileState other) {
   493             return value >= other.value;
   494         }
   495         private int value;
   496     };
   497     /** Partial map to record which compiler phases have been executed
   498      * for each compilation unit. Used for ATTR and FLOW phases.
   499      */
   500     protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
   501         private static final long serialVersionUID = 1812267524140424433L;
   502         boolean isDone(Env<AttrContext> env, CompileState cs) {
   503             CompileState ecs = get(env);
   504             return ecs != null && ecs.isDone(cs);
   505         }
   506     }
   507     private CompileStates compileStates = new CompileStates();
   509     /** The set of currently compiled inputfiles, needed to ensure
   510      *  we don't accidentally overwrite an input file when -s is set.
   511      *  initialized by `compile'.
   512      */
   513     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   515     protected boolean shouldStop(CompileState cs) {
   516         if (shouldStopPolicy == null)
   517             return (errorCount() > 0);
   518         else
   519             return cs.ordinal() > shouldStopPolicy.ordinal();
   520     }
   522     /** The number of errors reported so far.
   523      */
   524     public int errorCount() {
   525         if (delegateCompiler != null && delegateCompiler != this)
   526             return delegateCompiler.errorCount();
   527         else {
   528             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   529                 log.error("warnings.and.werror");
   530             }
   531         }
   532         return log.nerrors;
   533     }
   535     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   536         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   537     }
   539     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   540         return shouldStop(cs) ? List.<T>nil() : list;
   541     }
   543     /** The number of warnings reported so far.
   544      */
   545     public int warningCount() {
   546         if (delegateCompiler != null && delegateCompiler != this)
   547             return delegateCompiler.warningCount();
   548         else
   549             return log.nwarnings;
   550     }
   552     /** Try to open input stream with given name.
   553      *  Report an error if this fails.
   554      *  @param filename   The file name of the input stream to be opened.
   555      */
   556     public CharSequence readSource(JavaFileObject filename) {
   557         try {
   558             inputFiles.add(filename);
   559             return filename.getCharContent(false);
   560         } catch (IOException e) {
   561             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   562             return null;
   563         }
   564     }
   566     /** Parse contents of input stream.
   567      *  @param filename     The name of the file from which input stream comes.
   568      *  @param input        The input stream to be parsed.
   569      */
   570     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   571         long msec = now();
   572         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   573                                       null, List.<JCTree>nil());
   574         if (content != null) {
   575             if (verbose) {
   576                 printVerbose("parsing.started", filename);
   577             }
   578             if (taskListener != null) {
   579                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   580                 taskListener.started(e);
   581             }
   582             int initialErrorCount = log.nerrors;
   583             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   584             tree = parser.parseCompilationUnit();
   585             log.unrecoverableError |= (log.nerrors > initialErrorCount);
   586             if (verbose) {
   587                 printVerbose("parsing.done", Long.toString(elapsed(msec)));
   588             }
   589         }
   591         tree.sourcefile = filename;
   593         if (content != null && taskListener != null) {
   594             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   595             taskListener.finished(e);
   596         }
   598         return tree;
   599     }
   600     // where
   601         public boolean keepComments = false;
   602         protected boolean keepComments() {
   603             return keepComments || sourceOutput || stubOutput;
   604         }
   607     /** Parse contents of file.
   608      *  @param filename     The name of the file to be parsed.
   609      */
   610     @Deprecated
   611     public JCTree.JCCompilationUnit parse(String filename) throws IOException {
   612         JavacFileManager fm = (JavacFileManager)fileManager;
   613         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   614     }
   616     /** Parse contents of file.
   617      *  @param filename     The name of the file to be parsed.
   618      */
   619     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   620         JavaFileObject prev = log.useSource(filename);
   621         try {
   622             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   623             if (t.endPositions != null)
   624                 log.setEndPosTable(filename, t.endPositions);
   625             return t;
   626         } finally {
   627             log.useSource(prev);
   628         }
   629     }
   631     /** Resolve an identifier.
   632      * @param name      The identifier to resolve
   633      */
   634     public Symbol resolveIdent(String name) {
   635         if (name.equals(""))
   636             return syms.errSymbol;
   637         JavaFileObject prev = log.useSource(null);
   638         try {
   639             JCExpression tree = null;
   640             for (String s : name.split("\\.", -1)) {
   641                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   642                     return syms.errSymbol;
   643                 tree = (tree == null) ? make.Ident(names.fromString(s))
   644                                       : make.Select(tree, names.fromString(s));
   645             }
   646             JCCompilationUnit toplevel =
   647                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   648             toplevel.packge = syms.unnamedPackage;
   649             return attr.attribIdent(tree, toplevel);
   650         } finally {
   651             log.useSource(prev);
   652         }
   653     }
   655     /** Emit plain Java source for a class.
   656      *  @param env    The attribution environment of the outermost class
   657      *                containing this class.
   658      *  @param cdef   The class definition to be printed.
   659      */
   660     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   661         JavaFileObject outFile
   662             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   663                                                cdef.sym.flatname.toString(),
   664                                                JavaFileObject.Kind.SOURCE,
   665                                                null);
   666         if (inputFiles.contains(outFile)) {
   667             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   668             return null;
   669         } else {
   670             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   671             try {
   672                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   673                 if (verbose)
   674                     printVerbose("wrote.file", outFile);
   675             } finally {
   676                 out.close();
   677             }
   678             return outFile;
   679         }
   680     }
   682     /** Generate code and emit a class file for a given class
   683      *  @param env    The attribution environment of the outermost class
   684      *                containing this class.
   685      *  @param cdef   The class definition from which code is generated.
   686      */
   687     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   688         try {
   689             if (gen.genClass(env, cdef) && (errorCount() == 0))
   690                 return writer.writeClass(cdef.sym);
   691         } catch (ClassWriter.PoolOverflow ex) {
   692             log.error(cdef.pos(), "limit.pool");
   693         } catch (ClassWriter.StringOverflow ex) {
   694             log.error(cdef.pos(), "limit.string.overflow",
   695                       ex.value.substring(0, 20));
   696         } catch (CompletionFailure ex) {
   697             chk.completionError(cdef.pos(), ex);
   698         }
   699         return null;
   700     }
   702     /** Complete compiling a source file that has been accessed
   703      *  by the class file reader.
   704      *  @param c          The class the source file of which needs to be compiled.
   705      *  @param filename   The name of the source file.
   706      *  @param f          An input stream that reads the source file.
   707      */
   708     public void complete(ClassSymbol c) throws CompletionFailure {
   709 //      System.err.println("completing " + c);//DEBUG
   710         if (completionFailureName == c.fullname) {
   711             throw new CompletionFailure(c, "user-selected completion failure by class name");
   712         }
   713         JCCompilationUnit tree;
   714         JavaFileObject filename = c.classfile;
   715         JavaFileObject prev = log.useSource(filename);
   717         try {
   718             tree = parse(filename, filename.getCharContent(false));
   719         } catch (IOException e) {
   720             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   721             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   722         } finally {
   723             log.useSource(prev);
   724         }
   726         if (taskListener != null) {
   727             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   728             taskListener.started(e);
   729         }
   731         enter.complete(List.of(tree), c);
   733         if (taskListener != null) {
   734             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   735             taskListener.finished(e);
   736         }
   738         if (enter.getEnv(c) == null) {
   739             boolean isPkgInfo =
   740                 tree.sourcefile.isNameCompatible("package-info",
   741                                                  JavaFileObject.Kind.SOURCE);
   742             if (isPkgInfo) {
   743                 if (enter.getEnv(tree.packge) == null) {
   744                     JCDiagnostic diag =
   745                         diagFactory.fragment("file.does.not.contain.package",
   746                                                  c.location());
   747                     throw reader.new BadClassFile(c, filename, diag);
   748                 }
   749             } else {
   750                 JCDiagnostic diag =
   751                         diagFactory.fragment("file.doesnt.contain.class",
   752                                             c.getQualifiedName());
   753                 throw reader.new BadClassFile(c, filename, diag);
   754             }
   755         }
   757         implicitSourceFilesRead = true;
   758     }
   760     /** Track when the JavaCompiler has been used to compile something. */
   761     private boolean hasBeenUsed = false;
   762     private long start_msec = 0;
   763     public long elapsed_msec = 0;
   765     public void compile(List<JavaFileObject> sourceFileObject)
   766         throws Throwable {
   767         compile(sourceFileObject, List.<String>nil(), null);
   768     }
   770     /**
   771      * Main method: compile a list of files, return all compiled classes
   772      *
   773      * @param sourceFileObjects file objects to be compiled
   774      * @param classnames class names to process for annotations
   775      * @param processors user provided annotation processors to bypass
   776      * discovery, {@code null} means that no processors were provided
   777      */
   778     public void compile(List<JavaFileObject> sourceFileObjects,
   779                         List<String> classnames,
   780                         Iterable<? extends Processor> processors)
   781         throws IOException // TODO: temp, from JavacProcessingEnvironment
   782     {
   783         if (processors != null && processors.iterator().hasNext())
   784             explicitAnnotationProcessingRequested = true;
   785         // as a JavaCompiler can only be used once, throw an exception if
   786         // it has been used before.
   787         if (hasBeenUsed)
   788             throw new AssertionError("attempt to reuse JavaCompiler");
   789         hasBeenUsed = true;
   791         start_msec = now();
   792         try {
   793             initProcessAnnotations(processors);
   795             // These method calls must be chained to avoid memory leaks
   796             delegateCompiler =
   797                 processAnnotations(
   798                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   799                     classnames);
   801             delegateCompiler.compile2();
   802             delegateCompiler.close();
   803             elapsed_msec = delegateCompiler.elapsed_msec;
   804         } catch (Abort ex) {
   805             if (devVerbose)
   806                 ex.printStackTrace();
   807         } finally {
   808             if (procEnvImpl != null)
   809                 procEnvImpl.close();
   810         }
   811     }
   813     /**
   814      * The phases following annotation processing: attribution,
   815      * desugar, and finally code generation.
   816      */
   817     private void compile2() {
   818         try {
   819             switch (compilePolicy) {
   820             case ATTR_ONLY:
   821                 attribute(todo);
   822                 break;
   824             case CHECK_ONLY:
   825                 flow(attribute(todo));
   826                 break;
   828             case SIMPLE:
   829                 generate(desugar(flow(attribute(todo))));
   830                 break;
   832             case BY_FILE: {
   833                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   834                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   835                         generate(desugar(flow(attribute(q.remove()))));
   836                     }
   837                 }
   838                 break;
   840             case BY_TODO:
   841                 while (!todo.isEmpty())
   842                     generate(desugar(flow(attribute(todo.remove()))));
   843                 break;
   845             default:
   846                 assert false: "unknown compile policy";
   847             }
   848         } catch (Abort ex) {
   849             if (devVerbose)
   850                 ex.printStackTrace();
   851         }
   853         if (verbose) {
   854             elapsed_msec = elapsed(start_msec);
   855             printVerbose("total", Long.toString(elapsed_msec));
   856         }
   858         reportDeferredDiagnostics();
   860         if (!log.hasDiagnosticListener()) {
   861             printCount("error", errorCount());
   862             printCount("warn", warningCount());
   863         }
   864     }
   866     private List<JCClassDecl> rootClasses;
   868     /**
   869      * Parses a list of files.
   870      */
   871    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) throws IOException {
   872        if (shouldStop(CompileState.PARSE))
   873            return List.nil();
   875         //parse all files
   876         ListBuffer<JCCompilationUnit> trees = lb();
   877         for (JavaFileObject fileObject : fileObjects)
   878             trees.append(parse(fileObject));
   879         return trees.toList();
   880     }
   882     /**
   883      * Enter the symbols found in a list of parse trees.
   884      * As a side-effect, this puts elements on the "todo" list.
   885      * Also stores a list of all top level classes in rootClasses.
   886      */
   887     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   888         //enter symbols for all files
   889         if (taskListener != null) {
   890             for (JCCompilationUnit unit: roots) {
   891                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   892                 taskListener.started(e);
   893             }
   894         }
   896         enter.main(roots);
   898         if (taskListener != null) {
   899             for (JCCompilationUnit unit: roots) {
   900                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   901                 taskListener.finished(e);
   902             }
   903         }
   905         //If generating source, remember the classes declared in
   906         //the original compilation units listed on the command line.
   907         if (sourceOutput || stubOutput) {
   908             ListBuffer<JCClassDecl> cdefs = lb();
   909             for (JCCompilationUnit unit : roots) {
   910                 for (List<JCTree> defs = unit.defs;
   911                      defs.nonEmpty();
   912                      defs = defs.tail) {
   913                     if (defs.head instanceof JCClassDecl)
   914                         cdefs.append((JCClassDecl)defs.head);
   915                 }
   916             }
   917             rootClasses = cdefs.toList();
   918         }
   920         // Ensure the input files have been recorded. Although this is normally
   921         // done by readSource, it may not have been done if the trees were read
   922         // in a prior round of annotation processing, and the trees have been
   923         // cleaned and are being reused.
   924         for (JCCompilationUnit unit : roots) {
   925             inputFiles.add(unit.sourcefile);
   926         }
   928         return roots;
   929     }
   931     /**
   932      * Set to true to enable skeleton annotation processing code.
   933      * Currently, we assume this variable will be replaced more
   934      * advanced logic to figure out if annotation processing is
   935      * needed.
   936      */
   937     boolean processAnnotations = false;
   939     /**
   940      * Object to handle annotation processing.
   941      */
   942     private JavacProcessingEnvironment procEnvImpl = null;
   944     /**
   945      * Check if we should process annotations.
   946      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
   947      * to catch doc comments, and set keepComments so the parser records them in
   948      * the compilation unit.
   949      *
   950      * @param processors user provided annotation processors to bypass
   951      * discovery, {@code null} means that no processors were provided
   952      */
   953     public void initProcessAnnotations(Iterable<? extends Processor> processors)
   954                 throws IOException {
   955         // Process annotations if processing is not disabled and there
   956         // is at least one Processor available.
   957         Options options = Options.instance(context);
   958         if (options.get("-proc:none") != null) {
   959             processAnnotations = false;
   960         } else if (procEnvImpl == null) {
   961             procEnvImpl = new JavacProcessingEnvironment(context, processors);
   962             processAnnotations = procEnvImpl.atLeastOneProcessor();
   964             if (processAnnotations) {
   965                 if (context.get(Scanner.Factory.scannerFactoryKey) == null)
   966                     DocCommentScanner.Factory.preRegister(context);
   967                 options.put("save-parameter-names", "save-parameter-names");
   968                 reader.saveParameterNames = true;
   969                 keepComments = true;
   970                 if (taskListener != null)
   971                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
   974             } else { // free resources
   975                 procEnvImpl.close();
   976             }
   977         }
   978     }
   980     // TODO: called by JavacTaskImpl
   981     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots)
   982             throws IOException {
   983         return processAnnotations(roots, List.<String>nil());
   984     }
   986     /**
   987      * Process any anotations found in the specifed compilation units.
   988      * @param roots a list of compilation units
   989      * @return an instance of the compiler in which to complete the compilation
   990      */
   991     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
   992                                            List<String> classnames)
   993             throws IOException  { // TODO: see TEMP note in JavacProcessingEnvironment
   994         if (shouldStop(CompileState.PROCESS)) {
   995             // Errors were encountered.
   996             // If log.unrecoverableError is set, the errors were parse errors
   997             // or other errors during enter which cannot be fixed by running
   998             // any annotation processors.
   999             if (log.unrecoverableError)
  1000                 return this;
  1003         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1004         // by initProcessAnnotations
  1006         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1008         if (!processAnnotations) {
  1009             // If there are no annotation processors present, and
  1010             // annotation processing is to occur with compilation,
  1011             // emit a warning.
  1012             Options options = Options.instance(context);
  1013             if (options.get("-proc:only") != null) {
  1014                 log.warning("proc.proc-only.requested.no.procs");
  1015                 todo.clear();
  1017             // If not processing annotations, classnames must be empty
  1018             if (!classnames.isEmpty()) {
  1019                 log.error("proc.no.explicit.annotation.processing.requested",
  1020                           classnames);
  1022             return this; // continue regular compilation
  1025         try {
  1026             List<ClassSymbol> classSymbols = List.nil();
  1027             List<PackageSymbol> pckSymbols = List.nil();
  1028             if (!classnames.isEmpty()) {
  1029                  // Check for explicit request for annotation
  1030                  // processing
  1031                 if (!explicitAnnotationProcessingRequested()) {
  1032                     log.error("proc.no.explicit.annotation.processing.requested",
  1033                               classnames);
  1034                     return this; // TODO: Will this halt compilation?
  1035                 } else {
  1036                     boolean errors = false;
  1037                     for (String nameStr : classnames) {
  1038                         Symbol sym = resolveIdent(nameStr);
  1039                         if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
  1040                             log.error("proc.cant.find.class", nameStr);
  1041                             errors = true;
  1042                             continue;
  1044                         try {
  1045                             if (sym.kind == Kinds.PCK)
  1046                                 sym.complete();
  1047                             if (sym.exists()) {
  1048                                 Name name = names.fromString(nameStr);
  1049                                 if (sym.kind == Kinds.PCK)
  1050                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1051                                 else
  1052                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1053                                 continue;
  1055                             assert sym.kind == Kinds.PCK;
  1056                             log.warning("proc.package.does.not.exist", nameStr);
  1057                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1058                         } catch (CompletionFailure e) {
  1059                             log.error("proc.cant.find.class", nameStr);
  1060                             errors = true;
  1061                             continue;
  1064                     if (errors)
  1065                         return this;
  1068             try {
  1069                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
  1070                 if (c != this)
  1071                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1072                 return c;
  1073             } finally {
  1074                 procEnvImpl.close();
  1076         } catch (CompletionFailure ex) {
  1077             log.error("cant.access", ex.sym, ex.getDetailValue());
  1078             return this;
  1083     boolean explicitAnnotationProcessingRequested() {
  1084         Options options = Options.instance(context);
  1085         return
  1086             explicitAnnotationProcessingRequested ||
  1087             options.get("-processor") != null ||
  1088             options.get("-processorpath") != null ||
  1089             options.get("-proc:only") != null ||
  1090             options.get("-Xprint") != null;
  1093     /**
  1094      * Attribute a list of parse trees, such as found on the "todo" list.
  1095      * Note that attributing classes may cause additional files to be
  1096      * parsed and entered via the SourceCompleter.
  1097      * Attribution of the entries in the list does not stop if any errors occur.
  1098      * @returns a list of environments for attributd classes.
  1099      */
  1100     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1101         ListBuffer<Env<AttrContext>> results = lb();
  1102         while (!envs.isEmpty())
  1103             results.append(attribute(envs.remove()));
  1104         return stopIfError(CompileState.ATTR, results);
  1107     /**
  1108      * Attribute a parse tree.
  1109      * @returns the attributed parse tree
  1110      */
  1111     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1112         if (compileStates.isDone(env, CompileState.ATTR))
  1113             return env;
  1115         if (verboseCompilePolicy)
  1116             printNote("[attribute " + env.enclClass.sym + "]");
  1117         if (verbose)
  1118             printVerbose("checking.attribution", env.enclClass.sym);
  1120         if (taskListener != null) {
  1121             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1122             taskListener.started(e);
  1125         JavaFileObject prev = log.useSource(
  1126                                   env.enclClass.sym.sourcefile != null ?
  1127                                   env.enclClass.sym.sourcefile :
  1128                                   env.toplevel.sourcefile);
  1129         try {
  1130             attr.attribClass(env.tree.pos(), env.enclClass.sym);
  1131             compileStates.put(env, CompileState.ATTR);
  1133         finally {
  1134             log.useSource(prev);
  1137         return env;
  1140     /**
  1141      * Perform dataflow checks on attributed parse trees.
  1142      * These include checks for definite assignment and unreachable statements.
  1143      * If any errors occur, an empty list will be returned.
  1144      * @returns the list of attributed parse trees
  1145      */
  1146     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1147         ListBuffer<Env<AttrContext>> results = lb();
  1148         for (Env<AttrContext> env: envs) {
  1149             flow(env, results);
  1151         return stopIfError(CompileState.FLOW, results);
  1154     /**
  1155      * Perform dataflow checks on an attributed parse tree.
  1156      */
  1157     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1158         ListBuffer<Env<AttrContext>> results = lb();
  1159         flow(env, results);
  1160         return stopIfError(CompileState.FLOW, results);
  1163     /**
  1164      * Perform dataflow checks on an attributed parse tree.
  1165      */
  1166     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1167         try {
  1168             if (shouldStop(CompileState.FLOW))
  1169                 return;
  1171             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1172                 results.add(env);
  1173                 return;
  1176             if (verboseCompilePolicy)
  1177                 printNote("[flow " + env.enclClass.sym + "]");
  1178             JavaFileObject prev = log.useSource(
  1179                                                 env.enclClass.sym.sourcefile != null ?
  1180                                                 env.enclClass.sym.sourcefile :
  1181                                                 env.toplevel.sourcefile);
  1182             try {
  1183                 make.at(Position.FIRSTPOS);
  1184                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1185                 flow.analyzeTree(env, localMake);
  1186                 compileStates.put(env, CompileState.FLOW);
  1188                 if (shouldStop(CompileState.FLOW))
  1189                     return;
  1191                 results.add(env);
  1193             finally {
  1194                 log.useSource(prev);
  1197         finally {
  1198             if (taskListener != null) {
  1199                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1200                 taskListener.finished(e);
  1205     /**
  1206      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1207      * for source or code generation.
  1208      * If any errors occur, an empty list will be returned.
  1209      * @returns a list containing the classes to be generated
  1210      */
  1211     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1212         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1213         for (Env<AttrContext> env: envs)
  1214             desugar(env, results);
  1215         return stopIfError(CompileState.FLOW, results);
  1218     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1219             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1221     /**
  1222      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1223      * for source or code generation. If the file was not listed on the command line,
  1224      * the current implicitSourcePolicy is taken into account.
  1225      * The preparation stops as soon as an error is found.
  1226      */
  1227     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1228         if (shouldStop(CompileState.TRANSTYPES))
  1229             return;
  1231         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1232                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1233             return;
  1236         if (compileStates.isDone(env, CompileState.LOWER)) {
  1237             results.addAll(desugaredEnvs.get(env));
  1238             return;
  1241         /**
  1242          * Ensure that superclasses of C are desugared before C itself. This is
  1243          * required for two reasons: (i) as erasure (TransTypes) destroys
  1244          * information needed in flow analysis and (ii) as some checks carried
  1245          * out during lowering require that all synthetic fields/methods have
  1246          * already been added to C and its superclasses.
  1247          */
  1248         class ScanNested extends TreeScanner {
  1249             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1250             @Override
  1251             public void visitClassDef(JCClassDecl node) {
  1252                 Type st = types.supertype(node.sym.type);
  1253                 if (st.tag == TypeTags.CLASS) {
  1254                     ClassSymbol c = st.tsym.outermostClass();
  1255                     Env<AttrContext> stEnv = enter.getEnv(c);
  1256                     if (stEnv != null && env != stEnv) {
  1257                         if (dependencies.add(stEnv))
  1258                             scan(stEnv.tree);
  1261                 super.visitClassDef(node);
  1264         ScanNested scanner = new ScanNested();
  1265         scanner.scan(env.tree);
  1266         for (Env<AttrContext> dep: scanner.dependencies) {
  1267         if (!compileStates.isDone(dep, CompileState.FLOW))
  1268             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1271         //We need to check for error another time as more classes might
  1272         //have been attributed and analyzed at this stage
  1273         if (shouldStop(CompileState.TRANSTYPES))
  1274             return;
  1276         if (verboseCompilePolicy)
  1277             printNote("[desugar " + env.enclClass.sym + "]");
  1279         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1280                                   env.enclClass.sym.sourcefile :
  1281                                   env.toplevel.sourcefile);
  1282         try {
  1283             //save tree prior to rewriting
  1284             JCTree untranslated = env.tree;
  1286             make.at(Position.FIRSTPOS);
  1287             TreeMaker localMake = make.forToplevel(env.toplevel);
  1289             if (env.tree instanceof JCCompilationUnit) {
  1290                 if (!(stubOutput || sourceOutput || printFlat)) {
  1291                     if (shouldStop(CompileState.LOWER))
  1292                         return;
  1293                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1294                     if (pdef.head != null) {
  1295                         assert pdef.tail.isEmpty();
  1296                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1299                 return;
  1302             if (stubOutput) {
  1303                 //emit stub Java source file, only for compilation
  1304                 //units enumerated explicitly on the command line
  1305                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1306                 if (untranslated instanceof JCClassDecl &&
  1307                     rootClasses.contains((JCClassDecl)untranslated) &&
  1308                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1309                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1310                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1312                 return;
  1315             if (shouldStop(CompileState.TRANSTYPES))
  1316                 return;
  1318             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1319             compileStates.put(env, CompileState.TRANSTYPES);
  1321             if (shouldStop(CompileState.LOWER))
  1322                 return;
  1324             if (sourceOutput) {
  1325                 //emit standard Java source file, only for compilation
  1326                 //units enumerated explicitly on the command line
  1327                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1328                 if (untranslated instanceof JCClassDecl &&
  1329                     rootClasses.contains((JCClassDecl)untranslated)) {
  1330                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1332                 return;
  1335             //translate out inner classes
  1336             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1337             compileStates.put(env, CompileState.LOWER);
  1339             if (shouldStop(CompileState.LOWER))
  1340                 return;
  1342             //generate code for each class
  1343             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1344                 JCClassDecl cdef = (JCClassDecl)l.head;
  1345                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1348         finally {
  1349             log.useSource(prev);
  1354     /** Generates the source or class file for a list of classes.
  1355      * The decision to generate a source file or a class file is
  1356      * based upon the compiler's options.
  1357      * Generation stops if an error occurs while writing files.
  1358      */
  1359     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1360         generate(queue, null);
  1363     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1364         if (shouldStop(CompileState.GENERATE))
  1365             return;
  1367         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1369         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1370             Env<AttrContext> env = x.fst;
  1371             JCClassDecl cdef = x.snd;
  1373             if (verboseCompilePolicy) {
  1374                 printNote("[generate "
  1375                                + (usePrintSource ? " source" : "code")
  1376                                + " " + cdef.sym + "]");
  1379             if (taskListener != null) {
  1380                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1381                 taskListener.started(e);
  1384             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1385                                       env.enclClass.sym.sourcefile :
  1386                                       env.toplevel.sourcefile);
  1387             try {
  1388                 JavaFileObject file;
  1389                 if (usePrintSource)
  1390                     file = printSource(env, cdef);
  1391                 else
  1392                     file = genCode(env, cdef);
  1393                 if (results != null && file != null)
  1394                     results.add(file);
  1395             } catch (IOException ex) {
  1396                 log.error(cdef.pos(), "class.cant.write",
  1397                           cdef.sym, ex.getMessage());
  1398                 return;
  1399             } finally {
  1400                 log.useSource(prev);
  1403             if (taskListener != null) {
  1404                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1405                 taskListener.finished(e);
  1410         // where
  1411         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1412             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1413             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1414             for (Env<AttrContext> env: envs) {
  1415                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1416                 if (sublist == null) {
  1417                     sublist = new ListBuffer<Env<AttrContext>>();
  1418                     map.put(env.toplevel, sublist);
  1420                 sublist.add(env);
  1422             return map;
  1425         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1426             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1427             class MethodBodyRemover extends TreeTranslator {
  1428                 @Override
  1429                 public void visitMethodDef(JCMethodDecl tree) {
  1430                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1431                     for (JCVariableDecl vd : tree.params)
  1432                         vd.mods.flags &= ~Flags.FINAL;
  1433                     tree.body = null;
  1434                     super.visitMethodDef(tree);
  1436                 @Override
  1437                 public void visitVarDef(JCVariableDecl tree) {
  1438                     if (tree.init != null && tree.init.type.constValue() == null)
  1439                         tree.init = null;
  1440                     super.visitVarDef(tree);
  1442                 @Override
  1443                 public void visitClassDef(JCClassDecl tree) {
  1444                     ListBuffer<JCTree> newdefs = lb();
  1445                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1446                         JCTree t = it.head;
  1447                         switch (t.getTag()) {
  1448                         case JCTree.CLASSDEF:
  1449                             if (isInterface ||
  1450                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1451                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1452                                 newdefs.append(t);
  1453                             break;
  1454                         case JCTree.METHODDEF:
  1455                             if (isInterface ||
  1456                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1457                                 ((JCMethodDecl) t).sym.name == names.init ||
  1458                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1459                                 newdefs.append(t);
  1460                             break;
  1461                         case JCTree.VARDEF:
  1462                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1463                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1464                                 newdefs.append(t);
  1465                             break;
  1466                         default:
  1467                             break;
  1470                     tree.defs = newdefs.toList();
  1471                     super.visitClassDef(tree);
  1474             MethodBodyRemover r = new MethodBodyRemover();
  1475             return r.translate(cdef);
  1478     public void reportDeferredDiagnostics() {
  1479         if (annotationProcessingOccurred
  1480                 && implicitSourceFilesRead
  1481                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1482             if (explicitAnnotationProcessingRequested())
  1483                 log.warning("proc.use.implicit");
  1484             else
  1485                 log.warning("proc.use.proc.or.implicit");
  1487         chk.reportDeferredDiagnostics();
  1490     /** Close the compiler, flushing the logs
  1491      */
  1492     public void close() {
  1493         close(true);
  1496     public void close(boolean disposeNames) {
  1497         rootClasses = null;
  1498         reader = null;
  1499         make = null;
  1500         writer = null;
  1501         enter = null;
  1502         if (todo != null)
  1503             todo.clear();
  1504         todo = null;
  1505         parserFactory = null;
  1506         syms = null;
  1507         source = null;
  1508         attr = null;
  1509         chk = null;
  1510         gen = null;
  1511         flow = null;
  1512         transTypes = null;
  1513         lower = null;
  1514         annotate = null;
  1515         types = null;
  1517         log.flush();
  1518         try {
  1519             fileManager.flush();
  1520         } catch (IOException e) {
  1521             throw new Abort(e);
  1522         } finally {
  1523             if (names != null && disposeNames)
  1524                 names.dispose();
  1525             names = null;
  1529     protected void printNote(String lines) {
  1530         Log.printLines(log.noticeWriter, lines);
  1533     /** Output for "-verbose" option.
  1534      *  @param key The key to look up the correct internationalized string.
  1535      *  @param arg An argument for substitution into the output string.
  1536      */
  1537     protected void printVerbose(String key, Object arg) {
  1538         log.printNoteLines("verbose." + key, arg);
  1541     /** Print numbers of errors and warnings.
  1542      */
  1543     protected void printCount(String kind, int count) {
  1544         if (count != 0) {
  1545             String key;
  1546             if (count == 1)
  1547                 key = "count." + kind;
  1548             else
  1549                 key = "count." + kind + ".plural";
  1550             log.printErrLines(key, String.valueOf(count));
  1551             log.errWriter.flush();
  1555     private static long now() {
  1556         return System.currentTimeMillis();
  1559     private static long elapsed(long then) {
  1560         return now() - then;
  1563     public void initRound(JavaCompiler prev) {
  1564         keepComments = prev.keepComments;
  1565         start_msec = prev.start_msec;
  1566         hasBeenUsed = true;
  1569     public static void enableLogging() {
  1570         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1571         logger.setLevel(Level.ALL);
  1572         for (Handler h : logger.getParent().getHandlers()) {
  1573             h.setLevel(Level.ALL);

mercurial