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

Tue, 07 May 2013 14:27:30 -0700

author
jjg
date
Tue, 07 May 2013 14:27:30 -0700
changeset 1728
43c2f7cb9c76
parent 1690
76537856a54e
child 1755
ddb4a2bfcd82
permissions
-rw-r--r--

8004082: test/tools/javac/plugin/showtype/Test.java fails on windows: jtreg can't delete plugin.jar
Reviewed-by: vromero, mcimadamore

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

mercurial