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