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