Thu, 02 Oct 2008 19:58:40 -0700
6754988: Update copyright year
Summary: Update for files that have been modified starting July 2008
Reviewed-by: ohair, tbell
1 /*
2 * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
26 package com.sun.tools.javac.main;
28 import java.io.*;
29 import java.util.HashSet;
30 import java.util.LinkedHashSet;
31 import java.util.LinkedHashMap;
32 import java.util.Map;
33 import java.util.MissingResourceException;
34 import java.util.ResourceBundle;
35 import java.util.Set;
36 import java.util.logging.Handler;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
40 import javax.tools.JavaFileManager;
41 import javax.tools.JavaFileObject;
42 import javax.tools.DiagnosticListener;
44 import com.sun.tools.javac.file.JavacFileManager;
45 import com.sun.source.util.TaskEvent;
46 import com.sun.source.util.TaskListener;
48 import com.sun.tools.javac.util.*;
49 import com.sun.tools.javac.code.*;
50 import com.sun.tools.javac.tree.*;
51 import com.sun.tools.javac.parser.*;
52 import com.sun.tools.javac.comp.*;
53 import com.sun.tools.javac.jvm.*;
55 import com.sun.tools.javac.code.Symbol.*;
56 import com.sun.tools.javac.tree.JCTree.*;
58 import com.sun.tools.javac.processing.*;
59 import javax.annotation.processing.Processor;
61 import static javax.tools.StandardLocation.CLASS_OUTPUT;
62 import static com.sun.tools.javac.util.ListBuffer.lb;
64 // TEMP, until we have a more efficient way to save doc comment info
65 import com.sun.tools.javac.parser.DocCommentScanner;
67 import java.util.HashMap;
68 import java.util.Queue;
69 import javax.lang.model.SourceVersion;
71 /** This class could be the main entry point for GJC when GJC is used as a
72 * component in a larger software system. It provides operations to
73 * construct a new compiler, and to run a new compiler on a set of source
74 * files.
75 *
76 * <p><b>This is NOT part of any API supported by Sun Microsystems. If
77 * you write code that depends on this, you do so at your own risk.
78 * This code and its internal interfaces are subject to change or
79 * deletion without notice.</b>
80 */
81 public class JavaCompiler implements ClassReader.SourceCompleter {
82 /** The context key for the compiler. */
83 protected static final Context.Key<JavaCompiler> compilerKey =
84 new Context.Key<JavaCompiler>();
86 /** Get the JavaCompiler instance for this context. */
87 public static JavaCompiler instance(Context context) {
88 JavaCompiler instance = context.get(compilerKey);
89 if (instance == null)
90 instance = new JavaCompiler(context);
91 return instance;
92 }
94 /** The current version number as a string.
95 */
96 public static String version() {
97 return version("release"); // mm.nn.oo[-milestone]
98 }
100 /** The current full version number as a string.
101 */
102 public static String fullVersion() {
103 return version("full"); // mm.mm.oo[-milestone]-build
104 }
106 private static final String versionRBName = "com.sun.tools.javac.resources.version";
107 private static ResourceBundle versionRB;
109 private static String version(String key) {
110 if (versionRB == null) {
111 try {
112 versionRB = ResourceBundle.getBundle(versionRBName);
113 } catch (MissingResourceException e) {
114 return Log.getLocalizedString("version.resource.missing", System.getProperty("java.version"));
115 }
116 }
117 try {
118 return versionRB.getString(key);
119 }
120 catch (MissingResourceException e) {
121 return Log.getLocalizedString("version.unknown", System.getProperty("java.version"));
122 }
123 }
125 private static enum CompilePolicy {
126 /*
127 * Just attribute the parse trees
128 */
129 ATTR_ONLY,
131 /*
132 * Just attribute and do flow analysis on the parse trees.
133 * This should catch most user errors.
134 */
135 CHECK_ONLY,
137 /*
138 * Attribute everything, then do flow analysis for everything,
139 * then desugar everything, and only then generate output.
140 * Means nothing is generated if there are any errors in any classes.
141 */
142 SIMPLE,
144 /*
145 * After attributing everything and doing flow analysis,
146 * group the work by compilation unit.
147 * Then, process the work for each compilation unit together.
148 * Means nothing is generated for a compilation unit if the are any errors
149 * in the compilation unit (or in any preceding compilation unit.)
150 */
151 BY_FILE,
153 /*
154 * Completely process each entry on the todo list in turn.
155 * -- this is the same for 1.5.
156 * Means output might be generated for some classes in a compilation unit
157 * and not others.
158 */
159 BY_TODO;
161 static CompilePolicy decode(String option) {
162 if (option == null)
163 return DEFAULT_COMPILE_POLICY;
164 else if (option.equals("attr"))
165 return ATTR_ONLY;
166 else if (option.equals("check"))
167 return CHECK_ONLY;
168 else if (option.equals("simple"))
169 return SIMPLE;
170 else if (option.equals("byfile"))
171 return BY_FILE;
172 else if (option.equals("bytodo"))
173 return BY_TODO;
174 else
175 return DEFAULT_COMPILE_POLICY;
176 }
177 }
179 private static CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
181 private static enum ImplicitSourcePolicy {
182 /** Don't generate or process implicitly read source files. */
183 NONE,
184 /** Generate classes for implicitly read source files. */
185 CLASS,
186 /** Like CLASS, but generate warnings if annotation processing occurs */
187 UNSET;
189 static ImplicitSourcePolicy decode(String option) {
190 if (option == null)
191 return UNSET;
192 else if (option.equals("none"))
193 return NONE;
194 else if (option.equals("class"))
195 return CLASS;
196 else
197 return UNSET;
198 }
199 }
201 /** The log to be used for error reporting.
202 */
203 public Log log;
205 /** Factory for creating diagnostic objects
206 */
207 JCDiagnostic.Factory diagFactory;
209 /** The tree factory module.
210 */
211 protected TreeMaker make;
213 /** The class reader.
214 */
215 protected ClassReader reader;
217 /** The class writer.
218 */
219 protected ClassWriter writer;
221 /** The module for the symbol table entry phases.
222 */
223 protected Enter enter;
225 /** The symbol table.
226 */
227 protected Symtab syms;
229 /** The language version.
230 */
231 protected Source source;
233 /** The module for code generation.
234 */
235 protected Gen gen;
237 /** The name table.
238 */
239 protected Names names;
241 /** The attributor.
242 */
243 protected Attr attr;
245 /** The attributor.
246 */
247 protected Check chk;
249 /** The flow analyzer.
250 */
251 protected Flow flow;
253 /** The type eraser.
254 */
255 TransTypes transTypes;
257 /** The syntactic sugar desweetener.
258 */
259 Lower lower;
261 /** The annotation annotator.
262 */
263 protected Annotate annotate;
265 /** Force a completion failure on this name
266 */
267 protected final Name completionFailureName;
269 /** Type utilities.
270 */
271 protected Types types;
273 /** Access to file objects.
274 */
275 protected JavaFileManager fileManager;
277 /** Factory for parsers.
278 */
279 protected ParserFactory parserFactory;
281 /** Optional listener for progress events
282 */
283 protected TaskListener taskListener;
285 /**
286 * Annotation processing may require and provide a new instance
287 * of the compiler to be used for the analyze and generate phases.
288 */
289 protected JavaCompiler delegateCompiler;
291 /**
292 * Flag set if any annotation processing occurred.
293 **/
294 protected boolean annotationProcessingOccurred;
296 /**
297 * Flag set if any implicit source files read.
298 **/
299 protected boolean implicitSourceFilesRead;
301 protected Context context;
303 /** Construct a new compiler using a shared context.
304 */
305 public JavaCompiler(final Context context) {
306 this.context = context;
307 context.put(compilerKey, this);
309 // if fileManager not already set, register the JavacFileManager to be used
310 if (context.get(JavaFileManager.class) == null)
311 JavacFileManager.preRegister(context);
313 names = Names.instance(context);
314 log = Log.instance(context);
315 diagFactory = JCDiagnostic.Factory.instance(context);
316 reader = ClassReader.instance(context);
317 make = TreeMaker.instance(context);
318 writer = ClassWriter.instance(context);
319 enter = Enter.instance(context);
320 todo = Todo.instance(context);
322 fileManager = context.get(JavaFileManager.class);
323 parserFactory = ParserFactory.instance(context);
325 try {
326 // catch completion problems with predefineds
327 syms = Symtab.instance(context);
328 } catch (CompletionFailure ex) {
329 // inlined Check.completionError as it is not initialized yet
330 log.error("cant.access", ex.sym, ex.getDetailValue());
331 if (ex instanceof ClassReader.BadClassFile)
332 throw new Abort();
333 }
334 source = Source.instance(context);
335 attr = Attr.instance(context);
336 chk = Check.instance(context);
337 gen = Gen.instance(context);
338 flow = Flow.instance(context);
339 transTypes = TransTypes.instance(context);
340 lower = Lower.instance(context);
341 annotate = Annotate.instance(context);
342 types = Types.instance(context);
343 taskListener = context.get(TaskListener.class);
345 reader.sourceCompleter = this;
347 Options options = Options.instance(context);
349 verbose = options.get("-verbose") != null;
350 sourceOutput = options.get("-printsource") != null; // used to be -s
351 stubOutput = options.get("-stubs") != null;
352 relax = options.get("-relax") != null;
353 printFlat = options.get("-printflat") != null;
354 attrParseOnly = options.get("-attrparseonly") != null;
355 encoding = options.get("-encoding");
356 lineDebugInfo = options.get("-g:") == null ||
357 options.get("-g:lines") != null;
358 genEndPos = options.get("-Xjcov") != null ||
359 context.get(DiagnosticListener.class) != null;
360 devVerbose = options.get("dev") != null;
361 processPcks = options.get("process.packages") != null;
363 verboseCompilePolicy = options.get("verboseCompilePolicy") != null;
365 if (attrParseOnly)
366 compilePolicy = CompilePolicy.ATTR_ONLY;
367 else
368 compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
370 implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
372 completionFailureName =
373 (options.get("failcomplete") != null)
374 ? names.fromString(options.get("failcomplete"))
375 : null;
376 }
378 /* Switches:
379 */
381 /** Verbose output.
382 */
383 public boolean verbose;
385 /** Emit plain Java source files rather than class files.
386 */
387 public boolean sourceOutput;
389 /** Emit stub source files rather than class files.
390 */
391 public boolean stubOutput;
393 /** Generate attributed parse tree only.
394 */
395 public boolean attrParseOnly;
397 /** Switch: relax some constraints for producing the jsr14 prototype.
398 */
399 boolean relax;
401 /** Debug switch: Emit Java sources after inner class flattening.
402 */
403 public boolean printFlat;
405 /** The encoding to be used for source input.
406 */
407 public String encoding;
409 /** Generate code with the LineNumberTable attribute for debugging
410 */
411 public boolean lineDebugInfo;
413 /** Switch: should we store the ending positions?
414 */
415 public boolean genEndPos;
417 /** Switch: should we debug ignored exceptions
418 */
419 protected boolean devVerbose;
421 /** Switch: should we (annotation) process packages as well
422 */
423 protected boolean processPcks;
425 /** Switch: is annotation processing requested explitly via
426 * CompilationTask.setProcessors?
427 */
428 protected boolean explicitAnnotationProcessingRequested = false;
430 /**
431 * The policy for the order in which to perform the compilation
432 */
433 protected CompilePolicy compilePolicy;
435 /**
436 * The policy for what to do with implicitly read source files
437 */
438 protected ImplicitSourcePolicy implicitSourcePolicy;
440 /**
441 * Report activity related to compilePolicy
442 */
443 public boolean verboseCompilePolicy;
445 /** A queue of all as yet unattributed classes.
446 */
447 public Todo todo;
449 protected enum CompileState {
450 TODO(0),
451 ATTR(1),
452 FLOW(2);
453 CompileState(int value) {
454 this.value = value;
455 }
456 boolean isDone(CompileState other) {
457 return value >= other.value;
458 }
459 private int value;
460 };
461 protected class CompileStates extends HashMap<Env<AttrContext>,CompileState> {
462 boolean isDone(Env<AttrContext> env, CompileState cs) {
463 CompileState ecs = get(env);
464 return ecs != null && ecs.isDone(cs);
465 }
466 }
467 private CompileStates compileStates = new CompileStates();
469 /** The set of currently compiled inputfiles, needed to ensure
470 * we don't accidentally overwrite an input file when -s is set.
471 * initialized by `compile'.
472 */
473 protected Set<JavaFileObject> inputFiles = new HashSet<JavaFileObject>();
475 /** The number of errors reported so far.
476 */
477 public int errorCount() {
478 if (delegateCompiler != null && delegateCompiler != this)
479 return delegateCompiler.errorCount();
480 else
481 return log.nerrors;
482 }
484 protected final <T> Queue<T> stopIfError(Queue<T> queue) {
485 if (errorCount() == 0)
486 return queue;
487 else
488 return ListBuffer.lb();
489 }
491 protected final <T> List<T> stopIfError(List<T> list) {
492 if (errorCount() == 0)
493 return list;
494 else
495 return List.nil();
496 }
498 /** The number of warnings reported so far.
499 */
500 public int warningCount() {
501 if (delegateCompiler != null && delegateCompiler != this)
502 return delegateCompiler.warningCount();
503 else
504 return log.nwarnings;
505 }
507 /** Whether or not any parse errors have occurred.
508 */
509 public boolean parseErrors() {
510 return parseErrors;
511 }
513 /** Try to open input stream with given name.
514 * Report an error if this fails.
515 * @param filename The file name of the input stream to be opened.
516 */
517 public CharSequence readSource(JavaFileObject filename) {
518 try {
519 inputFiles.add(filename);
520 return filename.getCharContent(false);
521 } catch (IOException e) {
522 log.error("error.reading.file", filename, e.getLocalizedMessage());
523 return null;
524 }
525 }
527 /** Parse contents of input stream.
528 * @param filename The name of the file from which input stream comes.
529 * @param input The input stream to be parsed.
530 */
531 protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
532 long msec = now();
533 JCCompilationUnit tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(),
534 null, List.<JCTree>nil());
535 if (content != null) {
536 if (verbose) {
537 printVerbose("parsing.started", filename);
538 }
539 if (taskListener != null) {
540 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
541 taskListener.started(e);
542 }
543 int initialErrorCount = log.nerrors;
544 Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);
545 tree = parser.parseCompilationUnit();
546 parseErrors |= (log.nerrors > initialErrorCount);
547 if (verbose) {
548 printVerbose("parsing.done", Long.toString(elapsed(msec)));
549 }
550 }
552 tree.sourcefile = filename;
554 if (content != null && taskListener != null) {
555 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
556 taskListener.finished(e);
557 }
559 return tree;
560 }
561 // where
562 public boolean keepComments = false;
563 protected boolean keepComments() {
564 return keepComments || sourceOutput || stubOutput;
565 }
568 /** Parse contents of file.
569 * @param filename The name of the file to be parsed.
570 */
571 @Deprecated
572 public JCTree.JCCompilationUnit parse(String filename) throws IOException {
573 JavacFileManager fm = (JavacFileManager)fileManager;
574 return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
575 }
577 /** Parse contents of file.
578 * @param filename The name of the file to be parsed.
579 */
580 public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
581 JavaFileObject prev = log.useSource(filename);
582 try {
583 JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
584 if (t.endPositions != null)
585 log.setEndPosTable(filename, t.endPositions);
586 return t;
587 } finally {
588 log.useSource(prev);
589 }
590 }
592 /** Resolve an identifier.
593 * @param name The identifier to resolve
594 */
595 public Symbol resolveIdent(String name) {
596 if (name.equals(""))
597 return syms.errSymbol;
598 JavaFileObject prev = log.useSource(null);
599 try {
600 JCExpression tree = null;
601 for (String s : name.split("\\.", -1)) {
602 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
603 return syms.errSymbol;
604 tree = (tree == null) ? make.Ident(names.fromString(s))
605 : make.Select(tree, names.fromString(s));
606 }
607 JCCompilationUnit toplevel =
608 make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
609 toplevel.packge = syms.unnamedPackage;
610 return attr.attribIdent(tree, toplevel);
611 } finally {
612 log.useSource(prev);
613 }
614 }
616 /** Emit plain Java source for a class.
617 * @param env The attribution environment of the outermost class
618 * containing this class.
619 * @param cdef The class definition to be printed.
620 */
621 JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
622 JavaFileObject outFile
623 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
624 cdef.sym.flatname.toString(),
625 JavaFileObject.Kind.SOURCE,
626 null);
627 if (inputFiles.contains(outFile)) {
628 log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
629 return null;
630 } else {
631 BufferedWriter out = new BufferedWriter(outFile.openWriter());
632 try {
633 new Pretty(out, true).printUnit(env.toplevel, cdef);
634 if (verbose)
635 printVerbose("wrote.file", outFile);
636 } finally {
637 out.close();
638 }
639 return outFile;
640 }
641 }
643 /** Generate code and emit a class file for a given class
644 * @param env The attribution environment of the outermost class
645 * containing this class.
646 * @param cdef The class definition from which code is generated.
647 */
648 JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
649 try {
650 if (gen.genClass(env, cdef))
651 return writer.writeClass(cdef.sym);
652 } catch (ClassWriter.PoolOverflow ex) {
653 log.error(cdef.pos(), "limit.pool");
654 } catch (ClassWriter.StringOverflow ex) {
655 log.error(cdef.pos(), "limit.string.overflow",
656 ex.value.substring(0, 20));
657 } catch (CompletionFailure ex) {
658 chk.completionError(cdef.pos(), ex);
659 }
660 return null;
661 }
663 /** Complete compiling a source file that has been accessed
664 * by the class file reader.
665 * @param c The class the source file of which needs to be compiled.
666 * @param filename The name of the source file.
667 * @param f An input stream that reads the source file.
668 */
669 public void complete(ClassSymbol c) throws CompletionFailure {
670 // System.err.println("completing " + c);//DEBUG
671 if (completionFailureName == c.fullname) {
672 throw new CompletionFailure(c, "user-selected completion failure by class name");
673 }
674 JCCompilationUnit tree;
675 JavaFileObject filename = c.classfile;
676 JavaFileObject prev = log.useSource(filename);
678 try {
679 tree = parse(filename, filename.getCharContent(false));
680 } catch (IOException e) {
681 log.error("error.reading.file", filename, e);
682 tree = make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
683 } finally {
684 log.useSource(prev);
685 }
687 if (taskListener != null) {
688 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
689 taskListener.started(e);
690 }
692 enter.complete(List.of(tree), c);
694 if (taskListener != null) {
695 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
696 taskListener.finished(e);
697 }
699 if (enter.getEnv(c) == null) {
700 boolean isPkgInfo =
701 tree.sourcefile.isNameCompatible("package-info",
702 JavaFileObject.Kind.SOURCE);
703 if (isPkgInfo) {
704 if (enter.getEnv(tree.packge) == null) {
705 JCDiagnostic diag =
706 diagFactory.fragment("file.does.not.contain.package",
707 c.location());
708 throw reader.new BadClassFile(c, filename, diag);
709 }
710 } else {
711 JCDiagnostic diag =
712 diagFactory.fragment("file.doesnt.contain.class",
713 c.getQualifiedName());
714 throw reader.new BadClassFile(c, filename, diag);
715 }
716 }
718 implicitSourceFilesRead = true;
719 }
721 /** Track when the JavaCompiler has been used to compile something. */
722 private boolean hasBeenUsed = false;
723 private long start_msec = 0;
724 public long elapsed_msec = 0;
726 /** Track whether any errors occurred while parsing source text. */
727 private boolean parseErrors = false;
729 public void compile(List<JavaFileObject> sourceFileObject)
730 throws Throwable {
731 compile(sourceFileObject, List.<String>nil(), null);
732 }
734 /**
735 * Main method: compile a list of files, return all compiled classes
736 *
737 * @param sourceFileObjects file objects to be compiled
738 * @param classnames class names to process for annotations
739 * @param processors user provided annotation processors to bypass
740 * discovery, {@code null} means that no processors were provided
741 */
742 public void compile(List<JavaFileObject> sourceFileObjects,
743 List<String> classnames,
744 Iterable<? extends Processor> processors)
745 throws IOException // TODO: temp, from JavacProcessingEnvironment
746 {
747 if (processors != null && processors.iterator().hasNext())
748 explicitAnnotationProcessingRequested = true;
749 // as a JavaCompiler can only be used once, throw an exception if
750 // it has been used before.
751 if (hasBeenUsed)
752 throw new AssertionError("attempt to reuse JavaCompiler");
753 hasBeenUsed = true;
755 start_msec = now();
756 try {
757 initProcessAnnotations(processors);
759 // These method calls must be chained to avoid memory leaks
760 delegateCompiler = processAnnotations(enterTrees(stopIfError(parseFiles(sourceFileObjects))),
761 classnames);
763 delegateCompiler.compile2();
764 delegateCompiler.close();
765 elapsed_msec = delegateCompiler.elapsed_msec;
766 } catch (Abort ex) {
767 if (devVerbose)
768 ex.printStackTrace();
769 }
770 }
772 /**
773 * The phases following annotation processing: attribution,
774 * desugar, and finally code generation.
775 */
776 private void compile2() {
777 try {
778 switch (compilePolicy) {
779 case ATTR_ONLY:
780 attribute(todo);
781 break;
783 case CHECK_ONLY:
784 flow(attribute(todo));
785 break;
787 case SIMPLE:
788 generate(desugar(flow(attribute(todo))));
789 break;
791 case BY_FILE:
792 for (Queue<Env<AttrContext>> queue : groupByFile(flow(attribute(todo))).values())
793 generate(desugar(queue));
794 break;
796 case BY_TODO:
797 while (todo.nonEmpty())
798 generate(desugar(flow(attribute(todo.next()))));
799 break;
801 default:
802 assert false: "unknown compile policy";
803 }
804 } catch (Abort ex) {
805 if (devVerbose)
806 ex.printStackTrace();
807 }
809 if (verbose) {
810 elapsed_msec = elapsed(start_msec);
811 printVerbose("total", Long.toString(elapsed_msec));
812 }
814 reportDeferredDiagnostics();
816 if (!log.hasDiagnosticListener()) {
817 printCount("error", errorCount());
818 printCount("warn", warningCount());
819 }
820 }
822 private List<JCClassDecl> rootClasses;
824 /**
825 * Parses a list of files.
826 */
827 public List<JCCompilationUnit> parseFiles(List<JavaFileObject> fileObjects) throws IOException {
828 if (errorCount() > 0)
829 return List.nil();
831 //parse all files
832 ListBuffer<JCCompilationUnit> trees = lb();
833 for (JavaFileObject fileObject : fileObjects)
834 trees.append(parse(fileObject));
835 return trees.toList();
836 }
838 /**
839 * Enter the symbols found in a list of parse trees.
840 * As a side-effect, this puts elements on the "todo" list.
841 * Also stores a list of all top level classes in rootClasses.
842 */
843 public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
844 //enter symbols for all files
845 if (taskListener != null) {
846 for (JCCompilationUnit unit: roots) {
847 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
848 taskListener.started(e);
849 }
850 }
852 enter.main(roots);
854 if (taskListener != null) {
855 for (JCCompilationUnit unit: roots) {
856 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
857 taskListener.finished(e);
858 }
859 }
861 //If generating source, remember the classes declared in
862 //the original compilation units listed on the command line.
863 if (sourceOutput || stubOutput) {
864 ListBuffer<JCClassDecl> cdefs = lb();
865 for (JCCompilationUnit unit : roots) {
866 for (List<JCTree> defs = unit.defs;
867 defs.nonEmpty();
868 defs = defs.tail) {
869 if (defs.head instanceof JCClassDecl)
870 cdefs.append((JCClassDecl)defs.head);
871 }
872 }
873 rootClasses = cdefs.toList();
874 }
875 return roots;
876 }
878 /**
879 * Set to true to enable skeleton annotation processing code.
880 * Currently, we assume this variable will be replaced more
881 * advanced logic to figure out if annotation processing is
882 * needed.
883 */
884 boolean processAnnotations = false;
886 /**
887 * Object to handle annotation processing.
888 */
889 JavacProcessingEnvironment procEnvImpl = null;
891 /**
892 * Check if we should process annotations.
893 * If so, and if no scanner is yet registered, then set up the DocCommentScanner
894 * to catch doc comments, and set keepComments so the parser records them in
895 * the compilation unit.
896 *
897 * @param processors user provided annotation processors to bypass
898 * discovery, {@code null} means that no processors were provided
899 */
900 public void initProcessAnnotations(Iterable<? extends Processor> processors) {
901 // Process annotations if processing is not disabled and there
902 // is at least one Processor available.
903 Options options = Options.instance(context);
904 if (options.get("-proc:none") != null) {
905 processAnnotations = false;
906 } else if (procEnvImpl == null) {
907 procEnvImpl = new JavacProcessingEnvironment(context, processors);
908 processAnnotations = procEnvImpl.atLeastOneProcessor();
910 if (processAnnotations) {
911 if (context.get(Scanner.Factory.scannerFactoryKey) == null)
912 DocCommentScanner.Factory.preRegister(context);
913 options.put("save-parameter-names", "save-parameter-names");
914 reader.saveParameterNames = true;
915 keepComments = true;
916 if (taskListener != null)
917 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
920 } else { // free resources
921 procEnvImpl.close();
922 }
923 }
924 }
926 // TODO: called by JavacTaskImpl
927 public JavaCompiler processAnnotations(List<JCCompilationUnit> roots) throws IOException {
928 return processAnnotations(roots, List.<String>nil());
929 }
931 /**
932 * Process any anotations found in the specifed compilation units.
933 * @param roots a list of compilation units
934 * @return an instance of the compiler in which to complete the compilation
935 */
936 public JavaCompiler processAnnotations(List<JCCompilationUnit> roots,
937 List<String> classnames)
938 throws IOException { // TODO: see TEMP note in JavacProcessingEnvironment
939 if (errorCount() != 0) {
940 // Errors were encountered. If todo is empty, then the
941 // encountered errors were parse errors. Otherwise, the
942 // errors were found during the enter phase which should
943 // be ignored when processing annotations.
945 if (todo.isEmpty())
946 return this;
947 }
949 // ASSERT: processAnnotations and procEnvImpl should have been set up by
950 // by initProcessAnnotations
952 // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
954 if (!processAnnotations) {
955 // If there are no annotation processors present, and
956 // annotation processing is to occur with compilation,
957 // emit a warning.
958 Options options = Options.instance(context);
959 if (options.get("-proc:only") != null) {
960 log.warning("proc.proc-only.requested.no.procs");
961 todo.clear();
962 }
963 // If not processing annotations, classnames must be empty
964 if (!classnames.isEmpty()) {
965 log.error("proc.no.explicit.annotation.processing.requested",
966 classnames);
967 }
968 return this; // continue regular compilation
969 }
971 try {
972 List<ClassSymbol> classSymbols = List.nil();
973 List<PackageSymbol> pckSymbols = List.nil();
974 if (!classnames.isEmpty()) {
975 // Check for explicit request for annotation
976 // processing
977 if (!explicitAnnotationProcessingRequested()) {
978 log.error("proc.no.explicit.annotation.processing.requested",
979 classnames);
980 return this; // TODO: Will this halt compilation?
981 } else {
982 boolean errors = false;
983 for (String nameStr : classnames) {
984 Symbol sym = resolveIdent(nameStr);
985 if (sym == null || (sym.kind == Kinds.PCK && !processPcks)) {
986 log.error("proc.cant.find.class", nameStr);
987 errors = true;
988 continue;
989 }
990 try {
991 if (sym.kind == Kinds.PCK)
992 sym.complete();
993 if (sym.exists()) {
994 Name name = names.fromString(nameStr);
995 if (sym.kind == Kinds.PCK)
996 pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
997 else
998 classSymbols = classSymbols.prepend((ClassSymbol)sym);
999 continue;
1000 }
1001 assert sym.kind == Kinds.PCK;
1002 log.warning("proc.package.does.not.exist", nameStr);
1003 pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1004 } catch (CompletionFailure e) {
1005 log.error("proc.cant.find.class", nameStr);
1006 errors = true;
1007 continue;
1008 }
1009 }
1010 if (errors)
1011 return this;
1012 }
1013 }
1014 JavaCompiler c = procEnvImpl.doProcessing(context, roots, classSymbols, pckSymbols);
1015 if (c != this)
1016 annotationProcessingOccurred = c.annotationProcessingOccurred = true;
1017 return c;
1018 } catch (CompletionFailure ex) {
1019 log.error("cant.access", ex.sym, ex.getDetailValue());
1020 return this;
1022 }
1023 }
1025 boolean explicitAnnotationProcessingRequested() {
1026 Options options = Options.instance(context);
1027 return
1028 explicitAnnotationProcessingRequested ||
1029 options.get("-processor") != null ||
1030 options.get("-processorpath") != null ||
1031 options.get("-proc:only") != null ||
1032 options.get("-Xprint") != null;
1033 }
1035 /**
1036 * Attribute a list of parse trees, such as found on the "todo" list.
1037 * Note that attributing classes may cause additional files to be
1038 * parsed and entered via the SourceCompleter.
1039 * Attribution of the entries in the list does not stop if any errors occur.
1040 * @returns a list of environments for attributd classes.
1041 */
1042 public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
1043 ListBuffer<Env<AttrContext>> results = lb();
1044 while (!envs.isEmpty())
1045 results.append(attribute(envs.remove()));
1046 return results;
1047 }
1049 /**
1050 * Attribute a parse tree.
1051 * @returns the attributed parse tree
1052 */
1053 public Env<AttrContext> attribute(Env<AttrContext> env) {
1054 if (compileStates.isDone(env, CompileState.ATTR))
1055 return env;
1057 if (verboseCompilePolicy)
1058 log.printLines(log.noticeWriter, "[attribute " + env.enclClass.sym + "]");
1059 if (verbose)
1060 printVerbose("checking.attribution", env.enclClass.sym);
1062 if (taskListener != null) {
1063 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1064 taskListener.started(e);
1065 }
1067 JavaFileObject prev = log.useSource(
1068 env.enclClass.sym.sourcefile != null ?
1069 env.enclClass.sym.sourcefile :
1070 env.toplevel.sourcefile);
1071 try {
1072 attr.attribClass(env.tree.pos(), env.enclClass.sym);
1073 compileStates.put(env, CompileState.ATTR);
1074 }
1075 finally {
1076 log.useSource(prev);
1077 }
1079 return env;
1080 }
1082 /**
1083 * Perform dataflow checks on attributed parse trees.
1084 * These include checks for definite assignment and unreachable statements.
1085 * If any errors occur, an empty list will be returned.
1086 * @returns the list of attributed parse trees
1087 */
1088 public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
1089 ListBuffer<Env<AttrContext>> results = lb();
1090 for (Env<AttrContext> env: envs) {
1091 flow(env, results);
1092 }
1093 return stopIfError(results);
1094 }
1096 /**
1097 * Perform dataflow checks on an attributed parse tree.
1098 */
1099 public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
1100 ListBuffer<Env<AttrContext>> results = lb();
1101 flow(env, results);
1102 return stopIfError(results);
1103 }
1105 /**
1106 * Perform dataflow checks on an attributed parse tree.
1107 */
1108 protected void flow(Env<AttrContext> env, ListBuffer<Env<AttrContext>> results) {
1109 try {
1110 if (errorCount() > 0)
1111 return;
1113 if (relax || compileStates.isDone(env, CompileState.FLOW)) {
1114 results.append(env);
1115 return;
1116 }
1118 if (verboseCompilePolicy)
1119 log.printLines(log.noticeWriter, "[flow " + env.enclClass.sym + "]");
1120 JavaFileObject prev = log.useSource(
1121 env.enclClass.sym.sourcefile != null ?
1122 env.enclClass.sym.sourcefile :
1123 env.toplevel.sourcefile);
1124 try {
1125 make.at(Position.FIRSTPOS);
1126 TreeMaker localMake = make.forToplevel(env.toplevel);
1127 flow.analyzeTree(env.tree, localMake);
1128 compileStates.put(env, CompileState.FLOW);
1130 if (errorCount() > 0)
1131 return;
1133 results.append(env);
1134 }
1135 finally {
1136 log.useSource(prev);
1137 }
1138 }
1139 finally {
1140 if (taskListener != null) {
1141 TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
1142 taskListener.finished(e);
1143 }
1144 }
1145 }
1147 /**
1148 * Prepare attributed parse trees, in conjunction with their attribution contexts,
1149 * for source or code generation.
1150 * If any errors occur, an empty list will be returned.
1151 * @returns a list containing the classes to be generated
1152 */
1153 public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
1154 ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = lb();
1155 for (Env<AttrContext> env: envs)
1156 desugar(env, results);
1157 return stopIfError(results);
1158 }
1160 /**
1161 * Prepare attributed parse trees, in conjunction with their attribution contexts,
1162 * for source or code generation. If the file was not listed on the command line,
1163 * the current implicitSourcePolicy is taken into account.
1164 * The preparation stops as soon as an error is found.
1165 */
1166 protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
1167 if (errorCount() > 0)
1168 return;
1170 if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
1171 && !inputFiles.contains(env.toplevel.sourcefile)) {
1172 return;
1173 }
1175 /**
1176 * As erasure (TransTypes) destroys information needed in flow analysis,
1177 * including information in supertypes, we need to ensure that supertypes
1178 * are processed through attribute and flow before subtypes are translated.
1179 */
1180 class ScanNested extends TreeScanner {
1181 Set<Env<AttrContext>> dependencies = new LinkedHashSet<Env<AttrContext>>();
1182 public void visitClassDef(JCClassDecl node) {
1183 Type st = types.supertype(node.sym.type);
1184 if (st.tag == TypeTags.CLASS) {
1185 ClassSymbol c = st.tsym.outermostClass();
1186 Env<AttrContext> stEnv = enter.getEnv(c);
1187 if (stEnv != null && env != stEnv) {
1188 if (dependencies.add(stEnv))
1189 scan(stEnv.tree);
1190 }
1191 }
1192 super.visitClassDef(node);
1193 }
1194 }
1195 ScanNested scanner = new ScanNested();
1196 scanner.scan(env.tree);
1197 for (Env<AttrContext> dep: scanner.dependencies) {
1198 if (!compileStates.isDone(dep, CompileState.FLOW))
1199 flow(attribute(dep));
1200 }
1202 //We need to check for error another time as more classes might
1203 //have been attributed and analyzed at this stage
1204 if (errorCount() > 0)
1205 return;
1207 if (verboseCompilePolicy)
1208 log.printLines(log.noticeWriter, "[desugar " + env.enclClass.sym + "]");
1210 JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1211 env.enclClass.sym.sourcefile :
1212 env.toplevel.sourcefile);
1213 try {
1214 //save tree prior to rewriting
1215 JCTree untranslated = env.tree;
1217 make.at(Position.FIRSTPOS);
1218 TreeMaker localMake = make.forToplevel(env.toplevel);
1220 if (env.tree instanceof JCCompilationUnit) {
1221 if (!(stubOutput || sourceOutput || printFlat)) {
1222 List<JCTree> pdef = lower.translateTopLevelClass(env, env.tree, localMake);
1223 if (pdef.head != null) {
1224 assert pdef.tail.isEmpty();
1225 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, (JCClassDecl)pdef.head));
1226 }
1227 }
1228 return;
1229 }
1231 if (stubOutput) {
1232 //emit stub Java source file, only for compilation
1233 //units enumerated explicitly on the command line
1234 JCClassDecl cdef = (JCClassDecl)env.tree;
1235 if (untranslated instanceof JCClassDecl &&
1236 rootClasses.contains((JCClassDecl)untranslated) &&
1237 ((cdef.mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1238 cdef.sym.packge().getQualifiedName() == names.java_lang)) {
1239 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, removeMethodBodies(cdef)));
1240 }
1241 return;
1242 }
1244 env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
1246 if (errorCount() != 0)
1247 return;
1249 if (sourceOutput) {
1250 //emit standard Java source file, only for compilation
1251 //units enumerated explicitly on the command line
1252 JCClassDecl cdef = (JCClassDecl)env.tree;
1253 if (untranslated instanceof JCClassDecl &&
1254 rootClasses.contains((JCClassDecl)untranslated)) {
1255 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
1256 }
1257 return;
1258 }
1260 //translate out inner classes
1261 List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
1263 if (errorCount() != 0)
1264 return;
1266 //generate code for each class
1267 for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
1268 JCClassDecl cdef = (JCClassDecl)l.head;
1269 results.add(new Pair<Env<AttrContext>, JCClassDecl>(env, cdef));
1270 }
1271 }
1272 finally {
1273 log.useSource(prev);
1274 }
1276 }
1278 /** Generates the source or class file for a list of classes.
1279 * The decision to generate a source file or a class file is
1280 * based upon the compiler's options.
1281 * Generation stops if an error occurs while writing files.
1282 */
1283 public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
1284 generate(queue, null);
1285 }
1287 public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, ListBuffer<JavaFileObject> results) {
1288 boolean usePrintSource = (stubOutput || sourceOutput || printFlat);
1290 for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
1291 Env<AttrContext> env = x.fst;
1292 JCClassDecl cdef = x.snd;
1294 if (verboseCompilePolicy) {
1295 log.printLines(log.noticeWriter, "[generate "
1296 + (usePrintSource ? " source" : "code")
1297 + " " + env.enclClass.sym + "]");
1298 }
1300 if (taskListener != null) {
1301 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1302 taskListener.started(e);
1303 }
1305 JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1306 env.enclClass.sym.sourcefile :
1307 env.toplevel.sourcefile);
1308 try {
1309 JavaFileObject file;
1310 if (usePrintSource)
1311 file = printSource(env, cdef);
1312 else
1313 file = genCode(env, cdef);
1314 if (results != null && file != null)
1315 results.append(file);
1316 } catch (IOException ex) {
1317 log.error(cdef.pos(), "class.cant.write",
1318 cdef.sym, ex.getMessage());
1319 return;
1320 } finally {
1321 log.useSource(prev);
1322 }
1324 if (taskListener != null) {
1325 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1326 taskListener.finished(e);
1327 }
1328 }
1329 }
1331 // where
1332 Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
1333 // use a LinkedHashMap to preserve the order of the original list as much as possible
1334 Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<JCCompilationUnit, Queue<Env<AttrContext>>>();
1335 for (Env<AttrContext> env: envs) {
1336 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
1337 if (sublist == null) {
1338 sublist = new ListBuffer<Env<AttrContext>>();
1339 map.put(env.toplevel, sublist);
1340 }
1341 sublist.add(env);
1342 }
1343 return map;
1344 }
1346 JCClassDecl removeMethodBodies(JCClassDecl cdef) {
1347 final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
1348 class MethodBodyRemover extends TreeTranslator {
1349 public void visitMethodDef(JCMethodDecl tree) {
1350 tree.mods.flags &= ~Flags.SYNCHRONIZED;
1351 for (JCVariableDecl vd : tree.params)
1352 vd.mods.flags &= ~Flags.FINAL;
1353 tree.body = null;
1354 super.visitMethodDef(tree);
1355 }
1356 public void visitVarDef(JCVariableDecl tree) {
1357 if (tree.init != null && tree.init.type.constValue() == null)
1358 tree.init = null;
1359 super.visitVarDef(tree);
1360 }
1361 public void visitClassDef(JCClassDecl tree) {
1362 ListBuffer<JCTree> newdefs = lb();
1363 for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
1364 JCTree t = it.head;
1365 switch (t.getTag()) {
1366 case JCTree.CLASSDEF:
1367 if (isInterface ||
1368 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1369 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1370 newdefs.append(t);
1371 break;
1372 case JCTree.METHODDEF:
1373 if (isInterface ||
1374 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1375 ((JCMethodDecl) t).sym.name == names.init ||
1376 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1377 newdefs.append(t);
1378 break;
1379 case JCTree.VARDEF:
1380 if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1381 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1382 newdefs.append(t);
1383 break;
1384 default:
1385 break;
1386 }
1387 }
1388 tree.defs = newdefs.toList();
1389 super.visitClassDef(tree);
1390 }
1391 }
1392 MethodBodyRemover r = new MethodBodyRemover();
1393 return r.translate(cdef);
1394 }
1396 public void reportDeferredDiagnostics() {
1397 if (annotationProcessingOccurred
1398 && implicitSourceFilesRead
1399 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
1400 if (explicitAnnotationProcessingRequested())
1401 log.warning("proc.use.implicit");
1402 else
1403 log.warning("proc.use.proc.or.implicit");
1404 }
1405 chk.reportDeferredDiagnostics();
1406 }
1408 /** Close the compiler, flushing the logs
1409 */
1410 public void close() {
1411 close(true);
1412 }
1414 public void close(boolean disposeNames) {
1415 rootClasses = null;
1416 reader = null;
1417 make = null;
1418 writer = null;
1419 enter = null;
1420 if (todo != null)
1421 todo.clear();
1422 todo = null;
1423 parserFactory = null;
1424 syms = null;
1425 source = null;
1426 attr = null;
1427 chk = null;
1428 gen = null;
1429 flow = null;
1430 transTypes = null;
1431 lower = null;
1432 annotate = null;
1433 types = null;
1435 log.flush();
1436 try {
1437 fileManager.flush();
1438 } catch (IOException e) {
1439 throw new Abort(e);
1440 } finally {
1441 if (names != null && disposeNames)
1442 names.dispose();
1443 names = null;
1444 }
1445 }
1447 /** Output for "-verbose" option.
1448 * @param key The key to look up the correct internationalized string.
1449 * @param arg An argument for substitution into the output string.
1450 */
1451 protected void printVerbose(String key, Object arg) {
1452 Log.printLines(log.noticeWriter, log.getLocalizedString("verbose." + key, arg));
1453 }
1455 /** Print numbers of errors and warnings.
1456 */
1457 protected void printCount(String kind, int count) {
1458 if (count != 0) {
1459 String text;
1460 if (count == 1)
1461 text = log.getLocalizedString("count." + kind, String.valueOf(count));
1462 else
1463 text = log.getLocalizedString("count." + kind + ".plural", String.valueOf(count));
1464 Log.printLines(log.errWriter, text);
1465 log.errWriter.flush();
1466 }
1467 }
1469 private static long now() {
1470 return System.currentTimeMillis();
1471 }
1473 private static long elapsed(long then) {
1474 return now() - then;
1475 }
1477 public void initRound(JavaCompiler prev) {
1478 keepComments = prev.keepComments;
1479 start_msec = prev.start_msec;
1480 hasBeenUsed = true;
1481 }
1483 public static void enableLogging() {
1484 Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
1485 logger.setLevel(Level.ALL);
1486 for (Handler h : logger.getParent().getHandlers()) {
1487 h.setLevel(Level.ALL);
1488 }
1490 }
1491 }