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