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

Thu, 05 Sep 2013 11:27:27 +0200

author
jfranck
date
Thu, 05 Sep 2013 11:27:27 +0200
changeset 2007
a76c663a9cac
parent 1982
662a5188bded
child 2047
5f915a0c9615
permissions
-rw-r--r--

8023974: Drop 'implements Completer' and 'implements SourceCompleter' from ClassReader resp. JavaCompiler.
Reviewed-by: jjg, jfranck
Contributed-by: Andreas Lundblad <andreas.lundblad@oracle.com>

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

mercurial