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