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