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