Tue, 15 Mar 2011 11:48:55 -0700
6988079: Errors reported via Messager.printMessage(ERROR,"error message") are not tallied correctly
Reviewed-by: darcy
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 /** The number of Messager errors generated in this round. */
824 int nMessagerErrors;
826 /** Create a round (common code). */
827 private Round(Context context, int number, int priorErrors, int priorWarnings) {
828 this.context = context;
829 this.number = number;
831 compiler = JavaCompiler.instance(context);
832 log = Log.instance(context);
833 log.nerrors = priorErrors;
834 log.nwarnings += priorWarnings;
835 log.deferDiagnostics = true;
837 // the following is for the benefit of JavacProcessingEnvironment.getContext()
838 JavacProcessingEnvironment.this.context = context;
840 // the following will be populated as needed
841 topLevelClasses = List.nil();
842 packageInfoFiles = List.nil();
843 }
845 /** Create the first round. */
846 Round(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols) {
847 this(context, 1, 0, 0);
848 this.roots = roots;
849 genClassFiles = new HashMap<String,JavaFileObject>();
851 compiler.todo.clear(); // free the compiler's resources
853 // The reverse() in the following line is to maintain behavioural
854 // compatibility with the previous revision of the code. Strictly speaking,
855 // it should not be necessary, but a javah golden file test fails without it.
856 topLevelClasses =
857 getTopLevelClasses(roots).prependList(classSymbols.reverse());
859 packageInfoFiles = getPackageInfoFiles(roots);
861 findAnnotationsPresent();
862 }
864 /** Create a new round. */
865 private Round(Round prev,
866 Set<JavaFileObject> newSourceFiles, Map<String,JavaFileObject> newClassFiles) {
867 this(prev.nextContext(),
868 prev.number+1,
869 prev.nMessagerErrors,
870 prev.compiler.log.nwarnings);
871 this.genClassFiles = prev.genClassFiles;
873 List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles);
874 roots = cleanTrees(prev.roots).appendList(parsedFiles);
876 // Check for errors after parsing
877 if (unrecoverableError())
878 return;
880 enterClassFiles(genClassFiles);
881 List<ClassSymbol> newClasses = enterClassFiles(newClassFiles);
882 genClassFiles.putAll(newClassFiles);
883 enterTrees(roots);
885 if (unrecoverableError())
886 return;
888 topLevelClasses = join(
889 getTopLevelClasses(parsedFiles),
890 getTopLevelClassesFromClasses(newClasses));
892 packageInfoFiles = join(
893 getPackageInfoFiles(parsedFiles),
894 getPackageInfoFilesFromClasses(newClasses));
896 findAnnotationsPresent();
897 }
899 /** Create the next round to be used. */
900 Round next(Set<JavaFileObject> newSourceFiles, Map<String, JavaFileObject> newClassFiles) {
901 try {
902 return new Round(this, newSourceFiles, newClassFiles);
903 } finally {
904 compiler.close(false);
905 }
906 }
908 /** Create the compiler to be used for the final compilation. */
909 JavaCompiler finalCompiler(boolean errorStatus) {
910 try {
911 JavaCompiler c = JavaCompiler.instance(nextContext());
912 c.log.nwarnings += compiler.log.nwarnings;
913 if (errorStatus) {
914 c.log.nerrors += compiler.log.nerrors;
915 }
916 return c;
917 } finally {
918 compiler.close(false);
919 }
920 }
922 /** Return the number of errors found so far in this round.
923 * This may include uncoverable errors, such as parse errors,
924 * and transient errors, such as missing symbols. */
925 int errorCount() {
926 return compiler.errorCount();
927 }
929 /** Return the number of warnings found so far in this round. */
930 int warningCount() {
931 return compiler.warningCount();
932 }
934 /** Return whether or not an unrecoverable error has occurred. */
935 boolean unrecoverableError() {
936 if (messager.errorRaised())
937 return true;
939 for (JCDiagnostic d: log.deferredDiagnostics) {
940 switch (d.getKind()) {
941 case WARNING:
942 if (werror)
943 return true;
944 break;
946 case ERROR:
947 if (fatalErrors || !d.isFlagSet(RECOVERABLE))
948 return true;
949 break;
950 }
951 }
953 return false;
954 }
956 /** Find the set of annotations present in the set of top level
957 * classes and package info files to be processed this round. */
958 void findAnnotationsPresent() {
959 ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
960 // Use annotation processing to compute the set of annotations present
961 annotationsPresent = new LinkedHashSet<TypeElement>();
962 for (ClassSymbol classSym : topLevelClasses)
963 annotationComputer.scan(classSym, annotationsPresent);
964 for (PackageSymbol pkgSym : packageInfoFiles)
965 annotationComputer.scan(pkgSym, annotationsPresent);
966 }
968 /** Enter a set of generated class files. */
969 private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) {
970 ClassReader reader = ClassReader.instance(context);
971 Names names = Names.instance(context);
972 List<ClassSymbol> list = List.nil();
974 for (Map.Entry<String,JavaFileObject> entry : classFiles.entrySet()) {
975 Name name = names.fromString(entry.getKey());
976 JavaFileObject file = entry.getValue();
977 if (file.getKind() != JavaFileObject.Kind.CLASS)
978 throw new AssertionError(file);
979 ClassSymbol cs;
980 if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
981 Name packageName = Convert.packagePart(name);
982 PackageSymbol p = reader.enterPackage(packageName);
983 if (p.package_info == null)
984 p.package_info = reader.enterClass(Convert.shortName(name), p);
985 cs = p.package_info;
986 if (cs.classfile == null)
987 cs.classfile = file;
988 } else
989 cs = reader.enterClass(name, file);
990 list = list.prepend(cs);
991 }
992 return list.reverse();
993 }
995 /** Enter a set of syntax trees. */
996 private void enterTrees(List<JCCompilationUnit> roots) {
997 compiler.enterTrees(roots);
998 }
1000 /** Run a processing round. */
1001 void run(boolean lastRound, boolean errorStatus) {
1002 printRoundInfo(lastRound);
1004 TaskListener taskListener = context.get(TaskListener.class);
1005 if (taskListener != null)
1006 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1008 try {
1009 if (lastRound) {
1010 filer.setLastRound(true);
1011 Set<Element> emptyRootElements = Collections.emptySet(); // immutable
1012 RoundEnvironment renv = new JavacRoundEnvironment(true,
1013 errorStatus,
1014 emptyRootElements,
1015 JavacProcessingEnvironment.this);
1016 discoveredProcs.iterator().runContributingProcs(renv);
1017 } else {
1018 discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles);
1019 }
1020 } finally {
1021 if (taskListener != null)
1022 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1023 }
1025 nMessagerErrors = messager.errorCount();
1026 }
1028 void showDiagnostics(boolean showAll) {
1029 Set<JCDiagnostic.Kind> kinds = EnumSet.allOf(JCDiagnostic.Kind.class);
1030 if (!showAll) {
1031 // suppress errors, which are all presumed to be transient resolve errors
1032 kinds.remove(JCDiagnostic.Kind.ERROR);
1033 }
1034 log.reportDeferredDiagnostics(kinds);
1035 }
1037 /** Print info about this round. */
1038 private void printRoundInfo(boolean lastRound) {
1039 if (printRounds || verbose) {
1040 List<ClassSymbol> tlc = lastRound ? List.<ClassSymbol>nil() : topLevelClasses;
1041 Set<TypeElement> ap = lastRound ? Collections.<TypeElement>emptySet() : annotationsPresent;
1042 log.printNoteLines("x.print.rounds",
1043 number,
1044 "{" + tlc.toString(", ") + "}",
1045 ap,
1046 lastRound);
1047 }
1048 }
1050 /** Get the context for the next round of processing.
1051 * Important values are propogated from round to round;
1052 * other values are implicitly reset.
1053 */
1054 private Context nextContext() {
1055 Context next = new Context(context);
1057 Options options = Options.instance(context);
1058 Assert.checkNonNull(options);
1059 next.put(Options.optionsKey, options);
1061 PrintWriter out = context.get(Log.outKey);
1062 Assert.checkNonNull(out);
1063 next.put(Log.outKey, out);
1065 final boolean shareNames = true;
1066 if (shareNames) {
1067 Names names = Names.instance(context);
1068 Assert.checkNonNull(names);
1069 next.put(Names.namesKey, names);
1070 }
1072 DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
1073 if (dl != null)
1074 next.put(DiagnosticListener.class, dl);
1076 TaskListener tl = context.get(TaskListener.class);
1077 if (tl != null)
1078 next.put(TaskListener.class, tl);
1080 FSInfo fsInfo = context.get(FSInfo.class);
1081 if (fsInfo != null)
1082 next.put(FSInfo.class, fsInfo);
1084 JavaFileManager jfm = context.get(JavaFileManager.class);
1085 Assert.checkNonNull(jfm);
1086 next.put(JavaFileManager.class, jfm);
1087 if (jfm instanceof JavacFileManager) {
1088 ((JavacFileManager)jfm).setContext(next);
1089 }
1091 Names names = Names.instance(context);
1092 Assert.checkNonNull(names);
1093 next.put(Names.namesKey, names);
1095 Keywords keywords = Keywords.instance(context);
1096 Assert.checkNonNull(keywords);
1097 next.put(Keywords.keywordsKey, keywords);
1099 JavaCompiler oldCompiler = JavaCompiler.instance(context);
1100 JavaCompiler nextCompiler = JavaCompiler.instance(next);
1101 nextCompiler.initRound(oldCompiler);
1103 filer.newRound(next);
1104 messager.newRound(next);
1105 elementUtils.setContext(next);
1106 typeUtils.setContext(next);
1108 JavacTaskImpl task = context.get(JavacTaskImpl.class);
1109 if (task != null) {
1110 next.put(JavacTaskImpl.class, task);
1111 task.updateContext(next);
1112 }
1114 JavacTrees trees = context.get(JavacTrees.class);
1115 if (trees != null) {
1116 next.put(JavacTrees.class, trees);
1117 trees.updateContext(next);
1118 }
1120 context.clear();
1121 return next;
1122 }
1123 }
1126 // TODO: internal catch clauses?; catch and rethrow an annotation
1127 // processing error
1128 public JavaCompiler doProcessing(Context context,
1129 List<JCCompilationUnit> roots,
1130 List<ClassSymbol> classSymbols,
1131 Iterable<? extends PackageSymbol> pckSymbols) {
1133 TaskListener taskListener = context.get(TaskListener.class);
1134 log = Log.instance(context);
1136 Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
1137 for (PackageSymbol psym : pckSymbols)
1138 specifiedPackages.add(psym);
1139 this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
1141 Round round = new Round(context, roots, classSymbols);
1143 boolean errorStatus;
1144 boolean moreToDo;
1145 do {
1146 // Run processors for round n
1147 round.run(false, false);
1149 // Processors for round n have run to completion.
1150 // Check for errors and whether there is more work to do.
1151 errorStatus = round.unrecoverableError();
1152 moreToDo = moreToDo();
1154 round.showDiagnostics(errorStatus || showResolveErrors);
1156 // Set up next round.
1157 // Copy mutable collections returned from filer.
1158 round = round.next(
1159 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()),
1160 new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses()));
1162 // Check for errors during setup.
1163 if (round.unrecoverableError())
1164 errorStatus = true;
1166 } while (moreToDo && !errorStatus);
1168 // run last round
1169 round.run(true, errorStatus);
1170 round.showDiagnostics(true);
1172 filer.warnIfUnclosedFiles();
1173 warnIfUnmatchedOptions();
1175 /*
1176 * If an annotation processor raises an error in a round,
1177 * that round runs to completion and one last round occurs.
1178 * The last round may also occur because no more source or
1179 * class files have been generated. Therefore, if an error
1180 * was raised on either of the last *two* rounds, the compile
1181 * should exit with a nonzero exit code. The current value of
1182 * errorStatus holds whether or not an error was raised on the
1183 * second to last round; errorRaised() gives the error status
1184 * of the last round.
1185 */
1186 if (messager.errorRaised()
1187 || werror && round.warningCount() > 0 && round.errorCount() > 0)
1188 errorStatus = true;
1190 Set<JavaFileObject> newSourceFiles =
1191 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
1192 roots = cleanTrees(round.roots);
1194 JavaCompiler compiler = round.finalCompiler(errorStatus);
1196 if (newSourceFiles.size() > 0)
1197 roots = roots.appendList(compiler.parseFiles(newSourceFiles));
1199 errorStatus = errorStatus || (compiler.errorCount() > 0);
1201 // Free resources
1202 this.close();
1204 if (taskListener != null)
1205 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
1207 if (errorStatus) {
1208 if (compiler.errorCount() == 0)
1209 compiler.log.nerrors++;
1210 return compiler;
1211 }
1213 if (procOnly && !foundTypeProcessors) {
1214 compiler.todo.clear();
1215 } else {
1216 if (procOnly && foundTypeProcessors)
1217 compiler.shouldStopPolicy = CompileState.FLOW;
1219 compiler.enterTrees(roots);
1220 }
1222 return compiler;
1223 }
1225 private void warnIfUnmatchedOptions() {
1226 if (!unmatchedProcessorOptions.isEmpty()) {
1227 log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
1228 }
1229 }
1231 /**
1232 * Free resources related to annotation processing.
1233 */
1234 public void close() {
1235 filer.close();
1236 if (discoveredProcs != null) // Make calling close idempotent
1237 discoveredProcs.close();
1238 discoveredProcs = null;
1239 if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
1240 try {
1241 ((Closeable) processorClassLoader).close();
1242 } catch (IOException e) {
1243 JCDiagnostic msg = diags.fragment("fatal.err.cant.close.loader");
1244 throw new FatalError(msg, e);
1245 }
1246 }
1247 }
1249 private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
1250 List<ClassSymbol> classes = List.nil();
1251 for (JCCompilationUnit unit : units) {
1252 for (JCTree node : unit.defs) {
1253 if (node.getTag() == JCTree.CLASSDEF) {
1254 ClassSymbol sym = ((JCClassDecl) node).sym;
1255 Assert.checkNonNull(sym);
1256 classes = classes.prepend(sym);
1257 }
1258 }
1259 }
1260 return classes.reverse();
1261 }
1263 private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) {
1264 List<ClassSymbol> classes = List.nil();
1265 for (ClassSymbol sym : syms) {
1266 if (!isPkgInfo(sym)) {
1267 classes = classes.prepend(sym);
1268 }
1269 }
1270 return classes.reverse();
1271 }
1273 private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
1274 List<PackageSymbol> packages = List.nil();
1275 for (JCCompilationUnit unit : units) {
1276 if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
1277 packages = packages.prepend(unit.packge);
1278 }
1279 }
1280 return packages.reverse();
1281 }
1283 private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) {
1284 List<PackageSymbol> packages = List.nil();
1285 for (ClassSymbol sym : syms) {
1286 if (isPkgInfo(sym)) {
1287 packages = packages.prepend((PackageSymbol) sym.owner);
1288 }
1289 }
1290 return packages.reverse();
1291 }
1293 // avoid unchecked warning from use of varargs
1294 private static <T> List<T> join(List<T> list1, List<T> list2) {
1295 return list1.appendList(list2);
1296 }
1298 private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
1299 return fo.isNameCompatible("package-info", kind);
1300 }
1302 private boolean isPkgInfo(ClassSymbol sym) {
1303 return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
1304 }
1306 /*
1307 * Called retroactively to determine if a class loader was required,
1308 * after we have failed to create one.
1309 */
1310 private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
1311 if (procNames != null)
1312 return true;
1314 String procPath;
1315 URL[] urls = new URL[1];
1316 for(File pathElement : workingpath) {
1317 try {
1318 urls[0] = pathElement.toURI().toURL();
1319 if (ServiceProxy.hasService(Processor.class, urls))
1320 return true;
1321 } catch (MalformedURLException ex) {
1322 throw new AssertionError(ex);
1323 }
1324 catch (ServiceProxy.ServiceConfigurationError e) {
1325 log.error("proc.bad.config.file", e.getLocalizedMessage());
1326 return true;
1327 }
1328 }
1330 return false;
1331 }
1333 private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) {
1334 for (T node : nodes)
1335 treeCleaner.scan(node);
1336 return nodes;
1337 }
1339 private static TreeScanner treeCleaner = new TreeScanner() {
1340 public void scan(JCTree node) {
1341 super.scan(node);
1342 if (node != null)
1343 node.type = null;
1344 }
1345 public void visitTopLevel(JCCompilationUnit node) {
1346 node.packge = null;
1347 super.visitTopLevel(node);
1348 }
1349 public void visitClassDef(JCClassDecl node) {
1350 node.sym = null;
1351 super.visitClassDef(node);
1352 }
1353 public void visitMethodDef(JCMethodDecl node) {
1354 node.sym = null;
1355 super.visitMethodDef(node);
1356 }
1357 public void visitVarDef(JCVariableDecl node) {
1358 node.sym = null;
1359 super.visitVarDef(node);
1360 }
1361 public void visitNewClass(JCNewClass node) {
1362 node.constructor = null;
1363 super.visitNewClass(node);
1364 }
1365 public void visitAssignop(JCAssignOp node) {
1366 node.operator = null;
1367 super.visitAssignop(node);
1368 }
1369 public void visitUnary(JCUnary node) {
1370 node.operator = null;
1371 super.visitUnary(node);
1372 }
1373 public void visitBinary(JCBinary node) {
1374 node.operator = null;
1375 super.visitBinary(node);
1376 }
1377 public void visitSelect(JCFieldAccess node) {
1378 node.sym = null;
1379 super.visitSelect(node);
1380 }
1381 public void visitIdent(JCIdent node) {
1382 node.sym = null;
1383 super.visitIdent(node);
1384 }
1385 };
1388 private boolean moreToDo() {
1389 return filer.newFiles();
1390 }
1392 /**
1393 * {@inheritdoc}
1394 *
1395 * Command line options suitable for presenting to annotation
1396 * processors. "-Afoo=bar" should be "-Afoo" => "bar".
1397 */
1398 public Map<String,String> getOptions() {
1399 return processorOptions;
1400 }
1402 public Messager getMessager() {
1403 return messager;
1404 }
1406 public Filer getFiler() {
1407 return filer;
1408 }
1410 public JavacElements getElementUtils() {
1411 return elementUtils;
1412 }
1414 public JavacTypes getTypeUtils() {
1415 return typeUtils;
1416 }
1418 public SourceVersion getSourceVersion() {
1419 return Source.toSourceVersion(source);
1420 }
1422 public Locale getLocale() {
1423 return messages.getCurrentLocale();
1424 }
1426 public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
1427 return specifiedPackages;
1428 }
1430 private static final Pattern allMatches = Pattern.compile(".*");
1431 public static final Pattern noMatches = Pattern.compile("(\\P{all})+");
1433 /**
1434 * Convert import-style string for supported annotations into a
1435 * regex matching that string. If the string is a valid
1436 * import-style string, return a regex that won't match anything.
1437 */
1438 private static Pattern importStringToPattern(String s, Processor p, Log log) {
1439 if (isValidImportString(s)) {
1440 return validImportStringToPattern(s);
1441 } else {
1442 log.warning("proc.malformed.supported.string", s, p.getClass().getName());
1443 return noMatches; // won't match any valid identifier
1444 }
1445 }
1447 /**
1448 * Return true if the argument string is a valid import-style
1449 * string specifying claimed annotations; return false otherwise.
1450 */
1451 public static boolean isValidImportString(String s) {
1452 if (s.equals("*"))
1453 return true;
1455 boolean valid = true;
1456 String t = s;
1457 int index = t.indexOf('*');
1459 if (index != -1) {
1460 // '*' must be last character...
1461 if (index == t.length() -1) {
1462 // ... any and preceding character must be '.'
1463 if ( index-1 >= 0 ) {
1464 valid = t.charAt(index-1) == '.';
1465 // Strip off ".*$" for identifier checks
1466 t = t.substring(0, t.length()-2);
1467 }
1468 } else
1469 return false;
1470 }
1472 // Verify string is off the form (javaId \.)+ or javaId
1473 if (valid) {
1474 String[] javaIds = t.split("\\.", t.length()+2);
1475 for(String javaId: javaIds)
1476 valid &= SourceVersion.isIdentifier(javaId);
1477 }
1478 return valid;
1479 }
1481 public static Pattern validImportStringToPattern(String s) {
1482 if (s.equals("*")) {
1483 return allMatches;
1484 } else {
1485 String s_prime = s.replace(".", "\\.");
1487 if (s_prime.endsWith("*")) {
1488 s_prime = s_prime.substring(0, s_prime.length() - 1) + ".+";
1489 }
1491 return Pattern.compile(s_prime);
1492 }
1493 }
1495 /**
1496 * For internal use only. This method will be
1497 * removed without warning.
1498 */
1499 public Context getContext() {
1500 return context;
1501 }
1503 public String toString() {
1504 return "javac ProcessingEnvironment";
1505 }
1507 public static boolean isValidOptionName(String optionName) {
1508 for(String s : optionName.split("\\.", -1)) {
1509 if (!SourceVersion.isIdentifier(s))
1510 return false;
1511 }
1512 return true;
1513 }
1514 }