Skip to content

Commit

Permalink
ignore equals in redundant if for boolean check
Browse files Browse the repository at this point in the history
  • Loading branch information
Luro02 committed Apr 6, 2024
1 parent f2d04e1 commit 6e603b3
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,16 @@
import spoon.reflect.code.CtIf;
import spoon.reflect.code.CtReturn;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtMethod;

import java.util.List;
import java.util.Map;
import java.util.Set;

@ExecutableCheck(reportedProblems = { ProblemType.REDUNDANT_IF_FOR_BOOLEAN })
public class RedundantIfForBooleanCheck extends IntegratedCheck {
private static final Set<String> METHODS_TO_IGNORE = Set.of("equals", "hashCode");

private String makeSuggestion(CtExpression<?> ctExpression, Effect thenEffect, Effect elseEffect) {
if (thenEffect instanceof AssignmentEffect thenAssignment && elseEffect instanceof AssignmentEffect) {
return "%s = %s".formatted(
Expand Down Expand Up @@ -129,8 +133,15 @@ protected void check(StaticAnalysis staticAnalysis, DynamicAnalysis dynamicAnaly
staticAnalysis.processWith(new AbstractProcessor<CtBlock<?>>() {
@Override
public void process(CtBlock<?> block) {
CtMethod<?> parentMethod = block.getParent(CtMethod.class);
if (parentMethod != null && METHODS_TO_IGNORE.contains(parentMethod.getSimpleName())) {
return;
}

List<CtStatement> statements = SpoonUtil.getEffectiveStatements(block);

// TODO: write test

for (int i = 0; i < statements.size(); i++) {
CtStatement statement = statements.get(i);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ public void process(CtUnaryOperator<?> ctUnaryOperator) {
return;
}

// TODO: do the same as in RepeatedMathOperationCheck

addLocalProblem(
ctUnaryOperator,
new LocalizedMessage(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,32 @@ boolean doB(int a) {
problems.assertExhausted();
}


@Test
void testInEquals() throws IOException, LinterException {
ProblemIterator problems = this.checkIterator(StringSourceInfo.fromSourceString(
JavaVersion.JAVA_17,
"Test",
"""
public class Test {
int a;
@Override
public boolean equals(Object other) {
if (a == 0) {
return a == 1;
}
return a == 2;
}
}
"""
), PROBLEM_TYPES);

problems.assertExhausted();
}


@Test
void testIgnoreInvalidIfWithValidElseIfElse() throws IOException, LinterException {
ProblemIterator problems = this.checkIterator(StringSourceInfo.fromSourceString(
Expand Down

0 comments on commit 6e603b3

Please sign in to comment.