From e7748beb9793c71249540e6d2e852bc23fa314c4 Mon Sep 17 00:00:00 2001 From: dpb Date: Fri, 15 Dec 2017 06:44:19 -0800 Subject: [PATCH 1/2] Write the correct @Generated annotation within auto-factory. RELNOTES=Use `@javax.annotation.processing.Generated` for Java 9. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=179187028 --- .../auto/factory/processor/FactoryWriter.java | 17 +- .../processor/AutoFactoryProcessorTest.java | 189 ++++++++++++------ .../ClassUsingQualifierWithArgsFactory.java | 2 +- .../expected/ConstructorAnnotatedFactory.java | 2 +- .../ConstructorAnnotatedNonFinalFactory.java | 2 +- .../expected/CustomNamedFactory.java | 2 +- .../expected/CustomNullableFactory.java | 2 +- .../FactoryExtendingAbstractClassFactory.java | 2 +- ...tingCreateMethod_ConcreteClassFactory.java | 2 +- ...ntingGenericInterfaceExtensionFactory.java | 2 +- ...ixedDepsImplementingInterfacesFactory.java | 2 +- ...oriesConflictingParameterNamesFactory.java | 2 +- ...esImplementingInterface_ClassAFactory.java | 2 +- ...esImplementingInterface_ClassBFactory.java | 2 +- .../MultipleProvidedParamsSameKeyFactory.java | 2 +- .../NestedClassCustomNamedFactory.java | 2 +- ...estedClasses_SimpleNestedClassFactory.java | 2 +- .../expected/OnlyPrimitivesFactory.java | 2 +- ...ProviderArgumentToCreateMethodFactory.java | 2 +- .../expected/PublicClassFactory.java | 2 +- .../expected/SimpleClassFactory.java | 2 +- .../SimpleClassImplementingMarkerFactory.java | 2 +- ...assImplementingSimpleInterfaceFactory.java | 2 +- .../expected/SimpleClassMixedDepsFactory.java | 2 +- .../expected/SimpleClassNonFinalFactory.java | 2 +- .../SimpleClassNullableParametersFactory.java | 2 +- .../SimpleClassPassedDepsFactory.java | 2 +- .../SimpleClassProvidedDepsFactory.java | 2 +- ...impleClassProvidedProviderDepsFactory.java | 2 +- .../expected/SimpleClassVarargsFactory.java | 2 +- 30 files changed, 158 insertions(+), 104 deletions(-) diff --git a/factory/src/main/java/com/google/auto/factory/processor/FactoryWriter.java b/factory/src/main/java/com/google/auto/factory/processor/FactoryWriter.java index 7450ae17c8..ad7e7badab 100644 --- a/factory/src/main/java/com/google/auto/factory/processor/FactoryWriter.java +++ b/factory/src/main/java/com/google/auto/factory/processor/FactoryWriter.java @@ -15,6 +15,7 @@ */ package com.google.auto.factory.processor; +import static com.google.auto.common.GeneratedAnnotationSpecs.generatedAnnotationSpec; import static com.google.auto.factory.processor.Mirrors.isProvider; import static com.squareup.javapoet.MethodSpec.constructorBuilder; import static com.squareup.javapoet.MethodSpec.methodBuilder; @@ -45,7 +46,6 @@ import javax.inject.Inject; import javax.inject.Provider; import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; @@ -65,16 +65,11 @@ void writeFactory(final FactoryDescriptor descriptor) throws IOException { String factoryName = getSimpleName(descriptor.name()).toString(); TypeSpec.Builder factory = classBuilder(factoryName); - // TODO(ronshapiro): use javax.annotation.processing.Generated if it's available? - TypeElement generatedAnnotation = elements.getTypeElement("javax.annotation.Generated"); - if (generatedAnnotation != null) { - factory.addAnnotation( - AnnotationSpec.builder(ClassName.get(generatedAnnotation)) - .addMember("value", "$S", AutoFactoryProcessor.class.getName()) - .addMember( - "comments", "$S", "https://github.com/google/auto/tree/master/factory") - .build()); - } + generatedAnnotationSpec( + elements, + AutoFactoryProcessor.class, + "https://github.com/google/auto/tree/master/factory") + .ifPresent(factory::addAnnotation); if (!descriptor.allowSubclasses()) { factory.addModifiers(FINAL); } diff --git a/factory/src/test/java/com/google/auto/factory/processor/AutoFactoryProcessorTest.java b/factory/src/test/java/com/google/auto/factory/processor/AutoFactoryProcessorTest.java index 368be63296..9e59c37203 100644 --- a/factory/src/test/java/com/google/auto/factory/processor/AutoFactoryProcessorTest.java +++ b/factory/src/test/java/com/google/auto/factory/processor/AutoFactoryProcessorTest.java @@ -19,10 +19,18 @@ import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; import static com.google.testing.compile.JavaSourcesSubject.assertThat; import static com.google.testing.compile.JavaSourcesSubjectFactory.javaSources; +import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.ImmutableSet; +import com.google.common.io.Resources; +import com.google.testing.compile.CompilationRule; import com.google.testing.compile.JavaFileObjects; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Collections; +import java.util.List; import javax.tools.JavaFileObject; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -32,12 +40,16 @@ */ @RunWith(JUnit4.class) public class AutoFactoryProcessorTest { + + @Rule public final CompilationRule compilationRule = new CompilationRule(); + @Test public void simpleClass() { assertAbout(javaSource()) .that(JavaFileObjects.forResource("good/SimpleClass.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources(JavaFileObjects.forResource("expected/SimpleClassFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/SimpleClassFactory.java")); } @Test @@ -48,8 +60,8 @@ public void nestedClasses() { .compilesWithoutError() .and() .generatesSources( - JavaFileObjects.forResource("expected/NestedClasses_SimpleNestedClassFactory.java"), - JavaFileObjects.forResource("expected/NestedClassCustomNamedFactory.java")); + loadExpectedFile("expected/NestedClasses_SimpleNestedClassFactory.java"), + loadExpectedFile("expected/NestedClassCustomNamedFactory.java")); } @Test public void simpleClassNonFinal() { @@ -57,8 +69,8 @@ public void nestedClasses() { .that(JavaFileObjects.forResource("good/SimpleClassNonFinal.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/SimpleClassNonFinalFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/SimpleClassNonFinalFactory.java")); } @Test public void publicClass() { @@ -66,7 +78,8 @@ public void nestedClasses() { .that(JavaFileObjects.forResource("good/PublicClass.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources(JavaFileObjects.forResource("expected/PublicClassFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/PublicClassFactory.java")); } @Test public void simpleClassCustomName() { @@ -74,18 +87,20 @@ public void nestedClasses() { .that(JavaFileObjects.forResource("good/SimpleClassCustomName.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources(JavaFileObjects.forResource("expected/CustomNamedFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/CustomNamedFactory.java")); } @Test public void simpleClassMixedDeps() { assertAbout(javaSources()) - .that(ImmutableSet.of( - JavaFileObjects.forResource("good/SimpleClassMixedDeps.java"), - JavaFileObjects.forResource("support/AQualifier.java"))) + .that( + ImmutableSet.of( + JavaFileObjects.forResource("good/SimpleClassMixedDeps.java"), + JavaFileObjects.forResource("support/AQualifier.java"))) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/SimpleClassMixedDepsFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/SimpleClassMixedDepsFactory.java")); } @Test public void simpleClassPassedDeps() { @@ -93,20 +108,21 @@ public void nestedClasses() { .that(JavaFileObjects.forResource("good/SimpleClassPassedDeps.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/SimpleClassPassedDepsFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/SimpleClassPassedDepsFactory.java")); } @Test public void simpleClassProvidedDeps() { assertAbout(javaSources()) - .that(ImmutableSet.of( - JavaFileObjects.forResource("support/AQualifier.java"), - JavaFileObjects.forResource("support/BQualifier.java"), - JavaFileObjects.forResource("good/SimpleClassProvidedDeps.java"))) + .that( + ImmutableSet.of( + JavaFileObjects.forResource("support/AQualifier.java"), + JavaFileObjects.forResource("support/BQualifier.java"), + JavaFileObjects.forResource("good/SimpleClassProvidedDeps.java"))) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/SimpleClassProvidedDepsFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/SimpleClassProvidedDepsFactory.java")); } @Test @@ -120,8 +136,7 @@ public void simpleClassProvidedProviderDeps() { .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() .and() - .generatesSources( - JavaFileObjects.forResource("expected/SimpleClassProvidedProviderDepsFactory.java")); + .generatesSources(loadExpectedFile("expected/SimpleClassProvidedProviderDepsFactory.java")); } @Test public void constructorAnnotated() { @@ -129,8 +144,8 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/ConstructorAnnotated.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/ConstructorAnnotatedFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/ConstructorAnnotatedFactory.java")); } @Test public void constructorAnnotatedNonFinal() { @@ -138,8 +153,8 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/ConstructorAnnotatedNonFinal.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/ConstructorAnnotatedNonFinalFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/ConstructorAnnotatedNonFinalFactory.java")); } @Test public void simpleClassImplementingMarker() { @@ -147,8 +162,8 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/SimpleClassImplementingMarker.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/SimpleClassImplementingMarkerFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/SimpleClassImplementingMarkerFactory.java")); } @Test public void simpleClassImplementingSimpleInterface() { @@ -156,8 +171,9 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/SimpleClassImplementingSimpleInterface.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources(JavaFileObjects.forResource( - "expected/SimpleClassImplementingSimpleInterfaceFactory.java")); + .and() + .generatesSources( + loadExpectedFile("expected/SimpleClassImplementingSimpleInterfaceFactory.java")); } @Test public void mixedDepsImplementingInterfaces() { @@ -165,8 +181,8 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/MixedDepsImplementingInterfaces.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/MixedDepsImplementingInterfacesFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/MixedDepsImplementingInterfacesFactory.java")); } @Test public void failsWithMixedFinals() { @@ -230,8 +246,8 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/FactoryExtendingAbstractClass.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/FactoryExtendingAbstractClassFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/FactoryExtendingAbstractClassFactory.java")); } @Test public void factoryExtendingAbstractClass_withConstructorParams() { @@ -298,8 +314,9 @@ public void simpleClassProvidedProviderDeps() { .that(file) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources(JavaFileObjects.forResource( - "expected/FactoryImplementingGenericInterfaceExtensionFactory.java")); + .and() + .generatesSources( + loadExpectedFile("expected/FactoryImplementingGenericInterfaceExtensionFactory.java")); } @Test public void multipleFactoriesImpementingInterface() { @@ -309,22 +326,22 @@ public void simpleClassProvidedProviderDeps() { .that(file) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource( - "expected/MultipleFactoriesImplementingInterface_ClassAFactory.java"), - JavaFileObjects.forResource( - "expected/MultipleFactoriesImplementingInterface_ClassBFactory.java")); + .and() + .generatesSources( + loadExpectedFile("expected/MultipleFactoriesImplementingInterface_ClassAFactory.java"), + loadExpectedFile("expected/MultipleFactoriesImplementingInterface_ClassBFactory.java")); } @Test public void classUsingQualifierWithArgs() { assertAbout(javaSources()) - .that(ImmutableSet.of( - JavaFileObjects.forResource("support/QualifierWithArgs.java"), - JavaFileObjects.forResource("good/ClassUsingQualifierWithArgs.java"))) + .that( + ImmutableSet.of( + JavaFileObjects.forResource("support/QualifierWithArgs.java"), + JavaFileObjects.forResource("good/ClassUsingQualifierWithArgs.java"))) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/ClassUsingQualifierWithArgsFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/ClassUsingQualifierWithArgsFactory.java")); } @Test public void factoryImplementingInterfaceWhichRedeclaresCreateMethods() { @@ -334,21 +351,22 @@ public void simpleClassProvidedProviderDeps() { .that(file) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource( - "expected/FactoryImplementingCreateMethod_ConcreteClassFactory.java")); + .and() + .generatesSources( + loadExpectedFile("expected/FactoryImplementingCreateMethod_ConcreteClassFactory.java")); } @Test public void nullableParams() { assertAbout(javaSources()) - .that(ImmutableSet.of( - JavaFileObjects.forResource("good/SimpleClassNullableParameters.java"), - JavaFileObjects.forResource("support/AQualifier.java"), - JavaFileObjects.forResource("support/BQualifier.java"))) + .that( + ImmutableSet.of( + JavaFileObjects.forResource("good/SimpleClassNullableParameters.java"), + JavaFileObjects.forResource("support/AQualifier.java"), + JavaFileObjects.forResource("support/BQualifier.java"))) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/SimpleClassNullableParametersFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/SimpleClassNullableParametersFactory.java")); } @Test public void customNullableType() { @@ -356,7 +374,8 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/CustomNullable.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources(JavaFileObjects.forResource("expected/CustomNullableFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/CustomNullableFactory.java")); } @Test public void multipleProvidedParamsWithSameKey() { @@ -364,8 +383,8 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/MultipleProvidedParamsSameKey.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/MultipleProvidedParamsSameKeyFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/MultipleProvidedParamsSameKeyFactory.java")); } @Test public void providerArgumentToCreateMethod() { @@ -373,8 +392,8 @@ public void simpleClassProvidedProviderDeps() { .that(JavaFileObjects.forResource("good/ProviderArgumentToCreateMethod.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource("expected/ProviderArgumentToCreateMethodFactory.java")); + .and() + .generatesSources(loadExpectedFile("expected/ProviderArgumentToCreateMethodFactory.java")); } @Test public void multipleFactoriesConflictingParameterNames() { @@ -383,9 +402,9 @@ public void simpleClassProvidedProviderDeps() { JavaFileObjects.forResource("support/AQualifier.java")) .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() - .and().generatesSources( - JavaFileObjects.forResource( - "expected/MultipleFactoriesConflictingParameterNamesFactory.java")); + .and() + .generatesSources( + loadExpectedFile("expected/MultipleFactoriesConflictingParameterNamesFactory.java")); } @Test public void factoryVarargs() { @@ -393,7 +412,7 @@ public void simpleClassProvidedProviderDeps() { .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() .and() - .generatesSources(JavaFileObjects.forResource("expected/SimpleClassVarargsFactory.java")); + .generatesSources(loadExpectedFile("expected/SimpleClassVarargsFactory.java")); } @Test public void onlyPrimitives() { @@ -401,6 +420,46 @@ public void simpleClassProvidedProviderDeps() { .processedWith(new AutoFactoryProcessor()) .compilesWithoutError() .and() - .generatesSources(JavaFileObjects.forResource("expected/OnlyPrimitivesFactory.java")); + .generatesSources(loadExpectedFile("expected/OnlyPrimitivesFactory.java")); + } + + private JavaFileObject loadExpectedFile(String resourceName) { + try { + List sourceLines = Resources.readLines(Resources.getResource(resourceName), UTF_8); + if (!isJavaxAnnotationProcessingGeneratedAvailable()) { + replaceGeneratedImport(sourceLines); + } + return JavaFileObjects.forSourceLines( + resourceName.replace('/', '.').replace(".java", ""), sourceLines); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private boolean isJavaxAnnotationProcessingGeneratedAvailable() { + return compilationRule.getElements().getTypeElement("javax.annotation.processing.Generated") + != null; + } + + private static void replaceGeneratedImport(List sourceLines) { + int i = 0; + int firstImport = Integer.MAX_VALUE; + int lastImport = -1; + for (String line : sourceLines) { + if (line.startsWith("import ") && !line.startsWith("import static ")) { + firstImport = Math.min(firstImport, i); + lastImport = Math.max(lastImport, i); + } + i++; + } + if (lastImport >= 0) { + List importLines = sourceLines.subList(firstImport, lastImport + 1); + importLines.replaceAll( + line -> + line.startsWith("import javax.annotation.processing.Generated;") + ? "import javax.annotation.Generated;" + : line); + Collections.sort(importLines); + } } } diff --git a/factory/src/test/resources/expected/ClassUsingQualifierWithArgsFactory.java b/factory/src/test/resources/expected/ClassUsingQualifierWithArgsFactory.java index 988e7b0b51..592bc67bc6 100644 --- a/factory/src/test/resources/expected/ClassUsingQualifierWithArgsFactory.java +++ b/factory/src/test/resources/expected/ClassUsingQualifierWithArgsFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/ConstructorAnnotatedFactory.java b/factory/src/test/resources/expected/ConstructorAnnotatedFactory.java index 35aac934ce..7d7d7e3561 100644 --- a/factory/src/test/resources/expected/ConstructorAnnotatedFactory.java +++ b/factory/src/test/resources/expected/ConstructorAnnotatedFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/ConstructorAnnotatedNonFinalFactory.java b/factory/src/test/resources/expected/ConstructorAnnotatedNonFinalFactory.java index ba1433cda7..6a5538cc00 100644 --- a/factory/src/test/resources/expected/ConstructorAnnotatedNonFinalFactory.java +++ b/factory/src/test/resources/expected/ConstructorAnnotatedNonFinalFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/CustomNamedFactory.java b/factory/src/test/resources/expected/CustomNamedFactory.java index 6682c818a6..2d116badd1 100644 --- a/factory/src/test/resources/expected/CustomNamedFactory.java +++ b/factory/src/test/resources/expected/CustomNamedFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/CustomNullableFactory.java b/factory/src/test/resources/expected/CustomNullableFactory.java index e00895c36d..dc81f44a2d 100644 --- a/factory/src/test/resources/expected/CustomNullableFactory.java +++ b/factory/src/test/resources/expected/CustomNullableFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/FactoryExtendingAbstractClassFactory.java b/factory/src/test/resources/expected/FactoryExtendingAbstractClassFactory.java index caf2c74922..4a731489ff 100644 --- a/factory/src/test/resources/expected/FactoryExtendingAbstractClassFactory.java +++ b/factory/src/test/resources/expected/FactoryExtendingAbstractClassFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/FactoryImplementingCreateMethod_ConcreteClassFactory.java b/factory/src/test/resources/expected/FactoryImplementingCreateMethod_ConcreteClassFactory.java index efc31ef149..ef8b3b7b1b 100644 --- a/factory/src/test/resources/expected/FactoryImplementingCreateMethod_ConcreteClassFactory.java +++ b/factory/src/test/resources/expected/FactoryImplementingCreateMethod_ConcreteClassFactory.java @@ -16,7 +16,7 @@ package tests; import java.util.List; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/FactoryImplementingGenericInterfaceExtensionFactory.java b/factory/src/test/resources/expected/FactoryImplementingGenericInterfaceExtensionFactory.java index 0c2d0eebb1..6b64db1da3 100644 --- a/factory/src/test/resources/expected/FactoryImplementingGenericInterfaceExtensionFactory.java +++ b/factory/src/test/resources/expected/FactoryImplementingGenericInterfaceExtensionFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/MixedDepsImplementingInterfacesFactory.java b/factory/src/test/resources/expected/MixedDepsImplementingInterfacesFactory.java index 723221d4e1..354d7c0df6 100644 --- a/factory/src/test/resources/expected/MixedDepsImplementingInterfacesFactory.java +++ b/factory/src/test/resources/expected/MixedDepsImplementingInterfacesFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/MultipleFactoriesConflictingParameterNamesFactory.java b/factory/src/test/resources/expected/MultipleFactoriesConflictingParameterNamesFactory.java index 60e64f1746..91cf151e76 100644 --- a/factory/src/test/resources/expected/MultipleFactoriesConflictingParameterNamesFactory.java +++ b/factory/src/test/resources/expected/MultipleFactoriesConflictingParameterNamesFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/MultipleFactoriesImplementingInterface_ClassAFactory.java b/factory/src/test/resources/expected/MultipleFactoriesImplementingInterface_ClassAFactory.java index a3dd9c4396..85de4571c3 100644 --- a/factory/src/test/resources/expected/MultipleFactoriesImplementingInterface_ClassAFactory.java +++ b/factory/src/test/resources/expected/MultipleFactoriesImplementingInterface_ClassAFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/MultipleFactoriesImplementingInterface_ClassBFactory.java b/factory/src/test/resources/expected/MultipleFactoriesImplementingInterface_ClassBFactory.java index 3a1287d053..17d9be65a8 100644 --- a/factory/src/test/resources/expected/MultipleFactoriesImplementingInterface_ClassBFactory.java +++ b/factory/src/test/resources/expected/MultipleFactoriesImplementingInterface_ClassBFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/MultipleProvidedParamsSameKeyFactory.java b/factory/src/test/resources/expected/MultipleProvidedParamsSameKeyFactory.java index a04e5bcf69..56d7fd2807 100644 --- a/factory/src/test/resources/expected/MultipleProvidedParamsSameKeyFactory.java +++ b/factory/src/test/resources/expected/MultipleProvidedParamsSameKeyFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/NestedClassCustomNamedFactory.java b/factory/src/test/resources/expected/NestedClassCustomNamedFactory.java index 0edfa69273..e86cc4ef0c 100644 --- a/factory/src/test/resources/expected/NestedClassCustomNamedFactory.java +++ b/factory/src/test/resources/expected/NestedClassCustomNamedFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/NestedClasses_SimpleNestedClassFactory.java b/factory/src/test/resources/expected/NestedClasses_SimpleNestedClassFactory.java index 4a2a686283..f649eda7fd 100644 --- a/factory/src/test/resources/expected/NestedClasses_SimpleNestedClassFactory.java +++ b/factory/src/test/resources/expected/NestedClasses_SimpleNestedClassFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/OnlyPrimitivesFactory.java b/factory/src/test/resources/expected/OnlyPrimitivesFactory.java index f732182270..6db73d2869 100644 --- a/factory/src/test/resources/expected/OnlyPrimitivesFactory.java +++ b/factory/src/test/resources/expected/OnlyPrimitivesFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/ProviderArgumentToCreateMethodFactory.java b/factory/src/test/resources/expected/ProviderArgumentToCreateMethodFactory.java index d04d7ac98d..9e12bb33e6 100644 --- a/factory/src/test/resources/expected/ProviderArgumentToCreateMethodFactory.java +++ b/factory/src/test/resources/expected/ProviderArgumentToCreateMethodFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/PublicClassFactory.java b/factory/src/test/resources/expected/PublicClassFactory.java index 4824637997..5d9361e4f3 100644 --- a/factory/src/test/resources/expected/PublicClassFactory.java +++ b/factory/src/test/resources/expected/PublicClassFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/SimpleClassFactory.java b/factory/src/test/resources/expected/SimpleClassFactory.java index ca56877113..9df1be3f1c 100644 --- a/factory/src/test/resources/expected/SimpleClassFactory.java +++ b/factory/src/test/resources/expected/SimpleClassFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/SimpleClassImplementingMarkerFactory.java b/factory/src/test/resources/expected/SimpleClassImplementingMarkerFactory.java index d2c0c76bf5..272ba29c55 100644 --- a/factory/src/test/resources/expected/SimpleClassImplementingMarkerFactory.java +++ b/factory/src/test/resources/expected/SimpleClassImplementingMarkerFactory.java @@ -16,7 +16,7 @@ package tests; import java.util.RandomAccess; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/SimpleClassImplementingSimpleInterfaceFactory.java b/factory/src/test/resources/expected/SimpleClassImplementingSimpleInterfaceFactory.java index c6c1db61a1..12505fccbb 100644 --- a/factory/src/test/resources/expected/SimpleClassImplementingSimpleInterfaceFactory.java +++ b/factory/src/test/resources/expected/SimpleClassImplementingSimpleInterfaceFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/SimpleClassMixedDepsFactory.java b/factory/src/test/resources/expected/SimpleClassMixedDepsFactory.java index 4aa772bee9..3107ac10d2 100644 --- a/factory/src/test/resources/expected/SimpleClassMixedDepsFactory.java +++ b/factory/src/test/resources/expected/SimpleClassMixedDepsFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/SimpleClassNonFinalFactory.java b/factory/src/test/resources/expected/SimpleClassNonFinalFactory.java index 781dc96967..b8d8a510e1 100644 --- a/factory/src/test/resources/expected/SimpleClassNonFinalFactory.java +++ b/factory/src/test/resources/expected/SimpleClassNonFinalFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/SimpleClassNullableParametersFactory.java b/factory/src/test/resources/expected/SimpleClassNullableParametersFactory.java index f01fc65502..7c690fce69 100644 --- a/factory/src/test/resources/expected/SimpleClassNullableParametersFactory.java +++ b/factory/src/test/resources/expected/SimpleClassNullableParametersFactory.java @@ -15,8 +15,8 @@ */ package tests; -import javax.annotation.Generated; import javax.annotation.Nullable; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/SimpleClassPassedDepsFactory.java b/factory/src/test/resources/expected/SimpleClassPassedDepsFactory.java index 70c57f1ef8..9a0740a831 100644 --- a/factory/src/test/resources/expected/SimpleClassPassedDepsFactory.java +++ b/factory/src/test/resources/expected/SimpleClassPassedDepsFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( diff --git a/factory/src/test/resources/expected/SimpleClassProvidedDepsFactory.java b/factory/src/test/resources/expected/SimpleClassProvidedDepsFactory.java index e52e8ff169..2f43ed739d 100644 --- a/factory/src/test/resources/expected/SimpleClassProvidedDepsFactory.java +++ b/factory/src/test/resources/expected/SimpleClassProvidedDepsFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/SimpleClassProvidedProviderDepsFactory.java b/factory/src/test/resources/expected/SimpleClassProvidedProviderDepsFactory.java index e49cce3214..4804f0e7ef 100644 --- a/factory/src/test/resources/expected/SimpleClassProvidedProviderDepsFactory.java +++ b/factory/src/test/resources/expected/SimpleClassProvidedProviderDepsFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; import javax.inject.Provider; diff --git a/factory/src/test/resources/expected/SimpleClassVarargsFactory.java b/factory/src/test/resources/expected/SimpleClassVarargsFactory.java index 0b56a1a3a9..1a2b47a418 100644 --- a/factory/src/test/resources/expected/SimpleClassVarargsFactory.java +++ b/factory/src/test/resources/expected/SimpleClassVarargsFactory.java @@ -15,7 +15,7 @@ */ package tests; -import javax.annotation.Generated; +import javax.annotation.processing.Generated; import javax.inject.Inject; @Generated( From f04406c1f11d3796bd93ed89ae160f47bcb4b7e4 Mon Sep 17 00:00:00 2001 From: dpb Date: Fri, 15 Dec 2017 06:53:13 -0800 Subject: [PATCH 2/2] Write the correct @Generated annotation within auto-value. RELNOTES=Use `@javax.annotation.processing.Generated` for Java 9. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=179187847 --- .../auto/value/gwt/GwtCompilationTest.java | 385 ++++---- .../extension/memoized/MemoizeExtension.java | 16 +- .../processor/AutoAnnotationProcessor.java | 11 +- .../value/processor/AutoValueProcessor.java | 10 +- .../AutoAnnotationCompilationTest.java | 464 +++++----- .../auto/value/processor/CompilationTest.java | 823 +++++++++--------- .../auto/value/processor/ExtensionTest.java | 109 +-- .../processor/GeneratedDoesNotExistTest.java | 30 +- .../value/processor/GeneratedImportRule.java | 55 ++ .../processor/PropertyAnnotationsTest.java | 14 +- 10 files changed, 999 insertions(+), 918 deletions(-) create mode 100644 value/src/test/java/com/google/auto/value/processor/GeneratedImportRule.java diff --git a/value/src/it/functional/src/test/java/com/google/auto/value/gwt/GwtCompilationTest.java b/value/src/it/functional/src/test/java/com/google/auto/value/gwt/GwtCompilationTest.java index 7e6c1f0dfa..970cc5979b 100644 --- a/value/src/it/functional/src/test/java/com/google/auto/value/gwt/GwtCompilationTest.java +++ b/value/src/it/functional/src/test/java/com/google/auto/value/gwt/GwtCompilationTest.java @@ -20,8 +20,10 @@ import com.google.auto.value.processor.AutoValueProcessor; import com.google.testing.compile.Compilation; +import com.google.testing.compile.CompilationRule; import com.google.testing.compile.JavaFileObjects; import javax.tools.JavaFileObject; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -42,6 +44,8 @@ public class GwtCompilationTest { "}" ); + @Rule public final CompilationRule compilationRule = new CompilationRule(); + /** * Test where the serialized properties don't include generics, so no {@code @SuppressWarnings} * annotation is needed. We explicitly check that one is not included anyway, because Eclipse for @@ -65,65 +69,65 @@ public void testBasic() { " return new AutoValue_Baz(buh);", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "foo.bar.AutoValue_Baz_CustomFieldSerializer", - "package foo.bar;", - "", - "import com.google.gwt.user.client.rpc.CustomFieldSerializer;", - "import com.google.gwt.user.client.rpc.SerializationException;", - "import com.google.gwt.user.client.rpc.SerializationStreamReader;", - "import com.google.gwt.user.client.rpc.SerializationStreamWriter;", - "import javax.annotation.Generated;", - "", - "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")", - "public final class AutoValue_Baz_CustomFieldSerializer" - + " extends CustomFieldSerializer {", - "", - " public static AutoValue_Baz instantiate(", - " SerializationStreamReader streamReader) throws SerializationException {", - " int buh = streamReader.readInt();", - " return new AutoValue_Baz(buh);", - " }", - "", - " public static void serialize(", - " SerializationStreamWriter streamWriter,", - " AutoValue_Baz instance) throws SerializationException {", - " streamWriter.writeInt(instance.buh());", - " }", - "", - " public static void deserialize(", - " @SuppressWarnings(\"unused\") SerializationStreamReader streamReader,", - " @SuppressWarnings(\"unused\") AutoValue_Baz instance) {", - " }", - "", - " @SuppressWarnings(\"unused\") private int dummy_3f8e1b04;", - "", - " @Override", - " public void deserializeInstance(", - " SerializationStreamReader streamReader,", - " AutoValue_Baz instance) {", - " deserialize(streamReader, instance);", - " }", - "", - " @Override", - " public boolean hasCustomInstantiateInstance() {", - " return true;", - " }", - "", - " @Override", - " public AutoValue_Baz instantiateInstance(", - " SerializationStreamReader streamReader) throws SerializationException {", - " return instantiate(streamReader);", - " }", - "", - " @Override", - " public void serializeInstance(", - " SerializationStreamWriter streamWriter,", - " AutoValue_Baz instance) throws SerializationException {", - " serialize(streamWriter, instance);", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "foo.bar.AutoValue_Baz_CustomFieldSerializer", + "package foo.bar;", + "", + "import com.google.gwt.user.client.rpc.CustomFieldSerializer;", + "import com.google.gwt.user.client.rpc.SerializationException;", + "import com.google.gwt.user.client.rpc.SerializationStreamReader;", + "import com.google.gwt.user.client.rpc.SerializationStreamWriter;", + "import " + generatedAnnotationType() + ";", + "", + "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")", + "public final class AutoValue_Baz_CustomFieldSerializer" + + " extends CustomFieldSerializer {", + "", + " public static AutoValue_Baz instantiate(", + " SerializationStreamReader streamReader) throws SerializationException {", + " int buh = streamReader.readInt();", + " return new AutoValue_Baz(buh);", + " }", + "", + " public static void serialize(", + " SerializationStreamWriter streamWriter,", + " AutoValue_Baz instance) throws SerializationException {", + " streamWriter.writeInt(instance.buh());", + " }", + "", + " public static void deserialize(", + " @SuppressWarnings(\"unused\") SerializationStreamReader streamReader,", + " @SuppressWarnings(\"unused\") AutoValue_Baz instance) {", + " }", + "", + " @SuppressWarnings(\"unused\") private int dummy_3f8e1b04;", + "", + " @Override", + " public void deserializeInstance(", + " SerializationStreamReader streamReader,", + " AutoValue_Baz instance) {", + " deserialize(streamReader, instance);", + " }", + "", + " @Override", + " public boolean hasCustomInstantiateInstance() {", + " return true;", + " }", + "", + " @Override", + " public AutoValue_Baz instantiateInstance(", + " SerializationStreamReader streamReader) throws SerializationException {", + " return instantiate(streamReader);", + " }", + "", + " @Override", + " public void serializeInstance(", + " SerializationStreamWriter streamWriter,", + " AutoValue_Baz instance) throws SerializationException {", + " serialize(streamWriter, instance);", + " }", + "}"); Compilation compilation = javac().withProcessors(new AutoValueProcessor()).compile(javaFileObject, GWT_COMPATIBLE); assertThat(compilation) @@ -157,67 +161,67 @@ public void testSuppressWarnings() { " return new AutoValue_Baz(buh);", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "foo.bar.AutoValue_Baz_CustomFieldSerializer", - "package foo.bar;", - "", - "import com.google.gwt.user.client.rpc.CustomFieldSerializer;", - "import com.google.gwt.user.client.rpc.SerializationException;", - "import com.google.gwt.user.client.rpc.SerializationStreamReader;", - "import com.google.gwt.user.client.rpc.SerializationStreamWriter;", - "import java.util.List;", - "import javax.annotation.Generated;", - "", - "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")", - "public final class AutoValue_Baz_CustomFieldSerializer" - + " extends CustomFieldSerializer {", - "", - " public static AutoValue_Baz instantiate(", - " SerializationStreamReader streamReader) throws SerializationException {", - " @SuppressWarnings(\"unchecked\")", - " List buh = (List) streamReader.readObject();", - " return new AutoValue_Baz(buh);", - " }", - "", - " public static void serialize(", - " SerializationStreamWriter streamWriter,", - " AutoValue_Baz instance) throws SerializationException {", - " streamWriter.writeObject(instance.buh());", - " }", - "", - " public static void deserialize(", - " @SuppressWarnings(\"unused\") SerializationStreamReader streamReader,", - " @SuppressWarnings(\"unused\") AutoValue_Baz instance) {", - " }", - "", - " @SuppressWarnings(\"unused\") private int dummy_949e312e;", - "", - " @Override", - " public void deserializeInstance(", - " SerializationStreamReader streamReader,", - " AutoValue_Baz instance) {", - " deserialize(streamReader, instance);", - " }", - "", - " @Override", - " public boolean hasCustomInstantiateInstance() {", - " return true;", - " }", - "", - " @Override", - " public AutoValue_Baz instantiateInstance(", - " SerializationStreamReader streamReader) throws SerializationException {", - " return instantiate(streamReader);", - " }", - "", - " @Override", - " public void serializeInstance(", - " SerializationStreamWriter streamWriter,", - " AutoValue_Baz instance) throws SerializationException {", - " serialize(streamWriter, instance);", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "foo.bar.AutoValue_Baz_CustomFieldSerializer", + "package foo.bar;", + "", + "import com.google.gwt.user.client.rpc.CustomFieldSerializer;", + "import com.google.gwt.user.client.rpc.SerializationException;", + "import com.google.gwt.user.client.rpc.SerializationStreamReader;", + "import com.google.gwt.user.client.rpc.SerializationStreamWriter;", + "import java.util.List;", + "import " + generatedAnnotationType() + ";", + "", + "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")", + "public final class AutoValue_Baz_CustomFieldSerializer" + + " extends CustomFieldSerializer {", + "", + " public static AutoValue_Baz instantiate(", + " SerializationStreamReader streamReader) throws SerializationException {", + " @SuppressWarnings(\"unchecked\")", + " List buh = (List) streamReader.readObject();", + " return new AutoValue_Baz(buh);", + " }", + "", + " public static void serialize(", + " SerializationStreamWriter streamWriter,", + " AutoValue_Baz instance) throws SerializationException {", + " streamWriter.writeObject(instance.buh());", + " }", + "", + " public static void deserialize(", + " @SuppressWarnings(\"unused\") SerializationStreamReader streamReader,", + " @SuppressWarnings(\"unused\") AutoValue_Baz instance) {", + " }", + "", + " @SuppressWarnings(\"unused\") private int dummy_949e312e;", + "", + " @Override", + " public void deserializeInstance(", + " SerializationStreamReader streamReader,", + " AutoValue_Baz instance) {", + " deserialize(streamReader, instance);", + " }", + "", + " @Override", + " public boolean hasCustomInstantiateInstance() {", + " return true;", + " }", + "", + " @Override", + " public AutoValue_Baz instantiateInstance(", + " SerializationStreamReader streamReader) throws SerializationException {", + " return instantiate(streamReader);", + " }", + "", + " @Override", + " public void serializeInstance(", + " SerializationStreamWriter streamWriter,", + " AutoValue_Baz instance) throws SerializationException {", + " serialize(streamWriter, instance);", + " }", + "}"); Compilation compilation = javac().withProcessors(new AutoValueProcessor()).compile(javaFileObject, GWT_COMPATIBLE); assertThat(compilation) @@ -257,71 +261,71 @@ public void testBuildersAndGenerics() { " Baz build();", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "foo.bar.AutoValue_Baz_CustomFieldSerializer", - "package foo.bar;", - "", - "import com.google.gwt.user.client.rpc.CustomFieldSerializer;", - "import com.google.gwt.user.client.rpc.SerializationException;", - "import com.google.gwt.user.client.rpc.SerializationStreamReader;", - "import com.google.gwt.user.client.rpc.SerializationStreamWriter;", - "import java.util.Map;", - "import javax.annotation.Generated;", - "", - "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")", - "public final class AutoValue_Baz_CustomFieldSerializer" - + ", V extends K>" - + " extends CustomFieldSerializer> {", - "", - " public static , V extends K> AutoValue_Baz instantiate(", - " SerializationStreamReader streamReader) throws SerializationException {", - " @SuppressWarnings(\"unchecked\")", - " Map map = (Map) streamReader.readObject();", - " return (AutoValue_Baz) new AutoValue_Baz.Builder()", - " .map(map)", - " .build();", - " }", - "", - " public static , V extends K> void serialize(", - " SerializationStreamWriter streamWriter,", - " AutoValue_Baz instance) throws SerializationException {", - " streamWriter.writeObject(instance.map());", - " }", - "", - " public static , V extends K> void deserialize(", - " @SuppressWarnings(\"unused\") SerializationStreamReader streamReader,", - " @SuppressWarnings(\"unused\") AutoValue_Baz instance) {", - " }", - "", - " @SuppressWarnings(\"unused\")", - " private int dummy_bd425a02;", - "", - " @Override", - " public void deserializeInstance(", - " SerializationStreamReader streamReader,", - " AutoValue_Baz instance) {", - " deserialize(streamReader, instance);", - " }", - "", - " @Override", - " public boolean hasCustomInstantiateInstance() {", - " return true;", - " }", - "", - " @Override", - " public AutoValue_Baz instantiateInstance(", - " SerializationStreamReader streamReader) throws SerializationException {", - " return instantiate(streamReader);", - " }", - "", - " @Override", - " public void serializeInstance(", - " SerializationStreamWriter streamWriter,", - " AutoValue_Baz instance) throws SerializationException {", - " serialize(streamWriter, instance);", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "foo.bar.AutoValue_Baz_CustomFieldSerializer", + "package foo.bar;", + "", + "import com.google.gwt.user.client.rpc.CustomFieldSerializer;", + "import com.google.gwt.user.client.rpc.SerializationException;", + "import com.google.gwt.user.client.rpc.SerializationStreamReader;", + "import com.google.gwt.user.client.rpc.SerializationStreamWriter;", + "import java.util.Map;", + "import " + generatedAnnotationType() + ";", + "", + "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")", + "public final class AutoValue_Baz_CustomFieldSerializer" + + ", V extends K>" + + " extends CustomFieldSerializer> {", + "", + " public static , V extends K> AutoValue_Baz instantiate(", + " SerializationStreamReader streamReader) throws SerializationException {", + " @SuppressWarnings(\"unchecked\")", + " Map map = (Map) streamReader.readObject();", + " return (AutoValue_Baz) new AutoValue_Baz.Builder()", + " .map(map)", + " .build();", + " }", + "", + " public static , V extends K> void serialize(", + " SerializationStreamWriter streamWriter,", + " AutoValue_Baz instance) throws SerializationException {", + " streamWriter.writeObject(instance.map());", + " }", + "", + " public static , V extends K> void deserialize(", + " @SuppressWarnings(\"unused\") SerializationStreamReader streamReader,", + " @SuppressWarnings(\"unused\") AutoValue_Baz instance) {", + " }", + "", + " @SuppressWarnings(\"unused\")", + " private int dummy_bd425a02;", + "", + " @Override", + " public void deserializeInstance(", + " SerializationStreamReader streamReader,", + " AutoValue_Baz instance) {", + " deserialize(streamReader, instance);", + " }", + "", + " @Override", + " public boolean hasCustomInstantiateInstance() {", + " return true;", + " }", + "", + " @Override", + " public AutoValue_Baz instantiateInstance(", + " SerializationStreamReader streamReader) throws SerializationException {", + " return instantiate(streamReader);", + " }", + "", + " @Override", + " public void serializeInstance(", + " SerializationStreamWriter streamWriter,", + " AutoValue_Baz instance) throws SerializationException {", + " serialize(streamWriter, instance);", + " }", + "}"); Compilation compilation = javac().withProcessors(new AutoValueProcessor()).compile(javaFileObject, GWT_COMPATIBLE); assertThat(compilation) @@ -330,4 +334,15 @@ public void testBuildersAndGenerics() { .generatedSourceFile("foo.bar.AutoValue_Baz_CustomFieldSerializer") .hasSourceEquivalentTo(expectedOutput); } + + private String generatedAnnotationType() { + return isJavaxAnnotationProcessingGeneratedAvailable() + ? "javax.annotation.processing.Generated" + : "javax.annotation.Generated"; + } + + private boolean isJavaxAnnotationProcessingGeneratedAvailable() { + return compilationRule.getElements().getTypeElement("javax.annotation.processing.Generated") + != null; + } } diff --git a/value/src/main/java/com/google/auto/value/extension/memoized/MemoizeExtension.java b/value/src/main/java/com/google/auto/value/extension/memoized/MemoizeExtension.java index 41d96f632f..ddfa9694a2 100644 --- a/value/src/main/java/com/google/auto/value/extension/memoized/MemoizeExtension.java +++ b/value/src/main/java/com/google/auto/value/extension/memoized/MemoizeExtension.java @@ -15,6 +15,7 @@ */ package com.google.auto.value.extension.memoized; +import static com.google.auto.common.GeneratedAnnotationSpecs.generatedAnnotationSpec; import static com.google.auto.common.MoreElements.isAnnotationPresent; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.not; @@ -121,7 +122,7 @@ String generate() { .addTypeVariables(typeVariableNames()) .addModifiers(isFinal ? FINAL : ABSTRACT) .addMethod(constructor()); - generatedAnnotation().ifPresent(generated::addAnnotation); + generatedAnnotationSpec(elements, MemoizeExtension.class).ifPresent(generated::addAnnotation); for (ExecutableElement method : memoizedMethods(context)) { MethodOverrider methodOverrider = new MethodOverrider(method); generated.addFields(methodOverrider.fields()); @@ -133,19 +134,6 @@ String generate() { return JavaFile.builder(context.packageName(), generated.build()).build().toString(); } - private Optional generatedAnnotation() { - TypeElement generatedAnnotationElement = - elements.getTypeElement("javax.annotation.Generated"); - if (generatedAnnotationElement == null) { - return Optional.empty(); - } - ClassName generatedName = ClassName.get(generatedAnnotationElement); - return Optional.of( - AnnotationSpec.builder(generatedName) - .addMember("value", "$S", MemoizeExtension.class.getCanonicalName()) - .build()); - } - private TypeName superType() { ClassName superType = ClassName.get(context.packageName(), classToExtend); ImmutableList typeVariableNames = typeVariableNames(); diff --git a/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java b/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java index b18b3e290f..17aa3189bb 100644 --- a/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java +++ b/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java @@ -15,6 +15,8 @@ */ package com.google.auto.value.processor; +import static com.google.auto.common.GeneratedAnnotations.generatedAnnotation; + import com.google.auto.common.MoreElements; import com.google.auto.common.SuperficialValidation; import com.google.auto.service.AutoService; @@ -177,12 +179,9 @@ private void processMethod(ExecutableElement method) { } private String getGeneratedTypeName() { - TypeElement generatedTypeElement = - processingEnv.getElementUtils().getTypeElement("javax.annotation.Generated"); - if (generatedTypeElement == null) { - return ""; - } - return TypeEncoder.encode(generatedTypeElement.asType()); + return generatedAnnotation(processingEnv.getElementUtils()) + .map(generatedAnnotation -> TypeEncoder.encode(generatedAnnotation.asType())) + .orElse(null); } /** diff --git a/value/src/main/java/com/google/auto/value/processor/AutoValueProcessor.java b/value/src/main/java/com/google/auto/value/processor/AutoValueProcessor.java index e11188e24d..16d5af46ab 100644 --- a/value/src/main/java/com/google/auto/value/processor/AutoValueProcessor.java +++ b/value/src/main/java/com/google/auto/value/processor/AutoValueProcessor.java @@ -16,6 +16,7 @@ package com.google.auto.value.processor; import static com.google.auto.common.AnnotationMirrors.getAnnotationValue; +import static com.google.auto.common.GeneratedAnnotations.generatedAnnotation; import static com.google.auto.common.MoreElements.getAnnotationMirror; import static com.google.auto.common.MoreElements.getLocalAndInheritedMethods; import static com.google.auto.common.MoreElements.getPackage; @@ -819,14 +820,13 @@ private void defineVarsForType( ImmutableSet toBuilderMethods, ImmutableSet propertyMethods, Optional builder) { - TypeElement generatedTypeElement = - processingEnv.getElementUtils().getTypeElement("javax.annotation.Generated"); // We can't use ImmutableList.toImmutableList() for obscure Google-internal reasons. vars.toBuilderMethods = ImmutableList.copyOf(toBuilderMethods.stream().map(SimpleMethod::new).collect(toList())); - vars.generated = generatedTypeElement == null - ? "" - : TypeEncoder.encode(generatedTypeElement.asType()); + vars.generated = + generatedAnnotation(processingEnv.getElementUtils()) + .map(annotation -> TypeEncoder.encode(annotation.asType())) + .orElse(""); ImmutableBiMap methodToPropertyName = propertyNameToMethodMap(propertyMethods).inverse(); vars.props = propertySet(type, propertyMethods); diff --git a/value/src/test/java/com/google/auto/value/processor/AutoAnnotationCompilationTest.java b/value/src/test/java/com/google/auto/value/processor/AutoAnnotationCompilationTest.java index db55c05cde..e155a3c1a0 100644 --- a/value/src/test/java/com/google/auto/value/processor/AutoAnnotationCompilationTest.java +++ b/value/src/test/java/com/google/auto/value/processor/AutoAnnotationCompilationTest.java @@ -33,6 +33,7 @@ import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.ToolProvider; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -42,6 +43,9 @@ */ @RunWith(JUnit4.class) public class AutoAnnotationCompilationTest { + + @Rule public final GeneratedImportRule generatedImportRule = new GeneratedImportRule(); + @Test public void testSimple() { JavaFileObject myAnnotationJavaFile = JavaFileObjects.forSourceLines( @@ -78,64 +82,64 @@ public void testSimple() { " return new AutoAnnotation_AnnotationFactory_newMyAnnotation(value);", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "com.example.factories.AutoAnnotation_AnnotationFactory_newMyAnnotation", - "package com.example.factories;", - "", - "import com.example.annotations.MyAnnotation;", - "import com.example.enums.MyEnum;", - "import javax.annotation.Generated;", - "", - "@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")", - "final class AutoAnnotation_AnnotationFactory_newMyAnnotation implements MyAnnotation {", - " private final MyEnum value;", - " private static final int defaultedValue = 23;", - "", - " AutoAnnotation_AnnotationFactory_newMyAnnotation(MyEnum value) {", - " if (value == null) {", - " throw new NullPointerException(\"Null value\");", - " }", - " this.value = value;", - " }", - "", - " @Override public Class annotationType() {", - " return MyAnnotation.class;", - " }", - "", - " @Override public MyEnum value() {", - " return value;", - " }", - "", - " @Override public int defaultedValue() {", - " return defaultedValue;", - " }", - "", - " @Override public String toString() {", - " StringBuilder sb = new StringBuilder(\"@com.example.annotations.MyAnnotation(\");", - " sb.append(value);", - " return sb.append(')').toString();", - " }", - "", - " @Override public boolean equals(Object o) {", - " if (o == this) {", - " return true;", - " }", - " if (o instanceof MyAnnotation) {", - " MyAnnotation that = (MyAnnotation) o;", - " return (value.equals(that.value()))", - " && (defaultedValue == that.defaultedValue());", - " }", - " return false;", - " }", - "", - " @Override public int hashCode() {", - " return ", - " " + invariableHash, - " + (" + 127 * "value".hashCode() + " ^ (value.hashCode()))", - " ;", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "com.example.factories.AutoAnnotation_AnnotationFactory_newMyAnnotation", + "package com.example.factories;", + "", + "import com.example.annotations.MyAnnotation;", + "import com.example.enums.MyEnum;", + generatedImportRule.importGeneratedAnnotationType(), + "", + "@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")", + "final class AutoAnnotation_AnnotationFactory_newMyAnnotation implements MyAnnotation {", + " private final MyEnum value;", + " private static final int defaultedValue = 23;", + "", + " AutoAnnotation_AnnotationFactory_newMyAnnotation(MyEnum value) {", + " if (value == null) {", + " throw new NullPointerException(\"Null value\");", + " }", + " this.value = value;", + " }", + "", + " @Override public Class annotationType() {", + " return MyAnnotation.class;", + " }", + "", + " @Override public MyEnum value() {", + " return value;", + " }", + "", + " @Override public int defaultedValue() {", + " return defaultedValue;", + " }", + "", + " @Override public String toString() {", + " StringBuilder sb = new StringBuilder(\"@com.example.annotations.MyAnnotation(\");", + " sb.append(value);", + " return sb.append(')').toString();", + " }", + "", + " @Override public boolean equals(Object o) {", + " if (o == this) {", + " return true;", + " }", + " if (o instanceof MyAnnotation) {", + " MyAnnotation that = (MyAnnotation) o;", + " return (value.equals(that.value()))", + " && (defaultedValue == that.defaultedValue());", + " }", + " return false;", + " }", + "", + " @Override public int hashCode() {", + " return ", + " " + invariableHash, + " + (" + 127 * "value".hashCode() + " ^ (value.hashCode()))", + " ;", + " }", + "}"); assert_().about(javaSources()) .that(ImmutableList.of(annotationFactoryJavaFile, myAnnotationJavaFile, myEnumJavaFile)) .processedWith(new AutoAnnotationProcessor()) @@ -159,39 +163,39 @@ public void testEmptyPackage() { " return new AutoAnnotation_AnnotationFactory_newMyAnnotation();", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "AutoAnnotation_AnnotationFactory_newMyAnnotation", - "import javax.annotation.Generated;", - "", - "@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")", - "final class AutoAnnotation_AnnotationFactory_newMyAnnotation implements MyAnnotation {", - " AutoAnnotation_AnnotationFactory_newMyAnnotation() {", - " }", - "", - " @Override public Class annotationType() {", - " return MyAnnotation.class;", - " }", - "", - " @Override public String toString() {", - " StringBuilder sb = new StringBuilder(\"@MyAnnotation(\");", - " return sb.append(')').toString();", - " }", - "", - " @Override public boolean equals(Object o) {", - " if (o == this) {", - " return true;", - " }", - " if (o instanceof MyAnnotation) {", - " return true;", - " }", - " return false;", - " }", - "", - " @Override public int hashCode() {", - " return 0;", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "AutoAnnotation_AnnotationFactory_newMyAnnotation", + generatedImportRule.importGeneratedAnnotationType(), + "", + "@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")", + "final class AutoAnnotation_AnnotationFactory_newMyAnnotation implements MyAnnotation {", + " AutoAnnotation_AnnotationFactory_newMyAnnotation() {", + " }", + "", + " @Override public Class annotationType() {", + " return MyAnnotation.class;", + " }", + "", + " @Override public String toString() {", + " StringBuilder sb = new StringBuilder(\"@MyAnnotation(\");", + " return sb.append(')').toString();", + " }", + "", + " @Override public boolean equals(Object o) {", + " if (o == this) {", + " return true;", + " }", + " if (o instanceof MyAnnotation) {", + " return true;", + " }", + " return false;", + " }", + "", + " @Override public int hashCode() {", + " return 0;", + " }", + "}"); assertAbout(javaSources()) .that(ImmutableList.of(annotationFactoryJavaFile, myAnnotationJavaFile)) .processedWith(new AutoAnnotationProcessor()) @@ -231,59 +235,59 @@ public void testGwtSimple() { " return new AutoAnnotation_AnnotationFactory_newMyAnnotation(value);", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "com.example.factories.AutoAnnotation_AnnotationFactory_newMyAnnotation", - "package com.example.factories;", - "", - "import com.example.annotations.MyAnnotation;", - "import java.util.Arrays;", - "import javax.annotation.Generated;", - "", - "@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")", - "final class AutoAnnotation_AnnotationFactory_newMyAnnotation implements MyAnnotation {", - " private final int[] value;", - "", - " AutoAnnotation_AnnotationFactory_newMyAnnotation(int[] value) {", - " if (value == null) {", - " throw new NullPointerException(\"Null value\");", - " }", - " this.value = Arrays.copyOf(value, value.length);", - " }", - "", - " @Override public Class annotationType() {", - " return MyAnnotation.class;", - " }", - "", - " @Override public int[] value() {", - " return Arrays.copyOf(value, value.length);", - " }", - "", - " @Override public String toString() {", - " StringBuilder sb = new StringBuilder(\"@com.example.annotations.MyAnnotation(\");", - " sb.append(Arrays.toString(value));", - " return sb.append(')').toString();", - " }", - "", - " @Override public boolean equals(Object o) {", - " if (o == this) {", - " return true;", - " }", - " if (o instanceof MyAnnotation) {", - " MyAnnotation that = (MyAnnotation) o;", - " return (Arrays.equals(value,", - " (that instanceof AutoAnnotation_AnnotationFactory_newMyAnnotation)", - " ? ((AutoAnnotation_AnnotationFactory_newMyAnnotation) that).value", - " : that.value()));", - " }", - " return false;", - " }", - "", - " @Override public int hashCode() {", - " return ", - " + (" + 127 * "value".hashCode() + " ^ (Arrays.hashCode(value)));", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "com.example.factories.AutoAnnotation_AnnotationFactory_newMyAnnotation", + "package com.example.factories;", + "", + "import com.example.annotations.MyAnnotation;", + "import java.util.Arrays;", + generatedImportRule.importGeneratedAnnotationType(), + "", + "@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")", + "final class AutoAnnotation_AnnotationFactory_newMyAnnotation implements MyAnnotation {", + " private final int[] value;", + "", + " AutoAnnotation_AnnotationFactory_newMyAnnotation(int[] value) {", + " if (value == null) {", + " throw new NullPointerException(\"Null value\");", + " }", + " this.value = Arrays.copyOf(value, value.length);", + " }", + "", + " @Override public Class annotationType() {", + " return MyAnnotation.class;", + " }", + "", + " @Override public int[] value() {", + " return Arrays.copyOf(value, value.length);", + " }", + "", + " @Override public String toString() {", + " StringBuilder sb = new StringBuilder(\"@com.example.annotations.MyAnnotation(\");", + " sb.append(Arrays.toString(value));", + " return sb.append(')').toString();", + " }", + "", + " @Override public boolean equals(Object o) {", + " if (o == this) {", + " return true;", + " }", + " if (o instanceof MyAnnotation) {", + " MyAnnotation that = (MyAnnotation) o;", + " return (Arrays.equals(value,", + " (that instanceof AutoAnnotation_AnnotationFactory_newMyAnnotation)", + " ? ((AutoAnnotation_AnnotationFactory_newMyAnnotation) that).value", + " : that.value()));", + " }", + " return false;", + " }", + "", + " @Override public int hashCode() {", + " return ", + " + (" + 127 * "value".hashCode() + " ^ (Arrays.hashCode(value)));", + " }", + "}"); assert_().about(javaSources()) .that(ImmutableList.of( annotationFactoryJavaFile, myAnnotationJavaFile, gwtCompatibleJavaFile)) @@ -331,92 +335,92 @@ public void testCollectionsForArrays() { " return new AutoAnnotation_AnnotationFactory_newMyAnnotation(value, enums);", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "com.example.factories.AutoAnnotation_AnnotationFactory_newMyAnnotation", - "package com.example.factories;", - "", - "import com.example.annotations.MyAnnotation;", - "import com.example.enums.MyEnum;", - "import java.util.Arrays;", - "import java.util.Collection;", - "import java.util.List;", - "import java.util.Set;", - "import javax.annotation.Generated", - "", - "@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")", - "final class AutoAnnotation_AnnotationFactory_newMyAnnotation implements MyAnnotation {", - " private final int[] value;", - " private final MyEnum[] enums;", - "", - " AutoAnnotation_AnnotationFactory_newMyAnnotation(", - " List value,", - " Set enums) {", - " if (value == null) {", - " throw new NullPointerException(\"Null value\");", - " }", - " this.value = intArrayFromCollection(value);", - " if (enums == null) {", - " throw new NullPointerException(\"Null enums\");", - " }", - " this.enums = enums.toArray(new MyEnum[0];", - " }", - "", - " @Override public Class annotationType() {", - " return MyAnnotation.class;", - " }", - "", - " @Override public int[] value() {", - " return value.clone();", - " }", - "", - " @Override public MyEnum[] enums() {", - " return enums.clone();", - " }", - "", - " @Override public String toString() {", - " StringBuilder sb = new StringBuilder(\"@com.example.annotations.MyAnnotation(\");", - " sb.append(\"value=\");", - " sb.append(Arrays.toString(value));", - " sb.append(\", \");", - " sb.append(\"enums=\");", - " sb.append(Arrays.toString(enums));", - " return sb.append(')').toString();", - " }", - "", - " @Override public boolean equals(Object o) {", - " if (o == this) {", - " return true;", - " }", - " if (o instanceof MyAnnotation) {", - " MyAnnotation that = (MyAnnotation) o;", - " return (Arrays.equals(value,", - " (that instanceof AutoAnnotation_AnnotationFactory_newMyAnnotation)", - " ? ((AutoAnnotation_AnnotationFactory_newMyAnnotation) that).value", - " : that.value()))", - " && (Arrays.equals(enums,", - " (that instanceof AutoAnnotation_AnnotationFactory_newMyAnnotation)", - " ? ((AutoAnnotation_AnnotationFactory_newMyAnnotation) that).enums", - " : that.enums()))", - " }", - " return false;", - " }", - "", - " @Override public int hashCode() {", - " return ", - " + (" + 127 * "value".hashCode() + " ^ (Arrays.hashCode(value)))", - " + (" + 127 * "enums".hashCode() + " ^ (Arrays.hashCode(enums)));", - " }", - "", - " private static int[] intArrayFromCollection(Collection c) {", - " int[] a = new int[c.size()];", - " int i = 0;", - " for (int x : c) {", - " a[i++] = x;", - " }", - " return a;", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "com.example.factories.AutoAnnotation_AnnotationFactory_newMyAnnotation", + "package com.example.factories;", + "", + "import com.example.annotations.MyAnnotation;", + "import com.example.enums.MyEnum;", + "import java.util.Arrays;", + "import java.util.Collection;", + "import java.util.List;", + "import java.util.Set;", + generatedImportRule.importGeneratedAnnotationType(), + "", + "@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")", + "final class AutoAnnotation_AnnotationFactory_newMyAnnotation implements MyAnnotation {", + " private final int[] value;", + " private final MyEnum[] enums;", + "", + " AutoAnnotation_AnnotationFactory_newMyAnnotation(", + " List value,", + " Set enums) {", + " if (value == null) {", + " throw new NullPointerException(\"Null value\");", + " }", + " this.value = intArrayFromCollection(value);", + " if (enums == null) {", + " throw new NullPointerException(\"Null enums\");", + " }", + " this.enums = enums.toArray(new MyEnum[0];", + " }", + "", + " @Override public Class annotationType() {", + " return MyAnnotation.class;", + " }", + "", + " @Override public int[] value() {", + " return value.clone();", + " }", + "", + " @Override public MyEnum[] enums() {", + " return enums.clone();", + " }", + "", + " @Override public String toString() {", + " StringBuilder sb = new StringBuilder(\"@com.example.annotations.MyAnnotation(\");", + " sb.append(\"value=\");", + " sb.append(Arrays.toString(value));", + " sb.append(\", \");", + " sb.append(\"enums=\");", + " sb.append(Arrays.toString(enums));", + " return sb.append(')').toString();", + " }", + "", + " @Override public boolean equals(Object o) {", + " if (o == this) {", + " return true;", + " }", + " if (o instanceof MyAnnotation) {", + " MyAnnotation that = (MyAnnotation) o;", + " return (Arrays.equals(value,", + " (that instanceof AutoAnnotation_AnnotationFactory_newMyAnnotation)", + " ? ((AutoAnnotation_AnnotationFactory_newMyAnnotation) that).value", + " : that.value()))", + " && (Arrays.equals(enums,", + " (that instanceof AutoAnnotation_AnnotationFactory_newMyAnnotation)", + " ? ((AutoAnnotation_AnnotationFactory_newMyAnnotation) that).enums", + " : that.enums()))", + " }", + " return false;", + " }", + "", + " @Override public int hashCode() {", + " return ", + " + (" + 127 * "value".hashCode() + " ^ (Arrays.hashCode(value)))", + " + (" + 127 * "enums".hashCode() + " ^ (Arrays.hashCode(enums)));", + " }", + "", + " private static int[] intArrayFromCollection(Collection c) {", + " int[] a = new int[c.size()];", + " int i = 0;", + " for (int x : c) {", + " a[i++] = x;", + " }", + " return a;", + " }", + "}"); assert_().about(javaSources()) .that(ImmutableList.of(annotationFactoryJavaFile, myEnumJavaFile, myAnnotationJavaFile)) .processedWith(new AutoAnnotationProcessor()) diff --git a/value/src/test/java/com/google/auto/value/processor/CompilationTest.java b/value/src/test/java/com/google/auto/value/processor/CompilationTest.java index aa09fcb62b..b8aec8c3d0 100644 --- a/value/src/test/java/com/google/auto/value/processor/CompilationTest.java +++ b/value/src/test/java/com/google/auto/value/processor/CompilationTest.java @@ -20,6 +20,7 @@ import static com.google.testing.compile.CompilationSubject.compilations; import static com.google.testing.compile.Compiler.javac; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; +import static java.util.stream.Collectors.joining; import com.google.common.collect.ImmutableSet; import com.google.common.truth.Expect; @@ -30,6 +31,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Set; +import java.util.stream.Stream; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; @@ -48,6 +50,7 @@ @RunWith(JUnit4.class) public class CompilationTest { @Rule public final Expect expect = Expect.create(); + @Rule public final GeneratedImportRule generatedImportRule = new GeneratedImportRule(); @Test public void simpleSuccess() { @@ -69,49 +72,49 @@ public void simpleSuccess() { " return new AutoValue_Baz(buh);", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "foo.bar.AutoValue_Baz", - "package foo.bar;", - "", - "import javax.annotation.Generated;", - "", - "@Generated(\"" + AutoValueProcessor.class.getName() + "\")", - "final class AutoValue_Baz extends Baz {", - " private final long buh;", - "", - " AutoValue_Baz(long buh) {", - " this.buh = buh;", - " }", - "", - " @Override public long buh() {", - " return buh;", - " }", - "", - " @Override public String toString() {", - " return \"Baz{\"", - " + \"buh=\" + buh", - " + \"}\";", - " }", - "", - " @Override public boolean equals(Object o) {", - " if (o == this) {", - " return true;", - " }", - " if (o instanceof Baz) {", - " Baz that = (Baz) o;", - " return (this.buh == that.buh());", - " }", - " return false;", - " }", - "", - " @Override public int hashCode() {", - " int h = 1;", - " h *= 1000003;", - " h ^= (int) ((this.buh >>> 32) ^ this.buh);", - " return h;", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "foo.bar.AutoValue_Baz", + "package foo.bar;", + "", + generatedImportRule.importGeneratedAnnotationType(), + "", + "@Generated(\"" + AutoValueProcessor.class.getName() + "\")", + "final class AutoValue_Baz extends Baz {", + " private final long buh;", + "", + " AutoValue_Baz(long buh) {", + " this.buh = buh;", + " }", + "", + " @Override public long buh() {", + " return buh;", + " }", + "", + " @Override public String toString() {", + " return \"Baz{\"", + " + \"buh=\" + buh", + " + \"}\";", + " }", + "", + " @Override public boolean equals(Object o) {", + " if (o == this) {", + " return true;", + " }", + " if (o instanceof Baz) {", + " Baz that = (Baz) o;", + " return (this.buh == that.buh());", + " }", + " return false;", + " }", + "", + " @Override public int hashCode() {", + " int h = 1;", + " h *= 1000003;", + " h ^= (int) ((this.buh >>> 32) ^ this.buh);", + " return h;", + " }", + "}"); Compilation compilation = javac().withProcessors(new AutoValueProcessor()).compile(javaFileObject); assertThat(compilation) @@ -147,68 +150,68 @@ public void importTwoWays() { " return new AutoValue_Baz(ints, arrays);", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "foo.bar.AutoValue_Baz", - "package foo.bar;", - "", - "import java.util.Arrays;", - "import javax.annotation.Generated;", - "", - "@Generated(\"" + AutoValueProcessor.class.getName() + "\")", - "final class AutoValue_Baz extends Baz {", - " private final int[] ints;", - " private final Arrays arrays;", - "", - " AutoValue_Baz(int[] ints, Arrays arrays) {", - " if (ints == null) {", - " throw new NullPointerException(\"Null ints\");", - " }", - " this.ints = ints;", - " if (arrays == null) {", - " throw new NullPointerException(\"Null arrays\");", - " }", - " this.arrays = arrays;", - " }", - "", - " @SuppressWarnings(value = {\"mutable\"})", - " @Override public int[] ints() {", - " return ints;", - " }", - "", - " @Override public Arrays arrays() {", - " return arrays;", - " }", - "", - " @Override public String toString() {", - " return \"Baz{\"", - " + \"ints=\" + Arrays.toString(ints) + \", \"", - " + \"arrays=\" + arrays", - " + \"}\";", - " }", - "", - " @Override public boolean equals(Object o) {", - " if (o == this) {", - " return true;", - " }", - " if (o instanceof Baz) {", - " Baz that = (Baz) o;", - " return (Arrays.equals(this.ints, (that instanceof AutoValue_Baz) " - + "? ((AutoValue_Baz) that).ints : that.ints()))", - " && (this.arrays.equals(that.arrays()));", - " }", - " return false;", - " }", - "", - " @Override public int hashCode() {", - " int h = 1;", - " h *= 1000003;", - " h ^= Arrays.hashCode(this.ints);", - " h *= 1000003;", - " h ^= this.arrays.hashCode();", - " return h;", - " }", - "}" - ); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "foo.bar.AutoValue_Baz", + "package foo.bar;", + "", + "import java.util.Arrays;", + generatedImportRule.importGeneratedAnnotationType(), + "", + "@Generated(\"" + AutoValueProcessor.class.getName() + "\")", + "final class AutoValue_Baz extends Baz {", + " private final int[] ints;", + " private final Arrays arrays;", + "", + " AutoValue_Baz(int[] ints, Arrays arrays) {", + " if (ints == null) {", + " throw new NullPointerException(\"Null ints\");", + " }", + " this.ints = ints;", + " if (arrays == null) {", + " throw new NullPointerException(\"Null arrays\");", + " }", + " this.arrays = arrays;", + " }", + "", + " @SuppressWarnings(value = {\"mutable\"})", + " @Override public int[] ints() {", + " return ints;", + " }", + "", + " @Override public Arrays arrays() {", + " return arrays;", + " }", + "", + " @Override public String toString() {", + " return \"Baz{\"", + " + \"ints=\" + Arrays.toString(ints) + \", \"", + " + \"arrays=\" + arrays", + " + \"}\";", + " }", + "", + " @Override public boolean equals(Object o) {", + " if (o == this) {", + " return true;", + " }", + " if (o instanceof Baz) {", + " Baz that = (Baz) o;", + " return (Arrays.equals(this.ints, (that instanceof AutoValue_Baz) " + + "? ((AutoValue_Baz) that).ints : that.ints()))", + " && (this.arrays.equals(that.arrays()));", + " }", + " return false;", + " }", + "", + " @Override public int hashCode() {", + " int h = 1;", + " h *= 1000003;", + " h ^= Arrays.hashCode(this.ints);", + " h *= 1000003;", + " h ^= this.arrays.hashCode();", + " return h;", + " }", + "}"); Compilation compilation = javac().withProcessors(new AutoValueProcessor()).compile(javaFileObject); assertThat(compilation) @@ -794,308 +797,310 @@ public void correctBuilder() throws Exception { " return AutoValue_NestedAutoValue.builder();", " }", "}"); - JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( - "foo.bar.AutoValue_Baz", - "package foo.bar;", - "", - "import com.google.common.base.Optional;", - "import com.google.common.collect.ImmutableList;", - "import java.util.Arrays;", - "import java.util.List;", - "import javax.annotation.Generated;", - "import javax.annotation.Nullable;", - "", - "@Generated(\"" + AutoValueProcessor.class.getName() + "\")", - "final class AutoValue_Baz extends Baz {", - " private final int anInt;", - " private final byte[] aByteArray;", - " private final int[] aNullableIntArray;", - " private final List aList;", - " private final ImmutableList anImmutableList;", - " private final Optional anOptionalString;", - " private final NestedAutoValue aNestedAutoValue;", - "", - " private AutoValue_Baz(", - " int anInt,", - " byte[] aByteArray,", - " @Nullable int[] aNullableIntArray,", - " List aList,", - " ImmutableList anImmutableList,", - " Optional anOptionalString,", - " NestedAutoValue aNestedAutoValue) {", - " this.anInt = anInt;", - " this.aByteArray = aByteArray;", - " this.aNullableIntArray = aNullableIntArray;", - " this.aList = aList;", - " this.anImmutableList = anImmutableList;", - " this.anOptionalString = anOptionalString;", - " this.aNestedAutoValue = aNestedAutoValue;", - " }", - "", - " @Override public int anInt() {", - " return anInt;", - " }", - "", - " @SuppressWarnings(value = {\"mutable\"})", - " @Override public byte[] aByteArray() {", - " return aByteArray;", - " }", - "", - " @SuppressWarnings(value = {\"mutable\"})", - " @Nullable", - " @Override public int[] aNullableIntArray() {", - " return aNullableIntArray;", - " }", - "", - " @Override public List aList() {", - " return aList;", - " }", - "", - " @Override public ImmutableList anImmutableList() {", - " return anImmutableList;", - " }", - "", - " @Override public Optional anOptionalString() {", - " return anOptionalString;", - " }", - "", - " @Override public NestedAutoValue aNestedAutoValue() {", - " return aNestedAutoValue;", - " }", - "", - " @Override public String toString() {", - " return \"Baz{\"", - " + \"anInt=\" + anInt + \", \"", - " + \"aByteArray=\" + Arrays.toString(aByteArray) + \", \"", - " + \"aNullableIntArray=\" + Arrays.toString(aNullableIntArray) + \", \"", - " + \"aList=\" + aList + \", \"", - " + \"anImmutableList=\" + anImmutableList + \", \"", - " + \"anOptionalString=\" + anOptionalString + \", \"", - " + \"aNestedAutoValue=\" + aNestedAutoValue", - " + \"}\";", - " }", - "", - " @Override public boolean equals(Object o) {", - " if (o == this) {", - " return true;", - " }", - " if (o instanceof Baz) {", - " Baz that = (Baz) o;", - " return (this.anInt == that.anInt())", - " && (Arrays.equals(this.aByteArray, " - + "(that instanceof AutoValue_Baz) " - + "? ((AutoValue_Baz) that).aByteArray : that.aByteArray()))", - " && (Arrays.equals(this.aNullableIntArray, " - + "(that instanceof AutoValue_Baz) " - + "? ((AutoValue_Baz) that).aNullableIntArray : that.aNullableIntArray()))", - " && (this.aList.equals(that.aList()))", - " && (this.anImmutableList.equals(that.anImmutableList()))", - " && (this.anOptionalString.equals(that.anOptionalString()))", - " && (this.aNestedAutoValue.equals(that.aNestedAutoValue()));", - " }", - " return false;", - " }", - "", - " @Override public int hashCode() {", - " int h = 1;", - " h *= 1000003;", - " h ^= this.anInt;", - " h *= 1000003;", - " h ^= Arrays.hashCode(this.aByteArray);", - " h *= 1000003;", - " h ^= Arrays.hashCode(this.aNullableIntArray);", - " h *= 1000003;", - " h ^= this.aList.hashCode();", - " h *= 1000003;", - " h ^= this.anImmutableList.hashCode();", - " h *= 1000003;", - " h ^= this.anOptionalString.hashCode();", - " h *= 1000003;", - " h ^= this.aNestedAutoValue.hashCode();", - " return h;", - " }", - "", - " @Override public Baz.Builder toBuilder() {", - " return new Builder(this);", - " }", - "", - " static final class Builder extends Baz.Builder {", - " private Integer anInt;", - " private byte[] aByteArray;", - " private int[] aNullableIntArray;", - " private List aList;", - " private ImmutableList.Builder anImmutableListBuilder$;", - " private ImmutableList anImmutableList;", - " private Optional anOptionalString = Optional.absent();", - " private NestedAutoValue.Builder aNestedAutoValueBuilder$;", - " private NestedAutoValue aNestedAutoValue;", - "", - " Builder() {", - " }", - "", - " private Builder(Baz source) {", - " this.anInt = source.anInt();", - " this.aByteArray = source.aByteArray();", - " this.aNullableIntArray = source.aNullableIntArray();", - " this.aList = source.aList();", - " this.anImmutableList = source.anImmutableList();", - " this.anOptionalString = source.anOptionalString();", - " this.aNestedAutoValue = source.aNestedAutoValue();", - " }", - "", - " @Override", - " public Baz.Builder anInt(int anInt) {", - " this.anInt = anInt;", - " return this;", - " }", - "", - " @Override", - " public Optional anInt() {", - " if (anInt == null) {", - " return Optional.absent();", - " } else {", - " return Optional.of(anInt);", - " }", - " }", - "", - " @Override", - " public Baz.Builder aByteArray(byte[] aByteArray) {", - " if (aByteArray == null) {", - " throw new NullPointerException(\"Null aByteArray\");", - " }", - " this.aByteArray = aByteArray;", - " return this;", - " }", - "", - " @Override", - " public Baz.Builder aNullableIntArray(@Nullable int[] aNullableIntArray) {", - " this.aNullableIntArray = aNullableIntArray;", - " return this;", - " }", - "", - " @Override", - " public Baz.Builder aList(List aList) {", - " if (aList == null) {", - " throw new NullPointerException(\"Null aList\");", - " }", - " this.aList = aList;", - " return this;", - " }", - "", - " @Override", - " public List aList() {", - " if (aList == null) {", - " throw new IllegalStateException(\"Property \\\"aList\\\" has not been set\");", - " }", - " return aList;", - " }", - "", - " @Override", - " public Baz.Builder anImmutableList(List anImmutableList) {", - " if (anImmutableList == null) {", - " throw new NullPointerException(\"Null anImmutableList\");", - " }", - " if (anImmutableListBuilder$ != null) {", - " throw new IllegalStateException(" - + "\"Cannot set anImmutableList after calling anImmutableListBuilder()\");", - " }", - " this.anImmutableList = ImmutableList.copyOf(anImmutableList);", - " return this;", - " }", - "", - " @Override", - " public ImmutableList.Builder anImmutableListBuilder() {", - " if (anImmutableListBuilder$ == null) {", - " if (anImmutableList == null) {", - " anImmutableListBuilder$ = ImmutableList.builder();", - " } else {", - " anImmutableListBuilder$ = ImmutableList.builder();", - " anImmutableListBuilder$.addAll(anImmutableList);", - " anImmutableList = null;", - " }", - " }", - " return anImmutableListBuilder$;", - " }", - "", - " @Override", - " public ImmutableList anImmutableList() {", - " if (anImmutableListBuilder$ != null) {", - " return anImmutableListBuilder$.build();", - " }", - " if (anImmutableList == null) {", - " anImmutableList = ImmutableList.of();", - " }", - " return anImmutableList;", - " }", - "", - " @Override", - " public Baz.Builder anOptionalString(Optional anOptionalString) {", - " if (anOptionalString == null) {", - " throw new NullPointerException(\"Null anOptionalString\");", - " }", - " this.anOptionalString = anOptionalString;", - " return this;", - " }", - "", - " @Override", - " public Baz.Builder anOptionalString(String anOptionalString) {", - " if (anOptionalString == null) {", - " throw new NullPointerException(\"Null anOptionalString\");", - " }", - " this.anOptionalString = Optional.of(anOptionalString);", - " return this;", - " }", - "", - " @Override", - " public NestedAutoValue.Builder aNestedAutoValueBuilder() {", - " if (aNestedAutoValueBuilder$ == null) {", - " if (aNestedAutoValue == null) {", - " aNestedAutoValueBuilder$ = NestedAutoValue.builder();", - " } else {", - " aNestedAutoValueBuilder$ = aNestedAutoValue.toBuilder();", - " aNestedAutoValue = null;", - " }", - " }", - " return aNestedAutoValueBuilder$;", - " }", - "", - " @Override", - " public Baz build() {", - " if (anImmutableListBuilder$ != null) {", - " this.anImmutableList = anImmutableListBuilder$.build();", - " } else if (this.anImmutableList == null) {", - " this.anImmutableList = ImmutableList.of();", - " }", - " if (aNestedAutoValueBuilder$ != null) {", - " this.aNestedAutoValue = aNestedAutoValueBuilder$.build();", - " } else if (this.aNestedAutoValue == null) {", - " NestedAutoValue.Builder aNestedAutoValue$builder = NestedAutoValue.builder();", - " this.aNestedAutoValue = aNestedAutoValue$builder.build();", - " }", - " String missing = \"\";", - " if (this.anInt == null) {", - " missing += \" anInt\";", - " }", - " if (this.aByteArray == null) {", - " missing += \" aByteArray\";", - " }", - " if (this.aList == null) {", - " missing += \" aList\";", - " }", - " if (!missing.isEmpty()) {", - " throw new IllegalStateException(\"Missing required properties:\" + missing);", - " }", - " return new AutoValue_Baz(", - " this.anInt,", - " this.aByteArray,", - " this.aNullableIntArray,", - " this.aList,", - " this.anImmutableList,", - " this.anOptionalString,", - " this.aNestedAutoValue);", - " }", - " }", - "}"); + JavaFileObject expectedOutput = + JavaFileObjects.forSourceLines( + "foo.bar.AutoValue_Baz", + "package foo.bar;", + "", + "import com.google.common.base.Optional;", + "import com.google.common.collect.ImmutableList;", + "import java.util.Arrays;", + "import java.util.List;", + sorted( + generatedImportRule.importGeneratedAnnotationType(), + "import javax.annotation.Nullable;"), + "", + "@Generated(\"" + AutoValueProcessor.class.getName() + "\")", + "final class AutoValue_Baz extends Baz {", + " private final int anInt;", + " private final byte[] aByteArray;", + " private final int[] aNullableIntArray;", + " private final List aList;", + " private final ImmutableList anImmutableList;", + " private final Optional anOptionalString;", + " private final NestedAutoValue aNestedAutoValue;", + "", + " private AutoValue_Baz(", + " int anInt,", + " byte[] aByteArray,", + " @Nullable int[] aNullableIntArray,", + " List aList,", + " ImmutableList anImmutableList,", + " Optional anOptionalString,", + " NestedAutoValue aNestedAutoValue) {", + " this.anInt = anInt;", + " this.aByteArray = aByteArray;", + " this.aNullableIntArray = aNullableIntArray;", + " this.aList = aList;", + " this.anImmutableList = anImmutableList;", + " this.anOptionalString = anOptionalString;", + " this.aNestedAutoValue = aNestedAutoValue;", + " }", + "", + " @Override public int anInt() {", + " return anInt;", + " }", + "", + " @SuppressWarnings(value = {\"mutable\"})", + " @Override public byte[] aByteArray() {", + " return aByteArray;", + " }", + "", + " @SuppressWarnings(value = {\"mutable\"})", + " @Nullable", + " @Override public int[] aNullableIntArray() {", + " return aNullableIntArray;", + " }", + "", + " @Override public List aList() {", + " return aList;", + " }", + "", + " @Override public ImmutableList anImmutableList() {", + " return anImmutableList;", + " }", + "", + " @Override public Optional anOptionalString() {", + " return anOptionalString;", + " }", + "", + " @Override public NestedAutoValue aNestedAutoValue() {", + " return aNestedAutoValue;", + " }", + "", + " @Override public String toString() {", + " return \"Baz{\"", + " + \"anInt=\" + anInt + \", \"", + " + \"aByteArray=\" + Arrays.toString(aByteArray) + \", \"", + " + \"aNullableIntArray=\" + Arrays.toString(aNullableIntArray) + \", \"", + " + \"aList=\" + aList + \", \"", + " + \"anImmutableList=\" + anImmutableList + \", \"", + " + \"anOptionalString=\" + anOptionalString + \", \"", + " + \"aNestedAutoValue=\" + aNestedAutoValue", + " + \"}\";", + " }", + "", + " @Override public boolean equals(Object o) {", + " if (o == this) {", + " return true;", + " }", + " if (o instanceof Baz) {", + " Baz that = (Baz) o;", + " return (this.anInt == that.anInt())", + " && (Arrays.equals(this.aByteArray, " + + "(that instanceof AutoValue_Baz) " + + "? ((AutoValue_Baz) that).aByteArray : that.aByteArray()))", + " && (Arrays.equals(this.aNullableIntArray, " + + "(that instanceof AutoValue_Baz) " + + "? ((AutoValue_Baz) that).aNullableIntArray : that.aNullableIntArray()))", + " && (this.aList.equals(that.aList()))", + " && (this.anImmutableList.equals(that.anImmutableList()))", + " && (this.anOptionalString.equals(that.anOptionalString()))", + " && (this.aNestedAutoValue.equals(that.aNestedAutoValue()));", + " }", + " return false;", + " }", + "", + " @Override public int hashCode() {", + " int h = 1;", + " h *= 1000003;", + " h ^= this.anInt;", + " h *= 1000003;", + " h ^= Arrays.hashCode(this.aByteArray);", + " h *= 1000003;", + " h ^= Arrays.hashCode(this.aNullableIntArray);", + " h *= 1000003;", + " h ^= this.aList.hashCode();", + " h *= 1000003;", + " h ^= this.anImmutableList.hashCode();", + " h *= 1000003;", + " h ^= this.anOptionalString.hashCode();", + " h *= 1000003;", + " h ^= this.aNestedAutoValue.hashCode();", + " return h;", + " }", + "", + " @Override public Baz.Builder toBuilder() {", + " return new Builder(this);", + " }", + "", + " static final class Builder extends Baz.Builder {", + " private Integer anInt;", + " private byte[] aByteArray;", + " private int[] aNullableIntArray;", + " private List aList;", + " private ImmutableList.Builder anImmutableListBuilder$;", + " private ImmutableList anImmutableList;", + " private Optional anOptionalString = Optional.absent();", + " private NestedAutoValue.Builder aNestedAutoValueBuilder$;", + " private NestedAutoValue aNestedAutoValue;", + "", + " Builder() {", + " }", + "", + " private Builder(Baz source) {", + " this.anInt = source.anInt();", + " this.aByteArray = source.aByteArray();", + " this.aNullableIntArray = source.aNullableIntArray();", + " this.aList = source.aList();", + " this.anImmutableList = source.anImmutableList();", + " this.anOptionalString = source.anOptionalString();", + " this.aNestedAutoValue = source.aNestedAutoValue();", + " }", + "", + " @Override", + " public Baz.Builder anInt(int anInt) {", + " this.anInt = anInt;", + " return this;", + " }", + "", + " @Override", + " public Optional anInt() {", + " if (anInt == null) {", + " return Optional.absent();", + " } else {", + " return Optional.of(anInt);", + " }", + " }", + "", + " @Override", + " public Baz.Builder aByteArray(byte[] aByteArray) {", + " if (aByteArray == null) {", + " throw new NullPointerException(\"Null aByteArray\");", + " }", + " this.aByteArray = aByteArray;", + " return this;", + " }", + "", + " @Override", + " public Baz.Builder aNullableIntArray(@Nullable int[] aNullableIntArray) {", + " this.aNullableIntArray = aNullableIntArray;", + " return this;", + " }", + "", + " @Override", + " public Baz.Builder aList(List aList) {", + " if (aList == null) {", + " throw new NullPointerException(\"Null aList\");", + " }", + " this.aList = aList;", + " return this;", + " }", + "", + " @Override", + " public List aList() {", + " if (aList == null) {", + " throw new IllegalStateException(\"Property \\\"aList\\\" has not been set\");", + " }", + " return aList;", + " }", + "", + " @Override", + " public Baz.Builder anImmutableList(List anImmutableList) {", + " if (anImmutableList == null) {", + " throw new NullPointerException(\"Null anImmutableList\");", + " }", + " if (anImmutableListBuilder$ != null) {", + " throw new IllegalStateException(" + + "\"Cannot set anImmutableList after calling anImmutableListBuilder()\");", + " }", + " this.anImmutableList = ImmutableList.copyOf(anImmutableList);", + " return this;", + " }", + "", + " @Override", + " public ImmutableList.Builder anImmutableListBuilder() {", + " if (anImmutableListBuilder$ == null) {", + " if (anImmutableList == null) {", + " anImmutableListBuilder$ = ImmutableList.builder();", + " } else {", + " anImmutableListBuilder$ = ImmutableList.builder();", + " anImmutableListBuilder$.addAll(anImmutableList);", + " anImmutableList = null;", + " }", + " }", + " return anImmutableListBuilder$;", + " }", + "", + " @Override", + " public ImmutableList anImmutableList() {", + " if (anImmutableListBuilder$ != null) {", + " return anImmutableListBuilder$.build();", + " }", + " if (anImmutableList == null) {", + " anImmutableList = ImmutableList.of();", + " }", + " return anImmutableList;", + " }", + "", + " @Override", + " public Baz.Builder anOptionalString(Optional anOptionalString) {", + " if (anOptionalString == null) {", + " throw new NullPointerException(\"Null anOptionalString\");", + " }", + " this.anOptionalString = anOptionalString;", + " return this;", + " }", + "", + " @Override", + " public Baz.Builder anOptionalString(String anOptionalString) {", + " if (anOptionalString == null) {", + " throw new NullPointerException(\"Null anOptionalString\");", + " }", + " this.anOptionalString = Optional.of(anOptionalString);", + " return this;", + " }", + "", + " @Override", + " public NestedAutoValue.Builder aNestedAutoValueBuilder() {", + " if (aNestedAutoValueBuilder$ == null) {", + " if (aNestedAutoValue == null) {", + " aNestedAutoValueBuilder$ = NestedAutoValue.builder();", + " } else {", + " aNestedAutoValueBuilder$ = aNestedAutoValue.toBuilder();", + " aNestedAutoValue = null;", + " }", + " }", + " return aNestedAutoValueBuilder$;", + " }", + "", + " @Override", + " public Baz build() {", + " if (anImmutableListBuilder$ != null) {", + " this.anImmutableList = anImmutableListBuilder$.build();", + " } else if (this.anImmutableList == null) {", + " this.anImmutableList = ImmutableList.of();", + " }", + " if (aNestedAutoValueBuilder$ != null) {", + " this.aNestedAutoValue = aNestedAutoValueBuilder$.build();", + " } else if (this.aNestedAutoValue == null) {", + " NestedAutoValue.Builder aNestedAutoValue$builder = NestedAutoValue.builder();", + " this.aNestedAutoValue = aNestedAutoValue$builder.build();", + " }", + " String missing = \"\";", + " if (this.anInt == null) {", + " missing += \" anInt\";", + " }", + " if (this.aByteArray == null) {", + " missing += \" aByteArray\";", + " }", + " if (this.aList == null) {", + " missing += \" aList\";", + " }", + " if (!missing.isEmpty()) {", + " throw new IllegalStateException(\"Missing required properties:\" + missing);", + " }", + " return new AutoValue_Baz(", + " this.anInt,", + " this.aByteArray,", + " this.aNullableIntArray,", + " this.aList,", + " this.anImmutableList,", + " this.anOptionalString,", + " this.aNestedAutoValue);", + " }", + " }", + "}"); Compilation compilation = javac() .withProcessors(new AutoValueProcessor()) @@ -2711,4 +2716,8 @@ public void builderWithVarArgsDoesNotImportJavaUtilArrays() { .contentsAsUtf8String() .doesNotContain("java.util.Arrays"); } + + private String sorted(String... imports) { + return Stream.of(imports).sorted().collect(joining("\n")); + } } diff --git a/value/src/test/java/com/google/auto/value/processor/ExtensionTest.java b/value/src/test/java/com/google/auto/value/processor/ExtensionTest.java index ce7da468f7..2061af573c 100644 --- a/value/src/test/java/com/google/auto/value/processor/ExtensionTest.java +++ b/value/src/test/java/com/google/auto/value/processor/ExtensionTest.java @@ -49,12 +49,16 @@ import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import javax.tools.StandardLocation; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ExtensionTest { + + @Rule public final GeneratedImportRule generatedImportRule = new GeneratedImportRule(); + @Test public void testExtensionCompilation() throws Exception { @@ -103,59 +107,58 @@ public void testExtensionConsumesProperties() throws Exception { " abstract String foo();", " abstract String dizzle();", "}"); - JavaFileObject expectedExtensionOutput = JavaFileObjects.forSourceLines( - "foo.bar.$AutoValue_Baz", - "package foo.bar;\n" - + "\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")\n" - + " abstract class $AutoValue_Baz extends Baz {\n" - + "\n" - + " private final String foo;\n" - + "\n" - + " $AutoValue_Baz(\n" - + " String foo) {\n" - + " if (foo == null) {\n" - + " throw new NullPointerException(\"Null foo\");\n" - + " }\n" - + " this.foo = foo;\n" - + " }\n" - + "\n" - + " @Override\n" - + " String foo() {\n" - + " return foo;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String toString() {\n" - + " return \"Baz{\"\n" - + " + \"foo=\" + foo\n" - + " + \"}\";\n" - + " }\n" - + "\n" - + " @Override\n" - + " public boolean equals(Object o) {\n" - + " if (o == this) {\n" - + " return true;\n" - + " }\n" - + " if (o instanceof Baz) {\n" - + " Baz that = (Baz) o;\n" - + " return (this.foo.equals(that.foo()));\n" - + " }\n" - + " return false;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public int hashCode() {\n" - + " int h = 1;\n" - + " h *= 1000003;\n" - + " h ^= this.foo.hashCode();\n" - + " return h;\n" - + " }\n" - + "\n" - + "}" - ); + JavaFileObject expectedExtensionOutput = + JavaFileObjects.forSourceLines( + "foo.bar.$AutoValue_Baz", + "package foo.bar;", + "", + generatedImportRule.importGeneratedAnnotationType(), + "", + "@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")", + " abstract class $AutoValue_Baz extends Baz {", + "", + " private final String foo;", + "", + " $AutoValue_Baz(", + " String foo) {", + " if (foo == null) {", + " throw new NullPointerException(\"Null foo\");", + " }", + " this.foo = foo;", + " }", + "", + " @Override", + " String foo() {", + " return foo;", + " }", + "", + " @Override", + " public String toString() {", + " return \"Baz{\"", + " + \"foo=\" + foo", + " + \"}\";", + " }", + "", + " @Override", + " public boolean equals(Object o) {", + " if (o == this) {", + " return true;", + " }", + " if (o instanceof Baz) {", + " Baz that = (Baz) o;", + " return (this.foo.equals(that.foo()));", + " }", + " return false;", + " }", + "", + " @Override", + " public int hashCode() {", + " int h = 1;", + " h *= 1000003;", + " h ^= this.foo.hashCode();", + " return h;", + " }", + "}"); assertThat(javaFileObject) .processedWith(new AutoValueProcessor(ImmutableList.of(new FooExtension()))) .compilesWithoutError() diff --git a/value/src/test/java/com/google/auto/value/processor/GeneratedDoesNotExistTest.java b/value/src/test/java/com/google/auto/value/processor/GeneratedDoesNotExistTest.java index 7b211b03a1..00173d0e64 100644 --- a/value/src/test/java/com/google/auto/value/processor/GeneratedDoesNotExistTest.java +++ b/value/src/test/java/com/google/auto/value/processor/GeneratedDoesNotExistTest.java @@ -19,11 +19,13 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; +import com.google.common.collect.ImmutableSet; import com.google.common.reflect.Reflection; import com.google.testing.compile.JavaFileObjects; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.lang.model.element.TypeElement; @@ -48,7 +50,11 @@ public class GeneratedDoesNotExistTest { // out the Generated class. So that ProcessingEnvironment forwards everything to the real // ProcessingEnvironment, except the ProcessingEnvironment.getElementUtils() method. That method // returns an Elements object that forwards everything to the real Elements except - // getTypeElement("javax.annotation.Generated"). + // getTypeElement("javax.annotation.Generated") and + // getTypeElement("javax.annotation.processing.Generated"). + + private static final ImmutableSet GENERATED_ANNOTATIONS = + ImmutableSet.of("javax.annotation.Generated", "javax.annotation.processing.Generated"); /** * InvocationHandler that forwards every method to an original object, except methods where @@ -85,16 +91,17 @@ private static T partialProxy(Class type, OverridableInvocationHandler } private static class ElementsHandler extends OverridableInvocationHandler { - private final AtomicBoolean ignoredGenerated; - ElementsHandler(Elements original, AtomicBoolean ignoredGenerated) { + private final Set ignoredGenerated; + + ElementsHandler(Elements original, Set ignoredGenerated) { super(original); this.ignoredGenerated = ignoredGenerated; } public TypeElement getTypeElement(CharSequence name) { - if (name.toString().equals("javax.annotation.Generated")) { - ignoredGenerated.set(true); + if (GENERATED_ANNOTATIONS.contains(name.toString())) { + ignoredGenerated.add(name.toString()); return null; } else { return original.getTypeElement(name); @@ -106,8 +113,7 @@ private static class ProcessingEnvironmentHandler extends OverridableInvocationHandler { private final Elements noGeneratedElements; - ProcessingEnvironmentHandler( - ProcessingEnvironment original, AtomicBoolean ignoredGenerated) { + ProcessingEnvironmentHandler(ProcessingEnvironment original, Set ignoredGenerated) { super(original); ElementsHandler elementsHandler = new ElementsHandler(original.getElementUtils(), ignoredGenerated); @@ -120,9 +126,9 @@ public Elements getElementUtils() { } private static class ProcessorHandler extends OverridableInvocationHandler { - private final AtomicBoolean ignoredGenerated; + private final Set ignoredGenerated; - ProcessorHandler(Processor original, AtomicBoolean ignoredGenerated) { + ProcessorHandler(Processor original, Set ignoredGenerated) { super(original); this.ignoredGenerated = ignoredGenerated; } @@ -179,7 +185,7 @@ public void test() { " }", "}" ); - AtomicBoolean ignoredGenerated = new AtomicBoolean(); + Set ignoredGenerated = ConcurrentHashMap.newKeySet(); Processor autoValueProcessor = new AutoValueProcessor(); ProcessorHandler handler = new ProcessorHandler(autoValueProcessor, ignoredGenerated); Processor noGeneratedProcessor = partialProxy(Processor.class, handler); @@ -189,6 +195,6 @@ public void test() { .compilesWithoutError() .and() .generatesSources(expectedOutput); - assertThat(ignoredGenerated.get()).isTrue(); + assertThat(ignoredGenerated).isEqualTo(GENERATED_ANNOTATIONS); } } diff --git a/value/src/test/java/com/google/auto/value/processor/GeneratedImportRule.java b/value/src/test/java/com/google/auto/value/processor/GeneratedImportRule.java new file mode 100644 index 0000000000..0502ae1035 --- /dev/null +++ b/value/src/test/java/com/google/auto/value/processor/GeneratedImportRule.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2017 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.testing.compile.CompilationRule; +import javax.lang.model.util.Elements; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * Test rule that allows compile-testing tests to know which {@code @Generated} annotation is + * available. + */ +final class GeneratedImportRule implements TestRule { + + private final CompilationRule compilationRule = new CompilationRule(); + + /** + * Returns the qualified name of the {@code @Generated} annotation available during a compilation + * task. + */ + String generatedAnnotationType() { + Elements elements = compilationRule.getElements(); + return elements.getTypeElement("javax.annotation.processing.Generated") != null + ? "javax.annotation.processing.Generated" + : "javax.annotation.Generated"; + } + + /** + * Returns an {@code import} statement that imports the {@code @Generated} annotation {@linkplain + * #generatedAnnotationType() available during a compilation task}. + */ + String importGeneratedAnnotationType() { + return "import " + generatedAnnotationType() + ";"; + } + + @Override + public Statement apply(Statement base, Description description) { + return compilationRule.apply(base, description); + } +} diff --git a/value/src/test/java/com/google/auto/value/processor/PropertyAnnotationsTest.java b/value/src/test/java/com/google/auto/value/processor/PropertyAnnotationsTest.java index 5f277a47bc..4d460c8ae3 100644 --- a/value/src/test/java/com/google/auto/value/processor/PropertyAnnotationsTest.java +++ b/value/src/test/java/com/google/auto/value/processor/PropertyAnnotationsTest.java @@ -24,6 +24,7 @@ import java.lang.annotation.Inherited; import java.util.List; import javax.tools.JavaFileObject; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -96,6 +97,8 @@ OtherAnnotation[] testAnnotations() @Inherited public @interface InheritedAnnotation {} + @Rule public final GeneratedImportRule generatedImportRule = new GeneratedImportRule(); + private JavaFileObject sourceCode(List imports, List annotations) { ImmutableList list = ImmutableList.builder() .add( @@ -126,10 +129,11 @@ private JavaFileObject sourceCode(List imports, List annotations private JavaFileObject expectedCode(List imports, List annotations) { String nullable = annotations.contains("@Nullable") ? "@Nullable " : ""; - ImmutableSortedSet allImports = ImmutableSortedSet.naturalOrder() - .add("import javax.annotation.Generated;") - .addAll(imports) - .build(); + ImmutableSortedSet allImports = + ImmutableSortedSet.naturalOrder() + .add(generatedImportRule.importGeneratedAnnotationType()) + .addAll(imports) + .build(); ImmutableList list = ImmutableList.builder() .add( "package foo.bar;", @@ -183,7 +187,6 @@ private JavaFileObject expectedCode(List imports, List annotatio return JavaFileObjects.forSourceLines("foo.bar.AutoValue_Baz", lines); } - private void assertGeneratedMatches( List imports, List annotations, @@ -408,5 +411,4 @@ public void testCopyingMethodAnnotations() { .and() .generatesSources(expectedOutput); } - }