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

Thu, 31 Aug 2017 15:17:03 +0800

author
aoqi
date
Thu, 31 Aug 2017 15:17:03 +0800
changeset 2525
2eb010b6cb22
parent 2306
ac7450d1ac51
parent 0
959103a6100f
child 3826
3fdfb200c295
permissions
-rw-r--r--

merge

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

mercurial