From b9c272faabfa50a6397626214c97800a7de7ffc4 Mon Sep 17 00:00:00 2001 From: ghm Date: Fri, 17 Jan 2025 07:05:26 -0800 Subject: [PATCH] PatternMatchingInstanceof: handle ternaries. How'd I forget them? PiperOrigin-RevId: 716655410 --- .../PatternMatchingInstanceof.java | 9 +++ .../PatternMatchingInstanceofTest.java | 56 +++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceof.java b/core/src/main/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceof.java index f9bf9062b91..ee6feb5626d 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceof.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceof.java @@ -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; @@ -194,6 +195,14 @@ private static ImmutableList 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(); } diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java index c5fb75b4c41..3357e4082a2 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java @@ -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(); + } }