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

Tue, 13 Mar 2012 15:43:40 -0700

author
jjg
date
Tue, 13 Mar 2012 15:43:40 -0700
changeset 1230
b14d9583ce92
parent 1210
62e611704863
child 1340
99d23c0ef8ee
permissions
-rw-r--r--

7150368: javac should include basic ability to generate native headers
Reviewed-by: mcimadamore, darcy, ohrstrom

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

mercurial