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

Mon, 28 Feb 2011 12:19:18 -0800

author
jjg
date
Mon, 28 Feb 2011 12:19:18 -0800
changeset 897
9029f694e5df
parent 893
8f0dcb9499db
child 902
2a5c919f20b8
permissions
-rw-r--r--

7022337: repeated warnings about bootclasspath not set
Reviewed-by: mcimadamore

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

mercurial