Mon, 10 Dec 2012 16:21:26 +0000
8003967: detect and remove all mutable implicit static enum fields in langtools
Reviewed-by: jjg
1 /*
2 * Copyright (c) 2005, 2012, 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.io.Closeable;
29 import java.io.File;
30 import java.io.PrintWriter;
31 import java.io.StringWriter;
32 import java.net.MalformedURLException;
33 import java.net.URL;
34 import java.util.*;
35 import java.util.regex.*;
37 import javax.annotation.processing.*;
38 import javax.lang.model.SourceVersion;
39 import javax.lang.model.element.AnnotationMirror;
40 import javax.lang.model.element.Element;
41 import javax.lang.model.element.PackageElement;
42 import javax.lang.model.element.TypeElement;
43 import javax.lang.model.util.*;
44 import javax.tools.DiagnosticListener;
45 import javax.tools.JavaFileManager;
46 import javax.tools.JavaFileObject;
47 import javax.tools.StandardJavaFileManager;
48 import static javax.tools.StandardLocation.*;
50 import com.sun.source.util.JavacTask;
51 import com.sun.source.util.TaskEvent;
52 import com.sun.tools.javac.api.BasicJavacTask;
53 import com.sun.tools.javac.api.JavacTrees;
54 import com.sun.tools.javac.api.MultiTaskListener;
55 import com.sun.tools.javac.code.*;
56 import com.sun.tools.javac.code.Symbol.*;
57 import com.sun.tools.javac.file.FSInfo;
58 import com.sun.tools.javac.file.JavacFileManager;
59 import com.sun.tools.javac.jvm.*;
60 import com.sun.tools.javac.jvm.ClassReader.BadClassFile;
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.JCDiagnostic;
74 import com.sun.tools.javac.util.JavacMessages;
75 import com.sun.tools.javac.util.List;
76 import com.sun.tools.javac.util.Log;
77 import com.sun.tools.javac.util.Name;
78 import com.sun.tools.javac.util.Names;
79 import com.sun.tools.javac.util.Options;
80 import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
81 import static com.sun.tools.javac.main.Option.*;
82 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
84 /**
85 * Objects of this class hold and manage the state needed to support
86 * annotation processing.
87 *
88 * <p><b>This is NOT part of any supported API.
89 * If you write code that depends on this, you do so at your own risk.
90 * This code and its internal interfaces are subject to change or
91 * deletion without notice.</b>
92 */
93 public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
94 Options options;
96 private final boolean printProcessorInfo;
97 private final boolean printRounds;
98 private final boolean verbose;
99 private final boolean lint;
100 private final boolean fatalErrors;
101 private final boolean werror;
102 private final boolean showResolveErrors;
104 private final JavacFiler filer;
105 private final JavacMessager messager;
106 private final JavacElements elementUtils;
107 private final JavacTypes typeUtils;
109 /**
110 * Holds relevant state history of which processors have been
111 * used.
112 */
113 private DiscoveredProcessors discoveredProcs;
115 /**
116 * Map of processor-specific options.
117 */
118 private final Map<String, String> processorOptions;
120 /**
121 */
122 private final Set<String> unmatchedProcessorOptions;
124 /**
125 * Annotations implicitly processed and claimed by javac.
126 */
127 private final Set<String> platformAnnotations;
129 /**
130 * Set of packages given on command line.
131 */
132 private Set<PackageSymbol> specifiedPackages = Collections.emptySet();
134 /** The log to be used for error reporting.
135 */
136 Log log;
138 /** Diagnostic factory.
139 */
140 JCDiagnostic.Factory diags;
142 /**
143 * Source level of the compile.
144 */
145 Source source;
147 private ClassLoader processorClassLoader;
148 private SecurityException processorClassLoaderException;
150 /**
151 * JavacMessages object used for localization
152 */
153 private JavacMessages messages;
155 private MultiTaskListener taskListener;
157 private Context context;
159 /** Get the JavacProcessingEnvironment instance for this context. */
160 public static JavacProcessingEnvironment instance(Context context) {
161 JavacProcessingEnvironment instance = context.get(JavacProcessingEnvironment.class);
162 if (instance == null)
163 instance = new JavacProcessingEnvironment(context);
164 return instance;
165 }
167 protected JavacProcessingEnvironment(Context context) {
168 this.context = context;
169 log = Log.instance(context);
170 source = Source.instance(context);
171 diags = JCDiagnostic.Factory.instance(context);
172 options = Options.instance(context);
173 printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
174 printRounds = options.isSet(XPRINTROUNDS);
175 verbose = options.isSet(VERBOSE);
176 lint = Lint.instance(context).isEnabled(PROCESSING);
177 if (options.isSet(PROC, "only") || options.isSet(XPRINT)) {
178 JavaCompiler compiler = JavaCompiler.instance(context);
179 compiler.shouldStopPolicyIfNoError = CompileState.PROCESS;
180 }
181 fatalErrors = options.isSet("fatalEnterError");
182 showResolveErrors = options.isSet("showResolveErrors");
183 werror = options.isSet(WERROR);
184 platformAnnotations = initPlatformAnnotations();
186 // Initialize services before any processors are initialized
187 // in case processors use them.
188 filer = new JavacFiler(context);
189 messager = new JavacMessager(context, this);
190 elementUtils = JavacElements.instance(context);
191 typeUtils = JavacTypes.instance(context);
192 processorOptions = initProcessorOptions(context);
193 unmatchedProcessorOptions = initUnmatchedProcessorOptions();
194 messages = JavacMessages.instance(context);
195 taskListener = MultiTaskListener.instance(context);
196 initProcessorClassLoader();
197 }
199 public void setProcessors(Iterable<? extends Processor> processors) {
200 Assert.checkNull(discoveredProcs);
201 initProcessorIterator(context, processors);
202 }
204 private Set<String> initPlatformAnnotations() {
205 Set<String> platformAnnotations = new HashSet<String>();
206 platformAnnotations.add("java.lang.Deprecated");
207 platformAnnotations.add("java.lang.Override");
208 platformAnnotations.add("java.lang.SuppressWarnings");
209 platformAnnotations.add("java.lang.annotation.Documented");
210 platformAnnotations.add("java.lang.annotation.Inherited");
211 platformAnnotations.add("java.lang.annotation.Retention");
212 platformAnnotations.add("java.lang.annotation.Target");
213 return Collections.unmodifiableSet(platformAnnotations);
214 }
216 private void initProcessorClassLoader() {
217 JavaFileManager fileManager = context.get(JavaFileManager.class);
218 try {
219 // If processorpath is not explicitly set, use the classpath.
220 processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
221 ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
222 : fileManager.getClassLoader(CLASS_PATH);
224 if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
225 JavaCompiler compiler = JavaCompiler.instance(context);
226 compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader);
227 }
228 } catch (SecurityException e) {
229 processorClassLoaderException = e;
230 }
231 }
233 private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
234 Log log = Log.instance(context);
235 Iterator<? extends Processor> processorIterator;
237 if (options.isSet(XPRINT)) {
238 try {
239 Processor processor = PrintingProcessor.class.newInstance();
240 processorIterator = List.of(processor).iterator();
241 } catch (Throwable t) {
242 AssertionError assertError =
243 new AssertionError("Problem instantiating PrintingProcessor.");
244 assertError.initCause(t);
245 throw assertError;
246 }
247 } else if (processors != null) {
248 processorIterator = processors.iterator();
249 } else {
250 String processorNames = options.get(PROCESSOR);
251 if (processorClassLoaderException == null) {
252 /*
253 * If the "-processor" option is used, search the appropriate
254 * path for the named class. Otherwise, use a service
255 * provider mechanism to create the processor iterator.
256 */
257 if (processorNames != null) {
258 processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
259 } else {
260 processorIterator = new ServiceIterator(processorClassLoader, log);
261 }
262 } else {
263 /*
264 * A security exception will occur if we can't create a classloader.
265 * Ignore the exception if, with hindsight, we didn't need it anyway
266 * (i.e. no processor was specified either explicitly, or implicitly,
267 * in service configuration file.) Otherwise, we cannot continue.
268 */
269 processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader",
270 processorClassLoaderException);
271 }
272 }
273 discoveredProcs = new DiscoveredProcessors(processorIterator);
274 }
276 /**
277 * Returns an empty processor iterator if no processors are on the
278 * relevant path, otherwise if processors are present, logs an
279 * error. Called when a service loader is unavailable for some
280 * reason, either because a service loader class cannot be found
281 * or because a security policy prevents class loaders from being
282 * created.
283 *
284 * @param key The resource key to use to log an error message
285 * @param e If non-null, pass this exception to Abort
286 */
287 private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
288 JavaFileManager fileManager = context.get(JavaFileManager.class);
290 if (fileManager instanceof JavacFileManager) {
291 StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
292 Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
293 ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
294 : standardFileManager.getLocation(CLASS_PATH);
296 if (needClassLoader(options.get(PROCESSOR), workingPath) )
297 handleException(key, e);
299 } else {
300 handleException(key, e);
301 }
303 java.util.List<Processor> pl = Collections.emptyList();
304 return pl.iterator();
305 }
307 /**
308 * Handle a security exception thrown during initializing the
309 * Processor iterator.
310 */
311 private void handleException(String key, Exception e) {
312 if (e != null) {
313 log.error(key, e.getLocalizedMessage());
314 throw new Abort(e);
315 } else {
316 log.error(key);
317 throw new Abort();
318 }
319 }
321 /**
322 * Use a service loader appropriate for the platform to provide an
323 * iterator over annotations processors; fails if a loader is
324 * needed but unavailable.
325 */
326 private class ServiceIterator implements Iterator<Processor> {
327 private Iterator<Processor> iterator;
328 private Log log;
329 private ServiceLoader<Processor> loader;
331 ServiceIterator(ClassLoader classLoader, Log log) {
332 this.log = log;
333 try {
334 try {
335 loader = ServiceLoader.load(Processor.class, classLoader);
336 this.iterator = loader.iterator();
337 } catch (Exception e) {
338 // Fail softly if a loader is not actually needed.
339 this.iterator = handleServiceLoaderUnavailability("proc.no.service", null);
340 }
341 } catch (Throwable t) {
342 log.error("proc.service.problem");
343 throw new Abort(t);
344 }
345 }
347 public boolean hasNext() {
348 try {
349 return iterator.hasNext();
350 } catch(ServiceConfigurationError sce) {
351 log.error("proc.bad.config.file", sce.getLocalizedMessage());
352 throw new Abort(sce);
353 } catch (Throwable t) {
354 throw new Abort(t);
355 }
356 }
358 public Processor next() {
359 try {
360 return iterator.next();
361 } catch (ServiceConfigurationError sce) {
362 log.error("proc.bad.config.file", sce.getLocalizedMessage());
363 throw new Abort(sce);
364 } catch (Throwable t) {
365 throw new Abort(t);
366 }
367 }
369 public void remove() {
370 throw new UnsupportedOperationException();
371 }
373 public void close() {
374 if (loader != null) {
375 try {
376 loader.reload();
377 } catch(Exception e) {
378 ; // Ignore problems during a call to reload.
379 }
380 }
381 }
382 }
385 private static class NameProcessIterator implements Iterator<Processor> {
386 Processor nextProc = null;
387 Iterator<String> names;
388 ClassLoader processorCL;
389 Log log;
391 NameProcessIterator(String names, ClassLoader processorCL, Log log) {
392 this.names = Arrays.asList(names.split(",")).iterator();
393 this.processorCL = processorCL;
394 this.log = log;
395 }
397 public boolean hasNext() {
398 if (nextProc != null)
399 return true;
400 else {
401 if (!names.hasNext())
402 return false;
403 else {
404 String processorName = names.next();
406 Processor processor;
407 try {
408 try {
409 processor =
410 (Processor) (processorCL.loadClass(processorName).newInstance());
411 } catch (ClassNotFoundException cnfe) {
412 log.error("proc.processor.not.found", processorName);
413 return false;
414 } catch (ClassCastException cce) {
415 log.error("proc.processor.wrong.type", processorName);
416 return false;
417 } catch (Exception e ) {
418 log.error("proc.processor.cant.instantiate", processorName);
419 return false;
420 }
421 } catch(ClientCodeException e) {
422 throw e;
423 } catch(Throwable t) {
424 throw new AnnotationProcessingError(t);
425 }
426 nextProc = processor;
427 return true;
428 }
430 }
431 }
433 public Processor next() {
434 if (hasNext()) {
435 Processor p = nextProc;
436 nextProc = null;
437 return p;
438 } else
439 throw new NoSuchElementException();
440 }
442 public void remove () {
443 throw new UnsupportedOperationException();
444 }
445 }
447 public boolean atLeastOneProcessor() {
448 return discoveredProcs.iterator().hasNext();
449 }
451 private Map<String, String> initProcessorOptions(Context context) {
452 Options options = Options.instance(context);
453 Set<String> keySet = options.keySet();
454 Map<String, String> tempOptions = new LinkedHashMap<String, String>();
456 for(String key : keySet) {
457 if (key.startsWith("-A") && key.length() > 2) {
458 int sepIndex = key.indexOf('=');
459 String candidateKey = null;
460 String candidateValue = null;
462 if (sepIndex == -1)
463 candidateKey = key.substring(2);
464 else if (sepIndex >= 3) {
465 candidateKey = key.substring(2, sepIndex);
466 candidateValue = (sepIndex < key.length()-1)?
467 key.substring(sepIndex+1) : null;
468 }
469 tempOptions.put(candidateKey, candidateValue);
470 }
471 }
473 return Collections.unmodifiableMap(tempOptions);
474 }
476 private Set<String> initUnmatchedProcessorOptions() {
477 Set<String> unmatchedProcessorOptions = new HashSet<String>();
478 unmatchedProcessorOptions.addAll(processorOptions.keySet());
479 return unmatchedProcessorOptions;
480 }
482 /**
483 * State about how a processor has been used by the tool. If a
484 * processor has been used on a prior round, its process method is
485 * called on all subsequent rounds, perhaps with an empty set of
486 * annotations to process. The {@code annotationSupported} method
487 * caches the supported annotation information from the first (and
488 * only) getSupportedAnnotationTypes call to the processor.
489 */
490 static class ProcessorState {
491 public Processor processor;
492 public boolean contributed;
493 private ArrayList<Pattern> supportedAnnotationPatterns;
494 private ArrayList<String> supportedOptionNames;
496 ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
497 processor = p;
498 contributed = false;
500 try {
501 processor.init(env);
503 checkSourceVersionCompatibility(source, log);
505 supportedAnnotationPatterns = new ArrayList<Pattern>();
506 for (String importString : processor.getSupportedAnnotationTypes()) {
507 supportedAnnotationPatterns.add(importStringToPattern(importString,
508 processor,
509 log));
510 }
512 supportedOptionNames = new ArrayList<String>();
513 for (String optionName : processor.getSupportedOptions() ) {
514 if (checkOptionName(optionName, log))
515 supportedOptionNames.add(optionName);
516 }
518 } catch (ClientCodeException e) {
519 throw e;
520 } catch (Throwable t) {
521 throw new AnnotationProcessingError(t);
522 }
523 }
525 /**
526 * Checks whether or not a processor's source version is
527 * compatible with the compilation source version. The
528 * processor's source version needs to be greater than or
529 * equal to the source version of the compile.
530 */
531 private void checkSourceVersionCompatibility(Source source, Log log) {
532 SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
534 if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 ) {
535 log.warning("proc.processor.incompatible.source.version",
536 procSourceVersion,
537 processor.getClass().getName(),
538 source.name);
539 }
540 }
542 private boolean checkOptionName(String optionName, Log log) {
543 boolean valid = isValidOptionName(optionName);
544 if (!valid)
545 log.error("proc.processor.bad.option.name",
546 optionName,
547 processor.getClass().getName());
548 return valid;
549 }
551 public boolean annotationSupported(String annotationName) {
552 for(Pattern p: supportedAnnotationPatterns) {
553 if (p.matcher(annotationName).matches())
554 return true;
555 }
556 return false;
557 }
559 /**
560 * Remove options that are matched by this processor.
561 */
562 public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) {
563 unmatchedProcessorOptions.removeAll(supportedOptionNames);
564 }
565 }
567 // TODO: These two classes can probably be rewritten better...
568 /**
569 * This class holds information about the processors that have
570 * been discoverd so far as well as the means to discover more, if
571 * necessary. A single iterator should be used per round of
572 * annotation processing. The iterator first visits already
573 * discovered processors then fails over to the service provider
574 * mechanism if additional queries are made.
575 */
576 class DiscoveredProcessors implements Iterable<ProcessorState> {
578 class ProcessorStateIterator implements Iterator<ProcessorState> {
579 DiscoveredProcessors psi;
580 Iterator<ProcessorState> innerIter;
581 boolean onProcInterator;
583 ProcessorStateIterator(DiscoveredProcessors psi) {
584 this.psi = psi;
585 this.innerIter = psi.procStateList.iterator();
586 this.onProcInterator = false;
587 }
589 public ProcessorState next() {
590 if (!onProcInterator) {
591 if (innerIter.hasNext())
592 return innerIter.next();
593 else
594 onProcInterator = true;
595 }
597 if (psi.processorIterator.hasNext()) {
598 ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
599 log, source, JavacProcessingEnvironment.this);
600 psi.procStateList.add(ps);
601 return ps;
602 } else
603 throw new NoSuchElementException();
604 }
606 public boolean hasNext() {
607 if (onProcInterator)
608 return psi.processorIterator.hasNext();
609 else
610 return innerIter.hasNext() || psi.processorIterator.hasNext();
611 }
613 public void remove () {
614 throw new UnsupportedOperationException();
615 }
617 /**
618 * Run all remaining processors on the procStateList that
619 * have not already run this round with an empty set of
620 * annotations.
621 */
622 public void runContributingProcs(RoundEnvironment re) {
623 if (!onProcInterator) {
624 Set<TypeElement> emptyTypeElements = Collections.emptySet();
625 while(innerIter.hasNext()) {
626 ProcessorState ps = innerIter.next();
627 if (ps.contributed)
628 callProcessor(ps.processor, emptyTypeElements, re);
629 }
630 }
631 }
632 }
634 Iterator<? extends Processor> processorIterator;
635 ArrayList<ProcessorState> procStateList;
637 public ProcessorStateIterator iterator() {
638 return new ProcessorStateIterator(this);
639 }
641 DiscoveredProcessors(Iterator<? extends Processor> processorIterator) {
642 this.processorIterator = processorIterator;
643 this.procStateList = new ArrayList<ProcessorState>();
644 }
646 /**
647 * Free jar files, etc. if using a service loader.
648 */
649 public void close() {
650 if (processorIterator != null &&
651 processorIterator instanceof ServiceIterator) {
652 ((ServiceIterator) processorIterator).close();
653 }
654 }
655 }
657 private void discoverAndRunProcs(Context context,
658 Set<TypeElement> annotationsPresent,
659 List<ClassSymbol> topLevelClasses,
660 List<PackageSymbol> packageInfoFiles) {
661 Map<String, TypeElement> unmatchedAnnotations =
662 new HashMap<String, TypeElement>(annotationsPresent.size());
664 for(TypeElement a : annotationsPresent) {
665 unmatchedAnnotations.put(a.getQualifiedName().toString(),
666 a);
667 }
669 // Give "*" processors a chance to match
670 if (unmatchedAnnotations.size() == 0)
671 unmatchedAnnotations.put("", null);
673 DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
674 // TODO: Create proper argument values; need past round
675 // information to fill in this constructor. Note that the 1
676 // st round of processing could be the last round if there
677 // were parse errors on the initial source files; however, we
678 // are not doing processing in that case.
680 Set<Element> rootElements = new LinkedHashSet<Element>();
681 rootElements.addAll(topLevelClasses);
682 rootElements.addAll(packageInfoFiles);
683 rootElements = Collections.unmodifiableSet(rootElements);
685 RoundEnvironment renv = new JavacRoundEnvironment(false,
686 false,
687 rootElements,
688 JavacProcessingEnvironment.this);
690 while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
691 ProcessorState ps = psi.next();
692 Set<String> matchedNames = new HashSet<String>();
693 Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();
695 for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) {
696 String unmatchedAnnotationName = entry.getKey();
697 if (ps.annotationSupported(unmatchedAnnotationName) ) {
698 matchedNames.add(unmatchedAnnotationName);
699 TypeElement te = entry.getValue();
700 if (te != null)
701 typeElements.add(te);
702 }
703 }
705 if (matchedNames.size() > 0 || ps.contributed) {
706 boolean processingResult = callProcessor(ps.processor, typeElements, renv);
707 ps.contributed = true;
708 ps.removeSupportedOptions(unmatchedProcessorOptions);
710 if (printProcessorInfo || verbose) {
711 log.printLines("x.print.processor.info",
712 ps.processor.getClass().getName(),
713 matchedNames.toString(),
714 processingResult);
715 }
717 if (processingResult) {
718 unmatchedAnnotations.keySet().removeAll(matchedNames);
719 }
721 }
722 }
723 unmatchedAnnotations.remove("");
725 if (lint && unmatchedAnnotations.size() > 0) {
726 // Remove annotations processed by javac
727 unmatchedAnnotations.keySet().removeAll(platformAnnotations);
728 if (unmatchedAnnotations.size() > 0) {
729 log = Log.instance(context);
730 log.warning("proc.annotations.without.processors",
731 unmatchedAnnotations.keySet());
732 }
733 }
735 // Run contributing processors that haven't run yet
736 psi.runContributingProcs(renv);
738 // Debugging
739 if (options.isSet("displayFilerState"))
740 filer.displayState();
741 }
743 /**
744 * Computes the set of annotations on the symbol in question.
745 * Leave class public for external testing purposes.
746 */
747 public static class ComputeAnnotationSet extends
748 ElementScanner8<Set<TypeElement>, Set<TypeElement>> {
749 final Elements elements;
751 public ComputeAnnotationSet(Elements elements) {
752 super();
753 this.elements = elements;
754 }
756 @Override
757 public Set<TypeElement> visitPackage(PackageElement e, Set<TypeElement> p) {
758 // Don't scan enclosed elements of a package
759 return p;
760 }
762 @Override
763 public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
764 for (AnnotationMirror annotationMirror :
765 elements.getAllAnnotationMirrors(e) ) {
766 Element e2 = annotationMirror.getAnnotationType().asElement();
767 p.add((TypeElement) e2);
768 }
769 return super.scan(e, p);
770 }
771 }
773 private boolean callProcessor(Processor proc,
774 Set<? extends TypeElement> tes,
775 RoundEnvironment renv) {
776 try {
777 return proc.process(tes, renv);
778 } catch (BadClassFile ex) {
779 log.error("proc.cant.access.1", ex.sym, ex.getDetailValue());
780 return false;
781 } catch (CompletionFailure ex) {
782 StringWriter out = new StringWriter();
783 ex.printStackTrace(new PrintWriter(out));
784 log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
785 return false;
786 } catch (ClientCodeException e) {
787 throw e;
788 } catch (Throwable t) {
789 throw new AnnotationProcessingError(t);
790 }
791 }
793 /**
794 * Helper object for a single round of annotation processing.
795 */
796 class Round {
797 /** The round number. */
798 final int number;
799 /** The context for the round. */
800 final Context context;
801 /** The compiler for the round. */
802 final JavaCompiler compiler;
803 /** The log for the round. */
804 final Log log;
805 /** The diagnostic handler for the round. */
806 final Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
808 /** The ASTs to be compiled. */
809 List<JCCompilationUnit> roots;
810 /** The classes to be compiler that have were generated. */
811 Map<String, JavaFileObject> genClassFiles;
813 /** The set of annotations to be processed this round. */
814 Set<TypeElement> annotationsPresent;
815 /** The set of top level classes to be processed this round. */
816 List<ClassSymbol> topLevelClasses;
817 /** The set of package-info files to be processed this round. */
818 List<PackageSymbol> packageInfoFiles;
820 /** The number of Messager errors generated in this round. */
821 int nMessagerErrors;
823 /** Create a round (common code). */
824 private Round(Context context, int number, int priorErrors, int priorWarnings,
825 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
826 this.context = context;
827 this.number = number;
829 compiler = JavaCompiler.instance(context);
830 log = Log.instance(context);
831 log.nerrors = priorErrors;
832 log.nwarnings += priorWarnings;
833 if (number == 1) {
834 Assert.checkNonNull(deferredDiagnosticHandler);
835 this.deferredDiagnosticHandler = deferredDiagnosticHandler;
836 } else {
837 this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
838 }
840 // the following is for the benefit of JavacProcessingEnvironment.getContext()
841 JavacProcessingEnvironment.this.context = context;
843 // the following will be populated as needed
844 topLevelClasses = List.nil();
845 packageInfoFiles = List.nil();
846 }
848 /** Create the first round. */
849 Round(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols,
850 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
851 this(context, 1, 0, 0, deferredDiagnosticHandler);
852 this.roots = roots;
853 genClassFiles = new HashMap<String,JavaFileObject>();
855 compiler.todo.clear(); // free the compiler's resources
857 // The reverse() in the following line is to maintain behavioural
858 // compatibility with the previous revision of the code. Strictly speaking,
859 // it should not be necessary, but a javah golden file test fails without it.
860 topLevelClasses =
861 getTopLevelClasses(roots).prependList(classSymbols.reverse());
863 packageInfoFiles = getPackageInfoFiles(roots);
865 findAnnotationsPresent();
866 }
868 /** Create a new round. */
869 private Round(Round prev,
870 Set<JavaFileObject> newSourceFiles, Map<String,JavaFileObject> newClassFiles) {
871 this(prev.nextContext(),
872 prev.number+1,
873 prev.nMessagerErrors,
874 prev.compiler.log.nwarnings,
875 null);
876 this.genClassFiles = prev.genClassFiles;
878 List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles);
879 roots = cleanTrees(prev.roots).appendList(parsedFiles);
881 // Check for errors after parsing
882 if (unrecoverableError())
883 return;
885 enterClassFiles(genClassFiles);
886 List<ClassSymbol> newClasses = enterClassFiles(newClassFiles);
887 genClassFiles.putAll(newClassFiles);
888 enterTrees(roots);
890 if (unrecoverableError())
891 return;
893 topLevelClasses = join(
894 getTopLevelClasses(parsedFiles),
895 getTopLevelClassesFromClasses(newClasses));
897 packageInfoFiles = join(
898 getPackageInfoFiles(parsedFiles),
899 getPackageInfoFilesFromClasses(newClasses));
901 findAnnotationsPresent();
902 }
904 /** Create the next round to be used. */
905 Round next(Set<JavaFileObject> newSourceFiles, Map<String, JavaFileObject> newClassFiles) {
906 try {
907 return new Round(this, newSourceFiles, newClassFiles);
908 } finally {
909 compiler.close(false);
910 }
911 }
913 /** Create the compiler to be used for the final compilation. */
914 JavaCompiler finalCompiler(boolean errorStatus) {
915 try {
916 Context nextCtx = nextContext();
917 JavacProcessingEnvironment.this.context = nextCtx;
918 JavaCompiler c = JavaCompiler.instance(nextCtx);
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: deferredDiagnosticHandler.getDiagnostics()) {
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 if (!taskListener.isEmpty())
1012 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1014 try {
1015 if (lastRound) {
1016 filer.setLastRound(true);
1017 Set<Element> emptyRootElements = Collections.emptySet(); // immutable
1018 RoundEnvironment renv = new JavacRoundEnvironment(true,
1019 errorStatus,
1020 emptyRootElements,
1021 JavacProcessingEnvironment.this);
1022 discoveredProcs.iterator().runContributingProcs(renv);
1023 } else {
1024 discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles);
1025 }
1026 } finally {
1027 if (!taskListener.isEmpty())
1028 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
1029 }
1031 nMessagerErrors = messager.errorCount();
1032 }
1034 void showDiagnostics(boolean showAll) {
1035 Set<JCDiagnostic.Kind> kinds = EnumSet.allOf(JCDiagnostic.Kind.class);
1036 if (!showAll) {
1037 // suppress errors, which are all presumed to be transient resolve errors
1038 kinds.remove(JCDiagnostic.Kind.ERROR);
1039 }
1040 deferredDiagnosticHandler.reportDeferredDiagnostics(kinds);
1041 log.popDiagnosticHandler(deferredDiagnosticHandler);
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.printLines("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 propagated 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 Locale locale = context.get(Locale.class);
1069 if (locale != null)
1070 next.put(Locale.class, locale);
1072 Assert.checkNonNull(messages);
1073 next.put(JavacMessages.messagesKey, messages);
1075 final boolean shareNames = true;
1076 if (shareNames) {
1077 Names names = Names.instance(context);
1078 Assert.checkNonNull(names);
1079 next.put(Names.namesKey, names);
1080 }
1082 DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
1083 if (dl != null)
1084 next.put(DiagnosticListener.class, dl);
1086 MultiTaskListener mtl = context.get(MultiTaskListener.taskListenerKey);
1087 if (mtl != null)
1088 next.put(MultiTaskListener.taskListenerKey, mtl);
1090 FSInfo fsInfo = context.get(FSInfo.class);
1091 if (fsInfo != null)
1092 next.put(FSInfo.class, fsInfo);
1094 JavaFileManager jfm = context.get(JavaFileManager.class);
1095 Assert.checkNonNull(jfm);
1096 next.put(JavaFileManager.class, jfm);
1097 if (jfm instanceof JavacFileManager) {
1098 ((JavacFileManager)jfm).setContext(next);
1099 }
1101 Names names = Names.instance(context);
1102 Assert.checkNonNull(names);
1103 next.put(Names.namesKey, names);
1105 Tokens tokens = Tokens.instance(context);
1106 Assert.checkNonNull(tokens);
1107 next.put(Tokens.tokensKey, tokens);
1109 Log nextLog = Log.instance(next);
1110 // propogate the log's writers directly, instead of going through context
1111 nextLog.setWriters(log);
1112 nextLog.setSourceMap(log);
1114 JavaCompiler oldCompiler = JavaCompiler.instance(context);
1115 JavaCompiler nextCompiler = JavaCompiler.instance(next);
1116 nextCompiler.initRound(oldCompiler);
1118 filer.newRound(next);
1119 messager.newRound(next);
1120 elementUtils.setContext(next);
1121 typeUtils.setContext(next);
1123 JavacTask task = context.get(JavacTask.class);
1124 if (task != null) {
1125 next.put(JavacTask.class, task);
1126 if (task instanceof BasicJavacTask)
1127 ((BasicJavacTask) task).updateContext(next);
1128 }
1130 JavacTrees trees = context.get(JavacTrees.class);
1131 if (trees != null) {
1132 next.put(JavacTrees.class, trees);
1133 trees.updateContext(next);
1134 }
1136 context.clear();
1137 return next;
1138 }
1139 }
1142 // TODO: internal catch clauses?; catch and rethrow an annotation
1143 // processing error
1144 public JavaCompiler doProcessing(Context context,
1145 List<JCCompilationUnit> roots,
1146 List<ClassSymbol> classSymbols,
1147 Iterable<? extends PackageSymbol> pckSymbols,
1148 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
1149 log = Log.instance(context);
1151 Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
1152 for (PackageSymbol psym : pckSymbols)
1153 specifiedPackages.add(psym);
1154 this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
1156 Round round = new Round(context, roots, classSymbols, deferredDiagnosticHandler);
1158 boolean errorStatus;
1159 boolean moreToDo;
1160 do {
1161 // Run processors for round n
1162 round.run(false, false);
1164 // Processors for round n have run to completion.
1165 // Check for errors and whether there is more work to do.
1166 errorStatus = round.unrecoverableError();
1167 moreToDo = moreToDo();
1169 round.showDiagnostics(errorStatus || showResolveErrors);
1171 // Set up next round.
1172 // Copy mutable collections returned from filer.
1173 round = round.next(
1174 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()),
1175 new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses()));
1177 // Check for errors during setup.
1178 if (round.unrecoverableError())
1179 errorStatus = true;
1181 } while (moreToDo && !errorStatus);
1183 // run last round
1184 round.run(true, errorStatus);
1185 round.showDiagnostics(true);
1187 filer.warnIfUnclosedFiles();
1188 warnIfUnmatchedOptions();
1190 /*
1191 * If an annotation processor raises an error in a round,
1192 * that round runs to completion and one last round occurs.
1193 * The last round may also occur because no more source or
1194 * class files have been generated. Therefore, if an error
1195 * was raised on either of the last *two* rounds, the compile
1196 * should exit with a nonzero exit code. The current value of
1197 * errorStatus holds whether or not an error was raised on the
1198 * second to last round; errorRaised() gives the error status
1199 * of the last round.
1200 */
1201 if (messager.errorRaised()
1202 || werror && round.warningCount() > 0 && round.errorCount() > 0)
1203 errorStatus = true;
1205 Set<JavaFileObject> newSourceFiles =
1206 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
1207 roots = cleanTrees(round.roots);
1209 JavaCompiler compiler = round.finalCompiler(errorStatus);
1211 if (newSourceFiles.size() > 0)
1212 roots = roots.appendList(compiler.parseFiles(newSourceFiles));
1214 errorStatus = errorStatus || (compiler.errorCount() > 0);
1216 // Free resources
1217 this.close();
1219 if (!taskListener.isEmpty())
1220 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
1222 if (errorStatus) {
1223 if (compiler.errorCount() == 0)
1224 compiler.log.nerrors++;
1225 return compiler;
1226 }
1228 compiler.enterTreesIfNeeded(roots);
1230 return compiler;
1231 }
1233 private void warnIfUnmatchedOptions() {
1234 if (!unmatchedProcessorOptions.isEmpty()) {
1235 log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
1236 }
1237 }
1239 /**
1240 * Free resources related to annotation processing.
1241 */
1242 public void close() {
1243 filer.close();
1244 if (discoveredProcs != null) // Make calling close idempotent
1245 discoveredProcs.close();
1246 discoveredProcs = null;
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.hasTag(JCTree.Tag.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 final 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.
1397 * {@literal "-Afoo=bar"} should be {@literal "-Afoo" => "bar"}.
1398 */
1399 public Map<String,String> getOptions() {
1400 return processorOptions;
1401 }
1403 public Messager getMessager() {
1404 return messager;
1405 }
1407 public Filer getFiler() {
1408 return filer;
1409 }
1411 public JavacElements getElementUtils() {
1412 return elementUtils;
1413 }
1415 public JavacTypes getTypeUtils() {
1416 return typeUtils;
1417 }
1419 public SourceVersion getSourceVersion() {
1420 return Source.toSourceVersion(source);
1421 }
1423 public Locale getLocale() {
1424 return messages.getCurrentLocale();
1425 }
1427 public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
1428 return specifiedPackages;
1429 }
1431 private static final Pattern allMatches = Pattern.compile(".*");
1432 public static final Pattern noMatches = Pattern.compile("(\\P{all})+");
1434 /**
1435 * Convert import-style string for supported annotations into a
1436 * regex matching that string. If the string is a valid
1437 * import-style string, return a regex that won't match anything.
1438 */
1439 private static Pattern importStringToPattern(String s, Processor p, Log log) {
1440 if (isValidImportString(s)) {
1441 return validImportStringToPattern(s);
1442 } else {
1443 log.warning("proc.malformed.supported.string", s, p.getClass().getName());
1444 return noMatches; // won't match any valid identifier
1445 }
1446 }
1448 /**
1449 * Return true if the argument string is a valid import-style
1450 * string specifying claimed annotations; return false otherwise.
1451 */
1452 public static boolean isValidImportString(String s) {
1453 if (s.equals("*"))
1454 return true;
1456 boolean valid = true;
1457 String t = s;
1458 int index = t.indexOf('*');
1460 if (index != -1) {
1461 // '*' must be last character...
1462 if (index == t.length() -1) {
1463 // ... any and preceding character must be '.'
1464 if ( index-1 >= 0 ) {
1465 valid = t.charAt(index-1) == '.';
1466 // Strip off ".*$" for identifier checks
1467 t = t.substring(0, t.length()-2);
1468 }
1469 } else
1470 return false;
1471 }
1473 // Verify string is off the form (javaId \.)+ or javaId
1474 if (valid) {
1475 String[] javaIds = t.split("\\.", t.length()+2);
1476 for(String javaId: javaIds)
1477 valid &= SourceVersion.isIdentifier(javaId);
1478 }
1479 return valid;
1480 }
1482 public static Pattern validImportStringToPattern(String s) {
1483 if (s.equals("*")) {
1484 return allMatches;
1485 } else {
1486 String s_prime = s.replace(".", "\\.");
1488 if (s_prime.endsWith("*")) {
1489 s_prime = s_prime.substring(0, s_prime.length() - 1) + ".+";
1490 }
1492 return Pattern.compile(s_prime);
1493 }
1494 }
1496 /**
1497 * For internal use only. This method may be removed without warning.
1498 */
1499 public Context getContext() {
1500 return context;
1501 }
1503 /**
1504 * For internal use only. This method may be removed without warning.
1505 */
1506 public ClassLoader getProcessorClassLoader() {
1507 return processorClassLoader;
1508 }
1510 public String toString() {
1511 return "javac ProcessingEnvironment";
1512 }
1514 public static boolean isValidOptionName(String optionName) {
1515 for(String s : optionName.split("\\.", -1)) {
1516 if (!SourceVersion.isIdentifier(s))
1517 return false;
1518 }
1519 return true;
1520 }
1521 }