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