Path: blob/master/src/java.compiler/share/classes/javax/annotation/processing/Processor.java
41159 views
/*1* Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.annotation.processing;2627import java.util.Set;28import javax.lang.model.util.Elements;29import javax.lang.model.AnnotatedConstruct;30import javax.lang.model.element.*;31import javax.lang.model.SourceVersion;3233/**34* The interface for an annotation processor.35*36* <p>Annotation processing happens in a sequence of {@linkplain37* javax.annotation.processing.RoundEnvironment rounds}. On each38* round, a processor may be asked to {@linkplain #process process} a39* subset of the annotations found on the source and class files40* produced by a prior round. The inputs to the first round of41* processing are the initial inputs to a run of the tool; these42* initial inputs can be regarded as the output of a virtual zeroth43* round of processing. If a processor was asked to process on a44* given round, it will be asked to process on subsequent rounds,45* including the last round, even if there are no annotations for it46* to process. The tool infrastructure may also ask a processor to47* process files generated implicitly by the tool's operation.48*49* <p> Each implementation of a {@code Processor} must provide a50* public no-argument constructor to be used by tools to instantiate51* the processor. The tool infrastructure will interact with classes52* implementing this interface as follows:53*54* <ol>55*56* <li>If an existing {@code Processor} object is not being used, to57* create an instance of a processor the tool calls the no-arg58* constructor of the processor class.59*60* <li>Next, the tool calls the {@link #init init} method with61* an appropriate {@link ProcessingEnvironment}.62*63* <li>Afterwards, the tool calls {@link #getSupportedAnnotationTypes64* getSupportedAnnotationTypes}, {@link #getSupportedOptions65* getSupportedOptions}, and {@link #getSupportedSourceVersion66* getSupportedSourceVersion}. These methods are only called once per67* run, not on each round.68*69* <li>As appropriate, the tool calls the {@link #process process}70* method on the {@code Processor} object; a new {@code Processor}71* object is <em>not</em> created for each round.72*73* </ol>74*75* If a processor object is created and used without the above76* protocol being followed, then the processor's behavior is not77* defined by this interface specification.78*79* <p> The tool uses a <i>discovery process</i> to find annotation80* processors and decide whether or not they should be run. By81* configuring the tool, the set of potential processors can be82* controlled. For example, for a {@link javax.tools.JavaCompiler83* JavaCompiler} the list of candidate processors to run can be84* {@linkplain javax.tools.JavaCompiler.CompilationTask#setProcessors85* set directly} or controlled by a {@linkplain86* javax.tools.StandardLocation#ANNOTATION_PROCESSOR_PATH search path}87* used for a {@linkplain java.util.ServiceLoader service-style}88* lookup. Other tool implementations may have different89* configuration mechanisms, such as command line options; for90* details, refer to the particular tool's documentation. Which91* processors the tool asks to {@linkplain #process run} is a function92* of the interfaces of the annotations <em>{@linkplain93* AnnotatedConstruct present}</em> on the {@linkplain94* RoundEnvironment#getRootElements root elements}, what {@linkplain95* #getSupportedAnnotationTypes annotation interfaces a processor96* supports}, and whether or not a processor {@linkplain #process97* claims the annotation interfaces it processes}. A processor will98* be asked to process a subset of the annotation interfaces it99* supports, possibly an empty set.100*101* For a given round, the tool computes the set of annotation102* interfaces that are present on the elements enclosed within the103* root elements. If there is at least one annotation interface104* present, then as processors claim annotation interfaces, they are105* removed from the set of unmatched annotation interfaces. When the106* set is empty or no more processors are available, the round has run107* to completion. If there are no annotation interfaces present,108* annotation processing still occurs but only <i>universal109* processors</i> which support processing all annotation interfaces,110* {@code "*"}, can claim the (empty) set of annotation interfaces.111*112* <p>An annotation interface is considered present if there is at least113* one annotation of that interface present on an element enclosed within114* the root elements of a round. For this purpose, a type parameter is115* considered to be enclosed by its {@linkplain116* TypeParameterElement#getGenericElement generic117* element}.118119* For this purpose, a package element is <em>not</em> considered to120* enclose the top-level classes and interfaces within that121* package. (A root element representing a package is created when a122* {@code package-info} file is processed.) Likewise, for this123* purpose, a module element is <em>not</em> considered to enclose the124* packages within that module. (A root element representing a module125* is created when a {@code module-info} file is processed.)126*127* Annotations on {@linkplain128* java.lang.annotation.ElementType#TYPE_USE type uses}, as opposed to129* annotations on elements, are ignored when computing whether or not130* an annotation interface is present.131*132* <p>An annotation is <em>present</em> if it meets the definition of being133* present given in {@link AnnotatedConstruct}. In brief, an134* annotation is considered present for the purposes of discovery if135* it is directly present or present via inheritance. An annotation is136* <em>not</em> considered present by virtue of being wrapped by a137* container annotation. Operationally, this is equivalent to an138* annotation being present on an element if and only if it would be139* included in the results of {@link140* Elements#getAllAnnotationMirrors(Element)} called on that element. Since141* annotations inside container annotations are not considered142* present, to properly process {@linkplain143* java.lang.annotation.Repeatable repeatable annotation interfaces},144* processors are advised to include both the repeatable annotation145* interface and its containing annotation interface in the set of {@linkplain146* #getSupportedAnnotationTypes() supported annotation interfaces} of a147* processor.148*149* <p>Note that if a processor supports {@code "*"} and returns {@code150* true}, all annotations are claimed. Therefore, a universal151* processor being used to, for example, implement additional validity152* checks should return {@code false} so as to not prevent other such153* checkers from being able to run.154*155* <p>If a processor throws an uncaught exception, the tool may cease156* other active annotation processors. If a processor raises an157* error, the current round will run to completion and the subsequent158* round will indicate an {@linkplain RoundEnvironment#errorRaised159* error was raised}. Since annotation processors are run in a160* cooperative environment, a processor should throw an uncaught161* exception only in situations where no error recovery or reporting162* is feasible.163*164* <p>The tool environment is not required to support annotation165* processors that access environmental resources, either {@linkplain166* RoundEnvironment per round} or {@linkplain ProcessingEnvironment167* cross-round}, in a multi-threaded fashion.168*169* <p>If the methods that return configuration information about the170* annotation processor return {@code null}, return other invalid171* input, or throw an exception, the tool infrastructure must treat172* this as an error condition.173*174* <p>To be robust when running in different tool implementations, an175* annotation processor should have the following properties:176*177* <ol>178*179* <li>The result of processing a given input is not a function of the presence or absence180* of other inputs (orthogonality).181*182* <li>Processing the same input produces the same output (consistency).183*184* <li>Processing input <i>A</i> followed by processing input <i>B</i>185* is equivalent to processing <i>B</i> then <i>A</i>186* (commutativity)187*188* <li>Processing an input does not rely on the presence of the output189* of other annotation processors (independence)190*191* </ol>192*193* <p>The {@link Filer} interface discusses restrictions on how194* processors can operate on files.195*196* @apiNote Implementors of this interface may find it convenient197* to extend {@link AbstractProcessor} rather than implementing this198* interface directly.199*200* @author Joseph D. Darcy201* @author Scott Seligman202* @author Peter von der Ahé203* @since 1.6204*/205public interface Processor {206/**207* Returns the options recognized by this processor. An208* implementation of the processing tool must provide a way to209* pass processor-specific options distinctly from options passed210* to the tool itself, see {@link ProcessingEnvironment#getOptions211* getOptions}.212*213* <p>Each string returned in the set must be a period separated214* sequence of {@linkplain215* javax.lang.model.SourceVersion#isIdentifier identifiers}:216*217* <blockquote>218* <dl>219* <dt><i>SupportedOptionString:</i>220* <dd><i>Identifiers</i>221*222* <dt><i>Identifiers:</i>223* <dd> <i>Identifier</i>224* <dd> <i>Identifier</i> {@code .} <i>Identifiers</i>225*226* <dt><i>Identifier:</i>227* <dd>Syntactic identifier, including keywords and literals228* </dl>229* </blockquote>230*231* <p> A tool might use this information to determine if any232* options provided by a user are unrecognized by any processor,233* in which case it may wish to report a warning.234*235* @return the options recognized by this processor or an236* empty set if none237* @see javax.annotation.processing.SupportedOptions238*/239Set<String> getSupportedOptions();240241/**242* Returns the names of the annotation interfaces supported by this243* processor. An element of the result may be the canonical244* (fully qualified) name of a supported annotation interface.245* Alternately it may be of the form "<code><i>name</i>.*</code>"246* representing the set of all annotation interfaces with canonical247* names beginning with "<code><i>name.</i></code>".248*249* In either of those cases, the name of the annotation interface can250* be optionally preceded by a module name followed by a {@code251* "/"} character. For example, if a processor supports {@code252* "a.B"}, this can include multiple annotation interfaces named {@code253* a.B} which reside in different modules. To only support {@code254* a.B} in the {@code foo} module, instead use {@code "foo/a.B"}.255*256* If a module name is included, only an annotation in that module257* is matched. In particular, if a module name is given in an258* environment where modules are not supported, such as an259* annotation processing environment configured for a {@linkplain260* javax.annotation.processing.ProcessingEnvironment#getSourceVersion261* source version} without modules, then the annotation interfaces with262* a module name do <em>not</em> match.263*264* Finally, {@code "*"} by itself represents the set of all265* annotation interfaces, including the empty set. Note that a266* processor should not claim {@code "*"} unless it is actually267* processing all files; claiming unnecessary annotations may268* cause a performance slowdown in some environments.269*270* <p>Each string returned in the set must be accepted by the271* following grammar:272*273* <blockquote>274* <dl>275* <dt><i>SupportedAnnotationTypeString:</i>276* <dd><i>ModulePrefix</i><sub><i>opt</i></sub> <i>TypeName</i> <i>DotStar</i><sub><i>opt</i></sub>277* <dd><code>*</code>278*279* <dt><i>ModulePrefix:</i>280* <dd><i>ModuleName</i> <code>/</code>281*282* <dt><i>DotStar:</i>283* <dd><code>.</code> <code>*</code>284* </dl>285* </blockquote>286*287* where <i>TypeName</i> and <i>ModuleName</i> are as defined in288* <cite>The Java Language Specification</cite>289* ({@jls 6.5 Determining the Meaning of a Name}).290*291* @apiNote When running in an environment which supports modules,292* processors are encouraged to include the module prefix when293* describing their supported annotation interfaces. The method {@link294* AbstractProcessor#getSupportedAnnotationTypes295* AbstractProcessor.getSupportedAnnotationTypes} provides support296* for stripping off the module prefix when running in an297* environment without modules.298*299* @return the names of the annotation interfaces supported by this processor300* or an empty set if none301* @see javax.annotation.processing.SupportedAnnotationTypes302* @jls 3.8 Identifiers303*/304Set<String> getSupportedAnnotationTypes();305306/**307* {@return the latest source version supported by this annotation308* processor}309*310* @see javax.annotation.processing.SupportedSourceVersion311* @see ProcessingEnvironment#getSourceVersion312*/313SourceVersion getSupportedSourceVersion();314315/**316* Initializes the processor with the processing environment.317*318* @param processingEnv environment for facilities the tool framework319* provides to the processor320*/321void init(ProcessingEnvironment processingEnv);322323/**324* Processes a set of annotation interfaces on type elements325* originating from the prior round and returns whether or not326* these annotation interfaces are claimed by this processor. If {@code327* true} is returned, the annotation interfaces are claimed and subsequent328* processors will not be asked to process them; if {@code false}329* is returned, the annotation interfaces are unclaimed and subsequent330* processors may be asked to process them. A processor may331* always return the same boolean value or may vary the result332* based on its own chosen criteria.333*334* <p>The input set will be empty if the processor supports {@code335* "*"} and the root elements have no annotations. A {@code336* Processor} must gracefully handle an empty set of annotations.337*338* @param annotations the annotation interfaces requested to be processed339* @param roundEnv environment for information about the current and prior round340* @return whether or not the set of annotation interfaces are claimed by this processor341*/342boolean process(Set<? extends TypeElement> annotations,343RoundEnvironment roundEnv);344345/**346* Returns to the tool infrastructure an iterable of suggested347* completions to an annotation. Since completions are being asked348* for, the information provided about the annotation may be349* incomplete, as if for a source code fragment. A processor may350* return an empty iterable. Annotation processors should focus351* their efforts on providing completions for annotation members352* with additional validity constraints known to the processor, for353* example an {@code int} member whose value should lie between 1354* and 10 or a string member that should be recognized by a known355* grammar, such as a regular expression or a URL.356*357* <p>Since incomplete programs are being modeled, some of the358* parameters may only have partial information or may be {@code359* null}. At least one of {@code element} and {@code userText}360* must be non-{@code null}. If {@code element} is non-{@code null},361* {@code annotation} and {@code member} may be {@code362* null}. Processors may not throw a {@code NullPointerException}363* if some parameters are {@code null}; if a processor has no364* completions to offer based on the provided information, an365* empty iterable can be returned. The processor may also return366* a single completion with an empty value string and a message367* describing why there are no completions.368*369* <p>Completions are informative and may reflect additional370* validity checks performed by annotation processors. For371* example, consider the simple annotation:372*373* <blockquote>374* <pre>375* @MersennePrime {376* int value();377* }378* </pre>379* </blockquote>380*381* (A Mersenne prime is prime number of the form382* 2<sup><i>n</i></sup> - 1.) Given an {@code AnnotationMirror}383* for this annotation interface, a list of all such primes in the384* {@code int} range could be returned without examining any other385* arguments to {@code getCompletions}:386*387* <blockquote>388* <pre>389* import static javax.annotation.processing.Completions.*;390* ...391* return List.of({@link Completions#of(String) of}("3"),392* of("7"),393* of("31"),394* of("127"),395* of("8191"),396* of("131071"),397* of("524287"),398* of("2147483647"));399* </pre>400* </blockquote>401*402* A more informative set of completions would include the number403* of each prime:404*405* <blockquote>406* <pre>407* return List.of({@link Completions#of(String, String) of}("3", "M2"),408* of("7", "M3"),409* of("31", "M5"),410* of("127", "M7"),411* of("8191", "M13"),412* of("131071", "M17"),413* of("524287", "M19"),414* of("2147483647", "M31"));415* </pre>416* </blockquote>417*418* However, if the {@code userText} is available, it can be checked419* to see if only a subset of the Mersenne primes are valid. For420* example, if the user has typed421*422* <blockquote>423* <code>424* @MersennePrime(1425* </code>426* </blockquote>427*428* the value of {@code userText} will be {@code "1"}; and only429* two of the primes are possible completions:430*431* <blockquote>432* <pre>433* return Arrays.asList(of("127", "M7"),434* of("131071", "M17"));435* </pre>436* </blockquote>437*438* Sometimes no valid completion is possible. For example, there439* is no in-range Mersenne prime starting with 9:440*441* <blockquote>442* <code>443* @MersennePrime(9444* </code>445* </blockquote>446*447* An appropriate response in this case is to either return an448* empty list of completions,449*450* <blockquote>451* <pre>452* return Collections.emptyList();453* </pre>454* </blockquote>455*456* or a single empty completion with a helpful message457*458* <blockquote>459* <pre>460* return Arrays.asList(of("", "No in-range Mersenne primes start with 9"));461* </pre>462* </blockquote>463*464* @param element the element being annotated465* @param annotation the (perhaps partial) annotation being466* applied to the element467* @param member the annotation member to return possible completions for468* @param userText source code text to be completed469*470* @return suggested completions to the annotation471*/472Iterable<? extends Completion> getCompletions(Element element,473AnnotationMirror annotation,474ExecutableElement member,475String userText);476}477478479