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