Wed, 12 Aug 2009 10:34:13 -0700
6558476: com/sun/tools/javac/Main.compile don't release file handles on return
Reviewed-by: darcy
1 /*
2 * Copyright 1999-2009 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
26 package com.sun.tools.javac.main;
28 import java.io.*;
29 import java.util.HashSet;
30 import java.util.LinkedHashSet;
31 import java.util.LinkedHashMap;
32 import java.util.Map;
33 import java.util.MissingResourceException;
34 import java.util.ResourceBundle;
35 import java.util.Set;
36 import java.util.logging.Handler;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
40 import javax.tools.JavaFileManager;
41 import javax.tools.JavaFileObject;
42 import javax.tools.DiagnosticListener;
44 import com.sun.tools.javac.file.JavacFileManager;
45 import com.sun.source.util.TaskEvent;
46 import com.sun.source.util.TaskListener;
48 import com.sun.tools.javac.util.*;
49 import com.sun.tools.javac.code.*;
50 import com.sun.tools.javac.tree.*;
51 import com.sun.tools.javac.parser.*;
52 import com.sun.tools.javac.comp.*;
53 import com.sun.tools.javac.jvm.*;
55 import com.sun.tools.javac.code.Symbol.*;
56 import com.sun.tools.javac.tree.JCTree.*;
58 import com.sun.tools.javac.processing.*;
59 import javax.annotation.processing.Processor;
61 import static javax.tools.StandardLocation.CLASS_OUTPUT;
62 import static com.sun.tools.javac.util.ListBuffer.lb;
64 // TEMP, until we have a more efficient way to save doc comment info
65 import com.sun.tools.javac.parser.DocCommentScanner;
67 import java.util.HashMap;
68 import java.util.Queue;
69 import javax.lang.model.SourceVersion;
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 API supported by Sun Microsystems. If
77 * 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.resource.missing", System.getProperty("java.version"));
115 }
116 }
117 try {
118 return versionRB.getString(key);
119 }
120 catch (MissingResourceException e) {
121 return Log.getLocalizedString("version.unknown", System.getProperty("java.version"));
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 module for the symbol table entry phases.
234 */
235 protected Enter enter;
237 /** The symbol table.
238 */
239 protected Symtab syms;
241 /** The language version.
242 */
243 protected Source source;
245 /** The module for code generation.
246 */
247 protected Gen gen;
249 /** The name table.
250 */
251 protected Names names;
253 /** The attributor.
254 */
255 protected Attr attr;
257 /** The attributor.
258 */
259 protected Check chk;
261 /** The flow analyzer.
262 */
263 protected Flow flow;
265 /** The type eraser.
266 */
267 protected TransTypes transTypes;
269 /** The syntactic sugar desweetener.
270 */
271 protected Lower lower;
273 /** The annotation annotator.
274 */
275 protected Annotate annotate;
277 /** Force a completion failure on this name
278 */
279 protected final Name completionFailureName;
281 /** Type utilities.
282 */
283 protected Types types;
285 /** Access to file objects.
286 */
287 protected JavaFileManager fileManager;
289 /** Factory for parsers.
290 */
291 protected ParserFactory parserFactory;
293 /** Optional listener for progress events
294 */
295 protected TaskListener taskListener;
297 /**
298 * Annotation processing may require and provide a new instance
299 * of the compiler to be used for the analyze and generate phases.
300 */
301 protected JavaCompiler delegateCompiler;
303 /**
304 * Flag set if any annotation processing occurred.
305 **/
306 protected boolean annotationProcessingOccurred;
308 /**
309 * Flag set if any implicit source files read.
310 **/
311 protected boolean implicitSourceFilesRead;
313 protected Context context;
315 /** Construct a new compiler using a shared context.
316 */
317 public JavaCompiler(final Context context) {
318 this.context = context;
319 context.put(compilerKey, this);
321 // if fileManager not already set, register the JavacFileManager to be used
322 if (context.get(JavaFileManager.class) == null)
323 JavacFileManager.preRegister(context);
325 names = Names.instance(context);
326 log = Log.instance(context);
327 diagFactory = JCDiagnostic.Factory.instance(context);
328 reader = ClassReader.instance(context);
329 make = TreeMaker.instance(context);
330 writer = ClassWriter.instance(context);
331 enter = Enter.instance(context);
332 todo = Todo.instance(context);
334 fileManager = context.get(JavaFileManager.class);
335 parserFactory = ParserFactory.instance(context);
337 try {
338 // catch completion problems with predefineds
339 syms = Symtab.instance(context);
340 } catch (CompletionFailure ex) {
341 // inlined Check.completionError as it is not initialized yet
342 log.error("cant.access", ex.sym, ex.getDetailValue());
343 if (ex instanceof ClassReader.BadClassFile)
344 throw new Abort();
345 }
346 source = Source.instance(context);
347 attr = Attr.instance(context);
348 chk = Check.instance(context);
349 gen = Gen.instance(context);
350 flow = Flow.instance(context);
351 transTypes = TransTypes.instance(context);
352 lower = Lower.instance(context);
353 annotate = Annotate.instance(context);
354 types = Types.instance(context);
355 taskListener = context.get(TaskListener.class);
357 reader.sourceCompleter = this;
359 Options options = Options.instance(context);
361 verbose = options.get("-verbose") != null;
362 sourceOutput = options.get("-printsource") != null; // used to be -s
363 stubOutput = options.get("-stubs") != null;
364 relax = options.get("-relax") != null;
365 printFlat = options.get("-printflat") != null;
366 attrParseOnly = options.get("-attrparseonly") != null;
367 encoding = options.get("-encoding");
368 lineDebugInfo = options.get("-g:") == null ||
369 options.get("-g:lines") != null;
370 genEndPos = options.get("-Xjcov") != null ||
371 context.get(DiagnosticListener.class) != null;
372 devVerbose = options.get("dev") != null;
373 processPcks = options.get("process.packages") != null;
374 werror = options.get("-Werror") != null;
376 verboseCompilePolicy = options.get("verboseCompilePolicy") != null;
378 if (attrParseOnly)
379 compilePolicy = CompilePolicy.ATTR_ONLY;
380 else
381 compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
383 implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
385 completionFailureName =
386 (options.get("failcomplete") != null)
387 ? names.fromString(options.get("failcomplete"))
388 : null;
390 shouldStopPolicy =
391 (options.get("shouldStopPolicy") != null)
392 ? CompileState.valueOf(options.get("shouldStopPolicy"))
393 : null;
394 if (options.get("oldDiags") == null)
395 log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
396 }
398 /* Switches:
399 */
401 /** Verbose output.
402 */
403 public boolean verbose;
405 /** Emit plain Java source files rather than class files.
406 */
407 public boolean sourceOutput;
409 /** Emit stub source files rather than class files.
410 */
411 public boolean stubOutput;
413 /** Generate attributed parse tree only.
414 */
415 public boolean attrParseOnly;
417 /** Switch: relax some constraints for producing the jsr14 prototype.
418 */
419 boolean relax;
421 /** Debug switch: Emit Java sources after inner class flattening.
422 */
423 public boolean printFlat;
425 /** The encoding to be used for source input.
426 */
427 public String encoding;
429 /** Generate code with the LineNumberTable attribute for debugging
430 */
431 public boolean lineDebugInfo;
433 /** Switch: should we store the ending positions?
434 */
435 public boolean genEndPos;
437 /** Switch: should we debug ignored exceptions
438 */
439 protected boolean devVerbose;
441 /** Switch: should we (annotation) process packages as well
442 */
443 protected boolean processPcks;
445 /** Switch: treat warnings as errors
446 */
447 protected boolean werror;
449 /** Switch: is annotation processing requested explitly via
450 * CompilationTask.setProcessors?
451 */
452 protected boolean explicitAnnotationProcessingRequested = false;
454 /**
455 * The policy for the order in which to perform the compilation
456 */
457 protected CompilePolicy compilePolicy;
459 /**
460 * The policy for what to do with implicitly read source files
461 */
462 protected ImplicitSourcePolicy implicitSourcePolicy;
464 /**
465 * Report activity related to compilePolicy
466 */
467 public boolean verboseCompilePolicy;
469 /**
470 * Policy of how far to continue processing. null means until first
471 * error.
472 */
473 public CompileState shouldStopPolicy;
475 /** A queue of all as yet unattributed classes.
476 */
477 public Todo todo;
479 /** Ordered list of compiler phases for each compilation unit. */
480 public enum CompileState {
481 PARSE(1),
482 ENTER(2),
483 PROCESS(3),
484 ATTR(4),
485 FLOW(5),
486 TRANSTYPES(6),
487 LOWER(7),
488 GENERATE(8);
489 CompileState(int value) {
490 this.value = value;
491 }
492 boolean isDone(CompileState other) {
493 return value >= other.value;
494 }
495 private int value;
496 };
497 /** Partial map to record which compiler phases have been executed
498 * for each compilation unit. Used for ATTR and FLOW phases.
499 */
500 protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
501 private static final long serialVersionUID = 1812267524140424433L;
502 boolean isDone(Env<AttrContext> env, CompileState cs) {
503 CompileState ecs = get(env);
504 return ecs != null && ecs.isDone(cs);
505 }
506 }
507 private CompileStates compileStates = new CompileStates();
509 /** The set of currently compiled inputfiles, needed to ensure
510 * we don't accidentally overwrite an input file when -s is set.
511 * initialized by `compile'.
512 */
513 protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
515 protected boolean shouldStop(CompileState cs) {
516 if (shouldStopPolicy == null)
517 return (errorCount() > 0);
518 else
519 return cs.ordinal() > shouldStopPolicy.ordinal();
520 }
522 /** The number of errors reported so far.
523 */
524 public int errorCount() {
525 if (delegateCompiler != null && delegateCompiler != this)
526 return delegateCompiler.errorCount();
527 else {
528 if (werror && log.nerrors == 0 && log.nwarnings > 0) {
529 log.error("warnings.and.werror");
530 }
531 }
532 return log.nerrors;
533 }
535 protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
536 return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
537 }
539 protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
540 return shouldStop(cs) ? List.<T>nil() : list;
541 }
543 /** The number of warnings reported so far.
544 */
545 public int warningCount() {
546 if (delegateCompiler != null && delegateCompiler != this)
547 return delegateCompiler.warningCount();
548 else
549 return log.nwarnings;
550 }
552 /** Whether or not any parse errors have occurred.
553 */
554 public boolean parseErrors() {
555 return parseErrors;
556 }
558 /** Try to open input stream with given name.
559 * Report an error if this fails.
560 * @param filename The file name of the input stream to be opened.
561 */
562 public CharSequence readSource(JavaFileObject filename) {
563 try {
564 inputFiles.add(filename);
565 return filename.getCharContent(false);
566 } catch (IOException e) {
567 log.error("error.reading.file", filename, e.getLocalizedMessage());
568 return null;
569 }
570 }
572 /** Parse contents of input stream.
573 * @param filename The name of the file from which input stream comes.
574 * @param input The input stream to be parsed.
575 */
576 protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
577 long msec = now();
578 JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
579 null, List.<JCTree>nil());
580 if (content != null) {
581 if (verbose) {
582 printVerbose("parsing.started", filename);
583 }
584 if (taskListener != null) {
585 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
586 taskListener.started(e);
587 }
588 int initialErrorCount = log.nerrors;
589 Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
590 tree = parser.parseCompilationUnit();
591 parseErrors |= (log.nerrors > initialErrorCount);
592 if (verbose) {
593 printVerbose("parsing.done", Long.toString(elapsed(msec)));
594 }
595 }
597 tree.sourcefile = filename;
599 if (content != null && taskListener != null) {
600 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
601 taskListener.finished(e);
602 }
604 return tree;
605 }
606 // where
607 public boolean keepComments = false;
608 protected boolean keepComments() {
609 return keepComments || sourceOutput || stubOutput;
610 }
613 /** Parse contents of file.
614 * @param filename The name of the file to be parsed.
615 */
616 @Deprecated
617 public JCTree.JCCompilationUnit parse(String filename) throws IOException {
618 JavacFileManager fm = (JavacFileManager)fileManager;
619 return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
620 }
622 /** Parse contents of file.
623 * @param filename The name of the file to be parsed.
624 */
625 public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
626 JavaFileObject prev = log.useSource(filename);
627 try {
628 JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
629 if (t.endPositions != null)
630 log.setEndPosTable(filename, t.endPositions);
631 return t;
632 } finally {
633 log.useSource(prev);
634 }
635 }
637 /** Resolve an identifier.
638 * @param name The identifier to resolve
639 */
640 public Symbol resolveIdent(String name) {
641 if (name.equals(""))
642 return syms.errSymbol;
643 JavaFileObject prev = log.useSource(null);
644 try {
645 JCExpression tree = null;
646 for (String s : name.split("\\.", -1)) {
647 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
648 return syms.errSymbol;
649 tree = (tree == null) ? make.Ident(names.fromString(s))
650 : make.Select(tree, names.fromString(s));
651 }
652 JCCompilationUnit toplevel =
653 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
654 toplevel.packge = syms.unnamedPackage;
655 return attr.attribIdent(tree, toplevel);
656 } finally {
657 log.useSource(prev);
658 }
659 }
661 /** Emit plain Java source for a class.
662 * @param env The attribution environment of the outermost class
663 * containing this class.
664 * @param cdef The class definition to be printed.
665 */
666 JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
667 JavaFileObject outFile
668 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
669 cdef.sym.flatname.toString(),
670 JavaFileObject.Kind.SOURCE,
671 null);
672 if (inputFiles.contains(outFile)) {
673 log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
674 return null;
675 } else {
676 BufferedWriter out = new BufferedWriter(outFile.openWriter());
677 try {
678 new Pretty(out, true).printUnit(env.toplevel, cdef);
679 if (verbose)
680 printVerbose("wrote.file", outFile);
681 } finally {
682 out.close();
683 }
684 return outFile;
685 }
686 }
688 /** Generate code and emit a class file for a given class
689 * @param env The attribution environment of the outermost class
690 * containing this class.
691 * @param cdef The class definition from which code is generated.
692 */
693 JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
694 try {
695 if (gen.genClass(env, cdef) && (errorCount() == 0))
696 return writer.writeClass(cdef.sym);
697 } catch (ClassWriter.PoolOverflow ex) {
698 log.error(cdef.pos(), "limit.pool");
699 } catch (ClassWriter.StringOverflow ex) {
700 log.error(cdef.pos(), "limit.string.overflow",
701 ex.value.substring(0, 20));
702 } catch (CompletionFailure ex) {
703 chk.completionError(cdef.pos(), ex);
704 }
705 return null;
706 }
708 /** Complete compiling a source file that has been accessed
709 * by the class file reader.
710 * @param c The class the source file of which needs to be compiled.
711 * @param filename The name of the source file.
712 * @param f An input stream that reads the source file.
713 */
714 public void complete(ClassSymbol c) throws CompletionFailure {
715 // System.err.println("completing " + c);//DEBUG
716 if (completionFailureName == c.fullname) {
717 throw new CompletionFailure(c, "user-selected completion failure by class name");
718 }
719 JCCompilationUnit tree;
720 JavaFileObject filename = c.classfile;
721 JavaFileObject prev = log.useSource(filename);
723 try {
724 tree = parse(filename, filename.getCharContent(false));
725 } catch (IOException e) {
726 log.error("error.reading.file", filename, e);
727 tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
728 } finally {
729 log.useSource(prev);
730 }
732 if (taskListener != null) {
733 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
734 taskListener.started(e);
735 }
737 enter.complete(List.of(tree), c);
739 if (taskListener != null) {
740 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
741 taskListener.finished(e);
742 }
744 if (enter.getEnv(c) == null) {
745 boolean isPkgInfo =
746 tree.sourcefile.isNameCompatible("package-info",
747 JavaFileObject.Kind.SOURCE);
748 if (isPkgInfo) {
749 if (enter.getEnv(tree.packge) == null) {
750 JCDiagnostic diag =
751 diagFactory.fragment("file.does.not.contain.package",
752 c.location());
753 throw reader.new BadClassFile(c, filename, diag);
754 }
755 } else {
756 JCDiagnostic diag =
757 diagFactory.fragment("file.doesnt.contain.class",
758 c.getQualifiedName());
759 throw reader.new BadClassFile(c, filename, diag);
760 }
761 }
763 implicitSourceFilesRead = true;
764 }
766 /** Track when the JavaCompiler has been used to compile something. */
767 private boolean hasBeenUsed = false;
768 private long start_msec = 0;
769 public long elapsed_msec = 0;
771 /** Track whether any errors occurred while parsing source text. */
772 private boolean parseErrors = false;
774 public void compile(List<JavaFileObject> sourceFileObject)
775 throws Throwable {
776 compile(sourceFileObject, List.<String>nil(), null);
777 }
779 /**
780 * Main method: compile a list of files, return all compiled classes
781 *
782 * @param sourceFileObjects file objects to be compiled
783 * @param classnames class names to process for annotations
784 * @param processors user provided annotation processors to bypass
785 * discovery, {@code null} means that no processors were provided
786 */
787 public void compile(List<JavaFileObject> sourceFileObjects,
788 List<String> classnames,
789 Iterable<? extends Processor> processors)
790 throws IOException // TODO: temp, from JavacProcessingEnvironment
791 {
792 if (processors != null && processors.iterator().hasNext())
793 explicitAnnotationProcessingRequested = true;
794 // as a JavaCompiler can only be used once, throw an exception if
795 // it has been used before.
796 if (hasBeenUsed)
797 throw new AssertionError("attempt to reuse JavaCompiler");
798 hasBeenUsed = true;
800 start_msec = now();
801 try {
802 initProcessAnnotations(processors);
804 // These method calls must be chained to avoid memory leaks
805 delegateCompiler =
806 processAnnotations(
807 enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
808 classnames);
810 delegateCompiler.compile2();
811 delegateCompiler.close();
812 elapsed_msec = delegateCompiler.elapsed_msec;
813 } catch (Abort ex) {
814 if (devVerbose)
815 ex.printStackTrace();
816 } finally {
817 if (procEnvImpl != null)
818 procEnvImpl.close();
819 }
820 }
822 /**
823 * The phases following annotation processing: attribution,
824 * desugar, and finally code generation.
825 */
826 private void compile2() {
827 try {
828 switch (compilePolicy) {
829 case ATTR_ONLY:
830 attribute(todo);
831 break;
833 case CHECK_ONLY:
834 flow(attribute(todo));
835 break;
837 case SIMPLE:
838 generate(desugar(flow(attribute(todo))));
839 break;
841 case BY_FILE: {
842 Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
843 while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
844 generate(desugar(flow(attribute(q.remove()))));
845 }
846 }
847 break;
849 case BY_TODO:
850 while (!todo.isEmpty())
851 generate(desugar(flow(attribute(todo.remove()))));
852 break;
854 default:
855 assert false: "unknown compile policy";
856 }
857 } catch (Abort ex) {
858 if (devVerbose)
859 ex.printStackTrace();
860 }
862 if (verbose) {
863 elapsed_msec = elapsed(start_msec);
864 printVerbose("total", Long.toString(elapsed_msec));
865 }
867 reportDeferredDiagnostics();
869 if (!log.hasDiagnosticListener()) {
870 printCount("error", errorCount());
871 printCount("warn", warningCount());
872 }
873 }
875 private List<JCClassDecl> rootClasses;
877 /**
878 * Parses a list of files.
879 */
880 public List<JCCompilationUnit> parseFiles(List<JavaFileObject> fileObjects) throws IOException {
881 if (shouldStop(CompileState.PARSE))
882 return List.nil();
884 //parse all files
885 ListBuffer<JCCompilationUnit> trees = lb();
886 for (JavaFileObject fileObject : fileObjects)
887 trees.append(parse(fileObject));
888 return trees.toList();
889 }
891 /**
892 * Enter the symbols found in a list of parse trees.
893 * As a side-effect, this puts elements on the "todo" list.
894 * Also stores a list of all top level classes in rootClasses.
895 */
896 public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
897 //enter symbols for all files
898 if (taskListener != null) {
899 for (JCCompilationUnit unit: roots) {
900 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
901 taskListener.started(e);
902 }
903 }
905 enter.main(roots);
907 if (taskListener != null) {
908 for (JCCompilationUnit unit: roots) {
909 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
910 taskListener.finished(e);
911 }
912 }
914 //If generating source, remember the classes declared in
915 //the original compilation units listed on the command line.
916 if (sourceOutput || stubOutput) {
917 ListBuffer<JCClassDecl> cdefs = lb();
918 for (JCCompilationUnit unit : roots) {
919 for (List<JCTree> defs = unit.defs;
920 defs.nonEmpty();
921 defs = defs.tail) {
922 if (defs.head instanceof JCClassDecl)
923 cdefs.append((JCClassDecl)defs.head);
924 }
925 }
926 rootClasses = cdefs.toList();
927 }
928 return roots;
929 }
931 /**
932 * Set to true to enable skeleton annotation processing code.
933 * Currently, we assume this variable will be replaced more
934 * advanced logic to figure out if annotation processing is
935 * needed.
936 */
937 boolean processAnnotations = false;
939 /**
940 * Object to handle annotation processing.
941 */
942 private JavacProcessingEnvironment procEnvImpl = null;
944 /**
945 * Check if we should process annotations.
946 * If so, and if no scanner is yet registered, then set up the DocCommentScanner
947 * to catch doc comments, and set keepComments so the parser records them in
948 * the compilation unit.
949 *
950 * @param processors user provided annotation processors to bypass
951 * discovery, {@code null} means that no processors were provided
952 */
953 public void initProcessAnnotations(Iterable<? extends Processor> processors)
954 throws IOException {
955 // Process annotations if processing is not disabled and there
956 // is at least one Processor available.
957 Options options = Options.instance(context);
958 if (options.get("-proc:none") != null) {
959 processAnnotations = false;
960 } else if (procEnvImpl == null) {
961 procEnvImpl = new JavacProcessingEnvironment(context, processors);
962 processAnnotations = procEnvImpl.atLeastOneProcessor();
964 if (processAnnotations) {
965 if (context.get(Scanner.Factory.scannerFactoryKey) == null)
966 DocCommentScanner.Factory.preRegister(context);
967 options.put("save-parameter-names", "save-parameter-names");
968 reader.saveParameterNames = true;
969 keepComments = true;
970 if (taskListener != null)
971 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
974 } else { // free resources
975 procEnvImpl.close();
976 }
977 }
978 }
980 // TODO: called by JavacTaskImpl
981 public JavaCompiler processAnnotations(List<JCCompilationUnit> roots)
982 throws IOException {
983 return processAnnotations(roots, List.<String>nil());
984 }
986 /**
987 * Process any anotations found in the specifed compilation units.
988 * @param roots a list of compilation units
989 * @return an instance of the compiler in which to complete the compilation
990 */
991 public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
992 List<String> classnames)
993 throws IOException { // TODO: see TEMP note in JavacProcessingEnvironment
994 if (shouldStop(CompileState.PROCESS)) {
995 // Errors were encountered. If todo is empty, then the
996 // encountered errors were parse errors. Otherwise, the
997 // errors were found during the enter phase which should
998 // be ignored when processing annotations.
1000 if (todo.isEmpty())
1001 return this;
1002 }
1004 // ASSERT: processAnnotations and procEnvImpl should have been set up by
1005 // by initProcessAnnotations
1007 // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
1009 if (!processAnnotations) {
1010 // If there are no annotation processors present, and
1011 // annotation processing is to occur with compilation,
1012 // emit a warning.
1013 Options options = Options.instance(context);
1014 if (options.get("-proc:only") != null) {
1015 log.warning("proc.proc-only.requested.no.procs");
1016 todo.clear();
1017 }
1018 // If not processing annotations, classnames must be empty
1019 if (!classnames.isEmpty()) {
1020 log.error("proc.no.explicit.annotation.processing.requested",
1021 classnames);
1022 }
1023 return this; // continue regular compilation
1024 }
1026 try {
1027 List<ClassSymbol> classSymbols = List.nil();
1028 List<PackageSymbol> pckSymbols = List.nil();
1029 if (!classnames.isEmpty()) {
1030 // Check for explicit request for annotation
1031 // processing
1032 if (!explicitAnnotationProcessingRequested()) {
1033 log.error("proc.no.explicit.annotation.processing.requested",
1034 classnames);
1035 return this; // TODO: Will this halt compilation?
1036 } else {
1037 boolean errors = false;
1038 for (String nameStr : classnames) {
1039 Symbol sym = resolveIdent(nameStr);
1040 if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
1041 log.error("proc.cant.find.class", nameStr);
1042 errors = true;
1043 continue;
1044 }
1045 try {
1046 if (sym.kind == Kinds.PCK)
1047 sym.complete();
1048 if (sym.exists()) {
1049 Name name = names.fromString(nameStr);
1050 if (sym.kind == Kinds.PCK)
1051 pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1052 else
1053 classSymbols = classSymbols.prepend((ClassSymbol)sym);
1054 continue;
1055 }
1056 assert sym.kind == Kinds.PCK;
1057 log.warning("proc.package.does.not.exist", nameStr);
1058 pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1059 } catch (CompletionFailure e) {
1060 log.error("proc.cant.find.class", nameStr);
1061 errors = true;
1062 continue;
1063 }
1064 }
1065 if (errors)
1066 return this;
1067 }
1068 }
1069 try {
1070 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
1071 if (c != this)
1072 annotationProcessingOccurred = c.annotationProcessingOccurred = true;
1073 return c;
1074 } finally {
1075 procEnvImpl.close();
1076 }
1077 } catch (CompletionFailure ex) {
1078 log.error("cant.access", ex.sym, ex.getDetailValue());
1079 return this;
1081 }
1082 }
1084 boolean explicitAnnotationProcessingRequested() {
1085 Options options = Options.instance(context);
1086 return
1087 explicitAnnotationProcessingRequested ||
1088 options.get("-processor") != null ||
1089 options.get("-processorpath") != null ||
1090 options.get("-proc:only") != null ||
1091 options.get("-Xprint") != null;
1092 }
1094 /**
1095 * Attribute a list of parse trees, such as found on the "todo" list.
1096 * Note that attributing classes may cause additional files to be
1097 * parsed and entered via the SourceCompleter.
1098 * Attribution of the entries in the list does not stop if any errors occur.
1099 * @returns a list of environments for attributd classes.
1100 */
1101 public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
1102 ListBuffer<Env<AttrContext>> results = lb();
1103 while (!envs.isEmpty())
1104 results.append(attribute(envs.remove()));
1105 return stopIfError(CompileState.ATTR, results);
1106 }
1108 /**
1109 * Attribute a parse tree.
1110 * @returns the attributed parse tree
1111 */
1112 public Env<AttrContext> attribute(Env<AttrContext> env) {
1113 if (compileStates.isDone(env, CompileState.ATTR))
1114 return env;
1116 if (verboseCompilePolicy)
1117 log.printLines(log.noticeWriter, "[attribute " + env.enclClass.sym + "]");
1118 if (verbose)
1119 printVerbose("checking.attribution", env.enclClass.sym);
1121 if (taskListener != null) {
1122 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1123 taskListener.started(e);
1124 }
1126 JavaFileObject prev = log.useSource(
1127 env.enclClass.sym.sourcefile != null ?
1128 env.enclClass.sym.sourcefile :
1129 env.toplevel.sourcefile);
1130 try {
1131 attr.attribClass(env.tree.pos(), env.enclClass.sym);
1132 compileStates.put(env, CompileState.ATTR);
1133 }
1134 finally {
1135 log.useSource(prev);
1136 }
1138 return env;
1139 }
1141 /**
1142 * Perform dataflow checks on attributed parse trees.
1143 * These include checks for definite assignment and unreachable statements.
1144 * If any errors occur, an empty list will be returned.
1145 * @returns the list of attributed parse trees
1146 */
1147 public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
1148 ListBuffer<Env<AttrContext>> results = lb();
1149 for (Env<AttrContext> env: envs) {
1150 flow(env, results);
1151 }
1152 return stopIfError(CompileState.FLOW, results);
1153 }
1155 /**
1156 * Perform dataflow checks on an attributed parse tree.
1157 */
1158 public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
1159 ListBuffer<Env<AttrContext>> results = lb();
1160 flow(env, results);
1161 return stopIfError(CompileState.FLOW, results);
1162 }
1164 /**
1165 * Perform dataflow checks on an attributed parse tree.
1166 */
1167 protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
1168 try {
1169 if (shouldStop(CompileState.FLOW))
1170 return;
1172 if (relax || compileStates.isDone(env, CompileState.FLOW)) {
1173 results.add(env);
1174 return;
1175 }
1177 if (verboseCompilePolicy)
1178 printNote("[flow " + env.enclClass.sym + "]");
1179 JavaFileObject prev = log.useSource(
1180 env.enclClass.sym.sourcefile != null ?
1181 env.enclClass.sym.sourcefile :
1182 env.toplevel.sourcefile);
1183 try {
1184 make.at(Position.FIRSTPOS);
1185 TreeMaker localMake = make.forToplevel(env.toplevel);
1186 flow.analyzeTree(env.tree, localMake);
1187 compileStates.put(env, CompileState.FLOW);
1189 if (shouldStop(CompileState.FLOW))
1190 return;
1192 results.add(env);
1193 }
1194 finally {
1195 log.useSource(prev);
1196 }
1197 }
1198 finally {
1199 if (taskListener != null) {
1200 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1201 taskListener.finished(e);
1202 }
1203 }
1204 }
1206 /**
1207 * Prepare attributed parse trees, in conjunction with their attribution contexts,
1208 * for source or code generation.
1209 * If any errors occur, an empty list will be returned.
1210 * @returns a list containing the classes to be generated
1211 */
1212 public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
1213 ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
1214 for (Env<AttrContext> env: envs)
1215 desugar(env, results);
1216 return stopIfError(CompileState.FLOW, results);
1217 }
1219 HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
1220 new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
1222 /**
1223 * Prepare attributed parse trees, in conjunction with their attribution contexts,
1224 * for source or code generation. If the file was not listed on the command line,
1225 * the current implicitSourcePolicy is taken into account.
1226 * The preparation stops as soon as an error is found.
1227 */
1228 protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
1229 if (shouldStop(CompileState.TRANSTYPES))
1230 return;
1232 if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
1233 && !inputFiles.contains(env.toplevel.sourcefile)) {
1234 return;
1235 }
1237 if (compileStates.isDone(env, CompileState.LOWER)) {
1238 results.addAll(desugaredEnvs.get(env));
1239 return;
1240 }
1242 /**
1243 * Ensure that superclasses of C are desugared before C itself. This is
1244 * required for two reasons: (i) as erasure (TransTypes) destroys
1245 * information needed in flow analysis and (ii) as some checks carried
1246 * out during lowering require that all synthetic fields/methods have
1247 * already been added to C and its superclasses.
1248 */
1249 class ScanNested extends TreeScanner {
1250 Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
1251 @Override
1252 public void visitClassDef(JCClassDecl node) {
1253 Type st = types.supertype(node.sym.type);
1254 if (st.tag == TypeTags.CLASS) {
1255 ClassSymbol c = st.tsym.outermostClass();
1256 Env<AttrContext> stEnv = enter.getEnv(c);
1257 if (stEnv != null && env != stEnv) {
1258 if (dependencies.add(stEnv))
1259 scan(stEnv.tree);
1260 }
1261 }
1262 super.visitClassDef(node);
1263 }
1264 }
1265 ScanNested scanner = new ScanNested();
1266 scanner.scan(env.tree);
1267 for (Env<AttrContext> dep: scanner.dependencies) {
1268 if (!compileStates.isDone(dep, CompileState.FLOW))
1269 desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
1270 }
1272 //We need to check for error another time as more classes might
1273 //have been attributed and analyzed at this stage
1274 if (shouldStop(CompileState.TRANSTYPES))
1275 return;
1277 if (verboseCompilePolicy)
1278 printNote("[desugar " + env.enclClass.sym + "]");
1280 JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1281 env.enclClass.sym.sourcefile :
1282 env.toplevel.sourcefile);
1283 try {
1284 //save tree prior to rewriting
1285 JCTree untranslated = env.tree;
1287 make.at(Position.FIRSTPOS);
1288 TreeMaker localMake = make.forToplevel(env.toplevel);
1290 if (env.tree instanceof JCCompilationUnit) {
1291 if (!(stubOutput || sourceOutput || printFlat)) {
1292 if (shouldStop(CompileState.LOWER))
1293 return;
1294 List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
1295 if (pdef.head != null) {
1296 assert pdef.tail.isEmpty();
1297 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
1298 }
1299 }
1300 return;
1301 }
1303 if (stubOutput) {
1304 //emit stub Java source file, only for compilation
1305 //units enumerated explicitly on the command line
1306 JCClassDecl cdef = (JCClassDecl)env.tree;
1307 if (untranslated instanceof JCClassDecl &&
1308 rootClasses.contains((JCClassDecl)untranslated) &&
1309 ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1310 cdef.sym.packge().getQualifiedName() == names.java_lang)) {
1311 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
1312 }
1313 return;
1314 }
1316 if (shouldStop(CompileState.TRANSTYPES))
1317 return;
1319 env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
1320 compileStates.put(env, CompileState.TRANSTYPES);
1322 if (shouldStop(CompileState.LOWER))
1323 return;
1325 if (sourceOutput) {
1326 //emit standard Java source file, only for compilation
1327 //units enumerated explicitly on the command line
1328 JCClassDecl cdef = (JCClassDecl)env.tree;
1329 if (untranslated instanceof JCClassDecl &&
1330 rootClasses.contains((JCClassDecl)untranslated)) {
1331 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
1332 }
1333 return;
1334 }
1336 //translate out inner classes
1337 List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
1338 compileStates.put(env, CompileState.LOWER);
1340 if (shouldStop(CompileState.LOWER))
1341 return;
1343 //generate code for each class
1344 for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
1345 JCClassDecl cdef = (JCClassDecl)l.head;
1346 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
1347 }
1348 }
1349 finally {
1350 log.useSource(prev);
1351 }
1353 }
1355 /** Generates the source or class file for a list of classes.
1356 * The decision to generate a source file or a class file is
1357 * based upon the compiler's options.
1358 * Generation stops if an error occurs while writing files.
1359 */
1360 public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
1361 generate(queue, null);
1362 }
1364 public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
1365 if (shouldStop(CompileState.GENERATE))
1366 return;
1368 boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
1370 for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
1371 Env<AttrContext> env = x.fst;
1372 JCClassDecl cdef = x.snd;
1374 if (verboseCompilePolicy) {
1375 printNote("[generate "
1376 + (usePrintSource ? " source" : "code")
1377 + " " + cdef.sym + "]");
1378 }
1380 if (taskListener != null) {
1381 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1382 taskListener.started(e);
1383 }
1385 JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1386 env.enclClass.sym.sourcefile :
1387 env.toplevel.sourcefile);
1388 try {
1389 JavaFileObject file;
1390 if (usePrintSource)
1391 file = printSource(env, cdef);
1392 else
1393 file = genCode(env, cdef);
1394 if (results != null && file != null)
1395 results.add(file);
1396 } catch (IOException ex) {
1397 log.error(cdef.pos(), "class.cant.write",
1398 cdef.sym, ex.getMessage());
1399 return;
1400 } finally {
1401 log.useSource(prev);
1402 }
1404 if (taskListener != null) {
1405 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1406 taskListener.finished(e);
1407 }
1408 }
1409 }
1411 // where
1412 Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
1413 // use a LinkedHashMap to preserve the order of the original list as much as possible
1414 Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
1415 for (Env<AttrContext> env: envs) {
1416 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
1417 if (sublist == null) {
1418 sublist = new ListBuffer<Env<AttrContext>>();
1419 map.put(env.toplevel, sublist);
1420 }
1421 sublist.add(env);
1422 }
1423 return map;
1424 }
1426 JCClassDecl removeMethodBodies(JCClassDecl cdef) {
1427 final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
1428 class MethodBodyRemover extends TreeTranslator {
1429 @Override
1430 public void visitMethodDef(JCMethodDecl tree) {
1431 tree.mods.flags &= ~Flags.SYNCHRONIZED;
1432 for (JCVariableDecl vd : tree.params)
1433 vd.mods.flags &= ~Flags.FINAL;
1434 tree.body = null;
1435 super.visitMethodDef(tree);
1436 }
1437 @Override
1438 public void visitVarDef(JCVariableDecl tree) {
1439 if (tree.init != null && tree.init.type.constValue() == null)
1440 tree.init = null;
1441 super.visitVarDef(tree);
1442 }
1443 @Override
1444 public void visitClassDef(JCClassDecl tree) {
1445 ListBuffer<JCTree> newdefs = lb();
1446 for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
1447 JCTree t = it.head;
1448 switch (t.getTag()) {
1449 case JCTree.CLASSDEF:
1450 if (isInterface ||
1451 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1452 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1453 newdefs.append(t);
1454 break;
1455 case JCTree.METHODDEF:
1456 if (isInterface ||
1457 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1458 ((JCMethodDecl) t).sym.name == names.init ||
1459 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1460 newdefs.append(t);
1461 break;
1462 case JCTree.VARDEF:
1463 if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1464 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1465 newdefs.append(t);
1466 break;
1467 default:
1468 break;
1469 }
1470 }
1471 tree.defs = newdefs.toList();
1472 super.visitClassDef(tree);
1473 }
1474 }
1475 MethodBodyRemover r = new MethodBodyRemover();
1476 return r.translate(cdef);
1477 }
1479 public void reportDeferredDiagnostics() {
1480 if (annotationProcessingOccurred
1481 && implicitSourceFilesRead
1482 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
1483 if (explicitAnnotationProcessingRequested())
1484 log.warning("proc.use.implicit");
1485 else
1486 log.warning("proc.use.proc.or.implicit");
1487 }
1488 chk.reportDeferredDiagnostics();
1489 }
1491 /** Close the compiler, flushing the logs
1492 */
1493 public void close() {
1494 close(true);
1495 }
1497 public void close(boolean disposeNames) {
1498 rootClasses = null;
1499 reader = null;
1500 make = null;
1501 writer = null;
1502 enter = null;
1503 if (todo != null)
1504 todo.clear();
1505 todo = null;
1506 parserFactory = null;
1507 syms = null;
1508 source = null;
1509 attr = null;
1510 chk = null;
1511 gen = null;
1512 flow = null;
1513 transTypes = null;
1514 lower = null;
1515 annotate = null;
1516 types = null;
1518 log.flush();
1519 try {
1520 fileManager.flush();
1521 } catch (IOException e) {
1522 throw new Abort(e);
1523 } finally {
1524 if (names != null && disposeNames)
1525 names.dispose();
1526 names = null;
1527 }
1528 }
1530 protected void printNote(String lines) {
1531 Log.printLines(log.noticeWriter, lines);
1532 }
1534 /** Output for "-verbose" option.
1535 * @param key The key to look up the correct internationalized string.
1536 * @param arg An argument for substitution into the output string.
1537 */
1538 protected void printVerbose(String key, Object arg) {
1539 Log.printLines(log.noticeWriter, Log.getLocalizedString("verbose." + key, arg));
1540 }
1542 /** Print numbers of errors and warnings.
1543 */
1544 protected void printCount(String kind, int count) {
1545 if (count != 0) {
1546 String text;
1547 if (count == 1)
1548 text = Log.getLocalizedString("count." + kind, String.valueOf(count));
1549 else
1550 text = Log.getLocalizedString("count." + kind + ".plural", String.valueOf(count));
1551 Log.printLines(log.errWriter, text);
1552 log.errWriter.flush();
1553 }
1554 }
1556 private static long now() {
1557 return System.currentTimeMillis();
1558 }
1560 private static long elapsed(long then) {
1561 return now() - then;
1562 }
1564 public void initRound(JavaCompiler prev) {
1565 keepComments = prev.keepComments;
1566 start_msec = prev.start_msec;
1567 hasBeenUsed = true;
1568 }
1570 public static void enableLogging() {
1571 Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
1572 logger.setLevel(Level.ALL);
1573 for (Handler h : logger.getParent().getHandlers()) {
1574 h.setLevel(Level.ALL);
1575 }
1577 }
1578 }