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