JavaCompiler.java revision 3257:3cdfbbdb6f61
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        encoding      = options.get(ENCODING);
393        lineDebugInfo = options.isUnset(G_CUSTOM) ||
394                        options.isSet(G_CUSTOM, "lines");
395        genEndPos     = options.isSet(XJCOV) ||
396                        context.get(DiagnosticListener.class) != null;
397        devVerbose    = options.isSet("dev");
398        processPcks   = options.isSet("process.packages");
399        werror        = options.isSet(WERROR);
400
401        verboseCompilePolicy = options.isSet("verboseCompilePolicy");
402
403        if (options.isSet("shouldStopPolicy") &&
404            CompileState.valueOf(options.get("shouldStopPolicy")) == CompileState.ATTR)
405            compilePolicy = CompilePolicy.ATTR_ONLY;
406        else
407            compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
408
409        implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
410
411        completionFailureName =
412            options.isSet("failcomplete")
413            ? names.fromString(options.get("failcomplete"))
414            : null;
415
416        shouldStopPolicyIfError =
417            options.isSet("shouldStopPolicy") // backwards compatible
418            ? CompileState.valueOf(options.get("shouldStopPolicy"))
419            : options.isSet("shouldStopPolicyIfError")
420            ? CompileState.valueOf(options.get("shouldStopPolicyIfError"))
421            : CompileState.INIT;
422        shouldStopPolicyIfNoError =
423            options.isSet("shouldStopPolicyIfNoError")
424            ? CompileState.valueOf(options.get("shouldStopPolicyIfNoError"))
425            : CompileState.GENERATE;
426
427        if (options.isUnset("oldDiags"))
428            log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
429
430        PlatformDescription platformProvider = context.get(PlatformDescription.class);
431
432        if (platformProvider != null)
433            closeables = closeables.prepend(platformProvider);
434    }
435
436    /* Switches:
437     */
438
439    /** Verbose output.
440     */
441    public boolean verbose;
442
443    /** Emit plain Java source files rather than class files.
444     */
445    public boolean sourceOutput;
446
447    /** The encoding to be used for source input.
448     */
449    public String encoding;
450
451    /** Generate code with the LineNumberTable attribute for debugging
452     */
453    public boolean lineDebugInfo;
454
455    /** Switch: should we store the ending positions?
456     */
457    public boolean genEndPos;
458
459    /** Switch: should we debug ignored exceptions
460     */
461    protected boolean devVerbose;
462
463    /** Switch: should we (annotation) process packages as well
464     */
465    protected boolean processPcks;
466
467    /** Switch: treat warnings as errors
468     */
469    protected boolean werror;
470
471    /** Switch: is annotation processing requested explicitly via
472     * CompilationTask.setProcessors?
473     */
474    protected boolean explicitAnnotationProcessingRequested = false;
475
476    /**
477     * The policy for the order in which to perform the compilation
478     */
479    protected CompilePolicy compilePolicy;
480
481    /**
482     * The policy for what to do with implicitly read source files
483     */
484    protected ImplicitSourcePolicy implicitSourcePolicy;
485
486    /**
487     * Report activity related to compilePolicy
488     */
489    public boolean verboseCompilePolicy;
490
491    /**
492     * Policy of how far to continue compilation after errors have occurred.
493     * Set this to minimum CompileState (INIT) to stop as soon as possible
494     * after errors.
495     */
496    public CompileState shouldStopPolicyIfError;
497
498    /**
499     * Policy of how far to continue compilation when no errors have occurred.
500     * Set this to maximum CompileState (GENERATE) to perform full compilation.
501     * Set this lower to perform partial compilation, such as -proc:only.
502     */
503    public CompileState shouldStopPolicyIfNoError;
504
505    /** A queue of all as yet unattributed classes.
506     */
507    public Todo todo;
508
509    /** A list of items to be closed when the compilation is complete.
510     */
511    public List<Closeable> closeables = List.nil();
512
513    /** The set of currently compiled inputfiles, needed to ensure
514     *  we don't accidentally overwrite an input file when -s is set.
515     *  initialized by `compile'.
516     */
517    protected Set<JavaFileObject> inputFiles = new HashSet<>();
518
519    protected boolean shouldStop(CompileState cs) {
520        CompileState shouldStopPolicy = (errorCount() > 0 || unrecoverableError())
521            ? shouldStopPolicyIfError
522            : shouldStopPolicyIfNoError;
523        return cs.isAfter(shouldStopPolicy);
524    }
525
526    /** The number of errors reported so far.
527     */
528    public int errorCount() {
529        if (werror && log.nerrors == 0 && log.nwarnings > 0) {
530            log.error("warnings.and.werror");
531        }
532        return log.nerrors;
533    }
534
535    protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
536        return shouldStop(cs) ? new ListBuffer<T>() : queue;
537    }
538
539    protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
540        return shouldStop(cs) ? List.<T>nil() : list;
541    }
542
543    /** The number of warnings reported so far.
544     */
545    public int warningCount() {
546        return log.nwarnings;
547    }
548
549    /** Try to open input stream with given name.
550     *  Report an error if this fails.
551     *  @param filename   The file name of the input stream to be opened.
552     */
553    public CharSequence readSource(JavaFileObject filename) {
554        try {
555            inputFiles.add(filename);
556            return filename.getCharContent(false);
557        } catch (IOException e) {
558            log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
559            return null;
560        }
561    }
562
563    /** Parse contents of input stream.
564     *  @param filename     The name of the file from which input stream comes.
565     *  @param content      The characters to be parsed.
566     */
567    protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
568        long msec = now();
569        JCCompilationUnit tree = make.TopLevel(List.<JCTree>nil());
570        if (content != null) {
571            if (verbose) {
572                log.printVerbose("parsing.started", filename);
573            }
574            if (!taskListener.isEmpty()) {
575                TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
576                taskListener.started(e);
577                keepComments = true;
578                genEndPos = true;
579            }
580            Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
581            tree = parser.parseCompilationUnit();
582            if (verbose) {
583                log.printVerbose("parsing.done", Long.toString(elapsed(msec)));
584            }
585        }
586
587        tree.sourcefile = filename;
588
589        if (content != null && !taskListener.isEmpty()) {
590            TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
591            taskListener.finished(e);
592        }
593
594        return tree;
595    }
596    // where
597        public boolean keepComments = false;
598        protected boolean keepComments() {
599            return keepComments || sourceOutput;
600        }
601
602
603    /** Parse contents of file.
604     *  @param filename     The name of the file to be parsed.
605     */
606    @Deprecated
607    public JCTree.JCCompilationUnit parse(String filename) {
608        JavacFileManager fm = (JavacFileManager)fileManager;
609        return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
610    }
611
612    /** Parse contents of file.
613     *  @param filename     The name of the file to be parsed.
614     */
615    public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
616        JavaFileObject prev = log.useSource(filename);
617        try {
618            JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
619            if (t.endPositions != null)
620                log.setEndPosTable(filename, t.endPositions);
621            return t;
622        } finally {
623            log.useSource(prev);
624        }
625    }
626
627    /** Resolve an identifier which may be the binary name of a class or
628     * the Java name of a class or package.
629     * @param name      The name to resolve
630     */
631    public Symbol resolveBinaryNameOrIdent(String name) {
632        try {
633            Name flatname = names.fromString(name.replace("/", "."));
634            return finder.loadClass(flatname);
635        } catch (CompletionFailure ignore) {
636            return resolveIdent(name);
637        }
638    }
639
640    /** Resolve an identifier.
641     * @param name      The identifier to resolve
642     */
643    public Symbol resolveIdent(String name) {
644        if (name.equals(""))
645            return syms.errSymbol;
646        JavaFileObject prev = log.useSource(null);
647        try {
648            JCExpression tree = null;
649            for (String s : name.split("\\.", -1)) {
650                if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
651                    return syms.errSymbol;
652                tree = (tree == null) ? make.Ident(names.fromString(s))
653                                      : make.Select(tree, names.fromString(s));
654            }
655            JCCompilationUnit toplevel =
656                make.TopLevel(List.<JCTree>nil());
657            toplevel.packge = syms.unnamedPackage;
658            return attr.attribIdent(tree, toplevel);
659        } finally {
660            log.useSource(prev);
661        }
662    }
663
664    /** Generate code and emit a class file for a given class
665     *  @param env    The attribution environment of the outermost class
666     *                containing this class.
667     *  @param cdef   The class definition from which code is generated.
668     */
669    JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
670        try {
671            if (gen.genClass(env, cdef) && (errorCount() == 0))
672                return writer.writeClass(cdef.sym);
673        } catch (ClassWriter.PoolOverflow ex) {
674            log.error(cdef.pos(), "limit.pool");
675        } catch (ClassWriter.StringOverflow ex) {
676            log.error(cdef.pos(), "limit.string.overflow",
677                      ex.value.substring(0, 20));
678        } catch (CompletionFailure ex) {
679            chk.completionError(cdef.pos(), ex);
680        }
681        return null;
682    }
683
684    /** Emit plain Java source for a class.
685     *  @param env    The attribution environment of the outermost class
686     *                containing this class.
687     *  @param cdef   The class definition to be printed.
688     */
689    JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
690        JavaFileObject outFile
691           = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
692                                               cdef.sym.flatname.toString(),
693                                               JavaFileObject.Kind.SOURCE,
694                                               null);
695        if (inputFiles.contains(outFile)) {
696            log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
697            return null;
698        } else {
699            try (BufferedWriter out = new BufferedWriter(outFile.openWriter())) {
700                new Pretty(out, true).printUnit(env.toplevel, cdef);
701                if (verbose)
702                    log.printVerbose("wrote.file", outFile);
703            }
704            return outFile;
705        }
706    }
707
708    /** Compile a source file that has been accessed by the class finder.
709     *  @param c          The class the source file of which needs to be compiled.
710     */
711    private void readSourceFile(ClassSymbol c) throws CompletionFailure {
712        readSourceFile(null, c);
713    }
714
715    /** Compile a ClassSymbol from source, optionally using the given compilation unit as
716     *  the source tree.
717     *  @param tree the compilation unit in which the given ClassSymbol resides,
718     *              or null if should be parsed from source
719     *  @param c    the ClassSymbol to complete
720     */
721    public void readSourceFile(JCCompilationUnit tree, ClassSymbol c) throws CompletionFailure {
722        if (completionFailureName == c.fullname) {
723            throw new CompletionFailure(c, "user-selected completion failure by class name");
724        }
725        JavaFileObject filename = c.classfile;
726        JavaFileObject prev = log.useSource(filename);
727
728        if (tree == null) {
729            try {
730                tree = parse(filename, filename.getCharContent(false));
731            } catch (IOException e) {
732                log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
733                tree = make.TopLevel(List.<JCTree>nil());
734            } finally {
735                log.useSource(prev);
736            }
737        }
738
739        if (!taskListener.isEmpty()) {
740            TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
741            taskListener.started(e);
742        }
743
744        enter.complete(List.of(tree), c);
745
746        if (!taskListener.isEmpty()) {
747            TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
748            taskListener.finished(e);
749        }
750
751        if (enter.getEnv(c) == null) {
752            boolean isPkgInfo =
753                tree.sourcefile.isNameCompatible("package-info",
754                                                 JavaFileObject.Kind.SOURCE);
755            if (isPkgInfo) {
756                if (enter.getEnv(tree.packge) == null) {
757                    JCDiagnostic diag =
758                        diagFactory.fragment("file.does.not.contain.package",
759                                                 c.location());
760                    throw new ClassFinder.BadClassFile(c, filename, diag, diagFactory);
761                }
762            } else {
763                JCDiagnostic diag =
764                        diagFactory.fragment("file.doesnt.contain.class",
765                                            c.getQualifiedName());
766                throw new ClassFinder.BadClassFile(c, filename, diag, diagFactory);
767            }
768        }
769
770        implicitSourceFilesRead = true;
771    }
772
773    /** Track when the JavaCompiler has been used to compile something. */
774    private boolean hasBeenUsed = false;
775    private long start_msec = 0;
776    public long elapsed_msec = 0;
777
778    public void compile(List<JavaFileObject> sourceFileObject)
779        throws Throwable {
780        compile(sourceFileObject, List.<String>nil(), null);
781    }
782
783    /**
784     * Main method: compile a list of files, return all compiled classes
785     *
786     * @param sourceFileObjects file objects to be compiled
787     * @param classnames class names to process for annotations
788     * @param processors user provided annotation processors to bypass
789     * discovery, {@code null} means that no processors were provided
790     */
791    public void compile(Collection<JavaFileObject> sourceFileObjects,
792                        Collection<String> classnames,
793                        Iterable<? extends Processor> processors)
794    {
795        if (!taskListener.isEmpty()) {
796            taskListener.started(new TaskEvent(TaskEvent.Kind.COMPILATION));
797        }
798
799        if (processors != null && processors.iterator().hasNext())
800            explicitAnnotationProcessingRequested = true;
801        // as a JavaCompiler can only be used once, throw an exception if
802        // it has been used before.
803        if (hasBeenUsed)
804            checkReusable();
805        hasBeenUsed = true;
806
807        // forcibly set the equivalent of -Xlint:-options, so that no further
808        // warnings about command line options are generated from this point on
809        options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
810        options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);
811
812        start_msec = now();
813
814        try {
815            initProcessAnnotations(processors);
816
817            // These method calls must be chained to avoid memory leaks
818            processAnnotations(
819                enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
820                classnames);
821
822            // If it's safe to do so, skip attr / flow / gen for implicit classes
823            if (taskListener.isEmpty() &&
824                    implicitSourcePolicy == ImplicitSourcePolicy.NONE) {
825                todo.retainFiles(inputFiles);
826            }
827
828            switch (compilePolicy) {
829            case ATTR_ONLY:
830                attribute(todo);
831                break;
832
833            case CHECK_ONLY:
834                flow(attribute(todo));
835                break;
836
837            case SIMPLE:
838                generate(desugar(flow(attribute(todo))));
839                break;
840
841            case BY_FILE: {
842                    Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
843                    while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
844                        generate(desugar(flow(attribute(q.remove()))));
845                    }
846                }
847                break;
848
849            case BY_TODO:
850                while (!todo.isEmpty())
851                    generate(desugar(flow(attribute(todo.remove()))));
852                break;
853
854            default:
855                Assert.error("unknown compile policy");
856            }
857        } catch (Abort ex) {
858            if (devVerbose)
859                ex.printStackTrace(System.err);
860        } finally {
861            if (verbose) {
862                elapsed_msec = elapsed(start_msec);
863                log.printVerbose("total", Long.toString(elapsed_msec));
864            }
865
866            reportDeferredDiagnostics();
867
868            if (!log.hasDiagnosticListener()) {
869                printCount("error", errorCount());
870                printCount("warn", warningCount());
871            }
872            if (!taskListener.isEmpty()) {
873                taskListener.finished(new TaskEvent(TaskEvent.Kind.COMPILATION));
874            }
875            close();
876            if (procEnvImpl != null)
877                procEnvImpl.close();
878        }
879    }
880
881    protected void checkReusable() {
882        throw new AssertionError("attempt to reuse JavaCompiler");
883    }
884
885    /**
886     * The list of classes explicitly supplied on the command line for compilation.
887     * Not always populated.
888     */
889    private List<JCClassDecl> rootClasses;
890
891    /**
892     * Parses a list of files.
893     */
894   public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
895       if (shouldStop(CompileState.PARSE))
896           return List.nil();
897
898        //parse all files
899        ListBuffer<JCCompilationUnit> trees = new ListBuffer<>();
900        Set<JavaFileObject> filesSoFar = new HashSet<>();
901        for (JavaFileObject fileObject : fileObjects) {
902            if (!filesSoFar.contains(fileObject)) {
903                filesSoFar.add(fileObject);
904                trees.append(parse(fileObject));
905            }
906        }
907        return trees.toList();
908    }
909
910    /**
911     * Enter the symbols found in a list of parse trees if the compilation
912     * is expected to proceed beyond anno processing into attr.
913     * As a side-effect, this puts elements on the "todo" list.
914     * Also stores a list of all top level classes in rootClasses.
915     */
916    public List<JCCompilationUnit> enterTreesIfNeeded(List<JCCompilationUnit> roots) {
917       if (shouldStop(CompileState.ATTR))
918           return List.nil();
919        return enterTrees(roots);
920    }
921
922    /**
923     * Enter the symbols found in a list of parse trees.
924     * As a side-effect, this puts elements on the "todo" list.
925     * Also stores a list of all top level classes in rootClasses.
926     */
927    public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
928        //enter symbols for all files
929        if (!taskListener.isEmpty()) {
930            for (JCCompilationUnit unit: roots) {
931                TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
932                taskListener.started(e);
933            }
934        }
935
936        enter.main(roots);
937
938        if (!taskListener.isEmpty()) {
939            for (JCCompilationUnit unit: roots) {
940                TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
941                taskListener.finished(e);
942            }
943        }
944
945        // If generating source, or if tracking public apis,
946        // then remember the classes declared in
947        // the original compilation units listed on the command line.
948        if (sourceOutput) {
949            ListBuffer<JCClassDecl> cdefs = new ListBuffer<>();
950            for (JCCompilationUnit unit : roots) {
951                for (List<JCTree> defs = unit.defs;
952                     defs.nonEmpty();
953                     defs = defs.tail) {
954                    if (defs.head instanceof JCClassDecl)
955                        cdefs.append((JCClassDecl)defs.head);
956                }
957            }
958            rootClasses = cdefs.toList();
959        }
960
961        // Ensure the input files have been recorded. Although this is normally
962        // done by readSource, it may not have been done if the trees were read
963        // in a prior round of annotation processing, and the trees have been
964        // cleaned and are being reused.
965        for (JCCompilationUnit unit : roots) {
966            inputFiles.add(unit.sourcefile);
967        }
968
969        return roots;
970    }
971
972    /**
973     * Set to true to enable skeleton annotation processing code.
974     * Currently, we assume this variable will be replaced more
975     * advanced logic to figure out if annotation processing is
976     * needed.
977     */
978    boolean processAnnotations = false;
979
980    Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
981
982    /**
983     * Object to handle annotation processing.
984     */
985    private JavacProcessingEnvironment procEnvImpl = null;
986
987    /**
988     * Check if we should process annotations.
989     * If so, and if no scanner is yet registered, then set up the DocCommentScanner
990     * to catch doc comments, and set keepComments so the parser records them in
991     * the compilation unit.
992     *
993     * @param processors user provided annotation processors to bypass
994     * discovery, {@code null} means that no processors were provided
995     */
996    public void initProcessAnnotations(Iterable<? extends Processor> processors) {
997        // Process annotations if processing is not disabled and there
998        // is at least one Processor available.
999        if (options.isSet(PROC, "none")) {
1000            processAnnotations = false;
1001        } else if (procEnvImpl == null) {
1002            procEnvImpl = JavacProcessingEnvironment.instance(context);
1003            procEnvImpl.setProcessors(processors);
1004            processAnnotations = procEnvImpl.atLeastOneProcessor();
1005
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                deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
1014            } else { // free resources
1015                procEnvImpl.close();
1016            }
1017        }
1018    }
1019
1020    // TODO: called by JavacTaskImpl
1021    public void processAnnotations(List<JCCompilationUnit> roots) {
1022        processAnnotations(roots, List.<String>nil());
1023    }
1024
1025    /**
1026     * Process any annotations found in the specified compilation units.
1027     * @param roots a list of compilation units
1028     */
1029    // Implementation note: when this method is called, log.deferredDiagnostics
1030    // will have been set true by initProcessAnnotations, meaning that any diagnostics
1031    // that are reported will go into the log.deferredDiagnostics queue.
1032    // By the time this method exits, log.deferDiagnostics must be set back to false,
1033    // and all deferredDiagnostics must have been handled: i.e. either reported
1034    // or determined to be transient, and therefore suppressed.
1035    public void processAnnotations(List<JCCompilationUnit> roots,
1036                                   Collection<String> classnames) {
1037        if (shouldStop(CompileState.PROCESS)) {
1038            // Errors were encountered.
1039            // Unless all the errors are resolve errors, the errors were parse errors
1040            // or other errors during enter which cannot be fixed by running
1041            // any annotation processors.
1042            if (unrecoverableError()) {
1043                deferredDiagnosticHandler.reportDeferredDiagnostics();
1044                log.popDiagnosticHandler(deferredDiagnosticHandler);
1045                return ;
1046            }
1047        }
1048
1049        // ASSERT: processAnnotations and procEnvImpl should have been set up by
1050        // by initProcessAnnotations
1051
1052        // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
1053
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();
1061            }
1062            // If not processing annotations, classnames must be empty
1063            if (!classnames.isEmpty()) {
1064                log.error("proc.no.explicit.annotation.processing.requested",
1065                          classnames);
1066            }
1067            Assert.checkNull(deferredDiagnosticHandler);
1068            return ; // continue regular compilation
1069        }
1070
1071        Assert.checkNonNull(deferredDiagnosticHandler);
1072
1073        try {
1074            List<ClassSymbol> classSymbols = List.nil();
1075            List<PackageSymbol> pckSymbols = List.nil();
1076            if (!classnames.isEmpty()) {
1077                 // Check for explicit request for annotation
1078                 // processing
1079                if (!explicitAnnotationProcessingRequested()) {
1080                    log.error("proc.no.explicit.annotation.processing.requested",
1081                              classnames);
1082                    deferredDiagnosticHandler.reportDeferredDiagnostics();
1083                    log.popDiagnosticHandler(deferredDiagnosticHandler);
1084                    return ; // TODO: Will this halt compilation?
1085                } else {
1086                    boolean errors = false;
1087                    for (String nameStr : classnames) {
1088                        Symbol sym = resolveBinaryNameOrIdent(nameStr);
1089                        if (sym == null ||
1090                            (sym.kind == PCK && !processPcks) ||
1091                            sym.kind == ABSENT_TYP) {
1092                            log.error("proc.cant.find.class", nameStr);
1093                            errors = true;
1094                            continue;
1095                        }
1096                        try {
1097                            if (sym.kind == PCK)
1098                                sym.complete();
1099                            if (sym.exists()) {
1100                                if (sym.kind == PCK)
1101                                    pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1102                                else
1103                                    classSymbols = classSymbols.prepend((ClassSymbol)sym);
1104                                continue;
1105                            }
1106                            Assert.check(sym.kind == PCK);
1107                            log.warning("proc.package.does.not.exist", nameStr);
1108                            pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1109                        } catch (CompletionFailure e) {
1110                            log.error("proc.cant.find.class", nameStr);
1111                            errors = true;
1112                            continue;
1113                        }
1114                    }
1115                    if (errors) {
1116                        deferredDiagnosticHandler.reportDeferredDiagnostics();
1117                        log.popDiagnosticHandler(deferredDiagnosticHandler);
1118                        return ;
1119                    }
1120                }
1121            }
1122            try {
1123                annotationProcessingOccurred =
1124                        procEnvImpl.doProcessing(roots,
1125                                                 classSymbols,
1126                                                 pckSymbols,
1127                                                 deferredDiagnosticHandler);
1128                // doProcessing will have handled deferred diagnostics
1129            } finally {
1130                procEnvImpl.close();
1131            }
1132        } catch (CompletionFailure ex) {
1133            log.error("cant.access", ex.sym, ex.getDetailValue());
1134            if (deferredDiagnosticHandler != null) {
1135                deferredDiagnosticHandler.reportDeferredDiagnostics();
1136                log.popDiagnosticHandler(deferredDiagnosticHandler);
1137            }
1138        }
1139    }
1140
1141    private boolean unrecoverableError() {
1142        if (deferredDiagnosticHandler != null) {
1143            for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
1144                if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
1145                    return true;
1146            }
1147        }
1148        return false;
1149    }
1150
1151    boolean explicitAnnotationProcessingRequested() {
1152        return
1153            explicitAnnotationProcessingRequested ||
1154            explicitAnnotationProcessingRequested(options);
1155    }
1156
1157    static boolean explicitAnnotationProcessingRequested(Options options) {
1158        return
1159            options.isSet(PROCESSOR) ||
1160            options.isSet(PROCESSORPATH) ||
1161            options.isSet(PROC, "only") ||
1162            options.isSet(XPRINT);
1163    }
1164
1165    public void setDeferredDiagnosticHandler(Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
1166        this.deferredDiagnosticHandler = deferredDiagnosticHandler;
1167    }
1168
1169    /**
1170     * Attribute a list of parse trees, such as found on the "todo" list.
1171     * Note that attributing classes may cause additional files to be
1172     * parsed and entered via the SourceCompleter.
1173     * Attribution of the entries in the list does not stop if any errors occur.
1174     * @return a list of environments for attribute classes.
1175     */
1176    public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
1177        ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1178        while (!envs.isEmpty())
1179            results.append(attribute(envs.remove()));
1180        return stopIfError(CompileState.ATTR, results);
1181    }
1182
1183    /**
1184     * Attribute a parse tree.
1185     * @return the attributed parse tree
1186     */
1187    public Env<AttrContext> attribute(Env<AttrContext> env) {
1188        if (compileStates.isDone(env, CompileState.ATTR))
1189            return env;
1190
1191        if (verboseCompilePolicy)
1192            printNote("[attribute " + env.enclClass.sym + "]");
1193        if (verbose)
1194            log.printVerbose("checking.attribution", env.enclClass.sym);
1195
1196        if (!taskListener.isEmpty()) {
1197            TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1198            taskListener.started(e);
1199        }
1200
1201        JavaFileObject prev = log.useSource(
1202                                  env.enclClass.sym.sourcefile != null ?
1203                                  env.enclClass.sym.sourcefile :
1204                                  env.toplevel.sourcefile);
1205        try {
1206            attr.attrib(env);
1207            if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
1208                //if in fail-over mode, ensure that AST expression nodes
1209                //are correctly initialized (e.g. they have a type/symbol)
1210                attr.postAttr(env.tree);
1211            }
1212            compileStates.put(env, CompileState.ATTR);
1213        }
1214        finally {
1215            log.useSource(prev);
1216        }
1217
1218        return env;
1219    }
1220
1221    /**
1222     * Perform dataflow checks on attributed parse trees.
1223     * These include checks for definite assignment and unreachable statements.
1224     * If any errors occur, an empty list will be returned.
1225     * @return the list of attributed parse trees
1226     */
1227    public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
1228        ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1229        for (Env<AttrContext> env: envs) {
1230            flow(env, results);
1231        }
1232        return stopIfError(CompileState.FLOW, results);
1233    }
1234
1235    /**
1236     * Perform dataflow checks on an attributed parse tree.
1237     */
1238    public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
1239        ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1240        flow(env, results);
1241        return stopIfError(CompileState.FLOW, results);
1242    }
1243
1244    /**
1245     * Perform dataflow checks on an attributed parse tree.
1246     */
1247    protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
1248        if (compileStates.isDone(env, CompileState.FLOW)) {
1249            results.add(env);
1250            return;
1251        }
1252
1253        try {
1254            if (shouldStop(CompileState.FLOW))
1255                return;
1256
1257            if (verboseCompilePolicy)
1258                printNote("[flow " + env.enclClass.sym + "]");
1259            JavaFileObject prev = log.useSource(
1260                                                env.enclClass.sym.sourcefile != null ?
1261                                                env.enclClass.sym.sourcefile :
1262                                                env.toplevel.sourcefile);
1263            try {
1264                make.at(Position.FIRSTPOS);
1265                TreeMaker localMake = make.forToplevel(env.toplevel);
1266                flow.analyzeTree(env, localMake);
1267                compileStates.put(env, CompileState.FLOW);
1268
1269                if (shouldStop(CompileState.FLOW))
1270                    return;
1271
1272                results.add(env);
1273            }
1274            finally {
1275                log.useSource(prev);
1276            }
1277        }
1278        finally {
1279            if (!taskListener.isEmpty()) {
1280                TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1281                taskListener.finished(e);
1282            }
1283        }
1284    }
1285
1286    /**
1287     * Prepare attributed parse trees, in conjunction with their attribution contexts,
1288     * for source or code generation.
1289     * If any errors occur, an empty list will be returned.
1290     * @return a list containing the classes to be generated
1291     */
1292    public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
1293        ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = new ListBuffer<>();
1294        for (Env<AttrContext> env: envs)
1295            desugar(env, results);
1296        return stopIfError(CompileState.FLOW, results);
1297    }
1298
1299    HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs = new HashMap<>();
1300
1301    /**
1302     * Prepare attributed parse trees, in conjunction with their attribution contexts,
1303     * for source or code generation. If the file was not listed on the command line,
1304     * the current implicitSourcePolicy is taken into account.
1305     * The preparation stops as soon as an error is found.
1306     */
1307    protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
1308        if (shouldStop(CompileState.TRANSTYPES))
1309            return;
1310
1311        if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
1312                && !inputFiles.contains(env.toplevel.sourcefile)) {
1313            return;
1314        }
1315
1316        if (compileStates.isDone(env, CompileState.LOWER)) {
1317            results.addAll(desugaredEnvs.get(env));
1318            return;
1319        }
1320
1321        /**
1322         * Ensure that superclasses of C are desugared before C itself. This is
1323         * required for two reasons: (i) as erasure (TransTypes) destroys
1324         * information needed in flow analysis and (ii) as some checks carried
1325         * out during lowering require that all synthetic fields/methods have
1326         * already been added to C and its superclasses.
1327         */
1328        class ScanNested extends TreeScanner {
1329            Set<Env<AttrContext>> dependencies = new LinkedHashSet<>();
1330            protected boolean hasLambdas;
1331            @Override
1332            public void visitClassDef(JCClassDecl node) {
1333                Type st = types.supertype(node.sym.type);
1334                boolean envForSuperTypeFound = false;
1335                while (!envForSuperTypeFound && st.hasTag(CLASS)) {
1336                    ClassSymbol c = st.tsym.outermostClass();
1337                    Env<AttrContext> stEnv = enter.getEnv(c);
1338                    if (stEnv != null && env != stEnv) {
1339                        if (dependencies.add(stEnv)) {
1340                            boolean prevHasLambdas = hasLambdas;
1341                            try {
1342                                scan(stEnv.tree);
1343                            } finally {
1344                                /*
1345                                 * ignore any updates to hasLambdas made during
1346                                 * the nested scan, this ensures an initalized
1347                                 * LambdaToMethod is available only to those
1348                                 * classes that contain lambdas
1349                                 */
1350                                hasLambdas = prevHasLambdas;
1351                            }
1352                        }
1353                        envForSuperTypeFound = true;
1354                    }
1355                    st = types.supertype(st);
1356                }
1357                super.visitClassDef(node);
1358            }
1359            @Override
1360            public void visitLambda(JCLambda tree) {
1361                hasLambdas = true;
1362                super.visitLambda(tree);
1363            }
1364            @Override
1365            public void visitReference(JCMemberReference tree) {
1366                hasLambdas = true;
1367                super.visitReference(tree);
1368            }
1369        }
1370        ScanNested scanner = new ScanNested();
1371        scanner.scan(env.tree);
1372        for (Env<AttrContext> dep: scanner.dependencies) {
1373        if (!compileStates.isDone(dep, CompileState.FLOW))
1374            desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
1375        }
1376
1377        //We need to check for error another time as more classes might
1378        //have been attributed and analyzed at this stage
1379        if (shouldStop(CompileState.TRANSTYPES))
1380            return;
1381
1382        if (verboseCompilePolicy)
1383            printNote("[desugar " + env.enclClass.sym + "]");
1384
1385        JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1386                                  env.enclClass.sym.sourcefile :
1387                                  env.toplevel.sourcefile);
1388        try {
1389            //save tree prior to rewriting
1390            JCTree untranslated = env.tree;
1391
1392            make.at(Position.FIRSTPOS);
1393            TreeMaker localMake = make.forToplevel(env.toplevel);
1394
1395            if (env.tree.hasTag(JCTree.Tag.PACKAGEDEF)) {
1396                if (!(sourceOutput)) {
1397                    if (shouldStop(CompileState.LOWER))
1398                       return;
1399                    List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
1400                    if (pdef.head != null) {
1401                        Assert.check(pdef.tail.isEmpty());
1402                        results.add(new Pair<>(env, (JCClassDecl)pdef.head));
1403                    }
1404                }
1405                return;
1406            }
1407
1408            if (shouldStop(CompileState.TRANSTYPES))
1409                return;
1410
1411            env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
1412            compileStates.put(env, CompileState.TRANSTYPES);
1413
1414            if (source.allowLambda() && scanner.hasLambdas) {
1415                if (shouldStop(CompileState.UNLAMBDA))
1416                    return;
1417
1418                env.tree = LambdaToMethod.instance(context).translateTopLevelClass(env, env.tree, localMake);
1419                compileStates.put(env, CompileState.UNLAMBDA);
1420            }
1421
1422            if (shouldStop(CompileState.LOWER))
1423                return;
1424
1425            if (sourceOutput) {
1426                //emit standard Java source file, only for compilation
1427                //units enumerated explicitly on the command line
1428                JCClassDecl cdef = (JCClassDecl)env.tree;
1429                if (untranslated instanceof JCClassDecl &&
1430                    rootClasses.contains((JCClassDecl)untranslated)) {
1431                    results.add(new Pair<>(env, cdef));
1432                }
1433                return;
1434            }
1435
1436            //translate out inner classes
1437            List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
1438            compileStates.put(env, CompileState.LOWER);
1439
1440            if (shouldStop(CompileState.LOWER))
1441                return;
1442
1443            //generate code for each class
1444            for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
1445                JCClassDecl cdef = (JCClassDecl)l.head;
1446                results.add(new Pair<>(env, cdef));
1447            }
1448        }
1449        finally {
1450            log.useSource(prev);
1451        }
1452
1453    }
1454
1455    /** Generates the source or class file for a list of classes.
1456     * The decision to generate a source file or a class file is
1457     * based upon the compiler's options.
1458     * Generation stops if an error occurs while writing files.
1459     */
1460    public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
1461        generate(queue, null);
1462    }
1463
1464    public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
1465        if (shouldStop(CompileState.GENERATE))
1466            return;
1467
1468        for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
1469            Env<AttrContext> env = x.fst;
1470            JCClassDecl cdef = x.snd;
1471
1472            if (verboseCompilePolicy) {
1473                printNote("[generate " + (sourceOutput ? " source" : "code") + " " + cdef.sym + "]");
1474            }
1475
1476            if (!taskListener.isEmpty()) {
1477                TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1478                taskListener.started(e);
1479            }
1480
1481            JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1482                                      env.enclClass.sym.sourcefile :
1483                                      env.toplevel.sourcefile);
1484            try {
1485                JavaFileObject file;
1486                if (sourceOutput) {
1487                    file = printSource(env, cdef);
1488                } else {
1489                    if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
1490                            && jniWriter.needsHeader(cdef.sym)) {
1491                        jniWriter.write(cdef.sym);
1492                    }
1493                    file = genCode(env, cdef);
1494                }
1495                if (results != null && file != null)
1496                    results.add(file);
1497            } catch (IOException ex) {
1498                log.error(cdef.pos(), "class.cant.write",
1499                          cdef.sym, ex.getMessage());
1500                return;
1501            } finally {
1502                log.useSource(prev);
1503            }
1504
1505            if (!taskListener.isEmpty()) {
1506                TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1507                taskListener.finished(e);
1508            }
1509        }
1510    }
1511
1512        // where
1513        Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
1514            // use a LinkedHashMap to preserve the order of the original list as much as possible
1515            Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<>();
1516            for (Env<AttrContext> env: envs) {
1517                Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
1518                if (sublist == null) {
1519                    sublist = new ListBuffer<>();
1520                    map.put(env.toplevel, sublist);
1521                }
1522                sublist.add(env);
1523            }
1524            return map;
1525        }
1526
1527        JCClassDecl removeMethodBodies(JCClassDecl cdef) {
1528            final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
1529            class MethodBodyRemover extends TreeTranslator {
1530                @Override
1531                public void visitMethodDef(JCMethodDecl tree) {
1532                    tree.mods.flags &= ~Flags.SYNCHRONIZED;
1533                    for (JCVariableDecl vd : tree.params)
1534                        vd.mods.flags &= ~Flags.FINAL;
1535                    tree.body = null;
1536                    super.visitMethodDef(tree);
1537                }
1538                @Override
1539                public void visitVarDef(JCVariableDecl tree) {
1540                    if (tree.init != null && tree.init.type.constValue() == null)
1541                        tree.init = null;
1542                    super.visitVarDef(tree);
1543                }
1544                @Override
1545                public void visitClassDef(JCClassDecl tree) {
1546                    ListBuffer<JCTree> newdefs = new ListBuffer<>();
1547                    for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
1548                        JCTree t = it.head;
1549                        switch (t.getTag()) {
1550                        case CLASSDEF:
1551                            if (isInterface ||
1552                                (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1553                                (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1554                                newdefs.append(t);
1555                            break;
1556                        case METHODDEF:
1557                            if (isInterface ||
1558                                (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1559                                ((JCMethodDecl) t).sym.name == names.init ||
1560                                (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1561                                newdefs.append(t);
1562                            break;
1563                        case VARDEF:
1564                            if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1565                                (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1566                                newdefs.append(t);
1567                            break;
1568                        default:
1569                            break;
1570                        }
1571                    }
1572                    tree.defs = newdefs.toList();
1573                    super.visitClassDef(tree);
1574                }
1575            }
1576            MethodBodyRemover r = new MethodBodyRemover();
1577            return r.translate(cdef);
1578        }
1579
1580    public void reportDeferredDiagnostics() {
1581        if (errorCount() == 0
1582                && annotationProcessingOccurred
1583                && implicitSourceFilesRead
1584                && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
1585            if (explicitAnnotationProcessingRequested())
1586                log.warning("proc.use.implicit");
1587            else
1588                log.warning("proc.use.proc.or.implicit");
1589        }
1590        chk.reportDeferredDiagnostics();
1591        if (log.compressedOutput) {
1592            log.mandatoryNote(null, "compressed.diags");
1593        }
1594    }
1595
1596    /** Close the compiler, flushing the logs
1597     */
1598    public void close() {
1599        rootClasses = null;
1600        finder = null;
1601        reader = null;
1602        make = null;
1603        writer = null;
1604        enter = null;
1605        if (todo != null)
1606            todo.clear();
1607        todo = null;
1608        parserFactory = null;
1609        syms = null;
1610        source = null;
1611        attr = null;
1612        chk = null;
1613        gen = null;
1614        flow = null;
1615        transTypes = null;
1616        lower = null;
1617        annotate = null;
1618        types = null;
1619
1620        log.flush();
1621        try {
1622            fileManager.flush();
1623        } catch (IOException e) {
1624            throw new Abort(e);
1625        } finally {
1626            if (names != null)
1627                names.dispose();
1628            names = null;
1629
1630            for (Closeable c: closeables) {
1631                try {
1632                    c.close();
1633                } catch (IOException e) {
1634                    // When javac uses JDK 7 as a baseline, this code would be
1635                    // better written to set any/all exceptions from all the
1636                    // Closeables as suppressed exceptions on the FatalError
1637                    // that is thrown.
1638                    JCDiagnostic msg = diagFactory.fragment("fatal.err.cant.close");
1639                    throw new FatalError(msg, e);
1640                }
1641            }
1642            closeables = List.nil();
1643        }
1644    }
1645
1646    protected void printNote(String lines) {
1647        log.printRawLines(Log.WriterKind.NOTICE, lines);
1648    }
1649
1650    /** Print numbers of errors and warnings.
1651     */
1652    public void printCount(String kind, int count) {
1653        if (count != 0) {
1654            String key;
1655            if (count == 1)
1656                key = "count." + kind;
1657            else
1658                key = "count." + kind + ".plural";
1659            log.printLines(WriterKind.ERROR, key, String.valueOf(count));
1660            log.flush(Log.WriterKind.ERROR);
1661        }
1662    }
1663
1664    private static long now() {
1665        return System.currentTimeMillis();
1666    }
1667
1668    private static long elapsed(long then) {
1669        return now() - then;
1670    }
1671
1672    public void newRound() {
1673        inputFiles.clear();
1674        todo.clear();
1675    }
1676}
1677