Mon, 30 Aug 2010 18:03:35 -0700
6403465: javac should defer diagnostics until it can be determined they are persistent
Reviewed-by: mcimadamore, darcy
1 /*
2 * Copyright (c) 1999, 2009, 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.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.JCDiagnostic.DiagnosticFlag.*;
63 import static com.sun.tools.javac.util.ListBuffer.lb;
65 // TEMP, until we have a more efficient way to save doc comment info
66 import com.sun.tools.javac.parser.DocCommentScanner;
68 import java.util.HashMap;
69 import java.util.Queue;
70 import javax.lang.model.SourceVersion;
72 /** This class could be the main entry point for GJC when GJC is used as a
73 * component in a larger software system. It provides operations to
74 * construct a new compiler, and to run a new compiler on a set of source
75 * files.
76 *
77 * <p><b>This is NOT part of any supported API.
78 * If you write code that depends on this, you do so at your own risk.
79 * This code and its internal interfaces are subject to change or
80 * deletion without notice.</b>
81 */
82 public class JavaCompiler implements ClassReader.SourceCompleter {
83 /** The context key for the compiler. */
84 protected static final Context.Key<JavaCompiler> compilerKey =
85 new Context.Key<JavaCompiler>();
87 /** Get the JavaCompiler instance for this context. */
88 public static JavaCompiler instance(Context context) {
89 JavaCompiler instance = context.get(compilerKey);
90 if (instance == null)
91 instance = new JavaCompiler(context);
92 return instance;
93 }
95 /** The current version number as a string.
96 */
97 public static String version() {
98 return version("release"); // mm.nn.oo[-milestone]
99 }
101 /** The current full version number as a string.
102 */
103 public static String fullVersion() {
104 return version("full"); // mm.mm.oo[-milestone]-build
105 }
107 private static final String versionRBName = "com.sun.tools.javac.resources.version";
108 private static ResourceBundle versionRB;
110 private static String version(String key) {
111 if (versionRB == null) {
112 try {
113 versionRB = ResourceBundle.getBundle(versionRBName);
114 } catch (MissingResourceException e) {
115 return Log.getLocalizedString("version.not.available");
116 }
117 }
118 try {
119 return versionRB.getString(key);
120 }
121 catch (MissingResourceException e) {
122 return Log.getLocalizedString("version.not.available");
123 }
124 }
126 /**
127 * Control how the compiler's latter phases (attr, flow, desugar, generate)
128 * are connected. Each individual file is processed by each phase in turn,
129 * but with different compile policies, you can control the order in which
130 * each class is processed through its next phase.
131 *
132 * <p>Generally speaking, the compiler will "fail fast" in the face of
133 * errors, although not aggressively so. flow, desugar, etc become no-ops
134 * once any errors have occurred. No attempt is currently made to determine
135 * if it might be safe to process a class through its next phase because
136 * it does not depend on any unrelated errors that might have occurred.
137 */
138 protected static enum CompilePolicy {
139 /**
140 * Just attribute the parse trees.
141 */
142 ATTR_ONLY,
144 /**
145 * Just attribute and do flow analysis on the parse trees.
146 * This should catch most user errors.
147 */
148 CHECK_ONLY,
150 /**
151 * Attribute everything, then do flow analysis for everything,
152 * then desugar everything, and only then generate output.
153 * This means no output will be generated if there are any
154 * errors in any classes.
155 */
156 SIMPLE,
158 /**
159 * Groups the classes for each source file together, then process
160 * each group in a manner equivalent to the {@code SIMPLE} policy.
161 * This means no output will be generated if there are any
162 * errors in any of the classes in a source file.
163 */
164 BY_FILE,
166 /**
167 * Completely process each entry on the todo list in turn.
168 * -- this is the same for 1.5.
169 * Means output might be generated for some classes in a compilation unit
170 * and not others.
171 */
172 BY_TODO;
174 static CompilePolicy decode(String option) {
175 if (option == null)
176 return DEFAULT_COMPILE_POLICY;
177 else if (option.equals("attr"))
178 return ATTR_ONLY;
179 else if (option.equals("check"))
180 return CHECK_ONLY;
181 else if (option.equals("simple"))
182 return SIMPLE;
183 else if (option.equals("byfile"))
184 return BY_FILE;
185 else if (option.equals("bytodo"))
186 return BY_TODO;
187 else
188 return DEFAULT_COMPILE_POLICY;
189 }
190 }
192 private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
194 protected static enum ImplicitSourcePolicy {
195 /** Don't generate or process implicitly read source files. */
196 NONE,
197 /** Generate classes for implicitly read source files. */
198 CLASS,
199 /** Like CLASS, but generate warnings if annotation processing occurs */
200 UNSET;
202 static ImplicitSourcePolicy decode(String option) {
203 if (option == null)
204 return UNSET;
205 else if (option.equals("none"))
206 return NONE;
207 else if (option.equals("class"))
208 return CLASS;
209 else
210 return UNSET;
211 }
212 }
214 /** The log to be used for error reporting.
215 */
216 public Log log;
218 /** Factory for creating diagnostic objects
219 */
220 JCDiagnostic.Factory diagFactory;
222 /** The tree factory module.
223 */
224 protected TreeMaker make;
226 /** The class reader.
227 */
228 protected ClassReader reader;
230 /** The class writer.
231 */
232 protected ClassWriter writer;
234 /** The module for the symbol table entry phases.
235 */
236 protected Enter enter;
238 /** The symbol table.
239 */
240 protected Symtab syms;
242 /** The language version.
243 */
244 protected Source source;
246 /** The module for code generation.
247 */
248 protected Gen gen;
250 /** The name table.
251 */
252 protected Names names;
254 /** The attributor.
255 */
256 protected Attr attr;
258 /** The attributor.
259 */
260 protected Check chk;
262 /** The flow analyzer.
263 */
264 protected Flow flow;
266 /** The type eraser.
267 */
268 protected TransTypes transTypes;
270 /** The syntactic sugar desweetener.
271 */
272 protected Lower lower;
274 /** The annotation annotator.
275 */
276 protected Annotate annotate;
278 /** Force a completion failure on this name
279 */
280 protected final Name completionFailureName;
282 /** Type utilities.
283 */
284 protected Types types;
286 /** Access to file objects.
287 */
288 protected JavaFileManager fileManager;
290 /** Factory for parsers.
291 */
292 protected ParserFactory parserFactory;
294 /** Optional listener for progress events
295 */
296 protected TaskListener taskListener;
298 /**
299 * Annotation processing may require and provide a new instance
300 * of the compiler to be used for the analyze and generate phases.
301 */
302 protected JavaCompiler delegateCompiler;
304 /**
305 * Flag set if any annotation processing occurred.
306 **/
307 protected boolean annotationProcessingOccurred;
309 /**
310 * Flag set if any implicit source files read.
311 **/
312 protected boolean implicitSourceFilesRead;
314 protected Context context;
316 /** Construct a new compiler using a shared context.
317 */
318 public JavaCompiler(final Context context) {
319 this.context = context;
320 context.put(compilerKey, this);
322 // if fileManager not already set, register the JavacFileManager to be used
323 if (context.get(JavaFileManager.class) == null)
324 JavacFileManager.preRegister(context);
326 names = Names.instance(context);
327 log = Log.instance(context);
328 diagFactory = JCDiagnostic.Factory.instance(context);
329 reader = ClassReader.instance(context);
330 make = TreeMaker.instance(context);
331 writer = ClassWriter.instance(context);
332 enter = Enter.instance(context);
333 todo = Todo.instance(context);
335 fileManager = context.get(JavaFileManager.class);
336 parserFactory = ParserFactory.instance(context);
338 try {
339 // catch completion problems with predefineds
340 syms = Symtab.instance(context);
341 } catch (CompletionFailure ex) {
342 // inlined Check.completionError as it is not initialized yet
343 log.error("cant.access", ex.sym, ex.getDetailValue());
344 if (ex instanceof ClassReader.BadClassFile)
345 throw new Abort();
346 }
347 source = Source.instance(context);
348 attr = Attr.instance(context);
349 chk = Check.instance(context);
350 gen = Gen.instance(context);
351 flow = Flow.instance(context);
352 transTypes = TransTypes.instance(context);
353 lower = Lower.instance(context);
354 annotate = Annotate.instance(context);
355 types = Types.instance(context);
356 taskListener = context.get(TaskListener.class);
358 reader.sourceCompleter = this;
360 Options options = Options.instance(context);
362 verbose = options.get("-verbose") != null;
363 sourceOutput = options.get("-printsource") != null; // used to be -s
364 stubOutput = options.get("-stubs") != null;
365 relax = options.get("-relax") != null;
366 printFlat = options.get("-printflat") != null;
367 attrParseOnly = options.get("-attrparseonly") != null;
368 encoding = options.get("-encoding");
369 lineDebugInfo = options.get("-g:") == null ||
370 options.get("-g:lines") != null;
371 genEndPos = options.get("-Xjcov") != null ||
372 context.get(DiagnosticListener.class) != null;
373 devVerbose = options.get("dev") != null;
374 processPcks = options.get("process.packages") != null;
375 werror = options.get("-Werror") != null;
377 verboseCompilePolicy = options.get("verboseCompilePolicy") != null;
379 if (attrParseOnly)
380 compilePolicy = CompilePolicy.ATTR_ONLY;
381 else
382 compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
384 implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
386 completionFailureName =
387 (options.get("failcomplete") != null)
388 ? names.fromString(options.get("failcomplete"))
389 : null;
391 shouldStopPolicy =
392 (options.get("shouldStopPolicy") != null)
393 ? CompileState.valueOf(options.get("shouldStopPolicy"))
394 : null;
395 if (options.get("oldDiags") == null)
396 log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
397 }
399 /* Switches:
400 */
402 /** Verbose output.
403 */
404 public boolean verbose;
406 /** Emit plain Java source files rather than class files.
407 */
408 public boolean sourceOutput;
410 /** Emit stub source files rather than class files.
411 */
412 public boolean stubOutput;
414 /** Generate attributed parse tree only.
415 */
416 public boolean attrParseOnly;
418 /** Switch: relax some constraints for producing the jsr14 prototype.
419 */
420 boolean relax;
422 /** Debug switch: Emit Java sources after inner class flattening.
423 */
424 public boolean printFlat;
426 /** The encoding to be used for source input.
427 */
428 public String encoding;
430 /** Generate code with the LineNumberTable attribute for debugging
431 */
432 public boolean lineDebugInfo;
434 /** Switch: should we store the ending positions?
435 */
436 public boolean genEndPos;
438 /** Switch: should we debug ignored exceptions
439 */
440 protected boolean devVerbose;
442 /** Switch: should we (annotation) process packages as well
443 */
444 protected boolean processPcks;
446 /** Switch: treat warnings as errors
447 */
448 protected boolean werror;
450 /** Switch: is annotation processing requested explitly via
451 * CompilationTask.setProcessors?
452 */
453 protected boolean explicitAnnotationProcessingRequested = false;
455 /**
456 * The policy for the order in which to perform the compilation
457 */
458 protected CompilePolicy compilePolicy;
460 /**
461 * The policy for what to do with implicitly read source files
462 */
463 protected ImplicitSourcePolicy implicitSourcePolicy;
465 /**
466 * Report activity related to compilePolicy
467 */
468 public boolean verboseCompilePolicy;
470 /**
471 * Policy of how far to continue processing. null means until first
472 * error.
473 */
474 public CompileState shouldStopPolicy;
476 /** A queue of all as yet unattributed classes.
477 */
478 public Todo todo;
480 /** Ordered list of compiler phases for each compilation unit. */
481 public enum CompileState {
482 PARSE(1),
483 ENTER(2),
484 PROCESS(3),
485 ATTR(4),
486 FLOW(5),
487 TRANSTYPES(6),
488 LOWER(7),
489 GENERATE(8);
490 CompileState(int value) {
491 this.value = value;
492 }
493 boolean isDone(CompileState other) {
494 return value >= other.value;
495 }
496 private int value;
497 };
498 /** Partial map to record which compiler phases have been executed
499 * for each compilation unit. Used for ATTR and FLOW phases.
500 */
501 protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
502 private static final long serialVersionUID = 1812267524140424433L;
503 boolean isDone(Env<AttrContext> env, CompileState cs) {
504 CompileState ecs = get(env);
505 return ecs != null && ecs.isDone(cs);
506 }
507 }
508 private CompileStates compileStates = new CompileStates();
510 /** The set of currently compiled inputfiles, needed to ensure
511 * we don't accidentally overwrite an input file when -s is set.
512 * initialized by `compile'.
513 */
514 protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
516 protected boolean shouldStop(CompileState cs) {
517 if (shouldStopPolicy == null)
518 return (errorCount() > 0);
519 else
520 return cs.ordinal() > shouldStopPolicy.ordinal();
521 }
523 /** The number of errors reported so far.
524 */
525 public int errorCount() {
526 if (delegateCompiler != null && delegateCompiler != this)
527 return delegateCompiler.errorCount();
528 else {
529 if (werror && log.nerrors == 0 && log.nwarnings > 0) {
530 log.error("warnings.and.werror");
531 }
532 }
533 return log.nerrors;
534 }
536 protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
537 return shouldStop(cs) ? ListBuffer.<T>lb() : queue;
538 }
540 protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
541 return shouldStop(cs) ? List.<T>nil() : list;
542 }
544 /** The number of warnings reported so far.
545 */
546 public int warningCount() {
547 if (delegateCompiler != null && delegateCompiler != this)
548 return delegateCompiler.warningCount();
549 else
550 return log.nwarnings;
551 }
553 /** Try to open input stream with given name.
554 * Report an error if this fails.
555 * @param filename The file name of the input stream to be opened.
556 */
557 public CharSequence readSource(JavaFileObject filename) {
558 try {
559 inputFiles.add(filename);
560 return filename.getCharContent(false);
561 } catch (IOException e) {
562 log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
563 return null;
564 }
565 }
567 /** Parse contents of input stream.
568 * @param filename The name of the file from which input stream comes.
569 * @param input The input stream to be parsed.
570 */
571 protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
572 long msec = now();
573 JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
574 null, List.<JCTree>nil());
575 if (content != null) {
576 if (verbose) {
577 printVerbose("parsing.started", filename);
578 }
579 if (taskListener != null) {
580 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
581 taskListener.started(e);
582 }
583 Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
584 tree = parser.parseCompilationUnit();
585 if (verbose) {
586 printVerbose("parsing.done", Long.toString(elapsed(msec)));
587 }
588 }
590 tree.sourcefile = filename;
592 if (content != null && taskListener != null) {
593 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
594 taskListener.finished(e);
595 }
597 return tree;
598 }
599 // where
600 public boolean keepComments = false;
601 protected boolean keepComments() {
602 return keepComments || sourceOutput || stubOutput;
603 }
606 /** Parse contents of file.
607 * @param filename The name of the file to be parsed.
608 */
609 @Deprecated
610 public JCTree.JCCompilationUnit parse(String filename) {
611 JavacFileManager fm = (JavacFileManager)fileManager;
612 return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
613 }
615 /** Parse contents of file.
616 * @param filename The name of the file to be parsed.
617 */
618 public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
619 JavaFileObject prev = log.useSource(filename);
620 try {
621 JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
622 if (t.endPositions != null)
623 log.setEndPosTable(filename, t.endPositions);
624 return t;
625 } finally {
626 log.useSource(prev);
627 }
628 }
630 /** Resolve an identifier.
631 * @param name The identifier to resolve
632 */
633 public Symbol resolveIdent(String name) {
634 if (name.equals(""))
635 return syms.errSymbol;
636 JavaFileObject prev = log.useSource(null);
637 try {
638 JCExpression tree = null;
639 for (String s : name.split("\\.", -1)) {
640 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
641 return syms.errSymbol;
642 tree = (tree == null) ? make.Ident(names.fromString(s))
643 : make.Select(tree, names.fromString(s));
644 }
645 JCCompilationUnit toplevel =
646 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
647 toplevel.packge = syms.unnamedPackage;
648 return attr.attribIdent(tree, toplevel);
649 } finally {
650 log.useSource(prev);
651 }
652 }
654 /** Emit plain Java source for a class.
655 * @param env The attribution environment of the outermost class
656 * containing this class.
657 * @param cdef The class definition to be printed.
658 */
659 JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
660 JavaFileObject outFile
661 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
662 cdef.sym.flatname.toString(),
663 JavaFileObject.Kind.SOURCE,
664 null);
665 if (inputFiles.contains(outFile)) {
666 log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
667 return null;
668 } else {
669 BufferedWriter out = new BufferedWriter(outFile.openWriter());
670 try {
671 new Pretty(out, true).printUnit(env.toplevel, cdef);
672 if (verbose)
673 printVerbose("wrote.file", outFile);
674 } finally {
675 out.close();
676 }
677 return outFile;
678 }
679 }
681 /** Generate code and emit a class file for a given class
682 * @param env The attribution environment of the outermost class
683 * containing this class.
684 * @param cdef The class definition from which code is generated.
685 */
686 JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
687 try {
688 if (gen.genClass(env, cdef) && (errorCount() == 0))
689 return writer.writeClass(cdef.sym);
690 } catch (ClassWriter.PoolOverflow ex) {
691 log.error(cdef.pos(), "limit.pool");
692 } catch (ClassWriter.StringOverflow ex) {
693 log.error(cdef.pos(), "limit.string.overflow",
694 ex.value.substring(0, 20));
695 } catch (CompletionFailure ex) {
696 chk.completionError(cdef.pos(), ex);
697 }
698 return null;
699 }
701 /** Complete compiling a source file that has been accessed
702 * by the class file reader.
703 * @param c The class the source file of which needs to be compiled.
704 * @param filename The name of the source file.
705 * @param f An input stream that reads the source file.
706 */
707 public void complete(ClassSymbol c) throws CompletionFailure {
708 // System.err.println("completing " + c);//DEBUG
709 if (completionFailureName == c.fullname) {
710 throw new CompletionFailure(c, "user-selected completion failure by class name");
711 }
712 JCCompilationUnit tree;
713 JavaFileObject filename = c.classfile;
714 JavaFileObject prev = log.useSource(filename);
716 try {
717 tree = parse(filename, filename.getCharContent(false));
718 } catch (IOException e) {
719 log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
720 tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
721 } finally {
722 log.useSource(prev);
723 }
725 if (taskListener != null) {
726 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
727 taskListener.started(e);
728 }
730 enter.complete(List.of(tree), c);
732 if (taskListener != null) {
733 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
734 taskListener.finished(e);
735 }
737 if (enter.getEnv(c) == null) {
738 boolean isPkgInfo =
739 tree.sourcefile.isNameCompatible("package-info",
740 JavaFileObject.Kind.SOURCE);
741 if (isPkgInfo) {
742 if (enter.getEnv(tree.packge) == null) {
743 JCDiagnostic diag =
744 diagFactory.fragment("file.does.not.contain.package",
745 c.location());
746 throw reader.new BadClassFile(c, filename, diag);
747 }
748 } else {
749 JCDiagnostic diag =
750 diagFactory.fragment("file.doesnt.contain.class",
751 c.getQualifiedName());
752 throw reader.new BadClassFile(c, filename, diag);
753 }
754 }
756 implicitSourceFilesRead = true;
757 }
759 /** Track when the JavaCompiler has been used to compile something. */
760 private boolean hasBeenUsed = false;
761 private long start_msec = 0;
762 public long elapsed_msec = 0;
764 public void compile(List<JavaFileObject> sourceFileObject)
765 throws Throwable {
766 compile(sourceFileObject, List.<String>nil(), null);
767 }
769 /**
770 * Main method: compile a list of files, return all compiled classes
771 *
772 * @param sourceFileObjects file objects to be compiled
773 * @param classnames class names to process for annotations
774 * @param processors user provided annotation processors to bypass
775 * discovery, {@code null} means that no processors were provided
776 */
777 public void compile(List<JavaFileObject> sourceFileObjects,
778 List<String> classnames,
779 Iterable<? extends Processor> processors)
780 {
781 if (processors != null && processors.iterator().hasNext())
782 explicitAnnotationProcessingRequested = true;
783 // as a JavaCompiler can only be used once, throw an exception if
784 // it has been used before.
785 if (hasBeenUsed)
786 throw new AssertionError("attempt to reuse JavaCompiler");
787 hasBeenUsed = true;
789 start_msec = now();
790 try {
791 initProcessAnnotations(processors);
793 // These method calls must be chained to avoid memory leaks
794 delegateCompiler =
795 processAnnotations(
796 enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
797 classnames);
799 delegateCompiler.compile2();
800 delegateCompiler.close();
801 elapsed_msec = delegateCompiler.elapsed_msec;
802 } catch (Abort ex) {
803 if (devVerbose)
804 ex.printStackTrace();
805 } finally {
806 if (procEnvImpl != null)
807 procEnvImpl.close();
808 }
809 }
811 /**
812 * The phases following annotation processing: attribution,
813 * desugar, and finally code generation.
814 */
815 private void compile2() {
816 try {
817 switch (compilePolicy) {
818 case ATTR_ONLY:
819 attribute(todo);
820 break;
822 case CHECK_ONLY:
823 flow(attribute(todo));
824 break;
826 case SIMPLE:
827 generate(desugar(flow(attribute(todo))));
828 break;
830 case BY_FILE: {
831 Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
832 while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
833 generate(desugar(flow(attribute(q.remove()))));
834 }
835 }
836 break;
838 case BY_TODO:
839 while (!todo.isEmpty())
840 generate(desugar(flow(attribute(todo.remove()))));
841 break;
843 default:
844 assert false: "unknown compile policy";
845 }
846 } catch (Abort ex) {
847 if (devVerbose)
848 ex.printStackTrace();
849 }
851 if (verbose) {
852 elapsed_msec = elapsed(start_msec);
853 printVerbose("total", Long.toString(elapsed_msec));
854 }
856 reportDeferredDiagnostics();
858 if (!log.hasDiagnosticListener()) {
859 printCount("error", errorCount());
860 printCount("warn", warningCount());
861 }
862 }
864 private List<JCClassDecl> rootClasses;
866 /**
867 * Parses a list of files.
868 */
869 public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
870 if (shouldStop(CompileState.PARSE))
871 return List.nil();
873 //parse all files
874 ListBuffer<JCCompilationUnit> trees = lb();
875 for (JavaFileObject fileObject : fileObjects)
876 trees.append(parse(fileObject));
877 return trees.toList();
878 }
880 /**
881 * Enter the symbols found in a list of parse trees.
882 * As a side-effect, this puts elements on the "todo" list.
883 * Also stores a list of all top level classes in rootClasses.
884 */
885 public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
886 //enter symbols for all files
887 if (taskListener != null) {
888 for (JCCompilationUnit unit: roots) {
889 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
890 taskListener.started(e);
891 }
892 }
894 enter.main(roots);
896 if (taskListener != null) {
897 for (JCCompilationUnit unit: roots) {
898 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
899 taskListener.finished(e);
900 }
901 }
903 //If generating source, remember the classes declared in
904 //the original compilation units listed on the command line.
905 if (sourceOutput || stubOutput) {
906 ListBuffer<JCClassDecl> cdefs = lb();
907 for (JCCompilationUnit unit : roots) {
908 for (List<JCTree> defs = unit.defs;
909 defs.nonEmpty();
910 defs = defs.tail) {
911 if (defs.head instanceof JCClassDecl)
912 cdefs.append((JCClassDecl)defs.head);
913 }
914 }
915 rootClasses = cdefs.toList();
916 }
918 // Ensure the input files have been recorded. Although this is normally
919 // done by readSource, it may not have been done if the trees were read
920 // in a prior round of annotation processing, and the trees have been
921 // cleaned and are being reused.
922 for (JCCompilationUnit unit : roots) {
923 inputFiles.add(unit.sourcefile);
924 }
926 return roots;
927 }
929 /**
930 * Set to true to enable skeleton annotation processing code.
931 * Currently, we assume this variable will be replaced more
932 * advanced logic to figure out if annotation processing is
933 * needed.
934 */
935 boolean processAnnotations = false;
937 /**
938 * Object to handle annotation processing.
939 */
940 private JavacProcessingEnvironment procEnvImpl = null;
942 /**
943 * Check if we should process annotations.
944 * If so, and if no scanner is yet registered, then set up the DocCommentScanner
945 * to catch doc comments, and set keepComments so the parser records them in
946 * the compilation unit.
947 *
948 * @param processors user provided annotation processors to bypass
949 * discovery, {@code null} means that no processors were provided
950 */
951 public void initProcessAnnotations(Iterable<? extends Processor> processors) {
952 // Process annotations if processing is not disabled and there
953 // is at least one Processor available.
954 Options options = Options.instance(context);
955 if (options.get("-proc:none") != null) {
956 processAnnotations = false;
957 } else if (procEnvImpl == null) {
958 procEnvImpl = new JavacProcessingEnvironment(context, processors);
959 processAnnotations = procEnvImpl.atLeastOneProcessor();
961 if (processAnnotations) {
962 if (context.get(Scanner.Factory.scannerFactoryKey) == null)
963 DocCommentScanner.Factory.preRegister(context);
964 options.put("save-parameter-names", "save-parameter-names");
965 reader.saveParameterNames = true;
966 keepComments = 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.get("-proc:only") != null) {
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.get("-processor") != null ||
1104 options.get("-processorpath") != null ||
1105 options.get("-proc:only") != null ||
1106 options.get("-Xprint") != null;
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 compileStates.put(env, CompileState.ATTR);
1148 }
1149 finally {
1150 log.useSource(prev);
1151 }
1153 return env;
1154 }
1156 /**
1157 * Perform dataflow checks on attributed parse trees.
1158 * These include checks for definite assignment and unreachable statements.
1159 * If any errors occur, an empty list will be returned.
1160 * @returns the list of attributed parse trees
1161 */
1162 public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
1163 ListBuffer<Env<AttrContext>> results = lb();
1164 for (Env<AttrContext> env: envs) {
1165 flow(env, results);
1166 }
1167 return stopIfError(CompileState.FLOW, results);
1168 }
1170 /**
1171 * Perform dataflow checks on an attributed parse tree.
1172 */
1173 public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
1174 ListBuffer<Env<AttrContext>> results = lb();
1175 flow(env, results);
1176 return stopIfError(CompileState.FLOW, results);
1177 }
1179 /**
1180 * Perform dataflow checks on an attributed parse tree.
1181 */
1182 protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
1183 try {
1184 if (shouldStop(CompileState.FLOW))
1185 return;
1187 if (relax || compileStates.isDone(env, CompileState.FLOW)) {
1188 results.add(env);
1189 return;
1190 }
1192 if (verboseCompilePolicy)
1193 printNote("[flow " + env.enclClass.sym + "]");
1194 JavaFileObject prev = log.useSource(
1195 env.enclClass.sym.sourcefile != null ?
1196 env.enclClass.sym.sourcefile :
1197 env.toplevel.sourcefile);
1198 try {
1199 make.at(Position.FIRSTPOS);
1200 TreeMaker localMake = make.forToplevel(env.toplevel);
1201 flow.analyzeTree(env, localMake);
1202 compileStates.put(env, CompileState.FLOW);
1204 if (shouldStop(CompileState.FLOW))
1205 return;
1207 results.add(env);
1208 }
1209 finally {
1210 log.useSource(prev);
1211 }
1212 }
1213 finally {
1214 if (taskListener != null) {
1215 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1216 taskListener.finished(e);
1217 }
1218 }
1219 }
1221 /**
1222 * Prepare attributed parse trees, in conjunction with their attribution contexts,
1223 * for source or code generation.
1224 * If any errors occur, an empty list will be returned.
1225 * @returns a list containing the classes to be generated
1226 */
1227 public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
1228 ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
1229 for (Env<AttrContext> env: envs)
1230 desugar(env, results);
1231 return stopIfError(CompileState.FLOW, results);
1232 }
1234 HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs =
1235 new HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>>();
1237 /**
1238 * Prepare attributed parse trees, in conjunction with their attribution contexts,
1239 * for source or code generation. If the file was not listed on the command line,
1240 * the current implicitSourcePolicy is taken into account.
1241 * The preparation stops as soon as an error is found.
1242 */
1243 protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
1244 if (shouldStop(CompileState.TRANSTYPES))
1245 return;
1247 if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
1248 && !inputFiles.contains(env.toplevel.sourcefile)) {
1249 return;
1250 }
1252 if (compileStates.isDone(env, CompileState.LOWER)) {
1253 results.addAll(desugaredEnvs.get(env));
1254 return;
1255 }
1257 /**
1258 * Ensure that superclasses of C are desugared before C itself. This is
1259 * required for two reasons: (i) as erasure (TransTypes) destroys
1260 * information needed in flow analysis and (ii) as some checks carried
1261 * out during lowering require that all synthetic fields/methods have
1262 * already been added to C and its superclasses.
1263 */
1264 class ScanNested extends TreeScanner {
1265 Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
1266 @Override
1267 public void visitClassDef(JCClassDecl node) {
1268 Type st = types.supertype(node.sym.type);
1269 if (st.tag == TypeTags.CLASS) {
1270 ClassSymbol c = st.tsym.outermostClass();
1271 Env<AttrContext> stEnv = enter.getEnv(c);
1272 if (stEnv != null && env != stEnv) {
1273 if (dependencies.add(stEnv))
1274 scan(stEnv.tree);
1275 }
1276 }
1277 super.visitClassDef(node);
1278 }
1279 }
1280 ScanNested scanner = new ScanNested();
1281 scanner.scan(env.tree);
1282 for (Env<AttrContext> dep: scanner.dependencies) {
1283 if (!compileStates.isDone(dep, CompileState.FLOW))
1284 desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
1285 }
1287 //We need to check for error another time as more classes might
1288 //have been attributed and analyzed at this stage
1289 if (shouldStop(CompileState.TRANSTYPES))
1290 return;
1292 if (verboseCompilePolicy)
1293 printNote("[desugar " + env.enclClass.sym + "]");
1295 JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1296 env.enclClass.sym.sourcefile :
1297 env.toplevel.sourcefile);
1298 try {
1299 //save tree prior to rewriting
1300 JCTree untranslated = env.tree;
1302 make.at(Position.FIRSTPOS);
1303 TreeMaker localMake = make.forToplevel(env.toplevel);
1305 if (env.tree instanceof JCCompilationUnit) {
1306 if (!(stubOutput || sourceOutput || printFlat)) {
1307 if (shouldStop(CompileState.LOWER))
1308 return;
1309 List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
1310 if (pdef.head != null) {
1311 assert pdef.tail.isEmpty();
1312 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
1313 }
1314 }
1315 return;
1316 }
1318 if (stubOutput) {
1319 //emit stub Java source file, only for compilation
1320 //units enumerated explicitly on the command line
1321 JCClassDecl cdef = (JCClassDecl)env.tree;
1322 if (untranslated instanceof JCClassDecl &&
1323 rootClasses.contains((JCClassDecl)untranslated) &&
1324 ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1325 cdef.sym.packge().getQualifiedName() == names.java_lang)) {
1326 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
1327 }
1328 return;
1329 }
1331 if (shouldStop(CompileState.TRANSTYPES))
1332 return;
1334 env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
1335 compileStates.put(env, CompileState.TRANSTYPES);
1337 if (shouldStop(CompileState.LOWER))
1338 return;
1340 if (sourceOutput) {
1341 //emit standard Java source file, only for compilation
1342 //units enumerated explicitly on the command line
1343 JCClassDecl cdef = (JCClassDecl)env.tree;
1344 if (untranslated instanceof JCClassDecl &&
1345 rootClasses.contains((JCClassDecl)untranslated)) {
1346 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
1347 }
1348 return;
1349 }
1351 //translate out inner classes
1352 List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
1353 compileStates.put(env, CompileState.LOWER);
1355 if (shouldStop(CompileState.LOWER))
1356 return;
1358 //generate code for each class
1359 for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
1360 JCClassDecl cdef = (JCClassDecl)l.head;
1361 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
1362 }
1363 }
1364 finally {
1365 log.useSource(prev);
1366 }
1368 }
1370 /** Generates the source or class file for a list of classes.
1371 * The decision to generate a source file or a class file is
1372 * based upon the compiler's options.
1373 * Generation stops if an error occurs while writing files.
1374 */
1375 public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
1376 generate(queue, null);
1377 }
1379 public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
1380 if (shouldStop(CompileState.GENERATE))
1381 return;
1383 boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
1385 for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
1386 Env<AttrContext> env = x.fst;
1387 JCClassDecl cdef = x.snd;
1389 if (verboseCompilePolicy) {
1390 printNote("[generate "
1391 + (usePrintSource ? " source" : "code")
1392 + " " + cdef.sym + "]");
1393 }
1395 if (taskListener != null) {
1396 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1397 taskListener.started(e);
1398 }
1400 JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1401 env.enclClass.sym.sourcefile :
1402 env.toplevel.sourcefile);
1403 try {
1404 JavaFileObject file;
1405 if (usePrintSource)
1406 file = printSource(env, cdef);
1407 else
1408 file = genCode(env, cdef);
1409 if (results != null && file != null)
1410 results.add(file);
1411 } catch (IOException ex) {
1412 log.error(cdef.pos(), "class.cant.write",
1413 cdef.sym, ex.getMessage());
1414 return;
1415 } finally {
1416 log.useSource(prev);
1417 }
1419 if (taskListener != null) {
1420 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1421 taskListener.finished(e);
1422 }
1423 }
1424 }
1426 // where
1427 Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
1428 // use a LinkedHashMap to preserve the order of the original list as much as possible
1429 Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
1430 for (Env<AttrContext> env: envs) {
1431 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
1432 if (sublist == null) {
1433 sublist = new ListBuffer<Env<AttrContext>>();
1434 map.put(env.toplevel, sublist);
1435 }
1436 sublist.add(env);
1437 }
1438 return map;
1439 }
1441 JCClassDecl removeMethodBodies(JCClassDecl cdef) {
1442 final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
1443 class MethodBodyRemover extends TreeTranslator {
1444 @Override
1445 public void visitMethodDef(JCMethodDecl tree) {
1446 tree.mods.flags &= ~Flags.SYNCHRONIZED;
1447 for (JCVariableDecl vd : tree.params)
1448 vd.mods.flags &= ~Flags.FINAL;
1449 tree.body = null;
1450 super.visitMethodDef(tree);
1451 }
1452 @Override
1453 public void visitVarDef(JCVariableDecl tree) {
1454 if (tree.init != null && tree.init.type.constValue() == null)
1455 tree.init = null;
1456 super.visitVarDef(tree);
1457 }
1458 @Override
1459 public void visitClassDef(JCClassDecl tree) {
1460 ListBuffer<JCTree> newdefs = lb();
1461 for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
1462 JCTree t = it.head;
1463 switch (t.getTag()) {
1464 case JCTree.CLASSDEF:
1465 if (isInterface ||
1466 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1467 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1468 newdefs.append(t);
1469 break;
1470 case JCTree.METHODDEF:
1471 if (isInterface ||
1472 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1473 ((JCMethodDecl) t).sym.name == names.init ||
1474 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1475 newdefs.append(t);
1476 break;
1477 case JCTree.VARDEF:
1478 if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1479 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1480 newdefs.append(t);
1481 break;
1482 default:
1483 break;
1484 }
1485 }
1486 tree.defs = newdefs.toList();
1487 super.visitClassDef(tree);
1488 }
1489 }
1490 MethodBodyRemover r = new MethodBodyRemover();
1491 return r.translate(cdef);
1492 }
1494 public void reportDeferredDiagnostics() {
1495 if (annotationProcessingOccurred
1496 && implicitSourceFilesRead
1497 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
1498 if (explicitAnnotationProcessingRequested())
1499 log.warning("proc.use.implicit");
1500 else
1501 log.warning("proc.use.proc.or.implicit");
1502 }
1503 chk.reportDeferredDiagnostics();
1504 }
1506 /** Close the compiler, flushing the logs
1507 */
1508 public void close() {
1509 close(true);
1510 }
1512 public void close(boolean disposeNames) {
1513 rootClasses = null;
1514 reader = null;
1515 make = null;
1516 writer = null;
1517 enter = null;
1518 if (todo != null)
1519 todo.clear();
1520 todo = null;
1521 parserFactory = null;
1522 syms = null;
1523 source = null;
1524 attr = null;
1525 chk = null;
1526 gen = null;
1527 flow = null;
1528 transTypes = null;
1529 lower = null;
1530 annotate = null;
1531 types = null;
1533 log.flush();
1534 try {
1535 fileManager.flush();
1536 } catch (IOException e) {
1537 throw new Abort(e);
1538 } finally {
1539 if (names != null && disposeNames)
1540 names.dispose();
1541 names = null;
1542 }
1543 }
1545 protected void printNote(String lines) {
1546 Log.printLines(log.noticeWriter, lines);
1547 }
1549 /** Output for "-verbose" option.
1550 * @param key The key to look up the correct internationalized string.
1551 * @param arg An argument for substitution into the output string.
1552 */
1553 protected void printVerbose(String key, Object arg) {
1554 log.printNoteLines("verbose." + key, arg);
1555 }
1557 /** Print numbers of errors and warnings.
1558 */
1559 protected void printCount(String kind, int count) {
1560 if (count != 0) {
1561 String key;
1562 if (count == 1)
1563 key = "count." + kind;
1564 else
1565 key = "count." + kind + ".plural";
1566 log.printErrLines(key, String.valueOf(count));
1567 log.errWriter.flush();
1568 }
1569 }
1571 private static long now() {
1572 return System.currentTimeMillis();
1573 }
1575 private static long elapsed(long then) {
1576 return now() - then;
1577 }
1579 public void initRound(JavaCompiler prev) {
1580 keepComments = prev.keepComments;
1581 start_msec = prev.start_msec;
1582 hasBeenUsed = true;
1583 }
1585 public static void enableLogging() {
1586 Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
1587 logger.setLevel(Level.ALL);
1588 for (Handler h : logger.getParent().getHandlers()) {
1589 h.setLevel(Level.ALL);
1590 }
1592 }
1593 }