1 /*
   2  * Copyright (c) 1999, 2023, 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.main;
  27 
  28 import java.io.*;
  29 import java.nio.file.FileSystemNotFoundException;
  30 import java.nio.file.InvalidPathException;
  31 import java.nio.file.ReadOnlyFileSystemException;
  32 import java.util.Collection;
  33 import java.util.Collections;
  34 import java.util.HashMap;
  35 import java.util.HashSet;
  36 import java.util.LinkedHashMap;
  37 import java.util.LinkedHashSet;
  38 import java.util.Map;
  39 import java.util.MissingResourceException;
  40 import java.util.Queue;
  41 import java.util.ResourceBundle;
  42 import java.util.Set;
  43 import java.util.function.Function;
  44 
  45 import javax.annotation.processing.Processor;
  46 import javax.lang.model.SourceVersion;
  47 import javax.lang.model.element.ElementVisitor;
  48 import javax.tools.DiagnosticListener;
  49 import javax.tools.JavaFileManager;
  50 import javax.tools.JavaFileObject;
  51 import javax.tools.JavaFileObject.Kind;
  52 import javax.tools.StandardLocation;
  53 
  54 import com.sun.source.util.TaskEvent;
  55 import com.sun.tools.javac.api.MultiTaskListener;
  56 import com.sun.tools.javac.code.*;
  57 import com.sun.tools.javac.code.Lint.LintCategory;
  58 import com.sun.tools.javac.code.Source.Feature;
  59 import com.sun.tools.javac.code.Symbol.ClassSymbol;
  60 import com.sun.tools.javac.code.Symbol.CompletionFailure;
  61 import com.sun.tools.javac.code.Symbol.PackageSymbol;
  62 import com.sun.tools.javac.comp.*;
  63 import com.sun.tools.javac.comp.CompileStates.CompileState;
  64 import com.sun.tools.javac.file.JavacFileManager;
  65 import com.sun.tools.javac.jvm.*;
  66 import com.sun.tools.javac.parser.*;
  67 import com.sun.tools.javac.platform.PlatformDescription;
  68 import com.sun.tools.javac.processing.*;
  69 import com.sun.tools.javac.tree.*;
  70 import com.sun.tools.javac.tree.JCTree.JCClassDecl;
  71 import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
  72 import com.sun.tools.javac.tree.JCTree.JCExpression;
  73 import com.sun.tools.javac.tree.JCTree.JCLambda;
  74 import com.sun.tools.javac.tree.JCTree.JCMemberReference;
  75 import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
  76 import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
  77 import com.sun.tools.javac.util.*;
  78 import com.sun.tools.javac.util.Context.Key;
  79 import com.sun.tools.javac.util.DefinedBy.Api;
  80 import com.sun.tools.javac.util.JCDiagnostic.Factory;
  81 import com.sun.tools.javac.util.Log.DiagnosticHandler;
  82 import com.sun.tools.javac.util.Log.DiscardDiagnosticHandler;
  83 import com.sun.tools.javac.util.Log.WriterKind;
  84 
  85 import static com.sun.tools.javac.code.Kinds.Kind.*;
  86 
  87 import com.sun.tools.javac.code.Lint;
  88 import com.sun.tools.javac.code.Lint.LintCategory;
  89 import com.sun.tools.javac.code.Symbol.ModuleSymbol;
  90 
  91 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  92 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  93 import com.sun.tools.javac.resources.CompilerProperties.Notes;
  94 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  95 
  96 import static com.sun.tools.javac.code.TypeTag.CLASS;
  97 import static com.sun.tools.javac.main.Option.*;
  98 import com.sun.tools.javac.tree.JCTree.JCBindingPattern;
  99 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
 100 
 101 import static javax.tools.StandardLocation.CLASS_OUTPUT;
 102 import static javax.tools.StandardLocation.ANNOTATION_PROCESSOR_PATH;
 103 
 104 import com.sun.tools.javac.tree.JCTree.JCModuleDecl;
 105 import com.sun.tools.javac.tree.JCTree.JCRecordPattern;
 106 import com.sun.tools.javac.tree.JCTree.JCSwitch;
 107 import com.sun.tools.javac.tree.JCTree.JCSwitchExpression;
 108 
 109 /** This class could be the main entry point for GJC when GJC is used as a
 110  *  component in a larger software system. It provides operations to
 111  *  construct a new compiler, and to run a new compiler on a set of source
 112  *  files.
 113  *
 114  *  <p><b>This is NOT part of any supported API.
 115  *  If you write code that depends on this, you do so at your own risk.
 116  *  This code and its internal interfaces are subject to change or
 117  *  deletion without notice.</b>
 118  */
 119 public class JavaCompiler {
 120     /** The context key for the compiler. */
 121     public static final Context.Key<JavaCompiler> compilerKey = new Context.Key<>();
 122 
 123     /** Get the JavaCompiler instance for this context. */
 124     public static JavaCompiler instance(Context context) {
 125         JavaCompiler instance = context.get(compilerKey);
 126         if (instance == null)
 127             instance = new JavaCompiler(context);
 128         return instance;
 129     }
 130 
 131     /** The current version number as a string.
 132      */
 133     public static String version() {
 134         return version("release");  // mm.nn.oo[-milestone]
 135     }
 136 
 137     /** The current full version number as a string.
 138      */
 139     public static String fullVersion() {
 140         return version("full"); // mm.mm.oo[-milestone]-build
 141     }
 142 
 143     private static final String versionRBName = "com.sun.tools.javac.resources.version";
 144     private static ResourceBundle versionRB;
 145 
 146     private static String version(String key) {
 147         if (versionRB == null) {
 148             try {
 149                 versionRB = ResourceBundle.getBundle(versionRBName);
 150             } catch (MissingResourceException e) {
 151                 return Log.getLocalizedString("version.not.available");
 152             }
 153         }
 154         try {
 155             return versionRB.getString(key);
 156         }
 157         catch (MissingResourceException e) {
 158             return Log.getLocalizedString("version.not.available");
 159         }
 160     }
 161 
 162     /**
 163      * Control how the compiler's latter phases (attr, flow, desugar, generate)
 164      * are connected. Each individual file is processed by each phase in turn,
 165      * but with different compile policies, you can control the order in which
 166      * each class is processed through its next phase.
 167      *
 168      * <p>Generally speaking, the compiler will "fail fast" in the face of
 169      * errors, although not aggressively so. flow, desugar, etc become no-ops
 170      * once any errors have occurred. No attempt is currently made to determine
 171      * if it might be safe to process a class through its next phase because
 172      * it does not depend on any unrelated errors that might have occurred.
 173      */
 174     protected static enum CompilePolicy {
 175         /**
 176          * Attribute everything, then do flow analysis for everything,
 177          * then desugar everything, and only then generate output.
 178          * This means no output will be generated if there are any
 179          * errors in any classes.
 180          */
 181         SIMPLE,
 182 
 183         /**
 184          * Groups the classes for each source file together, then process
 185          * each group in a manner equivalent to the {@code SIMPLE} policy.
 186          * This means no output will be generated if there are any
 187          * errors in any of the classes in a source file.
 188          */
 189         BY_FILE,
 190 
 191         /**
 192          * Completely process each entry on the todo list in turn.
 193          * -- this is the same for 1.5.
 194          * Means output might be generated for some classes in a compilation unit
 195          * and not others.
 196          */
 197         BY_TODO;
 198 
 199         static CompilePolicy decode(String option) {
 200             if (option == null)
 201                 return DEFAULT_COMPILE_POLICY;
 202             else if (option.equals("simple"))
 203                 return SIMPLE;
 204             else if (option.equals("byfile"))
 205                 return BY_FILE;
 206             else if (option.equals("bytodo"))
 207                 return BY_TODO;
 208             else
 209                 return DEFAULT_COMPILE_POLICY;
 210         }
 211     }
 212 
 213     private static final CompilePolicy DEFAULT_COMPILE_POLICY = CompilePolicy.BY_TODO;
 214 
 215     protected static enum ImplicitSourcePolicy {
 216         /** Don't generate or process implicitly read source files. */
 217         NONE,
 218         /** Generate classes for implicitly read source files. */
 219         CLASS,
 220         /** Like CLASS, but generate warnings if annotation processing occurs */
 221         UNSET;
 222 
 223         static ImplicitSourcePolicy decode(String option) {
 224             if (option == null)
 225                 return UNSET;
 226             else if (option.equals("none"))
 227                 return NONE;
 228             else if (option.equals("class"))
 229                 return CLASS;
 230             else
 231                 return UNSET;
 232         }
 233     }
 234 
 235     /** The log to be used for error reporting.
 236      */
 237     public Log log;
 238 
 239     /** Whether or not the options lint category was initially disabled
 240      */
 241     boolean optionsCheckingInitiallyDisabled;
 242 
 243     /** Factory for creating diagnostic objects
 244      */
 245     JCDiagnostic.Factory diagFactory;
 246 
 247     /** The tree factory module.
 248      */
 249     protected TreeMaker make;
 250 
 251     /** The class finder.
 252      */
 253     protected ClassFinder finder;
 254 
 255     /** The class reader.
 256      */
 257     protected ClassReader reader;
 258 
 259     /** The class writer.
 260      */
 261     protected ClassWriter writer;
 262 
 263     /** The native header writer.
 264      */
 265     protected JNIWriter jniWriter;
 266 
 267     /** The module for the symbol table entry phases.
 268      */
 269     protected Enter enter;
 270 
 271     /** The symbol table.
 272      */
 273     protected Symtab syms;
 274 
 275     /** The language version.
 276      */
 277     protected Source source;
 278 
 279     /** The preview language version.
 280      */
 281     protected Preview preview;
 282 
 283     /** The module for code generation.
 284      */
 285     protected Gen gen;
 286 
 287     /** The name table.
 288      */
 289     protected Names names;
 290 
 291     /** The attributor.
 292      */
 293     protected Attr attr;
 294 
 295     /** The analyzer
 296      */
 297     protected Analyzer analyzer;
 298 
 299     /** The attributor.
 300      */
 301     protected Check chk;
 302 
 303     /** The flow analyzer.
 304      */
 305     protected Flow flow;
 306 
 307     /** The modules visitor
 308      */
 309     protected Modules modules;
 310 
 311     /** The module finder
 312      */
 313     protected ModuleFinder moduleFinder;
 314 
 315     /** The diagnostics factory
 316      */
 317     protected JCDiagnostic.Factory diags;
 318 
 319     protected DeferredCompletionFailureHandler dcfh;
 320 
 321     /** The type eraser.
 322      */
 323     protected TransTypes transTypes;
 324 
 325     /** The syntactic sugar desweetener.
 326      */
 327     protected Lower lower;
 328 
 329     /** The annotation annotator.
 330      */
 331     protected Annotate annotate;
 332 
 333     /** Force a completion failure on this name
 334      */
 335     protected final Name completionFailureName;
 336 
 337     /** Type utilities.
 338      */
 339     protected Types types;
 340 
 341     /** Access to file objects.
 342      */
 343     protected JavaFileManager fileManager;
 344 
 345     /** Factory for parsers.
 346      */
 347     protected ParserFactory parserFactory;
 348 
 349     /** Broadcasting listener for progress events
 350      */
 351     protected MultiTaskListener taskListener;
 352 
 353     /**
 354      * SourceCompleter that delegates to the readSourceFile method of this class.
 355      */
 356     protected final Symbol.Completer sourceCompleter =
 357             sym -> readSourceFile((ClassSymbol) sym);
 358 
 359     /**
 360      * Command line options.
 361      */
 362     protected Options options;
 363 
 364     protected Context context;
 365 
 366     /**
 367      * Flag set if any annotation processing occurred.
 368      **/
 369     protected boolean annotationProcessingOccurred;
 370 
 371     /**
 372      * Flag set if any implicit source files read.
 373      **/
 374     protected boolean implicitSourceFilesRead;
 375 
 376     private boolean enterDone;
 377 
 378     protected CompileStates compileStates;
 379 
 380     /** Construct a new compiler using a shared context.
 381      */
 382     @SuppressWarnings("this-escape")
 383     public JavaCompiler(Context context) {
 384         this.context = context;
 385         context.put(compilerKey, this);
 386 
 387         // if fileManager not already set, register the JavacFileManager to be used
 388         if (context.get(JavaFileManager.class) == null)
 389             JavacFileManager.preRegister(context);
 390 
 391         names = Names.instance(context);
 392         log = Log.instance(context);
 393         diagFactory = JCDiagnostic.Factory.instance(context);
 394         finder = ClassFinder.instance(context);
 395         reader = ClassReader.instance(context);
 396         make = TreeMaker.instance(context);
 397         writer = ClassWriter.instance(context);
 398         jniWriter = JNIWriter.instance(context);
 399         enter = Enter.instance(context);
 400         todo = Todo.instance(context);
 401 
 402         fileManager = context.get(JavaFileManager.class);
 403         parserFactory = ParserFactory.instance(context);
 404         compileStates = CompileStates.instance(context);
 405 
 406         try {
 407             // catch completion problems with predefineds
 408             syms = Symtab.instance(context);
 409         } catch (CompletionFailure ex) {
 410             // inlined Check.completionError as it is not initialized yet
 411             log.error(Errors.CantAccess(ex.sym, ex.getDetailValue()));
 412         }
 413         source = Source.instance(context);
 414         preview = Preview.instance(context);
 415         attr = Attr.instance(context);
 416         analyzer = Analyzer.instance(context);
 417         chk = Check.instance(context);
 418         gen = Gen.instance(context);
 419         flow = Flow.instance(context);
 420         transTypes = TransTypes.instance(context);
 421         lower = Lower.instance(context);
 422         annotate = Annotate.instance(context);
 423         types = Types.instance(context);
 424         taskListener = MultiTaskListener.instance(context);
 425         modules = Modules.instance(context);
 426         moduleFinder = ModuleFinder.instance(context);
 427         diags = Factory.instance(context);
 428         dcfh = DeferredCompletionFailureHandler.instance(context);
 429 
 430         finder.sourceCompleter = sourceCompleter;
 431         modules.findPackageInFile = this::findPackageInFile;
 432         moduleFinder.moduleNameFromSourceReader = this::readModuleName;
 433 
 434         options = Options.instance(context);
 435         // See if lint options checking was explicitly disabled by the
 436         // user; this is distinct from the options check being
 437         // enabled/disabled.
 438         optionsCheckingInitiallyDisabled =
 439             options.isSet(Option.XLINT_CUSTOM, "-options") ||
 440             options.isSet(Option.XLINT_CUSTOM, "none");
 441 
 442         verbose       = options.isSet(VERBOSE);
 443         sourceOutput  = options.isSet(PRINTSOURCE); // used to be -s
 444         lineDebugInfo = options.isUnset(G_CUSTOM) ||
 445                         options.isSet(G_CUSTOM, "lines");
 446         genEndPos     = options.isSet(XJCOV) ||
 447                         context.get(DiagnosticListener.class) != null;
 448         devVerbose    = options.isSet("dev");
 449         processPcks   = options.isSet("process.packages");
 450         werror        = options.isSet(WERROR);
 451 
 452         verboseCompilePolicy = options.isSet("verboseCompilePolicy");
 453 
 454         compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));
 455 
 456         implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));
 457 
 458         completionFailureName =
 459             options.isSet("failcomplete")
 460             ? names.fromString(options.get("failcomplete"))
 461             : null;
 462 
 463         shouldStopPolicyIfError =
 464             options.isSet("should-stop.at") // backwards compatible
 465             ? CompileState.valueOf(options.get("should-stop.at"))
 466             : options.isSet("should-stop.ifError")
 467             ? CompileState.valueOf(options.get("should-stop.ifError"))
 468             : CompileState.INIT;
 469         shouldStopPolicyIfNoError =
 470             options.isSet("should-stop.ifNoError")
 471             ? CompileState.valueOf(options.get("should-stop.ifNoError"))
 472             : CompileState.GENERATE;
 473 
 474         if (options.isUnset("diags.legacy"))
 475             log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
 476 
 477         PlatformDescription platformProvider = context.get(PlatformDescription.class);
 478 
 479         if (platformProvider != null)
 480             closeables = closeables.prepend(platformProvider);
 481 
 482         silentFail = new Symbol(ABSENT_TYP, 0, names.empty, Type.noType, syms.rootPackage) {
 483             @DefinedBy(Api.LANGUAGE_MODEL)
 484             public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 485                 return v.visitUnknown(this, p);
 486             }
 487             @Override
 488             public boolean exists() {
 489                 return false;
 490             }
 491         };
 492 
 493     }
 494 
 495     /* Switches:
 496      */
 497 
 498     /** Verbose output.
 499      */
 500     public boolean verbose;
 501 
 502     /** Emit plain Java source files rather than class files.
 503      */
 504     public boolean sourceOutput;
 505 
 506 
 507     /** Generate code with the LineNumberTable attribute for debugging
 508      */
 509     public boolean lineDebugInfo;
 510 
 511     /** Switch: should we store the ending positions?
 512      */
 513     public boolean genEndPos;
 514 
 515     /** Switch: should we debug ignored exceptions
 516      */
 517     protected boolean devVerbose;
 518 
 519     /** Switch: should we (annotation) process packages as well
 520      */
 521     protected boolean processPcks;
 522 
 523     /** Switch: treat warnings as errors
 524      */
 525     protected boolean werror;
 526 
 527     /** Switch: is annotation processing requested explicitly via
 528      * CompilationTask.setProcessors?
 529      */
 530     protected boolean explicitAnnotationProcessingRequested = false;
 531 
 532     /**
 533      * The policy for the order in which to perform the compilation
 534      */
 535     protected CompilePolicy compilePolicy;
 536 
 537     /**
 538      * The policy for what to do with implicitly read source files
 539      */
 540     protected ImplicitSourcePolicy implicitSourcePolicy;
 541 
 542     /**
 543      * Report activity related to compilePolicy
 544      */
 545     public boolean verboseCompilePolicy;
 546 
 547     /**
 548      * Policy of how far to continue compilation after errors have occurred.
 549      * Set this to minimum CompileState (INIT) to stop as soon as possible
 550      * after errors.
 551      */
 552     public CompileState shouldStopPolicyIfError;
 553 
 554     /**
 555      * Policy of how far to continue compilation when no errors have occurred.
 556      * Set this to maximum CompileState (GENERATE) to perform full compilation.
 557      * Set this lower to perform partial compilation, such as -proc:only.
 558      */
 559     public CompileState shouldStopPolicyIfNoError;
 560 
 561     /** A queue of all as yet unattributed classes.
 562      */
 563     public Todo todo;
 564 
 565     /** A list of items to be closed when the compilation is complete.
 566      */
 567     public List<Closeable> closeables = List.nil();
 568 
 569     /** The set of currently compiled inputfiles, needed to ensure
 570      *  we don't accidentally overwrite an input file when -s is set.
 571      *  initialized by `compile'.
 572      */
 573     protected Set<JavaFileObject> inputFiles = new HashSet<>();
 574 
 575     /** Used by the resolveBinaryNameOrIdent to say that the given type cannot be found, and that
 576      *  an error has already been produced about that.
 577      */
 578     private final Symbol silentFail;
 579 
 580     protected boolean shouldStop(CompileState cs) {
 581         CompileState shouldStopPolicy = (errorCount() > 0 || unrecoverableError())
 582             ? shouldStopPolicyIfError
 583             : shouldStopPolicyIfNoError;
 584         return cs.isAfter(shouldStopPolicy);
 585     }
 586 
 587     /** The number of errors reported so far.
 588      */
 589     public int errorCount() {
 590         if (werror && log.nerrors == 0 && log.nwarnings > 0) {
 591             log.error(Errors.WarningsAndWerror);
 592         }
 593         return log.nerrors;
 594     }
 595 
 596     protected final <T> Queue<T> stopIfError(CompileState cs, Queue<T> queue) {
 597         return shouldStop(cs) ? new ListBuffer<T>() : queue;
 598     }
 599 
 600     protected final <T> List<T> stopIfError(CompileState cs, List<T> list) {
 601         return shouldStop(cs) ? List.nil() : list;
 602     }
 603 
 604     /** The number of warnings reported so far.
 605      */
 606     public int warningCount() {
 607         return log.nwarnings;
 608     }
 609 
 610     /** Try to open input stream with given name.
 611      *  Report an error if this fails.
 612      *  @param filename   The file name of the input stream to be opened.
 613      */
 614     public CharSequence readSource(JavaFileObject filename) {
 615         try {
 616             inputFiles.add(filename);
 617             return filename.getCharContent(false);
 618         } catch (IOException e) {
 619             log.error(Errors.ErrorReadingFile(filename, JavacFileManager.getMessage(e)));
 620             return null;
 621         }
 622     }
 623 
 624     /** Parse contents of input stream.
 625      *  @param filename     The name of the file from which input stream comes.
 626      *  @param content      The characters to be parsed.
 627      */
 628     protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
 629         return parse(filename, content, false);
 630     }
 631 
 632     /** Parse contents of input stream.
 633      *  @param filename     The name of the file from which input stream comes.
 634      *  @param content      The characters to be parsed.
 635      *  @param silent       true if TaskListeners should not be notified
 636      */
 637     private JCCompilationUnit parse(JavaFileObject filename, CharSequence content, boolean silent) {
 638         long msec = now();
 639         JCCompilationUnit tree = make.TopLevel(List.nil());
 640         if (content != null) {
 641             if (verbose) {
 642                 log.printVerbose("parsing.started", filename);
 643             }
 644             if (!taskListener.isEmpty() && !silent) {
 645                 TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, filename);
 646                 taskListener.started(e);
 647                 keepComments = true;
 648                 genEndPos = true;
 649             }
 650             Parser parser = parserFactory.newParser(content, keepComments(), genEndPos,
 651                                 lineDebugInfo, filename.isNameCompatible("module-info", Kind.SOURCE));
 652             tree = parser.parseCompilationUnit();
 653             if (verbose) {
 654                 log.printVerbose("parsing.done", Long.toString(elapsed(msec)));
 655             }
 656         }
 657 
 658         tree.sourcefile = filename;
 659 
 660         if (content != null && !taskListener.isEmpty() && !silent) {
 661             TaskEvent e = new TaskEvent(TaskEvent.Kind.PARSE, tree);
 662             taskListener.finished(e);
 663         }
 664 
 665         return tree;
 666     }
 667     // where
 668         public boolean keepComments = false;
 669         protected boolean keepComments() {
 670             return keepComments || sourceOutput;
 671         }
 672 
 673 
 674     /** Parse contents of file.
 675      *  @param filename     The name of the file to be parsed.
 676      */
 677     @Deprecated
 678     public JCTree.JCCompilationUnit parse(String filename) {
 679         JavacFileManager fm = (JavacFileManager)fileManager;
 680         return parse(fm.getJavaFileObjectsFromStrings(List.of(filename)).iterator().next());
 681     }
 682 
 683     /** Parse contents of file.
 684      *  @param filename     The name of the file to be parsed.
 685      */
 686     public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
 687         JavaFileObject prev = log.useSource(filename);
 688         try {
 689             JCTree.JCCompilationUnit t = parse(filename, readSource(filename));
 690             if (t.endPositions != null)
 691                 log.setEndPosTable(filename, t.endPositions);
 692             return t;
 693         } finally {
 694             log.useSource(prev);
 695         }
 696     }
 697 
 698     /** Resolve an identifier which may be the binary name of a class or
 699      * the Java name of a class or package.
 700      * @param name      The name to resolve
 701      */
 702     public Symbol resolveBinaryNameOrIdent(String name) {
 703         ModuleSymbol msym;
 704         String typeName;
 705         int sep = name.indexOf('/');
 706         if (sep == -1) {
 707             msym = modules.getDefaultModule();
 708             typeName = name;
 709         } else if (Feature.MODULES.allowedInSource(source)) {
 710             Name modName = names.fromString(name.substring(0, sep));
 711 
 712             msym = moduleFinder.findModule(modName);
 713             typeName = name.substring(sep + 1);
 714         } else {
 715             log.error(Errors.InvalidModuleSpecifier(name));
 716             return silentFail;
 717         }
 718 
 719         return resolveBinaryNameOrIdent(msym, typeName);
 720     }
 721 
 722     /** Resolve an identifier which may be the binary name of a class or
 723      * the Java name of a class or package.
 724      * @param msym      The module in which the search should be performed
 725      * @param name      The name to resolve
 726      */
 727     public Symbol resolveBinaryNameOrIdent(ModuleSymbol msym, String name) {
 728         try {
 729             Name flatname = names.fromString(name.replace("/", "."));
 730             return finder.loadClass(msym, flatname);
 731         } catch (CompletionFailure ignore) {
 732             return resolveIdent(msym, name);
 733         }
 734     }
 735 
 736     /** Resolve an identifier.
 737      * @param msym      The module in which the search should be performed
 738      * @param name      The identifier to resolve
 739      */
 740     public Symbol resolveIdent(ModuleSymbol msym, String name) {
 741         if (name.equals(""))
 742             return syms.errSymbol;
 743         JavaFileObject prev = log.useSource(null);
 744         try {
 745             JCExpression tree = null;
 746             for (String s : name.split("\\.", -1)) {
 747                 if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
 748                     return syms.errSymbol;
 749                 tree = (tree == null) ? make.Ident(names.fromString(s))
 750                                       : make.Select(tree, names.fromString(s));
 751             }
 752             JCCompilationUnit toplevel =
 753                 make.TopLevel(List.nil());
 754             toplevel.modle = msym;
 755             toplevel.packge = msym.unnamedPackage;
 756             return attr.attribIdent(tree, toplevel);
 757         } finally {
 758             log.useSource(prev);
 759         }
 760     }
 761 
 762     /** Generate code and emit a class file for a given class
 763      *  @param env    The attribution environment of the outermost class
 764      *                containing this class.
 765      *  @param cdef   The class definition from which code is generated.
 766      */
 767     JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
 768         try {
 769             if (gen.genClass(env, cdef) && (errorCount() == 0))
 770                 return writer.writeClass(cdef.sym);
 771         } catch (ClassWriter.PoolOverflow ex) {
 772             log.error(cdef.pos(), Errors.LimitPool);
 773         } catch (ClassWriter.StringOverflow ex) {
 774             log.error(cdef.pos(),
 775                       Errors.LimitStringOverflow(ex.value.substring(0, 20)));
 776         } catch (CompletionFailure ex) {
 777             chk.completionError(cdef.pos(), ex);
 778         }
 779         return null;
 780     }
 781 
 782     /** Emit plain Java source for a class.
 783      *  @param env    The attribution environment of the outermost class
 784      *                containing this class.
 785      *  @param cdef   The class definition to be printed.
 786      */
 787     JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
 788         JavaFileObject outFile
 789            = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
 790                                                cdef.sym.flatname.toString(),
 791                                                JavaFileObject.Kind.SOURCE,
 792                                                null);
 793         if (inputFiles.contains(outFile)) {
 794             log.error(cdef.pos(), Errors.SourceCantOverwriteInputFile(outFile));
 795             return null;
 796         } else {
 797             try (BufferedWriter out = new BufferedWriter(outFile.openWriter())) {
 798                 new Pretty(out, true).printUnit(env.toplevel, cdef);
 799                 if (verbose)
 800                     log.printVerbose("wrote.file", outFile.getName());
 801             }
 802             return outFile;
 803         }
 804     }
 805 
 806     /** Compile a source file that has been accessed by the class finder.
 807      *  @param c          The class the source file of which needs to be compiled.
 808      */
 809     private void readSourceFile(ClassSymbol c) throws CompletionFailure {
 810         readSourceFile(null, c);
 811     }
 812 
 813     /** Compile a ClassSymbol from source, optionally using the given compilation unit as
 814      *  the source tree.
 815      *  @param tree the compilation unit in which the given ClassSymbol resides,
 816      *              or null if should be parsed from source
 817      *  @param c    the ClassSymbol to complete
 818      */
 819     public void readSourceFile(JCCompilationUnit tree, ClassSymbol c) throws CompletionFailure {
 820         if (completionFailureName == c.fullname) {
 821             throw new CompletionFailure(
 822                 c, () -> diagFactory.fragment(Fragments.UserSelectedCompletionFailure), dcfh);
 823         }
 824         JavaFileObject filename = c.classfile;
 825         JavaFileObject prev = log.useSource(filename);
 826 
 827         if (tree == null) {
 828             try {
 829                 tree = parse(filename, filename.getCharContent(false));
 830             } catch (IOException e) {
 831                 log.error(Errors.ErrorReadingFile(filename, JavacFileManager.getMessage(e)));
 832                 tree = make.TopLevel(List.<JCTree>nil());
 833             } finally {
 834                 log.useSource(prev);
 835             }
 836         }
 837 
 838         if (!taskListener.isEmpty()) {
 839             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
 840             taskListener.started(e);
 841         }
 842 
 843         // Process module declarations.
 844         // If module resolution fails, ignore trees, and if trying to
 845         // complete a specific symbol, throw CompletionFailure.
 846         // Note that if module resolution failed, we may not even
 847         // have enough modules available to access java.lang, and
 848         // so risk getting FatalError("no.java.lang") from MemberEnter.
 849         if (!modules.enter(List.of(tree), c)) {
 850             throw new CompletionFailure(c, () -> diags.fragment(Fragments.CantResolveModules), dcfh);
 851         }
 852 
 853         enter.complete(List.of(tree), c);
 854 
 855         if (!taskListener.isEmpty()) {
 856             TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, tree);
 857             taskListener.finished(e);
 858         }
 859 
 860         if (enter.getEnv(c) == null) {
 861             boolean isPkgInfo =
 862                 tree.sourcefile.isNameCompatible("package-info",
 863                                                  JavaFileObject.Kind.SOURCE);
 864             boolean isModuleInfo =
 865                 tree.sourcefile.isNameCompatible("module-info",
 866                                                  JavaFileObject.Kind.SOURCE);
 867             if (isModuleInfo) {
 868                 if (enter.getEnv(tree.modle) == null) {
 869                     JCDiagnostic diag =
 870                         diagFactory.fragment(Fragments.FileDoesNotContainModule);
 871                     throw new ClassFinder.BadClassFile(c, filename, diag, diagFactory, dcfh);
 872                 }
 873             } else if (isPkgInfo) {
 874                 if (enter.getEnv(tree.packge) == null) {
 875                     JCDiagnostic diag =
 876                         diagFactory.fragment(Fragments.FileDoesNotContainPackage(c.location()));
 877                     throw new ClassFinder.BadClassFile(c, filename, diag, diagFactory, dcfh);
 878                 }
 879             } else {
 880                 JCDiagnostic diag =
 881                         diagFactory.fragment(Fragments.FileDoesntContainClass(c.getQualifiedName()));
 882                 throw new ClassFinder.BadClassFile(c, filename, diag, diagFactory, dcfh);
 883             }
 884         }
 885 
 886         implicitSourceFilesRead = true;
 887     }
 888 
 889     /** Track when the JavaCompiler has been used to compile something. */
 890     private boolean hasBeenUsed = false;
 891     private long start_msec = 0;
 892     public long elapsed_msec = 0;
 893 
 894     public void compile(List<JavaFileObject> sourceFileObject)
 895         throws Throwable {
 896         compile(sourceFileObject, List.nil(), null, List.nil());
 897     }
 898 
 899     /**
 900      * Main method: compile a list of files, return all compiled classes
 901      *
 902      * @param sourceFileObjects file objects to be compiled
 903      * @param classnames class names to process for annotations
 904      * @param processors user provided annotation processors to bypass
 905      * discovery, {@code null} means that no processors were provided
 906      * @param addModules additional root modules to be used during
 907      * module resolution.
 908      */
 909     public void compile(Collection<JavaFileObject> sourceFileObjects,
 910                         Collection<String> classnames,
 911                         Iterable<? extends Processor> processors,
 912                         Collection<String> addModules)
 913     {
 914         if (!taskListener.isEmpty()) {
 915             taskListener.started(new TaskEvent(TaskEvent.Kind.COMPILATION));
 916         }
 917 
 918         // as a JavaCompiler can only be used once, throw an exception if
 919         // it has been used before.
 920         if (hasBeenUsed)
 921             checkReusable();
 922         hasBeenUsed = true;
 923 
 924         // forcibly set the equivalent of -Xlint:-options, so that no further
 925         // warnings about command line options are generated from this point on
 926         options.put(XLINT_CUSTOM.primaryName + "-" + LintCategory.OPTIONS.option, "true");
 927         options.remove(XLINT_CUSTOM.primaryName + LintCategory.OPTIONS.option);
 928 
 929         start_msec = now();
 930 
 931         try {
 932             initProcessAnnotations(processors, sourceFileObjects, classnames);
 933 
 934             for (String className : classnames) {
 935                 int sep = className.indexOf('/');
 936                 if (sep != -1) {
 937                     modules.addExtraAddModules(className.substring(0, sep));
 938                 }
 939             }
 940 
 941             for (String moduleName : addModules) {
 942                 modules.addExtraAddModules(moduleName);
 943             }
 944 
 945             // These method calls must be chained to avoid memory leaks
 946             processAnnotations(
 947                 enterTrees(
 948                         stopIfError(CompileState.ENTER,
 949                                 initModules(stopIfError(CompileState.ENTER, parseFiles(sourceFileObjects))))
 950                 ),
 951                 classnames
 952             );
 953 
 954             // If it's safe to do so, skip attr / flow / gen for implicit classes
 955             if (taskListener.isEmpty() &&
 956                     implicitSourcePolicy == ImplicitSourcePolicy.NONE) {
 957                 todo.retainFiles(inputFiles);
 958             }
 959 
 960             if (!CompileState.ATTR.isAfter(shouldStopPolicyIfNoError)) {
 961                 switch (compilePolicy) {
 962                 case SIMPLE:
 963                     generate(desugar(flow(attribute(todo))));
 964                     break;
 965 
 966                 case BY_FILE: {
 967                         Queue<Queue<Env<AttrContext>>> q = todo.groupByFile();
 968                         while (!q.isEmpty() && !shouldStop(CompileState.ATTR)) {
 969                             generate(desugar(flow(attribute(q.remove()))));
 970                         }
 971                     }
 972                     break;
 973 
 974                 case BY_TODO:
 975                     while (!todo.isEmpty())
 976                         generate(desugar(flow(attribute(todo.remove()))));
 977                     break;
 978 
 979                 default:
 980                     Assert.error("unknown compile policy");
 981                 }
 982             }
 983         } catch (Abort ex) {
 984             if (devVerbose)
 985                 ex.printStackTrace(System.err);
 986 
 987             // In case an Abort was thrown before processAnnotations could be called,
 988             // we could have deferred diagnostics that haven't been reported.
 989             if (deferredDiagnosticHandler != null) {
 990                 deferredDiagnosticHandler.reportDeferredDiagnostics();
 991                 log.popDiagnosticHandler(deferredDiagnosticHandler);
 992             }
 993         } finally {
 994             if (verbose) {
 995                 elapsed_msec = elapsed(start_msec);
 996                 log.printVerbose("total", Long.toString(elapsed_msec));
 997             }
 998 
 999             reportDeferredDiagnostics();
1000 
1001             if (!log.hasDiagnosticListener()) {
1002                 printCount("error", errorCount());
1003                 printCount("warn", warningCount());
1004                 printSuppressedCount(errorCount(), log.nsuppressederrors, "count.error.recompile");
1005                 printSuppressedCount(warningCount(), log.nsuppressedwarns, "count.warn.recompile");
1006             }
1007             if (!taskListener.isEmpty()) {
1008                 taskListener.finished(new TaskEvent(TaskEvent.Kind.COMPILATION));
1009             }
1010             close();
1011             if (procEnvImpl != null)
1012                 procEnvImpl.close();
1013         }
1014     }
1015 
1016     protected void checkReusable() {
1017         throw new AssertionError("attempt to reuse JavaCompiler");
1018     }
1019 
1020     /**
1021      * The list of classes explicitly supplied on the command line for compilation.
1022      * Not always populated.
1023      */
1024     private List<JCClassDecl> rootClasses;
1025 
1026     /**
1027      * Parses a list of files.
1028      */
1029    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
1030        return InitialFileParser.instance(context).parse(fileObjects);
1031    }
1032 
1033    public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects, boolean force) {
1034        if (!force && shouldStop(CompileState.PARSE))
1035            return List.nil();
1036 
1037         //parse all files
1038         ListBuffer<JCCompilationUnit> trees = new ListBuffer<>();
1039         Set<JavaFileObject> filesSoFar = new HashSet<>();
1040         for (JavaFileObject fileObject : fileObjects) {
1041             if (!filesSoFar.contains(fileObject)) {
1042                 filesSoFar.add(fileObject);
1043                 trees.append(parse(fileObject));
1044             }
1045         }
1046         return trees.toList();
1047     }
1048 
1049    /**
1050     * Returns true iff the compilation will continue after annotation processing
1051     * is done.
1052     */
1053     public boolean continueAfterProcessAnnotations() {
1054         return !shouldStop(CompileState.ATTR);
1055     }
1056 
1057     public List<JCCompilationUnit> initModules(List<JCCompilationUnit> roots) {
1058         modules.initModules(roots);
1059         if (roots.isEmpty()) {
1060             enterDone();
1061         }
1062         return roots;
1063     }
1064 
1065     /**
1066      * Enter the symbols found in a list of parse trees.
1067      * As a side-effect, this puts elements on the "todo" list.
1068      * Also stores a list of all top level classes in rootClasses.
1069      */
1070     public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
1071         //enter symbols for all files
1072         if (!taskListener.isEmpty()) {
1073             for (JCCompilationUnit unit: roots) {
1074                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
1075                 taskListener.started(e);
1076             }
1077         }
1078 
1079         enter.main(roots);
1080 
1081         enterDone();
1082 
1083         if (!taskListener.isEmpty()) {
1084             for (JCCompilationUnit unit: roots) {
1085                 TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
1086                 taskListener.finished(e);
1087             }
1088         }
1089 
1090         // If generating source, or if tracking public apis,
1091         // then remember the classes declared in
1092         // the original compilation units listed on the command line.
1093         if (sourceOutput) {
1094             ListBuffer<JCClassDecl> cdefs = new ListBuffer<>();
1095             for (JCCompilationUnit unit : roots) {
1096                 for (List<JCTree> defs = unit.defs;
1097                      defs.nonEmpty();
1098                      defs = defs.tail) {
1099                     if (defs.head instanceof JCClassDecl classDecl)
1100                         cdefs.append(classDecl);
1101                 }
1102             }
1103             rootClasses = cdefs.toList();
1104         }
1105 
1106         // Ensure the input files have been recorded. Although this is normally
1107         // done by readSource, it may not have been done if the trees were read
1108         // in a prior round of annotation processing, and the trees have been
1109         // cleaned and are being reused.
1110         for (JCCompilationUnit unit : roots) {
1111             inputFiles.add(unit.sourcefile);
1112         }
1113 
1114         return roots;
1115     }
1116 
1117     /**
1118      * Set to true to enable skeleton annotation processing code.
1119      * Currently, we assume this variable will be replaced more
1120      * advanced logic to figure out if annotation processing is
1121      * needed.
1122      */
1123     boolean processAnnotations = false;
1124 
1125     Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
1126 
1127     /**
1128      * Object to handle annotation processing.
1129      */
1130     private JavacProcessingEnvironment procEnvImpl = null;
1131 
1132     /**
1133      * Check if we should process annotations.
1134      * If so, and if no scanner is yet registered, then set up the DocCommentScanner
1135      * to catch doc comments, and set keepComments so the parser records them in
1136      * the compilation unit.
1137      *
1138      * @param processors user provided annotation processors to bypass
1139      * discovery, {@code null} means that no processors were provided
1140      */
1141     public void initProcessAnnotations(Iterable<? extends Processor> processors,
1142                                        Collection<? extends JavaFileObject> initialFiles,
1143                                        Collection<String> initialClassNames) {
1144         if (processors != null && processors.iterator().hasNext())
1145             explicitAnnotationProcessingRequested = true;
1146 
1147         // Process annotations if processing is not disabled and there
1148         // is at least one Processor available.
1149         if (options.isSet(PROC, "none")) {
1150             processAnnotations = false;
1151         } else if (procEnvImpl == null) {
1152             procEnvImpl = JavacProcessingEnvironment.instance(context);
1153             procEnvImpl.setProcessors(processors);
1154             processAnnotations = procEnvImpl.atLeastOneProcessor();
1155 
1156             if (processAnnotations) {
1157                 if (!explicitAnnotationProcessingRequested() &&
1158                     !optionsCheckingInitiallyDisabled) {
1159                     log.note(Notes.ImplicitAnnotationProcessing);
1160                 }
1161 
1162                 options.put("parameters", "parameters");
1163                 reader.saveParameterNames = true;
1164                 keepComments = true;
1165                 genEndPos = true;
1166                 if (!taskListener.isEmpty())
1167                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
1168                 deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
1169                 procEnvImpl.getFiler().setInitialState(initialFiles, initialClassNames);
1170             } else { // free resources
1171                 procEnvImpl.close();
1172             }
1173         }
1174     }
1175 
1176     // TODO: called by JavacTaskImpl
1177     public void processAnnotations(List<JCCompilationUnit> roots) {
1178         processAnnotations(roots, List.nil());
1179     }
1180 
1181     /**
1182      * Process any annotations found in the specified compilation units.
1183      * @param roots a list of compilation units
1184      */
1185     // Implementation note: when this method is called, log.deferredDiagnostics
1186     // will have been set true by initProcessAnnotations, meaning that any diagnostics
1187     // that are reported will go into the log.deferredDiagnostics queue.
1188     // By the time this method exits, log.deferDiagnostics must be set back to false,
1189     // and all deferredDiagnostics must have been handled: i.e. either reported
1190     // or determined to be transient, and therefore suppressed.
1191     public void processAnnotations(List<JCCompilationUnit> roots,
1192                                    Collection<String> classnames) {
1193         if (shouldStop(CompileState.PROCESS)) {
1194             // Errors were encountered.
1195             // Unless all the errors are resolve errors, the errors were parse errors
1196             // or other errors during enter which cannot be fixed by running
1197             // any annotation processors.
1198             if (processAnnotations) {
1199                 deferredDiagnosticHandler.reportDeferredDiagnostics();
1200                 log.popDiagnosticHandler(deferredDiagnosticHandler);
1201                 return ;
1202             }
1203         }
1204 
1205         // ASSERT: processAnnotations and procEnvImpl should have been set up by
1206         // by initProcessAnnotations
1207 
1208         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
1209 
1210         if (!processAnnotations) {
1211             // If there are no annotation processors present, and
1212             // annotation processing is to occur with compilation,
1213             // emit a warning.
1214             if (options.isSet(PROC, "only")) {
1215                 log.warning(Warnings.ProcProcOnlyRequestedNoProcs);
1216                 todo.clear();
1217             }
1218             // If not processing annotations, classnames must be empty
1219             if (!classnames.isEmpty()) {
1220                 log.error(Errors.ProcNoExplicitAnnotationProcessingRequested(classnames));
1221             }
1222             Assert.checkNull(deferredDiagnosticHandler);
1223             return ; // continue regular compilation
1224         }
1225 
1226         Assert.checkNonNull(deferredDiagnosticHandler);
1227 
1228         try {
1229             List<ClassSymbol> classSymbols = List.nil();
1230             List<PackageSymbol> pckSymbols = List.nil();
1231             if (!classnames.isEmpty()) {
1232                  // Check for explicit request for annotation
1233                  // processing
1234                 if (!explicitAnnotationProcessingRequested()) {
1235                     log.error(Errors.ProcNoExplicitAnnotationProcessingRequested(classnames));
1236                     deferredDiagnosticHandler.reportDeferredDiagnostics();
1237                     log.popDiagnosticHandler(deferredDiagnosticHandler);
1238                     return ; // TODO: Will this halt compilation?
1239                 } else {
1240                     boolean errors = false;
1241                     for (String nameStr : classnames) {
1242                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
1243                         if (sym == null ||
1244                             (sym.kind == PCK && !processPcks) ||
1245                             sym.kind == ABSENT_TYP) {
1246                             if (sym != silentFail)
1247                                 log.error(Errors.ProcCantFindClass(nameStr));
1248                             errors = true;
1249                             continue;
1250                         }
1251                         try {
1252                             if (sym.kind == PCK)
1253                                 sym.complete();
1254                             if (sym.exists()) {
1255                                 if (sym.kind == PCK)
1256                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1257                                 else
1258                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
1259                                 continue;
1260                             }
1261                             Assert.check(sym.kind == PCK);
1262                             log.warning(Warnings.ProcPackageDoesNotExist(nameStr));
1263                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1264                         } catch (CompletionFailure e) {
1265                             log.error(Errors.ProcCantFindClass(nameStr));
1266                             errors = true;
1267                             continue;
1268                         }
1269                     }
1270                     if (errors) {
1271                         deferredDiagnosticHandler.reportDeferredDiagnostics();
1272                         log.popDiagnosticHandler(deferredDiagnosticHandler);
1273                         return ;
1274                     }
1275                 }
1276             }
1277             try {
1278                 annotationProcessingOccurred =
1279                         procEnvImpl.doProcessing(roots,
1280                                                  classSymbols,
1281                                                  pckSymbols,
1282                                                  deferredDiagnosticHandler);
1283                 // doProcessing will have handled deferred diagnostics
1284             } finally {
1285                 procEnvImpl.close();
1286             }
1287         } catch (CompletionFailure ex) {
1288             log.error(Errors.CantAccess(ex.sym, ex.getDetailValue()));
1289             if (deferredDiagnosticHandler != null) {
1290                 deferredDiagnosticHandler.reportDeferredDiagnostics();
1291                 log.popDiagnosticHandler(deferredDiagnosticHandler);
1292             }
1293         }
1294     }
1295 
1296     private boolean unrecoverableError() {
1297         if (deferredDiagnosticHandler != null) {
1298             for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
1299                 if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
1300                     return true;
1301             }
1302         }
1303         return false;
1304     }
1305 
1306     boolean explicitAnnotationProcessingRequested() {
1307         return
1308             explicitAnnotationProcessingRequested ||
1309             explicitAnnotationProcessingRequested(options, fileManager);
1310     }
1311 
1312     static boolean explicitAnnotationProcessingRequested(Options options, JavaFileManager fileManager) {
1313         return
1314             options.isSet(PROCESSOR) ||
1315             options.isSet(PROCESSOR_PATH) ||
1316             options.isSet(PROCESSOR_MODULE_PATH) ||
1317             options.isSet(PROC, "only") ||
1318             options.isSet(PROC, "full") ||
1319             options.isSet(A) ||
1320             options.isSet(XPRINT) ||
1321             fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH);
1322         // Skipping -XprintRounds and -XprintProcessorInfo
1323     }
1324 
1325     public void setDeferredDiagnosticHandler(Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
1326         this.deferredDiagnosticHandler = deferredDiagnosticHandler;
1327     }
1328 
1329     /**
1330      * Attribute a list of parse trees, such as found on the "todo" list.
1331      * Note that attributing classes may cause additional files to be
1332      * parsed and entered via the SourceCompleter.
1333      * Attribution of the entries in the list does not stop if any errors occur.
1334      * @return a list of environments for attribute classes.
1335      */
1336     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
1337         ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1338         while (!envs.isEmpty())
1339             results.append(attribute(envs.remove()));
1340         return stopIfError(CompileState.ATTR, results);
1341     }
1342 
1343     /**
1344      * Attribute a parse tree.
1345      * @return the attributed parse tree
1346      */
1347     public Env<AttrContext> attribute(Env<AttrContext> env) {
1348         if (compileStates.isDone(env, CompileState.ATTR))
1349             return env;
1350 
1351         if (verboseCompilePolicy)
1352             printNote("[attribute " + env.enclClass.sym + "]");
1353         if (verbose)
1354             log.printVerbose("checking.attribution", env.enclClass.sym);
1355 
1356         if (!taskListener.isEmpty()) {
1357             TaskEvent e = newAnalyzeTaskEvent(env);
1358             taskListener.started(e);
1359         }
1360 
1361         JavaFileObject prev = log.useSource(
1362                                   env.enclClass.sym.sourcefile != null ?
1363                                   env.enclClass.sym.sourcefile :
1364                                   env.toplevel.sourcefile);
1365         try {
1366             attr.attrib(env);
1367             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
1368                 //if in fail-over mode, ensure that AST expression nodes
1369                 //are correctly initialized (e.g. they have a type/symbol)
1370                 attr.postAttr(env.tree);
1371             }
1372             compileStates.put(env, CompileState.ATTR);
1373         }
1374         finally {
1375             log.useSource(prev);
1376         }
1377 
1378         return env;
1379     }
1380 
1381     /**
1382      * Perform dataflow checks on attributed parse trees.
1383      * These include checks for definite assignment and unreachable statements.
1384      * If any errors occur, an empty list will be returned.
1385      * @return the list of attributed parse trees
1386      */
1387     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
1388         ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1389         for (Env<AttrContext> env: envs) {
1390             flow(env, results);
1391         }
1392         return stopIfError(CompileState.FLOW, results);
1393     }
1394 
1395     /**
1396      * Perform dataflow checks on an attributed parse tree.
1397      */
1398     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
1399         ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1400         flow(env, results);
1401         return stopIfError(CompileState.FLOW, results);
1402     }
1403 
1404     /**
1405      * Perform dataflow checks on an attributed parse tree.
1406      */
1407     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
1408         if (compileStates.isDone(env, CompileState.FLOW)) {
1409             results.add(env);
1410             return;
1411         }
1412 
1413         try {
1414             if (shouldStop(CompileState.FLOW))
1415                 return;
1416 
1417             if (verboseCompilePolicy)
1418                 printNote("[flow " + env.enclClass.sym + "]");
1419             JavaFileObject prev = log.useSource(
1420                                                 env.enclClass.sym.sourcefile != null ?
1421                                                 env.enclClass.sym.sourcefile :
1422                                                 env.toplevel.sourcefile);
1423             try {
1424                 make.at(Position.FIRSTPOS);
1425                 TreeMaker localMake = make.forToplevel(env.toplevel);
1426                 flow.analyzeTree(env, localMake);
1427                 compileStates.put(env, CompileState.FLOW);
1428 
1429                 if (shouldStop(CompileState.FLOW))
1430                     return;
1431 
1432                 analyzer.flush(env);
1433 
1434                 results.add(env);
1435             }
1436             finally {
1437                 log.useSource(prev);
1438             }
1439         }
1440         finally {
1441             if (!taskListener.isEmpty()) {
1442                 TaskEvent e = newAnalyzeTaskEvent(env);
1443                 taskListener.finished(e);
1444             }
1445         }
1446     }
1447 
1448     private TaskEvent newAnalyzeTaskEvent(Env<AttrContext> env) {
1449         JCCompilationUnit toplevel = env.toplevel;
1450         ClassSymbol sym;
1451         if (env.enclClass.sym == syms.predefClass) {
1452             if (TreeInfo.isModuleInfo(toplevel)) {
1453                 sym = toplevel.modle.module_info;
1454             } else if (TreeInfo.isPackageInfo(toplevel)) {
1455                 sym = toplevel.packge.package_info;
1456             } else {
1457                 throw new IllegalStateException("unknown env.toplevel");
1458             }
1459         } else {
1460             sym = env.enclClass.sym;
1461         }
1462 
1463         return new TaskEvent(TaskEvent.Kind.ANALYZE, toplevel, sym);
1464     }
1465 
1466     /**
1467      * Prepare attributed parse trees, in conjunction with their attribution contexts,
1468      * for source or code generation.
1469      * If any errors occur, an empty list will be returned.
1470      * @return a list containing the classes to be generated
1471      */
1472     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
1473         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = new ListBuffer<>();
1474         for (Env<AttrContext> env: envs)
1475             desugar(env, results);
1476         return stopIfError(CompileState.FLOW, results);
1477     }
1478 
1479     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs = new HashMap<>();
1480 
1481     /**
1482      * Prepare attributed parse trees, in conjunction with their attribution contexts,
1483      * for source or code generation. If the file was not listed on the command line,
1484      * the current implicitSourcePolicy is taken into account.
1485      * The preparation stops as soon as an error is found.
1486      */
1487     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
1488         if (shouldStop(CompileState.TRANSTYPES))
1489             return;
1490 
1491         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
1492                 && !inputFiles.contains(env.toplevel.sourcefile)) {
1493             return;
1494         }
1495 
1496         if (!modules.multiModuleMode && env.toplevel.modle != modules.getDefaultModule()) {
1497             //can only generate classfiles for a single module:
1498             return;
1499         }
1500 
1501         if (compileStates.isDone(env, CompileState.LOWER)) {
1502             results.addAll(desugaredEnvs.get(env));
1503             return;
1504         }
1505 
1506         /**
1507          * Ensure that superclasses of C are desugared before C itself. This is
1508          * required for two reasons: (i) as erasure (TransTypes) destroys
1509          * information needed in flow analysis and (ii) as some checks carried
1510          * out during lowering require that all synthetic fields/methods have
1511          * already been added to C and its superclasses.
1512          */
1513         class ScanNested extends TreeScanner {
1514             Set<Env<AttrContext>> dependencies = new LinkedHashSet<>();
1515             protected boolean hasLambdas;
1516             protected boolean hasPatterns;
1517             @Override
1518             public void visitClassDef(JCClassDecl node) {
1519                 Type st = types.supertype(node.sym.type);
1520                 boolean envForSuperTypeFound = false;
1521                 while (!envForSuperTypeFound && st.hasTag(CLASS)) {
1522                     ClassSymbol c = st.tsym.outermostClass();
1523                     Env<AttrContext> stEnv = enter.getEnv(c);
1524                     if (stEnv != null && env != stEnv) {
1525                         if (dependencies.add(stEnv)) {
1526                             boolean prevHasLambdas = hasLambdas;
1527                             boolean prevHasPatterns = hasPatterns;
1528                             try {
1529                                 scan(stEnv.tree);
1530                             } finally {
1531                                 /*
1532                                  * ignore any updates to hasLambdas and hasPatterns
1533                                  * made during the nested scan, this ensures an
1534                                  * initialized LambdaToMethod or TransPatterns is
1535                                  * available only to those classes that contain
1536                                  * lambdas or patterns, respectivelly
1537                                  */
1538                                 hasLambdas = prevHasLambdas;
1539                                 hasPatterns = prevHasPatterns;
1540                             }
1541                         }
1542                         envForSuperTypeFound = true;
1543                     }
1544                     st = types.supertype(st);
1545                 }
1546                 super.visitClassDef(node);
1547             }
1548             @Override
1549             public void visitLambda(JCLambda tree) {
1550                 hasLambdas = true;
1551                 super.visitLambda(tree);
1552             }
1553             @Override
1554             public void visitReference(JCMemberReference tree) {
1555                 hasLambdas = true;
1556                 super.visitReference(tree);
1557             }
1558             @Override
1559             public void visitBindingPattern(JCBindingPattern tree) {
1560                 hasPatterns = true;
1561                 super.visitBindingPattern(tree);
1562             }
1563             @Override
1564             public void visitRecordPattern(JCRecordPattern that) {
1565                 hasPatterns = true;
1566                 super.visitRecordPattern(that);
1567             }
1568             @Override
1569             public void visitSwitch(JCSwitch tree) {
1570                 hasPatterns |= tree.patternSwitch;
1571                 super.visitSwitch(tree);
1572             }
1573             @Override
1574             public void visitSwitchExpression(JCSwitchExpression tree) {
1575                 hasPatterns |= tree.patternSwitch;
1576                 super.visitSwitchExpression(tree);
1577             }
1578         }
1579         ScanNested scanner = new ScanNested();
1580         scanner.scan(env.tree);
1581         for (Env<AttrContext> dep: scanner.dependencies) {
1582         if (!compileStates.isDone(dep, CompileState.FLOW))
1583             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
1584         }
1585 
1586         //We need to check for error another time as more classes might
1587         //have been attributed and analyzed at this stage
1588         if (shouldStop(CompileState.TRANSTYPES))
1589             return;
1590 
1591         if (verboseCompilePolicy)
1592             printNote("[desugar " + env.enclClass.sym + "]");
1593 
1594         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1595                                   env.enclClass.sym.sourcefile :
1596                                   env.toplevel.sourcefile);
1597         try {
1598             //save tree prior to rewriting
1599             JCTree untranslated = env.tree;
1600 
1601             make.at(Position.FIRSTPOS);
1602             TreeMaker localMake = make.forToplevel(env.toplevel);
1603 
1604             if (env.tree.hasTag(JCTree.Tag.PACKAGEDEF) || env.tree.hasTag(JCTree.Tag.MODULEDEF)) {
1605                 if (!(sourceOutput)) {
1606                     if (shouldStop(CompileState.LOWER))
1607                         return;
1608                     List<JCTree> def = lower.translateTopLevelClass(env, env.tree, localMake);
1609                     if (def.head != null) {
1610                         Assert.check(def.tail.isEmpty());
1611                         results.add(new Pair<>(env, (JCClassDecl)def.head));
1612                     }
1613                 }
1614                 return;
1615             }
1616 
1617             if (shouldStop(CompileState.TRANSTYPES))
1618                 return;
1619 
1620             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
1621             compileStates.put(env, CompileState.TRANSTYPES);
1622 
1623             if (shouldStop(CompileState.TRANSLITERALS))
1624                 return;
1625 
1626             env.tree = TransLiterals.instance(context).translateTopLevelClass(env, env.tree, localMake);
1627             compileStates.put(env, CompileState.TRANSLITERALS);
1628 
1629             if (shouldStop(CompileState.TRANSPATTERNS))
1630                 return;
1631 
1632             if (scanner.hasPatterns) {
1633                 env.tree = TransPatterns.instance(context).translateTopLevelClass(env, env.tree, localMake);
1634             }
1635 
1636             compileStates.put(env, CompileState.TRANSPATTERNS);
1637 
1638             if (scanner.hasLambdas) {
1639                 if (shouldStop(CompileState.UNLAMBDA))
1640                     return;
1641 
1642                 env.tree = LambdaToMethod.instance(context).translateTopLevelClass(env, env.tree, localMake);
1643                 compileStates.put(env, CompileState.UNLAMBDA);
1644             }
1645 
1646             if (shouldStop(CompileState.LOWER))
1647                 return;
1648 
1649             if (sourceOutput) {
1650                 //emit standard Java source file, only for compilation
1651                 //units enumerated explicitly on the command line
1652                 JCClassDecl cdef = (JCClassDecl)env.tree;
1653                 if (untranslated instanceof JCClassDecl classDecl &&
1654                     rootClasses.contains(classDecl)) {
1655                     results.add(new Pair<>(env, cdef));
1656                 }
1657                 return;
1658             }
1659 
1660             //translate out inner classes
1661             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
1662             compileStates.put(env, CompileState.LOWER);
1663 
1664             if (shouldStop(CompileState.LOWER))
1665                 return;
1666 
1667             //generate code for each class
1668             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
1669                 JCClassDecl cdef = (JCClassDecl)l.head;
1670                 results.add(new Pair<>(env, cdef));
1671             }
1672         }
1673         finally {
1674             log.useSource(prev);
1675         }
1676 
1677     }
1678 
1679     /** Generates the source or class file for a list of classes.
1680      * The decision to generate a source file or a class file is
1681      * based upon the compiler's options.
1682      * Generation stops if an error occurs while writing files.
1683      */
1684     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
1685         generate(queue, null);
1686     }
1687 
1688     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
1689         if (shouldStop(CompileState.GENERATE))
1690             return;
1691 
1692         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
1693             Env<AttrContext> env = x.fst;
1694             JCClassDecl cdef = x.snd;
1695 
1696             if (verboseCompilePolicy) {
1697                 printNote("[generate " + (sourceOutput ? " source" : "code") + " " + cdef.sym + "]");
1698             }
1699 
1700             if (!taskListener.isEmpty()) {
1701                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1702                 taskListener.started(e);
1703             }
1704 
1705             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1706                                       env.enclClass.sym.sourcefile :
1707                                       env.toplevel.sourcefile);
1708             try {
1709                 JavaFileObject file;
1710                 if (sourceOutput) {
1711                     file = printSource(env, cdef);
1712                 } else {
1713                     if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
1714                             && jniWriter.needsHeader(cdef.sym)) {
1715                         jniWriter.write(cdef.sym);
1716                     }
1717                     file = genCode(env, cdef);
1718                 }
1719                 if (results != null && file != null)
1720                     results.add(file);
1721             } catch (IOException
1722                     | UncheckedIOException
1723                     | FileSystemNotFoundException
1724                     | InvalidPathException
1725                     | ReadOnlyFileSystemException ex) {
1726                 log.error(cdef.pos(),
1727                           Errors.ClassCantWrite(cdef.sym, ex.getMessage()));
1728                 return;
1729             } finally {
1730                 log.useSource(prev);
1731             }
1732 
1733             if (!taskListener.isEmpty()) {
1734                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1735                 taskListener.finished(e);
1736             }
1737         }
1738     }
1739 
1740         // where
1741         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
1742             // use a LinkedHashMap to preserve the order of the original list as much as possible
1743             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<>();
1744             for (Env<AttrContext> env: envs) {
1745                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
1746                 if (sublist == null) {
1747                     sublist = new ListBuffer<>();
1748                     map.put(env.toplevel, sublist);
1749                 }
1750                 sublist.add(env);
1751             }
1752             return map;
1753         }
1754 
1755         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
1756             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
1757             class MethodBodyRemover extends TreeTranslator {
1758                 @Override
1759                 public void visitMethodDef(JCMethodDecl tree) {
1760                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
1761                     for (JCVariableDecl vd : tree.params)
1762                         vd.mods.flags &= ~Flags.FINAL;
1763                     tree.body = null;
1764                     super.visitMethodDef(tree);
1765                 }
1766                 @Override
1767                 public void visitVarDef(JCVariableDecl tree) {
1768                     if (tree.init != null && tree.init.type.constValue() == null)
1769                         tree.init = null;
1770                     super.visitVarDef(tree);
1771                 }
1772                 @Override
1773                 public void visitClassDef(JCClassDecl tree) {
1774                     ListBuffer<JCTree> newdefs = new ListBuffer<>();
1775                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
1776                         JCTree t = it.head;
1777                         switch (t.getTag()) {
1778                         case CLASSDEF:
1779                             if (isInterface ||
1780                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1781                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1782                                 newdefs.append(t);
1783                             break;
1784                         case METHODDEF:
1785                             if (isInterface ||
1786                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1787                                 ((JCMethodDecl) t).sym.name == names.init ||
1788                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1789                                 newdefs.append(t);
1790                             break;
1791                         case VARDEF:
1792                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1793                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1794                                 newdefs.append(t);
1795                             break;
1796                         default:
1797                             break;
1798                         }
1799                     }
1800                     tree.defs = newdefs.toList();
1801                     super.visitClassDef(tree);
1802                 }
1803             }
1804             MethodBodyRemover r = new MethodBodyRemover();
1805             return r.translate(cdef);
1806         }
1807 
1808     public void reportDeferredDiagnostics() {
1809         if (errorCount() == 0
1810                 && annotationProcessingOccurred
1811                 && implicitSourceFilesRead
1812                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
1813             if (explicitAnnotationProcessingRequested())
1814                 log.warning(Warnings.ProcUseImplicit);
1815             else
1816                 log.warning(Warnings.ProcUseProcOrImplicit);
1817         }
1818         chk.reportDeferredDiagnostics();
1819         preview.reportDeferredDiagnostics();
1820         if (log.compressedOutput) {
1821             log.mandatoryNote(null, Notes.CompressedDiags);
1822         }
1823     }
1824 
1825     public void enterDone() {
1826         enterDone = true;
1827         annotate.enterDone();
1828     }
1829 
1830     public boolean isEnterDone() {
1831         return enterDone;
1832     }
1833 
1834     private Name readModuleName(JavaFileObject fo) {
1835         return parseAndGetName(fo, t -> {
1836             JCModuleDecl md = t.getModuleDecl();
1837 
1838             return md != null ? TreeInfo.fullName(md.getName()) : null;
1839         });
1840     }
1841 
1842     private Name findPackageInFile(JavaFileObject fo) {
1843         return parseAndGetName(fo, t -> t.getPackage() != null ?
1844                                         TreeInfo.fullName(t.getPackage().getPackageName()) : null);
1845     }
1846 
1847     private Name parseAndGetName(JavaFileObject fo,
1848                                  Function<JCTree.JCCompilationUnit, Name> tree2Name) {
1849         DiagnosticHandler dh = new DiscardDiagnosticHandler(log);
1850         JavaFileObject prevSource = log.useSource(fo);
1851         try {
1852             JCTree.JCCompilationUnit t = parse(fo, fo.getCharContent(false), true);
1853             return tree2Name.apply(t);
1854         } catch (IOException e) {
1855             return null;
1856         } finally {
1857             log.popDiagnosticHandler(dh);
1858             log.useSource(prevSource);
1859         }
1860     }
1861 
1862     /** Close the compiler, flushing the logs
1863      */
1864     public void close() {
1865         rootClasses = null;
1866         finder = null;
1867         reader = null;
1868         make = null;
1869         writer = null;
1870         enter = null;
1871         if (todo != null)
1872             todo.clear();
1873         todo = null;
1874         parserFactory = null;
1875         syms = null;
1876         source = null;
1877         attr = null;
1878         chk = null;
1879         gen = null;
1880         flow = null;
1881         transTypes = null;
1882         lower = null;
1883         annotate = null;
1884         types = null;
1885 
1886         log.flush();
1887         try {
1888             fileManager.flush();
1889         } catch (IOException e) {
1890             throw new Abort(e);
1891         } finally {
1892             if (names != null)
1893                 names.dispose();
1894             names = null;
1895 
1896             FatalError fatalError = null;
1897             for (Closeable c: closeables) {
1898                 try {
1899                     c.close();
1900                 } catch (IOException e) {
1901                     if (fatalError == null) {
1902                         JCDiagnostic msg = diagFactory.fragment(Fragments.FatalErrCantClose);
1903                         fatalError = new FatalError(msg, e);
1904                     } else {
1905                         fatalError.addSuppressed(e);
1906                     }
1907                 }
1908             }
1909             if (fatalError != null) {
1910                 throw fatalError;
1911             }
1912             closeables = List.nil();
1913         }
1914     }
1915 
1916     protected void printNote(String lines) {
1917         log.printRawLines(Log.WriterKind.NOTICE, lines);
1918     }
1919 
1920     /** Print numbers of errors and warnings.
1921      */
1922     public void printCount(String kind, int count) {
1923         if (count != 0) {
1924             String key;
1925             if (count == 1)
1926                 key = "count." + kind;
1927             else
1928                 key = "count." + kind + ".plural";
1929             log.printLines(WriterKind.ERROR, key, String.valueOf(count));
1930             log.flush(Log.WriterKind.ERROR);
1931         }
1932     }
1933 
1934     private void printSuppressedCount(int shown, int suppressed, String diagKey) {
1935         if (suppressed > 0) {
1936             int total = shown + suppressed;
1937             log.printLines(WriterKind.ERROR, diagKey,
1938                     String.valueOf(shown), String.valueOf(total));
1939             log.flush(Log.WriterKind.ERROR);
1940         }
1941     }
1942 
1943     private static long now() {
1944         return System.currentTimeMillis();
1945     }
1946 
1947     private static long elapsed(long then) {
1948         return now() - then;
1949     }
1950 
1951     public void newRound() {
1952         inputFiles.clear();
1953         todo.clear();
1954     }
1955 
1956     public interface InitialFileParserIntf {
1957         public List<JCCompilationUnit> parse(Iterable<JavaFileObject> files);
1958     }
1959 
1960     public static class InitialFileParser implements InitialFileParserIntf {
1961 
1962         public static final Key<InitialFileParserIntf> initialParserKey = new Key<>();
1963 
1964         public static InitialFileParserIntf instance(Context context) {
1965             InitialFileParserIntf instance = context.get(initialParserKey);
1966             if (instance == null)
1967                 instance = new InitialFileParser(context);
1968             return instance;
1969         }
1970 
1971         private final JavaCompiler compiler;
1972 
1973         private InitialFileParser(Context context) {
1974             context.put(initialParserKey, this);
1975             this.compiler = JavaCompiler.instance(context);
1976         }
1977 
1978         @Override
1979         public List<JCCompilationUnit> parse(Iterable<JavaFileObject> fileObjects) {
1980            return compiler.parseFiles(fileObjects, false);
1981         }
1982     }
1983 }