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