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         if (options.isSet(PROC, "none")) {
1148             processAnnotations = false;
1149         } else if (procEnvImpl == null) {
1150             procEnvImpl = JavacProcessingEnvironment.instance(context);
1151             procEnvImpl.setProcessors(processors);
1152 
1153             // Process annotations if processing is requested and there
1154             // is at least one Processor available.
1155             processAnnotations = procEnvImpl.atLeastOneProcessor() &&
1156                 explicitAnnotationProcessingRequested();
1157 
1158             if (processAnnotations) {
1159                 options.put("parameters", "parameters");
1160                 reader.saveParameterNames = true;
1161                 keepComments = true;
1162                 genEndPos = true;
1163                 if (!taskListener.isEmpty())
1164                     taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
1165                 deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
1166                 procEnvImpl.getFiler().setInitialState(initialFiles, initialClassNames);
1167             }
1168         } else { // free resources
1169             procEnvImpl.close();
1170         }
1171     }
1172 
1173     // TODO: called by JavacTaskImpl
1174     public void processAnnotations(List<JCCompilationUnit> roots) {
1175         processAnnotations(roots, List.nil());
1176     }
1177 
1178     /**
1179      * Process any annotations found in the specified compilation units.
1180      * @param roots a list of compilation units
1181      */
1182     // Implementation note: when this method is called, log.deferredDiagnostics
1183     // will have been set true by initProcessAnnotations, meaning that any diagnostics
1184     // that are reported will go into the log.deferredDiagnostics queue.
1185     // By the time this method exits, log.deferDiagnostics must be set back to false,
1186     // and all deferredDiagnostics must have been handled: i.e. either reported
1187     // or determined to be transient, and therefore suppressed.
1188     public void processAnnotations(List<JCCompilationUnit> roots,
1189                                    Collection<String> classnames) {
1190         if (shouldStop(CompileState.PROCESS)) {
1191             // Errors were encountered.
1192             // Unless all the errors are resolve errors, the errors were parse errors
1193             // or other errors during enter which cannot be fixed by running
1194             // any annotation processors.
1195             if (processAnnotations) {
1196                 deferredDiagnosticHandler.reportDeferredDiagnostics();
1197                 log.popDiagnosticHandler(deferredDiagnosticHandler);
1198                 return ;
1199             }
1200         }
1201 
1202         // ASSERT: processAnnotations and procEnvImpl should have been set up by
1203         // by initProcessAnnotations
1204 
1205         // NOTE: The !classnames.isEmpty() checks should be refactored to Main.
1206 
1207         if (!processAnnotations) {
1208             // If there are no annotation processors present, and
1209             // annotation processing is to occur with compilation,
1210             // emit a warning.
1211             if (options.isSet(PROC, "only")) {
1212                 log.warning(Warnings.ProcProcOnlyRequestedNoProcs);
1213                 todo.clear();
1214             }
1215             // If not processing annotations, classnames must be empty
1216             if (!classnames.isEmpty()) {
1217                 log.error(Errors.ProcNoExplicitAnnotationProcessingRequested(classnames));
1218             }
1219             Assert.checkNull(deferredDiagnosticHandler);
1220             return ; // continue regular compilation
1221         }
1222 
1223         Assert.checkNonNull(deferredDiagnosticHandler);
1224 
1225         try {
1226             List<ClassSymbol> classSymbols = List.nil();
1227             List<PackageSymbol> pckSymbols = List.nil();
1228             if (!classnames.isEmpty()) {
1229                  // Check for explicit request for annotation
1230                  // processing
1231                 if (!explicitAnnotationProcessingRequested()) {
1232                     log.error(Errors.ProcNoExplicitAnnotationProcessingRequested(classnames));
1233                     deferredDiagnosticHandler.reportDeferredDiagnostics();
1234                     log.popDiagnosticHandler(deferredDiagnosticHandler);
1235                     return ; // TODO: Will this halt compilation?
1236                 } else {
1237                     boolean errors = false;
1238                     for (String nameStr : classnames) {
1239                         Symbol sym = resolveBinaryNameOrIdent(nameStr);
1240                         if (sym == null ||
1241                             (sym.kind == PCK && !processPcks) ||
1242                             sym.kind == ABSENT_TYP) {
1243                             if (sym != silentFail)
1244                                 log.error(Errors.ProcCantFindClass(nameStr));
1245                             errors = true;
1246                             continue;
1247                         }
1248                         try {
1249                             if (sym.kind == PCK)
1250                                 sym.complete();
1251                             if (sym.exists()) {
1252                                 if (sym.kind == PCK)
1253                                     pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1254                                 else
1255                                     classSymbols = classSymbols.prepend((ClassSymbol)sym);
1256                                 continue;
1257                             }
1258                             Assert.check(sym.kind == PCK);
1259                             log.warning(Warnings.ProcPackageDoesNotExist(nameStr));
1260                             pckSymbols = pckSymbols.prepend((PackageSymbol)sym);
1261                         } catch (CompletionFailure e) {
1262                             log.error(Errors.ProcCantFindClass(nameStr));
1263                             errors = true;
1264                             continue;
1265                         }
1266                     }
1267                     if (errors) {
1268                         deferredDiagnosticHandler.reportDeferredDiagnostics();
1269                         log.popDiagnosticHandler(deferredDiagnosticHandler);
1270                         return ;
1271                     }
1272                 }
1273             }
1274             try {
1275                 annotationProcessingOccurred =
1276                         procEnvImpl.doProcessing(roots,
1277                                                  classSymbols,
1278                                                  pckSymbols,
1279                                                  deferredDiagnosticHandler);
1280                 // doProcessing will have handled deferred diagnostics
1281             } finally {
1282                 procEnvImpl.close();
1283             }
1284         } catch (CompletionFailure ex) {
1285             log.error(Errors.CantAccess(ex.sym, ex.getDetailValue()));
1286             if (deferredDiagnosticHandler != null) {
1287                 deferredDiagnosticHandler.reportDeferredDiagnostics();
1288                 log.popDiagnosticHandler(deferredDiagnosticHandler);
1289             }
1290         }
1291     }
1292 
1293     private boolean unrecoverableError() {
1294         if (deferredDiagnosticHandler != null) {
1295             for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
1296                 if (d.getKind() == JCDiagnostic.Kind.ERROR && !d.isFlagSet(RECOVERABLE))
1297                     return true;
1298             }
1299         }
1300         return false;
1301     }
1302 
1303     boolean explicitAnnotationProcessingRequested() {
1304         return
1305             explicitAnnotationProcessingRequested ||
1306             explicitAnnotationProcessingRequested(options, fileManager);
1307     }
1308 
1309     static boolean explicitAnnotationProcessingRequested(Options options, JavaFileManager fileManager) {
1310         return
1311             options.isSet(PROCESSOR) ||
1312             options.isSet(PROCESSOR_PATH) ||
1313             options.isSet(PROCESSOR_MODULE_PATH) ||
1314             options.isSet(PROC, "only") ||
1315             options.isSet(PROC, "full") ||
1316             options.isSet(A) ||
1317             options.isSet(XPRINT) ||
1318             fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH);
1319         // Skipping -XprintRounds and -XprintProcessorInfo
1320     }
1321 
1322     public void setDeferredDiagnosticHandler(Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
1323         this.deferredDiagnosticHandler = deferredDiagnosticHandler;
1324     }
1325 
1326     /**
1327      * Attribute a list of parse trees, such as found on the "todo" list.
1328      * Note that attributing classes may cause additional files to be
1329      * parsed and entered via the SourceCompleter.
1330      * Attribution of the entries in the list does not stop if any errors occur.
1331      * @return a list of environments for attribute classes.
1332      */
1333     public Queue<Env<AttrContext>> attribute(Queue<Env<AttrContext>> envs) {
1334         ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1335         while (!envs.isEmpty())
1336             results.append(attribute(envs.remove()));
1337         return stopIfError(CompileState.ATTR, results);
1338     }
1339 
1340     /**
1341      * Attribute a parse tree.
1342      * @return the attributed parse tree
1343      */
1344     public Env<AttrContext> attribute(Env<AttrContext> env) {
1345         if (compileStates.isDone(env, CompileState.ATTR))
1346             return env;
1347 
1348         if (verboseCompilePolicy)
1349             printNote("[attribute " + env.enclClass.sym + "]");
1350         if (verbose)
1351             log.printVerbose("checking.attribution", env.enclClass.sym);
1352 
1353         if (!taskListener.isEmpty()) {
1354             TaskEvent e = newAnalyzeTaskEvent(env);
1355             taskListener.started(e);
1356         }
1357 
1358         JavaFileObject prev = log.useSource(
1359                                   env.enclClass.sym.sourcefile != null ?
1360                                   env.enclClass.sym.sourcefile :
1361                                   env.toplevel.sourcefile);
1362         try {
1363             attr.attrib(env);
1364             if (errorCount() > 0 && !shouldStop(CompileState.ATTR)) {
1365                 //if in fail-over mode, ensure that AST expression nodes
1366                 //are correctly initialized (e.g. they have a type/symbol)
1367                 attr.postAttr(env.tree);
1368             }
1369             compileStates.put(env, CompileState.ATTR);
1370         }
1371         finally {
1372             log.useSource(prev);
1373         }
1374 
1375         return env;
1376     }
1377 
1378     /**
1379      * Perform dataflow checks on attributed parse trees.
1380      * These include checks for definite assignment and unreachable statements.
1381      * If any errors occur, an empty list will be returned.
1382      * @return the list of attributed parse trees
1383      */
1384     public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
1385         ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1386         for (Env<AttrContext> env: envs) {
1387             flow(env, results);
1388         }
1389         return stopIfError(CompileState.FLOW, results);
1390     }
1391 
1392     /**
1393      * Perform dataflow checks on an attributed parse tree.
1394      */
1395     public Queue<Env<AttrContext>> flow(Env<AttrContext> env) {
1396         ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
1397         flow(env, results);
1398         return stopIfError(CompileState.FLOW, results);
1399     }
1400 
1401     /**
1402      * Perform dataflow checks on an attributed parse tree.
1403      */
1404     protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
1405         if (compileStates.isDone(env, CompileState.FLOW)) {
1406             results.add(env);
1407             return;
1408         }
1409 
1410         try {
1411             if (shouldStop(CompileState.FLOW))
1412                 return;
1413 
1414             if (verboseCompilePolicy)
1415                 printNote("[flow " + env.enclClass.sym + "]");
1416             JavaFileObject prev = log.useSource(
1417                                                 env.enclClass.sym.sourcefile != null ?
1418                                                 env.enclClass.sym.sourcefile :
1419                                                 env.toplevel.sourcefile);
1420             try {
1421                 make.at(Position.FIRSTPOS);
1422                 TreeMaker localMake = make.forToplevel(env.toplevel);
1423                 flow.analyzeTree(env, localMake);
1424                 compileStates.put(env, CompileState.FLOW);
1425 
1426                 if (shouldStop(CompileState.FLOW))
1427                     return;
1428 
1429                 analyzer.flush(env);
1430 
1431                 results.add(env);
1432             }
1433             finally {
1434                 log.useSource(prev);
1435             }
1436         }
1437         finally {
1438             if (!taskListener.isEmpty()) {
1439                 TaskEvent e = newAnalyzeTaskEvent(env);
1440                 taskListener.finished(e);
1441             }
1442         }
1443     }
1444 
1445     private TaskEvent newAnalyzeTaskEvent(Env<AttrContext> env) {
1446         JCCompilationUnit toplevel = env.toplevel;
1447         ClassSymbol sym;
1448         if (env.enclClass.sym == syms.predefClass) {
1449             if (TreeInfo.isModuleInfo(toplevel)) {
1450                 sym = toplevel.modle.module_info;
1451             } else if (TreeInfo.isPackageInfo(toplevel)) {
1452                 sym = toplevel.packge.package_info;
1453             } else {
1454                 throw new IllegalStateException("unknown env.toplevel");
1455             }
1456         } else {
1457             sym = env.enclClass.sym;
1458         }
1459 
1460         return new TaskEvent(TaskEvent.Kind.ANALYZE, toplevel, sym);
1461     }
1462 
1463     /**
1464      * Prepare attributed parse trees, in conjunction with their attribution contexts,
1465      * for source or code generation.
1466      * If any errors occur, an empty list will be returned.
1467      * @return a list containing the classes to be generated
1468      */
1469     public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
1470         ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = new ListBuffer<>();
1471         for (Env<AttrContext> env: envs)
1472             desugar(env, results);
1473         return stopIfError(CompileState.FLOW, results);
1474     }
1475 
1476     HashMap<Env<AttrContext>, Queue<Pair<Env<AttrContext>, JCClassDecl>>> desugaredEnvs = new HashMap<>();
1477 
1478     /**
1479      * Prepare attributed parse trees, in conjunction with their attribution contexts,
1480      * for source or code generation. If the file was not listed on the command line,
1481      * the current implicitSourcePolicy is taken into account.
1482      * The preparation stops as soon as an error is found.
1483      */
1484     protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
1485         if (shouldStop(CompileState.TRANSTYPES))
1486             return;
1487 
1488         if (implicitSourcePolicy == ImplicitSourcePolicy.NONE
1489                 && !inputFiles.contains(env.toplevel.sourcefile)) {
1490             return;
1491         }
1492 
1493         if (!modules.multiModuleMode && env.toplevel.modle != modules.getDefaultModule()) {
1494             //can only generate classfiles for a single module:
1495             return;
1496         }
1497 
1498         if (compileStates.isDone(env, CompileState.LOWER)) {
1499             results.addAll(desugaredEnvs.get(env));
1500             return;
1501         }
1502 
1503         /**
1504          * Ensure that superclasses of C are desugared before C itself. This is
1505          * required for two reasons: (i) as erasure (TransTypes) destroys
1506          * information needed in flow analysis and (ii) as some checks carried
1507          * out during lowering require that all synthetic fields/methods have
1508          * already been added to C and its superclasses.
1509          */
1510         class ScanNested extends TreeScanner {
1511             Set<Env<AttrContext>> dependencies = new LinkedHashSet<>();
1512             protected boolean hasLambdas;
1513             protected boolean hasPatterns;
1514             @Override
1515             public void visitClassDef(JCClassDecl node) {
1516                 Type st = types.supertype(node.sym.type);
1517                 boolean envForSuperTypeFound = false;
1518                 while (!envForSuperTypeFound && st.hasTag(CLASS)) {
1519                     ClassSymbol c = st.tsym.outermostClass();
1520                     Env<AttrContext> stEnv = enter.getEnv(c);
1521                     if (stEnv != null && env != stEnv) {
1522                         if (dependencies.add(stEnv)) {
1523                             boolean prevHasLambdas = hasLambdas;
1524                             boolean prevHasPatterns = hasPatterns;
1525                             try {
1526                                 scan(stEnv.tree);
1527                             } finally {
1528                                 /*
1529                                  * ignore any updates to hasLambdas and hasPatterns
1530                                  * made during the nested scan, this ensures an
1531                                  * initialized LambdaToMethod or TransPatterns is
1532                                  * available only to those classes that contain
1533                                  * lambdas or patterns, respectivelly
1534                                  */
1535                                 hasLambdas = prevHasLambdas;
1536                                 hasPatterns = prevHasPatterns;
1537                             }
1538                         }
1539                         envForSuperTypeFound = true;
1540                     }
1541                     st = types.supertype(st);
1542                 }
1543                 super.visitClassDef(node);
1544             }
1545             @Override
1546             public void visitLambda(JCLambda tree) {
1547                 hasLambdas = true;
1548                 super.visitLambda(tree);
1549             }
1550             @Override
1551             public void visitReference(JCMemberReference tree) {
1552                 hasLambdas = true;
1553                 super.visitReference(tree);
1554             }
1555             @Override
1556             public void visitBindingPattern(JCBindingPattern tree) {
1557                 hasPatterns = true;
1558                 super.visitBindingPattern(tree);
1559             }
1560             @Override
1561             public void visitRecordPattern(JCRecordPattern that) {
1562                 hasPatterns = true;
1563                 super.visitRecordPattern(that);
1564             }
1565             @Override
1566             public void visitSwitch(JCSwitch tree) {
1567                 hasPatterns |= tree.patternSwitch;
1568                 super.visitSwitch(tree);
1569             }
1570             @Override
1571             public void visitSwitchExpression(JCSwitchExpression tree) {
1572                 hasPatterns |= tree.patternSwitch;
1573                 super.visitSwitchExpression(tree);
1574             }
1575         }
1576         ScanNested scanner = new ScanNested();
1577         scanner.scan(env.tree);
1578         for (Env<AttrContext> dep: scanner.dependencies) {
1579         if (!compileStates.isDone(dep, CompileState.FLOW))
1580             desugaredEnvs.put(dep, desugar(flow(attribute(dep))));
1581         }
1582 
1583         //We need to check for error another time as more classes might
1584         //have been attributed and analyzed at this stage
1585         if (shouldStop(CompileState.TRANSTYPES))
1586             return;
1587 
1588         if (verboseCompilePolicy)
1589             printNote("[desugar " + env.enclClass.sym + "]");
1590 
1591         JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1592                                   env.enclClass.sym.sourcefile :
1593                                   env.toplevel.sourcefile);
1594         try {
1595             //save tree prior to rewriting
1596             JCTree untranslated = env.tree;
1597 
1598             make.at(Position.FIRSTPOS);
1599             TreeMaker localMake = make.forToplevel(env.toplevel);
1600 
1601             if (env.tree.hasTag(JCTree.Tag.PACKAGEDEF) || env.tree.hasTag(JCTree.Tag.MODULEDEF)) {
1602                 if (!(sourceOutput)) {
1603                     if (shouldStop(CompileState.LOWER))
1604                         return;
1605                     List<JCTree> def = lower.translateTopLevelClass(env, env.tree, localMake);
1606                     if (def.head != null) {
1607                         Assert.check(def.tail.isEmpty());
1608                         results.add(new Pair<>(env, (JCClassDecl)def.head));
1609                     }
1610                 }
1611                 return;
1612             }
1613 
1614             if (shouldStop(CompileState.TRANSTYPES))
1615                 return;
1616 
1617             env.tree = transTypes.translateTopLevelClass(env.tree, localMake);
1618             compileStates.put(env, CompileState.TRANSTYPES);
1619 
1620             if (shouldStop(CompileState.TRANSLITERALS))
1621                 return;
1622 
1623             env.tree = TransLiterals.instance(context).translateTopLevelClass(env, env.tree, localMake);
1624             compileStates.put(env, CompileState.TRANSLITERALS);
1625 
1626             if (shouldStop(CompileState.TRANSPATTERNS))
1627                 return;
1628 
1629             if (scanner.hasPatterns) {
1630                 env.tree = TransPatterns.instance(context).translateTopLevelClass(env, env.tree, localMake);
1631             }
1632 
1633             compileStates.put(env, CompileState.TRANSPATTERNS);
1634 
1635             if (scanner.hasLambdas) {
1636                 if (shouldStop(CompileState.UNLAMBDA))
1637                     return;
1638 
1639                 env.tree = LambdaToMethod.instance(context).translateTopLevelClass(env, env.tree, localMake);
1640                 compileStates.put(env, CompileState.UNLAMBDA);
1641             }
1642 
1643             if (shouldStop(CompileState.LOWER))
1644                 return;
1645 
1646             if (sourceOutput) {
1647                 //emit standard Java source file, only for compilation
1648                 //units enumerated explicitly on the command line
1649                 JCClassDecl cdef = (JCClassDecl)env.tree;
1650                 if (untranslated instanceof JCClassDecl classDecl &&
1651                     rootClasses.contains(classDecl)) {
1652                     results.add(new Pair<>(env, cdef));
1653                 }
1654                 return;
1655             }
1656 
1657             //translate out inner classes
1658             List<JCTree> cdefs = lower.translateTopLevelClass(env, env.tree, localMake);
1659             compileStates.put(env, CompileState.LOWER);
1660 
1661             if (shouldStop(CompileState.LOWER))
1662                 return;
1663 
1664             //generate code for each class
1665             for (List<JCTree> l = cdefs; l.nonEmpty(); l = l.tail) {
1666                 JCClassDecl cdef = (JCClassDecl)l.head;
1667                 results.add(new Pair<>(env, cdef));
1668             }
1669         }
1670         finally {
1671             log.useSource(prev);
1672         }
1673 
1674     }
1675 
1676     /** Generates the source or class file for a list of classes.
1677      * The decision to generate a source file or a class file is
1678      * based upon the compiler's options.
1679      * Generation stops if an error occurs while writing files.
1680      */
1681     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) {
1682         generate(queue, null);
1683     }
1684 
1685     public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
1686         if (shouldStop(CompileState.GENERATE))
1687             return;
1688 
1689         for (Pair<Env<AttrContext>, JCClassDecl> x: queue) {
1690             Env<AttrContext> env = x.fst;
1691             JCClassDecl cdef = x.snd;
1692 
1693             if (verboseCompilePolicy) {
1694                 printNote("[generate " + (sourceOutput ? " source" : "code") + " " + cdef.sym + "]");
1695             }
1696 
1697             if (!taskListener.isEmpty()) {
1698                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1699                 taskListener.started(e);
1700             }
1701 
1702             JavaFileObject prev = log.useSource(env.enclClass.sym.sourcefile != null ?
1703                                       env.enclClass.sym.sourcefile :
1704                                       env.toplevel.sourcefile);
1705             try {
1706                 JavaFileObject file;
1707                 if (sourceOutput) {
1708                     file = printSource(env, cdef);
1709                 } else {
1710                     if (fileManager.hasLocation(StandardLocation.NATIVE_HEADER_OUTPUT)
1711                             && jniWriter.needsHeader(cdef.sym)) {
1712                         jniWriter.write(cdef.sym);
1713                     }
1714                     file = genCode(env, cdef);
1715                 }
1716                 if (results != null && file != null)
1717                     results.add(file);
1718             } catch (IOException
1719                     | UncheckedIOException
1720                     | FileSystemNotFoundException
1721                     | InvalidPathException
1722                     | ReadOnlyFileSystemException ex) {
1723                 log.error(cdef.pos(),
1724                           Errors.ClassCantWrite(cdef.sym, ex.getMessage()));
1725                 return;
1726             } finally {
1727                 log.useSource(prev);
1728             }
1729 
1730             if (!taskListener.isEmpty()) {
1731                 TaskEvent e = new TaskEvent(TaskEvent.Kind.GENERATE, env.toplevel, cdef.sym);
1732                 taskListener.finished(e);
1733             }
1734         }
1735     }
1736 
1737         // where
1738         Map<JCCompilationUnit, Queue<Env<AttrContext>>> groupByFile(Queue<Env<AttrContext>> envs) {
1739             // use a LinkedHashMap to preserve the order of the original list as much as possible
1740             Map<JCCompilationUnit, Queue<Env<AttrContext>>> map = new LinkedHashMap<>();
1741             for (Env<AttrContext> env: envs) {
1742                 Queue<Env<AttrContext>> sublist = map.get(env.toplevel);
1743                 if (sublist == null) {
1744                     sublist = new ListBuffer<>();
1745                     map.put(env.toplevel, sublist);
1746                 }
1747                 sublist.add(env);
1748             }
1749             return map;
1750         }
1751 
1752         JCClassDecl removeMethodBodies(JCClassDecl cdef) {
1753             final boolean isInterface = (cdef.mods.flags & Flags.INTERFACE) != 0;
1754             class MethodBodyRemover extends TreeTranslator {
1755                 @Override
1756                 public void visitMethodDef(JCMethodDecl tree) {
1757                     tree.mods.flags &= ~Flags.SYNCHRONIZED;
1758                     for (JCVariableDecl vd : tree.params)
1759                         vd.mods.flags &= ~Flags.FINAL;
1760                     tree.body = null;
1761                     super.visitMethodDef(tree);
1762                 }
1763                 @Override
1764                 public void visitVarDef(JCVariableDecl tree) {
1765                     if (tree.init != null && tree.init.type.constValue() == null)
1766                         tree.init = null;
1767                     super.visitVarDef(tree);
1768                 }
1769                 @Override
1770                 public void visitClassDef(JCClassDecl tree) {
1771                     ListBuffer<JCTree> newdefs = new ListBuffer<>();
1772                     for (List<JCTree> it = tree.defs; it.tail != null; it = it.tail) {
1773                         JCTree t = it.head;
1774                         switch (t.getTag()) {
1775                         case CLASSDEF:
1776                             if (isInterface ||
1777                                 (((JCClassDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1778                                 (((JCClassDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCClassDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1779                                 newdefs.append(t);
1780                             break;
1781                         case METHODDEF:
1782                             if (isInterface ||
1783                                 (((JCMethodDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1784                                 ((JCMethodDecl) t).sym.name == names.init ||
1785                                 (((JCMethodDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCMethodDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1786                                 newdefs.append(t);
1787                             break;
1788                         case VARDEF:
1789                             if (isInterface || (((JCVariableDecl) t).mods.flags & (Flags.PROTECTED|Flags.PUBLIC)) != 0 ||
1790                                 (((JCVariableDecl) t).mods.flags & (Flags.PRIVATE)) == 0 && ((JCVariableDecl) t).sym.packge().getQualifiedName() == names.java_lang)
1791                                 newdefs.append(t);
1792                             break;
1793                         default:
1794                             break;
1795                         }
1796                     }
1797                     tree.defs = newdefs.toList();
1798                     super.visitClassDef(tree);
1799                 }
1800             }
1801             MethodBodyRemover r = new MethodBodyRemover();
1802             return r.translate(cdef);
1803         }
1804 
1805     public void reportDeferredDiagnostics() {
1806         if (errorCount() == 0
1807                 && annotationProcessingOccurred
1808                 && implicitSourceFilesRead
1809                 && implicitSourcePolicy == ImplicitSourcePolicy.UNSET) {
1810             if (explicitAnnotationProcessingRequested())
1811                 log.warning(Warnings.ProcUseImplicit);
1812             else
1813                 log.warning(Warnings.ProcUseProcOrImplicit);
1814         }
1815         chk.reportDeferredDiagnostics();
1816         preview.reportDeferredDiagnostics();
1817         if (log.compressedOutput) {
1818             log.mandatoryNote(null, Notes.CompressedDiags);
1819         }
1820     }
1821 
1822     public void enterDone() {
1823         enterDone = true;
1824         annotate.enterDone();
1825     }
1826 
1827     public boolean isEnterDone() {
1828         return enterDone;
1829     }
1830 
1831     private Name readModuleName(JavaFileObject fo) {
1832         return parseAndGetName(fo, t -> {
1833             JCModuleDecl md = t.getModuleDecl();
1834 
1835             return md != null ? TreeInfo.fullName(md.getName()) : null;
1836         });
1837     }
1838 
1839     private Name findPackageInFile(JavaFileObject fo) {
1840         return parseAndGetName(fo, t -> t.getPackage() != null ?
1841                                         TreeInfo.fullName(t.getPackage().getPackageName()) : null);
1842     }
1843 
1844     private Name parseAndGetName(JavaFileObject fo,
1845                                  Function<JCTree.JCCompilationUnit, Name> tree2Name) {
1846         DiagnosticHandler dh = new DiscardDiagnosticHandler(log);
1847         JavaFileObject prevSource = log.useSource(fo);
1848         try {
1849             JCTree.JCCompilationUnit t = parse(fo, fo.getCharContent(false), true);
1850             return tree2Name.apply(t);
1851         } catch (IOException e) {
1852             return null;
1853         } finally {
1854             log.popDiagnosticHandler(dh);
1855             log.useSource(prevSource);
1856         }
1857     }
1858 
1859     /** Close the compiler, flushing the logs
1860      */
1861     public void close() {
1862         rootClasses = null;
1863         finder = null;
1864         reader = null;
1865         make = null;
1866         writer = null;
1867         enter = null;
1868         if (todo != null)
1869             todo.clear();
1870         todo = null;
1871         parserFactory = null;
1872         syms = null;
1873         source = null;
1874         attr = null;
1875         chk = null;
1876         gen = null;
1877         flow = null;
1878         transTypes = null;
1879         lower = null;
1880         annotate = null;
1881         types = null;
1882 
1883         log.flush();
1884         try {
1885             fileManager.flush();
1886         } catch (IOException e) {
1887             throw new Abort(e);
1888         } finally {
1889             if (names != null)
1890                 names.dispose();
1891             names = null;
1892 
1893             FatalError fatalError = null;
1894             for (Closeable c: closeables) {
1895                 try {
1896                     c.close();
1897                 } catch (IOException e) {
1898                     if (fatalError == null) {
1899                         JCDiagnostic msg = diagFactory.fragment(Fragments.FatalErrCantClose);
1900                         fatalError = new FatalError(msg, e);
1901                     } else {
1902                         fatalError.addSuppressed(e);
1903                     }
1904                 }
1905             }
1906             if (fatalError != null) {
1907                 throw fatalError;
1908             }
1909             closeables = List.nil();
1910         }
1911     }
1912 
1913     protected void printNote(String lines) {
1914         log.printRawLines(Log.WriterKind.NOTICE, lines);
1915     }
1916 
1917     /** Print numbers of errors and warnings.
1918      */
1919     public void printCount(String kind, int count) {
1920         if (count != 0) {
1921             String key;
1922             if (count == 1)
1923                 key = "count." + kind;
1924             else
1925                 key = "count." + kind + ".plural";
1926             log.printLines(WriterKind.ERROR, key, String.valueOf(count));
1927             log.flush(Log.WriterKind.ERROR);
1928         }
1929     }
1930 
1931     private void printSuppressedCount(int shown, int suppressed, String diagKey) {
1932         if (suppressed > 0) {
1933             int total = shown + suppressed;
1934             log.printLines(WriterKind.ERROR, diagKey,
1935                     String.valueOf(shown), String.valueOf(total));
1936             log.flush(Log.WriterKind.ERROR);
1937         }
1938     }
1939 
1940     private static long now() {
1941         return System.currentTimeMillis();
1942     }
1943 
1944     private static long elapsed(long then) {
1945         return now() - then;
1946     }
1947 
1948     public void newRound() {
1949         inputFiles.clear();
1950         todo.clear();
1951     }
1952 
1953     public interface InitialFileParserIntf {
1954         public List<JCCompilationUnit> parse(Iterable<JavaFileObject> files);
1955     }
1956 
1957     public static class InitialFileParser implements InitialFileParserIntf {
1958 
1959         public static final Key<InitialFileParserIntf> initialParserKey = new Key<>();
1960 
1961         public static InitialFileParserIntf instance(Context context) {
1962             InitialFileParserIntf instance = context.get(initialParserKey);
1963             if (instance == null)
1964                 instance = new InitialFileParser(context);
1965             return instance;
1966         }
1967 
1968         private final JavaCompiler compiler;
1969 
1970         private InitialFileParser(Context context) {
1971             context.put(initialParserKey, this);
1972             this.compiler = JavaCompiler.instance(context);
1973         }
1974 
1975         @Override
1976         public List<JCCompilationUnit> parse(Iterable<JavaFileObject> fileObjects) {
1977            return compiler.parseFiles(fileObjects, false);
1978         }
1979     }
1980 }