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