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