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

Fri, 25 Feb 2011 12:09:33 -0800

author
jjg
date
Fri, 25 Feb 2011 12:09:33 -0800
changeset 893
8f0dcb9499db
parent 872
a19b1f4f23c9
child 898
bf9f162c7104
permissions
-rw-r--r--

7021650: fix Context issues
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright (c) 2005, 2011, 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 import com.sun.source.util.TaskEvent;
    53 import com.sun.source.util.TaskListener;
    54 import com.sun.tools.javac.api.JavacTaskImpl;
    55 import com.sun.tools.javac.api.JavacTrees;
    56 import com.sun.tools.javac.code.*;
    57 import com.sun.tools.javac.code.Symbol.*;
    58 import com.sun.tools.javac.file.FSInfo;
    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.Assert;
    70 import com.sun.tools.javac.util.Context;
    71 import com.sun.tools.javac.util.Convert;
    72 import com.sun.tools.javac.util.FatalError;
    73 import com.sun.tools.javac.util.JCDiagnostic;
    74 import com.sun.tools.javac.util.List;
    75 import com.sun.tools.javac.util.Log;
    76 import com.sun.tools.javac.util.JavacMessages;
    77 import com.sun.tools.javac.util.Name;
    78 import com.sun.tools.javac.util.Names;
    79 import com.sun.tools.javac.util.Options;
    81 import static javax.tools.StandardLocation.*;
    82 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    83 import static com.sun.tools.javac.main.OptionName.*;
    84 import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
    86 /**
    87  * Objects of this class hold and manage the state needed to support
    88  * annotation processing.
    89  *
    90  * <p><b>This is NOT part of any supported API.
    91  * If you write code that depends on this, you do so at your own risk.
    92  * This code and its internal interfaces are subject to change or
    93  * deletion without notice.</b>
    94  */
    95 public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
    96     Options options;
    98     private final boolean printProcessorInfo;
    99     private final boolean printRounds;
   100     private final boolean verbose;
   101     private final boolean lint;
   102     private final boolean procOnly;
   103     private final boolean fatalErrors;
   104     private final boolean werror;
   105     private final boolean showResolveErrors;
   106     private boolean foundTypeProcessors;
   108     private final JavacFiler filer;
   109     private final JavacMessager messager;
   110     private final JavacElements elementUtils;
   111     private final JavacTypes typeUtils;
   113     /**
   114      * Holds relevant state history of which processors have been
   115      * used.
   116      */
   117     private DiscoveredProcessors discoveredProcs;
   119     /**
   120      * Map of processor-specific options.
   121      */
   122     private final Map<String, String> processorOptions;
   124     /**
   125      */
   126     private final Set<String> unmatchedProcessorOptions;
   128     /**
   129      * Annotations implicitly processed and claimed by javac.
   130      */
   131     private final Set<String> platformAnnotations;
   133     /**
   134      * Set of packages given on command line.
   135      */
   136     private Set<PackageSymbol> specifiedPackages = Collections.emptySet();
   138     /** The log to be used for error reporting.
   139      */
   140     Log log;
   142     /** Diagnostic factory.
   143      */
   144     JCDiagnostic.Factory diags;
   146     /**
   147      * Source level of the compile.
   148      */
   149     Source source;
   151     private ClassLoader processorClassLoader;
   153     /**
   154      * JavacMessages object used for localization
   155      */
   156     private JavacMessages messages;
   158     private Context context;
   160     public JavacProcessingEnvironment(Context context, Iterable<? extends Processor> processors) {
   161         this.context = context;
   162         log = Log.instance(context);
   163         source = Source.instance(context);
   164         diags = JCDiagnostic.Factory.instance(context);
   165         options = Options.instance(context);
   166         printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
   167         printRounds = options.isSet(XPRINTROUNDS);
   168         verbose = options.isSet(VERBOSE);
   169         lint = Lint.instance(context).isEnabled(PROCESSING);
   170         procOnly = options.isSet(PROC, "only") || options.isSet(XPRINT);
   171         fatalErrors = options.isSet("fatalEnterError");
   172         showResolveErrors = options.isSet("showResolveErrors");
   173         werror = options.isSet(WERROR);
   174         platformAnnotations = initPlatformAnnotations();
   175         foundTypeProcessors = false;
   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         initProcessorIterator(context, processors);
   187     }
   189     private Set<String> initPlatformAnnotations() {
   190         Set<String> platformAnnotations = new HashSet<String>();
   191         platformAnnotations.add("java.lang.Deprecated");
   192         platformAnnotations.add("java.lang.Override");
   193         platformAnnotations.add("java.lang.SuppressWarnings");
   194         platformAnnotations.add("java.lang.annotation.Documented");
   195         platformAnnotations.add("java.lang.annotation.Inherited");
   196         platformAnnotations.add("java.lang.annotation.Retention");
   197         platformAnnotations.add("java.lang.annotation.Target");
   198         return Collections.unmodifiableSet(platformAnnotations);
   199     }
   201     private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
   202         Log   log   = Log.instance(context);
   203         Iterator<? extends Processor> processorIterator;
   205         if (options.isSet(XPRINT)) {
   206             try {
   207                 Processor processor = PrintingProcessor.class.newInstance();
   208                 processorIterator = List.of(processor).iterator();
   209             } catch (Throwable t) {
   210                 AssertionError assertError =
   211                     new AssertionError("Problem instantiating PrintingProcessor.");
   212                 assertError.initCause(t);
   213                 throw assertError;
   214             }
   215         } else if (processors != null) {
   216             processorIterator = processors.iterator();
   217         } else {
   218             String processorNames = options.get(PROCESSOR);
   219             JavaFileManager fileManager = context.get(JavaFileManager.class);
   220             try {
   221                 // If processorpath is not explicitly set, use the classpath.
   222                 processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
   223                     ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
   224                     : fileManager.getClassLoader(CLASS_PATH);
   226                 /*
   227                  * If the "-processor" option is used, search the appropriate
   228                  * path for the named class.  Otherwise, use a service
   229                  * provider mechanism to create the processor iterator.
   230                  */
   231                 if (processorNames != null) {
   232                     processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
   233                 } else {
   234                     processorIterator = new ServiceIterator(processorClassLoader, log);
   235                 }
   236             } catch (SecurityException e) {
   237                 /*
   238                  * A security exception will occur if we can't create a classloader.
   239                  * Ignore the exception if, with hindsight, we didn't need it anyway
   240                  * (i.e. no processor was specified either explicitly, or implicitly,
   241                  * in service configuration file.) Otherwise, we cannot continue.
   242                  */
   243                 processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader", e);
   244             }
   245         }
   246         discoveredProcs = new DiscoveredProcessors(processorIterator);
   247     }
   249     /**
   250      * Returns an empty processor iterator if no processors are on the
   251      * relevant path, otherwise if processors are present, logs an
   252      * error.  Called when a service loader is unavailable for some
   253      * reason, either because a service loader class cannot be found
   254      * or because a security policy prevents class loaders from being
   255      * created.
   256      *
   257      * @param key The resource key to use to log an error message
   258      * @param e   If non-null, pass this exception to Abort
   259      */
   260     private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
   261         JavaFileManager fileManager = context.get(JavaFileManager.class);
   263         if (fileManager instanceof JavacFileManager) {
   264             StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
   265             Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
   266                 ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
   267                 : standardFileManager.getLocation(CLASS_PATH);
   269             if (needClassLoader(options.get(PROCESSOR), workingPath) )
   270                 handleException(key, e);
   272         } else {
   273             handleException(key, e);
   274         }
   276         java.util.List<Processor> pl = Collections.emptyList();
   277         return pl.iterator();
   278     }
   280     /**
   281      * Handle a security exception thrown during initializing the
   282      * Processor iterator.
   283      */
   284     private void handleException(String key, Exception e) {
   285         if (e != null) {
   286             log.error(key, e.getLocalizedMessage());
   287             throw new Abort(e);
   288         } else {
   289             log.error(key);
   290             throw new Abort();
   291         }
   292     }
   294     /**
   295      * Use a service loader appropriate for the platform to provide an
   296      * iterator over annotations processors.  If
   297      * java.util.ServiceLoader is present use it, otherwise, use
   298      * sun.misc.Service, otherwise fail if a loader is needed.
   299      */
   300     private class ServiceIterator implements Iterator<Processor> {
   301         // The to-be-wrapped iterator.
   302         private Iterator<?> iterator;
   303         private Log log;
   304         private Class<?> loaderClass;
   305         private boolean jusl;
   306         private Object loader;
   308         ServiceIterator(ClassLoader classLoader, Log log) {
   309             String loadMethodName;
   311             this.log = log;
   312             try {
   313                 try {
   314                     loaderClass = Class.forName("java.util.ServiceLoader");
   315                     loadMethodName = "load";
   316                     jusl = true;
   317                 } catch (ClassNotFoundException cnfe) {
   318                     try {
   319                         loaderClass = Class.forName("sun.misc.Service");
   320                         loadMethodName = "providers";
   321                         jusl = false;
   322                     } catch (ClassNotFoundException cnfe2) {
   323                         // Fail softly if a loader is not actually needed.
   324                         this.iterator = handleServiceLoaderUnavailability("proc.no.service",
   325                                                                           null);
   326                         return;
   327                     }
   328                 }
   330                 // java.util.ServiceLoader.load or sun.misc.Service.providers
   331                 Method loadMethod = loaderClass.getMethod(loadMethodName,
   332                                                           Class.class,
   333                                                           ClassLoader.class);
   335                 Object result = loadMethod.invoke(null,
   336                                                   Processor.class,
   337                                                   classLoader);
   339                 // For java.util.ServiceLoader, we have to call another
   340                 // method to get the iterator.
   341                 if (jusl) {
   342                     loader = result; // Store ServiceLoader to call reload later
   343                     Method m = loaderClass.getMethod("iterator");
   344                     result = m.invoke(result); // serviceLoader.iterator();
   345                 }
   347                 // The result should now be an iterator.
   348                 this.iterator = (Iterator<?>) result;
   349             } catch (Throwable t) {
   350                 log.error("proc.service.problem");
   351                 throw new Abort(t);
   352             }
   353         }
   355         public boolean hasNext() {
   356             try {
   357                 return iterator.hasNext();
   358             } catch (Throwable t) {
   359                 if ("ServiceConfigurationError".
   360                     equals(t.getClass().getSimpleName())) {
   361                     log.error("proc.bad.config.file", t.getLocalizedMessage());
   362                 }
   363                 throw new Abort(t);
   364             }
   365         }
   367         public Processor next() {
   368             try {
   369                 return (Processor)(iterator.next());
   370             } catch (Throwable t) {
   371                 if ("ServiceConfigurationError".
   372                     equals(t.getClass().getSimpleName())) {
   373                     log.error("proc.bad.config.file", t.getLocalizedMessage());
   374                 } else {
   375                     log.error("proc.processor.constructor.error", t.getLocalizedMessage());
   376                 }
   377                 throw new Abort(t);
   378             }
   379         }
   381         public void remove() {
   382             throw new UnsupportedOperationException();
   383         }
   385         public void close() {
   386             if (jusl) {
   387                 try {
   388                     // Call java.util.ServiceLoader.reload
   389                     Method reloadMethod = loaderClass.getMethod("reload");
   390                     reloadMethod.invoke(loader);
   391                 } catch(Exception e) {
   392                     ; // Ignore problems during a call to reload.
   393                 }
   394             }
   395         }
   396     }
   399     private static class NameProcessIterator implements Iterator<Processor> {
   400         Processor nextProc = null;
   401         Iterator<String> names;
   402         ClassLoader processorCL;
   403         Log log;
   405         NameProcessIterator(String names, ClassLoader processorCL, Log log) {
   406             this.names = Arrays.asList(names.split(",")).iterator();
   407             this.processorCL = processorCL;
   408             this.log = log;
   409         }
   411         public boolean hasNext() {
   412             if (nextProc != null)
   413                 return true;
   414             else {
   415                 if (!names.hasNext())
   416                     return false;
   417                 else {
   418                     String processorName = names.next();
   420                     Processor processor;
   421                     try {
   422                         try {
   423                             processor =
   424                                 (Processor) (processorCL.loadClass(processorName).newInstance());
   425                         } catch (ClassNotFoundException cnfe) {
   426                             log.error("proc.processor.not.found", processorName);
   427                             return false;
   428                         } catch (ClassCastException cce) {
   429                             log.error("proc.processor.wrong.type", processorName);
   430                             return false;
   431                         } catch (Exception e ) {
   432                             log.error("proc.processor.cant.instantiate", processorName);
   433                             return false;
   434                         }
   435                     } catch(Throwable t) {
   436                         throw new AnnotationProcessingError(t);
   437                     }
   438                     nextProc = processor;
   439                     return true;
   440                 }
   442             }
   443         }
   445         public Processor next() {
   446             if (hasNext()) {
   447                 Processor p = nextProc;
   448                 nextProc = null;
   449                 return p;
   450             } else
   451                 throw new NoSuchElementException();
   452         }
   454         public void remove () {
   455             throw new UnsupportedOperationException();
   456         }
   457     }
   459     public boolean atLeastOneProcessor() {
   460         return discoveredProcs.iterator().hasNext();
   461     }
   463     private Map<String, String> initProcessorOptions(Context context) {
   464         Options options = Options.instance(context);
   465         Set<String> keySet = options.keySet();
   466         Map<String, String> tempOptions = new LinkedHashMap<String, String>();
   468         for(String key : keySet) {
   469             if (key.startsWith("-A") && key.length() > 2) {
   470                 int sepIndex = key.indexOf('=');
   471                 String candidateKey = null;
   472                 String candidateValue = null;
   474                 if (sepIndex == -1)
   475                     candidateKey = key.substring(2);
   476                 else if (sepIndex >= 3) {
   477                     candidateKey = key.substring(2, sepIndex);
   478                     candidateValue = (sepIndex < key.length()-1)?
   479                         key.substring(sepIndex+1) : null;
   480                 }
   481                 tempOptions.put(candidateKey, candidateValue);
   482             }
   483         }
   485         return Collections.unmodifiableMap(tempOptions);
   486     }
   488     private Set<String> initUnmatchedProcessorOptions() {
   489         Set<String> unmatchedProcessorOptions = new HashSet<String>();
   490         unmatchedProcessorOptions.addAll(processorOptions.keySet());
   491         return unmatchedProcessorOptions;
   492     }
   494     /**
   495      * State about how a processor has been used by the tool.  If a
   496      * processor has been used on a prior round, its process method is
   497      * called on all subsequent rounds, perhaps with an empty set of
   498      * annotations to process.  The {@code annotatedSupported} method
   499      * caches the supported annotation information from the first (and
   500      * only) getSupportedAnnotationTypes call to the processor.
   501      */
   502     static class ProcessorState {
   503         public Processor processor;
   504         public boolean   contributed;
   505         private ArrayList<Pattern> supportedAnnotationPatterns;
   506         private ArrayList<String>  supportedOptionNames;
   508         ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
   509             processor = p;
   510             contributed = false;
   512             try {
   513                 processor.init(env);
   515                 checkSourceVersionCompatibility(source, log);
   517                 supportedAnnotationPatterns = new ArrayList<Pattern>();
   518                 for (String importString : processor.getSupportedAnnotationTypes()) {
   519                     supportedAnnotationPatterns.add(importStringToPattern(importString,
   520                                                                           processor,
   521                                                                           log));
   522                 }
   524                 supportedOptionNames = new ArrayList<String>();
   525                 for (String optionName : processor.getSupportedOptions() ) {
   526                     if (checkOptionName(optionName, log))
   527                         supportedOptionNames.add(optionName);
   528                 }
   530             } catch (Throwable t) {
   531                 throw new AnnotationProcessingError(t);
   532             }
   533         }
   535         /**
   536          * Checks whether or not a processor's source version is
   537          * compatible with the compilation source version.  The
   538          * processor's source version needs to be greater than or
   539          * equal to the source version of the compile.
   540          */
   541         private void checkSourceVersionCompatibility(Source source, Log log) {
   542             SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
   544             if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 )  {
   545                 log.warning("proc.processor.incompatible.source.version",
   546                             procSourceVersion,
   547                             processor.getClass().getName(),
   548                             source.name);
   549             }
   550         }
   552         private boolean checkOptionName(String optionName, Log log) {
   553             boolean valid = isValidOptionName(optionName);
   554             if (!valid)
   555                 log.error("proc.processor.bad.option.name",
   556                             optionName,
   557                             processor.getClass().getName());
   558             return valid;
   559         }
   561         public boolean annotationSupported(String annotationName) {
   562             for(Pattern p: supportedAnnotationPatterns) {
   563                 if (p.matcher(annotationName).matches())
   564                     return true;
   565             }
   566             return false;
   567         }
   569         /**
   570          * Remove options that are matched by this processor.
   571          */
   572         public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) {
   573             unmatchedProcessorOptions.removeAll(supportedOptionNames);
   574         }
   575     }
   577     // TODO: These two classes can probably be rewritten better...
   578     /**
   579      * This class holds information about the processors that have
   580      * been discoverd so far as well as the means to discover more, if
   581      * necessary.  A single iterator should be used per round of
   582      * annotation processing.  The iterator first visits already
   583      * discovered processors then fails over to the service provider
   584      * mechanism if additional queries are made.
   585      */
   586     class DiscoveredProcessors implements Iterable<ProcessorState> {
   588         class ProcessorStateIterator implements Iterator<ProcessorState> {
   589             DiscoveredProcessors psi;
   590             Iterator<ProcessorState> innerIter;
   591             boolean onProcInterator;
   593             ProcessorStateIterator(DiscoveredProcessors psi) {
   594                 this.psi = psi;
   595                 this.innerIter = psi.procStateList.iterator();
   596                 this.onProcInterator = false;
   597             }
   599             public ProcessorState next() {
   600                 if (!onProcInterator) {
   601                     if (innerIter.hasNext())
   602                         return innerIter.next();
   603                     else
   604                         onProcInterator = true;
   605                 }
   607                 if (psi.processorIterator.hasNext()) {
   608                     ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
   609                                                            log, source, JavacProcessingEnvironment.this);
   610                     psi.procStateList.add(ps);
   611                     return ps;
   612                 } else
   613                     throw new NoSuchElementException();
   614             }
   616             public boolean hasNext() {
   617                 if (onProcInterator)
   618                     return  psi.processorIterator.hasNext();
   619                 else
   620                     return innerIter.hasNext() || psi.processorIterator.hasNext();
   621             }
   623             public void remove () {
   624                 throw new UnsupportedOperationException();
   625             }
   627             /**
   628              * Run all remaining processors on the procStateList that
   629              * have not already run this round with an empty set of
   630              * annotations.
   631              */
   632             public void runContributingProcs(RoundEnvironment re) {
   633                 if (!onProcInterator) {
   634                     Set<TypeElement> emptyTypeElements = Collections.emptySet();
   635                     while(innerIter.hasNext()) {
   636                         ProcessorState ps = innerIter.next();
   637                         if (ps.contributed)
   638                             callProcessor(ps.processor, emptyTypeElements, re);
   639                     }
   640                 }
   641             }
   642         }
   644         Iterator<? extends Processor> processorIterator;
   645         ArrayList<ProcessorState>  procStateList;
   647         public ProcessorStateIterator iterator() {
   648             return new ProcessorStateIterator(this);
   649         }
   651         DiscoveredProcessors(Iterator<? extends Processor> processorIterator) {
   652             this.processorIterator = processorIterator;
   653             this.procStateList = new ArrayList<ProcessorState>();
   654         }
   656         /**
   657          * Free jar files, etc. if using a service loader.
   658          */
   659         public void close() {
   660             if (processorIterator != null &&
   661                 processorIterator instanceof ServiceIterator) {
   662                 ((ServiceIterator) processorIterator).close();
   663             }
   664         }
   665     }
   667     private void discoverAndRunProcs(Context context,
   668                                      Set<TypeElement> annotationsPresent,
   669                                      List<ClassSymbol> topLevelClasses,
   670                                      List<PackageSymbol> packageInfoFiles) {
   671         Map<String, TypeElement> unmatchedAnnotations =
   672             new HashMap<String, TypeElement>(annotationsPresent.size());
   674         for(TypeElement a  : annotationsPresent) {
   675                 unmatchedAnnotations.put(a.getQualifiedName().toString(),
   676                                          a);
   677         }
   679         // Give "*" processors a chance to match
   680         if (unmatchedAnnotations.size() == 0)
   681             unmatchedAnnotations.put("", null);
   683         DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
   684         // TODO: Create proper argument values; need past round
   685         // information to fill in this constructor.  Note that the 1
   686         // st round of processing could be the last round if there
   687         // were parse errors on the initial source files; however, we
   688         // are not doing processing in that case.
   690         Set<Element> rootElements = new LinkedHashSet<Element>();
   691         rootElements.addAll(topLevelClasses);
   692         rootElements.addAll(packageInfoFiles);
   693         rootElements = Collections.unmodifiableSet(rootElements);
   695         RoundEnvironment renv = new JavacRoundEnvironment(false,
   696                                                           false,
   697                                                           rootElements,
   698                                                           JavacProcessingEnvironment.this);
   700         while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
   701             ProcessorState ps = psi.next();
   702             Set<String>  matchedNames = new HashSet<String>();
   703             Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();
   705             for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) {
   706                 String unmatchedAnnotationName = entry.getKey();
   707                 if (ps.annotationSupported(unmatchedAnnotationName) ) {
   708                     matchedNames.add(unmatchedAnnotationName);
   709                     TypeElement te = entry.getValue();
   710                     if (te != null)
   711                         typeElements.add(te);
   712                 }
   713             }
   715             if (matchedNames.size() > 0 || ps.contributed) {
   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(RECOVERABLE))
   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(context);
  1050             Options options = Options.instance(context);
  1051             Assert.checkNonNull(options);
  1052             next.put(Options.optionsKey, options);
  1054             PrintWriter out = context.get(Log.outKey);
  1055             Assert.checkNonNull(out);
  1056             next.put(Log.outKey, out);
  1058             final boolean shareNames = true;
  1059             if (shareNames) {
  1060                 Names names = Names.instance(context);
  1061                 Assert.checkNonNull(names);
  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             FSInfo fsInfo = context.get(FSInfo.class);
  1074             if (fsInfo != null)
  1075                 next.put(FSInfo.class, fsInfo);
  1077             JavaFileManager jfm = context.get(JavaFileManager.class);
  1078             Assert.checkNonNull(jfm);
  1079             next.put(JavaFileManager.class, jfm);
  1080             if (jfm instanceof JavacFileManager) {
  1081                 ((JavacFileManager)jfm).setContext(next);
  1084             Names names = Names.instance(context);
  1085             Assert.checkNonNull(names);
  1086             next.put(Names.namesKey, names);
  1088             Keywords keywords = Keywords.instance(context);
  1089             Assert.checkNonNull(keywords);
  1090             next.put(Keywords.keywordsKey, keywords);
  1092             JavaCompiler oldCompiler = JavaCompiler.instance(context);
  1093             JavaCompiler nextCompiler = JavaCompiler.instance(next);
  1094             nextCompiler.initRound(oldCompiler);
  1096             filer.newRound(next);
  1097             messager.newRound(next);
  1098             elementUtils.setContext(next);
  1099             typeUtils.setContext(next);
  1101             JavacTaskImpl task = context.get(JavacTaskImpl.class);
  1102             if (task != null) {
  1103                 next.put(JavacTaskImpl.class, task);
  1104                 task.updateContext(next);
  1107             JavacTrees trees = context.get(JavacTrees.class);
  1108             if (trees != null) {
  1109                 next.put(JavacTrees.class, trees);
  1110                 trees.updateContext(next);
  1113             context.clear();
  1114             return next;
  1119     // TODO: internal catch clauses?; catch and rethrow an annotation
  1120     // processing error
  1121     public JavaCompiler doProcessing(Context context,
  1122                                      List<JCCompilationUnit> roots,
  1123                                      List<ClassSymbol> classSymbols,
  1124                                      Iterable<? extends PackageSymbol> pckSymbols) {
  1126         TaskListener taskListener = context.get(TaskListener.class);
  1127         log = Log.instance(context);
  1129         Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
  1130         for (PackageSymbol psym : pckSymbols)
  1131             specifiedPackages.add(psym);
  1132         this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
  1134         Round round = new Round(context, roots, classSymbols);
  1136         boolean errorStatus;
  1137         boolean moreToDo;
  1138         do {
  1139             // Run processors for round n
  1140             round.run(false, false);
  1142             // Processors for round n have run to completion.
  1143             // Check for errors and whether there is more work to do.
  1144             errorStatus = round.unrecoverableError();
  1145             moreToDo = moreToDo();
  1147             round.showDiagnostics(errorStatus || showResolveErrors);
  1149             // Set up next round.
  1150             // Copy mutable collections returned from filer.
  1151             round = round.next(
  1152                     new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()),
  1153                     new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses()));
  1155              // Check for errors during setup.
  1156             if (round.unrecoverableError())
  1157                 errorStatus = true;
  1159         } while (moreToDo && !errorStatus);
  1161         // run last round
  1162         round.run(true, errorStatus);
  1163         round.showDiagnostics(true);
  1165         filer.warnIfUnclosedFiles();
  1166         warnIfUnmatchedOptions();
  1168         /*
  1169          * If an annotation processor raises an error in a round,
  1170          * that round runs to completion and one last round occurs.
  1171          * The last round may also occur because no more source or
  1172          * class files have been generated.  Therefore, if an error
  1173          * was raised on either of the last *two* rounds, the compile
  1174          * should exit with a nonzero exit code.  The current value of
  1175          * errorStatus holds whether or not an error was raised on the
  1176          * second to last round; errorRaised() gives the error status
  1177          * of the last round.
  1178          */
  1179         if (messager.errorRaised()
  1180                 || werror && round.warningCount() > 0 && round.errorCount() > 0)
  1181             errorStatus = true;
  1183         Set<JavaFileObject> newSourceFiles =
  1184                 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
  1185         roots = cleanTrees(round.roots);
  1187         JavaCompiler compiler = round.finalCompiler(errorStatus);
  1189         if (newSourceFiles.size() > 0)
  1190             roots = roots.appendList(compiler.parseFiles(newSourceFiles));
  1192         errorStatus = errorStatus || (compiler.errorCount() > 0);
  1194         // Free resources
  1195         this.close();
  1197         if (taskListener != null)
  1198             taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1200         if (errorStatus) {
  1201             if (compiler.errorCount() == 0)
  1202                 compiler.log.nerrors++;
  1203             return compiler;
  1206         if (procOnly && !foundTypeProcessors) {
  1207             compiler.todo.clear();
  1208         } else {
  1209             if (procOnly && foundTypeProcessors)
  1210                 compiler.shouldStopPolicy = CompileState.FLOW;
  1212             compiler.enterTrees(roots);
  1215         return compiler;
  1218     private void warnIfUnmatchedOptions() {
  1219         if (!unmatchedProcessorOptions.isEmpty()) {
  1220             log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
  1224     /**
  1225      * Free resources related to annotation processing.
  1226      */
  1227     public void close() {
  1228         filer.close();
  1229         if (discoveredProcs != null) // Make calling close idempotent
  1230             discoveredProcs.close();
  1231         discoveredProcs = null;
  1232         if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
  1233             try {
  1234                 ((Closeable) processorClassLoader).close();
  1235             } catch (IOException e) {
  1236                 JCDiagnostic msg = diags.fragment("fatal.err.cant.close.loader");
  1237                 throw new FatalError(msg, e);
  1242     private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
  1243         List<ClassSymbol> classes = List.nil();
  1244         for (JCCompilationUnit unit : units) {
  1245             for (JCTree node : unit.defs) {
  1246                 if (node.getTag() == JCTree.CLASSDEF) {
  1247                     ClassSymbol sym = ((JCClassDecl) node).sym;
  1248                     Assert.checkNonNull(sym);
  1249                     classes = classes.prepend(sym);
  1253         return classes.reverse();
  1256     private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) {
  1257         List<ClassSymbol> classes = List.nil();
  1258         for (ClassSymbol sym : syms) {
  1259             if (!isPkgInfo(sym)) {
  1260                 classes = classes.prepend(sym);
  1263         return classes.reverse();
  1266     private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
  1267         List<PackageSymbol> packages = List.nil();
  1268         for (JCCompilationUnit unit : units) {
  1269             if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
  1270                 packages = packages.prepend(unit.packge);
  1273         return packages.reverse();
  1276     private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) {
  1277         List<PackageSymbol> packages = List.nil();
  1278         for (ClassSymbol sym : syms) {
  1279             if (isPkgInfo(sym)) {
  1280                 packages = packages.prepend((PackageSymbol) sym.owner);
  1283         return packages.reverse();
  1286     // avoid unchecked warning from use of varargs
  1287     private static <T> List<T> join(List<T> list1, List<T> list2) {
  1288         return list1.appendList(list2);
  1291     private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
  1292         return fo.isNameCompatible("package-info", kind);
  1295     private boolean isPkgInfo(ClassSymbol sym) {
  1296         return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
  1299     /*
  1300      * Called retroactively to determine if a class loader was required,
  1301      * after we have failed to create one.
  1302      */
  1303     private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
  1304         if (procNames != null)
  1305             return true;
  1307         String procPath;
  1308         URL[] urls = new URL[1];
  1309         for(File pathElement : workingpath) {
  1310             try {
  1311                 urls[0] = pathElement.toURI().toURL();
  1312                 if (ServiceProxy.hasService(Processor.class, urls))
  1313                     return true;
  1314             } catch (MalformedURLException ex) {
  1315                 throw new AssertionError(ex);
  1317             catch (ServiceProxy.ServiceConfigurationError e) {
  1318                 log.error("proc.bad.config.file", e.getLocalizedMessage());
  1319                 return true;
  1323         return false;
  1326     private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) {
  1327         for (T node : nodes)
  1328             treeCleaner.scan(node);
  1329         return nodes;
  1332     private static TreeScanner treeCleaner = new TreeScanner() {
  1333             public void scan(JCTree node) {
  1334                 super.scan(node);
  1335                 if (node != null)
  1336                     node.type = null;
  1338             public void visitTopLevel(JCCompilationUnit node) {
  1339                 node.packge = null;
  1340                 super.visitTopLevel(node);
  1342             public void visitClassDef(JCClassDecl node) {
  1343                 node.sym = null;
  1344                 super.visitClassDef(node);
  1346             public void visitMethodDef(JCMethodDecl node) {
  1347                 node.sym = null;
  1348                 super.visitMethodDef(node);
  1350             public void visitVarDef(JCVariableDecl node) {
  1351                 node.sym = null;
  1352                 super.visitVarDef(node);
  1354             public void visitNewClass(JCNewClass node) {
  1355                 node.constructor = null;
  1356                 super.visitNewClass(node);
  1358             public void visitAssignop(JCAssignOp node) {
  1359                 node.operator = null;
  1360                 super.visitAssignop(node);
  1362             public void visitUnary(JCUnary node) {
  1363                 node.operator = null;
  1364                 super.visitUnary(node);
  1366             public void visitBinary(JCBinary node) {
  1367                 node.operator = null;
  1368                 super.visitBinary(node);
  1370             public void visitSelect(JCFieldAccess node) {
  1371                 node.sym = null;
  1372                 super.visitSelect(node);
  1374             public void visitIdent(JCIdent node) {
  1375                 node.sym = null;
  1376                 super.visitIdent(node);
  1378         };
  1381     private boolean moreToDo() {
  1382         return filer.newFiles();
  1385     /**
  1386      * {@inheritdoc}
  1388      * Command line options suitable for presenting to annotation
  1389      * processors.  "-Afoo=bar" should be "-Afoo" => "bar".
  1390      */
  1391     public Map<String,String> getOptions() {
  1392         return processorOptions;
  1395     public Messager getMessager() {
  1396         return messager;
  1399     public Filer getFiler() {
  1400         return filer;
  1403     public JavacElements getElementUtils() {
  1404         return elementUtils;
  1407     public JavacTypes getTypeUtils() {
  1408         return typeUtils;
  1411     public SourceVersion getSourceVersion() {
  1412         return Source.toSourceVersion(source);
  1415     public Locale getLocale() {
  1416         return messages.getCurrentLocale();
  1419     public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
  1420         return specifiedPackages;
  1423     private static final Pattern allMatches = Pattern.compile(".*");
  1424     public static final Pattern noMatches  = Pattern.compile("(\\P{all})+");
  1426     /**
  1427      * Convert import-style string for supported annotations into a
  1428      * regex matching that string.  If the string is a valid
  1429      * import-style string, return a regex that won't match anything.
  1430      */
  1431     private static Pattern importStringToPattern(String s, Processor p, Log log) {
  1432         if (isValidImportString(s)) {
  1433             return validImportStringToPattern(s);
  1434         } else {
  1435             log.warning("proc.malformed.supported.string", s, p.getClass().getName());
  1436             return noMatches; // won't match any valid identifier
  1440     /**
  1441      * Return true if the argument string is a valid import-style
  1442      * string specifying claimed annotations; return false otherwise.
  1443      */
  1444     public static boolean isValidImportString(String s) {
  1445         if (s.equals("*"))
  1446             return true;
  1448         boolean valid = true;
  1449         String t = s;
  1450         int index = t.indexOf('*');
  1452         if (index != -1) {
  1453             // '*' must be last character...
  1454             if (index == t.length() -1) {
  1455                 // ... any and preceding character must be '.'
  1456                 if ( index-1 >= 0 ) {
  1457                     valid = t.charAt(index-1) == '.';
  1458                     // Strip off ".*$" for identifier checks
  1459                     t = t.substring(0, t.length()-2);
  1461             } else
  1462                 return false;
  1465         // Verify string is off the form (javaId \.)+ or javaId
  1466         if (valid) {
  1467             String[] javaIds = t.split("\\.", t.length()+2);
  1468             for(String javaId: javaIds)
  1469                 valid &= SourceVersion.isIdentifier(javaId);
  1471         return valid;
  1474     public static Pattern validImportStringToPattern(String s) {
  1475         if (s.equals("*")) {
  1476             return allMatches;
  1477         } else {
  1478             String s_prime = s.replace(".", "\\.");
  1480             if (s_prime.endsWith("*")) {
  1481                 s_prime =  s_prime.substring(0, s_prime.length() - 1) + ".+";
  1484             return Pattern.compile(s_prime);
  1488     /**
  1489      * For internal use only.  This method will be
  1490      * removed without warning.
  1491      */
  1492     public Context getContext() {
  1493         return context;
  1496     public String toString() {
  1497         return "javac ProcessingEnvironment";
  1500     public static boolean isValidOptionName(String optionName) {
  1501         for(String s : optionName.split("\\.", -1)) {
  1502             if (!SourceVersion.isIdentifier(s))
  1503                 return false;
  1505         return true;

mercurial