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