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

Tue, 07 May 2013 14:27:30 -0700

author
jjg
date
Tue, 07 May 2013 14:27:30 -0700
changeset 1728
43c2f7cb9c76
parent 1690
76537856a54e
child 1755
ddb4a2bfcd82
permissions
-rw-r--r--

8004082: test/tools/javac/plugin/showtype/Test.java fails on windows: jtreg can't delete plugin.jar
Reviewed-by: vromero, mcimadamore

     1 /*
     2  * Copyright (c) 1999, 2013, 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 com.sun.tools.javac.comp.CompileStates;
    29 import java.io.*;
    30 import java.util.HashMap;
    31 import java.util.HashSet;
    32 import java.util.LinkedHashMap;
    33 import java.util.LinkedHashSet;
    34 import java.util.Map;
    35 import java.util.MissingResourceException;
    36 import java.util.Queue;
    37 import java.util.ResourceBundle;
    38 import java.util.Set;
    39 import java.util.logging.Handler;
    40 import java.util.logging.Level;
    41 import java.util.logging.Logger;
    43 import javax.annotation.processing.Processor;
    44 import javax.lang.model.SourceVersion;
    45 import javax.tools.DiagnosticListener;
    46 import javax.tools.JavaFileManager;
    47 import javax.tools.JavaFileObject;
    48 import javax.tools.StandardLocation;
    50 import static javax.tools.StandardLocation.CLASS_OUTPUT;
    52 import com.sun.source.util.TaskEvent;
    53 import com.sun.tools.javac.api.MultiTaskListener;
    54 import com.sun.tools.javac.code.*;
    55 import com.sun.tools.javac.code.Lint.LintCategory;
    56 import com.sun.tools.javac.code.Symbol.*;
    57 import com.sun.tools.javac.comp.*;
    58 import com.sun.tools.javac.file.JavacFileManager;
    59 import com.sun.tools.javac.jvm.*;
    60 import com.sun.tools.javac.parser.*;
    61 import com.sun.tools.javac.processing.*;
    62 import com.sun.tools.javac.tree.*;
    63 import com.sun.tools.javac.tree.JCTree.*;
    64 import com.sun.tools.javac.util.*;
    65 import com.sun.tools.javac.comp.CompileStates.CompileState;
    66 import com.sun.tools.javac.util.Log.WriterKind;
    68 import static com.sun.tools.javac.code.TypeTag.CLASS;
    69 import static com.sun.tools.javac.main.Option.*;
    70 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    71 import static com.sun.tools.javac.util.ListBuffer.lb;
    74 /** This class could be the main entry point for GJC when GJC is used as a
    75  *  component in a larger software system. It provides operations to
    76  *  construct a new compiler, and to run a new compiler on a set of source
    77  *  files.
    78  *
    79  *  <p><b>This is NOT part of any supported API.
    80  *  If you write code that depends on this, you do so at your own risk.
    81  *  This code and its internal interfaces are subject to change or
    82  *  deletion without notice.</b>
    83  */
    84 public class JavaCompiler implements ClassReader.SourceCompleter {
    85     /** The context key for the compiler. */
    86     protected static final Context.Key<JavaCompiler> compilerKey =
    87         new Context.Key<JavaCompiler>();
    89     /** Get the JavaCompiler instance for this context. */
    90     public static JavaCompiler instance(Context context) {
    91         JavaCompiler instance = context.get(compilerKey);
    92         if (instance == null)
    93             instance = new JavaCompiler(context);
    94         return instance;
    95     }
    97     /** The current version number as a string.
    98      */
    99     public static String version() {
   100         return version("release");  // mm.nn.oo[-milestone]
   101     }
   103     /** The current full version number as a string.
   104      */
   105     public static String fullVersion() {
   106         return version("full"); // mm.mm.oo[-milestone]-build
   107     }
   109     private static final String versionRBName = "com.sun.tools.javac.resources.version";
   110     private static ResourceBundle versionRB;
   112     private static String version(String key) {
   113         if (versionRB == null) {
   114             try {
   115                 versionRB = ResourceBundle.getBundle(versionRBName);
   116             } catch (MissingResourceException e) {
   117                 return Log.getLocalizedString("version.not.available");
   118             }
   119         }
   120         try {
   121             return versionRB.getString(key);
   122         }
   123         catch (MissingResourceException e) {
   124             return Log.getLocalizedString("version.not.available");
   125         }
   126     }
   128     /**
   129      * Control how the compiler's latter phases (attr, flow, desugar, generate)
   130      * are connected. Each individual file is processed by each phase in turn,
   131      * but with different compile policies, you can control the order in which
   132      * each class is processed through its next phase.
   133      *
   134      * <p>Generally speaking, the compiler will "fail fast" in the face of
   135      * errors, although not aggressively so. flow, desugar, etc become no-ops
   136      * once any errors have occurred. No attempt is currently made to determine
   137      * if it might be safe to process a class through its next phase because
   138      * it does not depend on any unrelated errors that might have occurred.
   139      */
   140     protected static enum CompilePolicy {
   141         /**
   142          * Just attribute the parse trees.
   143          */
   144         ATTR_ONLY,
   146         /**
   147          * Just attribute and do flow analysis on the parse trees.
   148          * This should catch most user errors.
   149          */
   150         CHECK_ONLY,
   152         /**
   153          * Attribute everything, then do flow analysis for everything,
   154          * then desugar everything, and only then generate output.
   155          * This means no output will be generated if there are any
   156          * errors in any classes.
   157          */
   158         SIMPLE,
   160         /**
   161          * Groups the classes for each source file together, then process
   162          * each group in a manner equivalent to the {@code SIMPLE} policy.
   163          * This means no output will be generated if there are any
   164          * errors in any of the classes in a source file.
   165          */
   166         BY_FILE,
   168         /**
   169          * Completely process each entry on the todo list in turn.
   170          * -- this is the same for 1.5.
   171          * Means output might be generated for some classes in a compilation unit
   172          * and not others.
   173          */
   174         BY_TODO;
   176         static CompilePolicy decode(String option) {
   177             if (option == null)
   178                 return DEFAULT_COMPILE_POLICY;
   179             else if (option.equals("attr"))
   180                 return ATTR_ONLY;
   181             else if (option.equals("check"))
   182                 return CHECK_ONLY;
   183             else if (option.equals("simple"))
   184                 return SIMPLE;
   185             else if (option.equals("byfile"))
   186                 return BY_FILE;
   187             else if (option.equals("bytodo"))
   188                 return BY_TODO;
   189             else
   190                 return DEFAULT_COMPILE_POLICY;
   191         }
   192     }
   194     private static final CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
   196     protected static enum ImplicitSourcePolicy {
   197         /** Don't generate or process implicitly read source files. */
   198         NONE,
   199         /** Generate classes for implicitly read source files. */
   200         CLASS,
   201         /** Like CLASS, but generate warnings if annotation processing occurs */
   202         UNSET;
   204         static ImplicitSourcePolicy decode(String option) {
   205             if (option == null)
   206                 return UNSET;
   207             else if (option.equals("none"))
   208                 return NONE;
   209             else if (option.equals("class"))
   210                 return CLASS;
   211             else
   212                 return UNSET;
   213         }
   214     }
   216     /** The log to be used for error reporting.
   217      */
   218     public Log log;
   220     /** Factory for creating diagnostic objects
   221      */
   222     JCDiagnostic.Factory diagFactory;
   224     /** The tree factory module.
   225      */
   226     protected TreeMaker make;
   228     /** The class reader.
   229      */
   230     protected ClassReader reader;
   232     /** The class writer.
   233      */
   234     protected ClassWriter writer;
   236     /** The native header writer.
   237      */
   238     protected JNIWriter jniWriter;
   240     /** The module for the symbol table entry phases.
   241      */
   242     protected Enter enter;
   244     /** The symbol table.
   245      */
   246     protected Symtab syms;
   248     /** The language version.
   249      */
   250     protected Source source;
   252     /** The module for code generation.
   253      */
   254     protected Gen gen;
   256     /** The name table.
   257      */
   258     protected Names names;
   260     /** The attributor.
   261      */
   262     protected Attr attr;
   264     /** The attributor.
   265      */
   266     protected Check chk;
   268     /** The flow analyzer.
   269      */
   270     protected Flow flow;
   272     /** The type eraser.
   273      */
   274     protected TransTypes transTypes;
   276     /** The lambda translator.
   277      */
   278     protected LambdaToMethod lambdaToMethod;
   280     /** The syntactic sugar desweetener.
   281      */
   282     protected Lower lower;
   284     /** The annotation annotator.
   285      */
   286     protected Annotate annotate;
   288     /** Force a completion failure on this name
   289      */
   290     protected final Name completionFailureName;
   292     /** Type utilities.
   293      */
   294     protected Types types;
   296     /** Access to file objects.
   297      */
   298     protected JavaFileManager fileManager;
   300     /** Factory for parsers.
   301      */
   302     protected ParserFactory parserFactory;
   304     /** Broadcasting listener for progress events
   305      */
   306     protected MultiTaskListener taskListener;
   308     /**
   309      * Annotation processing may require and provide a new instance
   310      * of the compiler to be used for the analyze and generate phases.
   311      */
   312     protected JavaCompiler delegateCompiler;
   314     /**
   315      * Command line options.
   316      */
   317     protected Options options;
   319     protected Context context;
   321     /**
   322      * Flag set if any annotation processing occurred.
   323      **/
   324     protected boolean annotationProcessingOccurred;
   326     /**
   327      * Flag set if any implicit source files read.
   328      **/
   329     protected boolean implicitSourceFilesRead;
   331     protected CompileStates compileStates;
   333     /** Construct a new compiler using a shared context.
   334      */
   335     public JavaCompiler(Context context) {
   336         this.context = context;
   337         context.put(compilerKey, this);
   339         // if fileManager not already set, register the JavacFileManager to be used
   340         if (context.get(JavaFileManager.class) == null)
   341             JavacFileManager.preRegister(context);
   343         names = Names.instance(context);
   344         log = Log.instance(context);
   345         diagFactory = JCDiagnostic.Factory.instance(context);
   346         reader = ClassReader.instance(context);
   347         make = TreeMaker.instance(context);
   348         writer = ClassWriter.instance(context);
   349         jniWriter = JNIWriter.instance(context);
   350         enter = Enter.instance(context);
   351         todo = Todo.instance(context);
   353         fileManager = context.get(JavaFileManager.class);
   354         parserFactory = ParserFactory.instance(context);
   355         compileStates = CompileStates.instance(context);
   357         try {
   358             // catch completion problems with predefineds
   359             syms = Symtab.instance(context);
   360         } catch (CompletionFailure ex) {
   361             // inlined Check.completionError as it is not initialized yet
   362             log.error("cant.access", ex.sym, ex.getDetailValue());
   363             if (ex instanceof ClassReader.BadClassFile)
   364                 throw new Abort();
   365         }
   366         source = Source.instance(context);
   367         attr = Attr.instance(context);
   368         chk = Check.instance(context);
   369         gen = Gen.instance(context);
   370         flow = Flow.instance(context);
   371         transTypes = TransTypes.instance(context);
   372         lower = Lower.instance(context);
   373         annotate = Annotate.instance(context);
   374         types = Types.instance(context);
   375         taskListener = MultiTaskListener.instance(context);
   377         reader.sourceCompleter = this;
   379         options = Options.instance(context);
   381         lambdaToMethod = LambdaToMethod.instance(context);
   383         verbose       = options.isSet(VERBOSE);
   384         sourceOutput  = options.isSet(PRINTSOURCE); // used to be -s
   385         stubOutput    = options.isSet("-stubs");
   386         relax         = options.isSet("-relax");
   387         printFlat     = options.isSet("-printflat");
   388         attrParseOnly = options.isSet("-attrparseonly");
   389         encoding      = options.get(ENCODING);
   390         lineDebugInfo = options.isUnset(G_CUSTOM) ||
   391                         options.isSet(G_CUSTOM, "lines");
   392         genEndPos     = options.isSet(XJCOV) ||
   393                         context.get(DiagnosticListener.class) != null;
   394         devVerbose    = options.isSet("dev");
   395         processPcks   = options.isSet("process.packages");
   396         werror        = options.isSet(WERROR);
   398         if (source.compareTo(Source.DEFAULT) < 0) {
   399             if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
   400                 if (fileManager instanceof BaseFileManager) {
   401                     if (((BaseFileManager) fileManager).isDefaultBootClassPath())
   402                         log.warning(LintCategory.OPTIONS, "source.no.bootclasspath", source.name);
   403                 }
   404             }
   405         }
   407         verboseCompilePolicy = options.isSet("verboseCompilePolicy");
   409         if (attrParseOnly)
   410             compilePolicy = CompilePolicy.ATTR_ONLY;
   411         else
   412             compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
   414         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
   416         completionFailureName =
   417             options.isSet("failcomplete")
   418             ? names.fromString(options.get("failcomplete"))
   419             : null;
   421         shouldStopPolicyIfError =
   422             options.isSet("shouldStopPolicy") // backwards compatible
   423             ? CompileState.valueOf(options.get("shouldStopPolicy"))
   424             : options.isSet("shouldStopPolicyIfError")
   425             ? CompileState.valueOf(options.get("shouldStopPolicyIfError"))
   426             : CompileState.INIT;
   427         shouldStopPolicyIfNoError =
   428             options.isSet("shouldStopPolicyIfNoError")
   429             ? CompileState.valueOf(options.get("shouldStopPolicyIfNoError"))
   430             : CompileState.GENERATE;
   432         if (options.isUnset("oldDiags"))
   433             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
   434     }
   436     /* Switches:
   437      */
   439     /** Verbose output.
   440      */
   441     public boolean verbose;
   443     /** Emit plain Java source files rather than class files.
   444      */
   445     public boolean sourceOutput;
   447     /** Emit stub source files rather than class files.
   448      */
   449     public boolean stubOutput;
   451     /** Generate attributed parse tree only.
   452      */
   453     public boolean attrParseOnly;
   455     /** Switch: relax some constraints for producing the jsr14 prototype.
   456      */
   457     boolean relax;
   459     /** Debug switch: Emit Java sources after inner class flattening.
   460      */
   461     public boolean printFlat;
   463     /** The encoding to be used for source input.
   464      */
   465     public String encoding;
   467     /** Generate code with the LineNumberTable attribute for debugging
   468      */
   469     public boolean lineDebugInfo;
   471     /** Switch: should we store the ending positions?
   472      */
   473     public boolean genEndPos;
   475     /** Switch: should we debug ignored exceptions
   476      */
   477     protected boolean devVerbose;
   479     /** Switch: should we (annotation) process packages as well
   480      */
   481     protected boolean processPcks;
   483     /** Switch: treat warnings as errors
   484      */
   485     protected boolean werror;
   487     /** Switch: is annotation processing requested explitly via
   488      * CompilationTask.setProcessors?
   489      */
   490     protected boolean explicitAnnotationProcessingRequested = false;
   492     /**
   493      * The policy for the order in which to perform the compilation
   494      */
   495     protected CompilePolicy compilePolicy;
   497     /**
   498      * The policy for what to do with implicitly read source files
   499      */
   500     protected ImplicitSourcePolicy implicitSourcePolicy;
   502     /**
   503      * Report activity related to compilePolicy
   504      */
   505     public boolean verboseCompilePolicy;
   507     /**
   508      * Policy of how far to continue compilation after errors have occurred.
   509      * Set this to minimum CompileState (INIT) to stop as soon as possible
   510      * after errors.
   511      */
   512     public CompileState shouldStopPolicyIfError;
   514     /**
   515      * Policy of how far to continue compilation when no errors have occurred.
   516      * Set this to maximum CompileState (GENERATE) to perform full compilation.
   517      * Set this lower to perform partial compilation, such as -proc:only.
   518      */
   519     public CompileState shouldStopPolicyIfNoError;
   521     /** A queue of all as yet unattributed classes.
   522      */
   523     public Todo todo;
   525     /** A list of items to be closed when the compilation is complete.
   526      */
   527     public List<Closeable> closeables = List.nil();
   529     /** The set of currently compiled inputfiles, needed to ensure
   530      *  we don't accidentally overwrite an input file when -s is set.
   531      *  initialized by `compile'.
   532      */
   533     protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
   535     protected boolean shouldStop(CompileState cs) {
   536         CompileState shouldStopPolicy = (errorCount() > 0 || unrecoverableError())
   537             ? shouldStopPolicyIfError
   538             : shouldStopPolicyIfNoError;
   539         return cs.isAfter(shouldStopPolicy);
   540     }
   542     /** The number of errors reported so far.
   543      */
   544     public int errorCount() {
   545         if (delegateCompiler != null && delegateCompiler != this)
   546             return delegateCompiler.errorCount();
   547         else {
   548             if (werror && log.nerrors == 0 && log.nwarnings > 0) {
   549                 log.error("warnings.and.werror");
   550             }
   551         }
   552         return log.nerrors;
   553     }
   555     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
   556         return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
   557     }
   559     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
   560         return shouldStop(cs) ? List.<T>nil() : list;
   561     }
   563     /** The number of warnings reported so far.
   564      */
   565     public int warningCount() {
   566         if (delegateCompiler != null && delegateCompiler != this)
   567             return delegateCompiler.warningCount();
   568         else
   569             return log.nwarnings;
   570     }
   572     /** Try to open input stream with given name.
   573      *  Report an error if this fails.
   574      *  @param filename   The file name of the input stream to be opened.
   575      */
   576     public CharSequence readSource(JavaFileObject filename) {
   577         try {
   578             inputFiles.add(filename);
   579             return filename.getCharContent(false);
   580         } catch (IOException e) {
   581             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   582             return null;
   583         }
   584     }
   586     /** Parse contents of input stream.
   587      *  @param filename     The name of the file from which input stream comes.
   588      *  @param content      The characters to be parsed.
   589      */
   590     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
   591         long msec = now();
   592         JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
   593                                       null, List.<JCTree>nil());
   594         if (content != null) {
   595             if (verbose) {
   596                 log.printVerbose("parsing.started", filename);
   597             }
   598             if (!taskListener.isEmpty()) {
   599                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
   600                 taskListener.started(e);
   601                 keepComments = true;
   602                 genEndPos = true;
   603             }
   604             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
   605             tree = parser.parseCompilationUnit();
   606             if (verbose) {
   607                 log.printVerbose("parsing.done", Long.toString(elapsed(msec)));
   608             }
   609         }
   611         tree.sourcefile = filename;
   613         if (content != null && !taskListener.isEmpty()) {
   614             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
   615             taskListener.finished(e);
   616         }
   618         return tree;
   619     }
   620     // where
   621         public boolean keepComments = false;
   622         protected boolean keepComments() {
   623             return keepComments || sourceOutput || stubOutput;
   624         }
   627     /** Parse contents of file.
   628      *  @param filename     The name of the file to be parsed.
   629      */
   630     @Deprecated
   631     public JCTree.JCCompilationUnit parse(String filename) {
   632         JavacFileManager fm = (JavacFileManager)fileManager;
   633         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
   634     }
   636     /** Parse contents of file.
   637      *  @param filename     The name of the file to be parsed.
   638      */
   639     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
   640         JavaFileObject prev = log.useSource(filename);
   641         try {
   642             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
   643             if (t.endPositions != null)
   644                 log.setEndPosTable(filename, t.endPositions);
   645             return t;
   646         } finally {
   647             log.useSource(prev);
   648         }
   649     }
   651     /** Resolve an identifier which may be the binary name of a class or
   652      * the Java name of a class or package.
   653      * @param name      The name to resolve
   654      */
   655     public Symbol resolveBinaryNameOrIdent(String name) {
   656         try {
   657             Name flatname = names.fromString(name.replace("/", "."));
   658             return reader.loadClass(flatname);
   659         } catch (CompletionFailure ignore) {
   660             return resolveIdent(name);
   661         }
   662     }
   664     /** Resolve an identifier.
   665      * @param name      The identifier to resolve
   666      */
   667     public Symbol resolveIdent(String name) {
   668         if (name.equals(""))
   669             return syms.errSymbol;
   670         JavaFileObject prev = log.useSource(null);
   671         try {
   672             JCExpression tree = null;
   673             for (String s : name.split("\\.", -1)) {
   674                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
   675                     return syms.errSymbol;
   676                 tree = (tree == null) ? make.Ident(names.fromString(s))
   677                                       : make.Select(tree, names.fromString(s));
   678             }
   679             JCCompilationUnit toplevel =
   680                 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   681             toplevel.packge = syms.unnamedPackage;
   682             return attr.attribIdent(tree, toplevel);
   683         } finally {
   684             log.useSource(prev);
   685         }
   686     }
   688     /** Emit plain Java source for a class.
   689      *  @param env    The attribution environment of the outermost class
   690      *                containing this class.
   691      *  @param cdef   The class definition to be printed.
   692      */
   693     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   694         JavaFileObject outFile
   695             = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
   696                                                cdef.sym.flatname.toString(),
   697                                                JavaFileObject.Kind.SOURCE,
   698                                                null);
   699         if (inputFiles.contains(outFile)) {
   700             log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
   701             return null;
   702         } else {
   703             BufferedWriter out = new BufferedWriter(outFile.openWriter());
   704             try {
   705                 new Pretty(out, true).printUnit(env.toplevel, cdef);
   706                 if (verbose)
   707                     log.printVerbose("wrote.file", outFile);
   708             } finally {
   709                 out.close();
   710             }
   711             return outFile;
   712         }
   713     }
   715     /** Generate code and emit a class file for a given class
   716      *  @param env    The attribution environment of the outermost class
   717      *                containing this class.
   718      *  @param cdef   The class definition from which code is generated.
   719      */
   720     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
   721         try {
   722             if (gen.genClass(env, cdef) && (errorCount() == 0))
   723                 return writer.writeClass(cdef.sym);
   724         } catch (ClassWriter.PoolOverflow ex) {
   725             log.error(cdef.pos(), "limit.pool");
   726         } catch (ClassWriter.StringOverflow ex) {
   727             log.error(cdef.pos(), "limit.string.overflow",
   728                       ex.value.substring(0, 20));
   729         } catch (CompletionFailure ex) {
   730             chk.completionError(cdef.pos(), ex);
   731         }
   732         return null;
   733     }
   735     /** Complete compiling a source file that has been accessed
   736      *  by the class file reader.
   737      *  @param c          The class the source file of which needs to be compiled.
   738      */
   739     public void complete(ClassSymbol c) throws CompletionFailure {
   740 //      System.err.println("completing " + c);//DEBUG
   741         if (completionFailureName == c.fullname) {
   742             throw new CompletionFailure(c, "user-selected completion failure by class name");
   743         }
   744         JCCompilationUnit tree;
   745         JavaFileObject filename = c.classfile;
   746         JavaFileObject prev = log.useSource(filename);
   748         try {
   749             tree = parse(filename, filename.getCharContent(false));
   750         } catch (IOException e) {
   751             log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
   752             tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
   753         } finally {
   754             log.useSource(prev);
   755         }
   757         if (!taskListener.isEmpty()) {
   758             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   759             taskListener.started(e);
   760         }
   762         enter.complete(List.of(tree), c);
   764         if (!taskListener.isEmpty()) {
   765             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
   766             taskListener.finished(e);
   767         }
   769         if (enter.getEnv(c) == null) {
   770             boolean isPkgInfo =
   771                 tree.sourcefile.isNameCompatible("package-info",
   772                                                  JavaFileObject.Kind.SOURCE);
   773             if (isPkgInfo) {
   774                 if (enter.getEnv(tree.packge) == null) {
   775                     JCDiagnostic diag =
   776                         diagFactory.fragment("file.does.not.contain.package",
   777                                                  c.location());
   778                     throw reader.new BadClassFile(c, filename, diag);
   779                 }
   780             } else {
   781                 JCDiagnostic diag =
   782                         diagFactory.fragment("file.doesnt.contain.class",
   783                                             c.getQualifiedName());
   784                 throw reader.new BadClassFile(c, filename, diag);
   785             }
   786         }
   788         implicitSourceFilesRead = true;
   789     }
   791     /** Track when the JavaCompiler has been used to compile something. */
   792     private boolean hasBeenUsed = false;
   793     private long start_msec = 0;
   794     public long elapsed_msec = 0;
   796     public void compile(List<JavaFileObject> sourceFileObject)
   797         throws Throwable {
   798         compile(sourceFileObject, List.<String>nil(), null);
   799     }
   801     /**
   802      * Main method: compile a list of files, return all compiled classes
   803      *
   804      * @param sourceFileObjects file objects to be compiled
   805      * @param classnames class names to process for annotations
   806      * @param processors user provided annotation processors to bypass
   807      * discovery, {@code null} means that no processors were provided
   808      */
   809     public void compile(List<JavaFileObject> sourceFileObjects,
   810                         List<String> classnames,
   811                         Iterable<? extends Processor> processors)
   812     {
   813         if (processors != null && processors.iterator().hasNext())
   814             explicitAnnotationProcessingRequested = true;
   815         // as a JavaCompiler can only be used once, throw an exception if
   816         // it has been used before.
   817         if (hasBeenUsed)
   818             throw new AssertionError("attempt to reuse JavaCompiler");
   819         hasBeenUsed = true;
   821         // forcibly set the equivalent of -Xlint:-options, so that no further
   822         // warnings about command line options are generated from this point on
   823         options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
   824         options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);
   826         start_msec = now();
   828         try {
   829             initProcessAnnotations(processors);
   831             // These method calls must be chained to avoid memory leaks
   832             delegateCompiler =
   833                 processAnnotations(
   834                     enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
   835                     classnames);
   837             delegateCompiler.compile2();
   838             delegateCompiler.close();
   839             elapsed_msec = delegateCompiler.elapsed_msec;
   840         } catch (Abort ex) {
   841             if (devVerbose)
   842                 ex.printStackTrace(System.err);
   843         } finally {
   844             if (procEnvImpl != null)
   845                 procEnvImpl.close();
   846         }
   847     }
   849     /**
   850      * The phases following annotation processing: attribution,
   851      * desugar, and finally code generation.
   852      */
   853     private void compile2() {
   854         try {
   855             switch (compilePolicy) {
   856             case ATTR_ONLY:
   857                 attribute(todo);
   858                 break;
   860             case CHECK_ONLY:
   861                 flow(attribute(todo));
   862                 break;
   864             case SIMPLE:
   865                 generate(desugar(flow(attribute(todo))));
   866                 break;
   868             case BY_FILE: {
   869                     Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
   870                     while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
   871                         generate(desugar(flow(attribute(q.remove()))));
   872                     }
   873                 }
   874                 break;
   876             case BY_TODO:
   877                 while (!todo.isEmpty())
   878                     generate(desugar(flow(attribute(todo.remove()))));
   879                 break;
   881             default:
   882                 Assert.error("unknown compile policy");
   883             }
   884         } catch (Abort ex) {
   885             if (devVerbose)
   886                 ex.printStackTrace(System.err);
   887         }
   889         if (verbose) {
   890             elapsed_msec = elapsed(start_msec);
   891             log.printVerbose("total", Long.toString(elapsed_msec));
   892         }
   894         reportDeferredDiagnostics();
   896         if (!log.hasDiagnosticListener()) {
   897             printCount("error", errorCount());
   898             printCount("warn", warningCount());
   899         }
   900     }
   902     /**
   903      * Set needRootClasses to true, in JavaCompiler subclass constructor
   904      * that want to collect public apis of classes supplied on the command line.
   905      */
   906     protected boolean needRootClasses = false;
   908     /**
   909      * The list of classes explicitly supplied on the command line for compilation.
   910      * Not always populated.
   911      */
   912     private List<JCClassDecl> rootClasses;
   914     /**
   915      * Parses a list of files.
   916      */
   917    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
   918        if (shouldStop(CompileState.PARSE))
   919            return List.nil();
   921         //parse all files
   922         ListBuffer<JCCompilationUnit> trees = lb();
   923         Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
   924         for (JavaFileObject fileObject : fileObjects) {
   925             if (!filesSoFar.contains(fileObject)) {
   926                 filesSoFar.add(fileObject);
   927                 trees.append(parse(fileObject));
   928             }
   929         }
   930         return trees.toList();
   931     }
   933     /**
   934      * Enter the symbols found in a list of parse trees if the compilation
   935      * is expected to proceed beyond anno processing into attr.
   936      * As a side-effect, this puts elements on the "todo" list.
   937      * Also stores a list of all top level classes in rootClasses.
   938      */
   939     public List<JCCompilationUnit> enterTreesIfNeeded(List<JCCompilationUnit> roots) {
   940        if (shouldStop(CompileState.ATTR))
   941            return List.nil();
   942         return enterTrees(roots);
   943     }
   945     /**
   946      * Enter the symbols found in a list of parse trees.
   947      * As a side-effect, this puts elements on the "todo" list.
   948      * Also stores a list of all top level classes in rootClasses.
   949      */
   950     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
   951         //enter symbols for all files
   952         if (!taskListener.isEmpty()) {
   953             for (JCCompilationUnit unit: roots) {
   954                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   955                 taskListener.started(e);
   956             }
   957         }
   959         enter.main(roots);
   961         if (!taskListener.isEmpty()) {
   962             for (JCCompilationUnit unit: roots) {
   963                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
   964                 taskListener.finished(e);
   965             }
   966         }
   968         // If generating source, or if tracking public apis,
   969         // then remember the classes declared in
   970         // the original compilation units listed on the command line.
   971         if (needRootClasses || sourceOutput || stubOutput) {
   972             ListBuffer<JCClassDecl> cdefs = lb();
   973             for (JCCompilationUnit unit : roots) {
   974                 for (List<JCTree> defs = unit.defs;
   975                      defs.nonEmpty();
   976                      defs = defs.tail) {
   977                     if (defs.head instanceof JCClassDecl)
   978                         cdefs.append((JCClassDecl)defs.head);
   979                 }
   980             }
   981             rootClasses = cdefs.toList();
   982         }
   984         // Ensure the input files have been recorded. Although this is normally
   985         // done by readSource, it may not have been done if the trees were read
   986         // in a prior round of annotation processing, and the trees have been
   987         // cleaned and are being reused.
   988         for (JCCompilationUnit unit : roots) {
   989             inputFiles.add(unit.sourcefile);
   990         }
   992         return roots;
   993     }
   995     /**
   996      * Set to true to enable skeleton annotation processing code.
   997      * Currently, we assume this variable will be replaced more
   998      * advanced logic to figure out if annotation processing is
   999      * needed.
  1000      */
  1001     boolean processAnnotations = false;
  1003     Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
  1005     /**
  1006      * Object to handle annotation processing.
  1007      */
  1008     private JavacProcessingEnvironment procEnvImpl = null;
  1010     /**
  1011      * Check if we should process annotations.
  1012      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
  1013      * to catch doc comments, and set keepComments so the parser records them in
  1014      * the compilation unit.
  1016      * @param processors user provided annotation processors to bypass
  1017      * discovery, {@code null} means that no processors were provided
  1018      */
  1019     public void initProcessAnnotations(Iterable<? extends Processor> processors) {
  1020         // Process annotations if processing is not disabled and there
  1021         // is at least one Processor available.
  1022         if (options.isSet(PROC, "none")) {
  1023             processAnnotations = false;
  1024         } else if (procEnvImpl == null) {
  1025             procEnvImpl = JavacProcessingEnvironment.instance(context);
  1026             procEnvImpl.setProcessors(processors);
  1027             processAnnotations = procEnvImpl.atLeastOneProcessor();
  1029             if (processAnnotations) {
  1030                 options.put("save-parameter-names", "save-parameter-names");
  1031                 reader.saveParameterNames = true;
  1032                 keepComments = true;
  1033                 genEndPos = true;
  1034                 if (!taskListener.isEmpty())
  1035                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1036                 deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
  1037             } else { // free resources
  1038                 procEnvImpl.close();
  1043     // TODO: called by JavacTaskImpl
  1044     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
  1045         return processAnnotations(roots, List.<String>nil());
  1048     /**
  1049      * Process any annotations found in the specified compilation units.
  1050      * @param roots a list of compilation units
  1051      * @return an instance of the compiler in which to complete the compilation
  1052      */
  1053     // Implementation note: when this method is called, log.deferredDiagnostics
  1054     // will have been set true by initProcessAnnotations, meaning that any diagnostics
  1055     // that are reported will go into the log.deferredDiagnostics queue.
  1056     // By the time this method exits, log.deferDiagnostics must be set back to false,
  1057     // and all deferredDiagnostics must have been handled: i.e. either reported
  1058     // or determined to be transient, and therefore suppressed.
  1059     public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
  1060                                            List<String> classnames) {
  1061         if (shouldStop(CompileState.PROCESS)) {
  1062             // Errors were encountered.
  1063             // Unless all the errors are resolve errors, the errors were parse errors
  1064             // or other errors during enter which cannot be fixed by running
  1065             // any annotation processors.
  1066             if (unrecoverableError()) {
  1067                 deferredDiagnosticHandler.reportDeferredDiagnostics();
  1068                 log.popDiagnosticHandler(deferredDiagnosticHandler);
  1069                 return this;
  1073         // ASSERT: processAnnotations and procEnvImpl should have been set up by
  1074         // by initProcessAnnotations
  1076         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
  1078         if (!processAnnotations) {
  1079             // If there are no annotation processors present, and
  1080             // annotation processing is to occur with compilation,
  1081             // emit a warning.
  1082             if (options.isSet(PROC, "only")) {
  1083                 log.warning("proc.proc-only.requested.no.procs");
  1084                 todo.clear();
  1086             // If not processing annotations, classnames must be empty
  1087             if (!classnames.isEmpty()) {
  1088                 log.error("proc.no.explicit.annotation.processing.requested",
  1089                           classnames);
  1091             Assert.checkNull(deferredDiagnosticHandler);
  1092             return this; // continue regular compilation
  1095         Assert.checkNonNull(deferredDiagnosticHandler);
  1097         try {
  1098             List<ClassSymbol> classSymbols = List.nil();
  1099             List<PackageSymbol> pckSymbols = List.nil();
  1100             if (!classnames.isEmpty()) {
  1101                  // Check for explicit request for annotation
  1102                  // processing
  1103                 if (!explicitAnnotationProcessingRequested()) {
  1104                     log.error("proc.no.explicit.annotation.processing.requested",
  1105                               classnames);
  1106                     deferredDiagnosticHandler.reportDeferredDiagnostics();
  1107                     log.popDiagnosticHandler(deferredDiagnosticHandler);
  1108                     return this; // TODO: Will this halt compilation?
  1109                 } else {
  1110                     boolean errors = false;
  1111                     for (String nameStr : classnames) {
  1112                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
  1113                         if (sym == null ||
  1114                             (sym.kind == Kinds.PCK && !processPcks) ||
  1115                             sym.kind == Kinds.ABSENT_TYP) {
  1116                             log.error("proc.cant.find.class", nameStr);
  1117                             errors = true;
  1118                             continue;
  1120                         try {
  1121                             if (sym.kind == Kinds.PCK)
  1122                                 sym.complete();
  1123                             if (sym.exists()) {
  1124                                 if (sym.kind == Kinds.PCK)
  1125                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1126                                 else
  1127                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
  1128                                 continue;
  1130                             Assert.check(sym.kind == Kinds.PCK);
  1131                             log.warning("proc.package.does.not.exist", nameStr);
  1132                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
  1133                         } catch (CompletionFailure e) {
  1134                             log.error("proc.cant.find.class", nameStr);
  1135                             errors = true;
  1136                             continue;
  1139                     if (errors) {
  1140                         deferredDiagnosticHandler.reportDeferredDiagnostics();
  1141                         log.popDiagnosticHandler(deferredDiagnosticHandler);
  1142                         return this;
  1146             try {
  1147                 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols,
  1148                         deferredDiagnosticHandler);
  1149                 if (c != this)
  1150                     annotationProcessingOccurred = c.annotationProcessingOccurred = true;
  1151                 // doProcessing will have handled deferred diagnostics
  1152                 return c;
  1153             } finally {
  1154                 procEnvImpl.close();
  1156         } catch (CompletionFailure ex) {
  1157             log.error("cant.access", ex.sym, ex.getDetailValue());
  1158             deferredDiagnosticHandler.reportDeferredDiagnostics();
  1159             log.popDiagnosticHandler(deferredDiagnosticHandler);
  1160             return this;
  1164     private boolean unrecoverableError() {
  1165         if (deferredDiagnosticHandler != null) {
  1166             for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
  1167                 if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
  1168                     return true;
  1171         return false;
  1174     boolean explicitAnnotationProcessingRequested() {
  1175         return
  1176             explicitAnnotationProcessingRequested ||
  1177             explicitAnnotationProcessingRequested(options);
  1180     static boolean explicitAnnotationProcessingRequested(Options options) {
  1181         return
  1182             options.isSet(PROCESSOR) ||
  1183             options.isSet(PROCESSORPATH) ||
  1184             options.isSet(PROC, "only") ||
  1185             options.isSet(XPRINT);
  1188     /**
  1189      * Attribute a list of parse trees, such as found on the "todo" list.
  1190      * Note that attributing classes may cause additional files to be
  1191      * parsed and entered via the SourceCompleter.
  1192      * Attribution of the entries in the list does not stop if any errors occur.
  1193      * @returns a list of environments for attributd classes.
  1194      */
  1195     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
  1196         ListBuffer<Env<AttrContext>> results = lb();
  1197         while (!envs.isEmpty())
  1198             results.append(attribute(envs.remove()));
  1199         return stopIfError(CompileState.ATTR, results);
  1202     /**
  1203      * Attribute a parse tree.
  1204      * @returns the attributed parse tree
  1205      */
  1206     public Env<AttrContext> attribute(Env<AttrContext> env) {
  1207         if (compileStates.isDone(env, CompileState.ATTR))
  1208             return env;
  1210         if (verboseCompilePolicy)
  1211             printNote("[attribute " + env.enclClass.sym + "]");
  1212         if (verbose)
  1213             log.printVerbose("checking.attribution", env.enclClass.sym);
  1215         if (!taskListener.isEmpty()) {
  1216             TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1217             taskListener.started(e);
  1220         JavaFileObject prev = log.useSource(
  1221                                   env.enclClass.sym.sourcefile != null ?
  1222                                   env.enclClass.sym.sourcefile :
  1223                                   env.toplevel.sourcefile);
  1224         try {
  1225             attr.attrib(env);
  1226             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
  1227                 //if in fail-over mode, ensure that AST expression nodes
  1228                 //are correctly initialized (e.g. they have a type/symbol)
  1229                 attr.postAttr(env.tree);
  1231             compileStates.put(env, CompileState.ATTR);
  1232             if (rootClasses != null && rootClasses.contains(env.enclClass)) {
  1233                 // This was a class that was explicitly supplied for compilation.
  1234                 // If we want to capture the public api of this class,
  1235                 // then now is a good time to do it.
  1236                 reportPublicApi(env.enclClass.sym);
  1239         finally {
  1240             log.useSource(prev);
  1243         return env;
  1246     /** Report the public api of a class that was supplied explicitly for compilation,
  1247      *  for example on the command line to javac.
  1248      * @param sym The symbol of the class.
  1249      */
  1250     public void reportPublicApi(ClassSymbol sym) {
  1251        // Override to collect the reported public api.
  1254     /**
  1255      * Perform dataflow checks on attributed parse trees.
  1256      * These include checks for definite assignment and unreachable statements.
  1257      * If any errors occur, an empty list will be returned.
  1258      * @returns the list of attributed parse trees
  1259      */
  1260     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
  1261         ListBuffer<Env<AttrContext>> results = lb();
  1262         for (Env<AttrContext> env: envs) {
  1263             flow(env, results);
  1265         return stopIfError(CompileState.FLOW, results);
  1268     /**
  1269      * Perform dataflow checks on an attributed parse tree.
  1270      */
  1271     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
  1272         ListBuffer<Env<AttrContext>> results = lb();
  1273         flow(env, results);
  1274         return stopIfError(CompileState.FLOW, results);
  1277     /**
  1278      * Perform dataflow checks on an attributed parse tree.
  1279      */
  1280     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
  1281         try {
  1282             if (shouldStop(CompileState.FLOW))
  1283                 return;
  1285             if (relax || compileStates.isDone(env, CompileState.FLOW)) {
  1286                 results.add(env);
  1287                 return;
  1290             if (verboseCompilePolicy)
  1291                 printNote("[flow " + env.enclClass.sym + "]");
  1292             JavaFileObject prev = log.useSource(
  1293                                                 env.enclClass.sym.sourcefile != null ?
  1294                                                 env.enclClass.sym.sourcefile :
  1295                                                 env.toplevel.sourcefile);
  1296             try {
  1297                 make.at(Position.FIRSTPOS);
  1298                 TreeMaker localMake = make.forToplevel(env.toplevel);
  1299                 flow.analyzeTree(env, localMake);
  1300                 compileStates.put(env, CompileState.FLOW);
  1302                 if (shouldStop(CompileState.FLOW))
  1303                     return;
  1305                 results.add(env);
  1307             finally {
  1308                 log.useSource(prev);
  1311         finally {
  1312             if (!taskListener.isEmpty()) {
  1313                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
  1314                 taskListener.finished(e);
  1319     /**
  1320      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1321      * for source or code generation.
  1322      * If any errors occur, an empty list will be returned.
  1323      * @returns a list containing the classes to be generated
  1324      */
  1325     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
  1326         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
  1327         for (Env<AttrContext> env: envs)
  1328             desugar(env, results);
  1329         return stopIfError(CompileState.FLOW, results);
  1332     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
  1333             new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
  1335     /**
  1336      * Prepare attributed parse trees, in conjunction with their attribution contexts,
  1337      * for source or code generation. If the file was not listed on the command line,
  1338      * the current implicitSourcePolicy is taken into account.
  1339      * The preparation stops as soon as an error is found.
  1340      */
  1341     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
  1342         if (shouldStop(CompileState.TRANSTYPES))
  1343             return;
  1345         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
  1346                 && !inputFiles.contains(env.toplevel.sourcefile)) {
  1347             return;
  1350         if (compileStates.isDone(env, CompileState.LOWER)) {
  1351             results.addAll(desugaredEnvs.get(env));
  1352             return;
  1355         /**
  1356          * Ensure that superclasses of C are desugared before C itself. This is
  1357          * required for two reasons: (i) as erasure (TransTypes) destroys
  1358          * information needed in flow analysis and (ii) as some checks carried
  1359          * out during lowering require that all synthetic fields/methods have
  1360          * already been added to C and its superclasses.
  1361          */
  1362         class ScanNested extends TreeScanner {
  1363             Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
  1364             @Override
  1365             public void visitClassDef(JCClassDecl node) {
  1366                 Type st = types.supertype(node.sym.type);
  1367                 boolean envForSuperTypeFound = false;
  1368                 while (!envForSuperTypeFound && st.hasTag(CLASS)) {
  1369                     ClassSymbol c = st.tsym.outermostClass();
  1370                     Env<AttrContext> stEnv = enter.getEnv(c);
  1371                     if (stEnv != null && env != stEnv) {
  1372                         if (dependencies.add(stEnv)) {
  1373                             scan(stEnv.tree);
  1375                         envForSuperTypeFound = true;
  1377                     st = types.supertype(st);
  1379                 super.visitClassDef(node);
  1382         ScanNested scanner = new ScanNested();
  1383         scanner.scan(env.tree);
  1384         for (Env<AttrContext> dep: scanner.dependencies) {
  1385         if (!compileStates.isDone(dep, CompileState.FLOW))
  1386             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
  1389         //We need to check for error another time as more classes might
  1390         //have been attributed and analyzed at this stage
  1391         if (shouldStop(CompileState.TRANSTYPES))
  1392             return;
  1394         if (verboseCompilePolicy)
  1395             printNote("[desugar " + env.enclClass.sym + "]");
  1397         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1398                                   env.enclClass.sym.sourcefile :
  1399                                   env.toplevel.sourcefile);
  1400         try {
  1401             //save tree prior to rewriting
  1402             JCTree untranslated = env.tree;
  1404             make.at(Position.FIRSTPOS);
  1405             TreeMaker localMake = make.forToplevel(env.toplevel);
  1407             if (env.tree instanceof JCCompilationUnit) {
  1408                 if (!(stubOutput || sourceOutput || printFlat)) {
  1409                     if (shouldStop(CompileState.LOWER))
  1410                         return;
  1411                     List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
  1412                     if (pdef.head != null) {
  1413                         Assert.check(pdef.tail.isEmpty());
  1414                         results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
  1417                 return;
  1420             if (stubOutput) {
  1421                 //emit stub Java source file, only for compilation
  1422                 //units enumerated explicitly on the command line
  1423                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1424                 if (untranslated instanceof JCClassDecl &&
  1425                     rootClasses.contains((JCClassDecl)untranslated) &&
  1426                     ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1427                      cdef.sym.packge().getQualifiedName() == names.java_lang)) {
  1428                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
  1430                 return;
  1433             if (shouldStop(CompileState.TRANSTYPES))
  1434                 return;
  1436             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
  1437             compileStates.put(env, CompileState.TRANSTYPES);
  1439             if (shouldStop(CompileState.UNLAMBDA))
  1440                 return;
  1442             env.tree = lambdaToMethod.translateTopLevelClass(env, env.tree, localMake);
  1443             compileStates.put(env, CompileState.UNLAMBDA);
  1445             if (shouldStop(CompileState.LOWER))
  1446                 return;
  1448             if (sourceOutput) {
  1449                 //emit standard Java source file, only for compilation
  1450                 //units enumerated explicitly on the command line
  1451                 JCClassDecl cdef = (JCClassDecl)env.tree;
  1452                 if (untranslated instanceof JCClassDecl &&
  1453                     rootClasses.contains((JCClassDecl)untranslated)) {
  1454                     results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1456                 return;
  1459             //translate out inner classes
  1460             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
  1461             compileStates.put(env, CompileState.LOWER);
  1463             if (shouldStop(CompileState.LOWER))
  1464                 return;
  1466             //generate code for each class
  1467             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
  1468                 JCClassDecl cdef = (JCClassDecl)l.head;
  1469                 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
  1472         finally {
  1473             log.useSource(prev);
  1478     /** Generates the source or class file for a list of classes.
  1479      * The decision to generate a source file or a class file is
  1480      * based upon the compiler's options.
  1481      * Generation stops if an error occurs while writing files.
  1482      */
  1483     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
  1484         generate(queue, null);
  1487     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
  1488         if (shouldStop(CompileState.GENERATE))
  1489             return;
  1491         boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
  1493         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
  1494             Env<AttrContext> env = x.fst;
  1495             JCClassDecl cdef = x.snd;
  1497             if (verboseCompilePolicy) {
  1498                 printNote("[generate "
  1499                                + (usePrintSource ? " source" : "code")
  1500                                + " " + cdef.sym + "]");
  1503             if (!taskListener.isEmpty()) {
  1504                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1505                 taskListener.started(e);
  1508             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
  1509                                       env.enclClass.sym.sourcefile :
  1510                                       env.toplevel.sourcefile);
  1511             try {
  1512                 JavaFileObject file;
  1513                 if (usePrintSource)
  1514                     file = printSource(env, cdef);
  1515                 else {
  1516                     if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
  1517                             && jniWriter.needsHeader(cdef.sym)) {
  1518                         jniWriter.write(cdef.sym);
  1520                     file = genCode(env, cdef);
  1522                 if (results != null && file != null)
  1523                     results.add(file);
  1524             } catch (IOException ex) {
  1525                 log.error(cdef.pos(), "class.cant.write",
  1526                           cdef.sym, ex.getMessage());
  1527                 return;
  1528             } finally {
  1529                 log.useSource(prev);
  1532             if (!taskListener.isEmpty()) {
  1533                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
  1534                 taskListener.finished(e);
  1539         // where
  1540         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
  1541             // use a LinkedHashMap to preserve the order of the original list as much as possible
  1542             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
  1543             for (Env<AttrContext> env: envs) {
  1544                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
  1545                 if (sublist == null) {
  1546                     sublist = new ListBuffer<Env<AttrContext>>();
  1547                     map.put(env.toplevel, sublist);
  1549                 sublist.add(env);
  1551             return map;
  1554         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
  1555             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
  1556             class MethodBodyRemover extends TreeTranslator {
  1557                 @Override
  1558                 public void visitMethodDef(JCMethodDecl tree) {
  1559                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
  1560                     for (JCVariableDecl vd : tree.params)
  1561                         vd.mods.flags &= ~Flags.FINAL;
  1562                     tree.body = null;
  1563                     super.visitMethodDef(tree);
  1565                 @Override
  1566                 public void visitVarDef(JCVariableDecl tree) {
  1567                     if (tree.init != null && tree.init.type.constValue() == null)
  1568                         tree.init = null;
  1569                     super.visitVarDef(tree);
  1571                 @Override
  1572                 public void visitClassDef(JCClassDecl tree) {
  1573                     ListBuffer<JCTree> newdefs = lb();
  1574                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
  1575                         JCTree t = it.head;
  1576                         switch (t.getTag()) {
  1577                         case CLASSDEF:
  1578                             if (isInterface ||
  1579                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1580                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1581                                 newdefs.append(t);
  1582                             break;
  1583                         case METHODDEF:
  1584                             if (isInterface ||
  1585                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1586                                 ((JCMethodDecl) t).sym.name == names.init ||
  1587                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1588                                 newdefs.append(t);
  1589                             break;
  1590                         case VARDEF:
  1591                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
  1592                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
  1593                                 newdefs.append(t);
  1594                             break;
  1595                         default:
  1596                             break;
  1599                     tree.defs = newdefs.toList();
  1600                     super.visitClassDef(tree);
  1603             MethodBodyRemover r = new MethodBodyRemover();
  1604             return r.translate(cdef);
  1607     public void reportDeferredDiagnostics() {
  1608         if (errorCount() == 0
  1609                 && annotationProcessingOccurred
  1610                 && implicitSourceFilesRead
  1611                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
  1612             if (explicitAnnotationProcessingRequested())
  1613                 log.warning("proc.use.implicit");
  1614             else
  1615                 log.warning("proc.use.proc.or.implicit");
  1617         chk.reportDeferredDiagnostics();
  1620     /** Close the compiler, flushing the logs
  1621      */
  1622     public void close() {
  1623         close(true);
  1626     public void close(boolean disposeNames) {
  1627         rootClasses = null;
  1628         reader = null;
  1629         make = null;
  1630         writer = null;
  1631         enter = null;
  1632         if (todo != null)
  1633             todo.clear();
  1634         todo = null;
  1635         parserFactory = null;
  1636         syms = null;
  1637         source = null;
  1638         attr = null;
  1639         chk = null;
  1640         gen = null;
  1641         flow = null;
  1642         transTypes = null;
  1643         lower = null;
  1644         annotate = null;
  1645         types = null;
  1647         log.flush();
  1648         try {
  1649             fileManager.flush();
  1650         } catch (IOException e) {
  1651             throw new Abort(e);
  1652         } finally {
  1653             if (names != null && disposeNames)
  1654                 names.dispose();
  1655             names = null;
  1657             for (Closeable c: closeables) {
  1658                 try {
  1659                     c.close();
  1660                 } catch (IOException e) {
  1661                     // When javac uses JDK 7 as a baseline, this code would be
  1662                     // better written to set any/all exceptions from all the
  1663                     // Closeables as suppressed exceptions on the FatalError
  1664                     // that is thrown.
  1665                     JCDiagnostic msg = diagFactory.fragment("fatal.err.cant.close");
  1666                     throw new FatalError(msg, e);
  1669             closeables = List.nil();
  1673     protected void printNote(String lines) {
  1674         log.printRawLines(Log.WriterKind.NOTICE, lines);
  1677     /** Print numbers of errors and warnings.
  1678      */
  1679     public void printCount(String kind, int count) {
  1680         if (count != 0) {
  1681             String key;
  1682             if (count == 1)
  1683                 key = "count." + kind;
  1684             else
  1685                 key = "count." + kind + ".plural";
  1686             log.printLines(WriterKind.ERROR, key, String.valueOf(count));
  1687             log.flush(Log.WriterKind.ERROR);
  1691     private static long now() {
  1692         return System.currentTimeMillis();
  1695     private static long elapsed(long then) {
  1696         return now() - then;
  1699     public void initRound(JavaCompiler prev) {
  1700         genEndPos = prev.genEndPos;
  1701         keepComments = prev.keepComments;
  1702         start_msec = prev.start_msec;
  1703         hasBeenUsed = true;
  1704         closeables = prev.closeables;
  1705         prev.closeables = List.nil();
  1706         shouldStopPolicyIfError = prev.shouldStopPolicyIfError;
  1707         shouldStopPolicyIfNoError = prev.shouldStopPolicyIfNoError;
  1710     public static void enableLogging() {
  1711         Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
  1712         logger.setLevel(Level.ALL);
  1713         for (Handler h : logger.getParent().getHandlers()) {
  1714             h.setLevel(Level.ALL);

mercurial