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