Skip to content

Commit

Permalink
Make AutoBuilder produce an error if it encounters a @Nullable prim…
Browse files Browse the repository at this point in the history
…itive parameter

RELNOTES=AutoBuilder now reports an error if it encounters a `@Nullable` primitive parameter. Primitive types cannot be `null`, and should not be annotated for nullness.
PiperOrigin-RevId: 596009085
  • Loading branch information
cushon authored and Google Java Core Libraries committed Jan 5, 2024
1 parent 19043eb commit 7cbdeb4
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -298,13 +298,20 @@ private ImmutableSet<Property> propertySet(
.map(
v -> {
String name = v.getSimpleName().toString();
return newProperty(
v,
identifiers.get(v),
propertyToGetterName.get(name),
Optional.ofNullable(builderInitializers.get(name)),
executable.isOptional(name),
nullables);
Property p =
newProperty(
v,
identifiers.get(v),
propertyToGetterName.get(name),
Optional.ofNullable(builderInitializers.get(name)),
executable.isOptional(name),
nullables);
if (p.isNullable() && v.asType().getKind().isPrimitive()) {
errorReporter()
.reportError(
v, "[AutoBuilderNullPrimitive] Primitive types cannot be @Nullable");
}
return p;
})
.collect(toImmutableSet());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,46 @@ public void nullableSetterForNonNullableParameter() {
.onLineContaining("thing(@Nullable String x)");
}

@Test
public void nullablePrimitiveParameter() {
JavaFileObject javaFileObject =
JavaFileObjects.forSourceLines(
"foo.bar.Baz",
"package foo.bar;",
"",
"import com.google.auto.value.AutoBuilder;",
"import com.example.annotations.Nullable;",
"",
"class Baz {",
" Baz(@Nullable int thing) {}",
"",
" @AutoBuilder",
" interface Builder {",
" abstract Builder thing(int x);",
" abstract Baz build();",
" }",
"}");
JavaFileObject nullableFileObject =
JavaFileObjects.forSourceLines(
"com.example.annotations.Nullable",
"package com.example.annotations;",
"",
"import java.lang.annotation.ElementType;",
"import java.lang.annotation.Target;",
"",
"@Target(ElementType.TYPE_USE)",
"public @interface Nullable {}");
Compilation compilation =
javac()
.withProcessors(new AutoBuilderProcessor())
.compile(javaFileObject, nullableFileObject);
assertThat(compilation).failed();
assertThat(compilation)
.hadErrorContaining("[AutoBuilderNullPrimitive] Primitive types cannot be @Nullable")
.inFile(javaFileObject)
.onLineContaining("Baz(@Nullable int thing)");
}

@Test
public void setterWrongType() {
JavaFileObject javaFileObject =
Expand Down

0 comments on commit 7cbdeb4

Please sign in to comment.