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