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