1 /* 2 * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package com.sun.tools.javac.processing; 27 28 import java.io.Closeable; 29 import java.io.IOException; 30 import java.io.PrintWriter; 31 import java.io.StringWriter; 32 import java.lang.reflect.Method; 33 import java.net.MalformedURLException; 34 import java.net.URL; 35 import java.nio.file.Path; 36 import java.util.*; 37 import java.util.Map.Entry; 38 import java.util.function.Predicate; 39 import java.util.regex.*; 40 41 import javax.annotation.processing.*; 42 import javax.lang.model.SourceVersion; 43 import javax.lang.model.element.*; 44 import javax.lang.model.util.*; 45 import javax.tools.JavaFileManager; 46 import javax.tools.JavaFileObject; 47 import javax.tools.JavaFileObject.Kind; 48 49 import static javax.tools.StandardLocation.*; 50 51 import com.sun.source.util.TaskEvent; 52 import com.sun.tools.javac.api.MultiTaskListener; 53 import com.sun.tools.javac.code.*; 54 import com.sun.tools.javac.code.DeferredCompletionFailureHandler.Handler; 55 import com.sun.tools.javac.code.Scope.WriteableScope; 56 import com.sun.tools.javac.code.Source.Feature; 57 import com.sun.tools.javac.code.Symbol.*; 58 import com.sun.tools.javac.code.Type.ClassType; 59 import com.sun.tools.javac.code.Types; 60 import com.sun.tools.javac.comp.AttrContext; 61 import com.sun.tools.javac.comp.Check; 62 import com.sun.tools.javac.comp.Enter; 63 import com.sun.tools.javac.comp.Env; 64 import com.sun.tools.javac.comp.Modules; 65 import com.sun.tools.javac.file.JavacFileManager; 66 import com.sun.tools.javac.main.JavaCompiler; 67 import com.sun.tools.javac.main.Option; 68 import com.sun.tools.javac.model.JavacElements; 69 import com.sun.tools.javac.model.JavacTypes; 70 import com.sun.tools.javac.platform.PlatformDescription; 71 import com.sun.tools.javac.platform.PlatformDescription.PluginInfo; 72 import com.sun.tools.javac.resources.CompilerProperties.Errors; 73 import com.sun.tools.javac.resources.CompilerProperties.Warnings; 74 import com.sun.tools.javac.tree.*; 75 import com.sun.tools.javac.tree.JCTree.*; 76 import com.sun.tools.javac.util.Abort; 77 import com.sun.tools.javac.util.Assert; 78 import com.sun.tools.javac.util.ClientCodeException; 79 import com.sun.tools.javac.util.Context; 80 import com.sun.tools.javac.util.Convert; 81 import com.sun.tools.javac.util.DefinedBy; 82 import com.sun.tools.javac.util.DefinedBy.Api; 83 import com.sun.tools.javac.util.Iterators; 84 import com.sun.tools.javac.util.JCDiagnostic; 85 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; 86 import com.sun.tools.javac.util.JavacMessages; 87 import com.sun.tools.javac.util.List; 88 import com.sun.tools.javac.util.Log; 89 import com.sun.tools.javac.util.MatchingUtils; 90 import com.sun.tools.javac.util.ModuleHelper; 91 import com.sun.tools.javac.util.Name; 92 import com.sun.tools.javac.util.Names; 93 import com.sun.tools.javac.util.Options; 94 95 import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING; 96 import static com.sun.tools.javac.code.Kinds.Kind.*; 97 import com.sun.tools.javac.comp.Annotate; 98 import static com.sun.tools.javac.comp.CompileStates.CompileState; 99 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*; 100 101 /** 102 * Objects of this class hold and manage the state needed to support 103 * annotation processing. 104 * 105 * <p><b>This is NOT part of any supported API. 106 * If you write code that depends on this, you do so at your own risk. 107 * This code and its internal interfaces are subject to change or 108 * deletion without notice.</b> 109 */ 110 public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable { 111 private final Options options; 112 113 private final boolean printProcessorInfo; 114 private final boolean printRounds; 115 private final boolean verbose; 116 private final boolean lint; 117 private final boolean fatalErrors; 118 private final boolean werror; 119 private final boolean showResolveErrors; 120 121 private final JavacFiler filer; 122 private final JavacMessager messager; 123 private final JavacElements elementUtils; 124 private final JavacTypes typeUtils; 125 private final JavaCompiler compiler; 126 private final Modules modules; 127 private final Types types; 128 private final Annotate annotate; 129 130 /** 131 * Holds relevant state history of which processors have been 132 * used. 133 */ 134 private DiscoveredProcessors discoveredProcs; 135 136 /** 137 * Map of processor-specific options. 138 */ 139 private final Map<String, String> processorOptions; 140 141 /** 142 */ 143 private final Set<String> unmatchedProcessorOptions; 144 145 /** 146 * Annotations implicitly processed and claimed by javac. 147 */ 148 private final Set<String> platformAnnotations; 149 150 /** 151 * Set of packages given on command line. 152 */ 153 private Set<PackageSymbol> specifiedPackages = Collections.emptySet(); 154 155 /** The log to be used for error reporting. 156 */ 157 final Log log; 158 159 /** Diagnostic factory. 160 */ 161 JCDiagnostic.Factory diags; 162 163 /** 164 * Source level of the compile. 165 */ 166 Source source; 167 168 private ClassLoader processorClassLoader; 169 private ServiceLoader<Processor> serviceLoader; 170 private SecurityException processorLoaderException; 171 172 private final JavaFileManager fileManager; 173 174 /** 175 * JavacMessages object used for localization 176 */ 177 private JavacMessages messages; 178 179 private MultiTaskListener taskListener; 180 private final Symtab symtab; 181 private final DeferredCompletionFailureHandler dcfh; 182 private final Names names; 183 private final Enter enter; 184 private final Completer initialCompleter; 185 private final Check chk; 186 187 private final Context context; 188 189 /** 190 * Support for preview language features. 191 */ 192 private final Preview preview; 193 194 /** Get the JavacProcessingEnvironment instance for this context. */ 195 public static JavacProcessingEnvironment instance(Context context) { 196 JavacProcessingEnvironment instance = context.get(JavacProcessingEnvironment.class); 197 if (instance == null) 198 instance = new JavacProcessingEnvironment(context); 199 return instance; 200 } 201 202 @SuppressWarnings("this-escape") 203 protected JavacProcessingEnvironment(Context context) { 204 this.context = context; 205 context.put(JavacProcessingEnvironment.class, this); 206 log = Log.instance(context); 207 source = Source.instance(context); 208 diags = JCDiagnostic.Factory.instance(context); 209 options = Options.instance(context); 210 printProcessorInfo = options.isSet(Option.XPRINTPROCESSORINFO); 211 printRounds = options.isSet(Option.XPRINTROUNDS); 212 verbose = options.isSet(Option.VERBOSE); 213 lint = Lint.instance(context).isEnabled(PROCESSING); 214 compiler = JavaCompiler.instance(context); 215 if (options.isSet(Option.PROC, "only") || options.isSet(Option.XPRINT)) { 216 compiler.shouldStopPolicyIfNoError = CompileState.PROCESS; 217 } 218 fatalErrors = options.isSet("fatalEnterError"); 219 showResolveErrors = options.isSet("showResolveErrors"); 220 werror = options.isSet(Option.WERROR); 221 fileManager = context.get(JavaFileManager.class); 222 platformAnnotations = initPlatformAnnotations(); 223 224 // Initialize services before any processors are initialized 225 // in case processors use them. 226 filer = new JavacFiler(context); 227 messager = new JavacMessager(context, this); 228 elementUtils = JavacElements.instance(context); 229 typeUtils = JavacTypes.instance(context); 230 modules = Modules.instance(context); 231 types = Types.instance(context); 232 annotate = Annotate.instance(context); 233 processorOptions = initProcessorOptions(); 234 unmatchedProcessorOptions = initUnmatchedProcessorOptions(); 235 messages = JavacMessages.instance(context); 236 taskListener = MultiTaskListener.instance(context); 237 symtab = Symtab.instance(context); 238 dcfh = DeferredCompletionFailureHandler.instance(context); 239 names = Names.instance(context); 240 enter = Enter.instance(context); 241 initialCompleter = ClassFinder.instance(context).getCompleter(); 242 chk = Check.instance(context); 243 preview = Preview.instance(context); 244 initProcessorLoader(); 245 } 246 247 public void setProcessors(Iterable<? extends Processor> processors) { 248 Assert.checkNull(discoveredProcs); 249 initProcessorIterator(processors); 250 } 251 252 private Set<String> initPlatformAnnotations() { 253 final String module_prefix = 254 Feature.MODULES.allowedInSource(source) ? "java.base/" : ""; 255 return Set.of(module_prefix + "java.lang.Deprecated", 256 module_prefix + "java.lang.FunctionalInterface", 257 module_prefix + "java.lang.Override", 258 module_prefix + "java.lang.SafeVarargs", 259 module_prefix + "java.lang.SuppressWarnings", 260 261 module_prefix + "java.lang.annotation.Documented", 262 module_prefix + "java.lang.annotation.Inherited", 263 module_prefix + "java.lang.annotation.Native", 264 module_prefix + "java.lang.annotation.Repeatable", 265 module_prefix + "java.lang.annotation.Retention", 266 module_prefix + "java.lang.annotation.Target", 267 268 module_prefix + "java.io.Serial"); 269 } 270 271 private void initProcessorLoader() { 272 try { 273 if (fileManager.hasLocation(ANNOTATION_PROCESSOR_MODULE_PATH)) { 274 try { 275 serviceLoader = fileManager.getServiceLoader(ANNOTATION_PROCESSOR_MODULE_PATH, Processor.class); 276 } catch (IOException e) { 277 throw new Abort(e); 278 } 279 } else { 280 // If processorpath is not explicitly set, use the classpath. 281 processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH) 282 ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH) 283 : fileManager.getClassLoader(CLASS_PATH); 284 285 if (options.isSet("accessInternalAPI")) 286 ModuleHelper.addExports(getClass().getModule(), processorClassLoader.getUnnamedModule()); 287 288 if (processorClassLoader != null && processorClassLoader instanceof Closeable closeable) { 289 compiler.closeables = compiler.closeables.prepend(closeable); 290 } 291 } 292 } catch (SecurityException e) { 293 processorLoaderException = e; 294 } 295 } 296 297 private void initProcessorIterator(Iterable<? extends Processor> processors) { 298 Iterator<? extends Processor> processorIterator; 299 300 if (options.isSet(Option.XPRINT)) { 301 try { 302 processorIterator = List.of(new PrintingProcessor()).iterator(); 303 } catch (Throwable t) { 304 throw new AssertionError("Problem instantiating PrintingProcessor.", t); 305 } 306 } else if (processors != null) { 307 processorIterator = processors.iterator(); 308 } else { 309 if (processorLoaderException == null) { 310 /* 311 * If the "-processor" option is used, search the appropriate 312 * path for the named class. Otherwise, use a service 313 * provider mechanism to create the processor iterator. 314 * 315 * Note: if an explicit processor path is not set, 316 * only the class path and _not_ the module path are 317 * searched for processors. 318 */ 319 String processorNames = options.get(Option.PROCESSOR); 320 if (fileManager.hasLocation(ANNOTATION_PROCESSOR_MODULE_PATH)) { 321 processorIterator = (processorNames == null) ? 322 new ServiceIterator(serviceLoader, log) : 323 new NameServiceIterator(serviceLoader, log, processorNames); 324 } else if (processorNames != null) { 325 processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log); 326 } else { 327 processorIterator = new ServiceIterator(processorClassLoader, log); 328 } 329 } else { 330 /* 331 * A security exception will occur if we can't create a classloader. 332 * Ignore the exception if, with hindsight, we didn't need it anyway 333 * (i.e. no processor was specified either explicitly, or implicitly, 334 * in service configuration file.) Otherwise, we cannot continue. 335 */ 336 processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader", 337 processorLoaderException); 338 } 339 } 340 PlatformDescription platformProvider = context.get(PlatformDescription.class); 341 java.util.List<Processor> platformProcessors = Collections.emptyList(); 342 if (platformProvider != null) { 343 platformProcessors = platformProvider.getAnnotationProcessors() 344 .stream() 345 .map(PluginInfo::getPlugin) 346 .toList(); 347 } 348 List<Iterator<? extends Processor>> iterators = List.of(processorIterator, 349 platformProcessors.iterator()); 350 Iterator<? extends Processor> compoundIterator = 351 Iterators.createCompoundIterator(iterators, i -> i); 352 discoveredProcs = new DiscoveredProcessors(compoundIterator); 353 } 354 355 public <S> ServiceLoader<S> getServiceLoader(Class<S> service) { 356 if (fileManager.hasLocation(ANNOTATION_PROCESSOR_MODULE_PATH)) { 357 try { 358 return fileManager.getServiceLoader(ANNOTATION_PROCESSOR_MODULE_PATH, service); 359 } catch (IOException e) { 360 throw new Abort(e); 361 } 362 } else { 363 return ServiceLoader.load(service, getProcessorClassLoader()); 364 } 365 } 366 367 /** 368 * Returns an empty processor iterator if no processors are on the 369 * relevant path, otherwise if processors are present, logs an 370 * error. Called when a service loader is unavailable for some 371 * reason, either because a service loader class cannot be found 372 * or because a security policy prevents class loaders from being 373 * created. 374 * 375 * @param key The resource key to use to log an error message 376 * @param e If non-null, pass this exception to Abort 377 */ 378 private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) { 379 if (fileManager instanceof JavacFileManager standardFileManager) { 380 Iterable<? extends Path> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH) 381 ? standardFileManager.getLocationAsPaths(ANNOTATION_PROCESSOR_PATH) 382 : standardFileManager.getLocationAsPaths(CLASS_PATH); 383 384 if (needClassLoader(options.get(Option.PROCESSOR), workingPath) ) 385 handleException(key, e); 386 387 } else { 388 handleException(key, e); 389 } 390 391 return Collections.emptyIterator(); 392 } 393 394 /** 395 * Handle a security exception thrown during initializing the 396 * Processor iterator. 397 */ 398 private void handleException(String key, Exception e) { 399 if (e != null) { 400 log.error(key, e.getLocalizedMessage()); 401 throw new Abort(e); 402 } else { 403 log.error(key); 404 throw new Abort(); 405 } 406 } 407 408 /** 409 * Use a service loader appropriate for the platform to provide an 410 * iterator over annotations processors; fails if a loader is 411 * needed but unavailable. 412 */ 413 private class ServiceIterator implements Iterator<Processor> { 414 Iterator<Processor> iterator; 415 Log log; 416 ServiceLoader<Processor> loader; 417 418 ServiceIterator(ClassLoader classLoader, Log log) { 419 this.log = log; 420 try { 421 try { 422 loader = ServiceLoader.load(Processor.class, classLoader); 423 this.iterator = loader.iterator(); 424 } catch (Exception e) { 425 // Fail softly if a loader is not actually needed. 426 this.iterator = handleServiceLoaderUnavailability("proc.no.service", null); 427 } 428 } catch (Throwable t) { 429 log.error(Errors.ProcServiceProblem); 430 throw new Abort(t); 431 } 432 } 433 434 ServiceIterator(ServiceLoader<Processor> loader, Log log) { 435 this.log = log; 436 this.loader = loader; 437 this.iterator = loader.iterator(); 438 } 439 440 @Override 441 public boolean hasNext() { 442 try { 443 return internalHasNext(); 444 } catch(ServiceConfigurationError sce) { 445 log.error(Errors.ProcBadConfigFile(sce.getLocalizedMessage())); 446 throw new Abort(sce); 447 } catch (UnsupportedClassVersionError ucve) { 448 log.error(Errors.ProcCantLoadClass(ucve.getLocalizedMessage())); 449 throw new Abort(ucve); 450 } catch (ClassFormatError cfe) { 451 log.error(Errors.ProcCantLoadClass(cfe.getLocalizedMessage())); 452 throw new Abort(cfe); 453 } catch (Throwable t) { 454 log.error(Errors.ProcBadConfigFile(t.getLocalizedMessage())); 455 throw new Abort(t); 456 } 457 } 458 459 boolean internalHasNext() { 460 return iterator.hasNext(); 461 } 462 463 @Override 464 public Processor next() { 465 try { 466 return internalNext(); 467 } catch (ServiceConfigurationError sce) { 468 log.error(Errors.ProcBadConfigFile(sce.getLocalizedMessage())); 469 throw new Abort(sce); 470 } catch (Throwable t) { 471 log.error(Errors.ProcBadConfigFile(t.getLocalizedMessage())); 472 throw new Abort(t); 473 } 474 } 475 476 Processor internalNext() { 477 return iterator.next(); 478 } 479 480 @Override 481 public void remove() { 482 throw new UnsupportedOperationException(); 483 } 484 485 public void close() { 486 if (loader != null) { 487 try { 488 loader.reload(); 489 } catch(Exception e) { 490 // Ignore problems during a call to reload. 491 } 492 } 493 } 494 } 495 496 private class NameServiceIterator extends ServiceIterator { 497 private Map<String, Processor> namedProcessorsMap = new HashMap<>(); 498 private Iterator<String> processorNames = null; 499 private Processor nextProc = null; 500 501 public NameServiceIterator(ServiceLoader<Processor> loader, Log log, String theNames) { 502 super(loader, log); 503 this.processorNames = Arrays.asList(theNames.split(",")).iterator(); 504 } 505 506 @Override 507 boolean internalHasNext() { 508 if (nextProc != null) { 509 return true; 510 } 511 if (!processorNames.hasNext()) { 512 namedProcessorsMap = null; 513 return false; 514 } 515 String processorName = processorNames.next(); 516 Processor theProcessor = namedProcessorsMap.get(processorName); 517 if (theProcessor != null) { 518 namedProcessorsMap.remove(processorName); 519 nextProc = theProcessor; 520 return true; 521 } else { 522 while (iterator.hasNext()) { 523 theProcessor = iterator.next(); 524 String name = theProcessor.getClass().getName(); 525 if (name.equals(processorName)) { 526 nextProc = theProcessor; 527 return true; 528 } else { 529 namedProcessorsMap.put(name, theProcessor); 530 } 531 } 532 log.error(Errors.ProcProcessorNotFound(processorName)); 533 return false; 534 } 535 } 536 537 @Override 538 Processor internalNext() { 539 if (hasNext()) { 540 Processor p = nextProc; 541 nextProc = null; 542 return p; 543 } else { 544 throw new NoSuchElementException(); 545 } 546 } 547 } 548 549 private static class NameProcessIterator implements Iterator<Processor> { 550 Processor nextProc = null; 551 Iterator<String> names; 552 ClassLoader processorCL; 553 Log log; 554 555 NameProcessIterator(String names, ClassLoader processorCL, Log log) { 556 this.names = Arrays.asList(names.split(",")).iterator(); 557 this.processorCL = processorCL; 558 this.log = log; 559 } 560 561 public boolean hasNext() { 562 if (nextProc != null) 563 return true; 564 else { 565 if (!names.hasNext()) { 566 return false; 567 } else { 568 Processor processor = getNextProcessor(names.next()); 569 if (processor == null) { 570 return false; 571 } else { 572 nextProc = processor; 573 return true; 574 } 575 } 576 } 577 } 578 579 private Processor getNextProcessor(String processorName) { 580 try { 581 try { 582 Class<?> processorClass = processorCL.loadClass(processorName); 583 ensureReadable(processorClass); 584 return (Processor) processorClass.getConstructor().newInstance(); 585 } catch (ClassNotFoundException cnfe) { 586 log.error(Errors.ProcProcessorNotFound(processorName)); 587 return null; 588 } catch (ClassCastException cce) { 589 log.error(Errors.ProcProcessorWrongType(processorName)); 590 return null; 591 } catch (Exception e ) { 592 log.error(Errors.ProcProcessorCantInstantiate(processorName)); 593 return null; 594 } 595 } catch (ClientCodeException e) { 596 throw e; 597 } catch (Throwable t) { 598 throw new AnnotationProcessingError(t); 599 } 600 } 601 602 public Processor next() { 603 if (hasNext()) { 604 Processor p = nextProc; 605 nextProc = null; 606 return p; 607 } else 608 throw new NoSuchElementException(); 609 } 610 611 public void remove () { 612 throw new UnsupportedOperationException(); 613 } 614 615 /** 616 * Ensures that the module of the given class is readable to this 617 * module. 618 */ 619 private void ensureReadable(Class<?> targetClass) { 620 try { 621 Method getModuleMethod = Class.class.getMethod("getModule"); 622 Object thisModule = getModuleMethod.invoke(this.getClass()); 623 Object targetModule = getModuleMethod.invoke(targetClass); 624 625 Class<?> moduleClass = getModuleMethod.getReturnType(); 626 Method addReadsMethod = moduleClass.getMethod("addReads", moduleClass); 627 addReadsMethod.invoke(thisModule, targetModule); 628 } catch (NoSuchMethodException e) { 629 // ignore 630 } catch (Exception e) { 631 throw new InternalError(e); 632 } 633 } 634 } 635 636 public boolean atLeastOneProcessor() { 637 return discoveredProcs.iterator().hasNext(); 638 } 639 640 private Map<String, String> initProcessorOptions() { 641 Set<String> keySet = options.keySet(); 642 Map<String, String> tempOptions = new LinkedHashMap<>(); 643 644 for(String key : keySet) { 645 if (key.startsWith("-A") && key.length() > 2) { 646 int sepIndex = key.indexOf('='); 647 String candidateKey = null; 648 String candidateValue = null; 649 650 if (sepIndex == -1) 651 candidateKey = key.substring(2); 652 else if (sepIndex >= 3) { 653 candidateKey = key.substring(2, sepIndex); 654 candidateValue = (sepIndex < key.length()-1)? 655 key.substring(sepIndex+1) : null; 656 } 657 tempOptions.put(candidateKey, candidateValue); 658 } 659 } 660 661 PlatformDescription platformProvider = context.get(PlatformDescription.class); 662 663 if (platformProvider != null) { 664 for (PluginInfo<Processor> ap : platformProvider.getAnnotationProcessors()) { 665 tempOptions.putAll(ap.getOptions()); 666 } 667 } 668 669 return Collections.unmodifiableMap(tempOptions); 670 } 671 672 private Set<String> initUnmatchedProcessorOptions() { 673 Set<String> unmatchedProcessorOptions = new HashSet<>(); 674 unmatchedProcessorOptions.addAll(processorOptions.keySet()); 675 return unmatchedProcessorOptions; 676 } 677 678 /** 679 * State about how a processor has been used by the tool. If a 680 * processor has been used on a prior round, its process method is 681 * called on all subsequent rounds, perhaps with an empty set of 682 * annotations to process. The {@code annotationSupported} method 683 * caches the supported annotation information from the first (and 684 * only) getSupportedAnnotationTypes call to the processor. 685 */ 686 static class ProcessorState { 687 public Processor processor; 688 public boolean contributed; 689 private Set<String> supportedAnnotationStrings; // Used for warning generation 690 private Set<Pattern> supportedAnnotationPatterns; 691 private Set<String> supportedOptionNames; 692 693 ProcessorState(Processor p, Log log, Source source, DeferredCompletionFailureHandler dcfh, 694 boolean allowModules, ProcessingEnvironment env, boolean lint) { 695 processor = p; 696 contributed = false; 697 698 Handler prevDeferredHandler = dcfh.setHandler(dcfh.userCodeHandler); 699 try { 700 processor.init(env); 701 702 checkSourceVersionCompatibility(source, log); 703 704 705 // Check for direct duplicates in the strings of 706 // supported annotation types. Do not check for 707 // duplicates that would result after stripping of 708 // module prefixes. 709 supportedAnnotationStrings = new LinkedHashSet<>(); 710 supportedAnnotationPatterns = new LinkedHashSet<>(); 711 for (String annotationPattern : processor.getSupportedAnnotationTypes()) { 712 boolean patternAdded = supportedAnnotationStrings.add(annotationPattern); 713 714 supportedAnnotationPatterns. 715 add(importStringToPattern(allowModules, annotationPattern, 716 processor, log, lint)); 717 if (lint && !patternAdded) { 718 log.warning(Warnings.ProcDuplicateSupportedAnnotation(annotationPattern, 719 p.getClass().getName())); 720 } 721 } 722 723 // If a processor supports "*", that matches 724 // everything and other entries are redundant. With 725 // more work, it could be checked that the supported 726 // annotation types were otherwise non-overlapping 727 // with each other in other cases, for example "foo.*" 728 // and "foo.bar.*". 729 if (lint && 730 supportedAnnotationPatterns.contains(MatchingUtils.validImportStringToPattern("*")) && 731 supportedAnnotationPatterns.size() > 1) { 732 log.warning(Warnings.ProcRedundantTypesWithWildcard(p.getClass().getName())); 733 } 734 735 supportedOptionNames = new LinkedHashSet<>(); 736 for (String optionName : processor.getSupportedOptions() ) { 737 if (checkOptionName(optionName, log)) { 738 boolean optionAdded = supportedOptionNames.add(optionName); 739 if (lint && !optionAdded) { 740 log.warning(Warnings.ProcDuplicateOptionName(optionName, 741 p.getClass().getName())); 742 } 743 } 744 } 745 746 } catch (ClientCodeException e) { 747 throw e; 748 } catch (Throwable t) { 749 throw new AnnotationProcessingError(t); 750 } finally { 751 dcfh.setHandler(prevDeferredHandler); 752 } 753 } 754 755 /** 756 * Checks whether or not a processor's source version is 757 * compatible with the compilation source version. The 758 * processor's source version needs to be greater than or 759 * equal to the source version of the compile. 760 */ 761 private void checkSourceVersionCompatibility(Source source, Log log) { 762 SourceVersion procSourceVersion = processor.getSupportedSourceVersion(); 763 if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 ) { 764 log.warning(Warnings.ProcProcessorIncompatibleSourceVersion(procSourceVersion, 765 processor.getClass().getName(), 766 source.name)); 767 } 768 } 769 770 private boolean checkOptionName(String optionName, Log log) { 771 boolean valid = isValidOptionName(optionName); 772 if (!valid) 773 log.error(Errors.ProcProcessorBadOptionName(optionName, 774 processor.getClass().getName())); 775 return valid; 776 } 777 778 public boolean annotationSupported(String annotationName) { 779 for(Pattern p: supportedAnnotationPatterns) { 780 if (p.matcher(annotationName).matches()) 781 return true; 782 } 783 return false; 784 } 785 786 /** 787 * Remove options that are matched by this processor. 788 */ 789 public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) { 790 unmatchedProcessorOptions.removeAll(supportedOptionNames); 791 } 792 } 793 794 // TODO: These two classes can probably be rewritten better... 795 /** 796 * This class holds information about the processors that have 797 * been discovered so far as well as the means to discover more, if 798 * necessary. A single iterator should be used per round of 799 * annotation processing. The iterator first visits already 800 * discovered processors then fails over to the service provider 801 * mechanism if additional queries are made. 802 */ 803 class DiscoveredProcessors implements Iterable<ProcessorState> { 804 805 class ProcessorStateIterator implements Iterator<ProcessorState> { 806 DiscoveredProcessors psi; 807 Iterator<ProcessorState> innerIter; 808 boolean onProcIterator; 809 810 ProcessorStateIterator(DiscoveredProcessors psi) { 811 this.psi = psi; 812 this.innerIter = psi.procStateList.iterator(); 813 this.onProcIterator = false; 814 } 815 816 public ProcessorState next() { 817 if (!onProcIterator) { 818 if (innerIter.hasNext()) 819 return innerIter.next(); 820 else 821 onProcIterator = true; 822 } 823 824 if (psi.processorIterator.hasNext()) { 825 ProcessorState ps = new ProcessorState(psi.processorIterator.next(), 826 log, source, dcfh, 827 Feature.MODULES.allowedInSource(source), 828 JavacProcessingEnvironment.this, 829 lint); 830 psi.procStateList.add(ps); 831 return ps; 832 } else 833 throw new NoSuchElementException(); 834 } 835 836 public boolean hasNext() { 837 if (onProcIterator) 838 return psi.processorIterator.hasNext(); 839 else 840 return innerIter.hasNext() || psi.processorIterator.hasNext(); 841 } 842 843 public void remove () { 844 throw new UnsupportedOperationException(); 845 } 846 847 /** 848 * Run all remaining processors on the procStateList that 849 * have not already run this round with an empty set of 850 * annotations. 851 */ 852 public void runContributingProcs(RoundEnvironment re) { 853 if (!onProcIterator) { 854 Set<TypeElement> emptyTypeElements = Collections.emptySet(); 855 while(innerIter.hasNext()) { 856 ProcessorState ps = innerIter.next(); 857 if (ps.contributed) 858 callProcessor(ps.processor, emptyTypeElements, re); 859 } 860 } 861 } 862 } 863 864 Iterator<? extends Processor> processorIterator; 865 ArrayList<ProcessorState> procStateList; 866 867 public ProcessorStateIterator iterator() { 868 return new ProcessorStateIterator(this); 869 } 870 871 DiscoveredProcessors(Iterator<? extends Processor> processorIterator) { 872 this.processorIterator = processorIterator; 873 this.procStateList = new ArrayList<>(); 874 } 875 876 /** 877 * Free jar files, etc. if using a service loader. 878 */ 879 public void close() { 880 if (processorIterator != null && 881 processorIterator instanceof ServiceIterator serviceIterator) { 882 serviceIterator.close(); 883 } 884 } 885 } 886 887 private void discoverAndRunProcs(Set<TypeElement> annotationsPresent, 888 List<ClassSymbol> topLevelClasses, 889 List<PackageSymbol> packageInfoFiles, 890 List<ModuleSymbol> moduleInfoFiles) { 891 Map<String, TypeElement> unmatchedAnnotations = new HashMap<>(annotationsPresent.size()); 892 893 for(TypeElement a : annotationsPresent) { 894 ModuleElement mod = elementUtils.getModuleOf(a); 895 String moduleSpec = Feature.MODULES.allowedInSource(source) && mod != null ? mod.getQualifiedName() + "/" : ""; 896 unmatchedAnnotations.put(moduleSpec + a.getQualifiedName().toString(), 897 a); 898 } 899 900 // Give "*" processors a chance to match 901 if (unmatchedAnnotations.size() == 0) 902 unmatchedAnnotations.put("", null); 903 904 DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator(); 905 // TODO: Create proper argument values; need past round 906 // information to fill in this constructor. Note that the 1 907 // st round of processing could be the last round if there 908 // were parse errors on the initial source files; however, we 909 // are not doing processing in that case. 910 911 Set<Element> rootElements = new LinkedHashSet<>(); 912 rootElements.addAll(topLevelClasses); 913 rootElements.addAll(packageInfoFiles); 914 rootElements.addAll(moduleInfoFiles); 915 rootElements = Collections.unmodifiableSet(rootElements); 916 917 RoundEnvironment renv = new JavacRoundEnvironment(false, 918 false, 919 rootElements, 920 JavacProcessingEnvironment.this); 921 922 while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) { 923 ProcessorState ps = psi.next(); 924 Set<String> matchedNames = new HashSet<>(); 925 Set<TypeElement> typeElements = new LinkedHashSet<>(); 926 927 for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) { 928 String unmatchedAnnotationName = entry.getKey(); 929 if (ps.annotationSupported(unmatchedAnnotationName) ) { 930 matchedNames.add(unmatchedAnnotationName); 931 TypeElement te = entry.getValue(); 932 if (te != null) 933 typeElements.add(te); 934 } 935 } 936 937 if (matchedNames.size() > 0 || ps.contributed) { 938 boolean processingResult = callProcessor(ps.processor, typeElements, renv); 939 ps.contributed = true; 940 ps.removeSupportedOptions(unmatchedProcessorOptions); 941 942 if (printProcessorInfo || verbose) { 943 log.printLines("x.print.processor.info", 944 ps.processor.getClass().getName(), 945 matchedNames.toString(), 946 processingResult); 947 } 948 949 if (processingResult) { 950 unmatchedAnnotations.keySet().removeAll(matchedNames); 951 } 952 953 } 954 } 955 unmatchedAnnotations.remove(""); 956 957 if (lint && unmatchedAnnotations.size() > 0) { 958 // Remove annotations processed by javac 959 unmatchedAnnotations.keySet().removeAll(platformAnnotations); 960 if (unmatchedAnnotations.size() > 0) { 961 log.warning(Warnings.ProcAnnotationsWithoutProcessors(unmatchedAnnotations.keySet())); 962 } 963 } 964 965 // Run contributing processors that haven't run yet 966 psi.runContributingProcs(renv); 967 } 968 969 /** 970 * Computes the set of annotations on the symbol in question. 971 * Leave class public for external testing purposes. 972 */ 973 public static class ComputeAnnotationSet extends 974 ElementScanner14<Set<TypeElement>, Set<TypeElement>> { 975 final Elements elements; 976 977 public ComputeAnnotationSet(Elements elements) { 978 super(); 979 this.elements = elements; 980 } 981 982 @Override @DefinedBy(Api.LANGUAGE_MODEL) 983 public Set<TypeElement> visitPackage(PackageElement e, Set<TypeElement> p) { 984 // Don't scan enclosed elements of a package 985 return p; 986 } 987 988 @Override @DefinedBy(Api.LANGUAGE_MODEL) 989 public Set<TypeElement> visitType(TypeElement e, Set<TypeElement> p) { 990 // Type parameters are not considered to be enclosed by a type 991 scan(e.getTypeParameters(), p); 992 return super.visitType(e, p); 993 } 994 995 @Override @DefinedBy(Api.LANGUAGE_MODEL) 996 public Set<TypeElement> visitExecutable(ExecutableElement e, Set<TypeElement> p) { 997 // Type parameters are not considered to be enclosed by an executable 998 scan(e.getTypeParameters(), p); 999 return super.visitExecutable(e, p); 1000 } 1001 1002 void addAnnotations(Element e, Set<TypeElement> p) { 1003 for (AnnotationMirror annotationMirror : 1004 elements.getAllAnnotationMirrors(e) ) { 1005 Element e2 = annotationMirror.getAnnotationType().asElement(); 1006 p.add((TypeElement) e2); 1007 } 1008 } 1009 1010 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1011 public Set<TypeElement> scan(Element e, Set<TypeElement> p) { 1012 addAnnotations(e, p); 1013 return super.scan(e, p); 1014 } 1015 } 1016 1017 private boolean callProcessor(Processor proc, 1018 Set<? extends TypeElement> tes, 1019 RoundEnvironment renv) { 1020 Handler prevDeferredHandler = dcfh.setHandler(dcfh.userCodeHandler); 1021 try { 1022 return proc.process(tes, renv); 1023 } catch (ClassFinder.BadClassFile ex) { 1024 log.error(Errors.ProcCantAccess1(ex.sym, ex.getDetailValue())); 1025 return false; 1026 } catch (CompletionFailure ex) { 1027 StringWriter out = new StringWriter(); 1028 ex.printStackTrace(new PrintWriter(out)); 1029 log.error(Errors.ProcCantAccess(ex.sym, ex.getDetailValue(), out.toString())); 1030 return false; 1031 } catch (ClientCodeException e) { 1032 throw e; 1033 } catch (Throwable t) { 1034 throw new AnnotationProcessingError(t); 1035 } finally { 1036 dcfh.setHandler(prevDeferredHandler); 1037 } 1038 } 1039 1040 /** 1041 * Helper object for a single round of annotation processing. 1042 */ 1043 class Round { 1044 /** The round number. */ 1045 final int number; 1046 /** The diagnostic handler for the round. */ 1047 final Log.DeferredDiagnosticHandler deferredDiagnosticHandler; 1048 1049 /** The ASTs to be compiled. */ 1050 List<JCCompilationUnit> roots; 1051 /** The trees that need to be cleaned - includes roots and implicitly parsed trees. */ 1052 Set<JCCompilationUnit> treesToClean; 1053 /** The classes to be compiler that have were generated. */ 1054 Map<ModuleSymbol, Map<String, JavaFileObject>> genClassFiles; 1055 1056 /** The set of annotations to be processed this round. */ 1057 Set<TypeElement> annotationsPresent; 1058 /** The set of top level classes to be processed this round. */ 1059 List<ClassSymbol> topLevelClasses; 1060 /** The set of package-info files to be processed this round. */ 1061 List<PackageSymbol> packageInfoFiles; 1062 /** The set of module-info files to be processed this round. */ 1063 List<ModuleSymbol> moduleInfoFiles; 1064 1065 /** Create a round (common code). */ 1066 private Round(int number, Set<JCCompilationUnit> treesToClean, 1067 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) { 1068 this.number = number; 1069 1070 if (number == 1) { 1071 Assert.checkNonNull(deferredDiagnosticHandler); 1072 this.deferredDiagnosticHandler = deferredDiagnosticHandler; 1073 } else { 1074 this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log); 1075 compiler.setDeferredDiagnosticHandler(this.deferredDiagnosticHandler); 1076 } 1077 1078 // the following will be populated as needed 1079 topLevelClasses = List.nil(); 1080 packageInfoFiles = List.nil(); 1081 moduleInfoFiles = List.nil(); 1082 this.treesToClean = treesToClean; 1083 } 1084 1085 /** Create the first round. */ 1086 Round(List<JCCompilationUnit> roots, 1087 List<ClassSymbol> classSymbols, 1088 Set<JCCompilationUnit> treesToClean, 1089 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) { 1090 this(1, treesToClean, deferredDiagnosticHandler); 1091 this.roots = roots; 1092 genClassFiles = new HashMap<>(); 1093 1094 // The reverse() in the following line is to maintain behavioural 1095 // compatibility with the previous revision of the code. Strictly speaking, 1096 // it should not be necessary, but a javah golden file test fails without it. 1097 topLevelClasses = 1098 getTopLevelClasses(roots).prependList(classSymbols.reverse()); 1099 1100 packageInfoFiles = getPackageInfoFiles(roots); 1101 1102 moduleInfoFiles = getModuleInfoFiles(roots); 1103 1104 findAnnotationsPresent(); 1105 } 1106 1107 /** Create a new round. */ 1108 private Round(Round prev, 1109 Set<JavaFileObject> newSourceFiles, Map<ModuleSymbol, Map<String,JavaFileObject>> newClassFiles) { 1110 this(prev.number+1, prev.treesToClean, null); 1111 prev.newRound(); 1112 this.genClassFiles = prev.genClassFiles; 1113 1114 //parse the generated files even despite errors reported so far, to eliminate 1115 //recoverable errors related to the type declared in the generated files: 1116 List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles, true); 1117 roots = prev.roots.appendList(parsedFiles); 1118 1119 // Check for errors after parsing 1120 if (unrecoverableError()) { 1121 compiler.initModules(List.nil()); 1122 return; 1123 } 1124 1125 roots = compiler.initModules(roots); 1126 1127 enterClassFiles(genClassFiles); 1128 List<ClassSymbol> newClasses = enterClassFiles(newClassFiles); 1129 for (Entry<ModuleSymbol, Map<String, JavaFileObject>> moduleAndClassFiles : newClassFiles.entrySet()) { 1130 genClassFiles.computeIfAbsent(moduleAndClassFiles.getKey(), m -> new LinkedHashMap<>()).putAll(moduleAndClassFiles.getValue()); 1131 } 1132 enterTrees(roots); 1133 1134 if (unrecoverableError()) 1135 return; 1136 1137 topLevelClasses = join( 1138 getTopLevelClasses(parsedFiles), 1139 getTopLevelClassesFromClasses(newClasses)); 1140 1141 packageInfoFiles = join( 1142 getPackageInfoFiles(parsedFiles), 1143 getPackageInfoFilesFromClasses(newClasses)); 1144 1145 moduleInfoFiles = List.nil(); //module-info cannot be generated 1146 1147 findAnnotationsPresent(); 1148 } 1149 1150 /** Create the next round to be used. */ 1151 Round next(Set<JavaFileObject> newSourceFiles, Map<ModuleSymbol, Map<String, JavaFileObject>> newClassFiles) { 1152 return new Round(this, newSourceFiles, newClassFiles); 1153 } 1154 1155 /** Prepare the compiler for the final compilation. */ 1156 void finalCompiler() { 1157 newRound(); 1158 } 1159 1160 /** Return the number of errors found so far in this round. 1161 * This may include unrecoverable errors, such as parse errors, 1162 * and transient errors, such as missing symbols. */ 1163 int errorCount() { 1164 return compiler.errorCount(); 1165 } 1166 1167 /** Return the number of warnings found so far in this round. */ 1168 int warningCount() { 1169 return compiler.warningCount(); 1170 } 1171 1172 /** Return whether or not an unrecoverable error has occurred. */ 1173 boolean unrecoverableError() { 1174 if (messager.errorRaised()) 1175 return true; 1176 1177 for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) { 1178 switch (d.getKind()) { 1179 case WARNING: 1180 if (werror) 1181 return true; 1182 break; 1183 1184 case ERROR: 1185 if (fatalErrors || !d.isFlagSet(RECOVERABLE)) 1186 return true; 1187 break; 1188 } 1189 } 1190 1191 return false; 1192 } 1193 1194 /** Find the set of annotations present in the set of top level 1195 * classes and package info files to be processed this round. */ 1196 void findAnnotationsPresent() { 1197 ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils); 1198 // Use annotation processing to compute the set of annotations present 1199 annotationsPresent = new LinkedHashSet<>(); 1200 for (ClassSymbol classSym : topLevelClasses) 1201 annotationComputer.scan(classSym, annotationsPresent); 1202 for (PackageSymbol pkgSym : packageInfoFiles) 1203 annotationComputer.scan(pkgSym, annotationsPresent); 1204 for (ModuleSymbol mdlSym : moduleInfoFiles) 1205 annotationComputer.scan(mdlSym, annotationsPresent); 1206 } 1207 1208 /** Enter a set of generated class files. */ 1209 private List<ClassSymbol> enterClassFiles(Map<ModuleSymbol, Map<String, JavaFileObject>> modulesAndClassFiles) { 1210 List<ClassSymbol> list = List.nil(); 1211 1212 for (Entry<ModuleSymbol, Map<String, JavaFileObject>> moduleAndClassFiles : modulesAndClassFiles.entrySet()) { 1213 for (Map.Entry<String,JavaFileObject> entry : moduleAndClassFiles.getValue().entrySet()) { 1214 Name name = names.fromString(entry.getKey()); 1215 JavaFileObject file = entry.getValue(); 1216 if (file.getKind() != JavaFileObject.Kind.CLASS) 1217 throw new AssertionError(file); 1218 ClassSymbol cs; 1219 if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) { 1220 Name packageName = Convert.packagePart(name); 1221 PackageSymbol p = symtab.enterPackage(moduleAndClassFiles.getKey(), packageName); 1222 if (p.package_info == null) 1223 p.package_info = symtab.enterClass(moduleAndClassFiles.getKey(), Convert.shortName(name), p); 1224 cs = p.package_info; 1225 cs.reset(); 1226 if (cs.classfile == null) 1227 cs.classfile = file; 1228 cs.completer = initialCompleter; 1229 } else { 1230 cs = symtab.enterClass(moduleAndClassFiles.getKey(), name); 1231 cs.reset(); 1232 cs.classfile = file; 1233 cs.completer = initialCompleter; 1234 if (cs.owner.kind == PCK) { 1235 cs.owner.members().enter(cs); //XXX - OverwriteBetweenCompilations; syms.getClass is not sufficient anymore 1236 } 1237 } 1238 list = list.prepend(cs); 1239 } 1240 } 1241 return list.reverse(); 1242 } 1243 1244 /** Enter a set of syntax trees. */ 1245 private void enterTrees(List<JCCompilationUnit> roots) { 1246 compiler.enterTrees(roots); 1247 } 1248 1249 /** Run a processing round. */ 1250 void run(boolean lastRound, boolean errorStatus) { 1251 printRoundInfo(lastRound); 1252 1253 if (!taskListener.isEmpty()) 1254 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND)); 1255 1256 try { 1257 if (lastRound) { 1258 filer.setLastRound(true); 1259 Set<Element> emptyRootElements = Collections.emptySet(); // immutable 1260 RoundEnvironment renv = new JavacRoundEnvironment(true, 1261 errorStatus, 1262 emptyRootElements, 1263 JavacProcessingEnvironment.this); 1264 discoveredProcs.iterator().runContributingProcs(renv); 1265 } else { 1266 discoverAndRunProcs(annotationsPresent, topLevelClasses, packageInfoFiles, moduleInfoFiles); 1267 } 1268 } catch (Throwable t) { 1269 // we're specifically expecting Abort here, but if any Throwable 1270 // comes by, we should flush all deferred diagnostics, rather than 1271 // drop them on the ground. 1272 compiler.reportDeferredDiagnosticAndClearHandler(); 1273 throw t; 1274 } finally { 1275 if (!taskListener.isEmpty()) 1276 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND)); 1277 } 1278 } 1279 1280 void showDiagnostics(boolean showAll) { 1281 deferredDiagnosticHandler.reportDeferredDiagnostics(showAll ? ACCEPT_ALL 1282 : ACCEPT_NON_RECOVERABLE); 1283 log.popDiagnosticHandler(deferredDiagnosticHandler); 1284 compiler.setDeferredDiagnosticHandler(null); 1285 } 1286 //where: 1287 private final Predicate<JCDiagnostic> ACCEPT_NON_RECOVERABLE = 1288 d -> d.getKind() != JCDiagnostic.Kind.ERROR || 1289 !d.isFlagSet(DiagnosticFlag.RECOVERABLE) || 1290 d.isFlagSet(DiagnosticFlag.API); 1291 private final Predicate<JCDiagnostic> ACCEPT_ALL = d -> true; 1292 1293 /** Print info about this round. */ 1294 private void printRoundInfo(boolean lastRound) { 1295 if (printRounds || verbose) { 1296 List<ClassSymbol> tlc = lastRound ? List.nil() : topLevelClasses; 1297 Set<TypeElement> ap = lastRound ? Collections.emptySet() : annotationsPresent; 1298 log.printLines("x.print.rounds", 1299 number, 1300 "{" + tlc.toString(", ") + "}", 1301 ap, 1302 lastRound); 1303 } 1304 } 1305 1306 /** Prepare for new round of annotation processing. Cleans trees, resets symbols, and 1307 * asks selected services to prepare to a new round of annotation processing. 1308 */ 1309 private void newRound() { 1310 //ensure treesToClean contains all trees, including implicitly parsed ones 1311 for (Env<AttrContext> env : enter.getEnvs()) { 1312 treesToClean.add(env.toplevel); 1313 } 1314 for (JCCompilationUnit node : treesToClean) { 1315 treeCleaner.scan(node); 1316 } 1317 chk.newRound(); 1318 enter.newRound(); 1319 filer.newRound(); 1320 messager.newRound(); 1321 compiler.newRound(); 1322 modules.newRound(); 1323 types.newRound(); 1324 annotate.newRound(); 1325 elementUtils.newRound(); 1326 1327 boolean foundError = false; 1328 1329 for (ClassSymbol cs : symtab.getAllClasses()) { 1330 if (cs.kind == ERR) { 1331 foundError = true; 1332 break; 1333 } 1334 } 1335 1336 if (foundError) { 1337 for (ClassSymbol cs : symtab.getAllClasses()) { 1338 if (cs.classfile != null || cs.kind == ERR) { 1339 Kinds.Kind symKind = cs.kind; 1340 cs.reset(); 1341 if (symKind == ERR) { 1342 cs.type = new ClassType(cs.type.getEnclosingType(), null, cs); 1343 } 1344 if (cs.isCompleted()) { 1345 cs.completer = initialCompleter; 1346 } 1347 } 1348 } 1349 } 1350 } 1351 } 1352 1353 1354 // TODO: internal catch clauses?; catch and rethrow an annotation 1355 // processing error 1356 public boolean doProcessing(List<JCCompilationUnit> roots, 1357 List<ClassSymbol> classSymbols, 1358 Iterable<? extends PackageSymbol> pckSymbols, 1359 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) { 1360 final Set<JCCompilationUnit> treesToClean = 1361 Collections.newSetFromMap(new IdentityHashMap<JCCompilationUnit, Boolean>()); 1362 1363 //fill already attributed implicit trees: 1364 for (Env<AttrContext> env : enter.getEnvs()) { 1365 treesToClean.add(env.toplevel); 1366 } 1367 1368 Set<PackageSymbol> specifiedPackages = new LinkedHashSet<>(); 1369 for (PackageSymbol psym : pckSymbols) 1370 specifiedPackages.add(psym); 1371 this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages); 1372 1373 Round round = new Round(roots, classSymbols, treesToClean, deferredDiagnosticHandler); 1374 1375 boolean errorStatus; 1376 boolean moreToDo; 1377 do { 1378 // Run processors for round n 1379 round.run(false, false); 1380 1381 // Processors for round n have run to completion. 1382 // Check for errors and whether there is more work to do. 1383 errorStatus = round.unrecoverableError(); 1384 moreToDo = moreToDo(); 1385 1386 round.showDiagnostics(showResolveErrors); 1387 1388 // Set up next round. 1389 // Copy mutable collections returned from filer. 1390 round = round.next( 1391 new LinkedHashSet<>(filer.getGeneratedSourceFileObjects()), 1392 new LinkedHashMap<>(filer.getGeneratedClasses())); 1393 1394 // Check for errors during setup. 1395 if (round.unrecoverableError()) 1396 errorStatus = true; 1397 1398 } while (moreToDo && !errorStatus); 1399 1400 // run last round 1401 round.run(true, errorStatus); 1402 round.showDiagnostics(true); 1403 1404 filer.warnIfUnclosedFiles(); 1405 warnIfUnmatchedOptions(); 1406 1407 /* 1408 * If an annotation processor raises an error in a round, 1409 * that round runs to completion and one last round occurs. 1410 * The last round may also occur because no more source or 1411 * class files have been generated. Therefore, if an error 1412 * was raised on either of the last *two* rounds, the compile 1413 * should exit with a nonzero exit code. The current value of 1414 * errorStatus holds whether or not an error was raised on the 1415 * second to last round; errorRaised() gives the error status 1416 * of the last round. 1417 */ 1418 if (messager.errorRaised() 1419 || werror && round.warningCount() > 0 && round.errorCount() > 0) 1420 errorStatus = true; 1421 1422 Set<JavaFileObject> newSourceFiles = 1423 new LinkedHashSet<>(filer.getGeneratedSourceFileObjects()); 1424 roots = round.roots; 1425 1426 errorStatus = errorStatus || (compiler.errorCount() > 0); 1427 1428 1429 if (newSourceFiles.size() > 0) 1430 roots = roots.appendList(compiler.parseFiles(newSourceFiles)); 1431 1432 errorStatus = errorStatus || (compiler.errorCount() > 0); 1433 1434 if (errorStatus && compiler.errorCount() == 0) { 1435 compiler.log.nerrors++; 1436 } 1437 1438 if (compiler.continueAfterProcessAnnotations()) { 1439 round.finalCompiler(); 1440 compiler.enterTrees(compiler.initModules(roots)); 1441 } else { 1442 compiler.todo.clear(); 1443 } 1444 1445 // Free resources 1446 this.close(); 1447 1448 if (!taskListener.isEmpty()) 1449 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING)); 1450 1451 return true; 1452 } 1453 1454 private void warnIfUnmatchedOptions() { 1455 if (!unmatchedProcessorOptions.isEmpty()) { 1456 log.warning(Warnings.ProcUnmatchedProcessorOptions(unmatchedProcessorOptions.toString())); 1457 } 1458 } 1459 1460 /** 1461 * Free resources related to annotation processing. 1462 */ 1463 public void close() { 1464 filer.close(); 1465 if (discoveredProcs != null) // Make calling close idempotent 1466 discoveredProcs.close(); 1467 discoveredProcs = null; 1468 } 1469 1470 private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) { 1471 List<ClassSymbol> classes = List.nil(); 1472 for (JCCompilationUnit unit : units) { 1473 for (JCTree node : unit.defs) { 1474 if (node.hasTag(JCTree.Tag.CLASSDEF)) { 1475 ClassSymbol sym = ((JCClassDecl) node).sym; 1476 Assert.checkNonNull(sym); 1477 classes = classes.prepend(sym); 1478 } 1479 } 1480 } 1481 return classes.reverse(); 1482 } 1483 1484 private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) { 1485 List<ClassSymbol> classes = List.nil(); 1486 for (ClassSymbol sym : syms) { 1487 if (!isPkgInfo(sym)) { 1488 classes = classes.prepend(sym); 1489 } 1490 } 1491 return classes.reverse(); 1492 } 1493 1494 private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) { 1495 List<PackageSymbol> packages = List.nil(); 1496 for (JCCompilationUnit unit : units) { 1497 if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) { 1498 packages = packages.prepend(unit.packge); 1499 } 1500 } 1501 return packages.reverse(); 1502 } 1503 1504 private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) { 1505 List<PackageSymbol> packages = List.nil(); 1506 for (ClassSymbol sym : syms) { 1507 if (isPkgInfo(sym)) { 1508 packages = packages.prepend((PackageSymbol) sym.owner); 1509 } 1510 } 1511 return packages.reverse(); 1512 } 1513 1514 private List<ModuleSymbol> getModuleInfoFiles(List<? extends JCCompilationUnit> units) { 1515 List<ModuleSymbol> modules = List.nil(); 1516 for (JCCompilationUnit unit : units) { 1517 if (isModuleInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE) && unit.defs.nonEmpty()) { 1518 for (JCTree tree : unit.defs) { 1519 if (tree.hasTag(Tag.IMPORT)) { 1520 continue; 1521 } 1522 else if (tree.hasTag(Tag.MODULEDEF)) { 1523 modules = modules.prepend(unit.modle); 1524 break; 1525 } 1526 else { 1527 break; 1528 } 1529 } 1530 } 1531 } 1532 return modules.reverse(); 1533 } 1534 1535 // avoid unchecked warning from use of varargs 1536 private static <T> List<T> join(List<T> list1, List<T> list2) { 1537 return list1.appendList(list2); 1538 } 1539 1540 private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) { 1541 return fo.isNameCompatible("package-info", kind); 1542 } 1543 1544 private boolean isPkgInfo(ClassSymbol sym) { 1545 return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym); 1546 } 1547 1548 private boolean isModuleInfo(JavaFileObject fo, JavaFileObject.Kind kind) { 1549 return fo.isNameCompatible("module-info", kind); 1550 } 1551 1552 /* 1553 * Called retroactively to determine if a class loader was required, 1554 * after we have failed to create one. 1555 */ 1556 private boolean needClassLoader(String procNames, Iterable<? extends Path> workingpath) { 1557 if (procNames != null) 1558 return true; 1559 1560 URL[] urls = new URL[1]; 1561 for(Path pathElement : workingpath) { 1562 try { 1563 urls[0] = pathElement.toUri().toURL(); 1564 if (ServiceProxy.hasService(Processor.class, urls)) 1565 return true; 1566 } catch (MalformedURLException ex) { 1567 throw new AssertionError(ex); 1568 } 1569 catch (ServiceProxy.ServiceConfigurationError e) { 1570 log.error(Errors.ProcBadConfigFile(e.getLocalizedMessage())); 1571 return true; 1572 } 1573 } 1574 1575 return false; 1576 } 1577 1578 class ImplicitCompleter implements Completer { 1579 1580 private final JCCompilationUnit topLevel; 1581 1582 public ImplicitCompleter(JCCompilationUnit topLevel) { 1583 this.topLevel = topLevel; 1584 } 1585 1586 @Override public void complete(Symbol sym) throws CompletionFailure { 1587 compiler.readSourceFile(topLevel, (ClassSymbol) sym); 1588 } 1589 } 1590 1591 private final TreeScanner treeCleaner = new TreeScanner() { 1592 public void scan(JCTree node) { 1593 super.scan(node); 1594 if (node != null) 1595 node.type = null; 1596 } 1597 JCCompilationUnit topLevel; 1598 public void visitTopLevel(JCCompilationUnit node) { 1599 if (node.packge != null) { 1600 if (isPkgInfo(node.sourcefile, Kind.SOURCE)) { 1601 node.packge.package_info.reset(); 1602 } 1603 node.packge.reset(); 1604 } 1605 if (isModuleInfo(node.sourcefile, Kind.SOURCE)) { 1606 node.modle.reset(); 1607 node.modle.completer = sym -> modules.enter(List.of(node), node.modle.module_info); 1608 node.modle.module_info.reset(); 1609 node.modle.module_info.members_field = WriteableScope.create(node.modle.module_info); 1610 } 1611 node.packge = null; 1612 topLevel = node; 1613 try { 1614 super.visitTopLevel(node); 1615 } finally { 1616 topLevel = null; 1617 } 1618 } 1619 public void visitClassDef(JCClassDecl node) { 1620 super.visitClassDef(node); 1621 // remove generated constructor that may have been added during attribution: 1622 List<JCTree> beforeConstructor = List.nil(); 1623 List<JCTree> defs = node.defs; 1624 while (defs.nonEmpty() && !defs.head.hasTag(Tag.METHODDEF)) { 1625 beforeConstructor = beforeConstructor.prepend(defs.head); 1626 defs = defs.tail; 1627 } 1628 if (defs.nonEmpty() && 1629 (((JCMethodDecl) defs.head).mods.flags & Flags.GENERATEDCONSTR) != 0) { 1630 defs = defs.tail; 1631 while (beforeConstructor.nonEmpty()) { 1632 defs = defs.prepend(beforeConstructor.head); 1633 beforeConstructor = beforeConstructor.tail; 1634 } 1635 node.defs = defs; 1636 } 1637 if (node.sym != null) { 1638 node.sym.completer = new ImplicitCompleter(topLevel); 1639 List<? extends RecordComponent> recordComponents = node.sym.getRecordComponents(); 1640 for (RecordComponent rc : recordComponents) { 1641 List<JCAnnotation> originalAnnos = rc.getOriginalAnnos(); 1642 originalAnnos.forEach(a -> visitAnnotation(a)); 1643 } 1644 // we should empty the list of permitted subclasses for next round 1645 node.sym.clearPermittedSubclasses(); 1646 } 1647 node.sym = null; 1648 } 1649 public void visitMethodDef(JCMethodDecl node) { 1650 // remove super constructor call that may have been added during attribution: 1651 if (TreeInfo.isConstructor(node) && node.sym != null && node.sym.owner.isEnum() && 1652 node.body != null && node.body.stats.nonEmpty() && TreeInfo.isSuperCall(node.body.stats.head) && 1653 node.body.stats.head.pos == node.body.pos) { 1654 node.body.stats = node.body.stats.tail; 1655 } 1656 node.sym = null; 1657 super.visitMethodDef(node); 1658 } 1659 public void visitVarDef(JCVariableDecl node) { 1660 node.sym = null; 1661 super.visitVarDef(node); 1662 } 1663 public void visitNewClass(JCNewClass node) { 1664 node.constructor = null; 1665 super.visitNewClass(node); 1666 } 1667 public void visitAssignop(JCAssignOp node) { 1668 node.operator = null; 1669 super.visitAssignop(node); 1670 } 1671 public void visitUnary(JCUnary node) { 1672 node.operator = null; 1673 super.visitUnary(node); 1674 } 1675 public void visitBinary(JCBinary node) { 1676 node.operator = null; 1677 super.visitBinary(node); 1678 } 1679 public void visitSelect(JCFieldAccess node) { 1680 node.sym = null; 1681 super.visitSelect(node); 1682 } 1683 public void visitIdent(JCIdent node) { 1684 node.sym = null; 1685 super.visitIdent(node); 1686 } 1687 public void visitAnnotation(JCAnnotation node) { 1688 node.attribute = null; 1689 super.visitAnnotation(node); 1690 } 1691 }; 1692 1693 1694 private boolean moreToDo() { 1695 return filer.newFiles(); 1696 } 1697 1698 /** 1699 * {@inheritDoc} 1700 * 1701 * Command line options suitable for presenting to annotation 1702 * processors. 1703 * {@literal "-Afoo=bar"} should be {@literal "-Afoo" => "bar"}. 1704 */ 1705 @DefinedBy(Api.ANNOTATION_PROCESSING) 1706 public Map<String,String> getOptions() { 1707 return processorOptions; 1708 } 1709 1710 @DefinedBy(Api.ANNOTATION_PROCESSING) 1711 public Messager getMessager() { 1712 return messager; 1713 } 1714 1715 @DefinedBy(Api.ANNOTATION_PROCESSING) 1716 public JavacFiler getFiler() { 1717 return filer; 1718 } 1719 1720 @DefinedBy(Api.ANNOTATION_PROCESSING) 1721 public JavacElements getElementUtils() { 1722 return elementUtils; 1723 } 1724 1725 @DefinedBy(Api.ANNOTATION_PROCESSING) 1726 public JavacTypes getTypeUtils() { 1727 return typeUtils; 1728 } 1729 1730 @DefinedBy(Api.ANNOTATION_PROCESSING) 1731 public SourceVersion getSourceVersion() { 1732 return Source.toSourceVersion(source); 1733 } 1734 1735 @DefinedBy(Api.ANNOTATION_PROCESSING) 1736 public Locale getLocale() { 1737 return messages.getCurrentLocale(); 1738 } 1739 1740 @DefinedBy(Api.ANNOTATION_PROCESSING) 1741 public boolean isPreviewEnabled() { 1742 return preview.isEnabled(); 1743 } 1744 1745 public Set<Symbol.PackageSymbol> getSpecifiedPackages() { 1746 return specifiedPackages; 1747 } 1748 1749 public static final Pattern noMatches = Pattern.compile("(\\P{all})+"); 1750 1751 /** 1752 * Convert import-style string for supported annotations into a 1753 * regex matching that string. If the string is not a valid 1754 * import-style string, return a regex that won't match anything. 1755 */ 1756 private static Pattern importStringToPattern(boolean allowModules, String s, Processor p, Log log, boolean lint) { 1757 String module; 1758 String pkg; 1759 int slash = s.indexOf('/'); 1760 if (slash == (-1)) { 1761 if (s.equals("*")) { 1762 return MatchingUtils.validImportStringToPattern(s); 1763 } 1764 module = allowModules ? ".*/" : ""; 1765 pkg = s; 1766 } else { 1767 String moduleName = s.substring(0, slash); 1768 if (!SourceVersion.isName(moduleName)) { 1769 return warnAndNoMatches(s, p, log, lint); 1770 } 1771 module = Pattern.quote(moduleName + "/"); 1772 // And warn if module is specified if modules aren't supported, conditional on -Xlint:proc? 1773 pkg = s.substring(slash + 1); 1774 } 1775 if (MatchingUtils.isValidImportString(pkg)) { 1776 return Pattern.compile(module + MatchingUtils.validImportStringToPatternString(pkg)); 1777 } else { 1778 return warnAndNoMatches(s, p, log, lint); 1779 } 1780 } 1781 1782 private static Pattern warnAndNoMatches(String s, Processor p, Log log, boolean lint) { 1783 if (lint) { 1784 log.warning(Warnings.ProcMalformedSupportedString(s, p.getClass().getName())); 1785 } 1786 return noMatches; // won't match any valid identifier 1787 } 1788 1789 /** 1790 * For internal use only. This method may be removed without warning. 1791 */ 1792 public Context getContext() { 1793 return context; 1794 } 1795 1796 /** 1797 * For internal use only. This method may be removed without warning. 1798 */ 1799 public ClassLoader getProcessorClassLoader() { 1800 return processorClassLoader; 1801 } 1802 1803 public String toString() { 1804 return "javac ProcessingEnvironment"; 1805 } 1806 1807 public static boolean isValidOptionName(String optionName) { 1808 for(String s : optionName.split("\\.", -1)) { 1809 if (!SourceVersion.isIdentifier(s)) 1810 return false; 1811 } 1812 return true; 1813 } 1814 }