Skip to content

Commit

Permalink
Make CompareToZero treat methods like Integer.compare similar to …
Browse files Browse the repository at this point in the history
…`compareTo`.

PiperOrigin-RevId: 563211769
  • Loading branch information
cpovirk authored and Error Prone Team committed Sep 7, 2023
1 parent 66537db commit d3f1a1d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.constValue;

import com.google.common.collect.ImmutableMap;
Expand Down Expand Up @@ -74,6 +75,31 @@ public final class CompareToZero extends BugChecker implements MethodInvocationT

private static final Matcher<ExpressionTree> COMPARE_TO =
anyOf(
staticMethod()
.onClassAny(
"com.google.common.primitives.Booleans",
"com.google.common.primitives.Chars",
"com.google.common.primitives.Doubles",
"com.google.common.primitives.Floats",
"com.google.common.primitives.Ints",
"com.google.common.primitives.Longs",
"com.google.common.primitives.Shorts",
"com.google.common.primitives.SignedBytes",
"com.google.common.primitives.UnsignedBytes",
"com.google.common.primitives.UnsignedInts",
"com.google.common.primitives.UnsignedLongs",
"com.google.protobuf.util.Durations",
"com.google.protobuf.util.Timestamps",
"java.lang.Boolean",
"java.lang.Byte",
"java.lang.Character",
"java.lang.Double",
"java.lang.Float",
"java.lang.Integer",
"java.lang.Long",
"java.lang.Short",
"java.util.Objects")
.named("compare"),
instanceMethod().onDescendantOf("java.lang.Comparable").named("compareTo"),
instanceMethod().onDescendantOf("java.util.Comparator").named("compare"));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ public void positive() {
.doTest();
}

@Test
public void positiveStaticCompare() {
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" boolean test(boolean x, boolean y) {",
" // BUG: Diagnostic contains: compared",
" return Boolean.compare(x, y) == -1;",
" }",
"}")
.doTest();
}

@Test
public void positiveSuggestionForConsistency() {
compilationHelper
Expand Down

0 comments on commit d3f1a1d

Please sign in to comment.