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