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