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