src/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java

Tue, 29 Mar 2011 16:41:18 +0100

author
mcimadamore
date
Tue, 29 Mar 2011 16:41:18 +0100
changeset 951
de1c65ecfec2
parent 946
31e5cfc5a990
child 952
02ba4ff98742
permissions
-rw-r--r--

7027157: Project Coin: javac warnings for AutoCloseable.close throwing InterruptedException
Summary: javac should warn about use/declaration of AutoCloseable subclasses that can throw InterruptedException
Reviewed-by: jjg

duke@1 1 /*
jjg@815 2 * Copyright (c) 2005, 2011, 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.processing;
duke@1 27
jjg@50 28 import java.lang.reflect.*;
jjg@50 29 import java.util.*;
jjg@50 30 import java.util.regex.*;
jjg@50 31
jjg@50 32 import java.net.URL;
jjg@50 33 import java.io.Closeable;
jjg@50 34 import java.io.File;
jjg@50 35 import java.io.PrintWriter;
jjg@50 36 import java.io.IOException;
jjg@944 37 import java.io.StringWriter;
jjg@50 38 import java.net.MalformedURLException;
duke@1 39
duke@1 40 import javax.annotation.processing.*;
duke@1 41 import javax.lang.model.SourceVersion;
duke@1 42 import javax.lang.model.element.AnnotationMirror;
duke@1 43 import javax.lang.model.element.Element;
duke@1 44 import javax.lang.model.element.TypeElement;
duke@1 45 import javax.lang.model.element.PackageElement;
duke@1 46 import javax.lang.model.util.*;
duke@1 47 import javax.tools.JavaFileManager;
duke@1 48 import javax.tools.StandardJavaFileManager;
duke@1 49 import javax.tools.JavaFileObject;
duke@1 50 import javax.tools.DiagnosticListener;
jjg@50 51
jjg@50 52 import com.sun.source.util.TaskEvent;
jjg@50 53 import com.sun.source.util.TaskListener;
jjg@50 54 import com.sun.tools.javac.api.JavacTaskImpl;
jjg@722 55 import com.sun.tools.javac.api.JavacTrees;
jjg@50 56 import com.sun.tools.javac.code.*;
jjg@50 57 import com.sun.tools.javac.code.Symbol.*;
jjg@872 58 import com.sun.tools.javac.file.FSInfo;
jjg@50 59 import com.sun.tools.javac.file.JavacFileManager;
jjg@50 60 import com.sun.tools.javac.jvm.*;
jjg@50 61 import com.sun.tools.javac.main.JavaCompiler;
jjg@310 62 import com.sun.tools.javac.main.JavaCompiler.CompileState;
jjg@50 63 import com.sun.tools.javac.model.JavacElements;
jjg@50 64 import com.sun.tools.javac.model.JavacTypes;
jjg@50 65 import com.sun.tools.javac.parser.*;
jjg@50 66 import com.sun.tools.javac.tree.*;
jjg@50 67 import com.sun.tools.javac.tree.JCTree.*;
jjg@50 68 import com.sun.tools.javac.util.Abort;
jjg@816 69 import com.sun.tools.javac.util.Assert;
jjg@946 70 import com.sun.tools.javac.util.ClientCodeException;
jjg@50 71 import com.sun.tools.javac.util.Context;
jjg@483 72 import com.sun.tools.javac.util.Convert;
jjg@663 73 import com.sun.tools.javac.util.FatalError;
jjg@663 74 import com.sun.tools.javac.util.JCDiagnostic;
jjg@50 75 import com.sun.tools.javac.util.List;
jjg@50 76 import com.sun.tools.javac.util.Log;
mcimadamore@136 77 import com.sun.tools.javac.util.JavacMessages;
jjg@50 78 import com.sun.tools.javac.util.Name;
jjg@113 79 import com.sun.tools.javac.util.Names;
jjg@50 80 import com.sun.tools.javac.util.Options;
jjg@50 81
duke@1 82 import static javax.tools.StandardLocation.*;
jjg@664 83 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
jjg@700 84 import static com.sun.tools.javac.main.OptionName.*;
jjg@700 85 import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
duke@1 86
duke@1 87 /**
duke@1 88 * Objects of this class hold and manage the state needed to support
duke@1 89 * annotation processing.
duke@1 90 *
jjg@581 91 * <p><b>This is NOT part of any supported API.
duke@1 92 * If you write code that depends on this, you do so at your own risk.
duke@1 93 * This code and its internal interfaces are subject to change or
duke@1 94 * deletion without notice.</b>
duke@1 95 */
duke@1 96 public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
duke@1 97 Options options;
duke@1 98
duke@1 99 private final boolean printProcessorInfo;
duke@1 100 private final boolean printRounds;
duke@1 101 private final boolean verbose;
duke@1 102 private final boolean lint;
duke@1 103 private final boolean procOnly;
duke@1 104 private final boolean fatalErrors;
jjg@614 105 private final boolean werror;
jjg@664 106 private final boolean showResolveErrors;
jjg@310 107 private boolean foundTypeProcessors;
duke@1 108
duke@1 109 private final JavacFiler filer;
duke@1 110 private final JavacMessager messager;
duke@1 111 private final JavacElements elementUtils;
duke@1 112 private final JavacTypes typeUtils;
duke@1 113
duke@1 114 /**
duke@1 115 * Holds relevant state history of which processors have been
duke@1 116 * used.
duke@1 117 */
duke@1 118 private DiscoveredProcessors discoveredProcs;
duke@1 119
duke@1 120 /**
duke@1 121 * Map of processor-specific options.
duke@1 122 */
duke@1 123 private final Map<String, String> processorOptions;
duke@1 124
duke@1 125 /**
duke@1 126 */
duke@1 127 private final Set<String> unmatchedProcessorOptions;
duke@1 128
duke@1 129 /**
duke@1 130 * Annotations implicitly processed and claimed by javac.
duke@1 131 */
duke@1 132 private final Set<String> platformAnnotations;
duke@1 133
duke@1 134 /**
duke@1 135 * Set of packages given on command line.
duke@1 136 */
duke@1 137 private Set<PackageSymbol> specifiedPackages = Collections.emptySet();
duke@1 138
duke@1 139 /** The log to be used for error reporting.
duke@1 140 */
duke@1 141 Log log;
duke@1 142
jjg@663 143 /** Diagnostic factory.
jjg@663 144 */
jjg@663 145 JCDiagnostic.Factory diags;
jjg@663 146
duke@1 147 /**
duke@1 148 * Source level of the compile.
duke@1 149 */
duke@1 150 Source source;
duke@1 151
jjg@372 152 private ClassLoader processorClassLoader;
jjg@372 153
mcimadamore@136 154 /**
mcimadamore@136 155 * JavacMessages object used for localization
mcimadamore@136 156 */
mcimadamore@136 157 private JavacMessages messages;
mcimadamore@136 158
duke@1 159 private Context context;
duke@1 160
mcimadamore@136 161 public JavacProcessingEnvironment(Context context, Iterable<? extends Processor> processors) {
duke@1 162 this.context = context;
duke@1 163 log = Log.instance(context);
duke@1 164 source = Source.instance(context);
jjg@663 165 diags = JCDiagnostic.Factory.instance(context);
jjg@663 166 options = Options.instance(context);
jjg@700 167 printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
jjg@700 168 printRounds = options.isSet(XPRINTROUNDS);
jjg@700 169 verbose = options.isSet(VERBOSE);
jjg@700 170 lint = Lint.instance(context).isEnabled(PROCESSING);
jjg@700 171 procOnly = options.isSet(PROC, "only") || options.isSet(XPRINT);
jjg@700 172 fatalErrors = options.isSet("fatalEnterError");
jjg@700 173 showResolveErrors = options.isSet("showResolveErrors");
jjg@700 174 werror = options.isSet(WERROR);
duke@1 175 platformAnnotations = initPlatformAnnotations();
jjg@310 176 foundTypeProcessors = false;
duke@1 177
jjg@706 178 // Initialize services before any processors are initialized
duke@1 179 // in case processors use them.
duke@1 180 filer = new JavacFiler(context);
duke@1 181 messager = new JavacMessager(context, this);
jjg@706 182 elementUtils = JavacElements.instance(context);
jjg@706 183 typeUtils = JavacTypes.instance(context);
duke@1 184 processorOptions = initProcessorOptions(context);
duke@1 185 unmatchedProcessorOptions = initUnmatchedProcessorOptions();
mcimadamore@136 186 messages = JavacMessages.instance(context);
duke@1 187 initProcessorIterator(context, processors);
duke@1 188 }
duke@1 189
duke@1 190 private Set<String> initPlatformAnnotations() {
duke@1 191 Set<String> platformAnnotations = new HashSet<String>();
duke@1 192 platformAnnotations.add("java.lang.Deprecated");
duke@1 193 platformAnnotations.add("java.lang.Override");
duke@1 194 platformAnnotations.add("java.lang.SuppressWarnings");
duke@1 195 platformAnnotations.add("java.lang.annotation.Documented");
duke@1 196 platformAnnotations.add("java.lang.annotation.Inherited");
duke@1 197 platformAnnotations.add("java.lang.annotation.Retention");
duke@1 198 platformAnnotations.add("java.lang.annotation.Target");
duke@1 199 return Collections.unmodifiableSet(platformAnnotations);
duke@1 200 }
duke@1 201
duke@1 202 private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
duke@1 203 Log log = Log.instance(context);
duke@1 204 Iterator<? extends Processor> processorIterator;
duke@1 205
jjg@700 206 if (options.isSet(XPRINT)) {
duke@1 207 try {
duke@1 208 Processor processor = PrintingProcessor.class.newInstance();
duke@1 209 processorIterator = List.of(processor).iterator();
duke@1 210 } catch (Throwable t) {
duke@1 211 AssertionError assertError =
duke@1 212 new AssertionError("Problem instantiating PrintingProcessor.");
duke@1 213 assertError.initCause(t);
duke@1 214 throw assertError;
duke@1 215 }
duke@1 216 } else if (processors != null) {
duke@1 217 processorIterator = processors.iterator();
duke@1 218 } else {
jjg@700 219 String processorNames = options.get(PROCESSOR);
duke@1 220 JavaFileManager fileManager = context.get(JavaFileManager.class);
duke@1 221 try {
duke@1 222 // If processorpath is not explicitly set, use the classpath.
jjg@372 223 processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
duke@1 224 ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
duke@1 225 : fileManager.getClassLoader(CLASS_PATH);
duke@1 226
duke@1 227 /*
duke@1 228 * If the "-processor" option is used, search the appropriate
duke@1 229 * path for the named class. Otherwise, use a service
duke@1 230 * provider mechanism to create the processor iterator.
duke@1 231 */
duke@1 232 if (processorNames != null) {
jjg@372 233 processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
duke@1 234 } else {
jjg@372 235 processorIterator = new ServiceIterator(processorClassLoader, log);
duke@1 236 }
duke@1 237 } catch (SecurityException e) {
duke@1 238 /*
duke@1 239 * A security exception will occur if we can't create a classloader.
duke@1 240 * Ignore the exception if, with hindsight, we didn't need it anyway
duke@1 241 * (i.e. no processor was specified either explicitly, or implicitly,
duke@1 242 * in service configuration file.) Otherwise, we cannot continue.
duke@1 243 */
duke@1 244 processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader", e);
duke@1 245 }
duke@1 246 }
duke@1 247 discoveredProcs = new DiscoveredProcessors(processorIterator);
duke@1 248 }
duke@1 249
duke@1 250 /**
duke@1 251 * Returns an empty processor iterator if no processors are on the
duke@1 252 * relevant path, otherwise if processors are present, logs an
duke@1 253 * error. Called when a service loader is unavailable for some
duke@1 254 * reason, either because a service loader class cannot be found
duke@1 255 * or because a security policy prevents class loaders from being
duke@1 256 * created.
duke@1 257 *
duke@1 258 * @param key The resource key to use to log an error message
duke@1 259 * @param e If non-null, pass this exception to Abort
duke@1 260 */
duke@1 261 private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
duke@1 262 JavaFileManager fileManager = context.get(JavaFileManager.class);
duke@1 263
duke@1 264 if (fileManager instanceof JavacFileManager) {
duke@1 265 StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
duke@1 266 Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
duke@1 267 ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
duke@1 268 : standardFileManager.getLocation(CLASS_PATH);
duke@1 269
jjg@700 270 if (needClassLoader(options.get(PROCESSOR), workingPath) )
duke@1 271 handleException(key, e);
duke@1 272
duke@1 273 } else {
duke@1 274 handleException(key, e);
duke@1 275 }
duke@1 276
duke@1 277 java.util.List<Processor> pl = Collections.emptyList();
duke@1 278 return pl.iterator();
duke@1 279 }
duke@1 280
duke@1 281 /**
duke@1 282 * Handle a security exception thrown during initializing the
duke@1 283 * Processor iterator.
duke@1 284 */
duke@1 285 private void handleException(String key, Exception e) {
duke@1 286 if (e != null) {
duke@1 287 log.error(key, e.getLocalizedMessage());
duke@1 288 throw new Abort(e);
duke@1 289 } else {
duke@1 290 log.error(key);
duke@1 291 throw new Abort();
duke@1 292 }
duke@1 293 }
duke@1 294
duke@1 295 /**
duke@1 296 * Use a service loader appropriate for the platform to provide an
duke@1 297 * iterator over annotations processors. If
duke@1 298 * java.util.ServiceLoader is present use it, otherwise, use
duke@1 299 * sun.misc.Service, otherwise fail if a loader is needed.
duke@1 300 */
duke@1 301 private class ServiceIterator implements Iterator<Processor> {
duke@1 302 // The to-be-wrapped iterator.
duke@1 303 private Iterator<?> iterator;
duke@1 304 private Log log;
darcy@382 305 private Class<?> loaderClass;
darcy@382 306 private boolean jusl;
darcy@382 307 private Object loader;
duke@1 308
duke@1 309 ServiceIterator(ClassLoader classLoader, Log log) {
duke@1 310 String loadMethodName;
duke@1 311
duke@1 312 this.log = log;
duke@1 313 try {
duke@1 314 try {
duke@1 315 loaderClass = Class.forName("java.util.ServiceLoader");
duke@1 316 loadMethodName = "load";
duke@1 317 jusl = true;
duke@1 318 } catch (ClassNotFoundException cnfe) {
duke@1 319 try {
duke@1 320 loaderClass = Class.forName("sun.misc.Service");
duke@1 321 loadMethodName = "providers";
duke@1 322 jusl = false;
duke@1 323 } catch (ClassNotFoundException cnfe2) {
duke@1 324 // Fail softly if a loader is not actually needed.
duke@1 325 this.iterator = handleServiceLoaderUnavailability("proc.no.service",
duke@1 326 null);
duke@1 327 return;
duke@1 328 }
duke@1 329 }
duke@1 330
duke@1 331 // java.util.ServiceLoader.load or sun.misc.Service.providers
duke@1 332 Method loadMethod = loaderClass.getMethod(loadMethodName,
duke@1 333 Class.class,
duke@1 334 ClassLoader.class);
duke@1 335
duke@1 336 Object result = loadMethod.invoke(null,
duke@1 337 Processor.class,
duke@1 338 classLoader);
duke@1 339
duke@1 340 // For java.util.ServiceLoader, we have to call another
duke@1 341 // method to get the iterator.
duke@1 342 if (jusl) {
darcy@382 343 loader = result; // Store ServiceLoader to call reload later
duke@1 344 Method m = loaderClass.getMethod("iterator");
duke@1 345 result = m.invoke(result); // serviceLoader.iterator();
duke@1 346 }
duke@1 347
duke@1 348 // The result should now be an iterator.
duke@1 349 this.iterator = (Iterator<?>) result;
duke@1 350 } catch (Throwable t) {
duke@1 351 log.error("proc.service.problem");
duke@1 352 throw new Abort(t);
duke@1 353 }
duke@1 354 }
duke@1 355
duke@1 356 public boolean hasNext() {
duke@1 357 try {
duke@1 358 return iterator.hasNext();
duke@1 359 } catch (Throwable t) {
duke@1 360 if ("ServiceConfigurationError".
duke@1 361 equals(t.getClass().getSimpleName())) {
duke@1 362 log.error("proc.bad.config.file", t.getLocalizedMessage());
duke@1 363 }
duke@1 364 throw new Abort(t);
duke@1 365 }
duke@1 366 }
duke@1 367
duke@1 368 public Processor next() {
duke@1 369 try {
duke@1 370 return (Processor)(iterator.next());
duke@1 371 } catch (Throwable t) {
duke@1 372 if ("ServiceConfigurationError".
duke@1 373 equals(t.getClass().getSimpleName())) {
duke@1 374 log.error("proc.bad.config.file", t.getLocalizedMessage());
duke@1 375 } else {
duke@1 376 log.error("proc.processor.constructor.error", t.getLocalizedMessage());
duke@1 377 }
duke@1 378 throw new Abort(t);
duke@1 379 }
duke@1 380 }
duke@1 381
duke@1 382 public void remove() {
duke@1 383 throw new UnsupportedOperationException();
duke@1 384 }
darcy@382 385
darcy@382 386 public void close() {
darcy@382 387 if (jusl) {
darcy@382 388 try {
darcy@382 389 // Call java.util.ServiceLoader.reload
darcy@382 390 Method reloadMethod = loaderClass.getMethod("reload");
darcy@382 391 reloadMethod.invoke(loader);
darcy@382 392 } catch(Exception e) {
darcy@382 393 ; // Ignore problems during a call to reload.
darcy@382 394 }
darcy@382 395 }
darcy@382 396 }
duke@1 397 }
duke@1 398
duke@1 399
duke@1 400 private static class NameProcessIterator implements Iterator<Processor> {
duke@1 401 Processor nextProc = null;
duke@1 402 Iterator<String> names;
duke@1 403 ClassLoader processorCL;
duke@1 404 Log log;
duke@1 405
duke@1 406 NameProcessIterator(String names, ClassLoader processorCL, Log log) {
duke@1 407 this.names = Arrays.asList(names.split(",")).iterator();
duke@1 408 this.processorCL = processorCL;
duke@1 409 this.log = log;
duke@1 410 }
duke@1 411
duke@1 412 public boolean hasNext() {
duke@1 413 if (nextProc != null)
duke@1 414 return true;
duke@1 415 else {
duke@1 416 if (!names.hasNext())
duke@1 417 return false;
duke@1 418 else {
duke@1 419 String processorName = names.next();
duke@1 420
duke@1 421 Processor processor;
duke@1 422 try {
duke@1 423 try {
duke@1 424 processor =
duke@1 425 (Processor) (processorCL.loadClass(processorName).newInstance());
duke@1 426 } catch (ClassNotFoundException cnfe) {
duke@1 427 log.error("proc.processor.not.found", processorName);
duke@1 428 return false;
duke@1 429 } catch (ClassCastException cce) {
duke@1 430 log.error("proc.processor.wrong.type", processorName);
duke@1 431 return false;
duke@1 432 } catch (Exception e ) {
duke@1 433 log.error("proc.processor.cant.instantiate", processorName);
duke@1 434 return false;
duke@1 435 }
jjg@946 436 } catch(ClientCodeException e) {
jjg@946 437 throw e;
duke@1 438 } catch(Throwable t) {
duke@1 439 throw new AnnotationProcessingError(t);
duke@1 440 }
duke@1 441 nextProc = processor;
duke@1 442 return true;
duke@1 443 }
duke@1 444
duke@1 445 }
duke@1 446 }
duke@1 447
duke@1 448 public Processor next() {
duke@1 449 if (hasNext()) {
duke@1 450 Processor p = nextProc;
duke@1 451 nextProc = null;
duke@1 452 return p;
duke@1 453 } else
duke@1 454 throw new NoSuchElementException();
duke@1 455 }
duke@1 456
duke@1 457 public void remove () {
duke@1 458 throw new UnsupportedOperationException();
duke@1 459 }
duke@1 460 }
duke@1 461
duke@1 462 public boolean atLeastOneProcessor() {
duke@1 463 return discoveredProcs.iterator().hasNext();
duke@1 464 }
duke@1 465
duke@1 466 private Map<String, String> initProcessorOptions(Context context) {
duke@1 467 Options options = Options.instance(context);
duke@1 468 Set<String> keySet = options.keySet();
duke@1 469 Map<String, String> tempOptions = new LinkedHashMap<String, String>();
duke@1 470
duke@1 471 for(String key : keySet) {
duke@1 472 if (key.startsWith("-A") && key.length() > 2) {
duke@1 473 int sepIndex = key.indexOf('=');
duke@1 474 String candidateKey = null;
duke@1 475 String candidateValue = null;
duke@1 476
duke@1 477 if (sepIndex == -1)
duke@1 478 candidateKey = key.substring(2);
duke@1 479 else if (sepIndex >= 3) {
duke@1 480 candidateKey = key.substring(2, sepIndex);
duke@1 481 candidateValue = (sepIndex < key.length()-1)?
duke@1 482 key.substring(sepIndex+1) : null;
duke@1 483 }
duke@1 484 tempOptions.put(candidateKey, candidateValue);
duke@1 485 }
duke@1 486 }
duke@1 487
duke@1 488 return Collections.unmodifiableMap(tempOptions);
duke@1 489 }
duke@1 490
duke@1 491 private Set<String> initUnmatchedProcessorOptions() {
duke@1 492 Set<String> unmatchedProcessorOptions = new HashSet<String>();
duke@1 493 unmatchedProcessorOptions.addAll(processorOptions.keySet());
duke@1 494 return unmatchedProcessorOptions;
duke@1 495 }
duke@1 496
duke@1 497 /**
duke@1 498 * State about how a processor has been used by the tool. If a
duke@1 499 * processor has been used on a prior round, its process method is
duke@1 500 * called on all subsequent rounds, perhaps with an empty set of
duke@1 501 * annotations to process. The {@code annotatedSupported} method
duke@1 502 * caches the supported annotation information from the first (and
duke@1 503 * only) getSupportedAnnotationTypes call to the processor.
duke@1 504 */
duke@1 505 static class ProcessorState {
duke@1 506 public Processor processor;
duke@1 507 public boolean contributed;
duke@1 508 private ArrayList<Pattern> supportedAnnotationPatterns;
duke@1 509 private ArrayList<String> supportedOptionNames;
duke@1 510
duke@1 511 ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
duke@1 512 processor = p;
duke@1 513 contributed = false;
duke@1 514
duke@1 515 try {
duke@1 516 processor.init(env);
duke@1 517
duke@1 518 checkSourceVersionCompatibility(source, log);
duke@1 519
duke@1 520 supportedAnnotationPatterns = new ArrayList<Pattern>();
duke@1 521 for (String importString : processor.getSupportedAnnotationTypes()) {
duke@1 522 supportedAnnotationPatterns.add(importStringToPattern(importString,
duke@1 523 processor,
duke@1 524 log));
duke@1 525 }
duke@1 526
duke@1 527 supportedOptionNames = new ArrayList<String>();
duke@1 528 for (String optionName : processor.getSupportedOptions() ) {
duke@1 529 if (checkOptionName(optionName, log))
duke@1 530 supportedOptionNames.add(optionName);
duke@1 531 }
duke@1 532
jjg@946 533 } catch (ClientCodeException e) {
jjg@946 534 throw e;
duke@1 535 } catch (Throwable t) {
duke@1 536 throw new AnnotationProcessingError(t);
duke@1 537 }
duke@1 538 }
duke@1 539
duke@1 540 /**
duke@1 541 * Checks whether or not a processor's source version is
duke@1 542 * compatible with the compilation source version. The
duke@1 543 * processor's source version needs to be greater than or
duke@1 544 * equal to the source version of the compile.
duke@1 545 */
duke@1 546 private void checkSourceVersionCompatibility(Source source, Log log) {
duke@1 547 SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
duke@1 548
duke@1 549 if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 ) {
duke@1 550 log.warning("proc.processor.incompatible.source.version",
duke@1 551 procSourceVersion,
duke@1 552 processor.getClass().getName(),
duke@1 553 source.name);
duke@1 554 }
duke@1 555 }
duke@1 556
duke@1 557 private boolean checkOptionName(String optionName, Log log) {
duke@1 558 boolean valid = isValidOptionName(optionName);
duke@1 559 if (!valid)
duke@1 560 log.error("proc.processor.bad.option.name",
duke@1 561 optionName,
duke@1 562 processor.getClass().getName());
duke@1 563 return valid;
duke@1 564 }
duke@1 565
duke@1 566 public boolean annotationSupported(String annotationName) {
duke@1 567 for(Pattern p: supportedAnnotationPatterns) {
duke@1 568 if (p.matcher(annotationName).matches())
duke@1 569 return true;
duke@1 570 }
duke@1 571 return false;
duke@1 572 }
duke@1 573
duke@1 574 /**
duke@1 575 * Remove options that are matched by this processor.
duke@1 576 */
duke@1 577 public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) {
duke@1 578 unmatchedProcessorOptions.removeAll(supportedOptionNames);
duke@1 579 }
duke@1 580 }
duke@1 581
duke@1 582 // TODO: These two classes can probably be rewritten better...
duke@1 583 /**
duke@1 584 * This class holds information about the processors that have
duke@1 585 * been discoverd so far as well as the means to discover more, if
duke@1 586 * necessary. A single iterator should be used per round of
duke@1 587 * annotation processing. The iterator first visits already
darcy@382 588 * discovered processors then fails over to the service provider
duke@1 589 * mechanism if additional queries are made.
duke@1 590 */
duke@1 591 class DiscoveredProcessors implements Iterable<ProcessorState> {
duke@1 592
duke@1 593 class ProcessorStateIterator implements Iterator<ProcessorState> {
duke@1 594 DiscoveredProcessors psi;
duke@1 595 Iterator<ProcessorState> innerIter;
duke@1 596 boolean onProcInterator;
duke@1 597
duke@1 598 ProcessorStateIterator(DiscoveredProcessors psi) {
duke@1 599 this.psi = psi;
duke@1 600 this.innerIter = psi.procStateList.iterator();
duke@1 601 this.onProcInterator = false;
duke@1 602 }
duke@1 603
duke@1 604 public ProcessorState next() {
duke@1 605 if (!onProcInterator) {
duke@1 606 if (innerIter.hasNext())
duke@1 607 return innerIter.next();
duke@1 608 else
duke@1 609 onProcInterator = true;
duke@1 610 }
duke@1 611
duke@1 612 if (psi.processorIterator.hasNext()) {
duke@1 613 ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
duke@1 614 log, source, JavacProcessingEnvironment.this);
duke@1 615 psi.procStateList.add(ps);
duke@1 616 return ps;
duke@1 617 } else
duke@1 618 throw new NoSuchElementException();
duke@1 619 }
duke@1 620
duke@1 621 public boolean hasNext() {
duke@1 622 if (onProcInterator)
duke@1 623 return psi.processorIterator.hasNext();
duke@1 624 else
duke@1 625 return innerIter.hasNext() || psi.processorIterator.hasNext();
duke@1 626 }
duke@1 627
duke@1 628 public void remove () {
duke@1 629 throw new UnsupportedOperationException();
duke@1 630 }
duke@1 631
duke@1 632 /**
duke@1 633 * Run all remaining processors on the procStateList that
duke@1 634 * have not already run this round with an empty set of
duke@1 635 * annotations.
duke@1 636 */
duke@1 637 public void runContributingProcs(RoundEnvironment re) {
duke@1 638 if (!onProcInterator) {
duke@1 639 Set<TypeElement> emptyTypeElements = Collections.emptySet();
duke@1 640 while(innerIter.hasNext()) {
duke@1 641 ProcessorState ps = innerIter.next();
duke@1 642 if (ps.contributed)
duke@1 643 callProcessor(ps.processor, emptyTypeElements, re);
duke@1 644 }
duke@1 645 }
duke@1 646 }
duke@1 647 }
duke@1 648
duke@1 649 Iterator<? extends Processor> processorIterator;
duke@1 650 ArrayList<ProcessorState> procStateList;
duke@1 651
duke@1 652 public ProcessorStateIterator iterator() {
duke@1 653 return new ProcessorStateIterator(this);
duke@1 654 }
duke@1 655
duke@1 656 DiscoveredProcessors(Iterator<? extends Processor> processorIterator) {
duke@1 657 this.processorIterator = processorIterator;
duke@1 658 this.procStateList = new ArrayList<ProcessorState>();
duke@1 659 }
darcy@382 660
darcy@382 661 /**
darcy@382 662 * Free jar files, etc. if using a service loader.
darcy@382 663 */
darcy@382 664 public void close() {
darcy@382 665 if (processorIterator != null &&
darcy@382 666 processorIterator instanceof ServiceIterator) {
darcy@382 667 ((ServiceIterator) processorIterator).close();
darcy@382 668 }
darcy@382 669 }
duke@1 670 }
duke@1 671
duke@1 672 private void discoverAndRunProcs(Context context,
duke@1 673 Set<TypeElement> annotationsPresent,
duke@1 674 List<ClassSymbol> topLevelClasses,
duke@1 675 List<PackageSymbol> packageInfoFiles) {
duke@1 676 Map<String, TypeElement> unmatchedAnnotations =
duke@1 677 new HashMap<String, TypeElement>(annotationsPresent.size());
duke@1 678
duke@1 679 for(TypeElement a : annotationsPresent) {
duke@1 680 unmatchedAnnotations.put(a.getQualifiedName().toString(),
duke@1 681 a);
duke@1 682 }
duke@1 683
duke@1 684 // Give "*" processors a chance to match
duke@1 685 if (unmatchedAnnotations.size() == 0)
duke@1 686 unmatchedAnnotations.put("", null);
duke@1 687
duke@1 688 DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
duke@1 689 // TODO: Create proper argument values; need past round
duke@1 690 // information to fill in this constructor. Note that the 1
duke@1 691 // st round of processing could be the last round if there
duke@1 692 // were parse errors on the initial source files; however, we
duke@1 693 // are not doing processing in that case.
duke@1 694
duke@1 695 Set<Element> rootElements = new LinkedHashSet<Element>();
duke@1 696 rootElements.addAll(topLevelClasses);
duke@1 697 rootElements.addAll(packageInfoFiles);
duke@1 698 rootElements = Collections.unmodifiableSet(rootElements);
duke@1 699
duke@1 700 RoundEnvironment renv = new JavacRoundEnvironment(false,
duke@1 701 false,
duke@1 702 rootElements,
duke@1 703 JavacProcessingEnvironment.this);
duke@1 704
duke@1 705 while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
duke@1 706 ProcessorState ps = psi.next();
duke@1 707 Set<String> matchedNames = new HashSet<String>();
duke@1 708 Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();
darcy@506 709
darcy@506 710 for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) {
darcy@506 711 String unmatchedAnnotationName = entry.getKey();
duke@1 712 if (ps.annotationSupported(unmatchedAnnotationName) ) {
duke@1 713 matchedNames.add(unmatchedAnnotationName);
darcy@506 714 TypeElement te = entry.getValue();
duke@1 715 if (te != null)
duke@1 716 typeElements.add(te);
duke@1 717 }
duke@1 718 }
duke@1 719
duke@1 720 if (matchedNames.size() > 0 || ps.contributed) {
duke@1 721 boolean processingResult = callProcessor(ps.processor, typeElements, renv);
duke@1 722 ps.contributed = true;
duke@1 723 ps.removeSupportedOptions(unmatchedProcessorOptions);
duke@1 724
duke@1 725 if (printProcessorInfo || verbose) {
jjg@604 726 log.printNoteLines("x.print.processor.info",
jjg@604 727 ps.processor.getClass().getName(),
jjg@604 728 matchedNames.toString(),
jjg@604 729 processingResult);
duke@1 730 }
duke@1 731
duke@1 732 if (processingResult) {
duke@1 733 unmatchedAnnotations.keySet().removeAll(matchedNames);
duke@1 734 }
duke@1 735
duke@1 736 }
duke@1 737 }
duke@1 738 unmatchedAnnotations.remove("");
duke@1 739
duke@1 740 if (lint && unmatchedAnnotations.size() > 0) {
duke@1 741 // Remove annotations processed by javac
duke@1 742 unmatchedAnnotations.keySet().removeAll(platformAnnotations);
duke@1 743 if (unmatchedAnnotations.size() > 0) {
duke@1 744 log = Log.instance(context);
duke@1 745 log.warning("proc.annotations.without.processors",
duke@1 746 unmatchedAnnotations.keySet());
duke@1 747 }
duke@1 748 }
duke@1 749
duke@1 750 // Run contributing processors that haven't run yet
duke@1 751 psi.runContributingProcs(renv);
duke@1 752
duke@1 753 // Debugging
jjg@700 754 if (options.isSet("displayFilerState"))
duke@1 755 filer.displayState();
duke@1 756 }
duke@1 757
duke@1 758 /**
duke@1 759 * Computes the set of annotations on the symbol in question.
duke@1 760 * Leave class public for external testing purposes.
duke@1 761 */
duke@1 762 public static class ComputeAnnotationSet extends
darcy@575 763 ElementScanner7<Set<TypeElement>, Set<TypeElement>> {
duke@1 764 final Elements elements;
duke@1 765
duke@1 766 public ComputeAnnotationSet(Elements elements) {
duke@1 767 super();
duke@1 768 this.elements = elements;
duke@1 769 }
duke@1 770
duke@1 771 @Override
duke@1 772 public Set<TypeElement> visitPackage(PackageElement e, Set<TypeElement> p) {
duke@1 773 // Don't scan enclosed elements of a package
duke@1 774 return p;
duke@1 775 }
duke@1 776
duke@1 777 @Override
jjg@620 778 public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
duke@1 779 for (AnnotationMirror annotationMirror :
duke@1 780 elements.getAllAnnotationMirrors(e) ) {
duke@1 781 Element e2 = annotationMirror.getAnnotationType().asElement();
duke@1 782 p.add((TypeElement) e2);
duke@1 783 }
duke@1 784 return super.scan(e, p);
duke@1 785 }
duke@1 786 }
duke@1 787
duke@1 788 private boolean callProcessor(Processor proc,
duke@1 789 Set<? extends TypeElement> tes,
duke@1 790 RoundEnvironment renv) {
duke@1 791 try {
duke@1 792 return proc.process(tes, renv);
duke@1 793 } catch (CompletionFailure ex) {
duke@1 794 StringWriter out = new StringWriter();
duke@1 795 ex.printStackTrace(new PrintWriter(out));
jjg@12 796 log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
duke@1 797 return false;
jjg@946 798 } catch (ClientCodeException e) {
jjg@946 799 throw e;
duke@1 800 } catch (Throwable t) {
duke@1 801 throw new AnnotationProcessingError(t);
duke@1 802 }
duke@1 803 }
duke@1 804
jjg@620 805 /**
jjg@620 806 * Helper object for a single round of annotation processing.
jjg@620 807 */
jjg@620 808 class Round {
jjg@620 809 /** The round number. */
jjg@620 810 final int number;
jjg@620 811 /** The context for the round. */
jjg@620 812 final Context context;
jjg@620 813 /** The compiler for the round. */
jjg@620 814 final JavaCompiler compiler;
jjg@620 815 /** The log for the round. */
jjg@620 816 final Log log;
jjg@642 817
jjg@642 818 /** The ASTs to be compiled. */
jjg@642 819 List<JCCompilationUnit> roots;
jjg@642 820 /** The classes to be compiler that have were generated. */
jjg@642 821 Map<String, JavaFileObject> genClassFiles;
jjg@620 822
jjg@620 823 /** The set of annotations to be processed this round. */
jjg@620 824 Set<TypeElement> annotationsPresent;
jjg@620 825 /** The set of top level classes to be processed this round. */
jjg@620 826 List<ClassSymbol> topLevelClasses;
jjg@620 827 /** The set of package-info files to be processed this round. */
jjg@620 828 List<PackageSymbol> packageInfoFiles;
jjg@620 829
jjg@933 830 /** The number of Messager errors generated in this round. */
jjg@933 831 int nMessagerErrors;
jjg@933 832
jjg@642 833 /** Create a round (common code). */
jjg@933 834 private Round(Context context, int number, int priorErrors, int priorWarnings) {
jjg@620 835 this.context = context;
jjg@620 836 this.number = number;
jjg@642 837
jjg@620 838 compiler = JavaCompiler.instance(context);
jjg@620 839 log = Log.instance(context);
jjg@933 840 log.nerrors = priorErrors;
jjg@898 841 log.nwarnings += priorWarnings;
jjg@664 842 log.deferDiagnostics = true;
jjg@620 843
jjg@620 844 // the following is for the benefit of JavacProcessingEnvironment.getContext()
jjg@620 845 JavacProcessingEnvironment.this.context = context;
jjg@620 846
jjg@620 847 // the following will be populated as needed
jjg@620 848 topLevelClasses = List.nil();
jjg@620 849 packageInfoFiles = List.nil();
jjg@620 850 }
jjg@620 851
jjg@642 852 /** Create the first round. */
jjg@642 853 Round(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols) {
jjg@933 854 this(context, 1, 0, 0);
jjg@642 855 this.roots = roots;
jjg@642 856 genClassFiles = new HashMap<String,JavaFileObject>();
jjg@642 857
jjg@642 858 compiler.todo.clear(); // free the compiler's resources
jjg@642 859
jjg@642 860 // The reverse() in the following line is to maintain behavioural
jjg@642 861 // compatibility with the previous revision of the code. Strictly speaking,
jjg@642 862 // it should not be necessary, but a javah golden file test fails without it.
jjg@642 863 topLevelClasses =
jjg@642 864 getTopLevelClasses(roots).prependList(classSymbols.reverse());
jjg@642 865
jjg@642 866 packageInfoFiles = getPackageInfoFiles(roots);
jjg@642 867
jjg@642 868 findAnnotationsPresent();
jjg@642 869 }
jjg@642 870
jjg@642 871 /** Create a new round. */
jjg@642 872 private Round(Round prev,
jjg@663 873 Set<JavaFileObject> newSourceFiles, Map<String,JavaFileObject> newClassFiles) {
jjg@933 874 this(prev.nextContext(),
jjg@933 875 prev.number+1,
jjg@933 876 prev.nMessagerErrors,
jjg@933 877 prev.compiler.log.nwarnings);
jjg@642 878 this.genClassFiles = prev.genClassFiles;
jjg@642 879
jjg@642 880 List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles);
jjg@642 881 roots = cleanTrees(prev.roots).appendList(parsedFiles);
jjg@642 882
jjg@642 883 // Check for errors after parsing
jjg@642 884 if (unrecoverableError())
jjg@642 885 return;
jjg@642 886
jjg@642 887 enterClassFiles(genClassFiles);
jjg@642 888 List<ClassSymbol> newClasses = enterClassFiles(newClassFiles);
jjg@642 889 genClassFiles.putAll(newClassFiles);
jjg@642 890 enterTrees(roots);
jjg@642 891
jjg@642 892 if (unrecoverableError())
jjg@642 893 return;
jjg@642 894
jjg@642 895 topLevelClasses = join(
jjg@642 896 getTopLevelClasses(parsedFiles),
jjg@642 897 getTopLevelClassesFromClasses(newClasses));
jjg@642 898
jjg@642 899 packageInfoFiles = join(
jjg@642 900 getPackageInfoFiles(parsedFiles),
jjg@642 901 getPackageInfoFilesFromClasses(newClasses));
jjg@642 902
jjg@642 903 findAnnotationsPresent();
jjg@642 904 }
jjg@642 905
jjg@620 906 /** Create the next round to be used. */
jjg@663 907 Round next(Set<JavaFileObject> newSourceFiles, Map<String, JavaFileObject> newClassFiles) {
jjg@642 908 try {
jjg@642 909 return new Round(this, newSourceFiles, newClassFiles);
jjg@642 910 } finally {
jjg@642 911 compiler.close(false);
jjg@642 912 }
jjg@642 913 }
jjg@642 914
jjg@642 915 /** Create the compiler to be used for the final compilation. */
jjg@642 916 JavaCompiler finalCompiler(boolean errorStatus) {
jjg@642 917 try {
jjg@642 918 JavaCompiler c = JavaCompiler.instance(nextContext());
jjg@898 919 c.log.nwarnings += compiler.log.nwarnings;
jjg@642 920 if (errorStatus) {
jjg@642 921 c.log.nerrors += compiler.log.nerrors;
jjg@642 922 }
jjg@642 923 return c;
jjg@642 924 } finally {
jjg@642 925 compiler.close(false);
jjg@642 926 }
jjg@620 927 }
jjg@620 928
jjg@620 929 /** Return the number of errors found so far in this round.
jjg@620 930 * This may include uncoverable errors, such as parse errors,
jjg@620 931 * and transient errors, such as missing symbols. */
jjg@620 932 int errorCount() {
jjg@620 933 return compiler.errorCount();
jjg@620 934 }
jjg@620 935
jjg@620 936 /** Return the number of warnings found so far in this round. */
jjg@620 937 int warningCount() {
jjg@620 938 return compiler.warningCount();
jjg@620 939 }
jjg@620 940
jjg@620 941 /** Return whether or not an unrecoverable error has occurred. */
jjg@620 942 boolean unrecoverableError() {
jjg@664 943 if (messager.errorRaised())
jjg@664 944 return true;
jjg@664 945
jjg@664 946 for (JCDiagnostic d: log.deferredDiagnostics) {
jjg@664 947 switch (d.getKind()) {
jjg@664 948 case WARNING:
jjg@664 949 if (werror)
jjg@664 950 return true;
jjg@664 951 break;
jjg@664 952
jjg@664 953 case ERROR:
jjg@726 954 if (fatalErrors || !d.isFlagSet(RECOVERABLE))
jjg@664 955 return true;
jjg@664 956 break;
jjg@664 957 }
jjg@664 958 }
jjg@664 959
jjg@664 960 return false;
jjg@620 961 }
jjg@620 962
jjg@620 963 /** Find the set of annotations present in the set of top level
jjg@642 964 * classes and package info files to be processed this round. */
jjg@642 965 void findAnnotationsPresent() {
jjg@642 966 ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
jjg@620 967 // Use annotation processing to compute the set of annotations present
jjg@620 968 annotationsPresent = new LinkedHashSet<TypeElement>();
jjg@620 969 for (ClassSymbol classSym : topLevelClasses)
jjg@620 970 annotationComputer.scan(classSym, annotationsPresent);
jjg@620 971 for (PackageSymbol pkgSym : packageInfoFiles)
jjg@620 972 annotationComputer.scan(pkgSym, annotationsPresent);
jjg@620 973 }
jjg@620 974
jjg@642 975 /** Enter a set of generated class files. */
jjg@664 976 private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) {
jjg@620 977 ClassReader reader = ClassReader.instance(context);
jjg@620 978 Names names = Names.instance(context);
jjg@620 979 List<ClassSymbol> list = List.nil();
jjg@620 980
jjg@642 981 for (Map.Entry<String,JavaFileObject> entry : classFiles.entrySet()) {
jjg@620 982 Name name = names.fromString(entry.getKey());
jjg@620 983 JavaFileObject file = entry.getValue();
jjg@620 984 if (file.getKind() != JavaFileObject.Kind.CLASS)
jjg@620 985 throw new AssertionError(file);
jjg@620 986 ClassSymbol cs;
jjg@620 987 if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
jjg@620 988 Name packageName = Convert.packagePart(name);
jjg@620 989 PackageSymbol p = reader.enterPackage(packageName);
jjg@620 990 if (p.package_info == null)
jjg@620 991 p.package_info = reader.enterClass(Convert.shortName(name), p);
jjg@620 992 cs = p.package_info;
jjg@620 993 if (cs.classfile == null)
jjg@620 994 cs.classfile = file;
jjg@620 995 } else
jjg@620 996 cs = reader.enterClass(name, file);
jjg@620 997 list = list.prepend(cs);
jjg@620 998 }
jjg@620 999 return list.reverse();
jjg@620 1000 }
jjg@620 1001
jjg@620 1002 /** Enter a set of syntax trees. */
jjg@664 1003 private void enterTrees(List<JCCompilationUnit> roots) {
jjg@620 1004 compiler.enterTrees(roots);
jjg@620 1005 }
jjg@620 1006
jjg@620 1007 /** Run a processing round. */
jjg@620 1008 void run(boolean lastRound, boolean errorStatus) {
jjg@642 1009 printRoundInfo(lastRound);
jjg@620 1010
jjg@620 1011 TaskListener taskListener = context.get(TaskListener.class);
jjg@620 1012 if (taskListener != null)
jjg@620 1013 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
jjg@620 1014
jjg@620 1015 try {
jjg@620 1016 if (lastRound) {
jjg@620 1017 filer.setLastRound(true);
jjg@620 1018 Set<Element> emptyRootElements = Collections.emptySet(); // immutable
jjg@620 1019 RoundEnvironment renv = new JavacRoundEnvironment(true,
jjg@620 1020 errorStatus,
jjg@620 1021 emptyRootElements,
jjg@620 1022 JavacProcessingEnvironment.this);
jjg@620 1023 discoveredProcs.iterator().runContributingProcs(renv);
jjg@620 1024 } else {
jjg@620 1025 discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles);
jjg@620 1026 }
jjg@620 1027 } finally {
jjg@620 1028 if (taskListener != null)
jjg@620 1029 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
jjg@620 1030 }
jjg@933 1031
jjg@933 1032 nMessagerErrors = messager.errorCount();
jjg@620 1033 }
jjg@620 1034
jjg@664 1035 void showDiagnostics(boolean showAll) {
jjg@664 1036 Set<JCDiagnostic.Kind> kinds = EnumSet.allOf(JCDiagnostic.Kind.class);
jjg@664 1037 if (!showAll) {
jjg@664 1038 // suppress errors, which are all presumed to be transient resolve errors
jjg@664 1039 kinds.remove(JCDiagnostic.Kind.ERROR);
jjg@664 1040 }
jjg@664 1041 log.reportDeferredDiagnostics(kinds);
jjg@664 1042 }
jjg@664 1043
jjg@620 1044 /** Print info about this round. */
jjg@642 1045 private void printRoundInfo(boolean lastRound) {
jjg@620 1046 if (printRounds || verbose) {
jjg@642 1047 List<ClassSymbol> tlc = lastRound ? List.<ClassSymbol>nil() : topLevelClasses;
jjg@642 1048 Set<TypeElement> ap = lastRound ? Collections.<TypeElement>emptySet() : annotationsPresent;
jjg@620 1049 log.printNoteLines("x.print.rounds",
jjg@642 1050 number,
jjg@642 1051 "{" + tlc.toString(", ") + "}",
jjg@642 1052 ap,
jjg@620 1053 lastRound);
jjg@620 1054 }
jjg@620 1055 }
jjg@620 1056
jjg@620 1057 /** Get the context for the next round of processing.
jjg@620 1058 * Important values are propogated from round to round;
jjg@620 1059 * other values are implicitly reset.
jjg@620 1060 */
jjg@642 1061 private Context nextContext() {
jjg@893 1062 Context next = new Context(context);
jjg@620 1063
jjg@620 1064 Options options = Options.instance(context);
jjg@816 1065 Assert.checkNonNull(options);
jjg@620 1066 next.put(Options.optionsKey, options);
jjg@620 1067
jjg@620 1068 PrintWriter out = context.get(Log.outKey);
jjg@816 1069 Assert.checkNonNull(out);
jjg@620 1070 next.put(Log.outKey, out);
jjg@944 1071 Locale locale = context.get(Locale.class);
jjg@944 1072 if (locale != null)
jjg@944 1073 next.put(Locale.class, locale);
jjg@944 1074 Assert.checkNonNull(messages);
jjg@944 1075 next.put(JavacMessages.messagesKey, messages);
jjg@620 1076
jjg@620 1077 final boolean shareNames = true;
jjg@620 1078 if (shareNames) {
jjg@620 1079 Names names = Names.instance(context);
jjg@816 1080 Assert.checkNonNull(names);
jjg@620 1081 next.put(Names.namesKey, names);
jjg@620 1082 }
jjg@620 1083
jjg@620 1084 DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
jjg@620 1085 if (dl != null)
jjg@620 1086 next.put(DiagnosticListener.class, dl);
jjg@620 1087
jjg@620 1088 TaskListener tl = context.get(TaskListener.class);
jjg@620 1089 if (tl != null)
jjg@620 1090 next.put(TaskListener.class, tl);
jjg@620 1091
jjg@872 1092 FSInfo fsInfo = context.get(FSInfo.class);
jjg@872 1093 if (fsInfo != null)
jjg@872 1094 next.put(FSInfo.class, fsInfo);
jjg@872 1095
jjg@620 1096 JavaFileManager jfm = context.get(JavaFileManager.class);
jjg@816 1097 Assert.checkNonNull(jfm);
jjg@620 1098 next.put(JavaFileManager.class, jfm);
jjg@620 1099 if (jfm instanceof JavacFileManager) {
jjg@620 1100 ((JavacFileManager)jfm).setContext(next);
jjg@620 1101 }
jjg@620 1102
jjg@620 1103 Names names = Names.instance(context);
jjg@816 1104 Assert.checkNonNull(names);
jjg@620 1105 next.put(Names.namesKey, names);
jjg@620 1106
jjg@620 1107 Keywords keywords = Keywords.instance(context);
jjg@816 1108 Assert.checkNonNull(keywords);
jjg@620 1109 next.put(Keywords.keywordsKey, keywords);
jjg@620 1110
jjg@620 1111 JavaCompiler oldCompiler = JavaCompiler.instance(context);
jjg@620 1112 JavaCompiler nextCompiler = JavaCompiler.instance(next);
jjg@620 1113 nextCompiler.initRound(oldCompiler);
jjg@620 1114
jjg@706 1115 filer.newRound(next);
jjg@706 1116 messager.newRound(next);
jjg@706 1117 elementUtils.setContext(next);
jjg@706 1118 typeUtils.setContext(next);
jjg@706 1119
jjg@620 1120 JavacTaskImpl task = context.get(JavacTaskImpl.class);
jjg@620 1121 if (task != null) {
jjg@620 1122 next.put(JavacTaskImpl.class, task);
jjg@620 1123 task.updateContext(next);
jjg@620 1124 }
jjg@620 1125
jjg@696 1126 JavacTrees trees = context.get(JavacTrees.class);
jjg@696 1127 if (trees != null) {
jjg@696 1128 next.put(JavacTrees.class, trees);
jjg@696 1129 trees.updateContext(next);
jjg@696 1130 }
jjg@696 1131
jjg@620 1132 context.clear();
jjg@620 1133 return next;
jjg@620 1134 }
jjg@620 1135 }
jjg@620 1136
duke@1 1137
duke@1 1138 // TODO: internal catch clauses?; catch and rethrow an annotation
duke@1 1139 // processing error
duke@1 1140 public JavaCompiler doProcessing(Context context,
duke@1 1141 List<JCCompilationUnit> roots,
duke@1 1142 List<ClassSymbol> classSymbols,
jjg@663 1143 Iterable<? extends PackageSymbol> pckSymbols) {
duke@1 1144
jjg@642 1145 TaskListener taskListener = context.get(TaskListener.class);
duke@1 1146 log = Log.instance(context);
duke@1 1147
duke@1 1148 Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
duke@1 1149 for (PackageSymbol psym : pckSymbols)
duke@1 1150 specifiedPackages.add(psym);
duke@1 1151 this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
duke@1 1152
jjg@642 1153 Round round = new Round(context, roots, classSymbols);
duke@1 1154
jjg@642 1155 boolean errorStatus;
jjg@642 1156 boolean moreToDo;
jjg@642 1157 do {
jjg@642 1158 // Run processors for round n
jjg@620 1159 round.run(false, false);
duke@1 1160
jjg@642 1161 // Processors for round n have run to completion.
jjg@642 1162 // Check for errors and whether there is more work to do.
jjg@642 1163 errorStatus = round.unrecoverableError();
jjg@642 1164 moreToDo = moreToDo();
jjg@642 1165
jjg@664 1166 round.showDiagnostics(errorStatus || showResolveErrors);
jjg@664 1167
jjg@642 1168 // Set up next round.
jjg@642 1169 // Copy mutable collections returned from filer.
jjg@642 1170 round = round.next(
jjg@642 1171 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()),
jjg@642 1172 new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses()));
jjg@642 1173
jjg@642 1174 // Check for errors during setup.
jjg@642 1175 if (round.unrecoverableError())
duke@1 1176 errorStatus = true;
duke@1 1177
jjg@642 1178 } while (moreToDo && !errorStatus);
jjg@620 1179
jjg@620 1180 // run last round
jjg@620 1181 round.run(true, errorStatus);
jjg@664 1182 round.showDiagnostics(true);
jjg@620 1183
duke@1 1184 filer.warnIfUnclosedFiles();
duke@1 1185 warnIfUnmatchedOptions();
duke@1 1186
jjg@642 1187 /*
jjg@642 1188 * If an annotation processor raises an error in a round,
jjg@642 1189 * that round runs to completion and one last round occurs.
jjg@642 1190 * The last round may also occur because no more source or
jjg@642 1191 * class files have been generated. Therefore, if an error
jjg@642 1192 * was raised on either of the last *two* rounds, the compile
jjg@642 1193 * should exit with a nonzero exit code. The current value of
jjg@642 1194 * errorStatus holds whether or not an error was raised on the
jjg@642 1195 * second to last round; errorRaised() gives the error status
jjg@642 1196 * of the last round.
jjg@642 1197 */
jjg@642 1198 if (messager.errorRaised()
jjg@642 1199 || werror && round.warningCount() > 0 && round.errorCount() > 0)
jjg@642 1200 errorStatus = true;
jjg@642 1201
jjg@642 1202 Set<JavaFileObject> newSourceFiles =
jjg@642 1203 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
jjg@642 1204 roots = cleanTrees(round.roots);
jjg@642 1205
jjg@642 1206 JavaCompiler compiler = round.finalCompiler(errorStatus);
jjg@642 1207
jjg@642 1208 if (newSourceFiles.size() > 0)
jjg@642 1209 roots = roots.appendList(compiler.parseFiles(newSourceFiles));
jjg@642 1210
jjg@642 1211 errorStatus = errorStatus || (compiler.errorCount() > 0);
duke@1 1212
duke@1 1213 // Free resources
duke@1 1214 this.close();
duke@1 1215
duke@1 1216 if (taskListener != null)
duke@1 1217 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
duke@1 1218
duke@1 1219 if (errorStatus) {
duke@1 1220 if (compiler.errorCount() == 0)
duke@1 1221 compiler.log.nerrors++;
jjg@642 1222 return compiler;
jjg@642 1223 }
jjg@642 1224
jjg@642 1225 if (procOnly && !foundTypeProcessors) {
duke@1 1226 compiler.todo.clear();
jjg@642 1227 } else {
jjg@310 1228 if (procOnly && foundTypeProcessors)
jjg@310 1229 compiler.shouldStopPolicy = CompileState.FLOW;
duke@1 1230
jjg@642 1231 compiler.enterTrees(roots);
duke@1 1232 }
duke@1 1233
duke@1 1234 return compiler;
duke@1 1235 }
duke@1 1236
duke@1 1237 private void warnIfUnmatchedOptions() {
duke@1 1238 if (!unmatchedProcessorOptions.isEmpty()) {
duke@1 1239 log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
duke@1 1240 }
duke@1 1241 }
duke@1 1242
duke@1 1243 /**
duke@1 1244 * Free resources related to annotation processing.
duke@1 1245 */
jjg@663 1246 public void close() {
duke@1 1247 filer.close();
darcy@382 1248 if (discoveredProcs != null) // Make calling close idempotent
darcy@382 1249 discoveredProcs.close();
duke@1 1250 discoveredProcs = null;
jjg@663 1251 if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
jjg@663 1252 try {
jjg@663 1253 ((Closeable) processorClassLoader).close();
jjg@663 1254 } catch (IOException e) {
jjg@663 1255 JCDiagnostic msg = diags.fragment("fatal.err.cant.close.loader");
jjg@663 1256 throw new FatalError(msg, e);
jjg@663 1257 }
jjg@663 1258 }
duke@1 1259 }
duke@1 1260
duke@1 1261 private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
duke@1 1262 List<ClassSymbol> classes = List.nil();
duke@1 1263 for (JCCompilationUnit unit : units) {
duke@1 1264 for (JCTree node : unit.defs) {
duke@1 1265 if (node.getTag() == JCTree.CLASSDEF) {
jjg@642 1266 ClassSymbol sym = ((JCClassDecl) node).sym;
jjg@816 1267 Assert.checkNonNull(sym);
jjg@642 1268 classes = classes.prepend(sym);
duke@1 1269 }
duke@1 1270 }
duke@1 1271 }
duke@1 1272 return classes.reverse();
duke@1 1273 }
duke@1 1274
jjg@483 1275 private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) {
jjg@483 1276 List<ClassSymbol> classes = List.nil();
jjg@483 1277 for (ClassSymbol sym : syms) {
jjg@483 1278 if (!isPkgInfo(sym)) {
jjg@483 1279 classes = classes.prepend(sym);
jjg@483 1280 }
jjg@483 1281 }
jjg@483 1282 return classes.reverse();
jjg@483 1283 }
jjg@483 1284
duke@1 1285 private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
duke@1 1286 List<PackageSymbol> packages = List.nil();
duke@1 1287 for (JCCompilationUnit unit : units) {
jjg@483 1288 if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
duke@1 1289 packages = packages.prepend(unit.packge);
duke@1 1290 }
duke@1 1291 }
duke@1 1292 return packages.reverse();
duke@1 1293 }
duke@1 1294
jjg@483 1295 private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) {
jjg@483 1296 List<PackageSymbol> packages = List.nil();
jjg@483 1297 for (ClassSymbol sym : syms) {
jjg@483 1298 if (isPkgInfo(sym)) {
jjg@483 1299 packages = packages.prepend((PackageSymbol) sym.owner);
jjg@483 1300 }
jjg@483 1301 }
jjg@483 1302 return packages.reverse();
jjg@483 1303 }
jjg@483 1304
jjg@620 1305 // avoid unchecked warning from use of varargs
jjg@620 1306 private static <T> List<T> join(List<T> list1, List<T> list2) {
jjg@620 1307 return list1.appendList(list2);
jjg@620 1308 }
jjg@620 1309
jjg@483 1310 private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
jjg@483 1311 return fo.isNameCompatible("package-info", kind);
jjg@483 1312 }
jjg@483 1313
jjg@483 1314 private boolean isPkgInfo(ClassSymbol sym) {
jjg@483 1315 return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
jjg@483 1316 }
jjg@483 1317
duke@1 1318 /*
duke@1 1319 * Called retroactively to determine if a class loader was required,
duke@1 1320 * after we have failed to create one.
duke@1 1321 */
duke@1 1322 private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
duke@1 1323 if (procNames != null)
duke@1 1324 return true;
duke@1 1325
duke@1 1326 String procPath;
duke@1 1327 URL[] urls = new URL[1];
duke@1 1328 for(File pathElement : workingpath) {
duke@1 1329 try {
duke@1 1330 urls[0] = pathElement.toURI().toURL();
duke@1 1331 if (ServiceProxy.hasService(Processor.class, urls))
duke@1 1332 return true;
duke@1 1333 } catch (MalformedURLException ex) {
duke@1 1334 throw new AssertionError(ex);
duke@1 1335 }
duke@1 1336 catch (ServiceProxy.ServiceConfigurationError e) {
duke@1 1337 log.error("proc.bad.config.file", e.getLocalizedMessage());
duke@1 1338 return true;
duke@1 1339 }
duke@1 1340 }
duke@1 1341
duke@1 1342 return false;
duke@1 1343 }
duke@1 1344
duke@1 1345 private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) {
duke@1 1346 for (T node : nodes)
duke@1 1347 treeCleaner.scan(node);
duke@1 1348 return nodes;
duke@1 1349 }
duke@1 1350
duke@1 1351 private static TreeScanner treeCleaner = new TreeScanner() {
duke@1 1352 public void scan(JCTree node) {
duke@1 1353 super.scan(node);
duke@1 1354 if (node != null)
duke@1 1355 node.type = null;
duke@1 1356 }
duke@1 1357 public void visitTopLevel(JCCompilationUnit node) {
duke@1 1358 node.packge = null;
duke@1 1359 super.visitTopLevel(node);
duke@1 1360 }
duke@1 1361 public void visitClassDef(JCClassDecl node) {
duke@1 1362 node.sym = null;
duke@1 1363 super.visitClassDef(node);
duke@1 1364 }
duke@1 1365 public void visitMethodDef(JCMethodDecl node) {
duke@1 1366 node.sym = null;
duke@1 1367 super.visitMethodDef(node);
duke@1 1368 }
duke@1 1369 public void visitVarDef(JCVariableDecl node) {
duke@1 1370 node.sym = null;
duke@1 1371 super.visitVarDef(node);
duke@1 1372 }
duke@1 1373 public void visitNewClass(JCNewClass node) {
duke@1 1374 node.constructor = null;
duke@1 1375 super.visitNewClass(node);
duke@1 1376 }
duke@1 1377 public void visitAssignop(JCAssignOp node) {
duke@1 1378 node.operator = null;
duke@1 1379 super.visitAssignop(node);
duke@1 1380 }
duke@1 1381 public void visitUnary(JCUnary node) {
duke@1 1382 node.operator = null;
duke@1 1383 super.visitUnary(node);
duke@1 1384 }
duke@1 1385 public void visitBinary(JCBinary node) {
duke@1 1386 node.operator = null;
duke@1 1387 super.visitBinary(node);
duke@1 1388 }
duke@1 1389 public void visitSelect(JCFieldAccess node) {
duke@1 1390 node.sym = null;
duke@1 1391 super.visitSelect(node);
duke@1 1392 }
duke@1 1393 public void visitIdent(JCIdent node) {
duke@1 1394 node.sym = null;
duke@1 1395 super.visitIdent(node);
duke@1 1396 }
duke@1 1397 };
duke@1 1398
duke@1 1399
duke@1 1400 private boolean moreToDo() {
duke@1 1401 return filer.newFiles();
duke@1 1402 }
duke@1 1403
duke@1 1404 /**
duke@1 1405 * {@inheritdoc}
duke@1 1406 *
duke@1 1407 * Command line options suitable for presenting to annotation
duke@1 1408 * processors. "-Afoo=bar" should be "-Afoo" => "bar".
duke@1 1409 */
duke@1 1410 public Map<String,String> getOptions() {
duke@1 1411 return processorOptions;
duke@1 1412 }
duke@1 1413
duke@1 1414 public Messager getMessager() {
duke@1 1415 return messager;
duke@1 1416 }
duke@1 1417
duke@1 1418 public Filer getFiler() {
duke@1 1419 return filer;
duke@1 1420 }
duke@1 1421
duke@1 1422 public JavacElements getElementUtils() {
duke@1 1423 return elementUtils;
duke@1 1424 }
duke@1 1425
duke@1 1426 public JavacTypes getTypeUtils() {
duke@1 1427 return typeUtils;
duke@1 1428 }
duke@1 1429
duke@1 1430 public SourceVersion getSourceVersion() {
duke@1 1431 return Source.toSourceVersion(source);
duke@1 1432 }
duke@1 1433
duke@1 1434 public Locale getLocale() {
mcimadamore@136 1435 return messages.getCurrentLocale();
duke@1 1436 }
duke@1 1437
duke@1 1438 public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
duke@1 1439 return specifiedPackages;
duke@1 1440 }
duke@1 1441
darcy@497 1442 private static final Pattern allMatches = Pattern.compile(".*");
darcy@497 1443 public static final Pattern noMatches = Pattern.compile("(\\P{all})+");
darcy@497 1444
duke@1 1445 /**
darcy@497 1446 * Convert import-style string for supported annotations into a
darcy@497 1447 * regex matching that string. If the string is a valid
darcy@497 1448 * import-style string, return a regex that won't match anything.
duke@1 1449 */
darcy@497 1450 private static Pattern importStringToPattern(String s, Processor p, Log log) {
darcy@497 1451 if (isValidImportString(s)) {
darcy@497 1452 return validImportStringToPattern(s);
darcy@497 1453 } else {
darcy@497 1454 log.warning("proc.malformed.supported.string", s, p.getClass().getName());
darcy@497 1455 return noMatches; // won't match any valid identifier
duke@1 1456 }
duke@1 1457 }
duke@1 1458
duke@1 1459 /**
darcy@497 1460 * Return true if the argument string is a valid import-style
darcy@497 1461 * string specifying claimed annotations; return false otherwise.
duke@1 1462 */
darcy@497 1463 public static boolean isValidImportString(String s) {
darcy@497 1464 if (s.equals("*"))
darcy@497 1465 return true;
darcy@497 1466
darcy@497 1467 boolean valid = true;
darcy@497 1468 String t = s;
darcy@497 1469 int index = t.indexOf('*');
darcy@497 1470
darcy@497 1471 if (index != -1) {
darcy@497 1472 // '*' must be last character...
darcy@497 1473 if (index == t.length() -1) {
darcy@497 1474 // ... any and preceding character must be '.'
darcy@497 1475 if ( index-1 >= 0 ) {
darcy@497 1476 valid = t.charAt(index-1) == '.';
darcy@497 1477 // Strip off ".*$" for identifier checks
darcy@497 1478 t = t.substring(0, t.length()-2);
darcy@497 1479 }
darcy@497 1480 } else
darcy@497 1481 return false;
duke@1 1482 }
darcy@497 1483
darcy@497 1484 // Verify string is off the form (javaId \.)+ or javaId
darcy@497 1485 if (valid) {
darcy@497 1486 String[] javaIds = t.split("\\.", t.length()+2);
darcy@497 1487 for(String javaId: javaIds)
darcy@497 1488 valid &= SourceVersion.isIdentifier(javaId);
duke@1 1489 }
darcy@497 1490 return valid;
duke@1 1491 }
duke@1 1492
darcy@497 1493 public static Pattern validImportStringToPattern(String s) {
duke@1 1494 if (s.equals("*")) {
duke@1 1495 return allMatches;
duke@1 1496 } else {
darcy@497 1497 String s_prime = s.replace(".", "\\.");
duke@1 1498
duke@1 1499 if (s_prime.endsWith("*")) {
duke@1 1500 s_prime = s_prime.substring(0, s_prime.length() - 1) + ".+";
duke@1 1501 }
duke@1 1502
duke@1 1503 return Pattern.compile(s_prime);
duke@1 1504 }
duke@1 1505 }
duke@1 1506
duke@1 1507 /**
jjg@581 1508 * For internal use only. This method will be
duke@1 1509 * removed without warning.
duke@1 1510 */
duke@1 1511 public Context getContext() {
duke@1 1512 return context;
duke@1 1513 }
duke@1 1514
duke@1 1515 public String toString() {
duke@1 1516 return "javac ProcessingEnvironment";
duke@1 1517 }
duke@1 1518
duke@1 1519 public static boolean isValidOptionName(String optionName) {
duke@1 1520 for(String s : optionName.split("\\.", -1)) {
duke@1 1521 if (!SourceVersion.isIdentifier(s))
duke@1 1522 return false;
duke@1 1523 }
duke@1 1524 return true;
duke@1 1525 }
duke@1 1526 }

mercurial