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

Wed, 16 Mar 2011 17:21:52 -0700

author
jjg
date
Wed, 16 Mar 2011 17:21:52 -0700
changeset 937
a2399c8db703
parent 931
c9432f06d9bc
child 1096
b0d5f00e69f7
permissions
-rw-r--r--

6930508: Passing nested class names on javac command line interfere with subsequent name -> class lookup
Reviewed-by: darcy

     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                 log.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                 log.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 which may be the binary name of a class or
   642      * the Java name of a class or package.
   643      * @param name      The name to resolve
   644      */
   645     public Symbol resolveBinaryNameOrIdent(String name) {
   646         try {
   647             Name flatname = names.fromString(name.replace("/", "."));
   648             return reader.loadClass(flatname);
   649         } catch (CompletionFailure ignore) {
   650             return resolveIdent(name);
   651         }
   652     }
   654     /** Resolve an identifier.
   655      * @param name      The identifier to resolve
   656      */
   657     public Symbol resolveIdent(String name) {
   658         if (name.equals(""))
   659             return syms.errSymbol;
   660         JavaFileObject prev = log.useSource(null);
   661         try {
   662             JCExpression tree = null;
   663             for (String s : name.split("\\.", -1)) {
   664                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   665                     return syms.errSymbol;
   666                 tree = (tree == null) ? make.Ident(names.fromString(s))
   667                                       : make.Select(tree, names.fromString(s));
   668             }
   669             JCCompilationUnit toplevel =
   670                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   671             toplevel.packge = syms.unnamedPackage;
   672             return attr.attribIdent(tree, toplevel);
   673         } finally {
   674             log.useSource(prev);
   675         }
   676     }
   678     /** Emit plain Java source for a class.
   679      *  @param env    The attribution environment of the outermost class
   680      *                containing this class.
   681      *  @param cdef   The class definition to be printed.
   682      */
   683     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   684         JavaFileObject outFile
   685             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   686                                                cdef.sym.flatname.toString(),
   687                                                JavaFileObject.Kind.SOURCE,
   688                                                null);
   689         if (inputFiles.contains(outFile)) {
   690             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   691             return null;
   692         } else {
   693             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   694             try {
   695                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   696                 if (verbose)
   697                     log.printVerbose("wrote.file", outFile);
   698             } finally {
   699                 out.close();
   700             }
   701             return outFile;
   702         }
   703     }
   705     /** Generate code and emit a class file for a given class
   706      *  @param env    The attribution environment of the outermost class
   707      *                containing this class.
   708      *  @param cdef   The class definition from which code is generated.
   709      */
   710     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   711         try {
   712             if (gen.genClass(env, cdef) && (errorCount() == 0))
   713                 return writer.writeClass(cdef.sym);
   714         } catch (ClassWriter.PoolOverflow ex) {
   715             log.error(cdef.pos(), "limit.pool");
   716         } catch (ClassWriter.StringOverflow ex) {
   717             log.error(cdef.pos(), "limit.string.overflow",
   718                       ex.value.substring(0, 20));
   719         } catch (CompletionFailure ex) {
   720             chk.completionError(cdef.pos(), ex);
   721         }
   722         return null;
   723     }
   725     /** Complete compiling a source file that has been accessed
   726      *  by the class file reader.
   727      *  @param c          The class the source file of which needs to be compiled.
   728      *  @param filename   The name of the source file.
   729      *  @param f          An input stream that reads the source file.
   730      */
   731     public void complete(ClassSymbol c) throws CompletionFailure {
   732 //      System.err.println("completing " + c);//DEBUG
   733         if (completionFailureName == c.fullname) {
   734             throw new CompletionFailure(c, "user-selected completion failure by class name");
   735         }
   736         JCCompilationUnit tree;
   737         JavaFileObject filename = c.classfile;
   738         JavaFileObject prev = log.useSource(filename);
   740         try {
   741             tree = parse(filename, filename.getCharContent(false));
   742         } catch (IOException e) {
   743             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   744             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   745         } finally {
   746             log.useSource(prev);
   747         }
   749         if (taskListener != null) {
   750             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   751             taskListener.started(e);
   752         }
   754         enter.complete(List.of(tree), c);
   756         if (taskListener != null) {
   757             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   758             taskListener.finished(e);
   759         }
   761         if (enter.getEnv(c) == null) {
   762             boolean isPkgInfo =
   763                 tree.sourcefile.isNameCompatible("package-info",
   764                                                  JavaFileObject.Kind.SOURCE);
   765             if (isPkgInfo) {
   766                 if (enter.getEnv(tree.packge) == null) {
   767                     JCDiagnostic diag =
   768                         diagFactory.fragment("file.does.not.contain.package",
   769                                                  c.location());
   770                     throw reader.new BadClassFile(c, filename, diag);
   771                 }
   772             } else {
   773                 JCDiagnostic diag =
   774                         diagFactory.fragment("file.doesnt.contain.class",
   775                                             c.getQualifiedName());
   776                 throw reader.new BadClassFile(c, filename, diag);
   777             }
   778         }
   780         implicitSourceFilesRead = true;
   781     }
   783     /** Track when the JavaCompiler has been used to compile something. */
   784     private boolean hasBeenUsed = false;
   785     private long start_msec = 0;
   786     public long elapsed_msec = 0;
   788     public void compile(List<JavaFileObject> sourceFileObject)
   789         throws Throwable {
   790         compile(sourceFileObject, List.<String>nil(), null);
   791     }
   793     /**
   794      * Main method: compile a list of files, return all compiled classes
   795      *
   796      * @param sourceFileObjects file objects to be compiled
   797      * @param classnames class names to process for annotations
   798      * @param processors user provided annotation processors to bypass
   799      * discovery, {@code null} means that no processors were provided
   800      */
   801     public void compile(List<JavaFileObject> sourceFileObjects,
   802                         List<String> classnames,
   803                         Iterable<? extends Processor> processors)
   804     {
   805         if (processors != null && processors.iterator().hasNext())
   806             explicitAnnotationProcessingRequested = true;
   807         // as a JavaCompiler can only be used once, throw an exception if
   808         // it has been used before.
   809         if (hasBeenUsed)
   810             throw new AssertionError("attempt to reuse JavaCompiler");
   811         hasBeenUsed = true;
   813         // forcibly set the equivalent of -Xlint:-options, so that no further
   814         // warnings about command line options are generated from this point on
   815         options.put(XLINT_CUSTOM + "-" + LintCategory.OPTIONS.option, "true");
   816         options.remove(XLINT_CUSTOM + LintCategory.OPTIONS.option);
   818         start_msec = now();
   820         try {
   821             initProcessAnnotations(processors);
   823             // These method calls must be chained to avoid memory leaks
   824             delegateCompiler =
   825                 processAnnotations(
   826                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   827                     classnames);
   829             delegateCompiler.compile2();
   830             delegateCompiler.close();
   831             elapsed_msec = delegateCompiler.elapsed_msec;
   832         } catch (Abort ex) {
   833             if (devVerbose)
   834                 ex.printStackTrace(System.err);
   835         } finally {
   836             if (procEnvImpl != null)
   837                 procEnvImpl.close();
   838         }
   839     }
   841     /**
   842      * The phases following annotation processing: attribution,
   843      * desugar, and finally code generation.
   844      */
   845     private void compile2() {
   846         try {
   847             switch (compilePolicy) {
   848             case ATTR_ONLY:
   849                 attribute(todo);
   850                 break;
   852             case CHECK_ONLY:
   853                 flow(attribute(todo));
   854                 break;
   856             case SIMPLE:
   857                 generate(desugar(flow(attribute(todo))));
   858                 break;
   860             case BY_FILE: {
   861                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   862                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   863                         generate(desugar(flow(attribute(q.remove()))));
   864                     }
   865                 }
   866                 break;
   868             case BY_TODO:
   869                 while (!todo.isEmpty())
   870                     generate(desugar(flow(attribute(todo.remove()))));
   871                 break;
   873             default:
   874                 Assert.error("unknown compile policy");
   875             }
   876         } catch (Abort ex) {
   877             if (devVerbose)
   878                 ex.printStackTrace(System.err);
   879         }
   881         if (verbose) {
   882             elapsed_msec = elapsed(start_msec);
   883             log.printVerbose("total", Long.toString(elapsed_msec));
   884         }
   886         reportDeferredDiagnostics();
   888         if (!log.hasDiagnosticListener()) {
   889             printCount("error", errorCount());
   890             printCount("warn", warningCount());
   891         }
   892     }
   894     private List<JCClassDecl> rootClasses;
   896     /**
   897      * Parses a list of files.
   898      */
   899    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   900        if (shouldStop(CompileState.PARSE))
   901            return List.nil();
   903         //parse all files
   904         ListBuffer<JCCompilationUnit> trees = lb();
   905         Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
   906         for (JavaFileObject fileObject : fileObjects) {
   907             if (!filesSoFar.contains(fileObject)) {
   908                 filesSoFar.add(fileObject);
   909                 trees.append(parse(fileObject));
   910             }
   911         }
   912         return trees.toList();
   913     }
   915     /**
   916      * Enter the symbols found in a list of parse trees.
   917      * As a side-effect, this puts elements on the "todo" list.
   918      * Also stores a list of all top level classes in rootClasses.
   919      */
   920     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   921         //enter symbols for all files
   922         if (taskListener != null) {
   923             for (JCCompilationUnit unit: roots) {
   924                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   925                 taskListener.started(e);
   926             }
   927         }
   929         enter.main(roots);
   931         if (taskListener != null) {
   932             for (JCCompilationUnit unit: roots) {
   933                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   934                 taskListener.finished(e);
   935             }
   936         }
   938         //If generating source, remember the classes declared in
   939         //the original compilation units listed on the command line.
   940         if (sourceOutput || stubOutput) {
   941             ListBuffer<JCClassDecl> cdefs = lb();
   942             for (JCCompilationUnit unit : roots) {
   943                 for (List<JCTree> defs = unit.defs;
   944                      defs.nonEmpty();
   945                      defs = defs.tail) {
   946                     if (defs.head instanceof JCClassDecl)
   947                         cdefs.append((JCClassDecl)defs.head);
   948                 }
   949             }
   950             rootClasses = cdefs.toList();
   951         }
   953         // Ensure the input files have been recorded. Although this is normally
   954         // done by readSource, it may not have been done if the trees were read
   955         // in a prior round of annotation processing, and the trees have been
   956         // cleaned and are being reused.
   957         for (JCCompilationUnit unit : roots) {
   958             inputFiles.add(unit.sourcefile);
   959         }
   961         return roots;
   962     }
   964     /**
   965      * Set to true to enable skeleton annotation processing code.
   966      * Currently, we assume this variable will be replaced more
   967      * advanced logic to figure out if annotation processing is
   968      * needed.
   969      */
   970     boolean processAnnotations = false;
   972     /**
   973      * Object to handle annotation processing.
   974      */
   975     private JavacProcessingEnvironment procEnvImpl = null;
   977     /**
   978      * Check if we should process annotations.
   979      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
   980      * to catch doc comments, and set keepComments so the parser records them in
   981      * the compilation unit.
   982      *
   983      * @param processors user provided annotation processors to bypass
   984      * discovery, {@code null} means that no processors were provided
   985      */
   986     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
   987         // Process annotations if processing is not disabled and there
   988         // is at least one Processor available.
   989         if (options.isSet(PROC, "none")) {
   990             processAnnotations = false;
   991         } else if (procEnvImpl == null) {
   992             procEnvImpl = new JavacProcessingEnvironment(context, processors);
   993             processAnnotations = procEnvImpl.atLeastOneProcessor();
   995             if (processAnnotations) {
   996                 options.put("save-parameter-names", "save-parameter-names");
   997                 reader.saveParameterNames = true;
   998                 keepComments = true;
   999                 genEndPos = true;
  1000                 if (taskListener != null)
  1001                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1002                 log.deferDiagnostics = true;
  1003             } else { // free resources
  1004                 procEnvImpl.close();
  1009     // TODO: called by JavacTaskImpl
  1010     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
  1011         return processAnnotations(roots, List.<String>nil());
  1014     /**
  1015      * Process any anotations found in the specifed compilation units.
  1016      * @param roots a list of compilation units
  1017      * @return an instance of the compiler in which to complete the compilation
  1018      */
  1019     // Implementation note: when this method is called, log.deferredDiagnostics
  1020     // will have been set true by initProcessAnnotations, meaning that any diagnostics
  1021     // that are reported will go into the log.deferredDiagnostics queue.
  1022     // By the time this method exits, log.deferDiagnostics must be set back to false,
  1023     // and all deferredDiagnostics must have been handled: i.e. either reported
  1024     // or determined to be transient, and therefore suppressed.
  1025     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
  1026                                            List<String> classnames) {
  1027         if (shouldStop(CompileState.PROCESS)) {
  1028             // Errors were encountered.
  1029             // Unless all the errors are resolve errors, the errors were parse errors
  1030             // or other errors during enter which cannot be fixed by running
  1031             // any annotation processors.
  1032             if (unrecoverableError()) {
  1033                 log.reportDeferredDiagnostics();
  1034                 return this;
  1038         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1039         // by initProcessAnnotations
  1041         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1043         if (!processAnnotations) {
  1044             // If there are no annotation processors present, and
  1045             // annotation processing is to occur with compilation,
  1046             // emit a warning.
  1047             if (options.isSet(PROC, "only")) {
  1048                 log.warning("proc.proc-only.requested.no.procs");
  1049                 todo.clear();
  1051             // If not processing annotations, classnames must be empty
  1052             if (!classnames.isEmpty()) {
  1053                 log.error("proc.no.explicit.annotation.processing.requested",
  1054                           classnames);
  1056             log.reportDeferredDiagnostics();
  1057             return this; // continue regular compilation
  1060         try {
  1061             List<ClassSymbol> classSymbols = List.nil();
  1062             List<PackageSymbol> pckSymbols = List.nil();
  1063             if (!classnames.isEmpty()) {
  1064                  // Check for explicit request for annotation
  1065                  // processing
  1066                 if (!explicitAnnotationProcessingRequested()) {
  1067                     log.error("proc.no.explicit.annotation.processing.requested",
  1068                               classnames);
  1069                     log.reportDeferredDiagnostics();
  1070                     return this; // TODO: Will this halt compilation?
  1071                 } else {
  1072                     boolean errors = false;
  1073                     for (String nameStr : classnames) {
  1074                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
  1075                         if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
  1076                             log.error("proc.cant.find.class", nameStr);
  1077                             errors = true;
  1078                             continue;
  1080                         try {
  1081                             if (sym.kind == Kinds.PCK)
  1082                                 sym.complete();
  1083                             if (sym.exists()) {
  1084                                 if (sym.kind == Kinds.PCK)
  1085                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1086                                 else
  1087                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1088                                 continue;
  1090                             Assert.check(sym.kind == Kinds.PCK);
  1091                             log.warning("proc.package.does.not.exist", nameStr);
  1092                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1093                         } catch (CompletionFailure e) {
  1094                             log.error("proc.cant.find.class", nameStr);
  1095                             errors = true;
  1096                             continue;
  1099                     if (errors) {
  1100                         log.reportDeferredDiagnostics();
  1101                         return this;
  1105             try {
  1106                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
  1107                 if (c != this)
  1108                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1109                 // doProcessing will have handled deferred diagnostics
  1110                 Assert.check(c.log.deferDiagnostics == false
  1111                         && c.log.deferredDiagnostics.size() == 0);
  1112                 return c;
  1113             } finally {
  1114                 procEnvImpl.close();
  1116         } catch (CompletionFailure ex) {
  1117             log.error("cant.access", ex.sym, ex.getDetailValue());
  1118             log.reportDeferredDiagnostics();
  1119             return this;
  1123     private boolean unrecoverableError() {
  1124         for (JCDiagnostic d: log.deferredDiagnostics) {
  1125             if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
  1126                 return true;
  1128         return false;
  1131     boolean explicitAnnotationProcessingRequested() {
  1132         return
  1133             explicitAnnotationProcessingRequested ||
  1134             explicitAnnotationProcessingRequested(options);
  1137     static boolean explicitAnnotationProcessingRequested(Options options) {
  1138         return
  1139             options.isSet(PROCESSOR) ||
  1140             options.isSet(PROCESSORPATH) ||
  1141             options.isSet(PROC, "only") ||
  1142             options.isSet(XPRINT);
  1145     /**
  1146      * Attribute a list of parse trees, such as found on the "todo" list.
  1147      * Note that attributing classes may cause additional files to be
  1148      * parsed and entered via the SourceCompleter.
  1149      * Attribution of the entries in the list does not stop if any errors occur.
  1150      * @returns a list of environments for attributd classes.
  1151      */
  1152     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1153         ListBuffer<Env<AttrContext>> results = lb();
  1154         while (!envs.isEmpty())
  1155             results.append(attribute(envs.remove()));
  1156         return stopIfError(CompileState.ATTR, results);
  1159     /**
  1160      * Attribute a parse tree.
  1161      * @returns the attributed parse tree
  1162      */
  1163     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1164         if (compileStates.isDone(env, CompileState.ATTR))
  1165             return env;
  1167         if (verboseCompilePolicy)
  1168             printNote("[attribute " + env.enclClass.sym + "]");
  1169         if (verbose)
  1170             log.printVerbose("checking.attribution", env.enclClass.sym);
  1172         if (taskListener != null) {
  1173             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1174             taskListener.started(e);
  1177         JavaFileObject prev = log.useSource(
  1178                                   env.enclClass.sym.sourcefile != null ?
  1179                                   env.enclClass.sym.sourcefile :
  1180                                   env.toplevel.sourcefile);
  1181         try {
  1182             attr.attrib(env);
  1183             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1184                 //if in fail-over mode, ensure that AST expression nodes
  1185                 //are correctly initialized (e.g. they have a type/symbol)
  1186                 attr.postAttr(env);
  1188             compileStates.put(env, CompileState.ATTR);
  1190         finally {
  1191             log.useSource(prev);
  1194         return env;
  1197     /**
  1198      * Perform dataflow checks on attributed parse trees.
  1199      * These include checks for definite assignment and unreachable statements.
  1200      * If any errors occur, an empty list will be returned.
  1201      * @returns the list of attributed parse trees
  1202      */
  1203     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1204         ListBuffer<Env<AttrContext>> results = lb();
  1205         for (Env<AttrContext> env: envs) {
  1206             flow(env, results);
  1208         return stopIfError(CompileState.FLOW, results);
  1211     /**
  1212      * Perform dataflow checks on an attributed parse tree.
  1213      */
  1214     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1215         ListBuffer<Env<AttrContext>> results = lb();
  1216         flow(env, results);
  1217         return stopIfError(CompileState.FLOW, results);
  1220     /**
  1221      * Perform dataflow checks on an attributed parse tree.
  1222      */
  1223     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1224         try {
  1225             if (shouldStop(CompileState.FLOW))
  1226                 return;
  1228             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1229                 results.add(env);
  1230                 return;
  1233             if (verboseCompilePolicy)
  1234                 printNote("[flow " + env.enclClass.sym + "]");
  1235             JavaFileObject prev = log.useSource(
  1236                                                 env.enclClass.sym.sourcefile != null ?
  1237                                                 env.enclClass.sym.sourcefile :
  1238                                                 env.toplevel.sourcefile);
  1239             try {
  1240                 make.at(Position.FIRSTPOS);
  1241                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1242                 flow.analyzeTree(env, localMake);
  1243                 compileStates.put(env, CompileState.FLOW);
  1245                 if (shouldStop(CompileState.FLOW))
  1246                     return;
  1248                 results.add(env);
  1250             finally {
  1251                 log.useSource(prev);
  1254         finally {
  1255             if (taskListener != null) {
  1256                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1257                 taskListener.finished(e);
  1262     /**
  1263      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1264      * for source or code generation.
  1265      * If any errors occur, an empty list will be returned.
  1266      * @returns a list containing the classes to be generated
  1267      */
  1268     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1269         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1270         for (Env<AttrContext> env: envs)
  1271             desugar(env, results);
  1272         return stopIfError(CompileState.FLOW, results);
  1275     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1276             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1278     /**
  1279      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1280      * for source or code generation. If the file was not listed on the command line,
  1281      * the current implicitSourcePolicy is taken into account.
  1282      * The preparation stops as soon as an error is found.
  1283      */
  1284     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1285         if (shouldStop(CompileState.TRANSTYPES))
  1286             return;
  1288         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1289                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1290             return;
  1293         if (compileStates.isDone(env, CompileState.LOWER)) {
  1294             results.addAll(desugaredEnvs.get(env));
  1295             return;
  1298         /**
  1299          * Ensure that superclasses of C are desugared before C itself. This is
  1300          * required for two reasons: (i) as erasure (TransTypes) destroys
  1301          * information needed in flow analysis and (ii) as some checks carried
  1302          * out during lowering require that all synthetic fields/methods have
  1303          * already been added to C and its superclasses.
  1304          */
  1305         class ScanNested extends TreeScanner {
  1306             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1307             @Override
  1308             public void visitClassDef(JCClassDecl node) {
  1309                 Type st = types.supertype(node.sym.type);
  1310                 if (st.tag == TypeTags.CLASS) {
  1311                     ClassSymbol c = st.tsym.outermostClass();
  1312                     Env<AttrContext> stEnv = enter.getEnv(c);
  1313                     if (stEnv != null && env != stEnv) {
  1314                         if (dependencies.add(stEnv))
  1315                             scan(stEnv.tree);
  1318                 super.visitClassDef(node);
  1321         ScanNested scanner = new ScanNested();
  1322         scanner.scan(env.tree);
  1323         for (Env<AttrContext> dep: scanner.dependencies) {
  1324         if (!compileStates.isDone(dep, CompileState.FLOW))
  1325             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1328         //We need to check for error another time as more classes might
  1329         //have been attributed and analyzed at this stage
  1330         if (shouldStop(CompileState.TRANSTYPES))
  1331             return;
  1333         if (verboseCompilePolicy)
  1334             printNote("[desugar " + env.enclClass.sym + "]");
  1336         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1337                                   env.enclClass.sym.sourcefile :
  1338                                   env.toplevel.sourcefile);
  1339         try {
  1340             //save tree prior to rewriting
  1341             JCTree untranslated = env.tree;
  1343             make.at(Position.FIRSTPOS);
  1344             TreeMaker localMake = make.forToplevel(env.toplevel);
  1346             if (env.tree instanceof JCCompilationUnit) {
  1347                 if (!(stubOutput || sourceOutput || printFlat)) {
  1348                     if (shouldStop(CompileState.LOWER))
  1349                         return;
  1350                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1351                     if (pdef.head != null) {
  1352                         Assert.check(pdef.tail.isEmpty());
  1353                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1356                 return;
  1359             if (stubOutput) {
  1360                 //emit stub Java source file, only for compilation
  1361                 //units enumerated explicitly on the command line
  1362                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1363                 if (untranslated instanceof JCClassDecl &&
  1364                     rootClasses.contains((JCClassDecl)untranslated) &&
  1365                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1366                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1367                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1369                 return;
  1372             if (shouldStop(CompileState.TRANSTYPES))
  1373                 return;
  1375             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1376             compileStates.put(env, CompileState.TRANSTYPES);
  1378             if (shouldStop(CompileState.LOWER))
  1379                 return;
  1381             if (sourceOutput) {
  1382                 //emit standard Java source file, only for compilation
  1383                 //units enumerated explicitly on the command line
  1384                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1385                 if (untranslated instanceof JCClassDecl &&
  1386                     rootClasses.contains((JCClassDecl)untranslated)) {
  1387                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1389                 return;
  1392             //translate out inner classes
  1393             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1394             compileStates.put(env, CompileState.LOWER);
  1396             if (shouldStop(CompileState.LOWER))
  1397                 return;
  1399             //generate code for each class
  1400             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1401                 JCClassDecl cdef = (JCClassDecl)l.head;
  1402                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1405         finally {
  1406             log.useSource(prev);
  1411     /** Generates the source or class file for a list of classes.
  1412      * The decision to generate a source file or a class file is
  1413      * based upon the compiler's options.
  1414      * Generation stops if an error occurs while writing files.
  1415      */
  1416     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1417         generate(queue, null);
  1420     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1421         if (shouldStop(CompileState.GENERATE))
  1422             return;
  1424         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1426         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1427             Env<AttrContext> env = x.fst;
  1428             JCClassDecl cdef = x.snd;
  1430             if (verboseCompilePolicy) {
  1431                 printNote("[generate "
  1432                                + (usePrintSource ? " source" : "code")
  1433                                + " " + cdef.sym + "]");
  1436             if (taskListener != null) {
  1437                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1438                 taskListener.started(e);
  1441             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1442                                       env.enclClass.sym.sourcefile :
  1443                                       env.toplevel.sourcefile);
  1444             try {
  1445                 JavaFileObject file;
  1446                 if (usePrintSource)
  1447                     file = printSource(env, cdef);
  1448                 else
  1449                     file = genCode(env, cdef);
  1450                 if (results != null && file != null)
  1451                     results.add(file);
  1452             } catch (IOException ex) {
  1453                 log.error(cdef.pos(), "class.cant.write",
  1454                           cdef.sym, ex.getMessage());
  1455                 return;
  1456             } finally {
  1457                 log.useSource(prev);
  1460             if (taskListener != null) {
  1461                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1462                 taskListener.finished(e);
  1467         // where
  1468         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1469             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1470             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1471             for (Env<AttrContext> env: envs) {
  1472                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1473                 if (sublist == null) {
  1474                     sublist = new ListBuffer<Env<AttrContext>>();
  1475                     map.put(env.toplevel, sublist);
  1477                 sublist.add(env);
  1479             return map;
  1482         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1483             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1484             class MethodBodyRemover extends TreeTranslator {
  1485                 @Override
  1486                 public void visitMethodDef(JCMethodDecl tree) {
  1487                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1488                     for (JCVariableDecl vd : tree.params)
  1489                         vd.mods.flags &= ~Flags.FINAL;
  1490                     tree.body = null;
  1491                     super.visitMethodDef(tree);
  1493                 @Override
  1494                 public void visitVarDef(JCVariableDecl tree) {
  1495                     if (tree.init != null && tree.init.type.constValue() == null)
  1496                         tree.init = null;
  1497                     super.visitVarDef(tree);
  1499                 @Override
  1500                 public void visitClassDef(JCClassDecl tree) {
  1501                     ListBuffer<JCTree> newdefs = lb();
  1502                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1503                         JCTree t = it.head;
  1504                         switch (t.getTag()) {
  1505                         case JCTree.CLASSDEF:
  1506                             if (isInterface ||
  1507                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1508                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1509                                 newdefs.append(t);
  1510                             break;
  1511                         case JCTree.METHODDEF:
  1512                             if (isInterface ||
  1513                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1514                                 ((JCMethodDecl) t).sym.name == names.init ||
  1515                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1516                                 newdefs.append(t);
  1517                             break;
  1518                         case JCTree.VARDEF:
  1519                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1520                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1521                                 newdefs.append(t);
  1522                             break;
  1523                         default:
  1524                             break;
  1527                     tree.defs = newdefs.toList();
  1528                     super.visitClassDef(tree);
  1531             MethodBodyRemover r = new MethodBodyRemover();
  1532             return r.translate(cdef);
  1535     public void reportDeferredDiagnostics() {
  1536         if (errorCount() == 0
  1537                 && annotationProcessingOccurred
  1538                 && implicitSourceFilesRead
  1539                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1540             if (explicitAnnotationProcessingRequested())
  1541                 log.warning("proc.use.implicit");
  1542             else
  1543                 log.warning("proc.use.proc.or.implicit");
  1545         chk.reportDeferredDiagnostics();
  1548     /** Close the compiler, flushing the logs
  1549      */
  1550     public void close() {
  1551         close(true);
  1554     public void close(boolean disposeNames) {
  1555         rootClasses = null;
  1556         reader = null;
  1557         make = null;
  1558         writer = null;
  1559         enter = null;
  1560         if (todo != null)
  1561             todo.clear();
  1562         todo = null;
  1563         parserFactory = null;
  1564         syms = null;
  1565         source = null;
  1566         attr = null;
  1567         chk = null;
  1568         gen = null;
  1569         flow = null;
  1570         transTypes = null;
  1571         lower = null;
  1572         annotate = null;
  1573         types = null;
  1575         log.flush();
  1576         try {
  1577             fileManager.flush();
  1578         } catch (IOException e) {
  1579             throw new Abort(e);
  1580         } finally {
  1581             if (names != null && disposeNames)
  1582                 names.dispose();
  1583             names = null;
  1587     protected void printNote(String lines) {
  1588         Log.printLines(log.noticeWriter, lines);
  1591     /** Print numbers of errors and warnings.
  1592      */
  1593     protected void printCount(String kind, int count) {
  1594         if (count != 0) {
  1595             String key;
  1596             if (count == 1)
  1597                 key = "count." + kind;
  1598             else
  1599                 key = "count." + kind + ".plural";
  1600             log.printErrLines(key, String.valueOf(count));
  1601             log.errWriter.flush();
  1605     private static long now() {
  1606         return System.currentTimeMillis();
  1609     private static long elapsed(long then) {
  1610         return now() - then;
  1613     public void initRound(JavaCompiler prev) {
  1614         genEndPos = prev.genEndPos;
  1615         keepComments = prev.keepComments;
  1616         start_msec = prev.start_msec;
  1617         hasBeenUsed = true;
  1620     public static void enableLogging() {
  1621         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1622         logger.setLevel(Level.ALL);
  1623         for (Handler h : logger.getParent().getHandlers()) {
  1624             h.setLevel(Level.ALL);

mercurial