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