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.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.*; 49 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.*; 83 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; 95 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; 103 104 private final JavacFiler filer; 105 private final JavacMessager messager; 106 private final JavacElements elementUtils; 107 private final JavacTypes typeUtils; 108 109 /** 110 * Holds relevant state history of which processors have been 111 * used. 112 */ 113 private DiscoveredProcessors discoveredProcs; 114 115 /** 116 * Map of processor-specific options. 117 */ 118 private final Map<String, String> processorOptions; 119 120 /** 121 */ 122 private final Set<String> unmatchedProcessorOptions; 123 124 /** 125 * Annotations implicitly processed and claimed by javac. 126 */ 127 private final Set<String> platformAnnotations; 128 129 /** 130 * Set of packages given on command line. 131 */ 132 private Set<PackageSymbol> specifiedPackages = Collections.emptySet(); 133 134 /** The log to be used for error reporting. 135 */ 136 Log log; 137 138 /** Diagnostic factory. 139 */ 140 JCDiagnostic.Factory diags; 141 142 /** 143 * Source level of the compile. 144 */ 145 Source source; 146 147 private ClassLoader processorClassLoader; 148 private SecurityException processorClassLoaderException; 149 150 /** 151 * JavacMessages object used for localization 152 */ 153 private JavacMessages messages; 154 155 private MultiTaskListener taskListener; 156 157 private Context context; 158 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 } 166 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(); 185 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 } 198 199 public void setProcessors(Iterable<? extends Processor> processors) { 200 Assert.checkNull(discoveredProcs); 201 initProcessorIterator(context, processors); 202 } 203 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 } 215 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); 223 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 } 232 233 private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) { 234 Log log = Log.instance(context); 235 Iterator<? extends Processor> processorIterator; 236 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 } 275 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); 289 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); 295 296 if (needClassLoader(options.get(PROCESSOR), workingPath) ) 297 handleException(key, e); 298 299 } else { 300 handleException(key, e); 301 } 302 303 java.util.List<Processor> pl = Collections.emptyList(); 304 return pl.iterator(); 305 } 306 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 } 320 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; 330 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 } 346 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 } 357 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 } 368 369 public void remove() { 370 throw new UnsupportedOperationException(); 371 } 372 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 } 383 384 385 private static class NameProcessIterator implements Iterator<Processor> { 386 Processor nextProc = null; 387 Iterator<String> names; 388 ClassLoader processorCL; 389 Log log; 390 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 } 396 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(); 405 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 } 429 430 } 431 } 432 433 public Processor next() { 434 if (hasNext()) { 435 Processor p = nextProc; 436 nextProc = null; 437 return p; 438 } else 439 throw new NoSuchElementException(); 440 } 441 442 public void remove () { 443 throw new UnsupportedOperationException(); 444 } 445 } 446 447 public boolean atLeastOneProcessor() { 448 return discoveredProcs.iterator().hasNext(); 449 } 450 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>(); 455 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; 461 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 } 472 473 return Collections.unmodifiableMap(tempOptions); 474 } 475 476 private Set<String> initUnmatchedProcessorOptions() { 477 Set<String> unmatchedProcessorOptions = new HashSet<String>(); 478 unmatchedProcessorOptions.addAll(processorOptions.keySet()); 479 return unmatchedProcessorOptions; 480 } 481 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; 495 496 ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) { 497 processor = p; 498 contributed = false; 499 500 try { 501 processor.init(env); 502 503 checkSourceVersionCompatibility(source, log); 504 505 supportedAnnotationPatterns = new ArrayList<Pattern>(); 506 for (String importString : processor.getSupportedAnnotationTypes()) { 507 supportedAnnotationPatterns.add(importStringToPattern(importString, 508 processor, 509 log)); 510 } 511 512 supportedOptionNames = new ArrayList<String>(); 513 for (String optionName : processor.getSupportedOptions() ) { 514 if (checkOptionName(optionName, log)) 515 supportedOptionNames.add(optionName); 516 } 517 518 } catch (ClientCodeException e) { 519 throw e; 520 } catch (Throwable t) { 521 throw new AnnotationProcessingError(t); 522 } 523 } 524 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(); 533 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 } 541 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 } 550 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 } 558 559 /** 560 * Remove options that are matched by this processor. 561 */ 562 public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) { 563 unmatchedProcessorOptions.removeAll(supportedOptionNames); 564 } 565 } 566 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> { 577 578 class ProcessorStateIterator implements Iterator<ProcessorState> { 579 DiscoveredProcessors psi; 580 Iterator<ProcessorState> innerIter; 581 boolean onProcInterator; 582 583 ProcessorStateIterator(DiscoveredProcessors psi) { 584 this.psi = psi; 585 this.innerIter = psi.procStateList.iterator(); 586 this.onProcInterator = false; 587 } 588 589 public ProcessorState next() { 590 if (!onProcInterator) { 591 if (innerIter.hasNext()) 592 return innerIter.next(); 593 else 594 onProcInterator = true; 595 } 596 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 } 605 606 public boolean hasNext() { 607 if (onProcInterator) 608 return psi.processorIterator.hasNext(); 609 else 610 return innerIter.hasNext() || psi.processorIterator.hasNext(); 611 } 612 613 public void remove () { 614 throw new UnsupportedOperationException(); 615 } 616 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 } 633 634 Iterator<? extends Processor> processorIterator; 635 ArrayList<ProcessorState> procStateList; 636 637 public ProcessorStateIterator iterator() { 638 return new ProcessorStateIterator(this); 639 } 640 641 DiscoveredProcessors(Iterator<? extends Processor> processorIterator) { 642 this.processorIterator = processorIterator; 643 this.procStateList = new ArrayList<ProcessorState>(); 644 } 645 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 } 656 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()); 663 664 for(TypeElement a : annotationsPresent) { 665 unmatchedAnnotations.put(a.getQualifiedName().toString(), 666 a); 667 } 668 669 // Give "*" processors a chance to match 670 if (unmatchedAnnotations.size() == 0) 671 unmatchedAnnotations.put("", null); 672 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. 679 680 Set<Element> rootElements = new LinkedHashSet<Element>(); 681 rootElements.addAll(topLevelClasses); 682 rootElements.addAll(packageInfoFiles); 683 rootElements = Collections.unmodifiableSet(rootElements); 684 685 RoundEnvironment renv = new JavacRoundEnvironment(false, 686 false, 687 rootElements, 688 JavacProcessingEnvironment.this); 689 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>(); 694 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 } 704 705 if (matchedNames.size() > 0 || ps.contributed) { 706 boolean processingResult = callProcessor(ps.processor, typeElements, renv); 707 ps.contributed = true; 708 ps.removeSupportedOptions(unmatchedProcessorOptions); 709 710 if (printProcessorInfo || verbose) { 711 log.printLines("x.print.processor.info", 712 ps.processor.getClass().getName(), 713 matchedNames.toString(), 714 processingResult); 715 } 716 717 if (processingResult) { 718 unmatchedAnnotations.keySet().removeAll(matchedNames); 719 } 720 721 } 722 } 723 unmatchedAnnotations.remove(""); 724 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 } 734 735 // Run contributing processors that haven't run yet 736 psi.runContributingProcs(renv); 737 738 // Debugging 739 if (options.isSet("displayFilerState")) 740 filer.displayState(); 741 } 742 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; 750 751 public ComputeAnnotationSet(Elements elements) { 752 super(); 753 this.elements = elements; 754 } 755 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 } 761 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 } 772 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 } 792 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; 807 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; 812 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; 819 820 /** Create a round (common code). */ 821 private Round(Context context, int number, int priorErrors, int priorWarnings, 822 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) { 823 this.context = context; 824 this.number = number; 825 826 compiler = JavaCompiler.instance(context); 827 log = Log.instance(context); 828 log.nerrors = priorErrors; 829 log.nwarnings = priorWarnings; 830 if (number == 1) { 831 Assert.checkNonNull(deferredDiagnosticHandler); 832 this.deferredDiagnosticHandler = deferredDiagnosticHandler; 833 } else { 834 this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log); 835 } 836 837 // the following is for the benefit of JavacProcessingEnvironment.getContext() 838 JavacProcessingEnvironment.this.context = context; 839 840 // the following will be populated as needed 841 topLevelClasses = List.nil(); 842 packageInfoFiles = List.nil(); 843 } 844 845 /** Create the first round. */ 846 Round(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols, 847 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) { 848 this(context, 1, 0, 0, deferredDiagnosticHandler); 849 this.roots = roots; 850 genClassFiles = new HashMap<String,JavaFileObject>(); 851 852 compiler.todo.clear(); // free the compiler's resources 853 854 // The reverse() in the following line is to maintain behavioural 855 // compatibility with the previous revision of the code. Strictly speaking, 856 // it should not be necessary, but a javah golden file test fails without it. 857 topLevelClasses = 858 getTopLevelClasses(roots).prependList(classSymbols.reverse()); 859 860 packageInfoFiles = getPackageInfoFiles(roots); 861 862 findAnnotationsPresent(); 863 } 864 865 /** Create a new round. */ 866 private Round(Round prev, 867 Set<JavaFileObject> newSourceFiles, Map<String,JavaFileObject> newClassFiles) { 868 this(prev.nextContext(), 869 prev.number+1, 870 prev.compiler.log.nerrors, 871 prev.compiler.log.nwarnings, 872 null); 873 this.genClassFiles = prev.genClassFiles; 874 875 List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles); 876 roots = cleanTrees(prev.roots).appendList(parsedFiles); 877 878 // Check for errors after parsing 879 if (unrecoverableError()) 880 return; 881 882 enterClassFiles(genClassFiles); 883 List<ClassSymbol> newClasses = enterClassFiles(newClassFiles); 884 genClassFiles.putAll(newClassFiles); 885 enterTrees(roots); 886 887 if (unrecoverableError()) 888 return; 889 890 topLevelClasses = join( 891 getTopLevelClasses(parsedFiles), 892 getTopLevelClassesFromClasses(newClasses)); 893 894 packageInfoFiles = join( 895 getPackageInfoFiles(parsedFiles), 896 getPackageInfoFilesFromClasses(newClasses)); 897 898 findAnnotationsPresent(); 899 } 900 901 /** Create the next round to be used. */ 902 Round next(Set<JavaFileObject> newSourceFiles, Map<String, JavaFileObject> newClassFiles) { 903 try { 904 return new Round(this, newSourceFiles, newClassFiles); 905 } finally { 906 compiler.close(false); 907 } 908 } 909 910 /** Create the compiler to be used for the final compilation. */ 911 JavaCompiler finalCompiler() { 912 try { 913 Context nextCtx = nextContext(); 914 JavacProcessingEnvironment.this.context = nextCtx; 915 JavaCompiler c = JavaCompiler.instance(nextCtx); 916 c.log.initRound(compiler.log); 917 return c; 918 } finally { 919 compiler.close(false); 920 } 921 } 922 923 /** Return the number of errors found so far in this round. 924 * This may include uncoverable errors, such as parse errors, 925 * and transient errors, such as missing symbols. */ 926 int errorCount() { 927 return compiler.errorCount(); 928 } 929 930 /** Return the number of warnings found so far in this round. */ 931 int warningCount() { 932 return compiler.warningCount(); 933 } 934 935 /** Return whether or not an unrecoverable error has occurred. */ 936 boolean unrecoverableError() { 937 if (messager.errorRaised()) 938 return true; 939 940 for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) { 941 switch (d.getKind()) { 942 case WARNING: 943 if (werror) 944 return true; 945 break; 946 947 case ERROR: 948 if (fatalErrors || !d.isFlagSet(RECOVERABLE)) 949 return true; 950 break; 951 } 952 } 953 954 return false; 955 } 956 957 /** Find the set of annotations present in the set of top level 958 * classes and package info files to be processed this round. */ 959 void findAnnotationsPresent() { 960 ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils); 961 // Use annotation processing to compute the set of annotations present 962 annotationsPresent = new LinkedHashSet<TypeElement>(); 963 for (ClassSymbol classSym : topLevelClasses) 964 annotationComputer.scan(classSym, annotationsPresent); 965 for (PackageSymbol pkgSym : packageInfoFiles) 966 annotationComputer.scan(pkgSym, annotationsPresent); 967 } 968 969 /** Enter a set of generated class files. */ 970 private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) { 971 ClassReader reader = ClassReader.instance(context); 972 Names names = Names.instance(context); 973 List<ClassSymbol> list = List.nil(); 974 975 for (Map.Entry<String,JavaFileObject> entry : classFiles.entrySet()) { 976 Name name = names.fromString(entry.getKey()); 977 JavaFileObject file = entry.getValue(); 978 if (file.getKind() != JavaFileObject.Kind.CLASS) 979 throw new AssertionError(file); 980 ClassSymbol cs; 981 if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) { 982 Name packageName = Convert.packagePart(name); 983 PackageSymbol p = reader.enterPackage(packageName); 984 if (p.package_info == null) 985 p.package_info = reader.enterClass(Convert.shortName(name), p); 986 cs = p.package_info; 987 if (cs.classfile == null) 988 cs.classfile = file; 989 } else 990 cs = reader.enterClass(name, file); 991 list = list.prepend(cs); 992 } 993 return list.reverse(); 994 } 995 996 /** Enter a set of syntax trees. */ 997 private void enterTrees(List<JCCompilationUnit> roots) { 998 compiler.enterTrees(roots); 999 } 1000 1001 /** Run a processing round. */ 1002 void run(boolean lastRound, boolean errorStatus) { 1003 printRoundInfo(lastRound); 1004 1005 if (!taskListener.isEmpty()) 1006 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND)); 1007 1008 try { 1009 if (lastRound) { 1010 filer.setLastRound(true); 1011 Set<Element> emptyRootElements = Collections.emptySet(); // immutable 1012 RoundEnvironment renv = new JavacRoundEnvironment(true, 1013 errorStatus, 1014 emptyRootElements, 1015 JavacProcessingEnvironment.this); 1016 discoveredProcs.iterator().runContributingProcs(renv); 1017 } else { 1018 discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles); 1019 } 1020 } finally { 1021 if (!taskListener.isEmpty()) 1022 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND)); 1023 } 1024 } 1025 1026 void showDiagnostics(boolean showAll) { 1027 Set<JCDiagnostic.Kind> kinds = EnumSet.allOf(JCDiagnostic.Kind.class); 1028 if (!showAll) { 1029 // suppress errors, which are all presumed to be transient resolve errors 1030 kinds.remove(JCDiagnostic.Kind.ERROR); 1031 } 1032 deferredDiagnosticHandler.reportDeferredDiagnostics(kinds); 1033 log.popDiagnosticHandler(deferredDiagnosticHandler); 1034 } 1035 1036 /** Print info about this round. */ 1037 private void printRoundInfo(boolean lastRound) { 1038 if (printRounds || verbose) { 1039 List<ClassSymbol> tlc = lastRound ? List.<ClassSymbol>nil() : topLevelClasses; 1040 Set<TypeElement> ap = lastRound ? Collections.<TypeElement>emptySet() : annotationsPresent; 1041 log.printLines("x.print.rounds", 1042 number, 1043 "{" + tlc.toString(", ") + "}", 1044 ap, 1045 lastRound); 1046 } 1047 } 1048 1049 /** Get the context for the next round of processing. 1050 * Important values are propagated from round to round; 1051 * other values are implicitly reset. 1052 */ 1053 private Context nextContext() { 1054 Context next = new Context(context); 1055 1056 Options options = Options.instance(context); 1057 Assert.checkNonNull(options); 1058 next.put(Options.optionsKey, options); 1059 1060 Locale locale = context.get(Locale.class); 1061 if (locale != null) 1062 next.put(Locale.class, locale); 1063 1064 Assert.checkNonNull(messages); 1065 next.put(JavacMessages.messagesKey, messages); 1066 1067 final boolean shareNames = true; 1068 if (shareNames) { 1069 Names names = Names.instance(context); 1070 Assert.checkNonNull(names); 1071 next.put(Names.namesKey, names); 1072 } 1073 1074 DiagnosticListener<?> dl = context.get(DiagnosticListener.class); 1075 if (dl != null) 1076 next.put(DiagnosticListener.class, dl); 1077 1078 MultiTaskListener mtl = context.get(MultiTaskListener.taskListenerKey); 1079 if (mtl != null) 1080 next.put(MultiTaskListener.taskListenerKey, mtl); 1081 1082 FSInfo fsInfo = context.get(FSInfo.class); 1083 if (fsInfo != null) 1084 next.put(FSInfo.class, fsInfo); 1085 1086 JavaFileManager jfm = context.get(JavaFileManager.class); 1087 Assert.checkNonNull(jfm); 1088 next.put(JavaFileManager.class, jfm); 1089 if (jfm instanceof JavacFileManager) { 1090 ((JavacFileManager)jfm).setContext(next); 1091 } 1092 1093 Names names = Names.instance(context); 1094 Assert.checkNonNull(names); 1095 next.put(Names.namesKey, names); 1096 1097 Tokens tokens = Tokens.instance(context); 1098 Assert.checkNonNull(tokens); 1099 next.put(Tokens.tokensKey, tokens); 1100 1101 Log nextLog = Log.instance(next); 1102 nextLog.initRound(log); 1103 1104 JavaCompiler oldCompiler = JavaCompiler.instance(context); 1105 JavaCompiler nextCompiler = JavaCompiler.instance(next); 1106 nextCompiler.initRound(oldCompiler); 1107 1108 filer.newRound(next); 1109 messager.newRound(next); 1110 elementUtils.setContext(next); 1111 typeUtils.setContext(next); 1112 1113 JavacTask task = context.get(JavacTask.class); 1114 if (task != null) { 1115 next.put(JavacTask.class, task); 1116 if (task instanceof BasicJavacTask) 1117 ((BasicJavacTask) task).updateContext(next); 1118 } 1119 1120 JavacTrees trees = context.get(JavacTrees.class); 1121 if (trees != null) { 1122 next.put(JavacTrees.class, trees); 1123 trees.updateContext(next); 1124 } 1125 1126 context.clear(); 1127 return next; 1128 } 1129 } 1130 1131 1132 // TODO: internal catch clauses?; catch and rethrow an annotation 1133 // processing error 1134 public JavaCompiler doProcessing(Context context, 1135 List<JCCompilationUnit> roots, 1136 List<ClassSymbol> classSymbols, 1137 Iterable<? extends PackageSymbol> pckSymbols, 1138 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) { 1139 log = Log.instance(context); 1140 1141 Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>(); 1142 for (PackageSymbol psym : pckSymbols) 1143 specifiedPackages.add(psym); 1144 this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages); 1145 1146 Round round = new Round(context, roots, classSymbols, deferredDiagnosticHandler); 1147 1148 boolean errorStatus; 1149 boolean moreToDo; 1150 do { 1151 // Run processors for round n 1152 round.run(false, false); 1153 1154 // Processors for round n have run to completion. 1155 // Check for errors and whether there is more work to do. 1156 errorStatus = round.unrecoverableError(); 1157 moreToDo = moreToDo(); 1158 1159 round.showDiagnostics(errorStatus || showResolveErrors); 1160 1161 // Set up next round. 1162 // Copy mutable collections returned from filer. 1163 round = round.next( 1164 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()), 1165 new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses())); 1166 1167 // Check for errors during setup. 1168 if (round.unrecoverableError()) 1169 errorStatus = true; 1170 1171 } while (moreToDo && !errorStatus); 1172 1173 // run last round 1174 round.run(true, errorStatus); 1175 round.showDiagnostics(true); 1176 1177 filer.warnIfUnclosedFiles(); 1178 warnIfUnmatchedOptions(); 1179 1180 /* 1181 * If an annotation processor raises an error in a round, 1182 * that round runs to completion and one last round occurs. 1183 * The last round may also occur because no more source or 1184 * class files have been generated. Therefore, if an error 1185 * was raised on either of the last *two* rounds, the compile 1186 * should exit with a nonzero exit code. The current value of 1187 * errorStatus holds whether or not an error was raised on the 1188 * second to last round; errorRaised() gives the error status 1189 * of the last round. 1190 */ 1191 if (messager.errorRaised() 1192 || werror && round.warningCount() > 0 && round.errorCount() > 0) 1193 errorStatus = true; 1194 1195 Set<JavaFileObject> newSourceFiles = 1196 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()); 1197 roots = cleanTrees(round.roots); 1198 1199 JavaCompiler compiler = round.finalCompiler(); 1200 1201 if (newSourceFiles.size() > 0) 1202 roots = roots.appendList(compiler.parseFiles(newSourceFiles)); 1203 1204 errorStatus = errorStatus || (compiler.errorCount() > 0); 1205 1206 // Free resources 1207 this.close(); 1208 1209 if (!taskListener.isEmpty()) 1210 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING)); 1211 1212 if (errorStatus) { 1213 if (compiler.errorCount() == 0) 1214 compiler.log.nerrors++; 1215 return compiler; 1216 } 1217 1218 compiler.enterTreesIfNeeded(roots); 1219 1220 return compiler; 1221 } 1222 1223 private void warnIfUnmatchedOptions() { 1224 if (!unmatchedProcessorOptions.isEmpty()) { 1225 log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString()); 1226 } 1227 } 1228 1229 /** 1230 * Free resources related to annotation processing. 1231 */ 1232 public void close() { 1233 filer.close(); 1234 if (discoveredProcs != null) // Make calling close idempotent 1235 discoveredProcs.close(); 1236 discoveredProcs = null; 1237 } 1238 1239 private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) { 1240 List<ClassSymbol> classes = List.nil(); 1241 for (JCCompilationUnit unit : units) { 1242 for (JCTree node : unit.defs) { 1243 if (node.hasTag(JCTree.Tag.CLASSDEF)) { 1244 ClassSymbol sym = ((JCClassDecl) node).sym; 1245 Assert.checkNonNull(sym); 1246 classes = classes.prepend(sym); 1247 } 1248 } 1249 } 1250 return classes.reverse(); 1251 } 1252 1253 private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) { 1254 List<ClassSymbol> classes = List.nil(); 1255 for (ClassSymbol sym : syms) { 1256 if (!isPkgInfo(sym)) { 1257 classes = classes.prepend(sym); 1258 } 1259 } 1260 return classes.reverse(); 1261 } 1262 1263 private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) { 1264 List<PackageSymbol> packages = List.nil(); 1265 for (JCCompilationUnit unit : units) { 1266 if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) { 1267 packages = packages.prepend(unit.packge); 1268 } 1269 } 1270 return packages.reverse(); 1271 } 1272 1273 private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) { 1274 List<PackageSymbol> packages = List.nil(); 1275 for (ClassSymbol sym : syms) { 1276 if (isPkgInfo(sym)) { 1277 packages = packages.prepend((PackageSymbol) sym.owner); 1278 } 1279 } 1280 return packages.reverse(); 1281 } 1282 1283 // avoid unchecked warning from use of varargs 1284 private static <T> List<T> join(List<T> list1, List<T> list2) { 1285 return list1.appendList(list2); 1286 } 1287 1288 private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) { 1289 return fo.isNameCompatible("package-info", kind); 1290 } 1291 1292 private boolean isPkgInfo(ClassSymbol sym) { 1293 return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym); 1294 } 1295 1296 /* 1297 * Called retroactively to determine if a class loader was required, 1298 * after we have failed to create one. 1299 */ 1300 private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) { 1301 if (procNames != null) 1302 return true; 1303 1304 URL[] urls = new URL[1]; 1305 for(File pathElement : workingpath) { 1306 try { 1307 urls[0] = pathElement.toURI().toURL(); 1308 if (ServiceProxy.hasService(Processor.class, urls)) 1309 return true; 1310 } catch (MalformedURLException ex) { 1311 throw new AssertionError(ex); 1312 } 1313 catch (ServiceProxy.ServiceConfigurationError e) { 1314 log.error("proc.bad.config.file", e.getLocalizedMessage()); 1315 return true; 1316 } 1317 } 1318 1319 return false; 1320 } 1321 1322 private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) { 1323 for (T node : nodes) 1324 treeCleaner.scan(node); 1325 return nodes; 1326 } 1327 1328 private static final TreeScanner treeCleaner = new TreeScanner() { 1329 public void scan(JCTree node) { 1330 super.scan(node); 1331 if (node != null) 1332 node.type = null; 1333 } 1334 public void visitTopLevel(JCCompilationUnit node) { 1335 node.packge = null; 1336 super.visitTopLevel(node); 1337 } 1338 public void visitClassDef(JCClassDecl node) { 1339 node.sym = null; 1340 super.visitClassDef(node); 1341 } 1342 public void visitMethodDef(JCMethodDecl node) { 1343 node.sym = null; 1344 super.visitMethodDef(node); 1345 } 1346 public void visitVarDef(JCVariableDecl node) { 1347 node.sym = null; 1348 super.visitVarDef(node); 1349 } 1350 public void visitNewClass(JCNewClass node) { 1351 node.constructor = null; 1352 super.visitNewClass(node); 1353 } 1354 public void visitAssignop(JCAssignOp node) { 1355 node.operator = null; 1356 super.visitAssignop(node); 1357 } 1358 public void visitUnary(JCUnary node) { 1359 node.operator = null; 1360 super.visitUnary(node); 1361 } 1362 public void visitBinary(JCBinary node) { 1363 node.operator = null; 1364 super.visitBinary(node); 1365 } 1366 public void visitSelect(JCFieldAccess node) { 1367 node.sym = null; 1368 super.visitSelect(node); 1369 } 1370 public void visitIdent(JCIdent node) { 1371 node.sym = null; 1372 super.visitIdent(node); 1373 } 1374 public void visitAnnotation(JCAnnotation node) { 1375 node.attribute = null; 1376 super.visitAnnotation(node); 1377 } 1378 }; 1379 1380 1381 private boolean moreToDo() { 1382 return filer.newFiles(); 1383 } 1384 1385 /** 1386 * {@inheritdoc} 1387 * 1388 * Command line options suitable for presenting to annotation 1389 * processors. 1390 * {@literal "-Afoo=bar"} should be {@literal "-Afoo" => "bar"}. 1391 */ 1392 public Map<String,String> getOptions() { 1393 return processorOptions; 1394 } 1395 1396 public Messager getMessager() { 1397 return messager; 1398 } 1399 1400 public Filer getFiler() { 1401 return filer; 1402 } 1403 1404 public JavacElements getElementUtils() { 1405 return elementUtils; 1406 } 1407 1408 public JavacTypes getTypeUtils() { 1409 return typeUtils; 1410 } 1411 1412 public SourceVersion getSourceVersion() { 1413 return Source.toSourceVersion(source); 1414 } 1415 1416 public Locale getLocale() { 1417 return messages.getCurrentLocale(); 1418 } 1419 1420 public Set<Symbol.PackageSymbol> getSpecifiedPackages() { 1421 return specifiedPackages; 1422 } 1423 1424 private static final Pattern allMatches = Pattern.compile(".*"); 1425 public static final Pattern noMatches = Pattern.compile("(\\P{all})+"); 1426 1427 /** 1428 * Convert import-style string for supported annotations into a 1429 * regex matching that string. If the string is a valid 1430 * import-style string, return a regex that won't match anything. 1431 */ 1432 private static Pattern importStringToPattern(String s, Processor p, Log log) { 1433 if (isValidImportString(s)) { 1434 return validImportStringToPattern(s); 1435 } else { 1436 log.warning("proc.malformed.supported.string", s, p.getClass().getName()); 1437 return noMatches; // won't match any valid identifier 1438 } 1439 } 1440 1441 /** 1442 * Return true if the argument string is a valid import-style 1443 * string specifying claimed annotations; return false otherwise. 1444 */ 1445 public static boolean isValidImportString(String s) { 1446 if (s.equals("*")) 1447 return true; 1448 1449 boolean valid = true; 1450 String t = s; 1451 int index = t.indexOf('*'); 1452 1453 if (index != -1) { 1454 // '*' must be last character... 1455 if (index == t.length() -1) { 1456 // ... any and preceding character must be '.' 1457 if ( index-1 >= 0 ) { 1458 valid = t.charAt(index-1) == '.'; 1459 // Strip off ".*$" for identifier checks 1460 t = t.substring(0, t.length()-2); 1461 } 1462 } else 1463 return false; 1464 } 1465 1466 // Verify string is off the form (javaId \.)+ or javaId 1467 if (valid) { 1468 String[] javaIds = t.split("\\.", t.length()+2); 1469 for(String javaId: javaIds) 1470 valid &= SourceVersion.isIdentifier(javaId); 1471 } 1472 return valid; 1473 } 1474 1475 public static Pattern validImportStringToPattern(String s) { 1476 if (s.equals("*")) { 1477 return allMatches; 1478 } else { 1479 String s_prime = s.replace(".", "\\."); 1480 1481 if (s_prime.endsWith("*")) { 1482 s_prime = s_prime.substring(0, s_prime.length() - 1) + ".+"; 1483 } 1484 1485 return Pattern.compile(s_prime); 1486 } 1487 } 1488 1489 /** 1490 * For internal use only. This method may be removed without warning. 1491 */ 1492 public Context getContext() { 1493 return context; 1494 } 1495 1496 /** 1497 * For internal use only. This method may be removed without warning. 1498 */ 1499 public ClassLoader getProcessorClassLoader() { 1500 return processorClassLoader; 1501 } 1502 1503 public String toString() { 1504 return "javac ProcessingEnvironment"; 1505 } 1506 1507 public static boolean isValidOptionName(String optionName) { 1508 for(String s : optionName.split("\\.", -1)) { 1509 if (!SourceVersion.isIdentifier(s)) 1510 return false; 1511 } 1512 return true; 1513 } 1514 }