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