Tue, 13 Jul 2010 19:14:09 -0700
6966732: replace use of static Log.getLocalizedString with non-static alternative where possible
Reviewed-by: darcy
1 /*
2 * Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.processing;
28 import java.lang.reflect.*;
29 import java.util.*;
30 import java.util.regex.*;
32 import java.net.URL;
33 import java.io.Closeable;
34 import java.io.File;
35 import java.io.PrintWriter;
36 import java.io.IOException;
37 import java.net.MalformedURLException;
38 import java.io.StringWriter;
40 import javax.annotation.processing.*;
41 import javax.lang.model.SourceVersion;
42 import javax.lang.model.element.AnnotationMirror;
43 import javax.lang.model.element.Element;
44 import javax.lang.model.element.TypeElement;
45 import javax.lang.model.element.PackageElement;
46 import javax.lang.model.util.*;
47 import javax.tools.JavaFileManager;
48 import javax.tools.StandardJavaFileManager;
49 import javax.tools.JavaFileObject;
50 import javax.tools.DiagnosticListener;
52 import com.sun.source.util.AbstractTypeProcessor;
53 import com.sun.source.util.TaskEvent;
54 import com.sun.source.util.TaskListener;
55 import com.sun.tools.javac.api.JavacTaskImpl;
56 import com.sun.tools.javac.code.*;
57 import com.sun.tools.javac.code.Symbol.*;
58 import com.sun.tools.javac.file.JavacFileManager;
59 import com.sun.tools.javac.jvm.*;
60 import com.sun.tools.javac.main.JavaCompiler;
61 import com.sun.tools.javac.main.JavaCompiler.CompileState;
62 import com.sun.tools.javac.model.JavacElements;
63 import com.sun.tools.javac.model.JavacTypes;
64 import com.sun.tools.javac.parser.*;
65 import com.sun.tools.javac.tree.*;
66 import com.sun.tools.javac.tree.JCTree.*;
67 import com.sun.tools.javac.util.Abort;
68 import com.sun.tools.javac.util.Context;
69 import com.sun.tools.javac.util.Convert;
70 import com.sun.tools.javac.util.List;
71 import com.sun.tools.javac.util.ListBuffer;
72 import com.sun.tools.javac.util.Log;
73 import com.sun.tools.javac.util.JavacMessages;
74 import com.sun.tools.javac.util.Name;
75 import com.sun.tools.javac.util.Names;
76 import com.sun.tools.javac.util.Options;
78 import static javax.tools.StandardLocation.*;
80 /**
81 * Objects of this class hold and manage the state needed to support
82 * annotation processing.
83 *
84 * <p><b>This is NOT part of any supported API.
85 * If you write code that depends on this, you do so at your own risk.
86 * This code and its internal interfaces are subject to change or
87 * deletion without notice.</b>
88 */
89 public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
90 Options options;
92 private final boolean printProcessorInfo;
93 private final boolean printRounds;
94 private final boolean verbose;
95 private final boolean lint;
96 private final boolean procOnly;
97 private final boolean fatalErrors;
98 private boolean foundTypeProcessors;
100 private final JavacFiler filer;
101 private final JavacMessager messager;
102 private final JavacElements elementUtils;
103 private final JavacTypes typeUtils;
105 /**
106 * Holds relevant state history of which processors have been
107 * used.
108 */
109 private DiscoveredProcessors discoveredProcs;
111 /**
112 * Map of processor-specific options.
113 */
114 private final Map<String, String> processorOptions;
116 /**
117 */
118 private final Set<String> unmatchedProcessorOptions;
120 /**
121 * Annotations implicitly processed and claimed by javac.
122 */
123 private final Set<String> platformAnnotations;
125 /**
126 * Set of packages given on command line.
127 */
128 private Set<PackageSymbol> specifiedPackages = Collections.emptySet();
130 /** The log to be used for error reporting.
131 */
132 Log log;
134 /**
135 * Source level of the compile.
136 */
137 Source source;
139 private ClassLoader processorClassLoader;
141 /**
142 * JavacMessages object used for localization
143 */
144 private JavacMessages messages;
146 private Context context;
148 public JavacProcessingEnvironment(Context context, Iterable<? extends Processor> processors) {
149 options = Options.instance(context);
150 this.context = context;
151 log = Log.instance(context);
152 source = Source.instance(context);
153 printProcessorInfo = options.get("-XprintProcessorInfo") != null;
154 printRounds = options.get("-XprintRounds") != null;
155 verbose = options.get("-verbose") != null;
156 lint = options.lint("processing");
157 procOnly = options.get("-proc:only") != null ||
158 options.get("-Xprint") != null;
159 fatalErrors = options.get("fatalEnterError") != null;
160 platformAnnotations = initPlatformAnnotations();
161 foundTypeProcessors = false;
163 // Initialize services before any processors are initialzied
164 // in case processors use them.
165 filer = new JavacFiler(context);
166 messager = new JavacMessager(context, this);
167 elementUtils = new JavacElements(context);
168 typeUtils = new JavacTypes(context);
169 processorOptions = initProcessorOptions(context);
170 unmatchedProcessorOptions = initUnmatchedProcessorOptions();
171 messages = JavacMessages.instance(context);
172 initProcessorIterator(context, processors);
173 }
175 private Set<String> initPlatformAnnotations() {
176 Set<String> platformAnnotations = new HashSet<String>();
177 platformAnnotations.add("java.lang.Deprecated");
178 platformAnnotations.add("java.lang.Override");
179 platformAnnotations.add("java.lang.SuppressWarnings");
180 platformAnnotations.add("java.lang.annotation.Documented");
181 platformAnnotations.add("java.lang.annotation.Inherited");
182 platformAnnotations.add("java.lang.annotation.Retention");
183 platformAnnotations.add("java.lang.annotation.Target");
184 return Collections.unmodifiableSet(platformAnnotations);
185 }
187 private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
188 Log log = Log.instance(context);
189 Iterator<? extends Processor> processorIterator;
191 if (options.get("-Xprint") != null) {
192 try {
193 Processor processor = PrintingProcessor.class.newInstance();
194 processorIterator = List.of(processor).iterator();
195 } catch (Throwable t) {
196 AssertionError assertError =
197 new AssertionError("Problem instantiating PrintingProcessor.");
198 assertError.initCause(t);
199 throw assertError;
200 }
201 } else if (processors != null) {
202 processorIterator = processors.iterator();
203 } else {
204 String processorNames = options.get("-processor");
205 JavaFileManager fileManager = context.get(JavaFileManager.class);
206 try {
207 // If processorpath is not explicitly set, use the classpath.
208 processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
209 ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
210 : fileManager.getClassLoader(CLASS_PATH);
212 /*
213 * If the "-processor" option is used, search the appropriate
214 * path for the named class. Otherwise, use a service
215 * provider mechanism to create the processor iterator.
216 */
217 if (processorNames != null) {
218 processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
219 } else {
220 processorIterator = new ServiceIterator(processorClassLoader, log);
221 }
222 } catch (SecurityException e) {
223 /*
224 * A security exception will occur if we can't create a classloader.
225 * Ignore the exception if, with hindsight, we didn't need it anyway
226 * (i.e. no processor was specified either explicitly, or implicitly,
227 * in service configuration file.) Otherwise, we cannot continue.
228 */
229 processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader", e);
230 }
231 }
232 discoveredProcs = new DiscoveredProcessors(processorIterator);
233 }
235 /**
236 * Returns an empty processor iterator if no processors are on the
237 * relevant path, otherwise if processors are present, logs an
238 * error. Called when a service loader is unavailable for some
239 * reason, either because a service loader class cannot be found
240 * or because a security policy prevents class loaders from being
241 * created.
242 *
243 * @param key The resource key to use to log an error message
244 * @param e If non-null, pass this exception to Abort
245 */
246 private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
247 JavaFileManager fileManager = context.get(JavaFileManager.class);
249 if (fileManager instanceof JavacFileManager) {
250 StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
251 Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
252 ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
253 : standardFileManager.getLocation(CLASS_PATH);
255 if (needClassLoader(options.get("-processor"), workingPath) )
256 handleException(key, e);
258 } else {
259 handleException(key, e);
260 }
262 java.util.List<Processor> pl = Collections.emptyList();
263 return pl.iterator();
264 }
266 /**
267 * Handle a security exception thrown during initializing the
268 * Processor iterator.
269 */
270 private void handleException(String key, Exception e) {
271 if (e != null) {
272 log.error(key, e.getLocalizedMessage());
273 throw new Abort(e);
274 } else {
275 log.error(key);
276 throw new Abort();
277 }
278 }
280 /**
281 * Use a service loader appropriate for the platform to provide an
282 * iterator over annotations processors. If
283 * java.util.ServiceLoader is present use it, otherwise, use
284 * sun.misc.Service, otherwise fail if a loader is needed.
285 */
286 private class ServiceIterator implements Iterator<Processor> {
287 // The to-be-wrapped iterator.
288 private Iterator<?> iterator;
289 private Log log;
290 private Class<?> loaderClass;
291 private boolean jusl;
292 private Object loader;
294 ServiceIterator(ClassLoader classLoader, Log log) {
295 String loadMethodName;
297 this.log = log;
298 try {
299 try {
300 loaderClass = Class.forName("java.util.ServiceLoader");
301 loadMethodName = "load";
302 jusl = true;
303 } catch (ClassNotFoundException cnfe) {
304 try {
305 loaderClass = Class.forName("sun.misc.Service");
306 loadMethodName = "providers";
307 jusl = false;
308 } catch (ClassNotFoundException cnfe2) {
309 // Fail softly if a loader is not actually needed.
310 this.iterator = handleServiceLoaderUnavailability("proc.no.service",
311 null);
312 return;
313 }
314 }
316 // java.util.ServiceLoader.load or sun.misc.Service.providers
317 Method loadMethod = loaderClass.getMethod(loadMethodName,
318 Class.class,
319 ClassLoader.class);
321 Object result = loadMethod.invoke(null,
322 Processor.class,
323 classLoader);
325 // For java.util.ServiceLoader, we have to call another
326 // method to get the iterator.
327 if (jusl) {
328 loader = result; // Store ServiceLoader to call reload later
329 Method m = loaderClass.getMethod("iterator");
330 result = m.invoke(result); // serviceLoader.iterator();
331 }
333 // The result should now be an iterator.
334 this.iterator = (Iterator<?>) result;
335 } catch (Throwable t) {
336 log.error("proc.service.problem");
337 throw new Abort(t);
338 }
339 }
341 public boolean hasNext() {
342 try {
343 return iterator.hasNext();
344 } catch (Throwable t) {
345 if ("ServiceConfigurationError".
346 equals(t.getClass().getSimpleName())) {
347 log.error("proc.bad.config.file", t.getLocalizedMessage());
348 }
349 throw new Abort(t);
350 }
351 }
353 public Processor next() {
354 try {
355 return (Processor)(iterator.next());
356 } catch (Throwable t) {
357 if ("ServiceConfigurationError".
358 equals(t.getClass().getSimpleName())) {
359 log.error("proc.bad.config.file", t.getLocalizedMessage());
360 } else {
361 log.error("proc.processor.constructor.error", t.getLocalizedMessage());
362 }
363 throw new Abort(t);
364 }
365 }
367 public void remove() {
368 throw new UnsupportedOperationException();
369 }
371 public void close() {
372 if (jusl) {
373 try {
374 // Call java.util.ServiceLoader.reload
375 Method reloadMethod = loaderClass.getMethod("reload");
376 reloadMethod.invoke(loader);
377 } catch(Exception e) {
378 ; // Ignore problems during a call to reload.
379 }
380 }
381 }
382 }
385 private static class NameProcessIterator implements Iterator<Processor> {
386 Processor nextProc = null;
387 Iterator<String> names;
388 ClassLoader processorCL;
389 Log log;
391 NameProcessIterator(String names, ClassLoader processorCL, Log log) {
392 this.names = Arrays.asList(names.split(",")).iterator();
393 this.processorCL = processorCL;
394 this.log = log;
395 }
397 public boolean hasNext() {
398 if (nextProc != null)
399 return true;
400 else {
401 if (!names.hasNext())
402 return false;
403 else {
404 String processorName = names.next();
406 Processor processor;
407 try {
408 try {
409 processor =
410 (Processor) (processorCL.loadClass(processorName).newInstance());
411 } catch (ClassNotFoundException cnfe) {
412 log.error("proc.processor.not.found", processorName);
413 return false;
414 } catch (ClassCastException cce) {
415 log.error("proc.processor.wrong.type", processorName);
416 return false;
417 } catch (Exception e ) {
418 log.error("proc.processor.cant.instantiate", processorName);
419 return false;
420 }
421 } catch(Throwable t) {
422 throw new AnnotationProcessingError(t);
423 }
424 nextProc = processor;
425 return true;
426 }
428 }
429 }
431 public Processor next() {
432 if (hasNext()) {
433 Processor p = nextProc;
434 nextProc = null;
435 return p;
436 } else
437 throw new NoSuchElementException();
438 }
440 public void remove () {
441 throw new UnsupportedOperationException();
442 }
443 }
445 public boolean atLeastOneProcessor() {
446 return discoveredProcs.iterator().hasNext();
447 }
449 private Map<String, String> initProcessorOptions(Context context) {
450 Options options = Options.instance(context);
451 Set<String> keySet = options.keySet();
452 Map<String, String> tempOptions = new LinkedHashMap<String, String>();
454 for(String key : keySet) {
455 if (key.startsWith("-A") && key.length() > 2) {
456 int sepIndex = key.indexOf('=');
457 String candidateKey = null;
458 String candidateValue = null;
460 if (sepIndex == -1)
461 candidateKey = key.substring(2);
462 else if (sepIndex >= 3) {
463 candidateKey = key.substring(2, sepIndex);
464 candidateValue = (sepIndex < key.length()-1)?
465 key.substring(sepIndex+1) : null;
466 }
467 tempOptions.put(candidateKey, candidateValue);
468 }
469 }
471 return Collections.unmodifiableMap(tempOptions);
472 }
474 private Set<String> initUnmatchedProcessorOptions() {
475 Set<String> unmatchedProcessorOptions = new HashSet<String>();
476 unmatchedProcessorOptions.addAll(processorOptions.keySet());
477 return unmatchedProcessorOptions;
478 }
480 /**
481 * State about how a processor has been used by the tool. If a
482 * processor has been used on a prior round, its process method is
483 * called on all subsequent rounds, perhaps with an empty set of
484 * annotations to process. The {@code annotatedSupported} method
485 * caches the supported annotation information from the first (and
486 * only) getSupportedAnnotationTypes call to the processor.
487 */
488 static class ProcessorState {
489 public Processor processor;
490 public boolean contributed;
491 private ArrayList<Pattern> supportedAnnotationPatterns;
492 private ArrayList<String> supportedOptionNames;
494 ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
495 processor = p;
496 contributed = false;
498 try {
499 processor.init(env);
501 checkSourceVersionCompatibility(source, log);
503 supportedAnnotationPatterns = new ArrayList<Pattern>();
504 for (String importString : processor.getSupportedAnnotationTypes()) {
505 supportedAnnotationPatterns.add(importStringToPattern(importString,
506 processor,
507 log));
508 }
510 supportedOptionNames = new ArrayList<String>();
511 for (String optionName : processor.getSupportedOptions() ) {
512 if (checkOptionName(optionName, log))
513 supportedOptionNames.add(optionName);
514 }
516 } catch (Throwable t) {
517 throw new AnnotationProcessingError(t);
518 }
519 }
521 /**
522 * Checks whether or not a processor's source version is
523 * compatible with the compilation source version. The
524 * processor's source version needs to be greater than or
525 * equal to the source version of the compile.
526 */
527 private void checkSourceVersionCompatibility(Source source, Log log) {
528 SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
530 if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 ) {
531 log.warning("proc.processor.incompatible.source.version",
532 procSourceVersion,
533 processor.getClass().getName(),
534 source.name);
535 }
536 }
538 private boolean checkOptionName(String optionName, Log log) {
539 boolean valid = isValidOptionName(optionName);
540 if (!valid)
541 log.error("proc.processor.bad.option.name",
542 optionName,
543 processor.getClass().getName());
544 return valid;
545 }
547 public boolean annotationSupported(String annotationName) {
548 for(Pattern p: supportedAnnotationPatterns) {
549 if (p.matcher(annotationName).matches())
550 return true;
551 }
552 return false;
553 }
555 /**
556 * Remove options that are matched by this processor.
557 */
558 public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) {
559 unmatchedProcessorOptions.removeAll(supportedOptionNames);
560 }
561 }
563 // TODO: These two classes can probably be rewritten better...
564 /**
565 * This class holds information about the processors that have
566 * been discoverd so far as well as the means to discover more, if
567 * necessary. A single iterator should be used per round of
568 * annotation processing. The iterator first visits already
569 * discovered processors then fails over to the service provider
570 * mechanism if additional queries are made.
571 */
572 class DiscoveredProcessors implements Iterable<ProcessorState> {
574 class ProcessorStateIterator implements Iterator<ProcessorState> {
575 DiscoveredProcessors psi;
576 Iterator<ProcessorState> innerIter;
577 boolean onProcInterator;
579 ProcessorStateIterator(DiscoveredProcessors psi) {
580 this.psi = psi;
581 this.innerIter = psi.procStateList.iterator();
582 this.onProcInterator = false;
583 }
585 public ProcessorState next() {
586 if (!onProcInterator) {
587 if (innerIter.hasNext())
588 return innerIter.next();
589 else
590 onProcInterator = true;
591 }
593 if (psi.processorIterator.hasNext()) {
594 ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
595 log, source, JavacProcessingEnvironment.this);
596 psi.procStateList.add(ps);
597 return ps;
598 } else
599 throw new NoSuchElementException();
600 }
602 public boolean hasNext() {
603 if (onProcInterator)
604 return psi.processorIterator.hasNext();
605 else
606 return innerIter.hasNext() || psi.processorIterator.hasNext();
607 }
609 public void remove () {
610 throw new UnsupportedOperationException();
611 }
613 /**
614 * Run all remaining processors on the procStateList that
615 * have not already run this round with an empty set of
616 * annotations.
617 */
618 public void runContributingProcs(RoundEnvironment re) {
619 if (!onProcInterator) {
620 Set<TypeElement> emptyTypeElements = Collections.emptySet();
621 while(innerIter.hasNext()) {
622 ProcessorState ps = innerIter.next();
623 if (ps.contributed)
624 callProcessor(ps.processor, emptyTypeElements, re);
625 }
626 }
627 }
628 }
630 Iterator<? extends Processor> processorIterator;
631 ArrayList<ProcessorState> procStateList;
633 public ProcessorStateIterator iterator() {
634 return new ProcessorStateIterator(this);
635 }
637 DiscoveredProcessors(Iterator<? extends Processor> processorIterator) {
638 this.processorIterator = processorIterator;
639 this.procStateList = new ArrayList<ProcessorState>();
640 }
642 /**
643 * Free jar files, etc. if using a service loader.
644 */
645 public void close() {
646 if (processorIterator != null &&
647 processorIterator instanceof ServiceIterator) {
648 ((ServiceIterator) processorIterator).close();
649 }
650 }
651 }
653 private void discoverAndRunProcs(Context context,
654 Set<TypeElement> annotationsPresent,
655 List<ClassSymbol> topLevelClasses,
656 List<PackageSymbol> packageInfoFiles) {
657 Map<String, TypeElement> unmatchedAnnotations =
658 new HashMap<String, TypeElement>(annotationsPresent.size());
660 for(TypeElement a : annotationsPresent) {
661 unmatchedAnnotations.put(a.getQualifiedName().toString(),
662 a);
663 }
665 // Give "*" processors a chance to match
666 if (unmatchedAnnotations.size() == 0)
667 unmatchedAnnotations.put("", null);
669 DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
670 // TODO: Create proper argument values; need past round
671 // information to fill in this constructor. Note that the 1
672 // st round of processing could be the last round if there
673 // were parse errors on the initial source files; however, we
674 // are not doing processing in that case.
676 Set<Element> rootElements = new LinkedHashSet<Element>();
677 rootElements.addAll(topLevelClasses);
678 rootElements.addAll(packageInfoFiles);
679 rootElements = Collections.unmodifiableSet(rootElements);
681 RoundEnvironment renv = new JavacRoundEnvironment(false,
682 false,
683 rootElements,
684 JavacProcessingEnvironment.this);
686 while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
687 ProcessorState ps = psi.next();
688 Set<String> matchedNames = new HashSet<String>();
689 Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();
691 for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) {
692 String unmatchedAnnotationName = entry.getKey();
693 if (ps.annotationSupported(unmatchedAnnotationName) ) {
694 matchedNames.add(unmatchedAnnotationName);
695 TypeElement te = entry.getValue();
696 if (te != null)
697 typeElements.add(te);
698 }
699 }
701 if (matchedNames.size() > 0 || ps.contributed) {
702 foundTypeProcessors = foundTypeProcessors || (ps.processor instanceof AbstractTypeProcessor);
703 boolean processingResult = callProcessor(ps.processor, typeElements, renv);
704 ps.contributed = true;
705 ps.removeSupportedOptions(unmatchedProcessorOptions);
707 if (printProcessorInfo || verbose) {
708 log.printNoteLines("x.print.processor.info",
709 ps.processor.getClass().getName(),
710 matchedNames.toString(),
711 processingResult);
712 }
714 if (processingResult) {
715 unmatchedAnnotations.keySet().removeAll(matchedNames);
716 }
718 }
719 }
720 unmatchedAnnotations.remove("");
722 if (lint && unmatchedAnnotations.size() > 0) {
723 // Remove annotations processed by javac
724 unmatchedAnnotations.keySet().removeAll(platformAnnotations);
725 if (unmatchedAnnotations.size() > 0) {
726 log = Log.instance(context);
727 log.warning("proc.annotations.without.processors",
728 unmatchedAnnotations.keySet());
729 }
730 }
732 // Run contributing processors that haven't run yet
733 psi.runContributingProcs(renv);
735 // Debugging
736 if (options.get("displayFilerState") != null)
737 filer.displayState();
738 }
740 /**
741 * Computes the set of annotations on the symbol in question.
742 * Leave class public for external testing purposes.
743 */
744 public static class ComputeAnnotationSet extends
745 ElementScanner7<Set<TypeElement>, Set<TypeElement>> {
746 final Elements elements;
748 public ComputeAnnotationSet(Elements elements) {
749 super();
750 this.elements = elements;
751 }
753 @Override
754 public Set<TypeElement> visitPackage(PackageElement e, Set<TypeElement> p) {
755 // Don't scan enclosed elements of a package
756 return p;
757 }
759 @Override
760 public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
761 for (AnnotationMirror annotationMirror :
762 elements.getAllAnnotationMirrors(e) ) {
763 Element e2 = annotationMirror.getAnnotationType().asElement();
764 p.add((TypeElement) e2);
765 }
766 return super.scan(e, p);
767 }
768 }
770 private boolean callProcessor(Processor proc,
771 Set<? extends TypeElement> tes,
772 RoundEnvironment renv) {
773 try {
774 return proc.process(tes, renv);
775 } catch (CompletionFailure ex) {
776 StringWriter out = new StringWriter();
777 ex.printStackTrace(new PrintWriter(out));
778 log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
779 return false;
780 } catch (Throwable t) {
781 throw new AnnotationProcessingError(t);
782 }
783 }
786 // TODO: internal catch clauses?; catch and rethrow an annotation
787 // processing error
788 public JavaCompiler doProcessing(Context context,
789 List<JCCompilationUnit> roots,
790 List<ClassSymbol> classSymbols,
791 Iterable<? extends PackageSymbol> pckSymbols)
792 throws IOException {
794 log = Log.instance(context);
795 TaskListener taskListener = context.get(TaskListener.class);
797 JavaCompiler compiler = JavaCompiler.instance(context);
798 compiler.todo.clear(); // free the compiler's resources
800 int round = 0;
802 // List<JCAnnotation> annotationsPresentInSource = collector.findAnnotations(roots);
803 List<ClassSymbol> topLevelClasses = getTopLevelClasses(roots);
805 for (ClassSymbol classSym : classSymbols)
806 topLevelClasses = topLevelClasses.prepend(classSym);
807 List<PackageSymbol> packageInfoFiles =
808 getPackageInfoFiles(roots);
810 Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
811 for (PackageSymbol psym : pckSymbols)
812 specifiedPackages.add(psym);
813 this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
815 // Use annotation processing to compute the set of annotations present
816 Set<TypeElement> annotationsPresent = new LinkedHashSet<TypeElement>();
817 ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
818 for (ClassSymbol classSym : topLevelClasses)
819 annotationComputer.scan(classSym, annotationsPresent);
820 for (PackageSymbol pkgSym : packageInfoFiles)
821 annotationComputer.scan(pkgSym, annotationsPresent);
823 Context currentContext = context;
825 int roundNumber = 0;
826 boolean errorStatus = false;
828 runAround:
829 while(true) {
830 if (fatalErrors && compiler.errorCount() != 0) {
831 errorStatus = true;
832 break runAround;
833 }
835 this.context = currentContext;
836 roundNumber++;
837 printRoundInfo(roundNumber, topLevelClasses, annotationsPresent, false);
839 if (taskListener != null)
840 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
842 try {
843 discoverAndRunProcs(currentContext, annotationsPresent, topLevelClasses, packageInfoFiles);
844 } finally {
845 if (taskListener != null)
846 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
847 }
849 /*
850 * Processors for round n have run to completion. Prepare
851 * for round (n+1) by checked for errors raised by
852 * annotation processors and then checking for syntax
853 * errors on any generated source files.
854 */
855 if (messager.errorRaised()) {
856 errorStatus = true;
857 break runAround;
858 } else {
859 if (moreToDo()) {
860 // annotationsPresentInSource = List.nil();
861 annotationsPresent = new LinkedHashSet<TypeElement>();
862 topLevelClasses = List.nil();
863 packageInfoFiles = List.nil();
865 compiler.close(false);
866 currentContext = contextForNextRound(currentContext, true);
868 JavaFileManager fileManager = currentContext.get(JavaFileManager.class);
870 compiler = JavaCompiler.instance(currentContext);
871 List<JCCompilationUnit> parsedFiles = sourcesToParsedFiles(compiler);
872 roots = cleanTrees(roots).appendList(parsedFiles);
874 // Check for errors after parsing
875 if (log.unrecoverableError) {
876 errorStatus = true;
877 break runAround;
878 } else {
879 List<ClassSymbol> newClasses = enterNewClassFiles(currentContext);
880 compiler.enterTrees(roots);
882 // annotationsPresentInSource =
883 // collector.findAnnotations(parsedFiles);
884 ListBuffer<ClassSymbol> tlc = new ListBuffer<ClassSymbol>();
885 tlc.appendList(getTopLevelClasses(parsedFiles));
886 tlc.appendList(getTopLevelClassesFromClasses(newClasses));
887 topLevelClasses = tlc.toList();
889 ListBuffer<PackageSymbol> pif = new ListBuffer<PackageSymbol>();
890 pif.appendList(getPackageInfoFiles(parsedFiles));
891 pif.appendList(getPackageInfoFilesFromClasses(newClasses));
892 packageInfoFiles = pif.toList();
894 annotationsPresent = new LinkedHashSet<TypeElement>();
895 for (ClassSymbol classSym : topLevelClasses)
896 annotationComputer.scan(classSym, annotationsPresent);
897 for (PackageSymbol pkgSym : packageInfoFiles)
898 annotationComputer.scan(pkgSym, annotationsPresent);
900 updateProcessingState(currentContext, false);
901 }
902 } else
903 break runAround; // No new files
904 }
905 }
906 roots = runLastRound(roundNumber, errorStatus, compiler, roots, taskListener);
907 // Set error status for any files compiled and generated in
908 // the last round
909 if (log.unrecoverableError)
910 errorStatus = true;
912 compiler.close(false);
913 currentContext = contextForNextRound(currentContext, true);
914 compiler = JavaCompiler.instance(currentContext);
916 filer.newRound(currentContext, true);
917 filer.warnIfUnclosedFiles();
918 warnIfUnmatchedOptions();
920 /*
921 * If an annotation processor raises an error in a round,
922 * that round runs to completion and one last round occurs.
923 * The last round may also occur because no more source or
924 * class files have been generated. Therefore, if an error
925 * was raised on either of the last *two* rounds, the compile
926 * should exit with a nonzero exit code. The current value of
927 * errorStatus holds whether or not an error was raised on the
928 * second to last round; errorRaised() gives the error status
929 * of the last round.
930 */
931 errorStatus = errorStatus || messager.errorRaised();
934 // Free resources
935 this.close();
937 if (taskListener != null)
938 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
940 if (errorStatus) {
941 compiler.log.nerrors += messager.errorCount();
942 if (compiler.errorCount() == 0)
943 compiler.log.nerrors++;
944 } else if (procOnly && !foundTypeProcessors) {
945 compiler.todo.clear();
946 } else { // Final compilation
947 compiler.close(false);
948 currentContext = contextForNextRound(currentContext, true);
949 this.context = currentContext;
950 updateProcessingState(currentContext, true);
951 compiler = JavaCompiler.instance(currentContext);
952 if (procOnly && foundTypeProcessors)
953 compiler.shouldStopPolicy = CompileState.FLOW;
955 if (true) {
956 compiler.enterTrees(cleanTrees(roots));
957 } else {
958 List<JavaFileObject> fileObjects = List.nil();
959 for (JCCompilationUnit unit : roots)
960 fileObjects = fileObjects.prepend(unit.getSourceFile());
961 roots = null;
962 compiler.enterTrees(compiler.parseFiles(fileObjects.reverse()));
963 }
964 }
966 return compiler;
967 }
969 private List<JCCompilationUnit> sourcesToParsedFiles(JavaCompiler compiler)
970 throws IOException {
971 List<JavaFileObject> fileObjects = List.nil();
972 for (JavaFileObject jfo : filer.getGeneratedSourceFileObjects() ) {
973 fileObjects = fileObjects.prepend(jfo);
974 }
976 return compiler.parseFiles(fileObjects);
977 }
979 // Call the last round of annotation processing
980 private List<JCCompilationUnit> runLastRound(int roundNumber,
981 boolean errorStatus,
982 JavaCompiler compiler,
983 List<JCCompilationUnit> roots,
984 TaskListener taskListener) throws IOException {
985 roundNumber++;
986 List<ClassSymbol> noTopLevelClasses = List.nil();
987 Set<TypeElement> noAnnotations = Collections.emptySet();
988 printRoundInfo(roundNumber, noTopLevelClasses, noAnnotations, true);
990 Set<Element> emptyRootElements = Collections.emptySet(); // immutable
991 RoundEnvironment renv = new JavacRoundEnvironment(true,
992 errorStatus,
993 emptyRootElements,
994 JavacProcessingEnvironment.this);
995 if (taskListener != null)
996 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
998 try {
999 discoveredProcs.iterator().runContributingProcs(renv);
1000 } finally {
1001 if (taskListener != null)
1002 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1003 }
1005 // Add any sources generated during the last round to the set
1006 // of files to be compiled.
1007 if (moreToDo()) {
1008 List<JCCompilationUnit> parsedFiles = sourcesToParsedFiles(compiler);
1009 roots = cleanTrees(roots).appendList(parsedFiles);
1010 }
1012 return roots;
1013 }
1015 private void updateProcessingState(Context currentContext, boolean lastRound) {
1016 filer.newRound(currentContext, lastRound);
1017 messager.newRound(currentContext);
1019 elementUtils.setContext(currentContext);
1020 typeUtils.setContext(currentContext);
1021 }
1023 private void warnIfUnmatchedOptions() {
1024 if (!unmatchedProcessorOptions.isEmpty()) {
1025 log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
1026 }
1027 }
1029 private void printRoundInfo(int roundNumber,
1030 List<ClassSymbol> topLevelClasses,
1031 Set<TypeElement> annotationsPresent,
1032 boolean lastRound) {
1033 if (printRounds || verbose) {
1034 log.printNoteLines("x.print.rounds",
1035 roundNumber,
1036 "{" + topLevelClasses.toString(", ") + "}",
1037 annotationsPresent,
1038 lastRound);
1039 }
1040 }
1042 private List<ClassSymbol> enterNewClassFiles(Context currentContext) {
1043 ClassReader reader = ClassReader.instance(currentContext);
1044 Names names = Names.instance(currentContext);
1045 List<ClassSymbol> list = List.nil();
1047 for (Map.Entry<String,JavaFileObject> entry : filer.getGeneratedClasses().entrySet()) {
1048 Name name = names.fromString(entry.getKey());
1049 JavaFileObject file = entry.getValue();
1050 if (file.getKind() != JavaFileObject.Kind.CLASS)
1051 throw new AssertionError(file);
1052 ClassSymbol cs;
1053 if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
1054 Name packageName = Convert.packagePart(name);
1055 PackageSymbol p = reader.enterPackage(packageName);
1056 if (p.package_info == null)
1057 p.package_info = reader.enterClass(Convert.shortName(name), p);
1058 cs = p.package_info;
1059 if (cs.classfile == null)
1060 cs.classfile = file;
1061 } else
1062 cs = reader.enterClass(name, file);
1063 list = list.prepend(cs);
1064 }
1065 return list.reverse();
1066 }
1068 /**
1069 * Free resources related to annotation processing.
1070 */
1071 public void close() throws IOException {
1072 filer.close();
1073 if (discoveredProcs != null) // Make calling close idempotent
1074 discoveredProcs.close();
1075 discoveredProcs = null;
1076 if (processorClassLoader != null && processorClassLoader instanceof Closeable)
1077 ((Closeable) processorClassLoader).close();
1078 }
1080 private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
1081 List<ClassSymbol> classes = List.nil();
1082 for (JCCompilationUnit unit : units) {
1083 for (JCTree node : unit.defs) {
1084 if (node.getTag() == JCTree.CLASSDEF) {
1085 classes = classes.prepend(((JCClassDecl) node).sym);
1086 }
1087 }
1088 }
1089 return classes.reverse();
1090 }
1092 private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) {
1093 List<ClassSymbol> classes = List.nil();
1094 for (ClassSymbol sym : syms) {
1095 if (!isPkgInfo(sym)) {
1096 classes = classes.prepend(sym);
1097 }
1098 }
1099 return classes.reverse();
1100 }
1102 private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
1103 List<PackageSymbol> packages = List.nil();
1104 for (JCCompilationUnit unit : units) {
1105 if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
1106 packages = packages.prepend(unit.packge);
1107 }
1108 }
1109 return packages.reverse();
1110 }
1112 private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) {
1113 List<PackageSymbol> packages = List.nil();
1114 for (ClassSymbol sym : syms) {
1115 if (isPkgInfo(sym)) {
1116 packages = packages.prepend((PackageSymbol) sym.owner);
1117 }
1118 }
1119 return packages.reverse();
1120 }
1122 private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
1123 return fo.isNameCompatible("package-info", kind);
1124 }
1126 private boolean isPkgInfo(ClassSymbol sym) {
1127 return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
1128 }
1130 private Context contextForNextRound(Context context, boolean shareNames)
1131 throws IOException
1132 {
1133 Context next = new Context();
1135 Options options = Options.instance(context);
1136 assert options != null;
1137 next.put(Options.optionsKey, options);
1139 PrintWriter out = context.get(Log.outKey);
1140 assert out != null;
1141 next.put(Log.outKey, out);
1143 if (shareNames) {
1144 Names names = Names.instance(context);
1145 assert names != null;
1146 next.put(Names.namesKey, names);
1147 }
1149 DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
1150 if (dl != null)
1151 next.put(DiagnosticListener.class, dl);
1153 TaskListener tl = context.get(TaskListener.class);
1154 if (tl != null)
1155 next.put(TaskListener.class, tl);
1157 JavaFileManager jfm = context.get(JavaFileManager.class);
1158 assert jfm != null;
1159 next.put(JavaFileManager.class, jfm);
1160 if (jfm instanceof JavacFileManager) {
1161 ((JavacFileManager)jfm).setContext(next);
1162 }
1164 Names names = Names.instance(context);
1165 assert names != null;
1166 next.put(Names.namesKey, names);
1168 Keywords keywords = Keywords.instance(context);
1169 assert(keywords != null);
1170 next.put(Keywords.keywordsKey, keywords);
1172 JavaCompiler oldCompiler = JavaCompiler.instance(context);
1173 JavaCompiler nextCompiler = JavaCompiler.instance(next);
1174 nextCompiler.initRound(oldCompiler);
1176 JavacTaskImpl task = context.get(JavacTaskImpl.class);
1177 if (task != null) {
1178 next.put(JavacTaskImpl.class, task);
1179 task.updateContext(next);
1180 }
1182 context.clear();
1183 return next;
1184 }
1186 /*
1187 * Called retroactively to determine if a class loader was required,
1188 * after we have failed to create one.
1189 */
1190 private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
1191 if (procNames != null)
1192 return true;
1194 String procPath;
1195 URL[] urls = new URL[1];
1196 for(File pathElement : workingpath) {
1197 try {
1198 urls[0] = pathElement.toURI().toURL();
1199 if (ServiceProxy.hasService(Processor.class, urls))
1200 return true;
1201 } catch (MalformedURLException ex) {
1202 throw new AssertionError(ex);
1203 }
1204 catch (ServiceProxy.ServiceConfigurationError e) {
1205 log.error("proc.bad.config.file", e.getLocalizedMessage());
1206 return true;
1207 }
1208 }
1210 return false;
1211 }
1213 private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) {
1214 for (T node : nodes)
1215 treeCleaner.scan(node);
1216 return nodes;
1217 }
1219 private static TreeScanner treeCleaner = new TreeScanner() {
1220 public void scan(JCTree node) {
1221 super.scan(node);
1222 if (node != null)
1223 node.type = null;
1224 }
1225 public void visitTopLevel(JCCompilationUnit node) {
1226 node.packge = null;
1227 super.visitTopLevel(node);
1228 }
1229 public void visitClassDef(JCClassDecl node) {
1230 node.sym = null;
1231 super.visitClassDef(node);
1232 }
1233 public void visitMethodDef(JCMethodDecl node) {
1234 node.sym = null;
1235 super.visitMethodDef(node);
1236 }
1237 public void visitVarDef(JCVariableDecl node) {
1238 node.sym = null;
1239 super.visitVarDef(node);
1240 }
1241 public void visitNewClass(JCNewClass node) {
1242 node.constructor = null;
1243 super.visitNewClass(node);
1244 }
1245 public void visitAssignop(JCAssignOp node) {
1246 node.operator = null;
1247 super.visitAssignop(node);
1248 }
1249 public void visitUnary(JCUnary node) {
1250 node.operator = null;
1251 super.visitUnary(node);
1252 }
1253 public void visitBinary(JCBinary node) {
1254 node.operator = null;
1255 super.visitBinary(node);
1256 }
1257 public void visitSelect(JCFieldAccess node) {
1258 node.sym = null;
1259 super.visitSelect(node);
1260 }
1261 public void visitIdent(JCIdent node) {
1262 node.sym = null;
1263 super.visitIdent(node);
1264 }
1265 };
1268 private boolean moreToDo() {
1269 return filer.newFiles();
1270 }
1272 /**
1273 * {@inheritdoc}
1274 *
1275 * Command line options suitable for presenting to annotation
1276 * processors. "-Afoo=bar" should be "-Afoo" => "bar".
1277 */
1278 public Map<String,String> getOptions() {
1279 return processorOptions;
1280 }
1282 public Messager getMessager() {
1283 return messager;
1284 }
1286 public Filer getFiler() {
1287 return filer;
1288 }
1290 public JavacElements getElementUtils() {
1291 return elementUtils;
1292 }
1294 public JavacTypes getTypeUtils() {
1295 return typeUtils;
1296 }
1298 public SourceVersion getSourceVersion() {
1299 return Source.toSourceVersion(source);
1300 }
1302 public Locale getLocale() {
1303 return messages.getCurrentLocale();
1304 }
1306 public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
1307 return specifiedPackages;
1308 }
1310 private static final Pattern allMatches = Pattern.compile(".*");
1311 public static final Pattern noMatches = Pattern.compile("(\\P{all})+");
1313 /**
1314 * Convert import-style string for supported annotations into a
1315 * regex matching that string. If the string is a valid
1316 * import-style string, return a regex that won't match anything.
1317 */
1318 private static Pattern importStringToPattern(String s, Processor p, Log log) {
1319 if (isValidImportString(s)) {
1320 return validImportStringToPattern(s);
1321 } else {
1322 log.warning("proc.malformed.supported.string", s, p.getClass().getName());
1323 return noMatches; // won't match any valid identifier
1324 }
1325 }
1327 /**
1328 * Return true if the argument string is a valid import-style
1329 * string specifying claimed annotations; return false otherwise.
1330 */
1331 public static boolean isValidImportString(String s) {
1332 if (s.equals("*"))
1333 return true;
1335 boolean valid = true;
1336 String t = s;
1337 int index = t.indexOf('*');
1339 if (index != -1) {
1340 // '*' must be last character...
1341 if (index == t.length() -1) {
1342 // ... any and preceding character must be '.'
1343 if ( index-1 >= 0 ) {
1344 valid = t.charAt(index-1) == '.';
1345 // Strip off ".*$" for identifier checks
1346 t = t.substring(0, t.length()-2);
1347 }
1348 } else
1349 return false;
1350 }
1352 // Verify string is off the form (javaId \.)+ or javaId
1353 if (valid) {
1354 String[] javaIds = t.split("\\.", t.length()+2);
1355 for(String javaId: javaIds)
1356 valid &= SourceVersion.isIdentifier(javaId);
1357 }
1358 return valid;
1359 }
1361 public static Pattern validImportStringToPattern(String s) {
1362 if (s.equals("*")) {
1363 return allMatches;
1364 } else {
1365 String s_prime = s.replace(".", "\\.");
1367 if (s_prime.endsWith("*")) {
1368 s_prime = s_prime.substring(0, s_prime.length() - 1) + ".+";
1369 }
1371 return Pattern.compile(s_prime);
1372 }
1373 }
1375 /**
1376 * For internal use only. This method will be
1377 * removed without warning.
1378 */
1379 public Context getContext() {
1380 return context;
1381 }
1383 public String toString() {
1384 return "javac ProcessingEnvironment";
1385 }
1387 public static boolean isValidOptionName(String optionName) {
1388 for(String s : optionName.split("\\.", -1)) {
1389 if (!SourceVersion.isIdentifier(s))
1390 return false;
1391 }
1392 return true;
1393 }
1394 }