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

Tue, 05 Jul 2011 16:37:24 -0700

author
darcy
date
Tue, 05 Jul 2011 16:37:24 -0700
changeset 1054
111bbf1ad913
parent 1048
f74e4269a50a
child 1096
b0d5f00e69f7
permissions
-rw-r--r--

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

mercurial