JavaCompiler.java revision 2981:d1e5707cd4eb
1223695Sdfr/*
2223695Sdfr * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
3223695Sdfr * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4223695Sdfr *
5223695Sdfr * This code is free software; you can redistribute it and/or modify it
6223695Sdfr * under the terms of the GNU General Public License version 2 only, as
7223695Sdfr * published by the Free Software Foundation.  Oracle designates this
8223695Sdfr * particular file as subject to the "Classpath" exception as provided
9223695Sdfr * by Oracle in the LICENSE file that accompanied this code.
10223695Sdfr *
11223695Sdfr * This code is distributed in the hope that it will be useful, but WITHOUT
12223695Sdfr * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13223695Sdfr * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14223695Sdfr * version 2 for more details (a copy is included in the LICENSE file that
15223695Sdfr * accompanied this code).
16223695Sdfr *
17223695Sdfr * You should have received a copy of the GNU General Public License version
18223695Sdfr * 2 along with this work; if not, write to the Free Software Foundation,
19223695Sdfr * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20223695Sdfr *
21223695Sdfr * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22223695Sdfr * or visit www.oracle.com if you need additional information or have any
23223695Sdfr * questions.
24223695Sdfr */
25223695Sdfr
26223695Sdfrpackage com.sun.tools.javac.main;
27223695Sdfr
28223695Sdfrimport java.io.*;
29223695Sdfrimport java.util.Collection;
30223695Sdfrimport java.util.HashMap;
31223695Sdfrimport java.util.HashSet;
32223695Sdfrimport java.util.LinkedHashMap;
33223695Sdfrimport java.util.LinkedHashSet;
34223695Sdfrimport java.util.Map;
35223695Sdfrimport java.util.MissingResourceException;
36223695Sdfrimport java.util.Queue;
37223695Sdfrimport java.util.ResourceBundle;
38223695Sdfrimport java.util.Set;
39223695Sdfr
40223695Sdfrimport javax.annotation.processing.Processor;
41223695Sdfrimport javax.lang.model.SourceVersion;
42223695Sdfrimport javax.tools.DiagnosticListener;
43223695Sdfrimport javax.tools.JavaFileManager;
44223695Sdfrimport javax.tools.JavaFileObject;
45223695Sdfrimport javax.tools.StandardLocation;
46223695Sdfr
47223695Sdfrimport com.sun.source.util.TaskEvent;
48223695Sdfrimport com.sun.tools.javac.api.MultiTaskListener;
49223695Sdfrimport com.sun.tools.javac.code.*;
50223695Sdfrimport com.sun.tools.javac.code.Lint.LintCategory;
51223695Sdfrimport com.sun.tools.javac.code.Symbol.ClassSymbol;
52223695Sdfrimport com.sun.tools.javac.code.Symbol.CompletionFailure;
53223695Sdfrimport com.sun.tools.javac.code.Symbol.PackageSymbol;
54223695Sdfrimport com.sun.tools.javac.comp.*;
55223695Sdfrimport com.sun.tools.javac.comp.CompileStates.CompileState;
56223695Sdfrimport com.sun.tools.javac.file.JavacFileManager;
57223695Sdfrimport com.sun.tools.javac.jvm.*;
58223695Sdfrimport com.sun.tools.javac.parser.*;
59223695Sdfrimport com.sun.tools.javac.platform.PlatformDescription;
60223695Sdfrimport com.sun.tools.javac.processing.*;
61223695Sdfrimport com.sun.tools.javac.tree.*;
62223695Sdfrimport com.sun.tools.javac.tree.JCTree.JCClassDecl;
63223695Sdfrimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
64223695Sdfrimport com.sun.tools.javac.tree.JCTree.JCExpression;
65223695Sdfrimport com.sun.tools.javac.tree.JCTree.JCLambda;
66223695Sdfrimport com.sun.tools.javac.tree.JCTree.JCMemberReference;
67223695Sdfrimport com.sun.tools.javac.tree.JCTree.JCMethodDecl;
68223695Sdfrimport com.sun.tools.javac.tree.JCTree.JCVariableDecl;
69223695Sdfrimport com.sun.tools.javac.util.*;
70223695Sdfrimport com.sun.tools.javac.util.Log.WriterKind;
71223695Sdfr
72223695Sdfrimport static com.sun.tools.javac.code.Kinds.Kind.*;
73223695Sdfrimport static com.sun.tools.javac.code.TypeTag.CLASS;
74223695Sdfrimport static com.sun.tools.javac.main.Option.*;
75223695Sdfrimport static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
76223695Sdfrimport static javax.tools.StandardLocation.CLASS_OUTPUT;
77223695Sdfr
78223695Sdfr/** This class could be the main entry point for GJC when GJC is used as a
79223695Sdfr *  component in a larger software system. It provides operations to
80223695Sdfr *  construct a new compiler, and to run a new compiler on a set of source
81223695Sdfr *  files.
82223695Sdfr *
83223695Sdfr *  <p><b>This is NOT part of any supported API.
84223695Sdfr *  If you write code that depends on this, you do so at your own risk.
85223695Sdfr *  This code and its internal interfaces are subject to change or
86223695Sdfr *  deletion without notice.</b>
87223695Sdfr */
88223695Sdfrpublic class JavaCompiler {
89223695Sdfr    /** The context key for the compiler. */
90223695Sdfr    protected static final Context.Key<JavaCompiler> compilerKey = new Context.Key<>();
91223695Sdfr
92223695Sdfr    /** Get the JavaCompiler instance for this context. */
93223695Sdfr    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            throw new AssertionError("attempt to reuse JavaCompiler");
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    /**
902     * Set needRootClasses to true, in JavaCompiler subclass constructor
903     * that want to collect public apis of classes supplied on the command line.
904     */
905    protected boolean needRootClasses = false;
906
907    /**
908     * The list of classes explicitly supplied on the command line for compilation.
909     * Not always populated.
910     */
911    private List<JCClassDecl> rootClasses;
912
913    /**
914     * Parses a list of files.
915     */
916   public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
917       if (shouldStop(CompileState.PARSE))
918           return List.nil();
919
920        //parse all files
921        ListBuffer<JCCompilationUnit> trees = new ListBuffer<>();
922        Set<JavaFileObject> filesSoFar = new HashSet<>();
923        for (JavaFileObject fileObject : fileObjects) {
924            if (!filesSoFar.contains(fileObject)) {
925                filesSoFar.add(fileObject);
926                trees.append(parse(fileObject));
927            }
928        }
929        return trees.toList();
930    }
931
932    /**
933     * Enter the symbols found in a list of parse trees if the compilation
934     * is expected to proceed beyond anno processing into attr.
935     * As a side-effect, this puts elements on the "todo" list.
936     * Also stores a list of all top level classes in rootClasses.
937     */
938    public List<JCCompilationUnit> enterTreesIfNeeded(List<JCCompilationUnit> roots) {
939       if (shouldStop(CompileState.ATTR))
940           return List.nil();
941        return enterTrees(roots);
942    }
943
944    /**
945     * Enter the symbols found in a list of parse trees.
946     * As a side-effect, this puts elements on the "todo" list.
947     * Also stores a list of all top level classes in rootClasses.
948     */
949    public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
950        //enter symbols for all files
951        if (!taskListener.isEmpty()) {
952            for (JCCompilationUnit unit: roots) {
953                TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
954                taskListener.started(e);
955            }
956        }
957
958        enter.main(roots);
959
960        if (!taskListener.isEmpty()) {
961            for (JCCompilationUnit unit: roots) {
962                TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
963                taskListener.finished(e);
964            }
965        }
966
967        // If generating source, or if tracking public apis,
968        // then remember the classes declared in
969        // the original compilation units listed on the command line.
970        if (needRootClasses || sourceOutput || stubOutput) {
971            ListBuffer<JCClassDecl> cdefs = new ListBuffer<>();
972            for (JCCompilationUnit unit : roots) {
973                for (List<JCTree> defs = unit.defs;
974                     defs.nonEmpty();
975                     defs = defs.tail) {
976                    if (defs.head instanceof JCClassDecl)
977                        cdefs.append((JCClassDecl)defs.head);
978                }
979            }
980            rootClasses = cdefs.toList();
981        }
982
983        // Ensure the input files have been recorded. Although this is normally
984        // done by readSource, it may not have been done if the trees were read
985        // in a prior round of annotation processing, and the trees have been
986        // cleaned and are being reused.
987        for (JCCompilationUnit unit : roots) {
988            inputFiles.add(unit.sourcefile);
989        }
990
991        return roots;
992    }
993
994    /**
995     * Set to true to enable skeleton annotation processing code.
996     * Currently, we assume this variable will be replaced more
997     * advanced logic to figure out if annotation processing is
998     * needed.
999     */
1000    boolean processAnnotations = false;
1001
1002    Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
1003
1004    /**
1005     * Object to handle annotation processing.
1006     */
1007    private JavacProcessingEnvironment procEnvImpl = null;
1008
1009    /**
1010     * Check if we should process annotations.
1011     * If so, and if no scanner is yet registered, then set up the DocCommentScanner
1012     * to catch doc comments, and set keepComments so the parser records them in
1013     * the compilation unit.
1014     *
1015     * @param processors user provided annotation processors to bypass
1016     * discovery, {@code null} means that no processors were provided
1017     */
1018    public void initProcessAnnotations(Iterable<? extends Processor> processors) {
1019        // Process annotations if processing is not disabled and there
1020        // is at least one Processor available.
1021        if (options.isSet(PROC, "none")) {
1022            processAnnotations = false;
1023        } else if (procEnvImpl == null) {
1024            procEnvImpl = JavacProcessingEnvironment.instance(context);
1025            procEnvImpl.setProcessors(processors);
1026            processAnnotations = procEnvImpl.atLeastOneProcessor();
1027
1028            if (processAnnotations) {
1029                options.put("save-parameter-names", "save-parameter-names");
1030                reader.saveParameterNames = true;
1031                keepComments = true;
1032                genEndPos = true;
1033                if (!taskListener.isEmpty())
1034                    taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
1035                deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
1036            } else { // free resources
1037                procEnvImpl.close();
1038            }
1039        }
1040    }
1041
1042    // TODO: called by JavacTaskImpl
1043    public void processAnnotations(List<JCCompilationUnit> roots) {
1044        processAnnotations(roots, List.<String>nil());
1045    }
1046
1047    /**
1048     * Process any annotations found in the specified compilation units.
1049     * @param roots a list of compilation units
1050     */
1051    // Implementation note: when this method is called, log.deferredDiagnostics
1052    // will have been set true by initProcessAnnotations, meaning that any diagnostics
1053    // that are reported will go into the log.deferredDiagnostics queue.
1054    // By the time this method exits, log.deferDiagnostics must be set back to false,
1055    // and all deferredDiagnostics must have been handled: i.e. either reported
1056    // or determined to be transient, and therefore suppressed.
1057    public void processAnnotations(List<JCCompilationUnit> roots,
1058                                   Collection<String> classnames) {
1059        if (shouldStop(CompileState.PROCESS)) {
1060            // Errors were encountered.
1061            // Unless all the errors are resolve errors, the errors were parse errors
1062            // or other errors during enter which cannot be fixed by running
1063            // any annotation processors.
1064            if (unrecoverableError()) {
1065                deferredDiagnosticHandler.reportDeferredDiagnostics();
1066                log.popDiagnosticHandler(deferredDiagnosticHandler);
1067                return ;
1068            }
1069        }
1070
1071        // ASSERT: processAnnotations and procEnvImpl should have been set up by
1072        // by initProcessAnnotations
1073
1074        // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
1075
1076        if (!processAnnotations) {
1077            // If there are no annotation processors present, and
1078            // annotation processing is to occur with compilation,
1079            // emit a warning.
1080            if (options.isSet(PROC, "only")) {
1081                log.warning("proc.proc-only.requested.no.procs");
1082                todo.clear();
1083            }
1084            // If not processing annotations, classnames must be empty
1085            if (!classnames.isEmpty()) {
1086                log.error("proc.no.explicit.annotation.processing.requested",
1087                          classnames);
1088            }
1089            Assert.checkNull(deferredDiagnosticHandler);
1090            return ; // continue regular compilation
1091        }
1092
1093        Assert.checkNonNull(deferredDiagnosticHandler);
1094
1095        try {
1096            List<ClassSymbol> classSymbols = List.nil();
1097            List<PackageSymbol> pckSymbols = List.nil();
1098            if (!classnames.isEmpty()) {
1099                 // Check for explicit request for annotation
1100                 // processing
1101                if (!explicitAnnotationProcessingRequested()) {
1102                    log.error("proc.no.explicit.annotation.processing.requested",
1103                              classnames);
1104                    deferredDiagnosticHandler.reportDeferredDiagnostics();
1105                    log.popDiagnosticHandler(deferredDiagnosticHandler);
1106                    return ; // TODO: Will this halt compilation?
1107                } else {
1108                    boolean errors = false;
1109                    for (String nameStr : classnames) {
1110                        Symbol sym = resolveBinaryNameOrIdent(nameStr);
1111                        if (sym == null ||
1112                            (sym.kind == PCK && !processPcks) ||
1113                            sym.kind == ABSENT_TYP) {
1114                            log.error("proc.cant.find.class", nameStr);
1115                            errors = true;
1116                            continue;
1117                        }
1118                        try {
1119                            if (sym.kind == PCK)
1120                                sym.complete();
1121                            if (sym.exists()) {
1122                                if (sym.kind == PCK)
1123                                    pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1124                                else
1125                                    classSymbols = classSymbols.prepend((ClassSymbol)sym);
1126                                continue;
1127                            }
1128                            Assert.check(sym.kind == PCK);
1129                            log.warning("proc.package.does.not.exist", nameStr);
1130                            pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1131                        } catch (CompletionFailure e) {
1132                            log.error("proc.cant.find.class", nameStr);
1133                            errors = true;
1134                            continue;
1135                        }
1136                    }
1137                    if (errors) {
1138                        deferredDiagnosticHandler.reportDeferredDiagnostics();
1139                        log.popDiagnosticHandler(deferredDiagnosticHandler);
1140                        return ;
1141                    }
1142                }
1143            }
1144            try {
1145                annotationProcessingOccurred =
1146                        procEnvImpl.doProcessing(roots,
1147                                                 classSymbols,
1148                                                 pckSymbols,
1149                                                 deferredDiagnosticHandler);
1150                // doProcessing will have handled deferred diagnostics
1151            } finally {
1152                procEnvImpl.close();
1153            }
1154        } catch (CompletionFailure ex) {
1155            log.error("cant.access", ex.sym, ex.getDetailValue());
1156            if (deferredDiagnosticHandler != null) {
1157                deferredDiagnosticHandler.reportDeferredDiagnostics();
1158                log.popDiagnosticHandler(deferredDiagnosticHandler);
1159            }
1160        }
1161    }
1162
1163    private boolean unrecoverableError() {
1164        if (deferredDiagnosticHandler != null) {
1165            for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
1166                if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
1167                    return true;
1168            }
1169        }
1170        return false;
1171    }
1172
1173    boolean explicitAnnotationProcessingRequested() {
1174        return
1175            explicitAnnotationProcessingRequested ||
1176            explicitAnnotationProcessingRequested(options);
1177    }
1178
1179    static boolean explicitAnnotationProcessingRequested(Options options) {
1180        return
1181            options.isSet(PROCESSOR) ||
1182            options.isSet(PROCESSORPATH) ||
1183            options.isSet(PROC, "only") ||
1184            options.isSet(XPRINT);
1185    }
1186
1187    public void setDeferredDiagnosticHandler(Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
1188        this.deferredDiagnosticHandler = deferredDiagnosticHandler;
1189    }
1190
1191    /**
1192     * Attribute a list of parse trees, such as found on the "todo" list.
1193     * Note that attributing classes may cause additional files to be
1194     * parsed and entered via the SourceCompleter.
1195     * Attribution of the entries in the list does not stop if any errors occur.
1196     * @return a list of environments for attribute classes.
1197     */
1198    public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
1199        ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1200        while (!envs.isEmpty())
1201            results.append(attribute(envs.remove()));
1202        return stopIfError(CompileState.ATTR, results);
1203    }
1204
1205    /**
1206     * Attribute a parse tree.
1207     * @return the attributed parse tree
1208     */
1209    public Env<AttrContext> attribute(Env<AttrContext> env) {
1210        if (compileStates.isDone(env, CompileState.ATTR))
1211            return env;
1212
1213        if (verboseCompilePolicy)
1214            printNote("[attribute " + env.enclClass.sym + "]");
1215        if (verbose)
1216            log.printVerbose("checking.attribution", env.enclClass.sym);
1217
1218        if (!taskListener.isEmpty()) {
1219            TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1220            taskListener.started(e);
1221        }
1222
1223        JavaFileObject prev = log.useSource(
1224                                  env.enclClass.sym.sourcefile != null ?
1225                                  env.enclClass.sym.sourcefile :
1226                                  env.toplevel.sourcefile);
1227        try {
1228            attr.attrib(env);
1229            if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
1230                //if in fail-over mode, ensure that AST expression nodes
1231                //are correctly initialized (e.g. they have a type/symbol)
1232                attr.postAttr(env.tree);
1233            }
1234            compileStates.put(env, CompileState.ATTR);
1235        }
1236        finally {
1237            log.useSource(prev);
1238        }
1239
1240        return env;
1241    }
1242
1243    /**
1244     * Perform dataflow checks on attributed parse trees.
1245     * These include checks for definite assignment and unreachable statements.
1246     * If any errors occur, an empty list will be returned.
1247     * @return the list of attributed parse trees
1248     */
1249    public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
1250        ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1251        for (Env<AttrContext> env: envs) {
1252            flow(env, results);
1253        }
1254        return stopIfError(CompileState.FLOW, results);
1255    }
1256
1257    /**
1258     * Perform dataflow checks on an attributed parse tree.
1259     */
1260    public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
1261        ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1262        flow(env, results);
1263        return stopIfError(CompileState.FLOW, results);
1264    }
1265
1266    /**
1267     * Perform dataflow checks on an attributed parse tree.
1268     */
1269    protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
1270        if (compileStates.isDone(env, CompileState.FLOW)) {
1271            results.add(env);
1272            return;
1273        }
1274
1275        try {
1276            if (shouldStop(CompileState.FLOW))
1277                return;
1278
1279            if (relax) {
1280                results.add(env);
1281                return;
1282            }
1283
1284            if (verboseCompilePolicy)
1285                printNote("[flow " + env.enclClass.sym + "]");
1286            JavaFileObject prev = log.useSource(
1287                                                env.enclClass.sym.sourcefile != null ?
1288                                                env.enclClass.sym.sourcefile :
1289                                                env.toplevel.sourcefile);
1290            try {
1291                make.at(Position.FIRSTPOS);
1292                TreeMaker localMake = make.forToplevel(env.toplevel);
1293                flow.analyzeTree(env, localMake);
1294                compileStates.put(env, CompileState.FLOW);
1295
1296                if (shouldStop(CompileState.FLOW))
1297                    return;
1298
1299                results.add(env);
1300            }
1301            finally {
1302                log.useSource(prev);
1303            }
1304        }
1305        finally {
1306            if (!taskListener.isEmpty()) {
1307                TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1308                taskListener.finished(e);
1309            }
1310        }
1311    }
1312
1313    /**
1314     * Prepare attributed parse trees, in conjunction with their attribution contexts,
1315     * for source or code generation.
1316     * If any errors occur, an empty list will be returned.
1317     * @return a list containing the classes to be generated
1318     */
1319    public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
1320        ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = new ListBuffer<>();
1321        for (Env<AttrContext> env: envs)
1322            desugar(env, results);
1323        return stopIfError(CompileState.FLOW, results);
1324    }
1325
1326    HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs = new HashMap<>();
1327
1328    /**
1329     * Prepare attributed parse trees, in conjunction with their attribution contexts,
1330     * for source or code generation. If the file was not listed on the command line,
1331     * the current implicitSourcePolicy is taken into account.
1332     * The preparation stops as soon as an error is found.
1333     */
1334    protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
1335        if (shouldStop(CompileState.TRANSTYPES))
1336            return;
1337
1338        if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
1339                && !inputFiles.contains(env.toplevel.sourcefile)) {
1340            return;
1341        }
1342
1343        if (compileStates.isDone(env, CompileState.LOWER)) {
1344            results.addAll(desugaredEnvs.get(env));
1345            return;
1346        }
1347
1348        /**
1349         * Ensure that superclasses of C are desugared before C itself. This is
1350         * required for two reasons: (i) as erasure (TransTypes) destroys
1351         * information needed in flow analysis and (ii) as some checks carried
1352         * out during lowering require that all synthetic fields/methods have
1353         * already been added to C and its superclasses.
1354         */
1355        class ScanNested extends TreeScanner {
1356            Set<Env<AttrContext>> dependencies = new LinkedHashSet<>();
1357            protected boolean hasLambdas;
1358            @Override
1359            public void visitClassDef(JCClassDecl node) {
1360                Type st = types.supertype(node.sym.type);
1361                boolean envForSuperTypeFound = false;
1362                while (!envForSuperTypeFound && st.hasTag(CLASS)) {
1363                    ClassSymbol c = st.tsym.outermostClass();
1364                    Env<AttrContext> stEnv = enter.getEnv(c);
1365                    if (stEnv != null && env != stEnv) {
1366                        if (dependencies.add(stEnv)) {
1367                            boolean prevHasLambdas = hasLambdas;
1368                            try {
1369                                scan(stEnv.tree);
1370                            } finally {
1371                                /*
1372                                 * ignore any updates to hasLambdas made during
1373                                 * the nested scan, this ensures an initalized
1374                                 * LambdaToMethod is available only to those
1375                                 * classes that contain lambdas
1376                                 */
1377                                hasLambdas = prevHasLambdas;
1378                            }
1379                        }
1380                        envForSuperTypeFound = true;
1381                    }
1382                    st = types.supertype(st);
1383                }
1384                super.visitClassDef(node);
1385            }
1386            @Override
1387            public void visitLambda(JCLambda tree) {
1388                hasLambdas = true;
1389                super.visitLambda(tree);
1390            }
1391            @Override
1392            public void visitReference(JCMemberReference tree) {
1393                hasLambdas = true;
1394                super.visitReference(tree);
1395            }
1396        }
1397        ScanNested scanner = new ScanNested();
1398        scanner.scan(env.tree);
1399        for (Env<AttrContext> dep: scanner.dependencies) {
1400        if (!compileStates.isDone(dep, CompileState.FLOW))
1401            desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
1402        }
1403
1404        //We need to check for error another time as more classes might
1405        //have been attributed and analyzed at this stage
1406        if (shouldStop(CompileState.TRANSTYPES))
1407            return;
1408
1409        if (verboseCompilePolicy)
1410            printNote("[desugar " + env.enclClass.sym + "]");
1411
1412        JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1413                                  env.enclClass.sym.sourcefile :
1414                                  env.toplevel.sourcefile);
1415        try {
1416            //save tree prior to rewriting
1417            JCTree untranslated = env.tree;
1418
1419            make.at(Position.FIRSTPOS);
1420            TreeMaker localMake = make.forToplevel(env.toplevel);
1421
1422            if (env.tree.hasTag(JCTree.Tag.PACKAGEDEF)) {
1423                if (!(stubOutput || sourceOutput || printFlat)) {
1424                    if (shouldStop(CompileState.LOWER))
1425                        return;
1426                    List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
1427                    if (pdef.head != null) {
1428                        Assert.check(pdef.tail.isEmpty());
1429                        results.add(new Pair<>(env, (JCClassDecl)pdef.head));
1430                    }
1431                }
1432                return;
1433            }
1434
1435            if (stubOutput) {
1436                //emit stub Java source file, only for compilation
1437                //units enumerated explicitly on the command line
1438                JCClassDecl cdef = (JCClassDecl)env.tree;
1439                if (untranslated instanceof JCClassDecl &&
1440                    rootClasses.contains((JCClassDecl)untranslated) &&
1441                    ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1442                     cdef.sym.packge().getQualifiedName() == names.java_lang)) {
1443                    results.add(new Pair<>(env, removeMethodBodies(cdef)));
1444                }
1445                return;
1446            }
1447
1448            if (shouldStop(CompileState.TRANSTYPES))
1449                return;
1450
1451            env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
1452            compileStates.put(env, CompileState.TRANSTYPES);
1453
1454            if (source.allowLambda() && scanner.hasLambdas) {
1455                if (shouldStop(CompileState.UNLAMBDA))
1456                    return;
1457
1458                env.tree = LambdaToMethod.instance(context).translateTopLevelClass(env, env.tree, localMake);
1459                compileStates.put(env, CompileState.UNLAMBDA);
1460            }
1461
1462            if (shouldStop(CompileState.LOWER))
1463                return;
1464
1465            if (sourceOutput) {
1466                //emit standard Java source file, only for compilation
1467                //units enumerated explicitly on the command line
1468                JCClassDecl cdef = (JCClassDecl)env.tree;
1469                if (untranslated instanceof JCClassDecl &&
1470                    rootClasses.contains((JCClassDecl)untranslated)) {
1471                    results.add(new Pair<>(env, cdef));
1472                }
1473                return;
1474            }
1475
1476            //translate out inner classes
1477            List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
1478            compileStates.put(env, CompileState.LOWER);
1479
1480            if (shouldStop(CompileState.LOWER))
1481                return;
1482
1483            //generate code for each class
1484            for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
1485                JCClassDecl cdef = (JCClassDecl)l.head;
1486                results.add(new Pair<>(env, cdef));
1487            }
1488        }
1489        finally {
1490            log.useSource(prev);
1491        }
1492
1493    }
1494
1495    /** Generates the source or class file for a list of classes.
1496     * The decision to generate a source file or a class file is
1497     * based upon the compiler's options.
1498     * Generation stops if an error occurs while writing files.
1499     */
1500    public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
1501        generate(queue, null);
1502    }
1503
1504    public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
1505        if (shouldStop(CompileState.GENERATE))
1506            return;
1507
1508        boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
1509
1510        for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
1511            Env<AttrContext> env = x.fst;
1512            JCClassDecl cdef = x.snd;
1513
1514            if (verboseCompilePolicy) {
1515                printNote("[generate "
1516                               + (usePrintSource ? " source" : "code")
1517                               + " " + cdef.sym + "]");
1518            }
1519
1520            if (!taskListener.isEmpty()) {
1521                TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1522                taskListener.started(e);
1523            }
1524
1525            JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1526                                      env.enclClass.sym.sourcefile :
1527                                      env.toplevel.sourcefile);
1528            try {
1529                JavaFileObject file;
1530                if (usePrintSource)
1531                    file = printSource(env, cdef);
1532                else {
1533                    if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
1534                            && jniWriter.needsHeader(cdef.sym)) {
1535                        jniWriter.write(cdef.sym);
1536                    }
1537                    file = genCode(env, cdef);
1538                }
1539                if (results != null && file != null)
1540                    results.add(file);
1541            } catch (IOException ex) {
1542                log.error(cdef.pos(), "class.cant.write",
1543                          cdef.sym, ex.getMessage());
1544                return;
1545            } finally {
1546                log.useSource(prev);
1547            }
1548
1549            if (!taskListener.isEmpty()) {
1550                TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1551                taskListener.finished(e);
1552            }
1553        }
1554    }
1555
1556        // where
1557        Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
1558            // use a LinkedHashMap to preserve the order of the original list as much as possible
1559            Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<>();
1560            for (Env<AttrContext> env: envs) {
1561                Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
1562                if (sublist == null) {
1563                    sublist = new ListBuffer<>();
1564                    map.put(env.toplevel, sublist);
1565                }
1566                sublist.add(env);
1567            }
1568            return map;
1569        }
1570
1571        JCClassDecl removeMethodBodies(JCClassDecl cdef) {
1572            final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
1573            class MethodBodyRemover extends TreeTranslator {
1574                @Override
1575                public void visitMethodDef(JCMethodDecl tree) {
1576                    tree.mods.flags &= ~Flags.SYNCHRONIZED;
1577                    for (JCVariableDecl vd : tree.params)
1578                        vd.mods.flags &= ~Flags.FINAL;
1579                    tree.body = null;
1580                    super.visitMethodDef(tree);
1581                }
1582                @Override
1583                public void visitVarDef(JCVariableDecl tree) {
1584                    if (tree.init != null && tree.init.type.constValue() == null)
1585                        tree.init = null;
1586                    super.visitVarDef(tree);
1587                }
1588                @Override
1589                public void visitClassDef(JCClassDecl tree) {
1590                    ListBuffer<JCTree> newdefs = new ListBuffer<>();
1591                    for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
1592                        JCTree t = it.head;
1593                        switch (t.getTag()) {
1594                        case CLASSDEF:
1595                            if (isInterface ||
1596                                (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1597                                (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1598                                newdefs.append(t);
1599                            break;
1600                        case METHODDEF:
1601                            if (isInterface ||
1602                                (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1603                                ((JCMethodDecl) t).sym.name == names.init ||
1604                                (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1605                                newdefs.append(t);
1606                            break;
1607                        case VARDEF:
1608                            if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1609                                (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1610                                newdefs.append(t);
1611                            break;
1612                        default:
1613                            break;
1614                        }
1615                    }
1616                    tree.defs = newdefs.toList();
1617                    super.visitClassDef(tree);
1618                }
1619            }
1620            MethodBodyRemover r = new MethodBodyRemover();
1621            return r.translate(cdef);
1622        }
1623
1624    public void reportDeferredDiagnostics() {
1625        if (errorCount() == 0
1626                && annotationProcessingOccurred
1627                && implicitSourceFilesRead
1628                && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
1629            if (explicitAnnotationProcessingRequested())
1630                log.warning("proc.use.implicit");
1631            else
1632                log.warning("proc.use.proc.or.implicit");
1633        }
1634        chk.reportDeferredDiagnostics();
1635        if (log.compressedOutput) {
1636            log.mandatoryNote(null, "compressed.diags");
1637        }
1638    }
1639
1640    /** Close the compiler, flushing the logs
1641     */
1642    public void close() {
1643        rootClasses = null;
1644        finder = null;
1645        reader = null;
1646        make = null;
1647        writer = null;
1648        enter = null;
1649        if (todo != null)
1650            todo.clear();
1651        todo = null;
1652        parserFactory = null;
1653        syms = null;
1654        source = null;
1655        attr = null;
1656        chk = null;
1657        gen = null;
1658        flow = null;
1659        transTypes = null;
1660        lower = null;
1661        annotate = null;
1662        types = null;
1663
1664        log.flush();
1665        try {
1666            fileManager.flush();
1667        } catch (IOException e) {
1668            throw new Abort(e);
1669        } finally {
1670            if (names != null)
1671                names.dispose();
1672            names = null;
1673
1674            for (Closeable c: closeables) {
1675                try {
1676                    c.close();
1677                } catch (IOException e) {
1678                    // When javac uses JDK 7 as a baseline, this code would be
1679                    // better written to set any/all exceptions from all the
1680                    // Closeables as suppressed exceptions on the FatalError
1681                    // that is thrown.
1682                    JCDiagnostic msg = diagFactory.fragment("fatal.err.cant.close");
1683                    throw new FatalError(msg, e);
1684                }
1685            }
1686            closeables = List.nil();
1687        }
1688    }
1689
1690    protected void printNote(String lines) {
1691        log.printRawLines(Log.WriterKind.NOTICE, lines);
1692    }
1693
1694    /** Print numbers of errors and warnings.
1695     */
1696    public void printCount(String kind, int count) {
1697        if (count != 0) {
1698            String key;
1699            if (count == 1)
1700                key = "count." + kind;
1701            else
1702                key = "count." + kind + ".plural";
1703            log.printLines(WriterKind.ERROR, key, String.valueOf(count));
1704            log.flush(Log.WriterKind.ERROR);
1705        }
1706    }
1707
1708    private static long now() {
1709        return System.currentTimeMillis();
1710    }
1711
1712    private static long elapsed(long then) {
1713        return now() - then;
1714    }
1715
1716    public void newRound() {
1717        inputFiles.clear();
1718        todo.clear();
1719    }
1720}
1721