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