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

Tue, 19 Oct 2010 15:02:48 -0700

author
jjg
date
Tue, 19 Oct 2010 15:02:48 -0700
changeset 722
4851ff2ffc10
parent 706
971c8132f5b2
child 726
2974d3800eb1
permissions
-rw-r--r--

6987760: remove 308 support from JDK7
Reviewed-by: darcy, mcimadamore

     1 /*
     2  * Copyright (c) 2005, 2010, 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.lang.reflect.*;
    29 import java.util.*;
    30 import java.util.regex.*;
    32 import java.net.URL;
    33 import java.io.Closeable;
    34 import java.io.File;
    35 import java.io.PrintWriter;
    36 import java.io.IOException;
    37 import java.net.MalformedURLException;
    38 import java.io.StringWriter;
    40 import javax.annotation.processing.*;
    41 import javax.lang.model.SourceVersion;
    42 import javax.lang.model.element.AnnotationMirror;
    43 import javax.lang.model.element.Element;
    44 import javax.lang.model.element.TypeElement;
    45 import javax.lang.model.element.PackageElement;
    46 import javax.lang.model.util.*;
    47 import javax.tools.JavaFileManager;
    48 import javax.tools.StandardJavaFileManager;
    49 import javax.tools.JavaFileObject;
    50 import javax.tools.DiagnosticListener;
    52 //308 import com.sun.source.util.AbstractTypeProcessor;
    53 import com.sun.source.util.TaskEvent;
    54 import com.sun.source.util.TaskListener;
    55 import com.sun.tools.javac.api.JavacTaskImpl;
    56 import com.sun.tools.javac.api.JavacTrees;
    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.Convert;
    71 import com.sun.tools.javac.util.FatalError;
    72 import com.sun.tools.javac.util.JCDiagnostic;
    73 import com.sun.tools.javac.util.List;
    74 import com.sun.tools.javac.util.Log;
    75 import com.sun.tools.javac.util.JavacMessages;
    76 import com.sun.tools.javac.util.Name;
    77 import com.sun.tools.javac.util.Names;
    78 import com.sun.tools.javac.util.Options;
    80 import static javax.tools.StandardLocation.*;
    81 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    82 import static com.sun.tools.javac.main.OptionName.*;
    83 import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
    85 /**
    86  * Objects of this class hold and manage the state needed to support
    87  * annotation processing.
    88  *
    89  * <p><b>This is NOT part of any supported API.
    90  * If you write code that depends on this, you do so at your own risk.
    91  * This code and its internal interfaces are subject to change or
    92  * deletion without notice.</b>
    93  */
    94 public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
    95     Options options;
    97     private final boolean printProcessorInfo;
    98     private final boolean printRounds;
    99     private final boolean verbose;
   100     private final boolean lint;
   101     private final boolean procOnly;
   102     private final boolean fatalErrors;
   103     private final boolean werror;
   104     private final boolean showResolveErrors;
   105     private boolean foundTypeProcessors;
   107     private final JavacFiler filer;
   108     private final JavacMessager messager;
   109     private final JavacElements elementUtils;
   110     private final JavacTypes typeUtils;
   112     /**
   113      * Holds relevant state history of which processors have been
   114      * used.
   115      */
   116     private DiscoveredProcessors discoveredProcs;
   118     /**
   119      * Map of processor-specific options.
   120      */
   121     private final Map<String, String> processorOptions;
   123     /**
   124      */
   125     private final Set<String> unmatchedProcessorOptions;
   127     /**
   128      * Annotations implicitly processed and claimed by javac.
   129      */
   130     private final Set<String> platformAnnotations;
   132     /**
   133      * Set of packages given on command line.
   134      */
   135     private Set<PackageSymbol> specifiedPackages = Collections.emptySet();
   137     /** The log to be used for error reporting.
   138      */
   139     Log log;
   141     /** Diagnostic factory.
   142      */
   143     JCDiagnostic.Factory diags;
   145     /**
   146      * Source level of the compile.
   147      */
   148     Source source;
   150     private ClassLoader processorClassLoader;
   152     /**
   153      * JavacMessages object used for localization
   154      */
   155     private JavacMessages messages;
   157     private Context context;
   159     public JavacProcessingEnvironment(Context context, Iterable<? extends Processor> processors) {
   160         this.context = context;
   161         log = Log.instance(context);
   162         source = Source.instance(context);
   163         diags = JCDiagnostic.Factory.instance(context);
   164         options = Options.instance(context);
   165         printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
   166         printRounds = options.isSet(XPRINTROUNDS);
   167         verbose = options.isSet(VERBOSE);
   168         lint = Lint.instance(context).isEnabled(PROCESSING);
   169         procOnly = options.isSet(PROC, "only") || options.isSet(XPRINT);
   170         fatalErrors = options.isSet("fatalEnterError");
   171         showResolveErrors = options.isSet("showResolveErrors");
   172         werror = options.isSet(WERROR);
   173         platformAnnotations = initPlatformAnnotations();
   174         foundTypeProcessors = false;
   176         // Initialize services before any processors are initialized
   177         // in case processors use them.
   178         filer = new JavacFiler(context);
   179         messager = new JavacMessager(context, this);
   180         elementUtils = JavacElements.instance(context);
   181         typeUtils = JavacTypes.instance(context);
   182         processorOptions = initProcessorOptions(context);
   183         unmatchedProcessorOptions = initUnmatchedProcessorOptions();
   184         messages = JavacMessages.instance(context);
   185         initProcessorIterator(context, processors);
   186     }
   188     private Set<String> initPlatformAnnotations() {
   189         Set<String> platformAnnotations = new HashSet<String>();
   190         platformAnnotations.add("java.lang.Deprecated");
   191         platformAnnotations.add("java.lang.Override");
   192         platformAnnotations.add("java.lang.SuppressWarnings");
   193         platformAnnotations.add("java.lang.annotation.Documented");
   194         platformAnnotations.add("java.lang.annotation.Inherited");
   195         platformAnnotations.add("java.lang.annotation.Retention");
   196         platformAnnotations.add("java.lang.annotation.Target");
   197         return Collections.unmodifiableSet(platformAnnotations);
   198     }
   200     private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
   201         Log   log   = Log.instance(context);
   202         Iterator<? extends Processor> processorIterator;
   204         if (options.isSet(XPRINT)) {
   205             try {
   206                 Processor processor = PrintingProcessor.class.newInstance();
   207                 processorIterator = List.of(processor).iterator();
   208             } catch (Throwable t) {
   209                 AssertionError assertError =
   210                     new AssertionError("Problem instantiating PrintingProcessor.");
   211                 assertError.initCause(t);
   212                 throw assertError;
   213             }
   214         } else if (processors != null) {
   215             processorIterator = processors.iterator();
   216         } else {
   217             String processorNames = options.get(PROCESSOR);
   218             JavaFileManager fileManager = context.get(JavaFileManager.class);
   219             try {
   220                 // If processorpath is not explicitly set, use the classpath.
   221                 processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
   222                     ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
   223                     : fileManager.getClassLoader(CLASS_PATH);
   225                 /*
   226                  * If the "-processor" option is used, search the appropriate
   227                  * path for the named class.  Otherwise, use a service
   228                  * provider mechanism to create the processor iterator.
   229                  */
   230                 if (processorNames != null) {
   231                     processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
   232                 } else {
   233                     processorIterator = new ServiceIterator(processorClassLoader, log);
   234                 }
   235             } catch (SecurityException e) {
   236                 /*
   237                  * A security exception will occur if we can't create a classloader.
   238                  * Ignore the exception if, with hindsight, we didn't need it anyway
   239                  * (i.e. no processor was specified either explicitly, or implicitly,
   240                  * in service configuration file.) Otherwise, we cannot continue.
   241                  */
   242                 processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader", e);
   243             }
   244         }
   245         discoveredProcs = new DiscoveredProcessors(processorIterator);
   246     }
   248     /**
   249      * Returns an empty processor iterator if no processors are on the
   250      * relevant path, otherwise if processors are present, logs an
   251      * error.  Called when a service loader is unavailable for some
   252      * reason, either because a service loader class cannot be found
   253      * or because a security policy prevents class loaders from being
   254      * created.
   255      *
   256      * @param key The resource key to use to log an error message
   257      * @param e   If non-null, pass this exception to Abort
   258      */
   259     private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
   260         JavaFileManager fileManager = context.get(JavaFileManager.class);
   262         if (fileManager instanceof JavacFileManager) {
   263             StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
   264             Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
   265                 ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
   266                 : standardFileManager.getLocation(CLASS_PATH);
   268             if (needClassLoader(options.get(PROCESSOR), workingPath) )
   269                 handleException(key, e);
   271         } else {
   272             handleException(key, e);
   273         }
   275         java.util.List<Processor> pl = Collections.emptyList();
   276         return pl.iterator();
   277     }
   279     /**
   280      * Handle a security exception thrown during initializing the
   281      * Processor iterator.
   282      */
   283     private void handleException(String key, Exception e) {
   284         if (e != null) {
   285             log.error(key, e.getLocalizedMessage());
   286             throw new Abort(e);
   287         } else {
   288             log.error(key);
   289             throw new Abort();
   290         }
   291     }
   293     /**
   294      * Use a service loader appropriate for the platform to provide an
   295      * iterator over annotations processors.  If
   296      * java.util.ServiceLoader is present use it, otherwise, use
   297      * sun.misc.Service, otherwise fail if a loader is needed.
   298      */
   299     private class ServiceIterator implements Iterator<Processor> {
   300         // The to-be-wrapped iterator.
   301         private Iterator<?> iterator;
   302         private Log log;
   303         private Class<?> loaderClass;
   304         private boolean jusl;
   305         private Object loader;
   307         ServiceIterator(ClassLoader classLoader, Log log) {
   308             String loadMethodName;
   310             this.log = log;
   311             try {
   312                 try {
   313                     loaderClass = Class.forName("java.util.ServiceLoader");
   314                     loadMethodName = "load";
   315                     jusl = true;
   316                 } catch (ClassNotFoundException cnfe) {
   317                     try {
   318                         loaderClass = Class.forName("sun.misc.Service");
   319                         loadMethodName = "providers";
   320                         jusl = false;
   321                     } catch (ClassNotFoundException cnfe2) {
   322                         // Fail softly if a loader is not actually needed.
   323                         this.iterator = handleServiceLoaderUnavailability("proc.no.service",
   324                                                                           null);
   325                         return;
   326                     }
   327                 }
   329                 // java.util.ServiceLoader.load or sun.misc.Service.providers
   330                 Method loadMethod = loaderClass.getMethod(loadMethodName,
   331                                                           Class.class,
   332                                                           ClassLoader.class);
   334                 Object result = loadMethod.invoke(null,
   335                                                   Processor.class,
   336                                                   classLoader);
   338                 // For java.util.ServiceLoader, we have to call another
   339                 // method to get the iterator.
   340                 if (jusl) {
   341                     loader = result; // Store ServiceLoader to call reload later
   342                     Method m = loaderClass.getMethod("iterator");
   343                     result = m.invoke(result); // serviceLoader.iterator();
   344                 }
   346                 // The result should now be an iterator.
   347                 this.iterator = (Iterator<?>) result;
   348             } catch (Throwable t) {
   349                 log.error("proc.service.problem");
   350                 throw new Abort(t);
   351             }
   352         }
   354         public boolean hasNext() {
   355             try {
   356                 return iterator.hasNext();
   357             } catch (Throwable t) {
   358                 if ("ServiceConfigurationError".
   359                     equals(t.getClass().getSimpleName())) {
   360                     log.error("proc.bad.config.file", t.getLocalizedMessage());
   361                 }
   362                 throw new Abort(t);
   363             }
   364         }
   366         public Processor next() {
   367             try {
   368                 return (Processor)(iterator.next());
   369             } catch (Throwable t) {
   370                 if ("ServiceConfigurationError".
   371                     equals(t.getClass().getSimpleName())) {
   372                     log.error("proc.bad.config.file", t.getLocalizedMessage());
   373                 } else {
   374                     log.error("proc.processor.constructor.error", t.getLocalizedMessage());
   375                 }
   376                 throw new Abort(t);
   377             }
   378         }
   380         public void remove() {
   381             throw new UnsupportedOperationException();
   382         }
   384         public void close() {
   385             if (jusl) {
   386                 try {
   387                     // Call java.util.ServiceLoader.reload
   388                     Method reloadMethod = loaderClass.getMethod("reload");
   389                     reloadMethod.invoke(loader);
   390                 } catch(Exception e) {
   391                     ; // Ignore problems during a call to reload.
   392                 }
   393             }
   394         }
   395     }
   398     private static class NameProcessIterator implements Iterator<Processor> {
   399         Processor nextProc = null;
   400         Iterator<String> names;
   401         ClassLoader processorCL;
   402         Log log;
   404         NameProcessIterator(String names, ClassLoader processorCL, Log log) {
   405             this.names = Arrays.asList(names.split(",")).iterator();
   406             this.processorCL = processorCL;
   407             this.log = log;
   408         }
   410         public boolean hasNext() {
   411             if (nextProc != null)
   412                 return true;
   413             else {
   414                 if (!names.hasNext())
   415                     return false;
   416                 else {
   417                     String processorName = names.next();
   419                     Processor processor;
   420                     try {
   421                         try {
   422                             processor =
   423                                 (Processor) (processorCL.loadClass(processorName).newInstance());
   424                         } catch (ClassNotFoundException cnfe) {
   425                             log.error("proc.processor.not.found", processorName);
   426                             return false;
   427                         } catch (ClassCastException cce) {
   428                             log.error("proc.processor.wrong.type", processorName);
   429                             return false;
   430                         } catch (Exception e ) {
   431                             log.error("proc.processor.cant.instantiate", processorName);
   432                             return false;
   433                         }
   434                     } catch(Throwable t) {
   435                         throw new AnnotationProcessingError(t);
   436                     }
   437                     nextProc = processor;
   438                     return true;
   439                 }
   441             }
   442         }
   444         public Processor next() {
   445             if (hasNext()) {
   446                 Processor p = nextProc;
   447                 nextProc = null;
   448                 return p;
   449             } else
   450                 throw new NoSuchElementException();
   451         }
   453         public void remove () {
   454             throw new UnsupportedOperationException();
   455         }
   456     }
   458     public boolean atLeastOneProcessor() {
   459         return discoveredProcs.iterator().hasNext();
   460     }
   462     private Map<String, String> initProcessorOptions(Context context) {
   463         Options options = Options.instance(context);
   464         Set<String> keySet = options.keySet();
   465         Map<String, String> tempOptions = new LinkedHashMap<String, String>();
   467         for(String key : keySet) {
   468             if (key.startsWith("-A") && key.length() > 2) {
   469                 int sepIndex = key.indexOf('=');
   470                 String candidateKey = null;
   471                 String candidateValue = null;
   473                 if (sepIndex == -1)
   474                     candidateKey = key.substring(2);
   475                 else if (sepIndex >= 3) {
   476                     candidateKey = key.substring(2, sepIndex);
   477                     candidateValue = (sepIndex < key.length()-1)?
   478                         key.substring(sepIndex+1) : null;
   479                 }
   480                 tempOptions.put(candidateKey, candidateValue);
   481             }
   482         }
   484         return Collections.unmodifiableMap(tempOptions);
   485     }
   487     private Set<String> initUnmatchedProcessorOptions() {
   488         Set<String> unmatchedProcessorOptions = new HashSet<String>();
   489         unmatchedProcessorOptions.addAll(processorOptions.keySet());
   490         return unmatchedProcessorOptions;
   491     }
   493     /**
   494      * State about how a processor has been used by the tool.  If a
   495      * processor has been used on a prior round, its process method is
   496      * called on all subsequent rounds, perhaps with an empty set of
   497      * annotations to process.  The {@code annotatedSupported} method
   498      * caches the supported annotation information from the first (and
   499      * only) getSupportedAnnotationTypes call to the processor.
   500      */
   501     static class ProcessorState {
   502         public Processor processor;
   503         public boolean   contributed;
   504         private ArrayList<Pattern> supportedAnnotationPatterns;
   505         private ArrayList<String>  supportedOptionNames;
   507         ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
   508             processor = p;
   509             contributed = false;
   511             try {
   512                 processor.init(env);
   514                 checkSourceVersionCompatibility(source, log);
   516                 supportedAnnotationPatterns = new ArrayList<Pattern>();
   517                 for (String importString : processor.getSupportedAnnotationTypes()) {
   518                     supportedAnnotationPatterns.add(importStringToPattern(importString,
   519                                                                           processor,
   520                                                                           log));
   521                 }
   523                 supportedOptionNames = new ArrayList<String>();
   524                 for (String optionName : processor.getSupportedOptions() ) {
   525                     if (checkOptionName(optionName, log))
   526                         supportedOptionNames.add(optionName);
   527                 }
   529             } catch (Throwable t) {
   530                 throw new AnnotationProcessingError(t);
   531             }
   532         }
   534         /**
   535          * Checks whether or not a processor's source version is
   536          * compatible with the compilation source version.  The
   537          * processor's source version needs to be greater than or
   538          * equal to the source version of the compile.
   539          */
   540         private void checkSourceVersionCompatibility(Source source, Log log) {
   541             SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
   543             if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 )  {
   544                 log.warning("proc.processor.incompatible.source.version",
   545                             procSourceVersion,
   546                             processor.getClass().getName(),
   547                             source.name);
   548             }
   549         }
   551         private boolean checkOptionName(String optionName, Log log) {
   552             boolean valid = isValidOptionName(optionName);
   553             if (!valid)
   554                 log.error("proc.processor.bad.option.name",
   555                             optionName,
   556                             processor.getClass().getName());
   557             return valid;
   558         }
   560         public boolean annotationSupported(String annotationName) {
   561             for(Pattern p: supportedAnnotationPatterns) {
   562                 if (p.matcher(annotationName).matches())
   563                     return true;
   564             }
   565             return false;
   566         }
   568         /**
   569          * Remove options that are matched by this processor.
   570          */
   571         public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) {
   572             unmatchedProcessorOptions.removeAll(supportedOptionNames);
   573         }
   574     }
   576     // TODO: These two classes can probably be rewritten better...
   577     /**
   578      * This class holds information about the processors that have
   579      * been discoverd so far as well as the means to discover more, if
   580      * necessary.  A single iterator should be used per round of
   581      * annotation processing.  The iterator first visits already
   582      * discovered processors then fails over to the service provider
   583      * mechanism if additional queries are made.
   584      */
   585     class DiscoveredProcessors implements Iterable<ProcessorState> {
   587         class ProcessorStateIterator implements Iterator<ProcessorState> {
   588             DiscoveredProcessors psi;
   589             Iterator<ProcessorState> innerIter;
   590             boolean onProcInterator;
   592             ProcessorStateIterator(DiscoveredProcessors psi) {
   593                 this.psi = psi;
   594                 this.innerIter = psi.procStateList.iterator();
   595                 this.onProcInterator = false;
   596             }
   598             public ProcessorState next() {
   599                 if (!onProcInterator) {
   600                     if (innerIter.hasNext())
   601                         return innerIter.next();
   602                     else
   603                         onProcInterator = true;
   604                 }
   606                 if (psi.processorIterator.hasNext()) {
   607                     ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
   608                                                            log, source, JavacProcessingEnvironment.this);
   609                     psi.procStateList.add(ps);
   610                     return ps;
   611                 } else
   612                     throw new NoSuchElementException();
   613             }
   615             public boolean hasNext() {
   616                 if (onProcInterator)
   617                     return  psi.processorIterator.hasNext();
   618                 else
   619                     return innerIter.hasNext() || psi.processorIterator.hasNext();
   620             }
   622             public void remove () {
   623                 throw new UnsupportedOperationException();
   624             }
   626             /**
   627              * Run all remaining processors on the procStateList that
   628              * have not already run this round with an empty set of
   629              * annotations.
   630              */
   631             public void runContributingProcs(RoundEnvironment re) {
   632                 if (!onProcInterator) {
   633                     Set<TypeElement> emptyTypeElements = Collections.emptySet();
   634                     while(innerIter.hasNext()) {
   635                         ProcessorState ps = innerIter.next();
   636                         if (ps.contributed)
   637                             callProcessor(ps.processor, emptyTypeElements, re);
   638                     }
   639                 }
   640             }
   641         }
   643         Iterator<? extends Processor> processorIterator;
   644         ArrayList<ProcessorState>  procStateList;
   646         public ProcessorStateIterator iterator() {
   647             return new ProcessorStateIterator(this);
   648         }
   650         DiscoveredProcessors(Iterator<? extends Processor> processorIterator) {
   651             this.processorIterator = processorIterator;
   652             this.procStateList = new ArrayList<ProcessorState>();
   653         }
   655         /**
   656          * Free jar files, etc. if using a service loader.
   657          */
   658         public void close() {
   659             if (processorIterator != null &&
   660                 processorIterator instanceof ServiceIterator) {
   661                 ((ServiceIterator) processorIterator).close();
   662             }
   663         }
   664     }
   666     private void discoverAndRunProcs(Context context,
   667                                      Set<TypeElement> annotationsPresent,
   668                                      List<ClassSymbol> topLevelClasses,
   669                                      List<PackageSymbol> packageInfoFiles) {
   670         Map<String, TypeElement> unmatchedAnnotations =
   671             new HashMap<String, TypeElement>(annotationsPresent.size());
   673         for(TypeElement a  : annotationsPresent) {
   674                 unmatchedAnnotations.put(a.getQualifiedName().toString(),
   675                                          a);
   676         }
   678         // Give "*" processors a chance to match
   679         if (unmatchedAnnotations.size() == 0)
   680             unmatchedAnnotations.put("", null);
   682         DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
   683         // TODO: Create proper argument values; need past round
   684         // information to fill in this constructor.  Note that the 1
   685         // st round of processing could be the last round if there
   686         // were parse errors on the initial source files; however, we
   687         // are not doing processing in that case.
   689         Set<Element> rootElements = new LinkedHashSet<Element>();
   690         rootElements.addAll(topLevelClasses);
   691         rootElements.addAll(packageInfoFiles);
   692         rootElements = Collections.unmodifiableSet(rootElements);
   694         RoundEnvironment renv = new JavacRoundEnvironment(false,
   695                                                           false,
   696                                                           rootElements,
   697                                                           JavacProcessingEnvironment.this);
   699         while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
   700             ProcessorState ps = psi.next();
   701             Set<String>  matchedNames = new HashSet<String>();
   702             Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();
   704             for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) {
   705                 String unmatchedAnnotationName = entry.getKey();
   706                 if (ps.annotationSupported(unmatchedAnnotationName) ) {
   707                     matchedNames.add(unmatchedAnnotationName);
   708                     TypeElement te = entry.getValue();
   709                     if (te != null)
   710                         typeElements.add(te);
   711                 }
   712             }
   714             if (matchedNames.size() > 0 || ps.contributed) {
   715 //308                foundTypeProcessors = foundTypeProcessors || (ps.processor instanceof AbstractTypeProcessor);
   716                 boolean processingResult = callProcessor(ps.processor, typeElements, renv);
   717                 ps.contributed = true;
   718                 ps.removeSupportedOptions(unmatchedProcessorOptions);
   720                 if (printProcessorInfo || verbose) {
   721                     log.printNoteLines("x.print.processor.info",
   722                             ps.processor.getClass().getName(),
   723                             matchedNames.toString(),
   724                             processingResult);
   725                 }
   727                 if (processingResult) {
   728                     unmatchedAnnotations.keySet().removeAll(matchedNames);
   729                 }
   731             }
   732         }
   733         unmatchedAnnotations.remove("");
   735         if (lint && unmatchedAnnotations.size() > 0) {
   736             // Remove annotations processed by javac
   737             unmatchedAnnotations.keySet().removeAll(platformAnnotations);
   738             if (unmatchedAnnotations.size() > 0) {
   739                 log = Log.instance(context);
   740                 log.warning("proc.annotations.without.processors",
   741                             unmatchedAnnotations.keySet());
   742             }
   743         }
   745         // Run contributing processors that haven't run yet
   746         psi.runContributingProcs(renv);
   748         // Debugging
   749         if (options.isSet("displayFilerState"))
   750             filer.displayState();
   751     }
   753     /**
   754      * Computes the set of annotations on the symbol in question.
   755      * Leave class public for external testing purposes.
   756      */
   757     public static class ComputeAnnotationSet extends
   758         ElementScanner7<Set<TypeElement>, Set<TypeElement>> {
   759         final Elements elements;
   761         public ComputeAnnotationSet(Elements elements) {
   762             super();
   763             this.elements = elements;
   764         }
   766         @Override
   767         public Set<TypeElement> visitPackage(PackageElement e, Set<TypeElement> p) {
   768             // Don't scan enclosed elements of a package
   769             return p;
   770         }
   772         @Override
   773         public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
   774             for (AnnotationMirror annotationMirror :
   775                      elements.getAllAnnotationMirrors(e) ) {
   776                 Element e2 = annotationMirror.getAnnotationType().asElement();
   777                 p.add((TypeElement) e2);
   778             }
   779             return super.scan(e, p);
   780         }
   781     }
   783     private boolean callProcessor(Processor proc,
   784                                          Set<? extends TypeElement> tes,
   785                                          RoundEnvironment renv) {
   786         try {
   787             return proc.process(tes, renv);
   788         } catch (CompletionFailure ex) {
   789             StringWriter out = new StringWriter();
   790             ex.printStackTrace(new PrintWriter(out));
   791             log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
   792             return false;
   793         } catch (Throwable t) {
   794             throw new AnnotationProcessingError(t);
   795         }
   796     }
   798     /**
   799      * Helper object for a single round of annotation processing.
   800      */
   801     class Round {
   802         /** The round number. */
   803         final int number;
   804         /** The context for the round. */
   805         final Context context;
   806         /** The compiler for the round. */
   807         final JavaCompiler compiler;
   808         /** The log for the round. */
   809         final Log log;
   810         /** The number of warnings in the previous round. */
   811         final int priorWarnings;
   813         /** The ASTs to be compiled. */
   814         List<JCCompilationUnit> roots;
   815         /** The classes to be compiler that have were generated. */
   816         Map<String, JavaFileObject> genClassFiles;
   818         /** The set of annotations to be processed this round. */
   819         Set<TypeElement> annotationsPresent;
   820         /** The set of top level classes to be processed this round. */
   821         List<ClassSymbol> topLevelClasses;
   822         /** The set of package-info files to be processed this round. */
   823         List<PackageSymbol> packageInfoFiles;
   825         /** Create a round (common code). */
   826         private Round(Context context, int number, int priorWarnings) {
   827             this.context = context;
   828             this.number = number;
   829             this.priorWarnings = priorWarnings;
   831             compiler = JavaCompiler.instance(context);
   832             log = Log.instance(context);
   833             log.deferDiagnostics = true;
   835             // the following is for the benefit of JavacProcessingEnvironment.getContext()
   836             JavacProcessingEnvironment.this.context = context;
   838             // the following will be populated as needed
   839             topLevelClasses  = List.nil();
   840             packageInfoFiles = List.nil();
   841         }
   843         /** Create the first round. */
   844         Round(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols) {
   845             this(context, 1, 0);
   846             this.roots = roots;
   847             genClassFiles = new HashMap<String,JavaFileObject>();
   849             compiler.todo.clear(); // free the compiler's resources
   851             // The reverse() in the following line is to maintain behavioural
   852             // compatibility with the previous revision of the code. Strictly speaking,
   853             // it should not be necessary, but a javah golden file test fails without it.
   854             topLevelClasses =
   855                 getTopLevelClasses(roots).prependList(classSymbols.reverse());
   857             packageInfoFiles = getPackageInfoFiles(roots);
   859             findAnnotationsPresent();
   860         }
   862         /** Create a new round. */
   863         private Round(Round prev,
   864                 Set<JavaFileObject> newSourceFiles, Map<String,JavaFileObject> newClassFiles) {
   865             this(prev.nextContext(), prev.number+1, prev.compiler.log.nwarnings);
   866             this.genClassFiles = prev.genClassFiles;
   868             List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles);
   869             roots = cleanTrees(prev.roots).appendList(parsedFiles);
   871             // Check for errors after parsing
   872             if (unrecoverableError())
   873                 return;
   875             enterClassFiles(genClassFiles);
   876             List<ClassSymbol> newClasses = enterClassFiles(newClassFiles);
   877             genClassFiles.putAll(newClassFiles);
   878             enterTrees(roots);
   880             if (unrecoverableError())
   881                 return;
   883             topLevelClasses = join(
   884                     getTopLevelClasses(parsedFiles),
   885                     getTopLevelClassesFromClasses(newClasses));
   887             packageInfoFiles = join(
   888                     getPackageInfoFiles(parsedFiles),
   889                     getPackageInfoFilesFromClasses(newClasses));
   891             findAnnotationsPresent();
   892         }
   894         /** Create the next round to be used. */
   895         Round next(Set<JavaFileObject> newSourceFiles, Map<String, JavaFileObject> newClassFiles) {
   896             try {
   897                 return new Round(this, newSourceFiles, newClassFiles);
   898             } finally {
   899                 compiler.close(false);
   900             }
   901         }
   903         /** Create the compiler to be used for the final compilation. */
   904         JavaCompiler finalCompiler(boolean errorStatus) {
   905             try {
   906                 JavaCompiler c = JavaCompiler.instance(nextContext());
   907                 if (errorStatus) {
   908                     c.log.nwarnings += priorWarnings + compiler.log.nwarnings;
   909                     c.log.nerrors += compiler.log.nerrors;
   910                 }
   911                 return c;
   912             } finally {
   913                 compiler.close(false);
   914             }
   915         }
   917         /** Return the number of errors found so far in this round.
   918          * This may include uncoverable errors, such as parse errors,
   919          * and transient errors, such as missing symbols. */
   920         int errorCount() {
   921             return compiler.errorCount();
   922         }
   924         /** Return the number of warnings found so far in this round. */
   925         int warningCount() {
   926             return compiler.warningCount();
   927         }
   929         /** Return whether or not an unrecoverable error has occurred. */
   930         boolean unrecoverableError() {
   931             if (messager.errorRaised())
   932                 return true;
   934             for (JCDiagnostic d: log.deferredDiagnostics) {
   935                 switch (d.getKind()) {
   936                     case WARNING:
   937                         if (werror)
   938                             return true;
   939                         break;
   941                     case ERROR:
   942                         if (fatalErrors || !d.isFlagSet(RESOLVE_ERROR))
   943                             return true;
   944                         break;
   945                 }
   946             }
   948             return false;
   949         }
   951         /** Find the set of annotations present in the set of top level
   952          *  classes and package info files to be processed this round. */
   953         void findAnnotationsPresent() {
   954             ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
   955             // Use annotation processing to compute the set of annotations present
   956             annotationsPresent = new LinkedHashSet<TypeElement>();
   957             for (ClassSymbol classSym : topLevelClasses)
   958                 annotationComputer.scan(classSym, annotationsPresent);
   959             for (PackageSymbol pkgSym : packageInfoFiles)
   960                 annotationComputer.scan(pkgSym, annotationsPresent);
   961         }
   963         /** Enter a set of generated class files. */
   964         private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) {
   965             ClassReader reader = ClassReader.instance(context);
   966             Names names = Names.instance(context);
   967             List<ClassSymbol> list = List.nil();
   969             for (Map.Entry<String,JavaFileObject> entry : classFiles.entrySet()) {
   970                 Name name = names.fromString(entry.getKey());
   971                 JavaFileObject file = entry.getValue();
   972                 if (file.getKind() != JavaFileObject.Kind.CLASS)
   973                     throw new AssertionError(file);
   974                 ClassSymbol cs;
   975                 if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
   976                     Name packageName = Convert.packagePart(name);
   977                     PackageSymbol p = reader.enterPackage(packageName);
   978                     if (p.package_info == null)
   979                         p.package_info = reader.enterClass(Convert.shortName(name), p);
   980                     cs = p.package_info;
   981                     if (cs.classfile == null)
   982                         cs.classfile = file;
   983                 } else
   984                     cs = reader.enterClass(name, file);
   985                 list = list.prepend(cs);
   986             }
   987             return list.reverse();
   988         }
   990         /** Enter a set of syntax trees. */
   991         private void enterTrees(List<JCCompilationUnit> roots) {
   992             compiler.enterTrees(roots);
   993         }
   995         /** Run a processing round. */
   996         void run(boolean lastRound, boolean errorStatus) {
   997             printRoundInfo(lastRound);
   999             TaskListener taskListener = context.get(TaskListener.class);
  1000             if (taskListener != null)
  1001                 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
  1003             try {
  1004                 if (lastRound) {
  1005                     filer.setLastRound(true);
  1006                     Set<Element> emptyRootElements = Collections.emptySet(); // immutable
  1007                     RoundEnvironment renv = new JavacRoundEnvironment(true,
  1008                             errorStatus,
  1009                             emptyRootElements,
  1010                             JavacProcessingEnvironment.this);
  1011                     discoveredProcs.iterator().runContributingProcs(renv);
  1012                 } else {
  1013                     discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles);
  1015             } finally {
  1016                 if (taskListener != null)
  1017                     taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
  1021         void showDiagnostics(boolean showAll) {
  1022             Set<JCDiagnostic.Kind> kinds = EnumSet.allOf(JCDiagnostic.Kind.class);
  1023             if (!showAll) {
  1024                 // suppress errors, which are all presumed to be transient resolve errors
  1025                 kinds.remove(JCDiagnostic.Kind.ERROR);
  1027             log.reportDeferredDiagnostics(kinds);
  1030         /** Print info about this round. */
  1031         private void printRoundInfo(boolean lastRound) {
  1032             if (printRounds || verbose) {
  1033                 List<ClassSymbol> tlc = lastRound ? List.<ClassSymbol>nil() : topLevelClasses;
  1034                 Set<TypeElement> ap = lastRound ? Collections.<TypeElement>emptySet() : annotationsPresent;
  1035                 log.printNoteLines("x.print.rounds",
  1036                         number,
  1037                         "{" + tlc.toString(", ") + "}",
  1038                         ap,
  1039                         lastRound);
  1043         /** Get the context for the next round of processing.
  1044          * Important values are propogated from round to round;
  1045          * other values are implicitly reset.
  1046          */
  1047         private Context nextContext() {
  1048             Context next = new Context();
  1050             Options options = Options.instance(context);
  1051             assert options != null;
  1052             next.put(Options.optionsKey, options);
  1054             PrintWriter out = context.get(Log.outKey);
  1055             assert out != null;
  1056             next.put(Log.outKey, out);
  1058             final boolean shareNames = true;
  1059             if (shareNames) {
  1060                 Names names = Names.instance(context);
  1061                 assert names != null;
  1062                 next.put(Names.namesKey, names);
  1065             DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
  1066             if (dl != null)
  1067                 next.put(DiagnosticListener.class, dl);
  1069             TaskListener tl = context.get(TaskListener.class);
  1070             if (tl != null)
  1071                 next.put(TaskListener.class, tl);
  1073             JavaFileManager jfm = context.get(JavaFileManager.class);
  1074             assert jfm != null;
  1075             next.put(JavaFileManager.class, jfm);
  1076             if (jfm instanceof JavacFileManager) {
  1077                 ((JavacFileManager)jfm).setContext(next);
  1080             Names names = Names.instance(context);
  1081             assert names != null;
  1082             next.put(Names.namesKey, names);
  1084             Keywords keywords = Keywords.instance(context);
  1085             assert(keywords != null);
  1086             next.put(Keywords.keywordsKey, keywords);
  1088             JavaCompiler oldCompiler = JavaCompiler.instance(context);
  1089             JavaCompiler nextCompiler = JavaCompiler.instance(next);
  1090             nextCompiler.initRound(oldCompiler);
  1092             filer.newRound(next);
  1093             messager.newRound(next);
  1094             elementUtils.setContext(next);
  1095             typeUtils.setContext(next);
  1097             JavacTaskImpl task = context.get(JavacTaskImpl.class);
  1098             if (task != null) {
  1099                 next.put(JavacTaskImpl.class, task);
  1100                 task.updateContext(next);
  1103             JavacTrees trees = context.get(JavacTrees.class);
  1104             if (trees != null) {
  1105                 next.put(JavacTrees.class, trees);
  1106                 trees.updateContext(next);
  1109             context.clear();
  1110             return next;
  1115     // TODO: internal catch clauses?; catch and rethrow an annotation
  1116     // processing error
  1117     public JavaCompiler doProcessing(Context context,
  1118                                      List<JCCompilationUnit> roots,
  1119                                      List<ClassSymbol> classSymbols,
  1120                                      Iterable<? extends PackageSymbol> pckSymbols) {
  1122         TaskListener taskListener = context.get(TaskListener.class);
  1123         log = Log.instance(context);
  1125         Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
  1126         for (PackageSymbol psym : pckSymbols)
  1127             specifiedPackages.add(psym);
  1128         this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
  1130         Round round = new Round(context, roots, classSymbols);
  1132         boolean errorStatus;
  1133         boolean moreToDo;
  1134         do {
  1135             // Run processors for round n
  1136             round.run(false, false);
  1138             // Processors for round n have run to completion.
  1139             // Check for errors and whether there is more work to do.
  1140             errorStatus = round.unrecoverableError();
  1141             moreToDo = moreToDo();
  1143             round.showDiagnostics(errorStatus || showResolveErrors);
  1145             // Set up next round.
  1146             // Copy mutable collections returned from filer.
  1147             round = round.next(
  1148                     new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()),
  1149                     new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses()));
  1151              // Check for errors during setup.
  1152             if (round.unrecoverableError())
  1153                 errorStatus = true;
  1155         } while (moreToDo && !errorStatus);
  1157         // run last round
  1158         round.run(true, errorStatus);
  1159         round.showDiagnostics(true);
  1161         filer.warnIfUnclosedFiles();
  1162         warnIfUnmatchedOptions();
  1164         /*
  1165          * If an annotation processor raises an error in a round,
  1166          * that round runs to completion and one last round occurs.
  1167          * The last round may also occur because no more source or
  1168          * class files have been generated.  Therefore, if an error
  1169          * was raised on either of the last *two* rounds, the compile
  1170          * should exit with a nonzero exit code.  The current value of
  1171          * errorStatus holds whether or not an error was raised on the
  1172          * second to last round; errorRaised() gives the error status
  1173          * of the last round.
  1174          */
  1175         if (messager.errorRaised()
  1176                 || werror && round.warningCount() > 0 && round.errorCount() > 0)
  1177             errorStatus = true;
  1179         Set<JavaFileObject> newSourceFiles =
  1180                 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
  1181         roots = cleanTrees(round.roots);
  1183         JavaCompiler compiler = round.finalCompiler(errorStatus);
  1185         if (newSourceFiles.size() > 0)
  1186             roots = roots.appendList(compiler.parseFiles(newSourceFiles));
  1188         errorStatus = errorStatus || (compiler.errorCount() > 0);
  1190         // Free resources
  1191         this.close();
  1193         if (taskListener != null)
  1194             taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1196         if (errorStatus) {
  1197             if (compiler.errorCount() == 0)
  1198                 compiler.log.nerrors++;
  1199             return compiler;
  1202         if (procOnly && !foundTypeProcessors) {
  1203             compiler.todo.clear();
  1204         } else {
  1205             if (procOnly && foundTypeProcessors)
  1206                 compiler.shouldStopPolicy = CompileState.FLOW;
  1208             compiler.enterTrees(roots);
  1211         return compiler;
  1214     private void warnIfUnmatchedOptions() {
  1215         if (!unmatchedProcessorOptions.isEmpty()) {
  1216             log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
  1220     /**
  1221      * Free resources related to annotation processing.
  1222      */
  1223     public void close() {
  1224         filer.close();
  1225         if (discoveredProcs != null) // Make calling close idempotent
  1226             discoveredProcs.close();
  1227         discoveredProcs = null;
  1228         if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
  1229             try {
  1230                 ((Closeable) processorClassLoader).close();
  1231             } catch (IOException e) {
  1232                 JCDiagnostic msg = diags.fragment("fatal.err.cant.close.loader");
  1233                 throw new FatalError(msg, e);
  1238     private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
  1239         List<ClassSymbol> classes = List.nil();
  1240         for (JCCompilationUnit unit : units) {
  1241             for (JCTree node : unit.defs) {
  1242                 if (node.getTag() == JCTree.CLASSDEF) {
  1243                     ClassSymbol sym = ((JCClassDecl) node).sym;
  1244                     assert sym != null;
  1245                     classes = classes.prepend(sym);
  1249         return classes.reverse();
  1252     private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) {
  1253         List<ClassSymbol> classes = List.nil();
  1254         for (ClassSymbol sym : syms) {
  1255             if (!isPkgInfo(sym)) {
  1256                 classes = classes.prepend(sym);
  1259         return classes.reverse();
  1262     private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
  1263         List<PackageSymbol> packages = List.nil();
  1264         for (JCCompilationUnit unit : units) {
  1265             if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
  1266                 packages = packages.prepend(unit.packge);
  1269         return packages.reverse();
  1272     private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) {
  1273         List<PackageSymbol> packages = List.nil();
  1274         for (ClassSymbol sym : syms) {
  1275             if (isPkgInfo(sym)) {
  1276                 packages = packages.prepend((PackageSymbol) sym.owner);
  1279         return packages.reverse();
  1282     // avoid unchecked warning from use of varargs
  1283     private static <T> List<T> join(List<T> list1, List<T> list2) {
  1284         return list1.appendList(list2);
  1287     private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
  1288         return fo.isNameCompatible("package-info", kind);
  1291     private boolean isPkgInfo(ClassSymbol sym) {
  1292         return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
  1295     /*
  1296      * Called retroactively to determine if a class loader was required,
  1297      * after we have failed to create one.
  1298      */
  1299     private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
  1300         if (procNames != null)
  1301             return true;
  1303         String procPath;
  1304         URL[] urls = new URL[1];
  1305         for(File pathElement : workingpath) {
  1306             try {
  1307                 urls[0] = pathElement.toURI().toURL();
  1308                 if (ServiceProxy.hasService(Processor.class, urls))
  1309                     return true;
  1310             } catch (MalformedURLException ex) {
  1311                 throw new AssertionError(ex);
  1313             catch (ServiceProxy.ServiceConfigurationError e) {
  1314                 log.error("proc.bad.config.file", e.getLocalizedMessage());
  1315                 return true;
  1319         return false;
  1322     private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) {
  1323         for (T node : nodes)
  1324             treeCleaner.scan(node);
  1325         return nodes;
  1328     private static TreeScanner treeCleaner = new TreeScanner() {
  1329             public void scan(JCTree node) {
  1330                 super.scan(node);
  1331                 if (node != null)
  1332                     node.type = null;
  1334             public void visitTopLevel(JCCompilationUnit node) {
  1335                 node.packge = null;
  1336                 super.visitTopLevel(node);
  1338             public void visitClassDef(JCClassDecl node) {
  1339                 node.sym = null;
  1340                 super.visitClassDef(node);
  1342             public void visitMethodDef(JCMethodDecl node) {
  1343                 node.sym = null;
  1344                 super.visitMethodDef(node);
  1346             public void visitVarDef(JCVariableDecl node) {
  1347                 node.sym = null;
  1348                 super.visitVarDef(node);
  1350             public void visitNewClass(JCNewClass node) {
  1351                 node.constructor = null;
  1352                 super.visitNewClass(node);
  1354             public void visitAssignop(JCAssignOp node) {
  1355                 node.operator = null;
  1356                 super.visitAssignop(node);
  1358             public void visitUnary(JCUnary node) {
  1359                 node.operator = null;
  1360                 super.visitUnary(node);
  1362             public void visitBinary(JCBinary node) {
  1363                 node.operator = null;
  1364                 super.visitBinary(node);
  1366             public void visitSelect(JCFieldAccess node) {
  1367                 node.sym = null;
  1368                 super.visitSelect(node);
  1370             public void visitIdent(JCIdent node) {
  1371                 node.sym = null;
  1372                 super.visitIdent(node);
  1374         };
  1377     private boolean moreToDo() {
  1378         return filer.newFiles();
  1381     /**
  1382      * {@inheritdoc}
  1384      * Command line options suitable for presenting to annotation
  1385      * processors.  "-Afoo=bar" should be "-Afoo" => "bar".
  1386      */
  1387     public Map<String,String> getOptions() {
  1388         return processorOptions;
  1391     public Messager getMessager() {
  1392         return messager;
  1395     public Filer getFiler() {
  1396         return filer;
  1399     public JavacElements getElementUtils() {
  1400         return elementUtils;
  1403     public JavacTypes getTypeUtils() {
  1404         return typeUtils;
  1407     public SourceVersion getSourceVersion() {
  1408         return Source.toSourceVersion(source);
  1411     public Locale getLocale() {
  1412         return messages.getCurrentLocale();
  1415     public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
  1416         return specifiedPackages;
  1419     private static final Pattern allMatches = Pattern.compile(".*");
  1420     public static final Pattern noMatches  = Pattern.compile("(\\P{all})+");
  1422     /**
  1423      * Convert import-style string for supported annotations into a
  1424      * regex matching that string.  If the string is a valid
  1425      * import-style string, return a regex that won't match anything.
  1426      */
  1427     private static Pattern importStringToPattern(String s, Processor p, Log log) {
  1428         if (isValidImportString(s)) {
  1429             return validImportStringToPattern(s);
  1430         } else {
  1431             log.warning("proc.malformed.supported.string", s, p.getClass().getName());
  1432             return noMatches; // won't match any valid identifier
  1436     /**
  1437      * Return true if the argument string is a valid import-style
  1438      * string specifying claimed annotations; return false otherwise.
  1439      */
  1440     public static boolean isValidImportString(String s) {
  1441         if (s.equals("*"))
  1442             return true;
  1444         boolean valid = true;
  1445         String t = s;
  1446         int index = t.indexOf('*');
  1448         if (index != -1) {
  1449             // '*' must be last character...
  1450             if (index == t.length() -1) {
  1451                 // ... any and preceding character must be '.'
  1452                 if ( index-1 >= 0 ) {
  1453                     valid = t.charAt(index-1) == '.';
  1454                     // Strip off ".*$" for identifier checks
  1455                     t = t.substring(0, t.length()-2);
  1457             } else
  1458                 return false;
  1461         // Verify string is off the form (javaId \.)+ or javaId
  1462         if (valid) {
  1463             String[] javaIds = t.split("\\.", t.length()+2);
  1464             for(String javaId: javaIds)
  1465                 valid &= SourceVersion.isIdentifier(javaId);
  1467         return valid;
  1470     public static Pattern validImportStringToPattern(String s) {
  1471         if (s.equals("*")) {
  1472             return allMatches;
  1473         } else {
  1474             String s_prime = s.replace(".", "\\.");
  1476             if (s_prime.endsWith("*")) {
  1477                 s_prime =  s_prime.substring(0, s_prime.length() - 1) + ".+";
  1480             return Pattern.compile(s_prime);
  1484     /**
  1485      * For internal use only.  This method will be
  1486      * removed without warning.
  1487      */
  1488     public Context getContext() {
  1489         return context;
  1492     public String toString() {
  1493         return "javac ProcessingEnvironment";
  1496     public static boolean isValidOptionName(String optionName) {
  1497         for(String s : optionName.split("\\.", -1)) {
  1498             if (!SourceVersion.isIdentifier(s))
  1499                 return false;
  1501         return true;

mercurial