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

Tue, 07 May 2013 14:27:30 -0700

author
jjg
date
Tue, 07 May 2013 14:27:30 -0700
changeset 1728
43c2f7cb9c76
parent 1690
76537856a54e
child 1876
1908e86ee49a
permissions
-rw-r--r--

8004082: test/tools/javac/plugin/showtype/Test.java fails on windows: jtreg can't delete plugin.jar
Reviewed-by: vromero, mcimadamore

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

mercurial