Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support to AutoValue.Id. #212

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions value/src/main/java/com/google/auto/value/AutoValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,15 @@
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface Validate {}


/**
* Specifies that the annotated method is an id method. All methods containing this annotation
* will be used in the {@link Object#equals equals} and {@link Object#hashCode hashCode} implementation.
*
* @author Rafael Torres
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface Id {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2014 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.value.processor;

import com.google.auto.common.MoreElements;
import com.google.auto.common.SuperficialValidation;
import com.google.auto.service.AutoService;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.util.Set;

import static com.google.auto.common.MoreElements.isAnnotationPresent;

/**
* Annotation processor that checks that the type that {@link com.google.auto.value.AutoValue.Id}
* is applied to is nested inside an {@code @AutoValue} class. The actual code generation for ids
* is done in {@link AutoValueProcessor}.
*
* @author Rafael Torres
*/
@AutoService(Processor.class)
public class AutoValueIdsProcessor extends AbstractProcessor {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was not sure if I should create another processor to validate Id or if I should use AutoValueBuilderProcessor. My suggestion is to rename AutoValueBuilderProcessor to some generic name and use it to validate Builder, Validate and Id.

@Override
public Set<String> getSupportedAnnotationTypes() {
return ImmutableSet.of(
AutoValue.Id.class.getCanonicalName());
}

@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Set<? extends Element> idsMethods =
roundEnv.getElementsAnnotatedWith(AutoValue.Id.class);
if (!SuperficialValidation.validateElements(idsMethods)) {
return false;
}
for (Element annotatedMethod : idsMethods) {
if (isAnnotationPresent(annotatedMethod, AutoValue.Id.class)) {
validate(
annotatedMethod,
"@AutoValue.Id can only be applied to a method inside an @AutoValue class");
}
}
return false;
}

private void validate(Element annotatedType, String errorMessage) {
Element container = annotatedType.getEnclosingElement();
if (!MoreElements.isAnnotationPresent(container, AutoValue.class)) {
processingEnv.getMessager().printMessage(
Diagnostic.Kind.ERROR, errorMessage, annotatedType);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package com.google.auto.value.processor;

import com.google.auto.common.MoreElements;
import com.google.auto.service.AutoService;
import com.google.auto.value.AutoValue;
import com.google.common.base.Functions;
Expand Down Expand Up @@ -414,15 +415,24 @@ private void defineVarsForType(TypeElement type, AutoValueTemplateVars vars) {
Maps.newLinkedHashMap(methodToPropertyName);
fixReservedIdentifiers(methodToIdentifier);
List<Property> props = new ArrayList<Property>();
List<Property> ids = new ArrayList<Property>();
for (ExecutableElement method : propertyMethods) {
String propertyType = typeSimplifier.simplify(method.getReturnType());
String propertyName = methodToPropertyName.get(method);
String identifier = methodToIdentifier.get(method);
props.add(new Property(propertyName, identifier, method, propertyType, typeSimplifier));
Property p = new Property(propertyName, identifier, method, propertyType, typeSimplifier);
props.add(p);
if (MoreElements.isAnnotationPresent(method, AutoValue.Id.class)) {
ids.add(p);
}
}
if (ids.isEmpty()) {
ids.addAll(props);
}
// If we are running from Eclipse, undo the work of its compiler which sorts methods.
eclipseHack().reorderProperties(props);
vars.props = props;
vars.ids = ids;
vars.serialVersionUID = getSerialVersionUID(type);
vars.formalTypes = typeSimplifier.formalTypeParametersString(type);
vars.actualTypes = TypeSimplifier.actualTypeParametersString(type);
Expand Down Expand Up @@ -494,7 +504,7 @@ private void fixReservedIdentifiers(Map<ExecutableElement, String> methodToIdent
}

private String disambiguate(String name, Collection<String> existingNames) {
for (int i = 0; ; i++) {
for (int i = 0;; i++) {
String candidate = name + i;
if (!existingNames.contains(candidate)) {
return candidate;
Expand Down Expand Up @@ -554,6 +564,11 @@ private ImmutableSet<ExecutableElement> methodsToImplement(List<ExecutableElemen
ImmutableSet.Builder<ExecutableElement> toImplement = ImmutableSet.builder();
boolean errors = false;
for (ExecutableElement method : methods) {
if (MoreElements.isAnnotationPresent(method, AutoValue.Id.class)
&& method.getModifiers().contains(Modifier.STATIC)) {
errorReporter.reportError("@AutoValue.Id cannot apply to a static method", method);
errors = true;
}
if (method.getModifiers().contains(Modifier.ABSTRACT)
&& objectMethodToOverride(method) == ObjectMethodToOverride.NONE) {
if (method.getParameters().isEmpty() && method.getReturnType().getKind() != TypeKind.VOID) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ class AutoValueTemplateVars extends TemplateVars {
/** The properties defined by the parent class's abstract methods. */
List<AutoValueProcessor.Property> props;

/** The properties of all methods marked as ids or a copy of props in case ids is empty*/
List<AutoValueProcessor.Property> ids;

/** Whether to generate an equals(Object) method. */
Boolean equals;
/** Whether to generate a hashCode() method. */
Expand Down Expand Up @@ -146,6 +149,7 @@ class AutoValueTemplateVars extends TemplateVars {

private static final SimpleNode TEMPLATE = parsedTemplateForResource("autovalue.vm");


@Override
SimpleNode parsedTemplate() {
return TEMPLATE;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,15 +127,15 @@ final class $subclass$formalTypes extends $origClass$actualTypes {
}
if (o instanceof $origClass) {

#if ($props.empty)
#if ($ids.empty)

return true;

#else

$origClass$wildcardTypes that = ($origClass$wildcardTypes) o;
return ##
#foreach ($p in $props)
#foreach ($p in $ids)
(#equalsThatExpression ($p))##
#if ($foreach.hasNext)

Expand Down Expand Up @@ -174,7 +174,7 @@ final class $subclass$formalTypes extends $origClass$actualTypes {
public int hashCode() {
int h = 1;

#foreach ($p in $props)
#foreach ($p in $ids)

h *= 1000003;
h ^= #hashCodeExpression($p);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1523,4 +1523,195 @@ public void testReferencingGeneratedClass() {
.processedWith(new AutoValueProcessor(), new FooProcessor())
.compilesWithoutError();
}

public void testId() {
JavaFileObject javaFileObject = JavaFileObjects.forSourceLines(
"foo.bar.Baz",
"package foo.bar;",
"",
"import com.google.auto.value.AutoValue;",
"",
"@AutoValue",
"public abstract class Baz {",
" public abstract String stringVar();",
" @AutoValue.Id public abstract String stringId();",


"}");
JavaFileObject expectedOutput = JavaFileObjects.forSourceString(
"foo.bar.AutoValue_Baz",
"package foo.bar;\n" +
"\n" +
"import javax.annotation.Generated;\n" +
"\n" +
"@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")\n" +
"final class AutoValue_Baz extends Baz {\n" +
"\n" +
" private final String stringVar;\n" +
" private final String stringId;\n" +
"\n" +
" AutoValue_Baz(\n" +
" String stringVar,\n" +
" String stringId) {\n" +
" if (stringVar == null) {\n" +
" throw new NullPointerException(\"Null stringVar\");\n" +
" }\n" +
" this.stringVar = stringVar;\n" +
" if (stringId == null) {\n" +
" throw new NullPointerException(\"Null stringId\");\n" +
" }\n" +
" this.stringId = stringId;\n" +
" }\n" +
"\n" +
" @Override\n" +
" public String stringVar() {\n" +
" return stringVar;\n" +
" }\n" +
"\n" +
" @com.google.auto.value.AutoValue.Id\n" +
" @Override\n" +
" public String stringId() {\n" +
" return stringId;\n" +
" }\n" +
"\n" +
" @Override\n" +
" public String toString() {\n" +
" return \"Baz{\"\n" +
" + \"stringVar=\" + stringVar + \", \"\n" +
" + \"stringId=\" + stringId\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.stringId.equals(that.stringId()));\n" +
" }\n" +
" return false;\n" +
" }\n" +
"\n" +
" @Override\n" +
" public int hashCode() {\n" +
" int h = 1;\n" +
" h *= 1000003;\n" +
" h ^= stringId.hashCode();\n" +
" return h;\n" +
" }\n" +
"\n" +
"}"
);
assertAbout(javaSource())
.that(javaFileObject)
.processedWith(new AutoValueProcessor())
.compilesWithoutError()
.and().generatesSources(expectedOutput);
}


public void testIds() {
JavaFileObject javaFileObject = JavaFileObjects.forSourceLines(
"foo.bar.Baz",
"package foo.bar;",
"",
"import com.google.auto.value.AutoValue;",
"",
"@AutoValue",
"public abstract class Baz {",
" public abstract String stringVar();",
" @AutoValue.Id public abstract String stringId();",
" @AutoValue.Id public abstract String stringId2();",

"}");
JavaFileObject expectedOutput = JavaFileObjects.forSourceString(
"foo.bar.AutoValue_Baz",
"package foo.bar;\n" +
"\n" +
"import javax.annotation.Generated;\n" +
"\n" +
"@Generated(\"com.google.auto.value.processor.AutoValueProcessor\")\n" +
"final class AutoValue_Baz extends Baz {\n" +
"\n" +
" private final String stringVar;\n" +
" private final String stringId;\n" +
" private final String stringId2;\n" +
"\n" +
" AutoValue_Baz(\n" +
" String stringVar,\n" +
" String stringId,\n" +
" String stringId2) {\n" +
" if (stringVar == null) {\n" +
" throw new NullPointerException(\"Null stringVar\");\n" +
" }\n" +
" this.stringVar = stringVar;\n" +
" if (stringId == null) {\n" +
" throw new NullPointerException(\"Null stringId\");\n" +
" }\n" +
" this.stringId = stringId;\n" +
" if (stringId2 == null) {\n" +
" throw new NullPointerException(\"Null stringId2\");\n" +
" }\n" +
" this.stringId2 = stringId2;\n" +
" }\n" +
"\n" +
" @Override\n" +
" public String stringVar() {\n" +
" return stringVar;\n" +
" }\n" +
"\n" +
" @com.google.auto.value.AutoValue.Id\n" +
" @Override\n" +
" public String stringId() {\n" +
" return stringId;\n" +
" }\n" +
"\n" +
" @com.google.auto.value.AutoValue.Id\n" +
" @Override\n" +
" public String stringId2() {\n" +
" return stringId2;\n" +
" }\n" +
"\n" +
" @Override\n" +
" public String toString() {\n" +
" return \"Baz{\"\n" +
" + \"stringVar=\" + stringVar + \", \"\n" +
" + \"stringId=\" + stringId + \", \"\n" +
" + \"stringId2=\" + stringId2\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.stringId.equals(that.stringId()))\n" +
" && (this.stringId2.equals(that.stringId2()));\n" +
" }\n" +
" return false;\n" +
" }\n" +
"\n" +
" @Override\n" +
" public int hashCode() {\n" +
" int h = 1;\n" +
" h *= 1000003;\n" +
" h ^= stringId.hashCode();\n" +
" h *= 1000003;\n" +
" h ^= stringId2.hashCode();\n" +
" return h;\n" +
" }\n" +
"\n" +
"}"
);
assertAbout(javaSource())
.that(javaFileObject)
.processedWith(new AutoValueProcessor())
.compilesWithoutError()
.and().generatesSources(expectedOutput);
}
}