src/share/classes/com/sun/tools/javac/main/JavaCompiler.java

Thu, 31 Aug 2017 15:17:03 +0800

author
aoqi
date
Thu, 31 Aug 2017 15:17:03 +0800
changeset 2525
2eb010b6cb22
parent 2386
f8e84de96252
parent 0
959103a6100f
permissions
-rw-r--r--

merge

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

mercurial