Skip to content

Commit

Permalink
Expand SimplifyBooleanExpressionVisitor to include String comparisons
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed Dec 18, 2024
1 parent 65c9cf1 commit 2882fdc
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -733,4 +733,37 @@ void foo(String a) {
rewriteRun(java(beforeJava, template.formatted(after)));
}
}

@Issue("https://github.com/openrewrite/rewrite-feature-flags/issues/40")
@Test
void simplifyStringLiteralEqualsStringLiteral() {
rewriteRun(
java(
"""
class A {
{
String foo = "foo";
if ("foo".equals("foo")) {}
if (foo.equals(foo)) {}
if (foo.equals("foo")) {}
if ("foo".equals(foo)) {}
if ("foo".equals("bar")) {}
}
}
""",
"""
class A {
{
String foo = "foo";
if (true) {}
if (true) {}
if (foo.equals("foo")) {}
if ("foo".equals(foo)) {}
if (false) {}
}
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ private J.Binary.Type maybeNegate(J.Binary.Type operator) {
}

private final MethodMatcher isEmpty = new MethodMatcher("java.lang.String isEmpty()");
private final MethodMatcher equals = new MethodMatcher("java.lang.String equals(java.lang.Object)");

@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) {
Expand All @@ -250,6 +251,15 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext execu
select instanceof J.Literal &&
select.getType() == JavaType.Primitive.String) {
return booleanLiteral(method, J.Literal.isLiteralValue(select, ""));
} else if (equals.matches(asMethod)) {
Expression arg = asMethod.getArguments().get(0);
if (arg instanceof J.Literal && select instanceof J.Literal) {
return booleanLiteral(method, ((J.Literal) select).getValue().equals(((J.Literal) arg).getValue()));
} else if (arg instanceof J.Identifier && select instanceof J.Identifier) {
return booleanLiteral(method, SemanticallyEqual.areEqual(select, arg));
} if (arg instanceof J.FieldAccess && select instanceof J.FieldAccess) {
return booleanLiteral(method, SemanticallyEqual.areEqual(select, arg));
}
}
return j;
}
Expand Down

0 comments on commit 2882fdc

Please sign in to comment.