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