diff --git a/src/main/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorgan.java b/src/main/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorgan.java index 901fcff3a4..7698ae8e19 100644 --- a/src/main/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorgan.java +++ b/src/main/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorgan.java @@ -15,6 +15,8 @@ */ package org.openrewrite.staticanalysis; +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; import org.openrewrite.ExecutionContext; import org.openrewrite.Recipe; import org.openrewrite.Tree; @@ -95,13 +97,22 @@ public J visitUnary(J.Unary unary, ExecutionContext ctx) { comments.addAll(parenthesesBinary.getComments()); comments.addAll(binary.getComments()); prefix = prefix.withComments(comments); - binary = binary.withLeft(left).withRight(right).withOperator(newOperator).withPrefix(prefix); - return new ParenthesizeVisitor<>().visit(binary, ctx); + getCursor().getParent().putMessage("MIGHT_NEED_PARENTHESES", true); + return binary.withLeft(left).withRight(right).withOperator(newOperator).withPrefix(prefix); } } return requireNonNull(super.visitUnary(unary, ctx)); } + @Override + public @Nullable J postVisit(@NonNull J tree, ExecutionContext ctx) { + J ret = super.postVisit(tree, ctx); + if (getCursor().pollMessage("MIGHT_NEED_PARENTHESES") != null) { + return new ParenthesizeVisitor<>().visit(ret, ctx); + }; + return ret; + } + private Expression negate(Expression expression) { if (expression instanceof J.Unary) { J.Unary unaryExpr = (J.Unary) expression; diff --git a/src/test/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorganTest.java b/src/test/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorganTest.java index 4d7dbabc72..cbddb64752 100644 --- a/src/test/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorganTest.java +++ b/src/test/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorganTest.java @@ -311,4 +311,25 @@ class Test { ) ); } + + @Test + void mixedOperators2() { + rewriteRun( + //language=java + java( + """ + class Test { + boolean a, b, c; + boolean x = a && !(b && c); + } + """, + """ + class Test { + boolean a, b, c; + boolean x = a && (!b || !c); + } + """ + ) + ); + } }