Skip to content

Commit

Permalink
Simplify constant ternary expressions too (#4617)
Browse files Browse the repository at this point in the history
* Simplify constant ternary expressions too

- For openrewrite/rewrite-static-analysis#258

* Show additional cases covered
  • Loading branch information
timtebeek authored Oct 27, 2024
1 parent 36efd20 commit 4e2eae9
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,64 @@ public class A {
);
}

@Test
void ternaryConstant() {
rewriteRun(
java(
"""
class A {
String alwaysA() {
return true ? "a" : "b";
}
String alwaysA2() {
return (true) ? "a" : "b";
}
String alwaysA3() {
return (true ? "a" : "b");
}
String alwaysA4() {
return !false ? "a" : "b";
}
String alwaysA5() {
return (!false) ? "a" : "b";
}
String alwaysA6() {
return !(false) ? "a" : "b";
}
String alwaysB() {
return false ? "a" : "b";
}
}
""",
"""
class A {
String alwaysA() {
return "a";
}
String alwaysA2() {
return "a";
}
String alwaysA3() {
return "a";
}
String alwaysA4() {
return "a";
}
String alwaysA5() {
return "a";
}
String alwaysA6() {
return "a";
}
String alwaysB() {
return "b";
}
}
"""
)
);
}

@Test
void ternaryDoubleNegation() {
rewriteRun(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,21 @@ public J visitTernary(J.Ternary ternary, ExecutionContext executionContext) {
.withTruePart(asTernary.getFalsePart())
.withFalsePart(asTernary.getTruePart());
}
} else if (asTernary.getCondition() instanceof J.Literal) {
if (isLiteralTrue(asTernary.getCondition())) {
j = asTernary.getTruePart();
} else if (isLiteralFalse(asTernary.getCondition())) {
j = asTernary.getFalsePart();
}
} else if (asTernary.getCondition() instanceof J.Parentheses) {
J.Parentheses<Expression> parenthesized = (J.Parentheses<Expression>) asTernary.getCondition();
if (parenthesized.getTree() instanceof J.Literal) {
if (isLiteralTrue(parenthesized.getTree())) {
j = asTernary.getTruePart();
} else if (isLiteralFalse(parenthesized.getTree())) {
j = asTernary.getFalsePart();
}
}
}
}
return j;
Expand Down

0 comments on commit 4e2eae9

Please sign in to comment.