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