Skip to content

Commit

Permalink
fix bug in use modulo operator
Browse files Browse the repository at this point in the history
  • Loading branch information
Luro02 committed Apr 18, 2024
1 parent a3d1a74 commit cc2ccc3
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,23 @@ private void checkModulo(CtIf ctIf) {
// is equal to
//
// variable %= 3;
if (Set.of(BinaryOperatorKind.GE, BinaryOperatorKind.EQ).contains(condition.getKind())) {
CtExpression<?> right = condition.getRightHandOperand();
CtExpression<?> checkedValue = condition.getRightHandOperand();

// for boxed types, one could check if the value is null,
// for which the suggestion `a %= null` would not make sense
if (SpoonUtil.isNullLiteral(checkedValue)) {
return;
}

if (Set.of(BinaryOperatorKind.GE, BinaryOperatorKind.EQ).contains(condition.getKind())) {
addLocalProblem(
ctIf,
new LocalizedMessage(
"common-reimplementation",
Map.of(
"suggestion", "%s %%= %s".formatted(
assignedVariable,
right
checkedValue
)
)
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,45 @@ public static int adjust(int value, int limit) {
}
problems.assertExhausted();
}

@Test
void testBoxedEqualsNull() throws LinterException, IOException {
ProblemIterator problems = this.checkIterator(StringSourceInfo.fromSourceString(
JavaVersion.JAVA_17,
"Main",
"""
public class Main {
public static void test(Integer i) {
if (i == null) {
i = 0;
}
}
}
"""
), PROBLEM_TYPES);

problems.assertExhausted();
}

@Test
void testBoxedInteger() throws LinterException, IOException {
ProblemIterator problems = this.checkIterator(StringSourceInfo.fromSourceString(
JavaVersion.JAVA_17,
"Main",
"""
public class Main {
public static void test(Integer i) {
Integer j = 7;
if (i == j) {
i = 0;
}
}
}
"""
), PROBLEM_TYPES);

assertReimplementation(problems.next(), "i %= j");

problems.assertExhausted();
}
}

0 comments on commit cc2ccc3

Please sign in to comment.