diff options
author | bcorso <bcorso@google.com> | 2020-03-09 11:54:09 -0700 |
---|---|---|
committer | David P. Baker <dpb@google.com> | 2020-03-10 13:54:48 -0400 |
commit | ab80dcb025ef17171873dfd5b86f78813b2781e0 (patch) | |
tree | 68f0b8320af7ea43e1efc7f652e35c36f41f3c5a /common | |
parent | 36a53b93375ba8e761122f27bbde6e99f9a7cac7 (diff) | |
download | auto-ab80dcb025ef17171873dfd5b86f78813b2781e0.tar.gz |
Refactor BasicAnnotationProcessor (1 of 3)
This CL just does a format fix and applies some error-prone suggestions on BasicAnnotationProcessor.
RELNOTES=N/A
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=299896536
Diffstat (limited to 'common')
-rw-r--r-- | common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java | 157 |
1 files changed, 71 insertions, 86 deletions
diff --git a/common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java b/common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java index be4c3766..a353c2d9 100644 --- a/common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java +++ b/common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java @@ -15,6 +15,8 @@ */ package com.google.auto.common; +import static com.google.auto.common.MoreElements.asExecutable; +import static com.google.auto.common.MoreElements.asPackage; import static com.google.auto.common.MoreElements.isAnnotationPresent; import static com.google.auto.common.SuperficialValidation.validateElement; import static com.google.common.base.Preconditions.checkNotNull; @@ -25,7 +27,6 @@ import static javax.lang.model.element.ElementKind.PACKAGE; import static javax.tools.Diagnostic.Kind.ERROR; import com.google.common.base.Ascii; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; @@ -39,7 +40,6 @@ import java.lang.annotation.Annotation; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Map; -import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import javax.annotation.processing.AbstractProcessor; @@ -59,22 +59,23 @@ import javax.lang.model.util.SimpleElementVisitor8; * An abstract {@link Processor} implementation that defers processing of {@link Element}s to later * rounds if they cannot be processed. * - * <p>Subclasses put their processing logic in {@link ProcessingStep} implementations. The - * steps are passed to the processor by returning them in the {@link #initSteps()} method, and can - * access the {@link ProcessingEnvironment} using {@link #processingEnv}. + * <p>Subclasses put their processing logic in {@link ProcessingStep} implementations. The steps are + * passed to the processor by returning them in the {@link #initSteps()} method, and can access the + * {@link ProcessingEnvironment} using {@link #processingEnv}. * - * Any logic that needs to happen once per round can be specified by overriding - * {@link #postRound(RoundEnvironment)}. + * <p>Any logic that needs to happen once per round can be specified by overriding {@link + * #postRound(RoundEnvironment)}. * * <h3>Ill-formed elements are deferred</h3> + * * Any annotated element whose nearest enclosing type is not well-formed is deferred, and not passed * to any {@code ProcessingStep}. This helps processors to avoid many common pitfalls, such as * {@link ErrorType} instances, {@link ClassCastException}s and badly coerced types. * * <p>A non-package element is considered well-formed if its type, type parameters, parameters, * default values, supertypes, annotations, and enclosed elements are. Package elements are treated - * similarly, except that their enclosed elements are not validated. See - * {@link SuperficialValidation#validateElement(Element)} for details. + * similarly, except that their enclosed elements are not validated. See {@link + * SuperficialValidation#validateElement(Element)} for details. * * <p>The primary disadvantage to this validation is that any element that forms a circular * dependency with a type generated by another {@code BasicAnnotationProcessor} will never compile @@ -83,15 +84,15 @@ import javax.lang.model.util.SimpleElementVisitor8; * * <h3>Each {@code ProcessingStep} can defer elements</h3> * - * <p>Each {@code ProcessingStep} can defer elements by including them in the set returned by - * {@link ProcessingStep#process(SetMultimap)}; elements deferred by a step will be passed back to - * that step in a later round of processing. + * <p>Each {@code ProcessingStep} can defer elements by including them in the set returned by {@link + * ProcessingStep#process(SetMultimap)}; elements deferred by a step will be passed back to that + * step in a later round of processing. * - * <p>This feature is useful when one processor may depend on code generated by another, - * independent processor, in a way that isn't caught by the well-formedness check described above. - * For example, if an element {@code A} cannot be processed because processing it depends on the - * existence of some class {@code B}, then {@code A} should be deferred until a later round of - * processing, when {@code B} will have been generated by another processor. + * <p>This feature is useful when one processor may depend on code generated by another, independent + * processor, in a way that isn't caught by the well-formedness check described above. For example, + * if an element {@code A} cannot be processed because processing it depends on the existence of + * some class {@code B}, then {@code A} should be deferred until a later round of processing, when + * {@code B} will have been generated by another processor. * * <p>If {@code A} directly references {@code B}, then the well-formedness check will correctly * defer processing of {@code A} until {@code B} has been generated. @@ -102,7 +103,7 @@ import javax.lang.model.util.SimpleElementVisitor8; */ public abstract class BasicAnnotationProcessor extends AbstractProcessor { - private final Set<ElementName> deferredElementNames = new LinkedHashSet<ElementName>(); + private final Set<ElementName> deferredElementNames = new LinkedHashSet<>(); private final SetMultimap<ProcessingStep, ElementName> elementsDeferredBySteps = LinkedHashMultimap.create(); @@ -119,8 +120,8 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { } /** - * Creates {@linkplain ProcessingStep processing steps} for this processor. - * {@link #processingEnv} is guaranteed to be set when this method is invoked. + * Creates {@linkplain ProcessingStep processing steps} for this processor. {@link #processingEnv} + * is guaranteed to be set when this method is invoked. */ protected abstract Iterable<? extends ProcessingStep> initSteps(); @@ -149,8 +150,8 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { } /** - * Returns the set of supported annotation types as a collected from registered - * {@linkplain ProcessingStep processing steps}. + * Returns the set of supported annotation types as a collected from registered {@linkplain + * ProcessingStep processing steps}. */ @Override public final ImmutableSet<String> getSupportedAnnotationTypes() { @@ -202,15 +203,7 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { } else { Set<? extends Element> rejectedElements = step.process(stepElements); elementsDeferredBySteps.replaceValues( - step, - transform( - rejectedElements, - new Function<Element, ElementName>() { - @Override - public ElementName apply(Element element) { - return ElementName.forAnnotatedElement(element); - } - })); + step, transform(rejectedElements, ElementName::forAnnotatedElement)); } } } @@ -239,23 +232,19 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { } missingElements = allMissingElements.build(); } - for (Entry<String, ? extends Optional<? extends Element>> missingElementEntry : - missingElements.entrySet()) { - Optional<? extends Element> missingElement = missingElementEntry.getValue(); - if (missingElement.isPresent()) { - processingEnv - .getMessager() - .printMessage( + + missingElements.forEach( + (missingElementName, missingElement) -> { + if (missingElement.isPresent()) { + messager.printMessage( ERROR, processingErrorMessage( "this " + Ascii.toLowerCase(missingElement.get().getKind().name())), missingElement.get()); - } else { - processingEnv - .getMessager() - .printMessage(ERROR, processingErrorMessage(missingElementEntry.getKey())); - } - } + } else { + messager.printMessage(ERROR, processingErrorMessage(missingElementName)); + } + }); } private String processingErrorMessage(String target) { @@ -263,9 +252,7 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { "[%s:MiscError] %s was unable to process %s because not all of its dependencies could be " + "resolved. Check for compilation errors or a circular dependency with generated " + "code.", - getClass().getSimpleName(), - getClass().getCanonicalName(), - target); + getClass().getSimpleName(), getClass().getCanonicalName(), target); } /** @@ -277,18 +264,17 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { RoundEnvironment roundEnv) { ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> deferredElementsByAnnotationBuilder = ImmutableSetMultimap.builder(); - for (Entry<String, Optional<? extends Element>> deferredTypeElementEntry : - deferredElements.entrySet()) { - Optional<? extends Element> deferredElement = deferredTypeElementEntry.getValue(); - if (deferredElement.isPresent()) { - findAnnotatedElements( - deferredElement.get(), - getSupportedAnnotationClasses(), - deferredElementsByAnnotationBuilder); - } else { - deferredElementNames.add(ElementName.forTypeName(deferredTypeElementEntry.getKey())); - } - } + deferredElements.forEach( + (deferredElementName, deferredElement) -> { + if (deferredElement.isPresent()) { + findAnnotatedElements( + deferredElement.get(), + getSupportedAnnotationClasses(), + deferredElementsByAnnotationBuilder); + } else { + deferredElementNames.add(ElementName.forTypeName(deferredElementName)); + } + }); ImmutableSetMultimap<Class<? extends Annotation>, Element> deferredElementsByAnnotation = deferredElementsByAnnotationBuilder.build(); @@ -296,7 +282,7 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> validElements = ImmutableSetMultimap.builder(); - Set<ElementName> validElementNames = new LinkedHashSet<ElementName>(); + Set<ElementName> validElementNames = new LinkedHashSet<>(); // Look at the elements we've found and the new elements from this round and validate them. for (Class<? extends Annotation> annotationClass : getSupportedAnnotationClasses()) { @@ -310,7 +296,7 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { for (Element annotatedElement : Sets.union(elementsAnnotatedWith, deferredElementsByAnnotation.get(annotationClass))) { if (annotatedElement.getKind().equals(PACKAGE)) { - PackageElement annotatedPackageElement = (PackageElement) annotatedElement; + PackageElement annotatedPackageElement = asPackage(annotatedElement); ElementName annotatedPackageName = ElementName.forPackageName(annotatedPackageElement.getQualifiedName().toString()); boolean validPackage = @@ -388,7 +374,7 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { // element.getEnclosedElements() does NOT return parameter elements if (element instanceof ExecutableElement) { - for (Element parameterElement : ((ExecutableElement) element).getParameters()) { + for (Element parameterElement : asExecutable(element).getParameters()) { findAnnotatedElements(parameterElement, annotationClasses, annotatedElements); } } @@ -400,25 +386,30 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { } /** - * Returns the nearest enclosing {@link TypeElement} to the current element, throwing - * an {@link IllegalArgumentException} if the provided {@link Element} is a - * {@link PackageElement} or is otherwise not enclosed by a type. + * Returns the nearest enclosing {@link TypeElement} to the current element, throwing an {@link + * IllegalArgumentException} if the provided {@link Element} is a {@link PackageElement} or is + * otherwise not enclosed by a type. */ // TODO(cgruber) move to MoreElements and make public. private static TypeElement getEnclosingType(Element element) { - return element.accept(new SimpleElementVisitor8<TypeElement, Void>() { - @Override protected TypeElement defaultAction(Element e, Void p) { - return e.getEnclosingElement().accept(this, p); - } + return element.accept( + new SimpleElementVisitor8<TypeElement, Void>() { + @Override + protected TypeElement defaultAction(Element e, Void p) { + return e.getEnclosingElement().accept(this, p); + } - @Override public TypeElement visitType(TypeElement e, Void p) { - return e; - } + @Override + public TypeElement visitType(TypeElement e, Void p) { + return e; + } - @Override public TypeElement visitPackage(PackageElement e, Void p) { - throw new IllegalArgumentException(); - } - }, null); + @Override + public TypeElement visitPackage(PackageElement e, Void p) { + throw new IllegalArgumentException(); + } + }, + null); } /** @@ -467,16 +458,12 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { this.name = checkNotNull(name); } - /** - * An {@link ElementName} for a package. - */ + /** An {@link ElementName} for a package. */ static ElementName forPackageName(String packageName) { return new ElementName(Kind.PACKAGE_NAME, packageName); } - /** - * An {@link ElementName} for a type. - */ + /** An {@link ElementName} for a type. */ static ElementName forTypeName(String typeName) { return new ElementName(Kind.TYPE_NAME, typeName); } @@ -488,13 +475,11 @@ public abstract class BasicAnnotationProcessor extends AbstractProcessor { */ static ElementName forAnnotatedElement(Element element) { return element.getKind() == PACKAGE - ? ElementName.forPackageName(((PackageElement) element).getQualifiedName().toString()) + ? ElementName.forPackageName(asPackage(element).getQualifiedName().toString()) : ElementName.forTypeName(getEnclosingType(element).getQualifiedName().toString()); } - /** - * The fully-qualified name of the element. - */ + /** The fully-qualified name of the element. */ String name() { return name; } |