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