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