-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVulnAutoValueProcessor.java
698 lines (643 loc) · 27.5 KB
/
VulnAutoValueProcessor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
/*
* Copyright (C) 2012 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.value.processor;
import com.google.auto.service.AutoService;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.beans.Introspector;
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Generated;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
/**
* Javac annotation processor (compiler plugin) for value types; user code never references this
* class.
*
* @see AutoValue
* @author Éamonn McManus
*/
@AutoService(Processor.class)
public class AutoValueProcessor extends AbstractProcessor {
public AutoValueProcessor() {}
@Override
public Set<String> getSupportedAnnotationTypes() {
return ImmutableSet.of(AutoValue.class.getName());
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
private ErrorReporter errorReporter;
/**
* Qualified names of {@code @AutoValue} classes that we attempted to process but had to abandon
* because we needed other types that they referenced and those other types were missing.
*/
private final List<String> deferredTypeNames = new ArrayList<String>();
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
errorReporter = new ErrorReporter(processingEnv);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
List<TypeElement> deferredTypes = new ArrayList<TypeElement>();
for (String deferred : deferredTypeNames) {
deferredTypes.add(processingEnv.getElementUtils().getTypeElement(deferred));
}
if (roundEnv.processingOver()) {
// This means that the previous round didn't generate any new sources, so we can't have found
// any new instances of @AutoValue; and we can't have any new types that are the reason a type
// was in deferredTypes.
for (TypeElement type : deferredTypes) {
errorReporter.reportError("Did not generate @AutoValue class for " + type.getQualifiedName()
+ " because it references undefined types", type);
}
return false;
}
Collection<? extends Element> annotatedElements =
roundEnv.getElementsAnnotatedWith(AutoValue.class);
List<TypeElement> types = new ImmutableList.Builder<TypeElement>()
.addAll(deferredTypes)
.addAll(ElementFilter.typesIn(annotatedElements))
.build();
deferredTypeNames.clear();
for (TypeElement type : types) {
try {
processType(type);
} catch (AbortProcessingException e) {
// We abandoned this type; continue with the next.
} catch (MissingTypeException e) {
// We abandoned this type, but only because we needed another type that it references and
// that other type was missing. It is possible that the missing type will be generated by
// further annotation processing, so we will try again on the next round (perhaps failing
// again and adding it back to the list). We save the name of the @AutoValue type rather
// than its TypeElement because it is not guaranteed that it will be represented by
// the same TypeElement on the next round.
deferredTypeNames.add(type.getQualifiedName().toString());
} catch (RuntimeException e) {
// Don't propagate this exception, which will confusingly crash the compiler.
// Instead, report a compiler error with the stack trace.
String trace = Throwables.getStackTraceAsString(e);
errorReporter.reportError("@AutoValue processor threw an exception: " + trace, type);
}
}
return false; // never claim annotation, because who knows what other processors want?
}
private String generatedClassName(TypeElement type, String prefix) {
String name = type.getSimpleName().toString();
while (type.getEnclosingElement() instanceof TypeElement) {
type = (TypeElement) type.getEnclosingElement();
name = type.getSimpleName() + "_" + name;
}
String pkg = TypeSimplifier.packageNameOf(type);
String dot = pkg.isEmpty() ? "" : ".";
return pkg + dot + prefix + name;
}
private String generatedSubclassName(TypeElement type) {
return generatedClassName(type, "AutoValue_");
}
// Return the name of the class, including any enclosing classes but not the package.
private static String classNameOf(TypeElement type) {
String name = type.getQualifiedName().toString();
String pkgName = TypeSimplifier.packageNameOf(type);
if (!pkgName.isEmpty()) {
return name.substring(pkgName.length() + 1);
} else {
return name;
}
}
/**
* A property of an {@code @AutoValue} class, defined by one of its abstract methods.
* An instance of this class is made available to the Velocity template engine for
* each property. The public methods of this class define JavaBeans-style properties
* that are accessible from templates. For example {@link #getType()} means we can
* write {@code $p.type} for a Velocity variable {@code $p} that is a {@code Property}.
*/
public static class Property {
private final String name;
private final String identifier;
private final ExecutableElement method;
private final String type;
private final ImmutableList<String> annotations;
Property(
String name,
String identifier,
ExecutableElement method,
String type,
TypeSimplifier typeSimplifier) {
this.name = name;
this.identifier = identifier;
this.method = method;
this.type = type;
this.annotations = buildAnnotations(typeSimplifier);
}
private ImmutableList<String> buildAnnotations(TypeSimplifier typeSimplifier) {
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (AnnotationMirror annotationMirror : method.getAnnotationMirrors()) {
TypeElement annotationElement =
(TypeElement) annotationMirror.getAnnotationType().asElement();
if (annotationElement.getQualifiedName().toString().equals(Override.class.getName())) {
// Don't copy @Override if present, since we will be adding our own @Override in the
// implementation.
continue;
}
String annotationName = typeSimplifier.simplify(annotationMirror.getAnnotationType());
String annotation = "@" + annotationName;
List<String> values = Lists.newArrayList();
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
annotationMirror.getElementValues().entrySet()) {
values.add(entry.getKey().getSimpleName() + "=" + entry.getValue());
}
if (!values.isEmpty()) {
annotation += "(" + Joiner.on(", ").join(values) + ")";
}
builder.add(annotation);
}
return builder.build();
}
/**
* Returns the name of the property as it should be used when declaring identifiers (fields and
* parameters). If the original getter method was {@code foo()} then this will be {@code foo}.
* If it was {@code getFoo()} then it will be {@code foo}. If it was {@code getPackage()} then
* it will be something like {@code package0}, since {@code package} is a reserved word.
*/
@Override
public String toString() {
return identifier;
}
/**
* Returns the name of the property as it should be used in strings visible to users. This is
* usually the same as {@code toString()}, except that if we had to use an identifier like
* "package0" because "package" is a reserved word, the name here will be the original
* "package".
*/
public String getName() {
return name;
}
/**
* Returns the name of the getter method for this property as defined by the {@code @AutoValue}
* class. For property {@code foo}, this will be {@code foo} or {@code getFoo} or {@code isFoo}.
*/
public String getGetter() {
return method.getSimpleName().toString();
}
TypeElement getOwner() {
return (TypeElement) method.getEnclosingElement();
}
TypeMirror getTypeMirror() {
return method.getReturnType();
}
public String getType() {
return type;
}
public TypeKind getKind() {
return method.getReturnType().getKind();
}
public List<String> getAnnotations() {
return annotations;
}
public boolean isNullable() {
for (AnnotationMirror annotationMirror : method.getAnnotationMirrors()) {
String name = annotationMirror.getAnnotationType().asElement().getSimpleName().toString();
if (name.equals("Nullable")) {
return true;
}
}
return false;
}
public String getAccess() {
Set<Modifier> mods = method.getModifiers();
if (mods.contains(Modifier.PUBLIC)) {
return "public ";
} else if (mods.contains(Modifier.PROTECTED)) {
return "protected ";
} else {
return "";
}
}
}
private static boolean isJavaLangObject(TypeElement type) {
return type.getSuperclass().getKind() == TypeKind.NONE && type.getKind() == ElementKind.CLASS;
}
private enum ObjectMethodToOverride {
NONE, TO_STRING, EQUALS, HASH_CODE
}
private static ObjectMethodToOverride objectMethodToOverride(ExecutableElement method) {
String name = method.getSimpleName().toString();
switch (method.getParameters().size()) {
case 0:
if (name.equals("toString")) {
return ObjectMethodToOverride.TO_STRING;
} else if (name.equals("hashCode")) {
return ObjectMethodToOverride.HASH_CODE;
}
break;
case 1:
if (name.equals("equals")
&& method.getParameters().get(0).asType().toString().equals("java.lang.Object")) {
return ObjectMethodToOverride.EQUALS;
}
break;
}
return ObjectMethodToOverride.NONE;
}
private void findLocalAndInheritedMethods(TypeElement type, List<ExecutableElement> methods) {
Types typeUtils = processingEnv.getTypeUtils();
Elements elementUtils = processingEnv.getElementUtils();
for (TypeMirror superInterface : type.getInterfaces()) {
findLocalAndInheritedMethods((TypeElement) typeUtils.asElement(superInterface), methods);
}
if (type.getSuperclass().getKind() != TypeKind.NONE) {
// Visit the superclass after superinterfaces so we will always see the implementation of a
// method after any interfaces that declared it.
findLocalAndInheritedMethods(
(TypeElement) typeUtils.asElement(type.getSuperclass()), methods);
}
// Add each method of this class, and in so doing remove any inherited method it overrides.
// This algorithm is quadratic in the number of methods but it's hard to see how to improve
// that while still using Elements.overrides.
List<ExecutableElement> theseMethods = ElementFilter.methodsIn(type.getEnclosedElements());
for (ExecutableElement method : theseMethods) {
if (!method.getModifiers().contains(Modifier.PRIVATE)) {
boolean alreadySeen = false;
for (Iterator<ExecutableElement> methodIter = methods.iterator(); methodIter.hasNext();) {
ExecutableElement otherMethod = methodIter.next();
if (elementUtils.overrides(method, otherMethod, type)) {
methodIter.remove();
} else if (method.getSimpleName().equals(otherMethod.getSimpleName())
&& method.getParameters().equals(otherMethod.getParameters())) {
// If we inherit this method on more than one path, we don't want to add it twice.
alreadySeen = true;
}
}
if (!alreadySeen) {
methods.add(method);
}
}
}
}
private void processType(TypeElement type) {
AutoValue autoValue = type.getAnnotation(AutoValue.class);
if (autoValue == null) {
// This shouldn't happen unless the compilation environment is buggy,
// but it has happened in the past and can crash the compiler.
errorReporter.abortWithError("annotation processor for @AutoValue was invoked with a type"
+ " that does not have that annotation; this is probably a compiler bug", type);
}
if (type.getKind() != ElementKind.CLASS) {
errorReporter.abortWithError(
"@" + AutoValue.class.getName() + " only applies to classes", type);
}
if (ancestorIsAutoValue(type)) {
errorReporter.abortWithError("One @AutoValue class may not extend another", type);
}
if (implementsAnnotation(type)) {
errorReporter.abortWithError("@AutoValue may not be used to implement an annotation"
+ " interface; try using @AutoAnnotation instead", type);
}
AutoValueTemplateVars vars = new AutoValueTemplateVars();
vars.pkg = TypeSimplifier.packageNameOf(type);
vars.origClass = classNameOf(type);
vars.simpleClassName = TypeSimplifier.simpleNameOf(vars.origClass);
vars.subclass = TypeSimplifier.simpleNameOf(generatedSubclassName(type));
defineVarsForType(type, vars);
GwtCompatibility gwtCompatibility = new GwtCompatibility(type);
vars.gwtCompatibleAnnotation = gwtCompatibility.gwtCompatibleAnnotationString();
String text = vars.toText();
text = Reformatter.fixup(text);
writeSourceFile(generatedSubclassName(type), text, type);
GwtSerialization gwtSerialization = new GwtSerialization(gwtCompatibility, processingEnv, type);
gwtSerialization.maybeWriteGwtSerializer(vars);
}
private void defineVarsForType(TypeElement type, AutoValueTemplateVars vars) {
Types typeUtils = processingEnv.getTypeUtils();
List<ExecutableElement> methods = new ArrayList<ExecutableElement>();
findLocalAndInheritedMethods(type, methods);
determineObjectMethodsToGenerate(methods, vars);
ImmutableList<ExecutableElement> toImplement = methodsToImplement(methods);
Set<TypeMirror> types = new TypeMirrorSet();
types.addAll(returnTypesOf(toImplement));
TypeMirror javaxAnnotationGenerated = getTypeMirror(Generated.class);
types.add(javaxAnnotationGenerated);
TypeMirror javaUtilArrays = getTypeMirror(Arrays.class);
if (containsArrayType(types)) {
// If there are array properties then we will be referencing java.util.Arrays.
// Arrange to import it unless that would introduce ambiguity.
types.add(javaUtilArrays);
}
String pkg = TypeSimplifier.packageNameOf(type);
TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, pkg, types, type.asType());
vars.imports = typeSimplifier.typesToImport();
vars.generated = typeSimplifier.simplify(javaxAnnotationGenerated);
vars.arrays = typeSimplifier.simplify(javaUtilArrays);
Map<ExecutableElement, String> methodToPropertyName = Maps.newLinkedHashMap();
boolean allGetters = allGetters(toImplement);
for (ExecutableElement method : toImplement) {
String methodName = method.getSimpleName().toString();
String name = allGetters ? nameWithoutPrefix(methodName) : methodName;
methodToPropertyName.put(method, name);
}
if (allGetters) {
checkDuplicateGetters(methodToPropertyName);
}
Map<ExecutableElement, String> methodToIdentifier = Maps.newLinkedHashMap(methodToPropertyName);
fixReservedIdentifiers(methodToIdentifier);
List<Property> props = new ArrayList<Property>();
for (ExecutableElement method : toImplement) {
String propertyType = typeSimplifier.simplify(method.getReturnType());
String propertyName = methodToPropertyName.get(method);
String identifier = methodToIdentifier.get(method);
props.add(new Property(propertyName, identifier, method, propertyType, typeSimplifier));
}
// If we are running from Eclipse, undo the work of its compiler which sorts methods.
eclipseHack().reorderProperties(props);
vars.props = props;
vars.serialVersionUID = getSerialVersionUID(type);
vars.formalTypes = typeSimplifier.formalTypeParametersString(type);
vars.actualTypes = actualTypeParametersString(type);
vars.wildcardTypes = wildcardTypeParametersString(type);
// Check for @AutoValue.Builder and add appropriate variables if it is present.
BuilderSpec builderSpec = new BuilderSpec(type, processingEnv, errorReporter);
Optional<BuilderSpec.Builder> builder = builderSpec.getBuilder();
if (builder.isPresent() && builder.get().validSetters(methodToPropertyName)) {
// TODO(user): define vars for builder here
}
}
private boolean allGetters(List<ExecutableElement> methods) {
for (ExecutableElement method : methods) {
String name = method.getSimpleName().toString();
// TODO(user): decide whether getfoo() (without a capital) is a getter. Currently it is.
boolean get = name.startsWith("get") && !name.equals("get");
boolean is = name.startsWith("is") && !name.equals("is")
&& method.getReturnType().getKind() == TypeKind.BOOLEAN;
if (!get && !is) {
return false;
}
}
return true;
}
private String nameWithoutPrefix(String name) {
if (name.startsWith("get")) {
name = name.substring(3);
} else {
assert name.startsWith("is");
name = name.substring(2);
}
return Introspector.decapitalize(name);
}
private void checkDuplicateGetters(Map<ExecutableElement, String> methodToIdentifier) {
Set<String> seen = Sets.newHashSet();
for (Map.Entry<ExecutableElement, String> entry : methodToIdentifier.entrySet()) {
if (!seen.add(entry.getValue())) {
errorReporter.reportError(
"More than one @AutoValue property called " + entry.getValue(), entry.getKey());
}
}
}
// If we have a getter called getPackage() then we can't use the identifier "package" to represent
// its value since that's a reserved word.
private void fixReservedIdentifiers(Map<ExecutableElement, String> methodToIdentifier) {
for (Map.Entry<ExecutableElement, String> entry : methodToIdentifier.entrySet()) {
if (SourceVersion.isKeyword(entry.getValue())) {
entry.setValue(disambiguate(entry.getValue(), methodToIdentifier.values()));
}
}
}
private String disambiguate(String name, Collection<String> existingNames) {
for (int i = 0; ; i++) {
String candidate = name + i;
if (!existingNames.contains(candidate)) {
return candidate;
}
}
}
private Set<TypeMirror> returnTypesOf(List<ExecutableElement> methods) {
Set<TypeMirror> returnTypes = new TypeMirrorSet();
for (ExecutableElement method : methods) {
returnTypes.add(method.getReturnType());
}
return returnTypes;
}
private static boolean containsArrayType(Set<TypeMirror> types) {
for (TypeMirror type : types) {
if (type.getKind() == TypeKind.ARRAY) {
return true;
}
}
return false;
}
/**
* Given a list of all methods defined in or inherited by a class, sets the equals, hashCode, and
* toString fields of vars according as the corresponding methods should be generated.
*/
private static void determineObjectMethodsToGenerate(
List<ExecutableElement> methods, AutoValueTemplateVars vars) {
// The defaults here only come into play when an ancestor class doesn't exist.
// Compilation will fail in that case, but we don't want it to crash the compiler with
// an exception before it does. If all ancestors do exist then we will definitely find
// definitions of these three methods (perhaps the ones in Object) so we will overwrite these:
vars.equals = false;
vars.hashCode = false;
vars.toString = false;
for (ExecutableElement method : methods) {
ObjectMethodToOverride override = objectMethodToOverride(method);
boolean canGenerate = method.getModifiers().contains(Modifier.ABSTRACT)
|| isJavaLangObject((TypeElement) method.getEnclosingElement());
switch (override) {
case EQUALS:
vars.equals = canGenerate;
break;
case HASH_CODE:
vars.hashCode = canGenerate;
break;
case TO_STRING:
vars.toString = canGenerate;
break;
}
}
}
private ImmutableList<ExecutableElement> methodsToImplement(List<ExecutableElement> methods) {
ImmutableList.Builder<ExecutableElement> toImplement = ImmutableList.builder();
boolean errors = false;
for (ExecutableElement method : methods) {
if (method.getModifiers().contains(Modifier.ABSTRACT)
&& objectMethodToOverride(method) == ObjectMethodToOverride.NONE) {
if (method.getParameters().isEmpty() && method.getReturnType().getKind() != TypeKind.VOID) {
if (isReferenceArrayType(method.getReturnType())) {
errorReporter.reportError("An @AutoValue class cannot define an array-valued property"
+ " unless it is a primitive array", method);
errors = true;
}
toImplement.add(method);
} else {
// This could reasonably be an error, were it not for an Eclipse bug in
// ElementUtils.override that sometimes fails to recognize that one method overrides
// another, and therefore leaves us with both an abstract method and the subclass method
// that overrides it. This shows up in AutoValueTest.LukesBase for example.
errorReporter.reportWarning("@AutoValue classes cannot have abstract methods other than"
+ " property getters", method);
}
}
}
if (errors) {
throw new AbortProcessingException();
}
return toImplement.build();
}
private static boolean isReferenceArrayType(TypeMirror type) {
return type.getKind() == TypeKind.ARRAY
&& !((ArrayType) type).getComponentType().getKind().isPrimitive();
}
private void writeSourceFile(String className, String text, TypeElement originatingType) {
try {
JavaFileObject sourceFile =
processingEnv.getFiler().createSourceFile(className, originatingType);
Writer writer = sourceFile.openWriter();
try {
writer.write(text);
} finally {
writer.close();
}
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Could not write generated class " + className + ": " + e);
}
}
private boolean ancestorIsAutoValue(TypeElement type) {
while (true) {
TypeMirror parentMirror = type.getSuperclass();
if (parentMirror.getKind() == TypeKind.NONE) {
return false;
}
Types typeUtils = processingEnv.getTypeUtils();
TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror);
if (parentElement.getAnnotation(AutoValue.class) != null) {
return true;
}
type = parentElement;
}
}
private boolean implementsAnnotation(TypeElement type) {
Types typeUtils = processingEnv.getTypeUtils();
return typeUtils.isAssignable(type.asType(), getTypeMirror(Annotation.class));
}
// Return a string like "1234L" if type instanceof Serializable and defines
// serialVersionUID = 1234L, otherwise "".
private String getSerialVersionUID(TypeElement type) {
Types typeUtils = processingEnv.getTypeUtils();
TypeMirror serializable = getTypeMirror(Serializable.class);
if (typeUtils.isAssignable(type.asType(), serializable)) {
List<VariableElement> fields = ElementFilter.fieldsIn(type.getEnclosedElements());
for (VariableElement field : fields) {
if (field.getSimpleName().toString().equals("serialVersionUID")) {
Object value = field.getConstantValue();
if (field.getModifiers().containsAll(Arrays.asList(Modifier.STATIC, Modifier.FINAL))
&& field.asType().getKind() == TypeKind.LONG
&& value != null) {
return value + "L";
} else {
errorReporter.reportError(
"serialVersionUID must be a static final long compile-time constant", field);
break;
}
}
}
}
return "";
}
private TypeMirror getTypeMirror(Class<?> c) {
return processingEnv.getElementUtils().getTypeElement(c.getName()).asType();
}
private enum ElementNameFunction implements Function<Element, String> {
INSTANCE;
@Override public String apply(Element element) {
return element.getSimpleName().toString();
}
}
// The actual type parameters of the generated type.
// If we have @AutoValue abstract class Foo<T extends Something> then the subclass will be
// final class AutoValue_Foo<T extends Something> extends Foo<T>.
// <T extends Something> is the formal type parameter list and
// <T> is the actual type parameter list, which is what this method returns.
private static String actualTypeParametersString(TypeElement type) {
List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
if (typeParameters.isEmpty()) {
return "";
} else {
return "<"
+ Joiner.on(", ").join(
FluentIterable.from(typeParameters).transform(ElementNameFunction.INSTANCE))
+ ">";
}
}
// The @AutoValue type, with a ? for every type.
// If we have @AutoValue abstract class Foo<T extends Something> then this method will return
// just <?>.
private static String wildcardTypeParametersString(TypeElement type) {
List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
if (typeParameters.isEmpty()) {
return "";
} else {
return "<"
+ Joiner.on(", ").join(
FluentIterable.from(typeParameters).transform(Functions.constant("?")))
+ ">";
}
}
private EclipseHack eclipseHack() {
return new EclipseHack(processingEnv);
}
}