From 53c638d15f3e6f7e4ac6d01ba9f1ae9194f6e838 Mon Sep 17 00:00:00 2001 From: cpovirk Date: Thu, 5 Dec 2024 09:05:12 -0800 Subject: [PATCH] Clarify why our check for `<` and friends works. (very belated followup to https://github.com/google/error-prone/issues/274) PiperOrigin-RevId: 703135821 --- .../bugpatterns/ComparisonOutOfRange.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonOutOfRange.java b/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonOutOfRange.java index a166cf8cee3..c73cefa7ca3 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonOutOfRange.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/ComparisonOutOfRange.java @@ -103,10 +103,10 @@ Description matchConstantResult() { return switch (tree.getKind()) { case EQUAL_TO -> matchOutOfBounds(/* willEvaluateTo= */ false); case NOT_EQUAL_TO -> matchOutOfBounds(/* willEvaluateTo= */ true); - case LESS_THAN -> matchMinAndMaxHaveSameResult(cmp -> cmp < 0); - case LESS_THAN_EQUAL -> matchMinAndMaxHaveSameResult(cmp -> cmp <= 0); - case GREATER_THAN -> matchMinAndMaxHaveSameResult(cmp -> cmp > 0); - case GREATER_THAN_EQUAL -> matchMinAndMaxHaveSameResult(cmp -> cmp >= 0); + case LESS_THAN -> matchDoesNotSplitNumberLine(cmp -> cmp < 0); + case LESS_THAN_EQUAL -> matchDoesNotSplitNumberLine(cmp -> cmp <= 0); + case GREATER_THAN -> matchDoesNotSplitNumberLine(cmp -> cmp > 0); + case GREATER_THAN_EQUAL -> matchDoesNotSplitNumberLine(cmp -> cmp >= 0); default -> NO_MATCH; }; } @@ -118,13 +118,14 @@ Description matchOutOfBounds(boolean willEvaluateTo) { } /* - * If `minValue < constant` and `maxValue < constant` are both true, then `anything < - * constant` is true. + * A proper "<" comparison to `constant` splits the number line into two pieces: On one + * side, the comparison is true; on the other, false. (Ditto for "<=," ">," and ">=.") * - * The same holds if we replace "<" with another inequality operator, if we replace - * "true" with "false," or if we move "constant" to the left operand. + * So, if the comparison returns the *same* value for the far left side of the number + * line as it does for the far right side, then the comparison is out of range (e.g., + * "someInt < Long.MAX_VALUE"). */ - Description matchMinAndMaxHaveSameResult(IntPredicate op) { + Description matchDoesNotSplitNumberLine(IntPredicate op) { boolean minResult; boolean maxResult; if (constant == tree.getRightOperand()) {