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

Tue, 25 Sep 2012 13:11:05 -0700

author
jjg
date
Tue, 25 Sep 2012 13:11:05 -0700
changeset 1340
99d23c0ef8ee
parent 1334
8987971bcb45
child 1347
1408af4cd8b0
permissions
-rw-r--r--

7196464: upgrade JavaCompiler.shouldStopPolicy to accomodate policies in face of error and no error
Reviewed-by: mcimadamore

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

mercurial