Mon, 28 Feb 2011 13:37:48 -0800
7022741: warning counts are wrong after anno processing
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 2005, 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.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.TaskEvent;
53 import com.sun.source.util.TaskListener;
54 import com.sun.tools.javac.api.JavacTaskImpl;
55 import com.sun.tools.javac.api.JavacTrees;
56 import com.sun.tools.javac.code.*;
57 import com.sun.tools.javac.code.Symbol.*;
58 import com.sun.tools.javac.file.FSInfo;
59 import com.sun.tools.javac.file.JavacFileManager;
60 import com.sun.tools.javac.jvm.*;
61 import com.sun.tools.javac.main.JavaCompiler;
62 import com.sun.tools.javac.main.JavaCompiler.CompileState;
63 import com.sun.tools.javac.model.JavacElements;
64 import com.sun.tools.javac.model.JavacTypes;
65 import com.sun.tools.javac.parser.*;
66 import com.sun.tools.javac.tree.*;
67 import com.sun.tools.javac.tree.JCTree.*;
68 import com.sun.tools.javac.util.Abort;
69 import com.sun.tools.javac.util.Assert;
70 import com.sun.tools.javac.util.Context;
71 import com.sun.tools.javac.util.Convert;
72 import com.sun.tools.javac.util.FatalError;
73 import com.sun.tools.javac.util.JCDiagnostic;
74 import com.sun.tools.javac.util.List;
75 import com.sun.tools.javac.util.Log;
76 import com.sun.tools.javac.util.JavacMessages;
77 import com.sun.tools.javac.util.Name;
78 import com.sun.tools.javac.util.Names;
79 import com.sun.tools.javac.util.Options;
81 import static javax.tools.StandardLocation.*;
82 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
83 import static com.sun.tools.javac.main.OptionName.*;
84 import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
86 /**
87 * Objects of this class hold and manage the state needed to support
88 * annotation processing.
89 *
90 * <p><b>This is NOT part of any supported API.
91 * If you write code that depends on this, you do so at your own risk.
92 * This code and its internal interfaces are subject to change or
93 * deletion without notice.</b>
94 */
95 public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
96 Options options;
98 private final boolean printProcessorInfo;
99 private final boolean printRounds;
100 private final boolean verbose;
101 private final boolean lint;
102 private final boolean procOnly;
103 private final boolean fatalErrors;
104 private final boolean werror;
105 private final boolean showResolveErrors;
106 private boolean foundTypeProcessors;
108 private final JavacFiler filer;
109 private final JavacMessager messager;
110 private final JavacElements elementUtils;
111 private final JavacTypes typeUtils;
113 /**
114 * Holds relevant state history of which processors have been
115 * used.
116 */
117 private DiscoveredProcessors discoveredProcs;
119 /**
120 * Map of processor-specific options.
121 */
122 private final Map<String, String> processorOptions;
124 /**
125 */
126 private final Set<String> unmatchedProcessorOptions;
128 /**
129 * Annotations implicitly processed and claimed by javac.
130 */
131 private final Set<String> platformAnnotations;
133 /**
134 * Set of packages given on command line.
135 */
136 private Set<PackageSymbol> specifiedPackages = Collections.emptySet();
138 /** The log to be used for error reporting.
139 */
140 Log log;
142 /** Diagnostic factory.
143 */
144 JCDiagnostic.Factory diags;
146 /**
147 * Source level of the compile.
148 */
149 Source source;
151 private ClassLoader processorClassLoader;
153 /**
154 * JavacMessages object used for localization
155 */
156 private JavacMessages messages;
158 private Context context;
160 public JavacProcessingEnvironment(Context context, Iterable<? extends Processor> processors) {
161 this.context = context;
162 log = Log.instance(context);
163 source = Source.instance(context);
164 diags = JCDiagnostic.Factory.instance(context);
165 options = Options.instance(context);
166 printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
167 printRounds = options.isSet(XPRINTROUNDS);
168 verbose = options.isSet(VERBOSE);
169 lint = Lint.instance(context).isEnabled(PROCESSING);
170 procOnly = options.isSet(PROC, "only") || options.isSet(XPRINT);
171 fatalErrors = options.isSet("fatalEnterError");
172 showResolveErrors = options.isSet("showResolveErrors");
173 werror = options.isSet(WERROR);
174 platformAnnotations = initPlatformAnnotations();
175 foundTypeProcessors = false;
177 // Initialize services before any processors are initialized
178 // in case processors use them.
179 filer = new JavacFiler(context);
180 messager = new JavacMessager(context, this);
181 elementUtils = JavacElements.instance(context);
182 typeUtils = JavacTypes.instance(context);
183 processorOptions = initProcessorOptions(context);
184 unmatchedProcessorOptions = initUnmatchedProcessorOptions();
185 messages = JavacMessages.instance(context);
186 initProcessorIterator(context, processors);
187 }
189 private Set<String> initPlatformAnnotations() {
190 Set<String> platformAnnotations = new HashSet<String>();
191 platformAnnotations.add("java.lang.Deprecated");
192 platformAnnotations.add("java.lang.Override");
193 platformAnnotations.add("java.lang.SuppressWarnings");
194 platformAnnotations.add("java.lang.annotation.Documented");
195 platformAnnotations.add("java.lang.annotation.Inherited");
196 platformAnnotations.add("java.lang.annotation.Retention");
197 platformAnnotations.add("java.lang.annotation.Target");
198 return Collections.unmodifiableSet(platformAnnotations);
199 }
201 private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
202 Log log = Log.instance(context);
203 Iterator<? extends Processor> processorIterator;
205 if (options.isSet(XPRINT)) {
206 try {
207 Processor processor = PrintingProcessor.class.newInstance();
208 processorIterator = List.of(processor).iterator();
209 } catch (Throwable t) {
210 AssertionError assertError =
211 new AssertionError("Problem instantiating PrintingProcessor.");
212 assertError.initCause(t);
213 throw assertError;
214 }
215 } else if (processors != null) {
216 processorIterator = processors.iterator();
217 } else {
218 String processorNames = options.get(PROCESSOR);
219 JavaFileManager fileManager = context.get(JavaFileManager.class);
220 try {
221 // If processorpath is not explicitly set, use the classpath.
222 processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
223 ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
224 : fileManager.getClassLoader(CLASS_PATH);
226 /*
227 * If the "-processor" option is used, search the appropriate
228 * path for the named class. Otherwise, use a service
229 * provider mechanism to create the processor iterator.
230 */
231 if (processorNames != null) {
232 processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
233 } else {
234 processorIterator = new ServiceIterator(processorClassLoader, log);
235 }
236 } catch (SecurityException e) {
237 /*
238 * A security exception will occur if we can't create a classloader.
239 * Ignore the exception if, with hindsight, we didn't need it anyway
240 * (i.e. no processor was specified either explicitly, or implicitly,
241 * in service configuration file.) Otherwise, we cannot continue.
242 */
243 processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader", e);
244 }
245 }
246 discoveredProcs = new DiscoveredProcessors(processorIterator);
247 }
249 /**
250 * Returns an empty processor iterator if no processors are on the
251 * relevant path, otherwise if processors are present, logs an
252 * error. Called when a service loader is unavailable for some
253 * reason, either because a service loader class cannot be found
254 * or because a security policy prevents class loaders from being
255 * created.
256 *
257 * @param key The resource key to use to log an error message
258 * @param e If non-null, pass this exception to Abort
259 */
260 private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
261 JavaFileManager fileManager = context.get(JavaFileManager.class);
263 if (fileManager instanceof JavacFileManager) {
264 StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
265 Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
266 ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
267 : standardFileManager.getLocation(CLASS_PATH);
269 if (needClassLoader(options.get(PROCESSOR), workingPath) )
270 handleException(key, e);
272 } else {
273 handleException(key, e);
274 }
276 java.util.List<Processor> pl = Collections.emptyList();
277 return pl.iterator();
278 }
280 /**
281 * Handle a security exception thrown during initializing the
282 * Processor iterator.
283 */
284 private void handleException(String key, Exception e) {
285 if (e != null) {
286 log.error(key, e.getLocalizedMessage());
287 throw new Abort(e);
288 } else {
289 log.error(key);
290 throw new Abort();
291 }
292 }
294 /**
295 * Use a service loader appropriate for the platform to provide an
296 * iterator over annotations processors. If
297 * java.util.ServiceLoader is present use it, otherwise, use
298 * sun.misc.Service, otherwise fail if a loader is needed.
299 */
300 private class ServiceIterator implements Iterator<Processor> {
301 // The to-be-wrapped iterator.
302 private Iterator<?> iterator;
303 private Log log;
304 private Class<?> loaderClass;
305 private boolean jusl;
306 private Object loader;
308 ServiceIterator(ClassLoader classLoader, Log log) {
309 String loadMethodName;
311 this.log = log;
312 try {
313 try {
314 loaderClass = Class.forName("java.util.ServiceLoader");
315 loadMethodName = "load";
316 jusl = true;
317 } catch (ClassNotFoundException cnfe) {
318 try {
319 loaderClass = Class.forName("sun.misc.Service");
320 loadMethodName = "providers";
321 jusl = false;
322 } catch (ClassNotFoundException cnfe2) {
323 // Fail softly if a loader is not actually needed.
324 this.iterator = handleServiceLoaderUnavailability("proc.no.service",
325 null);
326 return;
327 }
328 }
330 // java.util.ServiceLoader.load or sun.misc.Service.providers
331 Method loadMethod = loaderClass.getMethod(loadMethodName,
332 Class.class,
333 ClassLoader.class);
335 Object result = loadMethod.invoke(null,
336 Processor.class,
337 classLoader);
339 // For java.util.ServiceLoader, we have to call another
340 // method to get the iterator.
341 if (jusl) {
342 loader = result; // Store ServiceLoader to call reload later
343 Method m = loaderClass.getMethod("iterator");
344 result = m.invoke(result); // serviceLoader.iterator();
345 }
347 // The result should now be an iterator.
348 this.iterator = (Iterator<?>) result;
349 } catch (Throwable t) {
350 log.error("proc.service.problem");
351 throw new Abort(t);
352 }
353 }
355 public boolean hasNext() {
356 try {
357 return iterator.hasNext();
358 } catch (Throwable t) {
359 if ("ServiceConfigurationError".
360 equals(t.getClass().getSimpleName())) {
361 log.error("proc.bad.config.file", t.getLocalizedMessage());
362 }
363 throw new Abort(t);
364 }
365 }
367 public Processor next() {
368 try {
369 return (Processor)(iterator.next());
370 } catch (Throwable t) {
371 if ("ServiceConfigurationError".
372 equals(t.getClass().getSimpleName())) {
373 log.error("proc.bad.config.file", t.getLocalizedMessage());
374 } else {
375 log.error("proc.processor.constructor.error", t.getLocalizedMessage());
376 }
377 throw new Abort(t);
378 }
379 }
381 public void remove() {
382 throw new UnsupportedOperationException();
383 }
385 public void close() {
386 if (jusl) {
387 try {
388 // Call java.util.ServiceLoader.reload
389 Method reloadMethod = loaderClass.getMethod("reload");
390 reloadMethod.invoke(loader);
391 } catch(Exception e) {
392 ; // Ignore problems during a call to reload.
393 }
394 }
395 }
396 }
399 private static class NameProcessIterator implements Iterator<Processor> {
400 Processor nextProc = null;
401 Iterator<String> names;
402 ClassLoader processorCL;
403 Log log;
405 NameProcessIterator(String names, ClassLoader processorCL, Log log) {
406 this.names = Arrays.asList(names.split(",")).iterator();
407 this.processorCL = processorCL;
408 this.log = log;
409 }
411 public boolean hasNext() {
412 if (nextProc != null)
413 return true;
414 else {
415 if (!names.hasNext())
416 return false;
417 else {
418 String processorName = names.next();
420 Processor processor;
421 try {
422 try {
423 processor =
424 (Processor) (processorCL.loadClass(processorName).newInstance());
425 } catch (ClassNotFoundException cnfe) {
426 log.error("proc.processor.not.found", processorName);
427 return false;
428 } catch (ClassCastException cce) {
429 log.error("proc.processor.wrong.type", processorName);
430 return false;
431 } catch (Exception e ) {
432 log.error("proc.processor.cant.instantiate", processorName);
433 return false;
434 }
435 } catch(Throwable t) {
436 throw new AnnotationProcessingError(t);
437 }
438 nextProc = processor;
439 return true;
440 }
442 }
443 }
445 public Processor next() {
446 if (hasNext()) {
447 Processor p = nextProc;
448 nextProc = null;
449 return p;
450 } else
451 throw new NoSuchElementException();
452 }
454 public void remove () {
455 throw new UnsupportedOperationException();
456 }
457 }
459 public boolean atLeastOneProcessor() {
460 return discoveredProcs.iterator().hasNext();
461 }
463 private Map<String, String> initProcessorOptions(Context context) {
464 Options options = Options.instance(context);
465 Set<String> keySet = options.keySet();
466 Map<String, String> tempOptions = new LinkedHashMap<String, String>();
468 for(String key : keySet) {
469 if (key.startsWith("-A") && key.length() > 2) {
470 int sepIndex = key.indexOf('=');
471 String candidateKey = null;
472 String candidateValue = null;
474 if (sepIndex == -1)
475 candidateKey = key.substring(2);
476 else if (sepIndex >= 3) {
477 candidateKey = key.substring(2, sepIndex);
478 candidateValue = (sepIndex < key.length()-1)?
479 key.substring(sepIndex+1) : null;
480 }
481 tempOptions.put(candidateKey, candidateValue);
482 }
483 }
485 return Collections.unmodifiableMap(tempOptions);
486 }
488 private Set<String> initUnmatchedProcessorOptions() {
489 Set<String> unmatchedProcessorOptions = new HashSet<String>();
490 unmatchedProcessorOptions.addAll(processorOptions.keySet());
491 return unmatchedProcessorOptions;
492 }
494 /**
495 * State about how a processor has been used by the tool. If a
496 * processor has been used on a prior round, its process method is
497 * called on all subsequent rounds, perhaps with an empty set of
498 * annotations to process. The {@code annotatedSupported} method
499 * caches the supported annotation information from the first (and
500 * only) getSupportedAnnotationTypes call to the processor.
501 */
502 static class ProcessorState {
503 public Processor processor;
504 public boolean contributed;
505 private ArrayList<Pattern> supportedAnnotationPatterns;
506 private ArrayList<String> supportedOptionNames;
508 ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
509 processor = p;
510 contributed = false;
512 try {
513 processor.init(env);
515 checkSourceVersionCompatibility(source, log);
517 supportedAnnotationPatterns = new ArrayList<Pattern>();
518 for (String importString : processor.getSupportedAnnotationTypes()) {
519 supportedAnnotationPatterns.add(importStringToPattern(importString,
520 processor,
521 log));
522 }
524 supportedOptionNames = new ArrayList<String>();
525 for (String optionName : processor.getSupportedOptions() ) {
526 if (checkOptionName(optionName, log))
527 supportedOptionNames.add(optionName);
528 }
530 } catch (Throwable t) {
531 throw new AnnotationProcessingError(t);
532 }
533 }
535 /**
536 * Checks whether or not a processor's source version is
537 * compatible with the compilation source version. The
538 * processor's source version needs to be greater than or
539 * equal to the source version of the compile.
540 */
541 private void checkSourceVersionCompatibility(Source source, Log log) {
542 SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
544 if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 ) {
545 log.warning("proc.processor.incompatible.source.version",
546 procSourceVersion,
547 processor.getClass().getName(),
548 source.name);
549 }
550 }
552 private boolean checkOptionName(String optionName, Log log) {
553 boolean valid = isValidOptionName(optionName);
554 if (!valid)
555 log.error("proc.processor.bad.option.name",
556 optionName,
557 processor.getClass().getName());
558 return valid;
559 }
561 public boolean annotationSupported(String annotationName) {
562 for(Pattern p: supportedAnnotationPatterns) {
563 if (p.matcher(annotationName).matches())
564 return true;
565 }
566 return false;
567 }
569 /**
570 * Remove options that are matched by this processor.
571 */
572 public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) {
573 unmatchedProcessorOptions.removeAll(supportedOptionNames);
574 }
575 }
577 // TODO: These two classes can probably be rewritten better...
578 /**
579 * This class holds information about the processors that have
580 * been discoverd so far as well as the means to discover more, if
581 * necessary. A single iterator should be used per round of
582 * annotation processing. The iterator first visits already
583 * discovered processors then fails over to the service provider
584 * mechanism if additional queries are made.
585 */
586 class DiscoveredProcessors implements Iterable<ProcessorState> {
588 class ProcessorStateIterator implements Iterator<ProcessorState> {
589 DiscoveredProcessors psi;
590 Iterator<ProcessorState> innerIter;
591 boolean onProcInterator;
593 ProcessorStateIterator(DiscoveredProcessors psi) {
594 this.psi = psi;
595 this.innerIter = psi.procStateList.iterator();
596 this.onProcInterator = false;
597 }
599 public ProcessorState next() {
600 if (!onProcInterator) {
601 if (innerIter.hasNext())
602 return innerIter.next();
603 else
604 onProcInterator = true;
605 }
607 if (psi.processorIterator.hasNext()) {
608 ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
609 log, source, JavacProcessingEnvironment.this);
610 psi.procStateList.add(ps);
611 return ps;
612 } else
613 throw new NoSuchElementException();
614 }
616 public boolean hasNext() {
617 if (onProcInterator)
618 return psi.processorIterator.hasNext();
619 else
620 return innerIter.hasNext() || psi.processorIterator.hasNext();
621 }
623 public void remove () {
624 throw new UnsupportedOperationException();
625 }
627 /**
628 * Run all remaining processors on the procStateList that
629 * have not already run this round with an empty set of
630 * annotations.
631 */
632 public void runContributingProcs(RoundEnvironment re) {
633 if (!onProcInterator) {
634 Set<TypeElement> emptyTypeElements = Collections.emptySet();
635 while(innerIter.hasNext()) {
636 ProcessorState ps = innerIter.next();
637 if (ps.contributed)
638 callProcessor(ps.processor, emptyTypeElements, re);
639 }
640 }
641 }
642 }
644 Iterator<? extends Processor> processorIterator;
645 ArrayList<ProcessorState> procStateList;
647 public ProcessorStateIterator iterator() {
648 return new ProcessorStateIterator(this);
649 }
651 DiscoveredProcessors(Iterator<? extends Processor> processorIterator) {
652 this.processorIterator = processorIterator;
653 this.procStateList = new ArrayList<ProcessorState>();
654 }
656 /**
657 * Free jar files, etc. if using a service loader.
658 */
659 public void close() {
660 if (processorIterator != null &&
661 processorIterator instanceof ServiceIterator) {
662 ((ServiceIterator) processorIterator).close();
663 }
664 }
665 }
667 private void discoverAndRunProcs(Context context,
668 Set<TypeElement> annotationsPresent,
669 List<ClassSymbol> topLevelClasses,
670 List<PackageSymbol> packageInfoFiles) {
671 Map<String, TypeElement> unmatchedAnnotations =
672 new HashMap<String, TypeElement>(annotationsPresent.size());
674 for(TypeElement a : annotationsPresent) {
675 unmatchedAnnotations.put(a.getQualifiedName().toString(),
676 a);
677 }
679 // Give "*" processors a chance to match
680 if (unmatchedAnnotations.size() == 0)
681 unmatchedAnnotations.put("", null);
683 DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
684 // TODO: Create proper argument values; need past round
685 // information to fill in this constructor. Note that the 1
686 // st round of processing could be the last round if there
687 // were parse errors on the initial source files; however, we
688 // are not doing processing in that case.
690 Set<Element> rootElements = new LinkedHashSet<Element>();
691 rootElements.addAll(topLevelClasses);
692 rootElements.addAll(packageInfoFiles);
693 rootElements = Collections.unmodifiableSet(rootElements);
695 RoundEnvironment renv = new JavacRoundEnvironment(false,
696 false,
697 rootElements,
698 JavacProcessingEnvironment.this);
700 while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
701 ProcessorState ps = psi.next();
702 Set<String> matchedNames = new HashSet<String>();
703 Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();
705 for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) {
706 String unmatchedAnnotationName = entry.getKey();
707 if (ps.annotationSupported(unmatchedAnnotationName) ) {
708 matchedNames.add(unmatchedAnnotationName);
709 TypeElement te = entry.getValue();
710 if (te != null)
711 typeElements.add(te);
712 }
713 }
715 if (matchedNames.size() > 0 || ps.contributed) {
716 boolean processingResult = callProcessor(ps.processor, typeElements, renv);
717 ps.contributed = true;
718 ps.removeSupportedOptions(unmatchedProcessorOptions);
720 if (printProcessorInfo || verbose) {
721 log.printNoteLines("x.print.processor.info",
722 ps.processor.getClass().getName(),
723 matchedNames.toString(),
724 processingResult);
725 }
727 if (processingResult) {
728 unmatchedAnnotations.keySet().removeAll(matchedNames);
729 }
731 }
732 }
733 unmatchedAnnotations.remove("");
735 if (lint && unmatchedAnnotations.size() > 0) {
736 // Remove annotations processed by javac
737 unmatchedAnnotations.keySet().removeAll(platformAnnotations);
738 if (unmatchedAnnotations.size() > 0) {
739 log = Log.instance(context);
740 log.warning("proc.annotations.without.processors",
741 unmatchedAnnotations.keySet());
742 }
743 }
745 // Run contributing processors that haven't run yet
746 psi.runContributingProcs(renv);
748 // Debugging
749 if (options.isSet("displayFilerState"))
750 filer.displayState();
751 }
753 /**
754 * Computes the set of annotations on the symbol in question.
755 * Leave class public for external testing purposes.
756 */
757 public static class ComputeAnnotationSet extends
758 ElementScanner7<Set<TypeElement>, Set<TypeElement>> {
759 final Elements elements;
761 public ComputeAnnotationSet(Elements elements) {
762 super();
763 this.elements = elements;
764 }
766 @Override
767 public Set<TypeElement> visitPackage(PackageElement e, Set<TypeElement> p) {
768 // Don't scan enclosed elements of a package
769 return p;
770 }
772 @Override
773 public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
774 for (AnnotationMirror annotationMirror :
775 elements.getAllAnnotationMirrors(e) ) {
776 Element e2 = annotationMirror.getAnnotationType().asElement();
777 p.add((TypeElement) e2);
778 }
779 return super.scan(e, p);
780 }
781 }
783 private boolean callProcessor(Processor proc,
784 Set<? extends TypeElement> tes,
785 RoundEnvironment renv) {
786 try {
787 return proc.process(tes, renv);
788 } catch (CompletionFailure ex) {
789 StringWriter out = new StringWriter();
790 ex.printStackTrace(new PrintWriter(out));
791 log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
792 return false;
793 } catch (Throwable t) {
794 throw new AnnotationProcessingError(t);
795 }
796 }
798 /**
799 * Helper object for a single round of annotation processing.
800 */
801 class Round {
802 /** The round number. */
803 final int number;
804 /** The context for the round. */
805 final Context context;
806 /** The compiler for the round. */
807 final JavaCompiler compiler;
808 /** The log for the round. */
809 final Log log;
811 /** The ASTs to be compiled. */
812 List<JCCompilationUnit> roots;
813 /** The classes to be compiler that have were generated. */
814 Map<String, JavaFileObject> genClassFiles;
816 /** The set of annotations to be processed this round. */
817 Set<TypeElement> annotationsPresent;
818 /** The set of top level classes to be processed this round. */
819 List<ClassSymbol> topLevelClasses;
820 /** The set of package-info files to be processed this round. */
821 List<PackageSymbol> packageInfoFiles;
823 /** Create a round (common code). */
824 private Round(Context context, int number, int priorWarnings) {
825 this.context = context;
826 this.number = number;
828 compiler = JavaCompiler.instance(context);
829 log = Log.instance(context);
830 log.nwarnings += priorWarnings;
831 log.deferDiagnostics = true;
833 // the following is for the benefit of JavacProcessingEnvironment.getContext()
834 JavacProcessingEnvironment.this.context = context;
836 // the following will be populated as needed
837 topLevelClasses = List.nil();
838 packageInfoFiles = List.nil();
839 }
841 /** Create the first round. */
842 Round(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols) {
843 this(context, 1, 0);
844 this.roots = roots;
845 genClassFiles = new HashMap<String,JavaFileObject>();
847 compiler.todo.clear(); // free the compiler's resources
849 // The reverse() in the following line is to maintain behavioural
850 // compatibility with the previous revision of the code. Strictly speaking,
851 // it should not be necessary, but a javah golden file test fails without it.
852 topLevelClasses =
853 getTopLevelClasses(roots).prependList(classSymbols.reverse());
855 packageInfoFiles = getPackageInfoFiles(roots);
857 findAnnotationsPresent();
858 }
860 /** Create a new round. */
861 private Round(Round prev,
862 Set<JavaFileObject> newSourceFiles, Map<String,JavaFileObject> newClassFiles) {
863 this(prev.nextContext(), prev.number+1, prev.compiler.log.nwarnings);
864 this.genClassFiles = prev.genClassFiles;
866 List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles);
867 roots = cleanTrees(prev.roots).appendList(parsedFiles);
869 // Check for errors after parsing
870 if (unrecoverableError())
871 return;
873 enterClassFiles(genClassFiles);
874 List<ClassSymbol> newClasses = enterClassFiles(newClassFiles);
875 genClassFiles.putAll(newClassFiles);
876 enterTrees(roots);
878 if (unrecoverableError())
879 return;
881 topLevelClasses = join(
882 getTopLevelClasses(parsedFiles),
883 getTopLevelClassesFromClasses(newClasses));
885 packageInfoFiles = join(
886 getPackageInfoFiles(parsedFiles),
887 getPackageInfoFilesFromClasses(newClasses));
889 findAnnotationsPresent();
890 }
892 /** Create the next round to be used. */
893 Round next(Set<JavaFileObject> newSourceFiles, Map<String, JavaFileObject> newClassFiles) {
894 try {
895 return new Round(this, newSourceFiles, newClassFiles);
896 } finally {
897 compiler.close(false);
898 }
899 }
901 /** Create the compiler to be used for the final compilation. */
902 JavaCompiler finalCompiler(boolean errorStatus) {
903 try {
904 JavaCompiler c = JavaCompiler.instance(nextContext());
905 c.log.nwarnings += compiler.log.nwarnings;
906 if (errorStatus) {
907 c.log.nerrors += compiler.log.nerrors;
908 }
909 return c;
910 } finally {
911 compiler.close(false);
912 }
913 }
915 /** Return the number of errors found so far in this round.
916 * This may include uncoverable errors, such as parse errors,
917 * and transient errors, such as missing symbols. */
918 int errorCount() {
919 return compiler.errorCount();
920 }
922 /** Return the number of warnings found so far in this round. */
923 int warningCount() {
924 return compiler.warningCount();
925 }
927 /** Return whether or not an unrecoverable error has occurred. */
928 boolean unrecoverableError() {
929 if (messager.errorRaised())
930 return true;
932 for (JCDiagnostic d: log.deferredDiagnostics) {
933 switch (d.getKind()) {
934 case WARNING:
935 if (werror)
936 return true;
937 break;
939 case ERROR:
940 if (fatalErrors || !d.isFlagSet(RECOVERABLE))
941 return true;
942 break;
943 }
944 }
946 return false;
947 }
949 /** Find the set of annotations present in the set of top level
950 * classes and package info files to be processed this round. */
951 void findAnnotationsPresent() {
952 ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
953 // Use annotation processing to compute the set of annotations present
954 annotationsPresent = new LinkedHashSet<TypeElement>();
955 for (ClassSymbol classSym : topLevelClasses)
956 annotationComputer.scan(classSym, annotationsPresent);
957 for (PackageSymbol pkgSym : packageInfoFiles)
958 annotationComputer.scan(pkgSym, annotationsPresent);
959 }
961 /** Enter a set of generated class files. */
962 private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) {
963 ClassReader reader = ClassReader.instance(context);
964 Names names = Names.instance(context);
965 List<ClassSymbol> list = List.nil();
967 for (Map.Entry<String,JavaFileObject> entry : classFiles.entrySet()) {
968 Name name = names.fromString(entry.getKey());
969 JavaFileObject file = entry.getValue();
970 if (file.getKind() != JavaFileObject.Kind.CLASS)
971 throw new AssertionError(file);
972 ClassSymbol cs;
973 if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
974 Name packageName = Convert.packagePart(name);
975 PackageSymbol p = reader.enterPackage(packageName);
976 if (p.package_info == null)
977 p.package_info = reader.enterClass(Convert.shortName(name), p);
978 cs = p.package_info;
979 if (cs.classfile == null)
980 cs.classfile = file;
981 } else
982 cs = reader.enterClass(name, file);
983 list = list.prepend(cs);
984 }
985 return list.reverse();
986 }
988 /** Enter a set of syntax trees. */
989 private void enterTrees(List<JCCompilationUnit> roots) {
990 compiler.enterTrees(roots);
991 }
993 /** Run a processing round. */
994 void run(boolean lastRound, boolean errorStatus) {
995 printRoundInfo(lastRound);
997 TaskListener taskListener = context.get(TaskListener.class);
998 if (taskListener != null)
999 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1001 try {
1002 if (lastRound) {
1003 filer.setLastRound(true);
1004 Set<Element> emptyRootElements = Collections.emptySet(); // immutable
1005 RoundEnvironment renv = new JavacRoundEnvironment(true,
1006 errorStatus,
1007 emptyRootElements,
1008 JavacProcessingEnvironment.this);
1009 discoveredProcs.iterator().runContributingProcs(renv);
1010 } else {
1011 discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles);
1012 }
1013 } finally {
1014 if (taskListener != null)
1015 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1016 }
1017 }
1019 void showDiagnostics(boolean showAll) {
1020 Set<JCDiagnostic.Kind> kinds = EnumSet.allOf(JCDiagnostic.Kind.class);
1021 if (!showAll) {
1022 // suppress errors, which are all presumed to be transient resolve errors
1023 kinds.remove(JCDiagnostic.Kind.ERROR);
1024 }
1025 log.reportDeferredDiagnostics(kinds);
1026 }
1028 /** Print info about this round. */
1029 private void printRoundInfo(boolean lastRound) {
1030 if (printRounds || verbose) {
1031 List<ClassSymbol> tlc = lastRound ? List.<ClassSymbol>nil() : topLevelClasses;
1032 Set<TypeElement> ap = lastRound ? Collections.<TypeElement>emptySet() : annotationsPresent;
1033 log.printNoteLines("x.print.rounds",
1034 number,
1035 "{" + tlc.toString(", ") + "}",
1036 ap,
1037 lastRound);
1038 }
1039 }
1041 /** Get the context for the next round of processing.
1042 * Important values are propogated from round to round;
1043 * other values are implicitly reset.
1044 */
1045 private Context nextContext() {
1046 Context next = new Context(context);
1048 Options options = Options.instance(context);
1049 Assert.checkNonNull(options);
1050 next.put(Options.optionsKey, options);
1052 PrintWriter out = context.get(Log.outKey);
1053 Assert.checkNonNull(out);
1054 next.put(Log.outKey, out);
1056 final boolean shareNames = true;
1057 if (shareNames) {
1058 Names names = Names.instance(context);
1059 Assert.checkNonNull(names);
1060 next.put(Names.namesKey, names);
1061 }
1063 DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
1064 if (dl != null)
1065 next.put(DiagnosticListener.class, dl);
1067 TaskListener tl = context.get(TaskListener.class);
1068 if (tl != null)
1069 next.put(TaskListener.class, tl);
1071 FSInfo fsInfo = context.get(FSInfo.class);
1072 if (fsInfo != null)
1073 next.put(FSInfo.class, fsInfo);
1075 JavaFileManager jfm = context.get(JavaFileManager.class);
1076 Assert.checkNonNull(jfm);
1077 next.put(JavaFileManager.class, jfm);
1078 if (jfm instanceof JavacFileManager) {
1079 ((JavacFileManager)jfm).setContext(next);
1080 }
1082 Names names = Names.instance(context);
1083 Assert.checkNonNull(names);
1084 next.put(Names.namesKey, names);
1086 Keywords keywords = Keywords.instance(context);
1087 Assert.checkNonNull(keywords);
1088 next.put(Keywords.keywordsKey, keywords);
1090 JavaCompiler oldCompiler = JavaCompiler.instance(context);
1091 JavaCompiler nextCompiler = JavaCompiler.instance(next);
1092 nextCompiler.initRound(oldCompiler);
1094 filer.newRound(next);
1095 messager.newRound(next);
1096 elementUtils.setContext(next);
1097 typeUtils.setContext(next);
1099 JavacTaskImpl task = context.get(JavacTaskImpl.class);
1100 if (task != null) {
1101 next.put(JavacTaskImpl.class, task);
1102 task.updateContext(next);
1103 }
1105 JavacTrees trees = context.get(JavacTrees.class);
1106 if (trees != null) {
1107 next.put(JavacTrees.class, trees);
1108 trees.updateContext(next);
1109 }
1111 context.clear();
1112 return next;
1113 }
1114 }
1117 // TODO: internal catch clauses?; catch and rethrow an annotation
1118 // processing error
1119 public JavaCompiler doProcessing(Context context,
1120 List<JCCompilationUnit> roots,
1121 List<ClassSymbol> classSymbols,
1122 Iterable<? extends PackageSymbol> pckSymbols) {
1124 TaskListener taskListener = context.get(TaskListener.class);
1125 log = Log.instance(context);
1127 Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
1128 for (PackageSymbol psym : pckSymbols)
1129 specifiedPackages.add(psym);
1130 this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
1132 Round round = new Round(context, roots, classSymbols);
1134 boolean errorStatus;
1135 boolean moreToDo;
1136 do {
1137 // Run processors for round n
1138 round.run(false, false);
1140 // Processors for round n have run to completion.
1141 // Check for errors and whether there is more work to do.
1142 errorStatus = round.unrecoverableError();
1143 moreToDo = moreToDo();
1145 round.showDiagnostics(errorStatus || showResolveErrors);
1147 // Set up next round.
1148 // Copy mutable collections returned from filer.
1149 round = round.next(
1150 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()),
1151 new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses()));
1153 // Check for errors during setup.
1154 if (round.unrecoverableError())
1155 errorStatus = true;
1157 } while (moreToDo && !errorStatus);
1159 // run last round
1160 round.run(true, errorStatus);
1161 round.showDiagnostics(true);
1163 filer.warnIfUnclosedFiles();
1164 warnIfUnmatchedOptions();
1166 /*
1167 * If an annotation processor raises an error in a round,
1168 * that round runs to completion and one last round occurs.
1169 * The last round may also occur because no more source or
1170 * class files have been generated. Therefore, if an error
1171 * was raised on either of the last *two* rounds, the compile
1172 * should exit with a nonzero exit code. The current value of
1173 * errorStatus holds whether or not an error was raised on the
1174 * second to last round; errorRaised() gives the error status
1175 * of the last round.
1176 */
1177 if (messager.errorRaised()
1178 || werror && round.warningCount() > 0 && round.errorCount() > 0)
1179 errorStatus = true;
1181 Set<JavaFileObject> newSourceFiles =
1182 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
1183 roots = cleanTrees(round.roots);
1185 JavaCompiler compiler = round.finalCompiler(errorStatus);
1187 if (newSourceFiles.size() > 0)
1188 roots = roots.appendList(compiler.parseFiles(newSourceFiles));
1190 errorStatus = errorStatus || (compiler.errorCount() > 0);
1192 // Free resources
1193 this.close();
1195 if (taskListener != null)
1196 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
1198 if (errorStatus) {
1199 if (compiler.errorCount() == 0)
1200 compiler.log.nerrors++;
1201 return compiler;
1202 }
1204 if (procOnly && !foundTypeProcessors) {
1205 compiler.todo.clear();
1206 } else {
1207 if (procOnly && foundTypeProcessors)
1208 compiler.shouldStopPolicy = CompileState.FLOW;
1210 compiler.enterTrees(roots);
1211 }
1213 return compiler;
1214 }
1216 private void warnIfUnmatchedOptions() {
1217 if (!unmatchedProcessorOptions.isEmpty()) {
1218 log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
1219 }
1220 }
1222 /**
1223 * Free resources related to annotation processing.
1224 */
1225 public void close() {
1226 filer.close();
1227 if (discoveredProcs != null) // Make calling close idempotent
1228 discoveredProcs.close();
1229 discoveredProcs = null;
1230 if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
1231 try {
1232 ((Closeable) processorClassLoader).close();
1233 } catch (IOException e) {
1234 JCDiagnostic msg = diags.fragment("fatal.err.cant.close.loader");
1235 throw new FatalError(msg, e);
1236 }
1237 }
1238 }
1240 private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
1241 List<ClassSymbol> classes = List.nil();
1242 for (JCCompilationUnit unit : units) {
1243 for (JCTree node : unit.defs) {
1244 if (node.getTag() == JCTree.CLASSDEF) {
1245 ClassSymbol sym = ((JCClassDecl) node).sym;
1246 Assert.checkNonNull(sym);
1247 classes = classes.prepend(sym);
1248 }
1249 }
1250 }
1251 return classes.reverse();
1252 }
1254 private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) {
1255 List<ClassSymbol> classes = List.nil();
1256 for (ClassSymbol sym : syms) {
1257 if (!isPkgInfo(sym)) {
1258 classes = classes.prepend(sym);
1259 }
1260 }
1261 return classes.reverse();
1262 }
1264 private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
1265 List<PackageSymbol> packages = List.nil();
1266 for (JCCompilationUnit unit : units) {
1267 if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
1268 packages = packages.prepend(unit.packge);
1269 }
1270 }
1271 return packages.reverse();
1272 }
1274 private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) {
1275 List<PackageSymbol> packages = List.nil();
1276 for (ClassSymbol sym : syms) {
1277 if (isPkgInfo(sym)) {
1278 packages = packages.prepend((PackageSymbol) sym.owner);
1279 }
1280 }
1281 return packages.reverse();
1282 }
1284 // avoid unchecked warning from use of varargs
1285 private static <T> List<T> join(List<T> list1, List<T> list2) {
1286 return list1.appendList(list2);
1287 }
1289 private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
1290 return fo.isNameCompatible("package-info", kind);
1291 }
1293 private boolean isPkgInfo(ClassSymbol sym) {
1294 return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
1295 }
1297 /*
1298 * Called retroactively to determine if a class loader was required,
1299 * after we have failed to create one.
1300 */
1301 private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
1302 if (procNames != null)
1303 return true;
1305 String procPath;
1306 URL[] urls = new URL[1];
1307 for(File pathElement : workingpath) {
1308 try {
1309 urls[0] = pathElement.toURI().toURL();
1310 if (ServiceProxy.hasService(Processor.class, urls))
1311 return true;
1312 } catch (MalformedURLException ex) {
1313 throw new AssertionError(ex);
1314 }
1315 catch (ServiceProxy.ServiceConfigurationError e) {
1316 log.error("proc.bad.config.file", e.getLocalizedMessage());
1317 return true;
1318 }
1319 }
1321 return false;
1322 }
1324 private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) {
1325 for (T node : nodes)
1326 treeCleaner.scan(node);
1327 return nodes;
1328 }
1330 private static TreeScanner treeCleaner = new TreeScanner() {
1331 public void scan(JCTree node) {
1332 super.scan(node);
1333 if (node != null)
1334 node.type = null;
1335 }
1336 public void visitTopLevel(JCCompilationUnit node) {
1337 node.packge = null;
1338 super.visitTopLevel(node);
1339 }
1340 public void visitClassDef(JCClassDecl node) {
1341 node.sym = null;
1342 super.visitClassDef(node);
1343 }
1344 public void visitMethodDef(JCMethodDecl node) {
1345 node.sym = null;
1346 super.visitMethodDef(node);
1347 }
1348 public void visitVarDef(JCVariableDecl node) {
1349 node.sym = null;
1350 super.visitVarDef(node);
1351 }
1352 public void visitNewClass(JCNewClass node) {
1353 node.constructor = null;
1354 super.visitNewClass(node);
1355 }
1356 public void visitAssignop(JCAssignOp node) {
1357 node.operator = null;
1358 super.visitAssignop(node);
1359 }
1360 public void visitUnary(JCUnary node) {
1361 node.operator = null;
1362 super.visitUnary(node);
1363 }
1364 public void visitBinary(JCBinary node) {
1365 node.operator = null;
1366 super.visitBinary(node);
1367 }
1368 public void visitSelect(JCFieldAccess node) {
1369 node.sym = null;
1370 super.visitSelect(node);
1371 }
1372 public void visitIdent(JCIdent node) {
1373 node.sym = null;
1374 super.visitIdent(node);
1375 }
1376 };
1379 private boolean moreToDo() {
1380 return filer.newFiles();
1381 }
1383 /**
1384 * {@inheritdoc}
1385 *
1386 * Command line options suitable for presenting to annotation
1387 * processors. "-Afoo=bar" should be "-Afoo" => "bar".
1388 */
1389 public Map<String,String> getOptions() {
1390 return processorOptions;
1391 }
1393 public Messager getMessager() {
1394 return messager;
1395 }
1397 public Filer getFiler() {
1398 return filer;
1399 }
1401 public JavacElements getElementUtils() {
1402 return elementUtils;
1403 }
1405 public JavacTypes getTypeUtils() {
1406 return typeUtils;
1407 }
1409 public SourceVersion getSourceVersion() {
1410 return Source.toSourceVersion(source);
1411 }
1413 public Locale getLocale() {
1414 return messages.getCurrentLocale();
1415 }
1417 public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
1418 return specifiedPackages;
1419 }
1421 private static final Pattern allMatches = Pattern.compile(".*");
1422 public static final Pattern noMatches = Pattern.compile("(\\P{all})+");
1424 /**
1425 * Convert import-style string for supported annotations into a
1426 * regex matching that string. If the string is a valid
1427 * import-style string, return a regex that won't match anything.
1428 */
1429 private static Pattern importStringToPattern(String s, Processor p, Log log) {
1430 if (isValidImportString(s)) {
1431 return validImportStringToPattern(s);
1432 } else {
1433 log.warning("proc.malformed.supported.string", s, p.getClass().getName());
1434 return noMatches; // won't match any valid identifier
1435 }
1436 }
1438 /**
1439 * Return true if the argument string is a valid import-style
1440 * string specifying claimed annotations; return false otherwise.
1441 */
1442 public static boolean isValidImportString(String s) {
1443 if (s.equals("*"))
1444 return true;
1446 boolean valid = true;
1447 String t = s;
1448 int index = t.indexOf('*');
1450 if (index != -1) {
1451 // '*' must be last character...
1452 if (index == t.length() -1) {
1453 // ... any and preceding character must be '.'
1454 if ( index-1 >= 0 ) {
1455 valid = t.charAt(index-1) == '.';
1456 // Strip off ".*$" for identifier checks
1457 t = t.substring(0, t.length()-2);
1458 }
1459 } else
1460 return false;
1461 }
1463 // Verify string is off the form (javaId \.)+ or javaId
1464 if (valid) {
1465 String[] javaIds = t.split("\\.", t.length()+2);
1466 for(String javaId: javaIds)
1467 valid &= SourceVersion.isIdentifier(javaId);
1468 }
1469 return valid;
1470 }
1472 public static Pattern validImportStringToPattern(String s) {
1473 if (s.equals("*")) {
1474 return allMatches;
1475 } else {
1476 String s_prime = s.replace(".", "\\.");
1478 if (s_prime.endsWith("*")) {
1479 s_prime = s_prime.substring(0, s_prime.length() - 1) + ".+";
1480 }
1482 return Pattern.compile(s_prime);
1483 }
1484 }
1486 /**
1487 * For internal use only. This method will be
1488 * removed without warning.
1489 */
1490 public Context getContext() {
1491 return context;
1492 }
1494 public String toString() {
1495 return "javac ProcessingEnvironment";
1496 }
1498 public static boolean isValidOptionName(String optionName) {
1499 for(String s : optionName.split("\\.", -1)) {
1500 if (!SourceVersion.isIdentifier(s))
1501 return false;
1502 }
1503 return true;
1504 }
1505 }