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

Mon, 02 Aug 2010 16:29:54 -0700

author
jjg
date
Mon, 02 Aug 2010 16:29:54 -0700
changeset 623
6318230cdb82
parent 620
2cf925ad67ab
child 642
6b95dd682538
permissions
-rw-r--r--

6973626: test/tools/javac/processing/* tests fail with assertions enabled
Reviewed-by: darcy

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

mercurial