Tue, 12 Oct 2010 13:15:46 -0700
6988407: javac crashes running processor on errant code; it used to print error message
Reviewed-by: darcy
1 /*
2 * Copyright (c) 1999, 2010, 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.LinkedHashSet;
32 import java.util.LinkedHashMap;
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.JavaFileManager;
45 import javax.tools.JavaFileObject;
46 import javax.tools.DiagnosticListener;
48 import com.sun.source.util.TaskEvent;
49 import com.sun.source.util.TaskListener;
51 import com.sun.tools.javac.file.JavacFileManager;
52 import com.sun.tools.javac.util.*;
53 import com.sun.tools.javac.code.*;
54 import com.sun.tools.javac.code.Symbol.*;
55 import com.sun.tools.javac.tree.*;
56 import com.sun.tools.javac.tree.JCTree.*;
57 import com.sun.tools.javac.parser.*;
58 import com.sun.tools.javac.comp.*;
59 import com.sun.tools.javac.jvm.*;
60 import com.sun.tools.javac.processing.*;
62 import static javax.tools.StandardLocation.CLASS_OUTPUT;
63 import static com.sun.tools.javac.main.OptionName.*;
64 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
65 import static com.sun.tools.javac.util.ListBuffer.lb;
68 /** This class could be the main entry point for GJC when GJC is used as a
69 * component in a larger software system. It provides operations to
70 * construct a new compiler, and to run a new compiler on a set of source
71 * files.
72 *
73 * <p><b>This is NOT part of any supported API.
74 * If you write code that depends on this, you do so at your own risk.
75 * This code and its internal interfaces are subject to change or
76 * deletion without notice.</b>
77 */
78 public class JavaCompiler implements ClassReader.SourceCompleter {
79 /** The context key for the compiler. */
80 protected static final Context.Key<JavaCompiler> compilerKey =
81 new Context.Key<JavaCompiler>();
83 /** Get the JavaCompiler instance for this context. */
84 public static JavaCompiler instance(Context context) {
85 JavaCompiler instance = context.get(compilerKey);
86 if (instance == null)
87 instance = new JavaCompiler(context);
88 return instance;
89 }
91 /** The current version number as a string.
92 */
93 public static String version() {
94 return version("release"); // mm.nn.oo[-milestone]
95 }
97 /** The current full version number as a string.
98 */
99 public static String fullVersion() {
100 return version("full"); // mm.mm.oo[-milestone]-build
101 }
103 private static final String versionRBName = "com.sun.tools.javac.resources.version";
104 private static ResourceBundle versionRB;
106 private static String version(String key) {
107 if (versionRB == null) {
108 try {
109 versionRB = ResourceBundle.getBundle(versionRBName);
110 } catch (MissingResourceException e) {
111 return Log.getLocalizedString("version.not.available");
112 }
113 }
114 try {
115 return versionRB.getString(key);
116 }
117 catch (MissingResourceException e) {
118 return Log.getLocalizedString("version.not.available");
119 }
120 }
122 /**
123 * Control how the compiler's latter phases (attr, flow, desugar, generate)
124 * are connected. Each individual file is processed by each phase in turn,
125 * but with different compile policies, you can control the order in which
126 * each class is processed through its next phase.
127 *
128 * <p>Generally speaking, the compiler will "fail fast" in the face of
129 * errors, although not aggressively so. flow, desugar, etc become no-ops
130 * once any errors have occurred. No attempt is currently made to determine
131 * if it might be safe to process a class through its next phase because
132 * it does not depend on any unrelated errors that might have occurred.
133 */
134 protected static enum CompilePolicy {
135 /**
136 * Just attribute the parse trees.
137 */
138 ATTR_ONLY,
140 /**
141 * Just attribute and do flow analysis on the parse trees.
142 * This should catch most user errors.
143 */
144 CHECK_ONLY,
146 /**
147 * Attribute everything, then do flow analysis for everything,
148 * then desugar everything, and only then generate output.
149 * This means no output will be generated if there are any
150 * errors in any classes.
151 */
152 SIMPLE,
154 /**
155 * Groups the classes for each source file together, then process
156 * each group in a manner equivalent to the {@code SIMPLE} policy.
157 * This means no output will be generated if there are any
158 * errors in any of the classes in a source file.
159 */
160 BY_FILE,
162 /**
163 * Completely process each entry on the todo list in turn.
164 * -- this is the same for 1.5.
165 * Means output might be generated for some classes in a compilation unit
166 * and not others.
167 */
168 BY_TODO;
170 static CompilePolicy decode(String option) {
171 if (option == null)
172 return DEFAULT_COMPILE_POLICY;
173 else if (option.equals("attr"))
174 return ATTR_ONLY;
175 else if (option.equals("check"))
176 return CHECK_ONLY;
177 else if (option.equals("simple"))
178 return SIMPLE;
179 else if (option.equals("byfile"))
180 return BY_FILE;
181 else if (option.equals("bytodo"))
182 return BY_TODO;
183 else
184 return DEFAULT_COMPILE_POLICY;
185 }
186 }
188 private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
190 protected static enum ImplicitSourcePolicy {
191 /** Don't generate or process implicitly read source files. */
192 NONE,
193 /** Generate classes for implicitly read source files. */
194 CLASS,
195 /** Like CLASS, but generate warnings if annotation processing occurs */
196 UNSET;
198 static ImplicitSourcePolicy decode(String option) {
199 if (option == null)
200 return UNSET;
201 else if (option.equals("none"))
202 return NONE;
203 else if (option.equals("class"))
204 return CLASS;
205 else
206 return UNSET;
207 }
208 }
210 /** The log to be used for error reporting.
211 */
212 public Log log;
214 /** Factory for creating diagnostic objects
215 */
216 JCDiagnostic.Factory diagFactory;
218 /** The tree factory module.
219 */
220 protected TreeMaker make;
222 /** The class reader.
223 */
224 protected ClassReader reader;
226 /** The class writer.
227 */
228 protected ClassWriter writer;
230 /** The module for the symbol table entry phases.
231 */
232 protected Enter enter;
234 /** The symbol table.
235 */
236 protected Symtab syms;
238 /** The language version.
239 */
240 protected Source source;
242 /** The module for code generation.
243 */
244 protected Gen gen;
246 /** The name table.
247 */
248 protected Names names;
250 /** The attributor.
251 */
252 protected Attr attr;
254 /** The attributor.
255 */
256 protected Check chk;
258 /** The flow analyzer.
259 */
260 protected Flow flow;
262 /** The type eraser.
263 */
264 protected TransTypes transTypes;
266 /** The syntactic sugar desweetener.
267 */
268 protected Lower lower;
270 /** The annotation annotator.
271 */
272 protected Annotate annotate;
274 /** Force a completion failure on this name
275 */
276 protected final Name completionFailureName;
278 /** Type utilities.
279 */
280 protected Types types;
282 /** Access to file objects.
283 */
284 protected JavaFileManager fileManager;
286 /** Factory for parsers.
287 */
288 protected ParserFactory parserFactory;
290 /** Optional listener for progress events
291 */
292 protected TaskListener taskListener;
294 /**
295 * Annotation processing may require and provide a new instance
296 * of the compiler to be used for the analyze and generate phases.
297 */
298 protected JavaCompiler delegateCompiler;
300 /**
301 * Flag set if any annotation processing occurred.
302 **/
303 protected boolean annotationProcessingOccurred;
305 /**
306 * Flag set if any implicit source files read.
307 **/
308 protected boolean implicitSourceFilesRead;
310 protected Context context;
312 /** Construct a new compiler using a shared context.
313 */
314 public JavaCompiler(final Context context) {
315 this.context = context;
316 context.put(compilerKey, this);
318 // if fileManager not already set, register the JavacFileManager to be used
319 if (context.get(JavaFileManager.class) == null)
320 JavacFileManager.preRegister(context);
322 names = Names.instance(context);
323 log = Log.instance(context);
324 diagFactory = JCDiagnostic.Factory.instance(context);
325 reader = ClassReader.instance(context);
326 make = TreeMaker.instance(context);
327 writer = ClassWriter.instance(context);
328 enter = Enter.instance(context);
329 todo = Todo.instance(context);
331 fileManager = context.get(JavaFileManager.class);
332 parserFactory = ParserFactory.instance(context);
334 try {
335 // catch completion problems with predefineds
336 syms = Symtab.instance(context);
337 } catch (CompletionFailure ex) {
338 // inlined Check.completionError as it is not initialized yet
339 log.error("cant.access", ex.sym, ex.getDetailValue());
340 if (ex instanceof ClassReader.BadClassFile)
341 throw new Abort();
342 }
343 source = Source.instance(context);
344 attr = Attr.instance(context);
345 chk = Check.instance(context);
346 gen = Gen.instance(context);
347 flow = Flow.instance(context);
348 transTypes = TransTypes.instance(context);
349 lower = Lower.instance(context);
350 annotate = Annotate.instance(context);
351 types = Types.instance(context);
352 taskListener = context.get(TaskListener.class);
354 reader.sourceCompleter = this;
356 Options options = Options.instance(context);
358 verbose = options.isSet(VERBOSE);
359 sourceOutput = options.isSet(PRINTSOURCE); // used to be -s
360 stubOutput = options.isSet("-stubs");
361 relax = options.isSet("-relax");
362 printFlat = options.isSet("-printflat");
363 attrParseOnly = options.isSet("-attrparseonly");
364 encoding = options.get(ENCODING);
365 lineDebugInfo = options.isUnset(G_CUSTOM) ||
366 options.isSet(G_CUSTOM, "lines");
367 genEndPos = options.isSet(XJCOV) ||
368 context.get(DiagnosticListener.class) != null;
369 devVerbose = options.isSet("dev");
370 processPcks = options.isSet("process.packages");
371 werror = options.isSet(WERROR);
373 verboseCompilePolicy = options.isSet("verboseCompilePolicy");
375 if (attrParseOnly)
376 compilePolicy = CompilePolicy.ATTR_ONLY;
377 else
378 compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
380 implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
382 completionFailureName =
383 options.isSet("failcomplete")
384 ? names.fromString(options.get("failcomplete"))
385 : null;
387 shouldStopPolicy =
388 options.isSet("shouldStopPolicy")
389 ? CompileState.valueOf(options.get("shouldStopPolicy"))
390 : null;
391 if (options.isUnset("oldDiags"))
392 log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
393 }
395 /* Switches:
396 */
398 /** Verbose output.
399 */
400 public boolean verbose;
402 /** Emit plain Java source files rather than class files.
403 */
404 public boolean sourceOutput;
406 /** Emit stub source files rather than class files.
407 */
408 public boolean stubOutput;
410 /** Generate attributed parse tree only.
411 */
412 public boolean attrParseOnly;
414 /** Switch: relax some constraints for producing the jsr14 prototype.
415 */
416 boolean relax;
418 /** Debug switch: Emit Java sources after inner class flattening.
419 */
420 public boolean printFlat;
422 /** The encoding to be used for source input.
423 */
424 public String encoding;
426 /** Generate code with the LineNumberTable attribute for debugging
427 */
428 public boolean lineDebugInfo;
430 /** Switch: should we store the ending positions?
431 */
432 public boolean genEndPos;
434 /** Switch: should we debug ignored exceptions
435 */
436 protected boolean devVerbose;
438 /** Switch: should we (annotation) process packages as well
439 */
440 protected boolean processPcks;
442 /** Switch: treat warnings as errors
443 */
444 protected boolean werror;
446 /** Switch: is annotation processing requested explitly via
447 * CompilationTask.setProcessors?
448 */
449 protected boolean explicitAnnotationProcessingRequested = false;
451 /**
452 * The policy for the order in which to perform the compilation
453 */
454 protected CompilePolicy compilePolicy;
456 /**
457 * The policy for what to do with implicitly read source files
458 */
459 protected ImplicitSourcePolicy implicitSourcePolicy;
461 /**
462 * Report activity related to compilePolicy
463 */
464 public boolean verboseCompilePolicy;
466 /**
467 * Policy of how far to continue processing. null means until first
468 * error.
469 */
470 public CompileState shouldStopPolicy;
472 /** A queue of all as yet unattributed classes.
473 */
474 public Todo todo;
476 /** Ordered list of compiler phases for each compilation unit. */
477 public enum CompileState {
478 PARSE(1),
479 ENTER(2),
480 PROCESS(3),
481 ATTR(4),
482 FLOW(5),
483 TRANSTYPES(6),
484 LOWER(7),
485 GENERATE(8);
486 CompileState(int value) {
487 this.value = value;
488 }
489 boolean isDone(CompileState other) {
490 return value >= other.value;
491 }
492 private int value;
493 };
494 /** Partial map to record which compiler phases have been executed
495 * for each compilation unit. Used for ATTR and FLOW phases.
496 */
497 protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
498 private static final long serialVersionUID = 1812267524140424433L;
499 boolean isDone(Env<AttrContext> env, CompileState cs) {
500 CompileState ecs = get(env);
501 return ecs != null && ecs.isDone(cs);
502 }
503 }
504 private CompileStates compileStates = new CompileStates();
506 /** The set of currently compiled inputfiles, needed to ensure
507 * we don't accidentally overwrite an input file when -s is set.
508 * initialized by `compile'.
509 */
510 protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
512 protected boolean shouldStop(CompileState cs) {
513 if (shouldStopPolicy == null)
514 return (errorCount() > 0 || unrecoverableError());
515 else
516 return cs.ordinal() > shouldStopPolicy.ordinal();
517 }
519 /** The number of errors reported so far.
520 */
521 public int errorCount() {
522 if (delegateCompiler != null && delegateCompiler != this)
523 return delegateCompiler.errorCount();
524 else {
525 if (werror && log.nerrors == 0 && log.nwarnings > 0) {
526 log.error("warnings.and.werror");
527 }
528 }
529 return log.nerrors;
530 }
532 protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
533 return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
534 }
536 protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
537 return shouldStop(cs) ? List.<T>nil() : list;
538 }
540 /** The number of warnings reported so far.
541 */
542 public int warningCount() {
543 if (delegateCompiler != null && delegateCompiler != this)
544 return delegateCompiler.warningCount();
545 else
546 return log.nwarnings;
547 }
549 /** Try to open input stream with given name.
550 * Report an error if this fails.
551 * @param filename The file name of the input stream to be opened.
552 */
553 public CharSequence readSource(JavaFileObject filename) {
554 try {
555 inputFiles.add(filename);
556 return filename.getCharContent(false);
557 } catch (IOException e) {
558 log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
559 return null;
560 }
561 }
563 /** Parse contents of input stream.
564 * @param filename The name of the file from which input stream comes.
565 * @param input The input stream to be parsed.
566 */
567 protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
568 long msec = now();
569 JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
570 null, List.<JCTree>nil());
571 if (content != null) {
572 if (verbose) {
573 printVerbose("parsing.started", filename);
574 }
575 if (taskListener != null) {
576 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
577 taskListener.started(e);
578 }
579 Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
580 tree = parser.parseCompilationUnit();
581 if (verbose) {
582 printVerbose("parsing.done", Long.toString(elapsed(msec)));
583 }
584 }
586 tree.sourcefile = filename;
588 if (content != null && taskListener != null) {
589 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
590 taskListener.finished(e);
591 }
593 return tree;
594 }
595 // where
596 public boolean keepComments = false;
597 protected boolean keepComments() {
598 return keepComments || sourceOutput || stubOutput;
599 }
602 /** Parse contents of file.
603 * @param filename The name of the file to be parsed.
604 */
605 @Deprecated
606 public JCTree.JCCompilationUnit parse(String filename) {
607 JavacFileManager fm = (JavacFileManager)fileManager;
608 return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
609 }
611 /** Parse contents of file.
612 * @param filename The name of the file to be parsed.
613 */
614 public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
615 JavaFileObject prev = log.useSource(filename);
616 try {
617 JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
618 if (t.endPositions != null)
619 log.setEndPosTable(filename, t.endPositions);
620 return t;
621 } finally {
622 log.useSource(prev);
623 }
624 }
626 /** Resolve an identifier.
627 * @param name The identifier to resolve
628 */
629 public Symbol resolveIdent(String name) {
630 if (name.equals(""))
631 return syms.errSymbol;
632 JavaFileObject prev = log.useSource(null);
633 try {
634 JCExpression tree = null;
635 for (String s : name.split("\\.", -1)) {
636 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
637 return syms.errSymbol;
638 tree = (tree == null) ? make.Ident(names.fromString(s))
639 : make.Select(tree, names.fromString(s));
640 }
641 JCCompilationUnit toplevel =
642 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
643 toplevel.packge = syms.unnamedPackage;
644 return attr.attribIdent(tree, toplevel);
645 } finally {
646 log.useSource(prev);
647 }
648 }
650 /** Emit plain Java source for a class.
651 * @param env The attribution environment of the outermost class
652 * containing this class.
653 * @param cdef The class definition to be printed.
654 */
655 JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
656 JavaFileObject outFile
657 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
658 cdef.sym.flatname.toString(),
659 JavaFileObject.Kind.SOURCE,
660 null);
661 if (inputFiles.contains(outFile)) {
662 log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
663 return null;
664 } else {
665 BufferedWriter out = new BufferedWriter(outFile.openWriter());
666 try {
667 new Pretty(out, true).printUnit(env.toplevel, cdef);
668 if (verbose)
669 printVerbose("wrote.file", outFile);
670 } finally {
671 out.close();
672 }
673 return outFile;
674 }
675 }
677 /** Generate code and emit a class file for a given class
678 * @param env The attribution environment of the outermost class
679 * containing this class.
680 * @param cdef The class definition from which code is generated.
681 */
682 JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
683 try {
684 if (gen.genClass(env, cdef) && (errorCount() == 0))
685 return writer.writeClass(cdef.sym);
686 } catch (ClassWriter.PoolOverflow ex) {
687 log.error(cdef.pos(), "limit.pool");
688 } catch (ClassWriter.StringOverflow ex) {
689 log.error(cdef.pos(), "limit.string.overflow",
690 ex.value.substring(0, 20));
691 } catch (CompletionFailure ex) {
692 chk.completionError(cdef.pos(), ex);
693 }
694 return null;
695 }
697 /** Complete compiling a source file that has been accessed
698 * by the class file reader.
699 * @param c The class the source file of which needs to be compiled.
700 * @param filename The name of the source file.
701 * @param f An input stream that reads the source file.
702 */
703 public void complete(ClassSymbol c) throws CompletionFailure {
704 // System.err.println("completing " + c);//DEBUG
705 if (completionFailureName == c.fullname) {
706 throw new CompletionFailure(c, "user-selected completion failure by class name");
707 }
708 JCCompilationUnit tree;
709 JavaFileObject filename = c.classfile;
710 JavaFileObject prev = log.useSource(filename);
712 try {
713 tree = parse(filename, filename.getCharContent(false));
714 } catch (IOException e) {
715 log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
716 tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
717 } finally {
718 log.useSource(prev);
719 }
721 if (taskListener != null) {
722 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
723 taskListener.started(e);
724 }
726 enter.complete(List.of(tree), c);
728 if (taskListener != null) {
729 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
730 taskListener.finished(e);
731 }
733 if (enter.getEnv(c) == null) {
734 boolean isPkgInfo =
735 tree.sourcefile.isNameCompatible("package-info",
736 JavaFileObject.Kind.SOURCE);
737 if (isPkgInfo) {
738 if (enter.getEnv(tree.packge) == null) {
739 JCDiagnostic diag =
740 diagFactory.fragment("file.does.not.contain.package",
741 c.location());
742 throw reader.new BadClassFile(c, filename, diag);
743 }
744 } else {
745 JCDiagnostic diag =
746 diagFactory.fragment("file.doesnt.contain.class",
747 c.getQualifiedName());
748 throw reader.new BadClassFile(c, filename, diag);
749 }
750 }
752 implicitSourceFilesRead = true;
753 }
755 /** Track when the JavaCompiler has been used to compile something. */
756 private boolean hasBeenUsed = false;
757 private long start_msec = 0;
758 public long elapsed_msec = 0;
760 public void compile(List<JavaFileObject> sourceFileObject)
761 throws Throwable {
762 compile(sourceFileObject, List.<String>nil(), null);
763 }
765 /**
766 * Main method: compile a list of files, return all compiled classes
767 *
768 * @param sourceFileObjects file objects to be compiled
769 * @param classnames class names to process for annotations
770 * @param processors user provided annotation processors to bypass
771 * discovery, {@code null} means that no processors were provided
772 */
773 public void compile(List<JavaFileObject> sourceFileObjects,
774 List<String> classnames,
775 Iterable<? extends Processor> processors)
776 {
777 if (processors != null && processors.iterator().hasNext())
778 explicitAnnotationProcessingRequested = true;
779 // as a JavaCompiler can only be used once, throw an exception if
780 // it has been used before.
781 if (hasBeenUsed)
782 throw new AssertionError("attempt to reuse JavaCompiler");
783 hasBeenUsed = true;
785 start_msec = now();
786 try {
787 initProcessAnnotations(processors);
789 // These method calls must be chained to avoid memory leaks
790 delegateCompiler =
791 processAnnotations(
792 enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
793 classnames);
795 delegateCompiler.compile2();
796 delegateCompiler.close();
797 elapsed_msec = delegateCompiler.elapsed_msec;
798 } catch (Abort ex) {
799 if (devVerbose)
800 ex.printStackTrace();
801 } finally {
802 if (procEnvImpl != null)
803 procEnvImpl.close();
804 }
805 }
807 /**
808 * The phases following annotation processing: attribution,
809 * desugar, and finally code generation.
810 */
811 private void compile2() {
812 try {
813 switch (compilePolicy) {
814 case ATTR_ONLY:
815 attribute(todo);
816 break;
818 case CHECK_ONLY:
819 flow(attribute(todo));
820 break;
822 case SIMPLE:
823 generate(desugar(flow(attribute(todo))));
824 break;
826 case BY_FILE: {
827 Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
828 while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
829 generate(desugar(flow(attribute(q.remove()))));
830 }
831 }
832 break;
834 case BY_TODO:
835 while (!todo.isEmpty())
836 generate(desugar(flow(attribute(todo.remove()))));
837 break;
839 default:
840 assert false: "unknown compile policy";
841 }
842 } catch (Abort ex) {
843 if (devVerbose)
844 ex.printStackTrace();
845 }
847 if (verbose) {
848 elapsed_msec = elapsed(start_msec);
849 printVerbose("total", Long.toString(elapsed_msec));
850 }
852 reportDeferredDiagnostics();
854 if (!log.hasDiagnosticListener()) {
855 printCount("error", errorCount());
856 printCount("warn", warningCount());
857 }
858 }
860 private List<JCClassDecl> rootClasses;
862 /**
863 * Parses a list of files.
864 */
865 public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
866 if (shouldStop(CompileState.PARSE))
867 return List.nil();
869 //parse all files
870 ListBuffer<JCCompilationUnit> trees = lb();
871 Set<JavaFileObject> filesSoFar = new HashSet<JavaFileObject>();
872 for (JavaFileObject fileObject : fileObjects) {
873 if (!filesSoFar.contains(fileObject)) {
874 filesSoFar.add(fileObject);
875 trees.append(parse(fileObject));
876 }
877 }
878 return trees.toList();
879 }
881 /**
882 * Enter the symbols found in a list of parse trees.
883 * As a side-effect, this puts elements on the "todo" list.
884 * Also stores a list of all top level classes in rootClasses.
885 */
886 public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
887 //enter symbols for all files
888 if (taskListener != null) {
889 for (JCCompilationUnit unit: roots) {
890 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
891 taskListener.started(e);
892 }
893 }
895 enter.main(roots);
897 if (taskListener != null) {
898 for (JCCompilationUnit unit: roots) {
899 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
900 taskListener.finished(e);
901 }
902 }
904 //If generating source, remember the classes declared in
905 //the original compilation units listed on the command line.
906 if (sourceOutput || stubOutput) {
907 ListBuffer<JCClassDecl> cdefs = lb();
908 for (JCCompilationUnit unit : roots) {
909 for (List<JCTree> defs = unit.defs;
910 defs.nonEmpty();
911 defs = defs.tail) {
912 if (defs.head instanceof JCClassDecl)
913 cdefs.append((JCClassDecl)defs.head);
914 }
915 }
916 rootClasses = cdefs.toList();
917 }
919 // Ensure the input files have been recorded. Although this is normally
920 // done by readSource, it may not have been done if the trees were read
921 // in a prior round of annotation processing, and the trees have been
922 // cleaned and are being reused.
923 for (JCCompilationUnit unit : roots) {
924 inputFiles.add(unit.sourcefile);
925 }
927 return roots;
928 }
930 /**
931 * Set to true to enable skeleton annotation processing code.
932 * Currently, we assume this variable will be replaced more
933 * advanced logic to figure out if annotation processing is
934 * needed.
935 */
936 boolean processAnnotations = false;
938 /**
939 * Object to handle annotation processing.
940 */
941 private JavacProcessingEnvironment procEnvImpl = null;
943 /**
944 * Check if we should process annotations.
945 * If so, and if no scanner is yet registered, then set up the DocCommentScanner
946 * to catch doc comments, and set keepComments so the parser records them in
947 * the compilation unit.
948 *
949 * @param processors user provided annotation processors to bypass
950 * discovery, {@code null} means that no processors were provided
951 */
952 public void initProcessAnnotations(Iterable<? extends Processor> processors) {
953 // Process annotations if processing is not disabled and there
954 // is at least one Processor available.
955 Options options = Options.instance(context);
956 if (options.isSet(PROC, "none")) {
957 processAnnotations = false;
958 } else if (procEnvImpl == null) {
959 procEnvImpl = new JavacProcessingEnvironment(context, processors);
960 processAnnotations = procEnvImpl.atLeastOneProcessor();
962 if (processAnnotations) {
963 options.put("save-parameter-names", "save-parameter-names");
964 reader.saveParameterNames = true;
965 keepComments = true;
966 genEndPos = true;
967 if (taskListener != null)
968 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
969 log.deferDiagnostics = true;
970 } else { // free resources
971 procEnvImpl.close();
972 }
973 }
974 }
976 // TODO: called by JavacTaskImpl
977 public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) {
978 return processAnnotations(roots, List.<String>nil());
979 }
981 /**
982 * Process any anotations found in the specifed compilation units.
983 * @param roots a list of compilation units
984 * @return an instance of the compiler in which to complete the compilation
985 */
986 // Implementation note: when this method is called, log.deferredDiagnostics
987 // will have been set true by initProcessAnnotations, meaning that any diagnostics
988 // that are reported will go into the log.deferredDiagnostics queue.
989 // By the time this method exits, log.deferDiagnostics must be set back to false,
990 // and all deferredDiagnostics must have been handled: i.e. either reported
991 // or determined to be transient, and therefore suppressed.
992 public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
993 List<String> classnames) {
994 if (shouldStop(CompileState.PROCESS)) {
995 // Errors were encountered.
996 // Unless all the errors are resolve errors, the errors were parse errors
997 // or other errors during enter which cannot be fixed by running
998 // any annotation processors.
999 if (unrecoverableError()) {
1000 log.reportDeferredDiagnostics();
1001 return this;
1002 }
1003 }
1005 // ASSERT: processAnnotations and procEnvImpl should have been set up by
1006 // by initProcessAnnotations
1008 // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
1010 if (!processAnnotations) {
1011 // If there are no annotation processors present, and
1012 // annotation processing is to occur with compilation,
1013 // emit a warning.
1014 Options options = Options.instance(context);
1015 if (options.isSet(PROC, "only")) {
1016 log.warning("proc.proc-only.requested.no.procs");
1017 todo.clear();
1018 }
1019 // If not processing annotations, classnames must be empty
1020 if (!classnames.isEmpty()) {
1021 log.error("proc.no.explicit.annotation.processing.requested",
1022 classnames);
1023 }
1024 log.reportDeferredDiagnostics();
1025 return this; // continue regular compilation
1026 }
1028 try {
1029 List<ClassSymbol> classSymbols = List.nil();
1030 List<PackageSymbol> pckSymbols = List.nil();
1031 if (!classnames.isEmpty()) {
1032 // Check for explicit request for annotation
1033 // processing
1034 if (!explicitAnnotationProcessingRequested()) {
1035 log.error("proc.no.explicit.annotation.processing.requested",
1036 classnames);
1037 log.reportDeferredDiagnostics();
1038 return this; // TODO: Will this halt compilation?
1039 } else {
1040 boolean errors = false;
1041 for (String nameStr : classnames) {
1042 Symbol sym = resolveIdent(nameStr);
1043 if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
1044 log.error("proc.cant.find.class", nameStr);
1045 errors = true;
1046 continue;
1047 }
1048 try {
1049 if (sym.kind == Kinds.PCK)
1050 sym.complete();
1051 if (sym.exists()) {
1052 if (sym.kind == Kinds.PCK)
1053 pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1054 else
1055 classSymbols = classSymbols.prepend((ClassSymbol)sym);
1056 continue;
1057 }
1058 assert sym.kind == Kinds.PCK;
1059 log.warning("proc.package.does.not.exist", nameStr);
1060 pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1061 } catch (CompletionFailure e) {
1062 log.error("proc.cant.find.class", nameStr);
1063 errors = true;
1064 continue;
1065 }
1066 }
1067 if (errors) {
1068 log.reportDeferredDiagnostics();
1069 return this;
1070 }
1071 }
1072 }
1073 try {
1074 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
1075 if (c != this)
1076 annotationProcessingOccurred = c.annotationProcessingOccurred = true;
1077 // doProcessing will have handled deferred diagnostics
1078 assert c.log.deferDiagnostics == false;
1079 assert c.log.deferredDiagnostics.size() == 0;
1080 return c;
1081 } finally {
1082 procEnvImpl.close();
1083 }
1084 } catch (CompletionFailure ex) {
1085 log.error("cant.access", ex.sym, ex.getDetailValue());
1086 log.reportDeferredDiagnostics();
1087 return this;
1088 }
1089 }
1091 private boolean unrecoverableError() {
1092 for (JCDiagnostic d: log.deferredDiagnostics) {
1093 if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RESOLVE_ERROR))
1094 return true;
1095 }
1096 return false;
1097 }
1099 boolean explicitAnnotationProcessingRequested() {
1100 Options options = Options.instance(context);
1101 return
1102 explicitAnnotationProcessingRequested ||
1103 options.isSet(PROCESSOR) ||
1104 options.isSet(PROCESSORPATH) ||
1105 options.isSet(PROC, "only") ||
1106 options.isSet(XPRINT);
1107 }
1109 /**
1110 * Attribute a list of parse trees, such as found on the "todo" list.
1111 * Note that attributing classes may cause additional files to be
1112 * parsed and entered via the SourceCompleter.
1113 * Attribution of the entries in the list does not stop if any errors occur.
1114 * @returns a list of environments for attributd classes.
1115 */
1116 public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
1117 ListBuffer<Env<AttrContext>> results = lb();
1118 while (!envs.isEmpty())
1119 results.append(attribute(envs.remove()));
1120 return stopIfError(CompileState.ATTR, results);
1121 }
1123 /**
1124 * Attribute a parse tree.
1125 * @returns the attributed parse tree
1126 */
1127 public Env<AttrContext> attribute(Env<AttrContext> env) {
1128 if (compileStates.isDone(env, CompileState.ATTR))
1129 return env;
1131 if (verboseCompilePolicy)
1132 printNote("[attribute " + env.enclClass.sym + "]");
1133 if (verbose)
1134 printVerbose("checking.attribution", env.enclClass.sym);
1136 if (taskListener != null) {
1137 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1138 taskListener.started(e);
1139 }
1141 JavaFileObject prev = log.useSource(
1142 env.enclClass.sym.sourcefile != null ?
1143 env.enclClass.sym.sourcefile :
1144 env.toplevel.sourcefile);
1145 try {
1146 attr.attribClass(env.tree.pos(), env.enclClass.sym);
1147 if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
1148 //if in fail-over mode, ensure that AST expression nodes
1149 //are correctly initialized (e.g. they have a type/symbol)
1150 attr.postAttr(env);
1151 }
1152 compileStates.put(env, CompileState.ATTR);
1153 }
1154 finally {
1155 log.useSource(prev);
1156 }
1158 return env;
1159 }
1161 /**
1162 * Perform dataflow checks on attributed parse trees.
1163 * These include checks for definite assignment and unreachable statements.
1164 * If any errors occur, an empty list will be returned.
1165 * @returns the list of attributed parse trees
1166 */
1167 public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
1168 ListBuffer<Env<AttrContext>> results = lb();
1169 for (Env<AttrContext> env: envs) {
1170 flow(env, results);
1171 }
1172 return stopIfError(CompileState.FLOW, results);
1173 }
1175 /**
1176 * Perform dataflow checks on an attributed parse tree.
1177 */
1178 public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
1179 ListBuffer<Env<AttrContext>> results = lb();
1180 flow(env, results);
1181 return stopIfError(CompileState.FLOW, results);
1182 }
1184 /**
1185 * Perform dataflow checks on an attributed parse tree.
1186 */
1187 protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
1188 try {
1189 if (shouldStop(CompileState.FLOW))
1190 return;
1192 if (relax || compileStates.isDone(env, CompileState.FLOW)) {
1193 results.add(env);
1194 return;
1195 }
1197 if (verboseCompilePolicy)
1198 printNote("[flow " + env.enclClass.sym + "]");
1199 JavaFileObject prev = log.useSource(
1200 env.enclClass.sym.sourcefile != null ?
1201 env.enclClass.sym.sourcefile :
1202 env.toplevel.sourcefile);
1203 try {
1204 make.at(Position.FIRSTPOS);
1205 TreeMaker localMake = make.forToplevel(env.toplevel);
1206 flow.analyzeTree(env, localMake);
1207 compileStates.put(env, CompileState.FLOW);
1209 if (shouldStop(CompileState.FLOW))
1210 return;
1212 results.add(env);
1213 }
1214 finally {
1215 log.useSource(prev);
1216 }
1217 }
1218 finally {
1219 if (taskListener != null) {
1220 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1221 taskListener.finished(e);
1222 }
1223 }
1224 }
1226 /**
1227 * Prepare attributed parse trees, in conjunction with their attribution contexts,
1228 * for source or code generation.
1229 * If any errors occur, an empty list will be returned.
1230 * @returns a list containing the classes to be generated
1231 */
1232 public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
1233 ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
1234 for (Env<AttrContext> env: envs)
1235 desugar(env, results);
1236 return stopIfError(CompileState.FLOW, results);
1237 }
1239 HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
1240 new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
1242 /**
1243 * Prepare attributed parse trees, in conjunction with their attribution contexts,
1244 * for source or code generation. If the file was not listed on the command line,
1245 * the current implicitSourcePolicy is taken into account.
1246 * The preparation stops as soon as an error is found.
1247 */
1248 protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
1249 if (shouldStop(CompileState.TRANSTYPES))
1250 return;
1252 if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
1253 && !inputFiles.contains(env.toplevel.sourcefile)) {
1254 return;
1255 }
1257 if (compileStates.isDone(env, CompileState.LOWER)) {
1258 results.addAll(desugaredEnvs.get(env));
1259 return;
1260 }
1262 /**
1263 * Ensure that superclasses of C are desugared before C itself. This is
1264 * required for two reasons: (i) as erasure (TransTypes) destroys
1265 * information needed in flow analysis and (ii) as some checks carried
1266 * out during lowering require that all synthetic fields/methods have
1267 * already been added to C and its superclasses.
1268 */
1269 class ScanNested extends TreeScanner {
1270 Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
1271 @Override
1272 public void visitClassDef(JCClassDecl node) {
1273 Type st = types.supertype(node.sym.type);
1274 if (st.tag == TypeTags.CLASS) {
1275 ClassSymbol c = st.tsym.outermostClass();
1276 Env<AttrContext> stEnv = enter.getEnv(c);
1277 if (stEnv != null && env != stEnv) {
1278 if (dependencies.add(stEnv))
1279 scan(stEnv.tree);
1280 }
1281 }
1282 super.visitClassDef(node);
1283 }
1284 }
1285 ScanNested scanner = new ScanNested();
1286 scanner.scan(env.tree);
1287 for (Env<AttrContext> dep: scanner.dependencies) {
1288 if (!compileStates.isDone(dep, CompileState.FLOW))
1289 desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
1290 }
1292 //We need to check for error another time as more classes might
1293 //have been attributed and analyzed at this stage
1294 if (shouldStop(CompileState.TRANSTYPES))
1295 return;
1297 if (verboseCompilePolicy)
1298 printNote("[desugar " + env.enclClass.sym + "]");
1300 JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1301 env.enclClass.sym.sourcefile :
1302 env.toplevel.sourcefile);
1303 try {
1304 //save tree prior to rewriting
1305 JCTree untranslated = env.tree;
1307 make.at(Position.FIRSTPOS);
1308 TreeMaker localMake = make.forToplevel(env.toplevel);
1310 if (env.tree instanceof JCCompilationUnit) {
1311 if (!(stubOutput || sourceOutput || printFlat)) {
1312 if (shouldStop(CompileState.LOWER))
1313 return;
1314 List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
1315 if (pdef.head != null) {
1316 assert pdef.tail.isEmpty();
1317 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
1318 }
1319 }
1320 return;
1321 }
1323 if (stubOutput) {
1324 //emit stub Java source file, only for compilation
1325 //units enumerated explicitly on the command line
1326 JCClassDecl cdef = (JCClassDecl)env.tree;
1327 if (untranslated instanceof JCClassDecl &&
1328 rootClasses.contains((JCClassDecl)untranslated) &&
1329 ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1330 cdef.sym.packge().getQualifiedName() == names.java_lang)) {
1331 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
1332 }
1333 return;
1334 }
1336 if (shouldStop(CompileState.TRANSTYPES))
1337 return;
1339 env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
1340 compileStates.put(env, CompileState.TRANSTYPES);
1342 if (shouldStop(CompileState.LOWER))
1343 return;
1345 if (sourceOutput) {
1346 //emit standard Java source file, only for compilation
1347 //units enumerated explicitly on the command line
1348 JCClassDecl cdef = (JCClassDecl)env.tree;
1349 if (untranslated instanceof JCClassDecl &&
1350 rootClasses.contains((JCClassDecl)untranslated)) {
1351 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
1352 }
1353 return;
1354 }
1356 //translate out inner classes
1357 List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
1358 compileStates.put(env, CompileState.LOWER);
1360 if (shouldStop(CompileState.LOWER))
1361 return;
1363 //generate code for each class
1364 for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
1365 JCClassDecl cdef = (JCClassDecl)l.head;
1366 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
1367 }
1368 }
1369 finally {
1370 log.useSource(prev);
1371 }
1373 }
1375 /** Generates the source or class file for a list of classes.
1376 * The decision to generate a source file or a class file is
1377 * based upon the compiler's options.
1378 * Generation stops if an error occurs while writing files.
1379 */
1380 public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
1381 generate(queue, null);
1382 }
1384 public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
1385 if (shouldStop(CompileState.GENERATE))
1386 return;
1388 boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
1390 for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
1391 Env<AttrContext> env = x.fst;
1392 JCClassDecl cdef = x.snd;
1394 if (verboseCompilePolicy) {
1395 printNote("[generate "
1396 + (usePrintSource ? " source" : "code")
1397 + " " + cdef.sym + "]");
1398 }
1400 if (taskListener != null) {
1401 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1402 taskListener.started(e);
1403 }
1405 JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1406 env.enclClass.sym.sourcefile :
1407 env.toplevel.sourcefile);
1408 try {
1409 JavaFileObject file;
1410 if (usePrintSource)
1411 file = printSource(env, cdef);
1412 else
1413 file = genCode(env, cdef);
1414 if (results != null && file != null)
1415 results.add(file);
1416 } catch (IOException ex) {
1417 log.error(cdef.pos(), "class.cant.write",
1418 cdef.sym, ex.getMessage());
1419 return;
1420 } finally {
1421 log.useSource(prev);
1422 }
1424 if (taskListener != null) {
1425 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1426 taskListener.finished(e);
1427 }
1428 }
1429 }
1431 // where
1432 Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
1433 // use a LinkedHashMap to preserve the order of the original list as much as possible
1434 Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
1435 for (Env<AttrContext> env: envs) {
1436 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
1437 if (sublist == null) {
1438 sublist = new ListBuffer<Env<AttrContext>>();
1439 map.put(env.toplevel, sublist);
1440 }
1441 sublist.add(env);
1442 }
1443 return map;
1444 }
1446 JCClassDecl removeMethodBodies(JCClassDecl cdef) {
1447 final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
1448 class MethodBodyRemover extends TreeTranslator {
1449 @Override
1450 public void visitMethodDef(JCMethodDecl tree) {
1451 tree.mods.flags &= ~Flags.SYNCHRONIZED;
1452 for (JCVariableDecl vd : tree.params)
1453 vd.mods.flags &= ~Flags.FINAL;
1454 tree.body = null;
1455 super.visitMethodDef(tree);
1456 }
1457 @Override
1458 public void visitVarDef(JCVariableDecl tree) {
1459 if (tree.init != null && tree.init.type.constValue() == null)
1460 tree.init = null;
1461 super.visitVarDef(tree);
1462 }
1463 @Override
1464 public void visitClassDef(JCClassDecl tree) {
1465 ListBuffer<JCTree> newdefs = lb();
1466 for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
1467 JCTree t = it.head;
1468 switch (t.getTag()) {
1469 case JCTree.CLASSDEF:
1470 if (isInterface ||
1471 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1472 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1473 newdefs.append(t);
1474 break;
1475 case JCTree.METHODDEF:
1476 if (isInterface ||
1477 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1478 ((JCMethodDecl) t).sym.name == names.init ||
1479 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1480 newdefs.append(t);
1481 break;
1482 case JCTree.VARDEF:
1483 if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1484 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1485 newdefs.append(t);
1486 break;
1487 default:
1488 break;
1489 }
1490 }
1491 tree.defs = newdefs.toList();
1492 super.visitClassDef(tree);
1493 }
1494 }
1495 MethodBodyRemover r = new MethodBodyRemover();
1496 return r.translate(cdef);
1497 }
1499 public void reportDeferredDiagnostics() {
1500 if (annotationProcessingOccurred
1501 && implicitSourceFilesRead
1502 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
1503 if (explicitAnnotationProcessingRequested())
1504 log.warning("proc.use.implicit");
1505 else
1506 log.warning("proc.use.proc.or.implicit");
1507 }
1508 chk.reportDeferredDiagnostics();
1509 }
1511 /** Close the compiler, flushing the logs
1512 */
1513 public void close() {
1514 close(true);
1515 }
1517 public void close(boolean disposeNames) {
1518 rootClasses = null;
1519 reader = null;
1520 make = null;
1521 writer = null;
1522 enter = null;
1523 if (todo != null)
1524 todo.clear();
1525 todo = null;
1526 parserFactory = null;
1527 syms = null;
1528 source = null;
1529 attr = null;
1530 chk = null;
1531 gen = null;
1532 flow = null;
1533 transTypes = null;
1534 lower = null;
1535 annotate = null;
1536 types = null;
1538 log.flush();
1539 try {
1540 fileManager.flush();
1541 } catch (IOException e) {
1542 throw new Abort(e);
1543 } finally {
1544 if (names != null && disposeNames)
1545 names.dispose();
1546 names = null;
1547 }
1548 }
1550 protected void printNote(String lines) {
1551 Log.printLines(log.noticeWriter, lines);
1552 }
1554 /** Output for "-verbose" option.
1555 * @param key The key to look up the correct internationalized string.
1556 * @param arg An argument for substitution into the output string.
1557 */
1558 protected void printVerbose(String key, Object arg) {
1559 log.printNoteLines("verbose." + key, arg);
1560 }
1562 /** Print numbers of errors and warnings.
1563 */
1564 protected void printCount(String kind, int count) {
1565 if (count != 0) {
1566 String key;
1567 if (count == 1)
1568 key = "count." + kind;
1569 else
1570 key = "count." + kind + ".plural";
1571 log.printErrLines(key, String.valueOf(count));
1572 log.errWriter.flush();
1573 }
1574 }
1576 private static long now() {
1577 return System.currentTimeMillis();
1578 }
1580 private static long elapsed(long then) {
1581 return now() - then;
1582 }
1584 public void initRound(JavaCompiler prev) {
1585 genEndPos = prev.genEndPos;
1586 keepComments = prev.keepComments;
1587 start_msec = prev.start_msec;
1588 hasBeenUsed = true;
1589 }
1591 public static void enableLogging() {
1592 Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
1593 logger.setLevel(Level.ALL);
1594 for (Handler h : logger.getParent().getHandlers()) {
1595 h.setLevel(Level.ALL);
1596 }
1598 }
1599 }