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