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