Skip to content

Commit c27b527

Browse files
eamonnmcmanusGoogle Java Core Libraries
authored andcommitted
Don't claim annotations in AutoAnnotationProcessor and AutoServiceProcessor.
Annotation claiming is a misfeature and we already stopped doing it years ago in AutoValueProcessor. It's an oversight that we didn't do it for these processors at the same time. Also apply some automated code-fix suggestions. RELNOTES=AutoAnnotationProcessor and AutoServiceProcessor no longer claim their annotations. PiperOrigin-RevId: 337750292
1 parent 6bed859 commit c27b527

File tree

2 files changed

+37
-40
lines changed

2 files changed

+37
-40
lines changed

service/processor/src/main/java/com/google/auto/service/processor/AutoServiceProcessor.java

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,10 @@
1717

1818
import static com.google.auto.common.AnnotationMirrors.getAnnotationValue;
1919
import static com.google.auto.common.MoreElements.getAnnotationMirror;
20+
import static com.google.common.base.Throwables.getStackTraceAsString;
2021
import static com.google.common.collect.ImmutableSet.toImmutableSet;
2122

23+
import com.google.auto.common.MoreElements;
2224
import com.google.auto.common.MoreTypes;
2325
import com.google.auto.service.AutoService;
2426
import com.google.common.annotations.VisibleForTesting;
@@ -28,8 +30,6 @@
2830
import com.google.common.collect.Sets;
2931
import java.io.IOException;
3032
import java.io.OutputStream;
31-
import java.io.PrintWriter;
32-
import java.io.StringWriter;
3333
import java.util.HashSet;
3434
import java.util.List;
3535
import java.util.Set;
@@ -74,7 +74,7 @@ public class AutoServiceProcessor extends AbstractProcessor {
7474
* {@code "com.google.apphosting.LocalRpcService" ->
7575
* "com.google.apphosting.datastore.LocalDatastoreService"}
7676
*/
77-
private Multimap<String, String> providers = HashMultimap.create();
77+
private final Multimap<String, String> providers = HashMultimap.create();
7878

7979
@Override
8080
public ImmutableSet<String> getSupportedAnnotationTypes() {
@@ -104,24 +104,20 @@ public SourceVersion getSupportedSourceVersion() {
104104
@Override
105105
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
106106
try {
107-
return processImpl(annotations, roundEnv);
108-
} catch (Exception e) {
107+
processImpl(annotations, roundEnv);
108+
} catch (RuntimeException e) {
109109
// We don't allow exceptions of any kind to propagate to the compiler
110-
StringWriter writer = new StringWriter();
111-
e.printStackTrace(new PrintWriter(writer));
112-
fatalError(writer.toString());
113-
return true;
110+
fatalError(getStackTraceAsString(e));
114111
}
112+
return false;
115113
}
116114

117-
private boolean processImpl(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
115+
private void processImpl(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
118116
if (roundEnv.processingOver()) {
119117
generateConfigFiles();
120118
} else {
121119
processAnnotations(annotations, roundEnv);
122120
}
123-
124-
return true;
125121
}
126122

127123
private void processAnnotations(Set<? extends TypeElement> annotations,
@@ -134,7 +130,7 @@ private void processAnnotations(Set<? extends TypeElement> annotations,
134130

135131
for (Element e : elements) {
136132
// TODO(gak): check for error trees?
137-
TypeElement providerImplementer = (TypeElement) e;
133+
TypeElement providerImplementer = MoreElements.asType(e);
138134
AnnotationMirror annotationMirror = getAnnotationMirror(e, AutoService.class).get();
139135
Set<DeclaredType> providerInterfaces = getValueFieldOfClasses(annotationMirror);
140136
if (providerInterfaces.isEmpty()) {
@@ -187,7 +183,7 @@ private void generateConfigFiles() {
187183
log("Resource file did not already exist.");
188184
}
189185

190-
Set<String> newServices = new HashSet<String>(providers.get(providerInterface));
186+
Set<String> newServices = new HashSet<>(providers.get(providerInterface));
191187
if (allServices.containsAll(newServices)) {
192188
log("No new service entries being added.");
193189
return;
@@ -197,9 +193,9 @@ private void generateConfigFiles() {
197193
log("New service file contents: " + allServices);
198194
FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "",
199195
resourceFile);
200-
OutputStream out = fileObject.openOutputStream();
201-
ServicesFiles.writeServiceFile(allServices, out);
202-
out.close();
196+
try (OutputStream out = fileObject.openOutputStream()) {
197+
ServicesFiles.writeServiceFile(allServices, out);
198+
}
203199
log("Wrote to: " + fileObject.toUri());
204200
} catch (IOException e) {
205201
fatalError("Unable to create " + resourceFile + ", " + e);
@@ -216,7 +212,7 @@ private void generateConfigFiles() {
216212
private boolean checkImplementer(TypeElement providerImplementer, TypeElement providerType) {
217213

218214
String verify = processingEnv.getOptions().get("verify");
219-
if (verify == null || !Boolean.valueOf(verify)) {
215+
if (verify == null || !Boolean.parseBoolean(verify)) {
220216
return true;
221217
}
222218

@@ -241,28 +237,29 @@ private String getBinaryNameImpl(TypeElement element, String className) {
241237
Element enclosingElement = element.getEnclosingElement();
242238

243239
if (enclosingElement instanceof PackageElement) {
244-
PackageElement pkg = (PackageElement) enclosingElement;
240+
PackageElement pkg = MoreElements.asPackage(enclosingElement);
245241
if (pkg.isUnnamed()) {
246242
return className;
247243
}
248244
return pkg.getQualifiedName() + "." + className;
249245
}
250246

251-
TypeElement typeElement = (TypeElement) enclosingElement;
247+
TypeElement typeElement = MoreElements.asType(enclosingElement);
252248
return getBinaryNameImpl(typeElement, typeElement.getSimpleName() + "$" + className);
253249
}
254250

255251
/**
256-
* Returns the contents of a {@code Class[]}-typed "value" field in a given {@code annotationMirror}.
252+
* Returns the contents of a {@code Class[]}-typed "value" field in a given {@code
253+
* annotationMirror}.
257254
*/
258255
private ImmutableSet<DeclaredType> getValueFieldOfClasses(AnnotationMirror annotationMirror) {
259256
return getAnnotationValue(annotationMirror, "value")
260257
.accept(
261258
new SimpleAnnotationValueVisitor8<ImmutableSet<DeclaredType>, Void>() {
262259
@Override
263260
public ImmutableSet<DeclaredType> visitType(TypeMirror typeMirror, Void v) {
264-
// TODO(ronshapiro): class literals may not always be declared types, i.e. int.class,
265-
// int[].class
261+
// TODO(ronshapiro): class literals may not always be declared types, i.e.
262+
// int.class, int[].class
266263
return ImmutableSet.of(MoreTypes.asDeclared(typeMirror));
267264
}
268265

value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import static java.util.stream.Collectors.joining;
2323

2424
import com.google.auto.common.MoreElements;
25+
import com.google.auto.common.MoreTypes;
2526
import com.google.auto.common.SuperficialValidation;
2627
import com.google.auto.service.AutoService;
2728
import com.google.common.base.Preconditions;
@@ -110,19 +111,18 @@ private AbortProcessingException abortWithError(Element e, String msg, Object...
110111
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
111112
elementUtils = processingEnv.getElementUtils();
112113
typeUtils = processingEnv.getTypeUtils();
113-
boolean claimed =
114+
// This should always be true: we shouldn't be called with any other annotation.
115+
boolean ours =
114116
(annotations.size() == 1
115117
&& annotations
116118
.iterator()
117119
.next()
118120
.getQualifiedName()
119121
.contentEquals(AUTO_ANNOTATION_NAME));
120-
if (claimed) {
122+
if (ours) {
121123
process(roundEnv);
122-
return true;
123-
} else {
124-
return false;
125124
}
125+
return false;
126126
}
127127

128128
private void process(RoundEnvironment roundEnv) {
@@ -156,7 +156,7 @@ private void processMethod(ExecutableElement method) {
156156
Set<Class<?>> wrapperTypesUsedInCollections = wrapperTypesUsedInCollections(method);
157157

158158
ImmutableMap<String, ExecutableElement> memberMethods = getMemberMethods(annotationElement);
159-
TypeElement methodClass = (TypeElement) method.getEnclosingElement();
159+
TypeElement methodClass = MoreElements.asType(method.getEnclosingElement());
160160
String pkg = TypeSimplifier.packageNameOf(methodClass);
161161

162162
ImmutableMap<String, AnnotationValue> defaultValues = getDefaultValues(annotationElement);
@@ -251,7 +251,7 @@ private static ImmutableMap<String, Integer> invariableHashes(
251251

252252
private boolean methodsAreOverloaded(List<ExecutableElement> methods) {
253253
boolean overloaded = false;
254-
Set<String> classNames = new HashSet<String>();
254+
Set<String> classNames = new HashSet<>();
255255
for (ExecutableElement method : methods) {
256256
String qualifiedClassName =
257257
fullyQualifiedName(
@@ -266,10 +266,10 @@ private boolean methodsAreOverloaded(List<ExecutableElement> methods) {
266266
}
267267

268268
private String generatedClassName(ExecutableElement method) {
269-
TypeElement type = (TypeElement) method.getEnclosingElement();
269+
TypeElement type = MoreElements.asType(method.getEnclosingElement());
270270
String name = type.getSimpleName().toString();
271271
while (type.getEnclosingElement() instanceof TypeElement) {
272-
type = (TypeElement) type.getEnclosingElement();
272+
type = MoreElements.asType(type.getEnclosingElement());
273273
name = type.getSimpleName() + "_" + name;
274274
}
275275
return "AutoAnnotation_" + name + "_" + method.getSimpleName();
@@ -280,7 +280,7 @@ private TypeElement getAnnotationReturnType(ExecutableElement method) {
280280
if (returnTypeMirror.getKind() == TypeKind.DECLARED) {
281281
Element returnTypeElement = typeUtils.asElement(method.getReturnType());
282282
if (returnTypeElement.getKind() == ElementKind.ANNOTATION_TYPE) {
283-
return (TypeElement) returnTypeElement;
283+
return MoreElements.asType(returnTypeElement);
284284
}
285285
}
286286
throw abortWithError(
@@ -404,7 +404,7 @@ private boolean compatibleTypes(TypeMirror parameterType, TypeMirror memberType)
404404
if (memberType.getKind() != TypeKind.ARRAY) {
405405
return false;
406406
}
407-
TypeMirror arrayElementType = ((ArrayType) memberType).getComponentType();
407+
TypeMirror arrayElementType = MoreTypes.asArray(memberType).getComponentType();
408408
TypeMirror wrappedArrayElementType =
409409
arrayElementType.getKind().isPrimitive()
410410
? typeUtils.boxedClass((PrimitiveType) arrayElementType).asType()
@@ -421,7 +421,7 @@ private boolean compatibleTypes(TypeMirror parameterType, TypeMirror memberType)
421421
* like {@code List<Integer>}. This is needed because we will emit a helper method for each such
422422
* type, for example to convert {@code Collection<Integer>} into {@code int[]}.
423423
*/
424-
private Set<Class<?>> wrapperTypesUsedInCollections(ExecutableElement method) {
424+
private ImmutableSet<Class<?>> wrapperTypesUsedInCollections(ExecutableElement method) {
425425
TypeElement javaUtilCollection = elementUtils.getTypeElement(Collection.class.getName());
426426
ImmutableSet.Builder<Class<?>> usedInCollections = ImmutableSet.builder();
427427
for (Class<?> wrapper : Primitives.allWrapperTypes()) {
@@ -533,7 +533,7 @@ public String getType() {
533533

534534
public String getComponentType() {
535535
Preconditions.checkState(getTypeMirror().getKind() == TypeKind.ARRAY);
536-
ArrayType arrayType = (ArrayType) getTypeMirror();
536+
ArrayType arrayType = MoreTypes.asArray(getTypeMirror());
537537
return TypeEncoder.encode(arrayType.getComponentType());
538538
}
539539

@@ -555,12 +555,12 @@ public boolean isArrayOfClassWithBounds() {
555555
if (getTypeMirror().getKind() != TypeKind.ARRAY) {
556556
return false;
557557
}
558-
TypeMirror componentType = ((ArrayType) getTypeMirror()).getComponentType();
558+
TypeMirror componentType = MoreTypes.asArray(getTypeMirror()).getComponentType();
559559
if (componentType.getKind() != TypeKind.DECLARED) {
560560
return false;
561561
}
562-
DeclaredType declared = (DeclaredType) componentType;
563-
if (!((TypeElement) processingEnv.getTypeUtils().asElement(componentType))
562+
DeclaredType declared = MoreTypes.asDeclared(componentType);
563+
if (!MoreElements.asType(processingEnv.getTypeUtils().asElement(componentType))
564564
.getQualifiedName()
565565
.contentEquals("java.lang.Class")) {
566566
return false;
@@ -572,7 +572,7 @@ public boolean isArrayOfClassWithBounds() {
572572
if (parameter.getKind() != TypeKind.WILDCARD) {
573573
return true; // for Class<Foo>
574574
}
575-
WildcardType wildcard = (WildcardType) parameter;
575+
WildcardType wildcard = MoreTypes.asWildcard(parameter);
576576
// In theory, we should check if getExtendsBound() != Object, since '?' is equivalent to
577577
// '? extends Object', but, experimentally, neither javac or ecj will sets getExtendsBound()
578578
// to 'Object', so there isn't a point in checking.

0 commit comments

Comments
 (0)