Skip to content

Commit

Permalink
Avoid parenthesis only cleanup in SimplifyConstantIfBranchExecution (#…
Browse files Browse the repository at this point in the history
…287)

Recognize when the recipe cannot optimize to a constant condition and
return the if-condition as before all attempted optimizations.

Fixes #286.
  • Loading branch information
Bananeweizen authored Apr 26, 2024
1 parent 456f278 commit c2fffaf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ private <E extends Expression> E cleanupBooleanExpression(
@Override
public J visitIf(J.If if_, ExecutionContext ctx) {
J.If if__ = (J.If) super.visitIf(if_, ctx);
J.If ifBeforeCleanup = if__;

J.ControlParentheses<Expression> cp = cleanupBooleanExpression(if__.getIfCondition(), ctx);
if__ = if__.withIfCondition(cp);
Expand All @@ -104,7 +105,7 @@ public J visitIf(J.If if_, ExecutionContext ctx) {

// The simplification process did not result in resolving to a single 'true' or 'false' value
if (!compileTimeConstantBoolean.isPresent()) {
return if__; // Return the visited `if`
return ifBeforeCleanup; // Return the visited `if`
} else if (compileTimeConstantBoolean.get()) {
// True branch
// Only keep the `then` branch, and remove the `else` branch.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,26 @@ public void test() {
);
}

@Test
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/286")
void doNotChangeParenthesisOnly() {
rewriteRun(
//language=java
java(
"""
public class A {
public void test() {
boolean b = true;
if (!(b)) {
System.out.println("hello");
}
}
}
"""
)
);
}

@DocumentExample
@Test
void simplifyConstantIfTrue() {
Expand Down

0 comments on commit c2fffaf

Please sign in to comment.