-
Notifications
You must be signed in to change notification settings - Fork 723
SONARJAVA-6686 Implement new rule S2198: Unnecessary mathematical comparisons #5845
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
romainbrenguier
wants to merge
5
commits into
master
Choose a base branch
from
new-rule/SONARJAVA-6686-S2198
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
bac0344
Implement new rule S2198
romainbrenguier 7c25038
Update S2198 rule metadata and add to Sonar way profile
romainbrenguier 5d44d08
Fix sonar issues in UselessMathematicalComparisonCheck
romainbrenguier a1ce778
Update ruling results for PR #5845 (#5846)
github-actions[bot] d0a0abe
Update ruling results for PR #5845 (#5856)
github-actions[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "ruleKey": "S2198", | ||
| "hasTruePositives": true, | ||
| "falseNegatives": 0, | ||
| "falsePositives": 0 | ||
| } |
6 changes: 6 additions & 0 deletions
6
its/ruling/src/test/resources/eclipse-jetty-similar-to-main/java-S2198.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "org.eclipse.jetty:jetty-project:jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java": [ | ||
| 876, | ||
| 890 | ||
| ] | ||
| } |
17 changes: 17 additions & 0 deletions
17
its/ruling/src/test/resources/eclipse-jetty/java-S2198.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| { | ||
| "org.eclipse.jetty:jetty-project:jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java": [ | ||
| 876, | ||
| 890 | ||
| ], | ||
| "org.eclipse.jetty:jetty-project:jetty-util/src/main/java/org/eclipse/jetty/util/ByteArrayISO8859Writer.java": [ | ||
| 107, | ||
| 124, | ||
| 142, | ||
| 167, | ||
| 185 | ||
| ], | ||
| "org.eclipse.jetty:jetty-project:jetty-util/src/main/java/org/eclipse/jetty/util/TreeTrie.java": [ | ||
| 98, | ||
| 135 | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| { | ||
| "com.google.guava:guava:src/com/google/common/net/InetAddresses.java": [ | ||
| 907 | ||
| ] | ||
| } |
116 changes: 116 additions & 0 deletions
116
...s-test-sources/default/src/main/java/checks/UselessMathematicalComparisonCheckSample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| package checks; | ||
|
|
||
| class UselessMathematicalComparisonCheckSample { | ||
|
|
||
| static final int CONSTANT_200 = 200; | ||
|
|
||
| void byteComparisons(byte b) { | ||
| if (b > 200) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (b > 127) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (b >= 128) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (b < -200) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (b < -128) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (b <= -129) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (b == 200) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (b == -200) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
|
|
||
| if (b < 200) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (b <= 127) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (b >= -128) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (b >= -200) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (b > -129) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (b != 200) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
|
|
||
| if (b > 100) {} // Compliant - 100 within byte range | ||
| if (b < -100) {} // Compliant | ||
| if (b == 0) {} // Compliant | ||
| if (b <= 126) {} // Compliant - 126 < max, not always true | ||
| } | ||
|
|
||
| void shortComparisons(short s) { | ||
| if (s > 40000) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (s >= 32768) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (s < -32769) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (s <= -32769) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (s == 40000) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
|
|
||
| if (s < 32768) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (s <= 32767) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (s >= -32768) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (s != 40000) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
|
|
||
| if (s > 30000) {} // Compliant - within range | ||
| if (s < -30000) {} // Compliant | ||
| } | ||
|
|
||
| void charComparisons(char c) { | ||
| if (c < 0) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (c > 65535) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (c >= 65536) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (c < -1) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (c == -1) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (c == 65536) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
|
|
||
| if (c >= 0) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (c <= 65535) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (c != -1) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
|
|
||
| if (c > 1000) {} // Compliant - within range | ||
| if (c < 60000) {} // Compliant | ||
| } | ||
|
|
||
| void intComparisons(int i) { | ||
| if (i > 2147483648L) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (i >= 2147483648L) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (i < -2147483649L) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (i == 2147483648L) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
|
|
||
| if (i < 2147483648L) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (i <= 2147483647L) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (i >= -2147483648L) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (i != 2147483648L) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
|
|
||
| if (i > 1000000) {} // Compliant | ||
| if (i < -1000000) {} // Compliant | ||
| } | ||
|
|
||
| void reversedOperands(byte b) { | ||
| if (200 < b) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (200 <= b) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (-200 > b) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (200 > b) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (200 >= b) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| if (200 == b) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (200 != b) {} // Noncompliant {{Remove this comparison; it will always return true.}} | ||
| } | ||
|
|
||
| void longVariable(long l) { | ||
| if (l > 2147483648L) {} // Compliant - long can hold this value | ||
| if (l < -2147483649L) {} // Compliant | ||
| } | ||
|
|
||
| void floatVariable(float f) { | ||
| if (f > 1000000) {} // Compliant - float/double not checked | ||
| } | ||
|
|
||
| void doubleVariable(double d) { | ||
| if (d > 1000000) {} // Compliant - float/double not checked | ||
| } | ||
|
|
||
| void intVariableWithinRange(int b) { | ||
| if (b > 200) {} // Compliant - int can hold 200 | ||
| } | ||
|
|
||
| void parenthesizedExpressions(byte b) { | ||
| if ((b) > 200) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| if (b > (200)) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| } | ||
|
|
||
| void constantExpressions(byte b) { | ||
| if (b > CONSTANT_200) {} // Noncompliant {{Remove this comparison; it will always return false.}} | ||
| } | ||
|
|
||
| void twoVariables(byte a, byte b) { | ||
| if (a > b) {} // Compliant - comparing two variables | ||
| } | ||
| } | ||
177 changes: 177 additions & 0 deletions
177
java-checks/src/main/java/org/sonar/java/checks/UselessMathematicalComparisonCheck.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,177 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Map; | ||
| import javax.annotation.Nullable; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.java.model.ExpressionUtils; | ||
| import org.sonar.java.model.LiteralUtils; | ||
| import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; | ||
| import org.sonar.plugins.java.api.semantic.Type; | ||
| import org.sonar.plugins.java.api.tree.BinaryExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.ExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
| import org.sonar.plugins.java.api.tree.Tree.Kind; | ||
|
|
||
| @Rule(key = "S2198") | ||
| public class UselessMathematicalComparisonCheck extends IssuableSubscriptionVisitor { | ||
|
|
||
| private static final Map<Type.Primitives, long[]> TYPE_BOUNDS = Map.of( | ||
| Type.Primitives.BYTE, new long[] {Byte.MIN_VALUE, Byte.MAX_VALUE}, | ||
| Type.Primitives.SHORT, new long[] {Short.MIN_VALUE, Short.MAX_VALUE}, | ||
| Type.Primitives.CHAR, new long[] {Character.MIN_VALUE, Character.MAX_VALUE}, | ||
| Type.Primitives.INT, new long[] {Integer.MIN_VALUE, Integer.MAX_VALUE} | ||
| ); | ||
|
|
||
| @Override | ||
| public List<Kind> nodesToVisit() { | ||
| return List.of( | ||
| Kind.GREATER_THAN, | ||
| Kind.GREATER_THAN_OR_EQUAL_TO, | ||
| Kind.LESS_THAN, | ||
| Kind.LESS_THAN_OR_EQUAL_TO, | ||
| Kind.EQUAL_TO, | ||
| Kind.NOT_EQUAL_TO); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(Tree tree) { | ||
| BinaryExpressionTree binaryExpression = (BinaryExpressionTree) tree; | ||
| ExpressionTree leftOperand = ExpressionUtils.skipParentheses(binaryExpression.leftOperand()); | ||
| ExpressionTree rightOperand = ExpressionUtils.skipParentheses(binaryExpression.rightOperand()); | ||
|
|
||
| // Try left=variable, right=constant | ||
| Boolean result = evaluate(leftOperand, rightOperand, binaryExpression.kind(), false); | ||
| if (result == null) { | ||
| // Try left=constant, right=variable (reversed) | ||
| result = evaluate(rightOperand, leftOperand, binaryExpression.kind(), true); | ||
| } | ||
|
|
||
| if (result != null) { | ||
| reportIssue(binaryExpression, "Remove this comparison; it will always return " + result + "."); | ||
| } | ||
| } | ||
|
|
||
| @Nullable | ||
| private static Boolean evaluate(ExpressionTree variableCandidate, ExpressionTree constantCandidate, Kind operatorKind, boolean reversed) { | ||
| long[] bounds = resolveTypeBounds(variableCandidate); | ||
| if (bounds == null) { | ||
| return null; | ||
| } | ||
| Long constantValue = resolveConstantValue(constantCandidate); | ||
| if (constantValue == null) { | ||
| return null; | ||
| } | ||
| long min = bounds[0]; | ||
| long max = bounds[1]; | ||
| Kind normalizedKind = reversed ? reverseOperator(operatorKind) : operatorKind; | ||
| return evaluateComparison(normalizedKind, min, max, constantValue); | ||
| } | ||
|
|
||
| @Nullable | ||
| private static long[] resolveTypeBounds(ExpressionTree expression) { | ||
| Type type = expression.symbolType(); | ||
| for (Map.Entry<Type.Primitives, long[]> entry : TYPE_BOUNDS.entrySet()) { | ||
| if (type.isPrimitive(entry.getKey())) { | ||
| return entry.getValue(); | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| @Nullable | ||
| private static Long resolveConstantValue(ExpressionTree expression) { | ||
| Long literal = LiteralUtils.longLiteralValue(expression); | ||
| if (literal != null) { | ||
| return literal; | ||
| } | ||
| Object constant = ExpressionUtils.resolveAsConstant(expression); | ||
| if (constant instanceof Integer intVal) { | ||
| return intVal.longValue(); | ||
| } | ||
| if (constant instanceof Long longVal) { | ||
| return longVal; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| private static Kind reverseOperator(Kind kind) { | ||
| return switch (kind) { | ||
| case GREATER_THAN -> Kind.LESS_THAN; | ||
| case GREATER_THAN_OR_EQUAL_TO -> Kind.LESS_THAN_OR_EQUAL_TO; | ||
| case LESS_THAN -> Kind.GREATER_THAN; | ||
| case LESS_THAN_OR_EQUAL_TO -> Kind.GREATER_THAN_OR_EQUAL_TO; | ||
| // EQUAL_TO, NOT_EQUAL_TO are symmetric | ||
| default -> kind; | ||
| }; | ||
| } | ||
|
|
||
| @Nullable | ||
| private static Boolean evaluateComparison(Kind normalizedKind, long min, long max, long constant) { | ||
| return switch (normalizedKind) { | ||
| case GREATER_THAN -> evaluateGreaterThan(min, max, constant); | ||
| case GREATER_THAN_OR_EQUAL_TO -> evaluateGreaterThanOrEqual(min, max, constant); | ||
| case LESS_THAN -> evaluateLessThan(min, max, constant); | ||
| case LESS_THAN_OR_EQUAL_TO -> evaluateLessThanOrEqual(min, max, constant); | ||
| case EQUAL_TO -> (constant < min || constant > max) ? Boolean.FALSE : null; | ||
| case NOT_EQUAL_TO -> (constant < min || constant > max) ? Boolean.TRUE : null; | ||
| default -> null; | ||
| }; | ||
| } | ||
|
|
||
| @Nullable | ||
| private static Boolean evaluateGreaterThan(long min, long max, long constant) { | ||
| if (constant >= max) { | ||
| return Boolean.FALSE; | ||
| } else if (constant < min) { | ||
| return Boolean.TRUE; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| @Nullable | ||
| private static Boolean evaluateGreaterThanOrEqual(long min, long max, long constant) { | ||
| if (constant > max) { | ||
| return Boolean.FALSE; | ||
| } else if (constant <= min) { | ||
| return Boolean.TRUE; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| @Nullable | ||
| private static Boolean evaluateLessThan(long min, long max, long constant) { | ||
| if (constant <= min) { | ||
| return Boolean.FALSE; | ||
| } else if (constant > max) { | ||
| return Boolean.TRUE; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| @Nullable | ||
| private static Boolean evaluateLessThanOrEqual(long min, long max, long constant) { | ||
| if (constant < min) { | ||
| return Boolean.FALSE; | ||
| } else if (constant >= max) { | ||
| return Boolean.TRUE; | ||
| } | ||
| return null; | ||
| } | ||
| } |
33 changes: 33 additions & 0 deletions
33
java-checks/src/test/java/org/sonar/java/checks/UselessMathematicalComparisonCheckTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.sonar.java.checks.verifier.CheckVerifier; | ||
|
|
||
| import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; | ||
|
|
||
| class UselessMathematicalComparisonCheckTest { | ||
|
|
||
| @Test | ||
| void test() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/UselessMathematicalComparisonCheckSample.java")) | ||
| .withCheck(new UselessMathematicalComparisonCheck()) | ||
| .verifyIssues(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.