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