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

Wed, 27 Apr 2016 01:34:52 +0800

author
aoqi
date
Wed, 27 Apr 2016 01:34:52 +0800
changeset 0
959103a6100f
child 2525
2eb010b6cb22
permissions
-rw-r--r--

Initial load
http://hg.openjdk.java.net/jdk8u/jdk8u/langtools/
changeset: 2573:53ca196be1ae
tag: jdk8u25-b17

     1 /*
     2  * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.processing;
    28 import java.io.Closeable;
    29 import java.io.File;
    30 import java.io.PrintWriter;
    31 import java.io.StringWriter;
    32 import java.net.MalformedURLException;
    33 import java.net.URL;
    34 import java.util.*;
    35 import java.util.regex.*;
    37 import javax.annotation.processing.*;
    38 import javax.lang.model.SourceVersion;
    39 import javax.lang.model.element.*;
    40 import javax.lang.model.util.*;
    41 import javax.tools.DiagnosticListener;
    42 import javax.tools.JavaFileManager;
    43 import javax.tools.JavaFileObject;
    44 import javax.tools.StandardJavaFileManager;
    45 import static javax.tools.StandardLocation.*;
    47 import com.sun.source.util.JavacTask;
    48 import com.sun.source.util.TaskEvent;
    49 import com.sun.tools.javac.api.BasicJavacTask;
    50 import com.sun.tools.javac.api.JavacTrees;
    51 import com.sun.tools.javac.api.MultiTaskListener;
    52 import com.sun.tools.javac.code.*;
    53 import com.sun.tools.javac.code.Symbol.*;
    54 import com.sun.tools.javac.file.FSInfo;
    55 import com.sun.tools.javac.file.JavacFileManager;
    56 import com.sun.tools.javac.jvm.*;
    57 import com.sun.tools.javac.jvm.ClassReader.BadClassFile;
    58 import com.sun.tools.javac.main.JavaCompiler;
    59 import com.sun.tools.javac.model.JavacElements;
    60 import com.sun.tools.javac.model.JavacTypes;
    61 import com.sun.tools.javac.parser.*;
    62 import com.sun.tools.javac.tree.*;
    63 import com.sun.tools.javac.tree.JCTree.*;
    64 import com.sun.tools.javac.util.Abort;
    65 import com.sun.tools.javac.util.Assert;
    66 import com.sun.tools.javac.util.ClientCodeException;
    67 import com.sun.tools.javac.util.Context;
    68 import com.sun.tools.javac.util.Convert;
    69 import com.sun.tools.javac.util.JCDiagnostic;
    70 import com.sun.tools.javac.util.JavacMessages;
    71 import com.sun.tools.javac.util.List;
    72 import com.sun.tools.javac.util.Log;
    73 import com.sun.tools.javac.util.Name;
    74 import com.sun.tools.javac.util.Names;
    75 import com.sun.tools.javac.util.Options;
    76 import com.sun.tools.javac.util.ServiceLoader;
    77 import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
    78 import static com.sun.tools.javac.main.Option.*;
    79 import static com.sun.tools.javac.comp.CompileStates.CompileState;
    80 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*;
    82 /**
    83  * Objects of this class hold and manage the state needed to support
    84  * annotation processing.
    85  *
    86  * <p><b>This is NOT part of any supported API.
    87  * If you write code that depends on this, you do so at your own risk.
    88  * This code and its internal interfaces are subject to change or
    89  * deletion without notice.</b>
    90  */
    91 public class JavacProcessingEnvironment implements ProcessingEnvironment, Closeable {
    92     private final Options options;
    94     private final boolean printProcessorInfo;
    95     private final boolean printRounds;
    96     private final boolean verbose;
    97     private final boolean lint;
    98     private final boolean fatalErrors;
    99     private final boolean werror;
   100     private final boolean showResolveErrors;
   102     private final JavacFiler filer;
   103     private final JavacMessager messager;
   104     private final JavacElements elementUtils;
   105     private final JavacTypes typeUtils;
   107     /**
   108      * Holds relevant state history of which processors have been
   109      * used.
   110      */
   111     private DiscoveredProcessors discoveredProcs;
   113     /**
   114      * Map of processor-specific options.
   115      */
   116     private final Map<String, String> processorOptions;
   118     /**
   119      */
   120     private final Set<String> unmatchedProcessorOptions;
   122     /**
   123      * Annotations implicitly processed and claimed by javac.
   124      */
   125     private final Set<String> platformAnnotations;
   127     /**
   128      * Set of packages given on command line.
   129      */
   130     private Set<PackageSymbol> specifiedPackages = Collections.emptySet();
   132     /** The log to be used for error reporting.
   133      */
   134     Log log;
   136     /** Diagnostic factory.
   137      */
   138     JCDiagnostic.Factory diags;
   140     /**
   141      * Source level of the compile.
   142      */
   143     Source source;
   145     private ClassLoader processorClassLoader;
   146     private SecurityException processorClassLoaderException;
   148     /**
   149      * JavacMessages object used for localization
   150      */
   151     private JavacMessages messages;
   153     private MultiTaskListener taskListener;
   155     private Context context;
   157     /** Get the JavacProcessingEnvironment instance for this context. */
   158     public static JavacProcessingEnvironment instance(Context context) {
   159         JavacProcessingEnvironment instance = context.get(JavacProcessingEnvironment.class);
   160         if (instance == null)
   161             instance = new JavacProcessingEnvironment(context);
   162         return instance;
   163     }
   165     protected JavacProcessingEnvironment(Context context) {
   166         this.context = context;
   167         context.put(JavacProcessingEnvironment.class, this);
   168         log = Log.instance(context);
   169         source = Source.instance(context);
   170         diags = JCDiagnostic.Factory.instance(context);
   171         options = Options.instance(context);
   172         printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
   173         printRounds = options.isSet(XPRINTROUNDS);
   174         verbose = options.isSet(VERBOSE);
   175         lint = Lint.instance(context).isEnabled(PROCESSING);
   176         if (options.isSet(PROC, "only") || options.isSet(XPRINT)) {
   177             JavaCompiler compiler = JavaCompiler.instance(context);
   178             compiler.shouldStopPolicyIfNoError = CompileState.PROCESS;
   179         }
   180         fatalErrors = options.isSet("fatalEnterError");
   181         showResolveErrors = options.isSet("showResolveErrors");
   182         werror = options.isSet(WERROR);
   183         platformAnnotations = initPlatformAnnotations();
   185         // Initialize services before any processors are initialized
   186         // in case processors use them.
   187         filer = new JavacFiler(context);
   188         messager = new JavacMessager(context, this);
   189         elementUtils = JavacElements.instance(context);
   190         typeUtils = JavacTypes.instance(context);
   191         processorOptions = initProcessorOptions(context);
   192         unmatchedProcessorOptions = initUnmatchedProcessorOptions();
   193         messages = JavacMessages.instance(context);
   194         taskListener = MultiTaskListener.instance(context);
   195         initProcessorClassLoader();
   196     }
   198     public void setProcessors(Iterable<? extends Processor> processors) {
   199         Assert.checkNull(discoveredProcs);
   200         initProcessorIterator(context, processors);
   201     }
   203     private Set<String> initPlatformAnnotations() {
   204         Set<String> platformAnnotations = new HashSet<String>();
   205         platformAnnotations.add("java.lang.Deprecated");
   206         platformAnnotations.add("java.lang.Override");
   207         platformAnnotations.add("java.lang.SuppressWarnings");
   208         platformAnnotations.add("java.lang.annotation.Documented");
   209         platformAnnotations.add("java.lang.annotation.Inherited");
   210         platformAnnotations.add("java.lang.annotation.Retention");
   211         platformAnnotations.add("java.lang.annotation.Target");
   212         return Collections.unmodifiableSet(platformAnnotations);
   213     }
   215     private void initProcessorClassLoader() {
   216         JavaFileManager fileManager = context.get(JavaFileManager.class);
   217         try {
   218             // If processorpath is not explicitly set, use the classpath.
   219             processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
   220                 ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
   221                 : fileManager.getClassLoader(CLASS_PATH);
   223             if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
   224                 JavaCompiler compiler = JavaCompiler.instance(context);
   225                 compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader);
   226             }
   227         } catch (SecurityException e) {
   228             processorClassLoaderException = e;
   229         }
   230     }
   232     private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
   233         Log   log   = Log.instance(context);
   234         Iterator<? extends Processor> processorIterator;
   236         if (options.isSet(XPRINT)) {
   237             try {
   238                 Processor processor = PrintingProcessor.class.newInstance();
   239                 processorIterator = List.of(processor).iterator();
   240             } catch (Throwable t) {
   241                 AssertionError assertError =
   242                     new AssertionError("Problem instantiating PrintingProcessor.");
   243                 assertError.initCause(t);
   244                 throw assertError;
   245             }
   246         } else if (processors != null) {
   247             processorIterator = processors.iterator();
   248         } else {
   249             String processorNames = options.get(PROCESSOR);
   250             if (processorClassLoaderException == null) {
   251                 /*
   252                  * If the "-processor" option is used, search the appropriate
   253                  * path for the named class.  Otherwise, use a service
   254                  * provider mechanism to create the processor iterator.
   255                  */
   256                 if (processorNames != null) {
   257                     processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
   258                 } else {
   259                     processorIterator = new ServiceIterator(processorClassLoader, log);
   260                 }
   261             } else {
   262                 /*
   263                  * A security exception will occur if we can't create a classloader.
   264                  * Ignore the exception if, with hindsight, we didn't need it anyway
   265                  * (i.e. no processor was specified either explicitly, or implicitly,
   266                  * in service configuration file.) Otherwise, we cannot continue.
   267                  */
   268                 processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader",
   269                         processorClassLoaderException);
   270             }
   271         }
   272         discoveredProcs = new DiscoveredProcessors(processorIterator);
   273     }
   275     /**
   276      * Returns an empty processor iterator if no processors are on the
   277      * relevant path, otherwise if processors are present, logs an
   278      * error.  Called when a service loader is unavailable for some
   279      * reason, either because a service loader class cannot be found
   280      * or because a security policy prevents class loaders from being
   281      * created.
   282      *
   283      * @param key The resource key to use to log an error message
   284      * @param e   If non-null, pass this exception to Abort
   285      */
   286     private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
   287         JavaFileManager fileManager = context.get(JavaFileManager.class);
   289         if (fileManager instanceof JavacFileManager) {
   290             StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
   291             Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
   292                 ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
   293                 : standardFileManager.getLocation(CLASS_PATH);
   295             if (needClassLoader(options.get(PROCESSOR), workingPath) )
   296                 handleException(key, e);
   298         } else {
   299             handleException(key, e);
   300         }
   302         java.util.List<Processor> pl = Collections.emptyList();
   303         return pl.iterator();
   304     }
   306     /**
   307      * Handle a security exception thrown during initializing the
   308      * Processor iterator.
   309      */
   310     private void handleException(String key, Exception e) {
   311         if (e != null) {
   312             log.error(key, e.getLocalizedMessage());
   313             throw new Abort(e);
   314         } else {
   315             log.error(key);
   316             throw new Abort();
   317         }
   318     }
   320     /**
   321      * Use a service loader appropriate for the platform to provide an
   322      * iterator over annotations processors; fails if a loader is
   323      * needed but unavailable.
   324      */
   325     private class ServiceIterator implements Iterator<Processor> {
   326         private Iterator<Processor> iterator;
   327         private Log log;
   328         private ServiceLoader<Processor> loader;
   330         ServiceIterator(ClassLoader classLoader, Log log) {
   331             this.log = log;
   332             try {
   333                 try {
   334                     loader = ServiceLoader.load(Processor.class, classLoader);
   335                     this.iterator = loader.iterator();
   336                 } catch (Exception e) {
   337                     // Fail softly if a loader is not actually needed.
   338                     this.iterator = handleServiceLoaderUnavailability("proc.no.service", null);
   339                 }
   340             } catch (Throwable t) {
   341                 log.error("proc.service.problem");
   342                 throw new Abort(t);
   343             }
   344         }
   346         public boolean hasNext() {
   347             try {
   348                 return iterator.hasNext();
   349             } catch(ServiceConfigurationError sce) {
   350                 log.error("proc.bad.config.file", sce.getLocalizedMessage());
   351                 throw new Abort(sce);
   352             } catch (Throwable t) {
   353                 throw new Abort(t);
   354             }
   355         }
   357         public Processor next() {
   358             try {
   359                 return iterator.next();
   360             } catch (ServiceConfigurationError sce) {
   361                 log.error("proc.bad.config.file", sce.getLocalizedMessage());
   362                 throw new Abort(sce);
   363             } catch (Throwable t) {
   364                 throw new Abort(t);
   365             }
   366         }
   368         public void remove() {
   369             throw new UnsupportedOperationException();
   370         }
   372         public void close() {
   373             if (loader != null) {
   374                 try {
   375                     loader.reload();
   376                 } catch(Exception e) {
   377                     ; // Ignore problems during a call to reload.
   378                 }
   379             }
   380         }
   381     }
   384     private static class NameProcessIterator implements Iterator<Processor> {
   385         Processor nextProc = null;
   386         Iterator<String> names;
   387         ClassLoader processorCL;
   388         Log log;
   390         NameProcessIterator(String names, ClassLoader processorCL, Log log) {
   391             this.names = Arrays.asList(names.split(",")).iterator();
   392             this.processorCL = processorCL;
   393             this.log = log;
   394         }
   396         public boolean hasNext() {
   397             if (nextProc != null)
   398                 return true;
   399             else {
   400                 if (!names.hasNext())
   401                     return false;
   402                 else {
   403                     String processorName = names.next();
   405                     Processor processor;
   406                     try {
   407                         try {
   408                             processor =
   409                                 (Processor) (processorCL.loadClass(processorName).newInstance());
   410                         } catch (ClassNotFoundException cnfe) {
   411                             log.error("proc.processor.not.found", processorName);
   412                             return false;
   413                         } catch (ClassCastException cce) {
   414                             log.error("proc.processor.wrong.type", processorName);
   415                             return false;
   416                         } catch (Exception e ) {
   417                             log.error("proc.processor.cant.instantiate", processorName);
   418                             return false;
   419                         }
   420                     } catch(ClientCodeException e) {
   421                         throw e;
   422                     } catch(Throwable t) {
   423                         throw new AnnotationProcessingError(t);
   424                     }
   425                     nextProc = processor;
   426                     return true;
   427                 }
   429             }
   430         }
   432         public Processor next() {
   433             if (hasNext()) {
   434                 Processor p = nextProc;
   435                 nextProc = null;
   436                 return p;
   437             } else
   438                 throw new NoSuchElementException();
   439         }
   441         public void remove () {
   442             throw new UnsupportedOperationException();
   443         }
   444     }
   446     public boolean atLeastOneProcessor() {
   447         return discoveredProcs.iterator().hasNext();
   448     }
   450     private Map<String, String> initProcessorOptions(Context context) {
   451         Options options = Options.instance(context);
   452         Set<String> keySet = options.keySet();
   453         Map<String, String> tempOptions = new LinkedHashMap<String, String>();
   455         for(String key : keySet) {
   456             if (key.startsWith("-A") && key.length() > 2) {
   457                 int sepIndex = key.indexOf('=');
   458                 String candidateKey = null;
   459                 String candidateValue = null;
   461                 if (sepIndex == -1)
   462                     candidateKey = key.substring(2);
   463                 else if (sepIndex >= 3) {
   464                     candidateKey = key.substring(2, sepIndex);
   465                     candidateValue = (sepIndex < key.length()-1)?
   466                         key.substring(sepIndex+1) : null;
   467                 }
   468                 tempOptions.put(candidateKey, candidateValue);
   469             }
   470         }
   472         return Collections.unmodifiableMap(tempOptions);
   473     }
   475     private Set<String> initUnmatchedProcessorOptions() {
   476         Set<String> unmatchedProcessorOptions = new HashSet<String>();
   477         unmatchedProcessorOptions.addAll(processorOptions.keySet());
   478         return unmatchedProcessorOptions;
   479     }
   481     /**
   482      * State about how a processor has been used by the tool.  If a
   483      * processor has been used on a prior round, its process method is
   484      * called on all subsequent rounds, perhaps with an empty set of
   485      * annotations to process.  The {@code annotationSupported} method
   486      * caches the supported annotation information from the first (and
   487      * only) getSupportedAnnotationTypes call to the processor.
   488      */
   489     static class ProcessorState {
   490         public Processor processor;
   491         public boolean   contributed;
   492         private ArrayList<Pattern> supportedAnnotationPatterns;
   493         private ArrayList<String>  supportedOptionNames;
   495         ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) {
   496             processor = p;
   497             contributed = false;
   499             try {
   500                 processor.init(env);
   502                 checkSourceVersionCompatibility(source, log);
   504                 supportedAnnotationPatterns = new ArrayList<Pattern>();
   505                 for (String importString : processor.getSupportedAnnotationTypes()) {
   506                     supportedAnnotationPatterns.add(importStringToPattern(importString,
   507                                                                           processor,
   508                                                                           log));
   509                 }
   511                 supportedOptionNames = new ArrayList<String>();
   512                 for (String optionName : processor.getSupportedOptions() ) {
   513                     if (checkOptionName(optionName, log))
   514                         supportedOptionNames.add(optionName);
   515                 }
   517             } catch (ClientCodeException e) {
   518                 throw e;
   519             } catch (Throwable t) {
   520                 throw new AnnotationProcessingError(t);
   521             }
   522         }
   524         /**
   525          * Checks whether or not a processor's source version is
   526          * compatible with the compilation source version.  The
   527          * processor's source version needs to be greater than or
   528          * equal to the source version of the compile.
   529          */
   530         private void checkSourceVersionCompatibility(Source source, Log log) {
   531             SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
   533             if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 )  {
   534                 log.warning("proc.processor.incompatible.source.version",
   535                             procSourceVersion,
   536                             processor.getClass().getName(),
   537                             source.name);
   538             }
   539         }
   541         private boolean checkOptionName(String optionName, Log log) {
   542             boolean valid = isValidOptionName(optionName);
   543             if (!valid)
   544                 log.error("proc.processor.bad.option.name",
   545                             optionName,
   546                             processor.getClass().getName());
   547             return valid;
   548         }
   550         public boolean annotationSupported(String annotationName) {
   551             for(Pattern p: supportedAnnotationPatterns) {
   552                 if (p.matcher(annotationName).matches())
   553                     return true;
   554             }
   555             return false;
   556         }
   558         /**
   559          * Remove options that are matched by this processor.
   560          */
   561         public void removeSupportedOptions(Set<String> unmatchedProcessorOptions) {
   562             unmatchedProcessorOptions.removeAll(supportedOptionNames);
   563         }
   564     }
   566     // TODO: These two classes can probably be rewritten better...
   567     /**
   568      * This class holds information about the processors that have
   569      * been discoverd so far as well as the means to discover more, if
   570      * necessary.  A single iterator should be used per round of
   571      * annotation processing.  The iterator first visits already
   572      * discovered processors then fails over to the service provider
   573      * mechanism if additional queries are made.
   574      */
   575     class DiscoveredProcessors implements Iterable<ProcessorState> {
   577         class ProcessorStateIterator implements Iterator<ProcessorState> {
   578             DiscoveredProcessors psi;
   579             Iterator<ProcessorState> innerIter;
   580             boolean onProcInterator;
   582             ProcessorStateIterator(DiscoveredProcessors psi) {
   583                 this.psi = psi;
   584                 this.innerIter = psi.procStateList.iterator();
   585                 this.onProcInterator = false;
   586             }
   588             public ProcessorState next() {
   589                 if (!onProcInterator) {
   590                     if (innerIter.hasNext())
   591                         return innerIter.next();
   592                     else
   593                         onProcInterator = true;
   594                 }
   596                 if (psi.processorIterator.hasNext()) {
   597                     ProcessorState ps = new ProcessorState(psi.processorIterator.next(),
   598                                                            log, source, JavacProcessingEnvironment.this);
   599                     psi.procStateList.add(ps);
   600                     return ps;
   601                 } else
   602                     throw new NoSuchElementException();
   603             }
   605             public boolean hasNext() {
   606                 if (onProcInterator)
   607                     return  psi.processorIterator.hasNext();
   608                 else
   609                     return innerIter.hasNext() || psi.processorIterator.hasNext();
   610             }
   612             public void remove () {
   613                 throw new UnsupportedOperationException();
   614             }
   616             /**
   617              * Run all remaining processors on the procStateList that
   618              * have not already run this round with an empty set of
   619              * annotations.
   620              */
   621             public void runContributingProcs(RoundEnvironment re) {
   622                 if (!onProcInterator) {
   623                     Set<TypeElement> emptyTypeElements = Collections.emptySet();
   624                     while(innerIter.hasNext()) {
   625                         ProcessorState ps = innerIter.next();
   626                         if (ps.contributed)
   627                             callProcessor(ps.processor, emptyTypeElements, re);
   628                     }
   629                 }
   630             }
   631         }
   633         Iterator<? extends Processor> processorIterator;
   634         ArrayList<ProcessorState>  procStateList;
   636         public ProcessorStateIterator iterator() {
   637             return new ProcessorStateIterator(this);
   638         }
   640         DiscoveredProcessors(Iterator<? extends Processor> processorIterator) {
   641             this.processorIterator = processorIterator;
   642             this.procStateList = new ArrayList<ProcessorState>();
   643         }
   645         /**
   646          * Free jar files, etc. if using a service loader.
   647          */
   648         public void close() {
   649             if (processorIterator != null &&
   650                 processorIterator instanceof ServiceIterator) {
   651                 ((ServiceIterator) processorIterator).close();
   652             }
   653         }
   654     }
   656     private void discoverAndRunProcs(Context context,
   657                                      Set<TypeElement> annotationsPresent,
   658                                      List<ClassSymbol> topLevelClasses,
   659                                      List<PackageSymbol> packageInfoFiles) {
   660         Map<String, TypeElement> unmatchedAnnotations =
   661             new HashMap<String, TypeElement>(annotationsPresent.size());
   663         for(TypeElement a  : annotationsPresent) {
   664                 unmatchedAnnotations.put(a.getQualifiedName().toString(),
   665                                          a);
   666         }
   668         // Give "*" processors a chance to match
   669         if (unmatchedAnnotations.size() == 0)
   670             unmatchedAnnotations.put("", null);
   672         DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
   673         // TODO: Create proper argument values; need past round
   674         // information to fill in this constructor.  Note that the 1
   675         // st round of processing could be the last round if there
   676         // were parse errors on the initial source files; however, we
   677         // are not doing processing in that case.
   679         Set<Element> rootElements = new LinkedHashSet<Element>();
   680         rootElements.addAll(topLevelClasses);
   681         rootElements.addAll(packageInfoFiles);
   682         rootElements = Collections.unmodifiableSet(rootElements);
   684         RoundEnvironment renv = new JavacRoundEnvironment(false,
   685                                                           false,
   686                                                           rootElements,
   687                                                           JavacProcessingEnvironment.this);
   689         while(unmatchedAnnotations.size() > 0 && psi.hasNext() ) {
   690             ProcessorState ps = psi.next();
   691             Set<String>  matchedNames = new HashSet<String>();
   692             Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();
   694             for (Map.Entry<String, TypeElement> entry: unmatchedAnnotations.entrySet()) {
   695                 String unmatchedAnnotationName = entry.getKey();
   696                 if (ps.annotationSupported(unmatchedAnnotationName) ) {
   697                     matchedNames.add(unmatchedAnnotationName);
   698                     TypeElement te = entry.getValue();
   699                     if (te != null)
   700                         typeElements.add(te);
   701                 }
   702             }
   704             if (matchedNames.size() > 0 || ps.contributed) {
   705                 boolean processingResult = callProcessor(ps.processor, typeElements, renv);
   706                 ps.contributed = true;
   707                 ps.removeSupportedOptions(unmatchedProcessorOptions);
   709                 if (printProcessorInfo || verbose) {
   710                     log.printLines("x.print.processor.info",
   711                             ps.processor.getClass().getName(),
   712                             matchedNames.toString(),
   713                             processingResult);
   714                 }
   716                 if (processingResult) {
   717                     unmatchedAnnotations.keySet().removeAll(matchedNames);
   718                 }
   720             }
   721         }
   722         unmatchedAnnotations.remove("");
   724         if (lint && unmatchedAnnotations.size() > 0) {
   725             // Remove annotations processed by javac
   726             unmatchedAnnotations.keySet().removeAll(platformAnnotations);
   727             if (unmatchedAnnotations.size() > 0) {
   728                 log = Log.instance(context);
   729                 log.warning("proc.annotations.without.processors",
   730                             unmatchedAnnotations.keySet());
   731             }
   732         }
   734         // Run contributing processors that haven't run yet
   735         psi.runContributingProcs(renv);
   737         // Debugging
   738         if (options.isSet("displayFilerState"))
   739             filer.displayState();
   740     }
   742     /**
   743      * Computes the set of annotations on the symbol in question.
   744      * Leave class public for external testing purposes.
   745      */
   746     public static class ComputeAnnotationSet extends
   747         ElementScanner8<Set<TypeElement>, Set<TypeElement>> {
   748         final Elements elements;
   750         public ComputeAnnotationSet(Elements elements) {
   751             super();
   752             this.elements = elements;
   753         }
   755         @Override
   756         public Set<TypeElement> visitPackage(PackageElement e, Set<TypeElement> p) {
   757             // Don't scan enclosed elements of a package
   758             return p;
   759         }
   761         @Override
   762         public Set<TypeElement> visitType(TypeElement e, Set<TypeElement> p) {
   763             // Type parameters are not considered to be enclosed by a type
   764             scan(e.getTypeParameters(), p);
   765             return super.visitType(e, p);
   766         }
   768         @Override
   769         public Set<TypeElement> visitExecutable(ExecutableElement e, Set<TypeElement> p) {
   770             // Type parameters are not considered to be enclosed by an executable
   771             scan(e.getTypeParameters(), p);
   772             return super.visitExecutable(e, p);
   773         }
   775         void addAnnotations(Element e, Set<TypeElement> p) {
   776             for (AnnotationMirror annotationMirror :
   777                      elements.getAllAnnotationMirrors(e) ) {
   778                 Element e2 = annotationMirror.getAnnotationType().asElement();
   779                 p.add((TypeElement) e2);
   780             }
   781         }
   783         @Override
   784         public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
   785             addAnnotations(e, p);
   786             return super.scan(e, p);
   787         }
   788     }
   790     private boolean callProcessor(Processor proc,
   791                                          Set<? extends TypeElement> tes,
   792                                          RoundEnvironment renv) {
   793         try {
   794             return proc.process(tes, renv);
   795         } catch (BadClassFile ex) {
   796             log.error("proc.cant.access.1", ex.sym, ex.getDetailValue());
   797             return false;
   798         } catch (CompletionFailure ex) {
   799             StringWriter out = new StringWriter();
   800             ex.printStackTrace(new PrintWriter(out));
   801             log.error("proc.cant.access", ex.sym, ex.getDetailValue(), out.toString());
   802             return false;
   803         } catch (ClientCodeException e) {
   804             throw e;
   805         } catch (Throwable t) {
   806             throw new AnnotationProcessingError(t);
   807         }
   808     }
   810     /**
   811      * Helper object for a single round of annotation processing.
   812      */
   813     class Round {
   814         /** The round number. */
   815         final int number;
   816         /** The context for the round. */
   817         final Context context;
   818         /** The compiler for the round. */
   819         final JavaCompiler compiler;
   820         /** The log for the round. */
   821         final Log log;
   822         /** The diagnostic handler for the round. */
   823         final Log.DeferredDiagnosticHandler deferredDiagnosticHandler;
   825         /** The ASTs to be compiled. */
   826         List<JCCompilationUnit> roots;
   827         /** The classes to be compiler that have were generated. */
   828         Map<String, JavaFileObject> genClassFiles;
   830         /** The set of annotations to be processed this round. */
   831         Set<TypeElement> annotationsPresent;
   832         /** The set of top level classes to be processed this round. */
   833         List<ClassSymbol> topLevelClasses;
   834         /** The set of package-info files to be processed this round. */
   835         List<PackageSymbol> packageInfoFiles;
   837         /** Create a round (common code). */
   838         private Round(Context context, int number, int priorErrors, int priorWarnings,
   839                 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
   840             this.context = context;
   841             this.number = number;
   843             compiler = JavaCompiler.instance(context);
   844             log = Log.instance(context);
   845             log.nerrors = priorErrors;
   846             log.nwarnings = priorWarnings;
   847             if (number == 1) {
   848                 Assert.checkNonNull(deferredDiagnosticHandler);
   849                 this.deferredDiagnosticHandler = deferredDiagnosticHandler;
   850             } else {
   851                 this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
   852             }
   854             // the following is for the benefit of JavacProcessingEnvironment.getContext()
   855             JavacProcessingEnvironment.this.context = context;
   857             // the following will be populated as needed
   858             topLevelClasses  = List.nil();
   859             packageInfoFiles = List.nil();
   860         }
   862         /** Create the first round. */
   863         Round(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols,
   864                 Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
   865             this(context, 1, 0, 0, deferredDiagnosticHandler);
   866             this.roots = roots;
   867             genClassFiles = new HashMap<String,JavaFileObject>();
   869             compiler.todo.clear(); // free the compiler's resources
   871             // The reverse() in the following line is to maintain behavioural
   872             // compatibility with the previous revision of the code. Strictly speaking,
   873             // it should not be necessary, but a javah golden file test fails without it.
   874             topLevelClasses =
   875                 getTopLevelClasses(roots).prependList(classSymbols.reverse());
   877             packageInfoFiles = getPackageInfoFiles(roots);
   879             findAnnotationsPresent();
   880         }
   882         /** Create a new round. */
   883         private Round(Round prev,
   884                 Set<JavaFileObject> newSourceFiles, Map<String,JavaFileObject> newClassFiles) {
   885             this(prev.nextContext(),
   886                     prev.number+1,
   887                     prev.compiler.log.nerrors,
   888                     prev.compiler.log.nwarnings,
   889                     null);
   890             this.genClassFiles = prev.genClassFiles;
   892             List<JCCompilationUnit> parsedFiles = compiler.parseFiles(newSourceFiles);
   893             roots = cleanTrees(prev.roots).appendList(parsedFiles);
   895             // Check for errors after parsing
   896             if (unrecoverableError())
   897                 return;
   899             enterClassFiles(genClassFiles);
   900             List<ClassSymbol> newClasses = enterClassFiles(newClassFiles);
   901             genClassFiles.putAll(newClassFiles);
   902             enterTrees(roots);
   904             if (unrecoverableError())
   905                 return;
   907             topLevelClasses = join(
   908                     getTopLevelClasses(parsedFiles),
   909                     getTopLevelClassesFromClasses(newClasses));
   911             packageInfoFiles = join(
   912                     getPackageInfoFiles(parsedFiles),
   913                     getPackageInfoFilesFromClasses(newClasses));
   915             findAnnotationsPresent();
   916         }
   918         /** Create the next round to be used. */
   919         Round next(Set<JavaFileObject> newSourceFiles, Map<String, JavaFileObject> newClassFiles) {
   920             try {
   921                 return new Round(this, newSourceFiles, newClassFiles);
   922             } finally {
   923                 compiler.close(false);
   924             }
   925         }
   927         /** Create the compiler to be used for the final compilation. */
   928         JavaCompiler finalCompiler() {
   929             try {
   930                 Context nextCtx = nextContext();
   931                 JavacProcessingEnvironment.this.context = nextCtx;
   932                 JavaCompiler c = JavaCompiler.instance(nextCtx);
   933                 c.log.initRound(compiler.log);
   934                 return c;
   935             } finally {
   936                 compiler.close(false);
   937             }
   938         }
   940         /** Return the number of errors found so far in this round.
   941          * This may include uncoverable errors, such as parse errors,
   942          * and transient errors, such as missing symbols. */
   943         int errorCount() {
   944             return compiler.errorCount();
   945         }
   947         /** Return the number of warnings found so far in this round. */
   948         int warningCount() {
   949             return compiler.warningCount();
   950         }
   952         /** Return whether or not an unrecoverable error has occurred. */
   953         boolean unrecoverableError() {
   954             if (messager.errorRaised())
   955                 return true;
   957             for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
   958                 switch (d.getKind()) {
   959                     case WARNING:
   960                         if (werror)
   961                             return true;
   962                         break;
   964                     case ERROR:
   965                         if (fatalErrors || !d.isFlagSet(RECOVERABLE))
   966                             return true;
   967                         break;
   968                 }
   969             }
   971             return false;
   972         }
   974         /** Find the set of annotations present in the set of top level
   975          *  classes and package info files to be processed this round. */
   976         void findAnnotationsPresent() {
   977             ComputeAnnotationSet annotationComputer = new ComputeAnnotationSet(elementUtils);
   978             // Use annotation processing to compute the set of annotations present
   979             annotationsPresent = new LinkedHashSet<TypeElement>();
   980             for (ClassSymbol classSym : topLevelClasses)
   981                 annotationComputer.scan(classSym, annotationsPresent);
   982             for (PackageSymbol pkgSym : packageInfoFiles)
   983                 annotationComputer.scan(pkgSym, annotationsPresent);
   984         }
   986         /** Enter a set of generated class files. */
   987         private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) {
   988             ClassReader reader = ClassReader.instance(context);
   989             Names names = Names.instance(context);
   990             List<ClassSymbol> list = List.nil();
   992             for (Map.Entry<String,JavaFileObject> entry : classFiles.entrySet()) {
   993                 Name name = names.fromString(entry.getKey());
   994                 JavaFileObject file = entry.getValue();
   995                 if (file.getKind() != JavaFileObject.Kind.CLASS)
   996                     throw new AssertionError(file);
   997                 ClassSymbol cs;
   998                 if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
   999                     Name packageName = Convert.packagePart(name);
  1000                     PackageSymbol p = reader.enterPackage(packageName);
  1001                     if (p.package_info == null)
  1002                         p.package_info = reader.enterClass(Convert.shortName(name), p);
  1003                     cs = p.package_info;
  1004                     if (cs.classfile == null)
  1005                         cs.classfile = file;
  1006                 } else
  1007                     cs = reader.enterClass(name, file);
  1008                 list = list.prepend(cs);
  1010             return list.reverse();
  1013         /** Enter a set of syntax trees. */
  1014         private void enterTrees(List<JCCompilationUnit> roots) {
  1015             compiler.enterTrees(roots);
  1018         /** Run a processing round. */
  1019         void run(boolean lastRound, boolean errorStatus) {
  1020             printRoundInfo(lastRound);
  1022             if (!taskListener.isEmpty())
  1023                 taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
  1025             try {
  1026                 if (lastRound) {
  1027                     filer.setLastRound(true);
  1028                     Set<Element> emptyRootElements = Collections.emptySet(); // immutable
  1029                     RoundEnvironment renv = new JavacRoundEnvironment(true,
  1030                             errorStatus,
  1031                             emptyRootElements,
  1032                             JavacProcessingEnvironment.this);
  1033                     discoveredProcs.iterator().runContributingProcs(renv);
  1034                 } else {
  1035                     discoverAndRunProcs(context, annotationsPresent, topLevelClasses, packageInfoFiles);
  1037             } catch (Throwable t) {
  1038                 // we're specifically expecting Abort here, but if any Throwable
  1039                 // comes by, we should flush all deferred diagnostics, rather than
  1040                 // drop them on the ground.
  1041                 deferredDiagnosticHandler.reportDeferredDiagnostics();
  1042                 log.popDiagnosticHandler(deferredDiagnosticHandler);
  1043                 throw t;
  1044             } finally {
  1045                 if (!taskListener.isEmpty())
  1046                     taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND));
  1050         void showDiagnostics(boolean showAll) {
  1051             Set<JCDiagnostic.Kind> kinds = EnumSet.allOf(JCDiagnostic.Kind.class);
  1052             if (!showAll) {
  1053                 // suppress errors, which are all presumed to be transient resolve errors
  1054                 kinds.remove(JCDiagnostic.Kind.ERROR);
  1056             deferredDiagnosticHandler.reportDeferredDiagnostics(kinds);
  1057             log.popDiagnosticHandler(deferredDiagnosticHandler);
  1060         /** Print info about this round. */
  1061         private void printRoundInfo(boolean lastRound) {
  1062             if (printRounds || verbose) {
  1063                 List<ClassSymbol> tlc = lastRound ? List.<ClassSymbol>nil() : topLevelClasses;
  1064                 Set<TypeElement> ap = lastRound ? Collections.<TypeElement>emptySet() : annotationsPresent;
  1065                 log.printLines("x.print.rounds",
  1066                         number,
  1067                         "{" + tlc.toString(", ") + "}",
  1068                         ap,
  1069                         lastRound);
  1073         /** Get the context for the next round of processing.
  1074          * Important values are propagated from round to round;
  1075          * other values are implicitly reset.
  1076          */
  1077         private Context nextContext() {
  1078             Context next = new Context(context);
  1080             Options options = Options.instance(context);
  1081             Assert.checkNonNull(options);
  1082             next.put(Options.optionsKey, options);
  1084             Locale locale = context.get(Locale.class);
  1085             if (locale != null)
  1086                 next.put(Locale.class, locale);
  1088             Assert.checkNonNull(messages);
  1089             next.put(JavacMessages.messagesKey, messages);
  1091             final boolean shareNames = true;
  1092             if (shareNames) {
  1093                 Names names = Names.instance(context);
  1094                 Assert.checkNonNull(names);
  1095                 next.put(Names.namesKey, names);
  1098             DiagnosticListener<?> dl = context.get(DiagnosticListener.class);
  1099             if (dl != null)
  1100                 next.put(DiagnosticListener.class, dl);
  1102             MultiTaskListener mtl = context.get(MultiTaskListener.taskListenerKey);
  1103             if (mtl != null)
  1104                 next.put(MultiTaskListener.taskListenerKey, mtl);
  1106             FSInfo fsInfo = context.get(FSInfo.class);
  1107             if (fsInfo != null)
  1108                 next.put(FSInfo.class, fsInfo);
  1110             JavaFileManager jfm = context.get(JavaFileManager.class);
  1111             Assert.checkNonNull(jfm);
  1112             next.put(JavaFileManager.class, jfm);
  1113             if (jfm instanceof JavacFileManager) {
  1114                 ((JavacFileManager)jfm).setContext(next);
  1117             Names names = Names.instance(context);
  1118             Assert.checkNonNull(names);
  1119             next.put(Names.namesKey, names);
  1121             Tokens tokens = Tokens.instance(context);
  1122             Assert.checkNonNull(tokens);
  1123             next.put(Tokens.tokensKey, tokens);
  1125             Log nextLog = Log.instance(next);
  1126             nextLog.initRound(log);
  1128             JavaCompiler oldCompiler = JavaCompiler.instance(context);
  1129             JavaCompiler nextCompiler = JavaCompiler.instance(next);
  1130             nextCompiler.initRound(oldCompiler);
  1132             filer.newRound(next);
  1133             messager.newRound(next);
  1134             elementUtils.setContext(next);
  1135             typeUtils.setContext(next);
  1137             JavacTask task = context.get(JavacTask.class);
  1138             if (task != null) {
  1139                 next.put(JavacTask.class, task);
  1140                 if (task instanceof BasicJavacTask)
  1141                     ((BasicJavacTask) task).updateContext(next);
  1144             JavacTrees trees = context.get(JavacTrees.class);
  1145             if (trees != null) {
  1146                 next.put(JavacTrees.class, trees);
  1147                 trees.updateContext(next);
  1150             context.clear();
  1151             return next;
  1156     // TODO: internal catch clauses?; catch and rethrow an annotation
  1157     // processing error
  1158     public JavaCompiler doProcessing(Context context,
  1159                                      List<JCCompilationUnit> roots,
  1160                                      List<ClassSymbol> classSymbols,
  1161                                      Iterable<? extends PackageSymbol> pckSymbols,
  1162                                      Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
  1163         log = Log.instance(context);
  1165         Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
  1166         for (PackageSymbol psym : pckSymbols)
  1167             specifiedPackages.add(psym);
  1168         this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);
  1170         Round round = new Round(context, roots, classSymbols, deferredDiagnosticHandler);
  1172         boolean errorStatus;
  1173         boolean moreToDo;
  1174         do {
  1175             // Run processors for round n
  1176             round.run(false, false);
  1178             // Processors for round n have run to completion.
  1179             // Check for errors and whether there is more work to do.
  1180             errorStatus = round.unrecoverableError();
  1181             moreToDo = moreToDo();
  1183             round.showDiagnostics(errorStatus || showResolveErrors);
  1185             // Set up next round.
  1186             // Copy mutable collections returned from filer.
  1187             round = round.next(
  1188                     new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()),
  1189                     new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses()));
  1191              // Check for errors during setup.
  1192             if (round.unrecoverableError())
  1193                 errorStatus = true;
  1195         } while (moreToDo && !errorStatus);
  1197         // run last round
  1198         round.run(true, errorStatus);
  1199         round.showDiagnostics(true);
  1201         filer.warnIfUnclosedFiles();
  1202         warnIfUnmatchedOptions();
  1204         /*
  1205          * If an annotation processor raises an error in a round,
  1206          * that round runs to completion and one last round occurs.
  1207          * The last round may also occur because no more source or
  1208          * class files have been generated.  Therefore, if an error
  1209          * was raised on either of the last *two* rounds, the compile
  1210          * should exit with a nonzero exit code.  The current value of
  1211          * errorStatus holds whether or not an error was raised on the
  1212          * second to last round; errorRaised() gives the error status
  1213          * of the last round.
  1214          */
  1215         if (messager.errorRaised()
  1216                 || werror && round.warningCount() > 0 && round.errorCount() > 0)
  1217             errorStatus = true;
  1219         Set<JavaFileObject> newSourceFiles =
  1220                 new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
  1221         roots = cleanTrees(round.roots);
  1223         JavaCompiler compiler = round.finalCompiler();
  1225         if (newSourceFiles.size() > 0)
  1226             roots = roots.appendList(compiler.parseFiles(newSourceFiles));
  1228         errorStatus = errorStatus || (compiler.errorCount() > 0);
  1230         // Free resources
  1231         this.close();
  1233         if (!taskListener.isEmpty())
  1234             taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
  1236         if (errorStatus) {
  1237             if (compiler.errorCount() == 0)
  1238                 compiler.log.nerrors++;
  1239             return compiler;
  1242         compiler.enterTreesIfNeeded(roots);
  1244         return compiler;
  1247     private void warnIfUnmatchedOptions() {
  1248         if (!unmatchedProcessorOptions.isEmpty()) {
  1249             log.warning("proc.unmatched.processor.options", unmatchedProcessorOptions.toString());
  1253     /**
  1254      * Free resources related to annotation processing.
  1255      */
  1256     public void close() {
  1257         filer.close();
  1258         if (discoveredProcs != null) // Make calling close idempotent
  1259             discoveredProcs.close();
  1260         discoveredProcs = null;
  1263     private List<ClassSymbol> getTopLevelClasses(List<? extends JCCompilationUnit> units) {
  1264         List<ClassSymbol> classes = List.nil();
  1265         for (JCCompilationUnit unit : units) {
  1266             for (JCTree node : unit.defs) {
  1267                 if (node.hasTag(JCTree.Tag.CLASSDEF)) {
  1268                     ClassSymbol sym = ((JCClassDecl) node).sym;
  1269                     Assert.checkNonNull(sym);
  1270                     classes = classes.prepend(sym);
  1274         return classes.reverse();
  1277     private List<ClassSymbol> getTopLevelClassesFromClasses(List<? extends ClassSymbol> syms) {
  1278         List<ClassSymbol> classes = List.nil();
  1279         for (ClassSymbol sym : syms) {
  1280             if (!isPkgInfo(sym)) {
  1281                 classes = classes.prepend(sym);
  1284         return classes.reverse();
  1287     private List<PackageSymbol> getPackageInfoFiles(List<? extends JCCompilationUnit> units) {
  1288         List<PackageSymbol> packages = List.nil();
  1289         for (JCCompilationUnit unit : units) {
  1290             if (isPkgInfo(unit.sourcefile, JavaFileObject.Kind.SOURCE)) {
  1291                 packages = packages.prepend(unit.packge);
  1294         return packages.reverse();
  1297     private List<PackageSymbol> getPackageInfoFilesFromClasses(List<? extends ClassSymbol> syms) {
  1298         List<PackageSymbol> packages = List.nil();
  1299         for (ClassSymbol sym : syms) {
  1300             if (isPkgInfo(sym)) {
  1301                 packages = packages.prepend((PackageSymbol) sym.owner);
  1304         return packages.reverse();
  1307     // avoid unchecked warning from use of varargs
  1308     private static <T> List<T> join(List<T> list1, List<T> list2) {
  1309         return list1.appendList(list2);
  1312     private boolean isPkgInfo(JavaFileObject fo, JavaFileObject.Kind kind) {
  1313         return fo.isNameCompatible("package-info", kind);
  1316     private boolean isPkgInfo(ClassSymbol sym) {
  1317         return isPkgInfo(sym.classfile, JavaFileObject.Kind.CLASS) && (sym.packge().package_info == sym);
  1320     /*
  1321      * Called retroactively to determine if a class loader was required,
  1322      * after we have failed to create one.
  1323      */
  1324     private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
  1325         if (procNames != null)
  1326             return true;
  1328         URL[] urls = new URL[1];
  1329         for(File pathElement : workingpath) {
  1330             try {
  1331                 urls[0] = pathElement.toURI().toURL();
  1332                 if (ServiceProxy.hasService(Processor.class, urls))
  1333                     return true;
  1334             } catch (MalformedURLException ex) {
  1335                 throw new AssertionError(ex);
  1337             catch (ServiceProxy.ServiceConfigurationError e) {
  1338                 log.error("proc.bad.config.file", e.getLocalizedMessage());
  1339                 return true;
  1343         return false;
  1346     private static <T extends JCTree> List<T> cleanTrees(List<T> nodes) {
  1347         for (T node : nodes)
  1348             treeCleaner.scan(node);
  1349         return nodes;
  1352     private static final TreeScanner treeCleaner = new TreeScanner() {
  1353             public void scan(JCTree node) {
  1354                 super.scan(node);
  1355                 if (node != null)
  1356                     node.type = null;
  1358             public void visitTopLevel(JCCompilationUnit node) {
  1359                 node.packge = null;
  1360                 super.visitTopLevel(node);
  1362             public void visitClassDef(JCClassDecl node) {
  1363                 node.sym = null;
  1364                 super.visitClassDef(node);
  1366             public void visitMethodDef(JCMethodDecl node) {
  1367                 node.sym = null;
  1368                 super.visitMethodDef(node);
  1370             public void visitVarDef(JCVariableDecl node) {
  1371                 node.sym = null;
  1372                 super.visitVarDef(node);
  1374             public void visitNewClass(JCNewClass node) {
  1375                 node.constructor = null;
  1376                 super.visitNewClass(node);
  1378             public void visitAssignop(JCAssignOp node) {
  1379                 node.operator = null;
  1380                 super.visitAssignop(node);
  1382             public void visitUnary(JCUnary node) {
  1383                 node.operator = null;
  1384                 super.visitUnary(node);
  1386             public void visitBinary(JCBinary node) {
  1387                 node.operator = null;
  1388                 super.visitBinary(node);
  1390             public void visitSelect(JCFieldAccess node) {
  1391                 node.sym = null;
  1392                 super.visitSelect(node);
  1394             public void visitIdent(JCIdent node) {
  1395                 node.sym = null;
  1396                 super.visitIdent(node);
  1398             public void visitAnnotation(JCAnnotation node) {
  1399                 node.attribute = null;
  1400                 super.visitAnnotation(node);
  1402         };
  1405     private boolean moreToDo() {
  1406         return filer.newFiles();
  1409     /**
  1410      * {@inheritdoc}
  1412      * Command line options suitable for presenting to annotation
  1413      * processors.
  1414      * {@literal "-Afoo=bar"} should be {@literal "-Afoo" => "bar"}.
  1415      */
  1416     public Map<String,String> getOptions() {
  1417         return processorOptions;
  1420     public Messager getMessager() {
  1421         return messager;
  1424     public Filer getFiler() {
  1425         return filer;
  1428     public JavacElements getElementUtils() {
  1429         return elementUtils;
  1432     public JavacTypes getTypeUtils() {
  1433         return typeUtils;
  1436     public SourceVersion getSourceVersion() {
  1437         return Source.toSourceVersion(source);
  1440     public Locale getLocale() {
  1441         return messages.getCurrentLocale();
  1444     public Set<Symbol.PackageSymbol> getSpecifiedPackages() {
  1445         return specifiedPackages;
  1448     private static final Pattern allMatches = Pattern.compile(".*");
  1449     public static final Pattern noMatches  = Pattern.compile("(\\P{all})+");
  1451     /**
  1452      * Convert import-style string for supported annotations into a
  1453      * regex matching that string.  If the string is a valid
  1454      * import-style string, return a regex that won't match anything.
  1455      */
  1456     private static Pattern importStringToPattern(String s, Processor p, Log log) {
  1457         if (isValidImportString(s)) {
  1458             return validImportStringToPattern(s);
  1459         } else {
  1460             log.warning("proc.malformed.supported.string", s, p.getClass().getName());
  1461             return noMatches; // won't match any valid identifier
  1465     /**
  1466      * Return true if the argument string is a valid import-style
  1467      * string specifying claimed annotations; return false otherwise.
  1468      */
  1469     public static boolean isValidImportString(String s) {
  1470         if (s.equals("*"))
  1471             return true;
  1473         boolean valid = true;
  1474         String t = s;
  1475         int index = t.indexOf('*');
  1477         if (index != -1) {
  1478             // '*' must be last character...
  1479             if (index == t.length() -1) {
  1480                 // ... any and preceding character must be '.'
  1481                 if ( index-1 >= 0 ) {
  1482                     valid = t.charAt(index-1) == '.';
  1483                     // Strip off ".*$" for identifier checks
  1484                     t = t.substring(0, t.length()-2);
  1486             } else
  1487                 return false;
  1490         // Verify string is off the form (javaId \.)+ or javaId
  1491         if (valid) {
  1492             String[] javaIds = t.split("\\.", t.length()+2);
  1493             for(String javaId: javaIds)
  1494                 valid &= SourceVersion.isIdentifier(javaId);
  1496         return valid;
  1499     public static Pattern validImportStringToPattern(String s) {
  1500         if (s.equals("*")) {
  1501             return allMatches;
  1502         } else {
  1503             String s_prime = s.replace(".", "\\.");
  1505             if (s_prime.endsWith("*")) {
  1506                 s_prime =  s_prime.substring(0, s_prime.length() - 1) + ".+";
  1509             return Pattern.compile(s_prime);
  1513     /**
  1514      * For internal use only.  This method may be removed without warning.
  1515      */
  1516     public Context getContext() {
  1517         return context;
  1520     /**
  1521      * For internal use only.  This method may be removed without warning.
  1522      */
  1523     public ClassLoader getProcessorClassLoader() {
  1524         return processorClassLoader;
  1527     public String toString() {
  1528         return "javac ProcessingEnvironment";
  1531     public static boolean isValidOptionName(String optionName) {
  1532         for(String s : optionName.split("\\.", -1)) {
  1533             if (!SourceVersion.isIdentifier(s))
  1534                 return false;
  1536         return true;

mercurial