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 
  29 import java.lang.reflect.*;
  30 import java.util.*;
  31 import java.util.regex.*;
  32 
  33 import java.net.URL;
  34 import java.io.Closeable;
  35 import java.io.File;
  36 import java.io.PrintWriter;
  37 import java.io.IOException;
  38 import java.net.MalformedURLException;
  39 import java.io.StringWriter;
  40 
  41 import javax.annotation.processing.*;
  42 import javax.lang.model.SourceVersion;
  43 import javax.lang.model.element.AnnotationMirror;
  44 import javax.lang.model.element.Element;
  45 import javax.lang.model.element.TypeElement;
  46 import javax.lang.model.element.PackageElement;
  47 import javax.lang.model.util.*;
  48 import javax.tools.JavaFileManager;
  49 import javax.tools.StandardJavaFileManager;
  50 import javax.tools.JavaFileObject;
  51 import javax.tools.DiagnosticListener;
  52 
  53 import com.sun.source.util.AbstractTypeProcessor;
  54 import com.sun.source.util.TaskEvent;
  55 import com.sun.source.util.TaskListener;
  56 import com.sun.tools.javac.api.JavacTaskImpl;
  57 import com.sun.tools.javac.code.*;
  58 import com.sun.tools.javac.code.Symbol.*;
  59 import com.sun.tools.javac.file.JavacFileManager;
  60 import com.sun.tools.javac.jvm.*;
  61 import com.sun.tools.javac.main.JavaCompiler;
  62 import com.sun.tools.javac.main.JavaCompiler.CompileState;
  63 import com.sun.tools.javac.model.JavacElements;
  64 import com.sun.tools.javac.model.JavacTypes;
  65 import com.sun.tools.javac.parser.*;
  66 import com.sun.tools.javac.tree.*;
  67 import com.sun.tools.javac.tree.JCTree.*;
  68 import com.sun.tools.javac.util.Abort;
  69 import com.sun.tools.javac.util.Context;
  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                     List<JavaFileObject> fileObjects = List.nil();
 877                     for (JavaFileObject jfo : filer.getGeneratedSourceFileObjects() ) {
 878                         fileObjects = fileObjects.prepend(jfo);
 879                     }
 880 
 881 
 882                     compiler = JavaCompiler.instance(currentContext);
 883                     List<JCCompilationUnit> parsedFiles = compiler.parseFiles(fileObjects);
 884                     roots = cleanTrees(roots).reverse();
 885 
 886 
 887                     for (JCCompilationUnit unit : parsedFiles)
 888                         roots = roots.prepend(unit);
 889                     roots = roots.reverse();
 890 
 891                     // Check for errors after parsing
 892                     if (compiler.parseErrors()) {
 893                         errorStatus = true;
 894                         break runAround;
 895                     } else {
 896                         ListBuffer<ClassSymbol> classes = enterNewClassFiles(currentContext);
 897                         compiler.enterTrees(roots);
 898 
 899                         // annotationsPresentInSource =
 900                         // collector.findAnnotations(parsedFiles);
 901                         classes.appendList(getTopLevelClasses(parsedFiles));
 902                         topLevelClasses  = classes.toList();
 903                         packageInfoFiles = getPackageInfoFiles(parsedFiles);
 904 
 905                         annotationsPresent = new LinkedHashSet<TypeElement>();
 906                         for (ClassSymbol classSym : topLevelClasses)
 907                             annotationComputer.scan(classSym, annotationsPresent);
 908                         for (PackageSymbol pkgSym : packageInfoFiles)
 909                             annotationComputer.scan(pkgSym, annotationsPresent);
 910 
 911                         updateProcessingState(currentContext, false);
 912                     }
 913                 } else
 914                     break runAround; // No new files
 915             }
 916         }
 917         runLastRound(xout, roundNumber, errorStatus, taskListener);
 918 
 919         compiler.close(false);
 920         currentContext = contextForNextRound(currentContext, true);
 921         compiler = JavaCompiler.instance(currentContext);
 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     // Call the last round of annotation processing
 976     private void runLastRound(PrintWriter xout,
 977                               int roundNumber,
 978                               boolean errorStatus,
 979                               TaskListener taskListener) throws IOException {
 980         roundNumber++;
 981         List<ClassSymbol> noTopLevelClasses = List.nil();
 982         Set<TypeElement> noAnnotations =  Collections.emptySet();
 983         printRoundInfo(xout, roundNumber, noTopLevelClasses, noAnnotations, true);
 984 
 985         Set<Element> emptyRootElements = Collections.emptySet(); // immutable
 986         RoundEnvironment renv = new JavacRoundEnvironment(true,
 987                                                           errorStatus,
 988                                                           emptyRootElements,
 989                                                           JavacProcessingEnvironment.this);
 990         if (taskListener != null)
 991             taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
 992 
 993         try {
 994             discoveredProcs.iterator().runContributingProcs(renv);
 995         } finally {
 996             if (taskListener != null)
 997                 taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
 998         }
 999     }
1000 
1001     private void updateProcessingState(Context currentContext, boolean lastRound) {
1002         filer.newRound(currentContext, lastRound);
1003         messager.newRound(currentContext);
1004 
1005         elementUtils.setContext(currentContext);
1006         typeUtils.setContext(currentContext);
1007     }
1008 
1009     private void warnIfUnmatchedOptions() {
1010         if (!unmatchedProcessorOptions.isEmpty()) {
1011             log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
1012         }
1013     }
1014 
1015     private void printRoundInfo(PrintWriter xout,
1016                                 int roundNumber,
1017                                 List<ClassSymbol> topLevelClasses,
1018                                 Set<TypeElement> annotationsPresent,
1019                                 boolean lastRound) {
1020         if (printRounds || verbose) {
1021             xout.println(Log.getLocalizedString("x.print.rounds",
1022                                                 roundNumber,
1023                                                 "{" + topLevelClasses.toString(", ") + "}",
1024                                                 annotationsPresent,
1025                                                 lastRound));
1026         }
1027     }
1028 
1029     private ListBuffer<ClassSymbol> enterNewClassFiles(Context currentContext) {
1030         ClassReader reader = ClassReader.instance(currentContext);
1031         Names names = Names.instance(currentContext);
1032         ListBuffer<ClassSymbol> list = new ListBuffer<ClassSymbol>();
1033 
1034         for (Map.Entry<String,JavaFileObject> entry : filer.getGeneratedClasses().entrySet()) {
1035             Name name = names.fromString(entry.getKey());
1036             JavaFileObject file = entry.getValue();
1037             if (file.getKind() != JavaFileObject.Kind.CLASS)
1038                 throw new AssertionError(file);
1039             ClassSymbol cs = reader.enterClass(name, file);
1040             list.append(cs);
1041         }
1042         return list;
1043     }
1044 
1045     /**
1046      * Free resources related to annotation processing.
1047      */
1048     public void close() throws IOException {
1049         filer.close();
1050         if (discoveredProcs != null) // Make calling close idempotent
1051             discoveredProcs.close();
1052         discoveredProcs = null;
1053         if (processorClassLoader != null && processorClassLoader instanceof Closeable)
1054             ((Closeable) processorClassLoader).close();
1055     }
1056 
1057     private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
1058         List<ClassSymbol> classes = List.nil();
1059         for (JCCompilationUnit unit : units) {
1060             for (JCTree node : unit.defs) {
1061                 if (node.getTag() == JCTree.CLASSDEF) {
1062                     classes = classes.prepend(((JCClassDecl) node).sym);
1063                 }
1064             }
1065         }
1066         return classes.reverse();
1067     }
1068 
1069     private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
1070         List<PackageSymbol> packages = List.nil();
1071         for (JCCompilationUnit unit : units) {
1072             boolean isPkgInfo = unit.sourcefile.isNameCompatible("package-info",
1073                                                                  JavaFileObject.Kind.SOURCE);
1074             if (isPkgInfo) {
1075                 packages = packages.prepend(unit.packge);
1076             }
1077         }
1078         return packages.reverse();
1079     }
1080 
1081     private Context contextForNextRound(Context context, boolean shareNames)
1082         throws IOException
1083     {
1084         Context next = new Context();
1085 
1086         Options options = Options.instance(context);
1087         assert options != null;
1088         next.put(Options.optionsKey, options);
1089 
1090         PrintWriter out = context.get(Log.outKey);
1091         assert out != null;
1092         next.put(Log.outKey, out);
1093 
1094         if (shareNames) {
1095             Names names = Names.instance(context);
1096             assert names != null;
1097             next.put(Names.namesKey, names);
1098         }
1099 
1100         DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
1101         if (dl != null)
1102             next.put(DiagnosticListener.class, dl);
1103 
1104         TaskListener tl = context.get(TaskListener.class);
1105         if (tl != null)
1106             next.put(TaskListener.class, tl);
1107 
1108         JavaFileManager jfm = context.get(JavaFileManager.class);
1109         assert jfm != null;
1110         next.put(JavaFileManager.class, jfm);
1111         if (jfm instanceof JavacFileManager) {
1112             ((JavacFileManager)jfm).setContext(next);
1113         }
1114 
1115         Names names = Names.instance(context);
1116         assert names != null;
1117         next.put(Names.namesKey, names);
1118 
1119         Keywords keywords = Keywords.instance(context);
1120         assert(keywords != null);
1121         next.put(Keywords.keywordsKey, keywords);
1122 
1123         JavaCompiler oldCompiler = JavaCompiler.instance(context);
1124         JavaCompiler nextCompiler = JavaCompiler.instance(next);
1125         nextCompiler.initRound(oldCompiler);
1126 
1127         JavacTaskImpl task = context.get(JavacTaskImpl.class);
1128         if (task != null) {
1129             next.put(JavacTaskImpl.class, task);
1130             task.updateContext(next);
1131         }
1132 
1133         context.clear();
1134         return next;
1135     }
1136 
1137     /*
1138      * Called retroactively to determine if a class loader was required,
1139      * after we have failed to create one.
1140      */
1141     private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
1142         if (procNames != null)
1143             return true;
1144 
1145         String procPath;
1146         URL[] urls = new URL[1];
1147         for(File pathElement : workingpath) {
1148             try {
1149                 urls[0] = pathElement.toURI().toURL();
1150                 if (ServiceProxy.hasService(Processor.class, urls))
1151                     return true;
1152             } catch (MalformedURLException ex) {
1153                 throw new AssertionError(ex);
1154             }
1155             catch (ServiceProxy.ServiceConfigurationError e) {
1156                 log.error("proc.bad.config.file", e.getLocalizedMessage());
1157                 return true;
1158             }
1159         }
1160 
1161         return false;
1162     }
1163 
1164     private class AnnotationCollector extends TreeScanner {
1165         List<JCTree> path = List.nil();
1166         static final boolean verbose = false;
1167         List<JCAnnotation> annotations = List.nil();
1168 
1169         public List<JCAnnotation> findAnnotations(List<? extends JCTree> nodes) {
1170             annotations = List.nil();
1171             scan(nodes);
1172             List<JCAnnotation> found = annotations;
1173             annotations = List.nil();
1174             return found.reverse();
1175         }
1176 
1177         public void scan(JCTree node) {
1178             if (node == null)
1179                 return;
1180             Symbol sym = TreeInfo.symbolFor(node);
1181             if (sym != null)
1182                 path = path.prepend(node);
1183             super.scan(node);
1184             if (sym != null)
1185                 path = path.tail;
1186         }
1187 
1188         public void visitAnnotation(JCAnnotation node) {
1189             annotations = annotations.prepend(node);
1190             if (verbose) {
1191                 StringBuilder sb = new StringBuilder();
1192                 for (JCTree tree : path.reverse()) {
1193                     System.err.print(sb);
1194                     System.err.println(TreeInfo.symbolFor(tree));
1195                     sb.append("  ");
1196                 }
1197                 System.err.print(sb);
1198                 System.err.println(node);
1199             }
1200         }
1201     }
1202 
1203     private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) {
1204         for (T node : nodes)
1205             treeCleaner.scan(node);
1206         return nodes;
1207     }
1208 
1209     private static TreeScanner treeCleaner = new TreeScanner() {
1210             public void scan(JCTree node) {
1211                 super.scan(node);
1212                 if (node != null)
1213                     node.type = null;
1214             }
1215             public void visitTopLevel(JCCompilationUnit node) {
1216                 node.packge = null;
1217                 super.visitTopLevel(node);
1218             }
1219             public void visitClassDef(JCClassDecl node) {
1220                 node.sym = null;
1221                 super.visitClassDef(node);
1222             }
1223             public void visitMethodDef(JCMethodDecl node) {
1224                 node.sym = null;
1225                 super.visitMethodDef(node);
1226             }
1227             public void visitVarDef(JCVariableDecl node) {
1228                 node.sym = null;
1229                 super.visitVarDef(node);
1230             }
1231             public void visitNewClass(JCNewClass node) {
1232                 node.constructor = null;
1233                 super.visitNewClass(node);
1234             }
1235             public void visitAssignop(JCAssignOp node) {
1236                 node.operator = null;
1237                 super.visitAssignop(node);
1238             }
1239             public void visitUnary(JCUnary node) {
1240                 node.operator = null;
1241                 super.visitUnary(node);
1242             }
1243             public void visitBinary(JCBinary node) {
1244                 node.operator = null;
1245                 super.visitBinary(node);
1246             }
1247             public void visitSelect(JCFieldAccess node) {
1248                 node.sym = null;
1249                 super.visitSelect(node);
1250             }
1251             public void visitIdent(JCIdent node) {
1252                 node.sym = null;
1253                 super.visitIdent(node);
1254             }
1255             public void visitApply(JCMethodInvocation node) {
1256                 scan(node.typeargs);
1257                 super.visitApply(node);
1258             }
1259         };
1260 
1261 
1262     private boolean moreToDo() {
1263         return filer.newFiles();
1264     }
1265 
1266     /**
1267      * {@inheritdoc}
1268      *
1269      * Command line options suitable for presenting to annotation
1270      * processors.  "-Afoo=bar" should be "-Afoo" => "bar".
1271      */
1272     public Map<String,String> getOptions() {
1273         return processorOptions;
1274     }
1275 
1276     public Messager getMessager() {
1277         return messager;
1278     }
1279 
1280     public Filer getFiler() {
1281         return filer;
1282     }
1283 
1284     public JavacElements getElementUtils() {
1285         return elementUtils;
1286     }
1287 
1288     public JavacTypes getTypeUtils() {
1289         return typeUtils;
1290     }
1291 
1292     public SourceVersion getSourceVersion() {
1293         return Source.toSourceVersion(source);
1294     }
1295 
1296     public Locale getLocale() {
1297         return messages.getCurrentLocale();
1298     }
1299 
1300     public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
1301         return specifiedPackages;
1302     }
1303 
1304     // Borrowed from DocletInvoker and apt
1305     // TODO: remove from apt's Main
1306     /**
1307      * Utility method for converting a search path string to an array
1308      * of directory and JAR file URLs.
1309      *
1310      * @param path the search path string
1311      * @return the resulting array of directory and JAR file URLs
1312      */
1313     public static URL[] pathToURLs(String path) {
1314         StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
1315         URL[] urls = new URL[st.countTokens()];
1316         int count = 0;
1317         while (st.hasMoreTokens()) {
1318             URL url = fileToURL(new File(st.nextToken()));
1319             if (url != null) {
1320                 urls[count++] = url;
1321             }
1322         }
1323         if (urls.length != count) {
1324             URL[] tmp = new URL[count];
1325             System.arraycopy(urls, 0, tmp, 0, count);
1326             urls = tmp;
1327         }
1328         return urls;
1329     }
1330 
1331     /**
1332      * Returns the directory or JAR file URL corresponding to the specified
1333      * local file name.
1334      *
1335      * @param file the File object
1336      * @return the resulting directory or JAR file URL, or null if unknown
1337      */
1338     private static URL fileToURL(File file) {
1339         String name;
1340         try {
1341             name = file.getCanonicalPath();
1342         } catch (IOException e) {
1343             name = file.getAbsolutePath();
1344         }
1345         name = name.replace(File.separatorChar, '/');
1346         if (!name.startsWith("/")) {
1347             name = "/" + name;
1348         }
1349         // If the file does not exist, then assume that it's a directory
1350         if (!file.isFile()) {
1351             name = name + "/";
1352         }
1353         try {
1354             return new URL("file", "", name);
1355         } catch (MalformedURLException e) {
1356             throw new IllegalArgumentException("file");
1357         }
1358     }
1359 
1360 
1361 
1362     private static final Pattern allMatches = Pattern.compile(".*");
1363 
1364     private static final Pattern noMatches  = Pattern.compile("(\\P{all})+");
1365     /**
1366      * Convert import-style string to regex matching that string.  If
1367      * the string is a valid import-style string, return a regex that
1368      * won't match anything.
1369      */
1370     // TODO: remove version in Apt.java
1371     public static Pattern importStringToPattern(String s, Processor p, Log log) {
1372         if (s.equals("*")) {
1373             return allMatches;
1374         } else {
1375             String t = s;
1376             boolean star = false;
1377 
1378             /*
1379              * Validate string from factory is legal.  If the string
1380              * has more than one asterisks or the asterisks does not
1381              * appear as the last character (preceded by a period),
1382              * the string is not legal.
1383              */
1384 
1385             boolean valid = true;
1386             int index = t.indexOf('*');
1387             if (index != -1) {
1388                 // '*' must be last character...
1389                 if (index == t.length() -1) {
1390                      // ... and preceeding character must be '.'
1391                     if ( index-1 >= 0 ) {
1392                         valid = t.charAt(index-1) == '.';
1393                         // Strip off ".*$" for identifier checks
1394                         t = t.substring(0, t.length()-2);
1395                     }
1396                 } else
1397                     valid = false;
1398             }
1399 
1400             // Verify string is off the form (javaId \.)+ or javaId
1401             if (valid) {
1402                 String[] javaIds = t.split("\\.", t.length()+2);
1403                 for(String javaId: javaIds)
1404                     valid &= SourceVersion.isIdentifier(javaId);
1405             }
1406 
1407             if (!valid) {
1408                 log.warning("proc.malformed.supported.string", s, p.getClass().getName());
1409                 return noMatches; // won't match any valid identifier
1410             }
1411 
1412             String s_prime = s.replaceAll("\\.", "\\\\.");
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 }