Skip to content

Commit

Permalink
Discourage nullness annotations on wildcards and type parameters them…
Browse files Browse the repository at this point in the history
…selves

PiperOrigin-RevId: 580288274
  • Loading branch information
cushon authored and Error Prone Team committed Nov 7, 2023
1 parent 46122d1 commit 29f4602
Show file tree
Hide file tree
Showing 9 changed files with 483 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,13 @@ public static Optional<Nullness> fromAnnotationsOn(@Nullable Symbol sym) {
* We try to read annotations in two ways:
*
* 1. from the TypeMirror: This is how we "should" always read *type-use* annotations, but
* we can't rely on it until the fix for JDK-8225377 is widely available.
* JDK-8225377 prevents it from working across compilation boundaries.
*
* 2. from getRawAttributes(): This works around the problem across compilation boundaries, and
* it handles declaration annotations (though there are other ways we could handle declaration
* annotations).
* annotations). But it has a bug of its own with type-use annotations on inner classes
* (b/203207989). To reduce the chance that we hit the inner-class bug, we apply it only if the
* first approach fails.
*/
TypeMirror elementType;
switch (sym.getKind()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright 2023 The Error Prone Authors.
*
* 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.errorprone.bugpatterns.nullness;

import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;

import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher;
import com.google.errorprone.dataflow.nullnesspropagation.Nullness;
import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnnotations;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
import java.util.List;
import java.util.Optional;

/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Nullness annotations directly on type parameters are interpreted differently by different"
+ " tools",
severity = WARNING)
public class NullableTypeParameter extends BugChecker implements TypeParameterTreeMatcher {

@Override
public Description matchTypeParameter(TypeParameterTree tree, VisitorState state) {
Optional<Nullness> nullness = NullnessAnnotations.fromAnnotationTrees(tree.getAnnotations());
if (nullness.isEmpty()) {
return NO_MATCH;
}
return describeMatch(tree, fix(tree.getAnnotations(), tree, state));
}

Fix fix(List<? extends AnnotationTree> annotations, TypeParameterTree tree, VisitorState state) {
ImmutableList<AnnotationTree> existingAnnotations =
NullnessAnnotations.annotationsRelevantToNullness(annotations);
if (existingAnnotations.size() != 1) {
return SuggestedFix.emptyFix();
}
AnnotationTree existingAnnotation = getOnlyElement(existingAnnotations);
SuggestedFix.Builder fix = SuggestedFix.builder().delete(existingAnnotation);
List<? extends Tree> bounds = tree.getBounds();
if (bounds.stream()
.anyMatch(
b ->
b instanceof AnnotatedTypeTree
&& NullnessAnnotations.fromAnnotationTrees(
((AnnotatedTypeTree) b).getAnnotations())
.isPresent())) {
return SuggestedFix.emptyFix();
}
if (bounds.isEmpty()) {
return fix.postfixWith(
tree, String.format(" extends %s Object", state.getSourceForNode(existingAnnotation)))
.build();
} else {
String prefix = String.format("%s ", state.getSourceForNode(existingAnnotation));
bounds.forEach(bound -> fix.prefixWith(bound, prefix));
return fix.build();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright 2023 The Error Prone Authors.
*
* 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.errorprone.bugpatterns.nullness;

import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;

import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotatedTypeTreeMatcher;
import com.google.errorprone.dataflow.nullnesspropagation.Nullness;
import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnnotations;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.WildcardTree;
import java.util.List;
import java.util.Optional;

/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"Nullness annotations directly on wildcard types are interpreted differently by different"
+ " tools",
severity = WARNING)
public class NullableWildcard extends BugChecker implements AnnotatedTypeTreeMatcher {
@Override
public Description matchAnnotatedType(AnnotatedTypeTree tree, VisitorState state) {
Optional<Nullness> nullness = NullnessAnnotations.fromAnnotationTrees(tree.getAnnotations());
if (nullness.isEmpty()) {
return NO_MATCH;
}
ExpressionTree typeTree = tree.getUnderlyingType();
if (!(typeTree instanceof WildcardTree)) {
return NO_MATCH;
}
return describeMatch(tree, fix(tree.getAnnotations(), (WildcardTree) typeTree, state));
}

Fix fix(List<? extends AnnotationTree> annotations, WildcardTree tree, VisitorState state) {
ImmutableList<AnnotationTree> existingAnnotations =
NullnessAnnotations.annotationsRelevantToNullness(annotations);
if (existingAnnotations.size() != 1) {
return SuggestedFix.emptyFix();
}
AnnotationTree existingAnnotation = getOnlyElement(existingAnnotations);
SuggestedFix.Builder fix = SuggestedFix.builder().delete(existingAnnotation);
switch (tree.getKind()) {
case EXTENDS_WILDCARD:
Tree bound = tree.getBound();
if (bound instanceof AnnotatedTypeTree
&& NullnessAnnotations.fromAnnotationTrees(((AnnotatedTypeTree) bound).getAnnotations())
.isPresent()) {
return SuggestedFix.emptyFix();
}
return fix.prefixWith(
bound, String.format("%s ", state.getSourceForNode(existingAnnotation)))
.build();
case SUPER_WILDCARD:
return SuggestedFix.emptyFix();
case UNBOUNDED_WILDCARD:
return fix.postfixWith(
tree,
String.format(" extends %s Object", state.getSourceForNode(existingAnnotation)))
.build();
default:
throw new AssertionError(tree.getKind());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,8 @@
import com.google.errorprone.bugpatterns.nullness.NullArgumentForNonNullParameter;
import com.google.errorprone.bugpatterns.nullness.NullablePrimitive;
import com.google.errorprone.bugpatterns.nullness.NullablePrimitiveArray;
import com.google.errorprone.bugpatterns.nullness.NullableTypeParameter;
import com.google.errorprone.bugpatterns.nullness.NullableWildcard;
import com.google.errorprone.bugpatterns.nullness.ParameterMissingNullable;
import com.google.errorprone.bugpatterns.nullness.ReturnMissingNullable;
import com.google.errorprone.bugpatterns.nullness.UnnecessaryCheckNotNull;
Expand Down Expand Up @@ -998,7 +1000,9 @@ public static ScannerSupplier warningChecks() {
NullableOptional.class,
NullablePrimitive.class,
NullablePrimitiveArray.class,
NullableTypeParameter.class,
NullableVoid.class,
NullableWildcard.class,
ObjectEqualsForPrimitives.class,
ObjectToString.class,
ObjectsHashCodePrimitive.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Copyright 2023 The Error Prone Authors.
*
* 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.errorprone.bugpatterns.nullness;

import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class NullableTypeParameterTest {

private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(NullableTypeParameter.class, getClass());

@Test
public void positive() {
testHelper
.addInputLines(
"T.java",
"import java.util.List;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"class T {",
" interface I {}",
" interface J {}",
" <@Nullable X, @NonNull Y> void f() {}",
" <@Nullable X extends Object> void h() {}",
" <@Nullable X extends I & J> void i() {}",
"}")
.addOutputLines(
"T.java",
"import java.util.List;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"class T {",
" interface I {}",
" interface J {}",
" <X extends @Nullable Object, Y extends @NonNull Object> void f() {}",
" <X extends @Nullable Object> void h() {}",
" <X extends @Nullable I & @Nullable J> void i() {}",
"}")
.doTest();
}

@Test
public void noFix() {
testHelper
.addInputLines(
"T.java",
"import java.util.List;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"class T {",
" interface I {}",
" interface J {}",
" <@Nullable @NonNull X> void f() {}",
" <@Nullable X extends @Nullable Object> void g() {}",
" <@Nullable X extends I & @Nullable J> void h() {}",
"}")
.expectUnchanged()
.doTest();
}

@Test
public void diagnostics() {
CompilationTestHelper.newInstance(NullableTypeParameter.class, getClass())
.addSourceLines(
"T.java",
"import java.util.List;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"class T {",
" interface I {}",
" interface J {}",
" // BUG: Diagnostic contains:",
" <@Nullable @NonNull X> void f() {}",
" // BUG: Diagnostic contains:",
" <@Nullable X extends @Nullable Object> void g() {}",
" // BUG: Diagnostic contains:",
" <@Nullable X extends I & @Nullable J> void h() {}",
"}")
.doTest();
}
}
Loading

0 comments on commit 29f4602

Please sign in to comment.