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

Wed, 21 Aug 2013 16:13:50 -0700

author
jjg
date
Wed, 21 Aug 2013 16:13:50 -0700
changeset 1969
7de231613e4a
parent 1876
1908e86ee49a
child 2086
2fa6ced325cc
permissions
-rw-r--r--

8023515: import type-annotations updates
Reviewed-by: jjg
Contributed-by: wdietl@gmail.com

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

mercurial