Skip to content

Commit

Permalink
PatternMatchingInstanceof: handle ternaries.
Browse files Browse the repository at this point in the history
How'd I forget them?

PiperOrigin-RevId: 716655410
  • Loading branch information
graememorgan authored and Error Prone Team committed Jan 17, 2025
1 parent 7851fd2 commit b9c272f
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.ParenthesizedTree;
Expand Down Expand Up @@ -194,6 +195,14 @@ private static ImmutableList<Tree> findImpliedStatements(
}
return impliedStatements.build();
}
case CONDITIONAL_EXPRESSION -> {
var conditionalExpression = (ConditionalExpressionTree) parent;
impliedStatements.add(
negated
? conditionalExpression.getFalseExpression()
: conditionalExpression.getTrueExpression());
return impliedStatements.build();
}
default -> {
return impliedStatements.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -591,4 +591,60 @@ public boolean equals(Object o) {
""")
.doTest();
}

@Test
public void conditionalExpression() {
helper
.addInputLines(
"Test.java",
"""
class Test {
private String val;
public String stringify(Object o) {
return o instanceof Test ? ((Test) o).val : "not a test";
}
}
""")
.addOutputLines(
"Test.java",
"""
class Test {
private String val;
public String stringify(Object o) {
return o instanceof Test test ? test.val : "not a test";
}
}
""")
.doTest();
}

@Test
public void conditionalExpression_negated() {
helper
.addInputLines(
"Test.java",
"""
class Test {
private String val;
public String stringify(Object o) {
return !(o instanceof Test) ? "not a test" : ((Test) o).val;
}
}
""")
.addOutputLines(
"Test.java",
"""
class Test {
private String val;
public String stringify(Object o) {
return !(o instanceof Test test) ? "not a test" : test.val;
}
}
""")
.doTest();
}
}

0 comments on commit b9c272f

Please sign in to comment.