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