From e78f08da63cf26d36f091c9ba9df6bd5df5992e5 Mon Sep 17 00:00:00 2001 From: Michael Keppler Date: Fri, 26 Apr 2024 19:15:31 +0200 Subject: [PATCH] Avoid parenthesis only cleanup in SimplifyConstantIfBranchExecution Recognize when the recipe cannot optimize to a constant condition and return the if-condition as before all attempted optimizations. Fixes #286. --- .../SimplifyConstantIfBranchExecution.java | 3 ++- ...SimplifyConstantIfBranchExecutionTest.java | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/openrewrite/staticanalysis/SimplifyConstantIfBranchExecution.java b/src/main/java/org/openrewrite/staticanalysis/SimplifyConstantIfBranchExecution.java index 704a6201f..d57b98487 100644 --- a/src/main/java/org/openrewrite/staticanalysis/SimplifyConstantIfBranchExecution.java +++ b/src/main/java/org/openrewrite/staticanalysis/SimplifyConstantIfBranchExecution.java @@ -87,6 +87,7 @@ private 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 cp = cleanupBooleanExpression(if__.getIfCondition(), ctx); if__ = if__.withIfCondition(cp); @@ -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. diff --git a/src/test/java/org/openrewrite/staticanalysis/SimplifyConstantIfBranchExecutionTest.java b/src/test/java/org/openrewrite/staticanalysis/SimplifyConstantIfBranchExecutionTest.java index 9393e24df..612da862e 100644 --- a/src/test/java/org/openrewrite/staticanalysis/SimplifyConstantIfBranchExecutionTest.java +++ b/src/test/java/org/openrewrite/staticanalysis/SimplifyConstantIfBranchExecutionTest.java @@ -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() {