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