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