Skip to content

Commit aa8d0c7

Browse files
SimplifyBooleanExpressionWithDeMorgan - Add parens when converting to OR (#660)
* Add parens when converting to OR * ctx Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * ctx fixed --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 105f102 commit aa8d0c7

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/main/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorgan.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
*/
1616
package org.openrewrite.staticanalysis;
1717

18+
import org.jspecify.annotations.NonNull;
19+
import org.jspecify.annotations.Nullable;
1820
import org.openrewrite.ExecutionContext;
1921
import org.openrewrite.Recipe;
2022
import org.openrewrite.Tree;
@@ -95,13 +97,22 @@ public J visitUnary(J.Unary unary, ExecutionContext ctx) {
9597
comments.addAll(parenthesesBinary.getComments());
9698
comments.addAll(binary.getComments());
9799
prefix = prefix.withComments(comments);
98-
binary = binary.withLeft(left).withRight(right).withOperator(newOperator).withPrefix(prefix);
99-
return new ParenthesizeVisitor<>().visit(binary, ctx);
100+
getCursor().getParent().putMessage("MIGHT_NEED_PARENTHESES", true);
101+
return binary.withLeft(left).withRight(right).withOperator(newOperator).withPrefix(prefix);
100102
}
101103
}
102104
return requireNonNull(super.visitUnary(unary, ctx));
103105
}
104106

107+
@Override
108+
public @Nullable J postVisit(@NonNull J tree, ExecutionContext ctx) {
109+
J ret = super.postVisit(tree, ctx);
110+
if (getCursor().pollMessage("MIGHT_NEED_PARENTHESES") != null) {
111+
return new ParenthesizeVisitor<>().visit(ret, ctx);
112+
};
113+
return ret;
114+
}
115+
105116
private Expression negate(Expression expression) {
106117
if (expression instanceof J.Unary) {
107118
J.Unary unaryExpr = (J.Unary) expression;

src/test/java/org/openrewrite/staticanalysis/SimplifyBooleanExpressionWithDeMorganTest.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,4 +311,25 @@ class Test {
311311
)
312312
);
313313
}
314+
315+
@Test
316+
void mixedOperators2() {
317+
rewriteRun(
318+
//language=java
319+
java(
320+
"""
321+
class Test {
322+
boolean a, b, c;
323+
boolean x = a && !(b && c);
324+
}
325+
""",
326+
"""
327+
class Test {
328+
boolean a, b, c;
329+
boolean x = a && (!b || !c);
330+
}
331+
"""
332+
)
333+
);
334+
}
314335
}

0 commit comments

Comments
 (0)