Skip to content

Commit

Permalink
Don't flag things which probably shouldn't be static anyway.
Browse files Browse the repository at this point in the history
There's probably a case to be made that we should remove the `static` modifier instead, but this will stop us making _broken_ suggestions.

PiperOrigin-RevId: 572927264
  • Loading branch information
graememorgan authored and Error Prone Team committed Oct 12, 2023
1 parent 3cdff25 commit 8d62eb6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@
import static com.google.errorprone.util.ASTHelpers.canBeRemoved;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.hasDirectAnnotationWithSimpleName;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;
import static com.google.errorprone.util.ASTHelpers.isSameType;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import static javax.lang.model.element.ElementKind.FIELD;
import static javax.lang.model.element.Modifier.FINAL;

import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
Expand All @@ -48,6 +50,9 @@
/** A BugPattern; see the summary. */
@BugPattern(summary = "Static fields should almost always be final.", severity = WARNING)
public final class NonFinalStaticField extends BugChecker implements VariableTreeMatcher {
private static final ImmutableSet<String> ANNOTATIONS_TO_AVOID =
ImmutableSet.of("Captor", "Inject", "Mock", "TestParameter");

@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
var symbol = getSymbol(tree);
Expand All @@ -60,6 +65,10 @@ public Description matchVariable(VariableTree tree, VisitorState state) {
if (isConsideredFinal(symbol)) {
return NO_MATCH;
}
if (ANNOTATIONS_TO_AVOID.stream()
.anyMatch(anno -> hasDirectAnnotationWithSimpleName(tree, anno))) {
return NO_MATCH;
}
if (!canBeRemoved(symbol, state) || isEverMutatedInSameCompilationUnit(symbol, state)) {
return describeMatch(tree);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,16 @@ public void negativeInterface() {
"}")
.doTest();
}

@Test
public void exemptedAnnotation_noFinding() {
compilationTestHelper
.addSourceLines(
"Test.java", //
"import org.mockito.Mock;",
"public class Test {",
" @Mock private static String foo;",
"}")
.doTest();
}
}

0 comments on commit 8d62eb6

Please sign in to comment.