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

Mon, 28 Feb 2011 13:37:48 -0800

author
jjg
date
Mon, 28 Feb 2011 13:37:48 -0800
changeset 898
bf9f162c7104
parent 893
8f0dcb9499db
child 933
0f9e5b7f0d7e
permissions
-rw-r--r--

7022741: warning counts are wrong after anno processing
Reviewed-by: mcimadamore

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

mercurial