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