Skip to content

[PatternMatchingInstanceof] Make negated matches optional #4930

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.InstanceOfTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
Expand All @@ -55,6 +56,7 @@
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.lang.model.SourceVersion;
import org.jspecify.annotations.Nullable;

Expand All @@ -64,6 +66,14 @@
summary = "This code can be simplified to use a pattern-matching instanceof.")
public final class PatternMatchingInstanceof extends BugChecker implements InstanceOfTreeMatcher {

private final boolean enableNegatedMatches;

@Inject
PatternMatchingInstanceof(ErrorProneFlags flags) {
this.enableNegatedMatches =
flags.getBoolean("PatternMatchingInstanceof:EnableNegatedMatches").orElse(true);
}

@Override
public Description matchInstanceOf(InstanceOfTree instanceOfTree, VisitorState state) {
if (!supportsPatternMatchingInstanceof(state.context)) {
Expand Down Expand Up @@ -162,7 +172,7 @@ private static String generateVariableName(Type targetType, VisitorState state)
}

/** Finds trees which are implied by the {@code instanceOfTree}. */
private static ImmutableList<Tree> findImpliedStatements(
private ImmutableList<Tree> findImpliedStatements(
InstanceOfTree tree, VisitorState state) {
Tree last = tree;
boolean negated = false;
Expand Down Expand Up @@ -198,15 +208,18 @@ private static ImmutableList<Tree> findImpliedStatements(
return impliedStatements.build();
}
if (negated) {
if (ifTree.getElseStatement() != null) {
impliedStatements.add(ifTree.getElseStatement());
}
if (!Reachability.canCompleteNormally(ifTree.getThenStatement())) {
var pparent = parentPath.getParentPath().getLeaf();
if (pparent instanceof BlockTree blockTree) {
var index = blockTree.getStatements().indexOf(ifTree);
impliedStatements.addAll(
blockTree.getStatements().subList(index + 1, blockTree.getStatements().size()));
if (enableNegatedMatches) {
if (ifTree.getElseStatement() != null) {
impliedStatements.add(ifTree.getElseStatement());
}
if (!Reachability.canCompleteNormally(ifTree.getThenStatement())) {
var pparent = parentPath.getParentPath().getLeaf();
if (pparent instanceof BlockTree blockTree) {
var index = blockTree.getStatements().indexOf(ifTree);
impliedStatements.addAll(
blockTree.getStatements().subList(
index + 1, blockTree.getStatements().size()));
}
}
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,36 @@ void test(Object o) {
.doTest();
}

@Test
public void positive_disabledNegation() {
helper
.addInputLines(
"Test.java",
"""
class Test {
void test(Object o) {
if (o instanceof Test) {
Test test = (Test) o;
test(test);
}
}
}
""")
.addOutputLines(
"Test.java",
"""
class Test {
void test(Object o) {
if (o instanceof Test test) {
test(test);
}
}
}
""")
.setArgs("-XepOpt:PatternMatchingInstanceof:EnableNegatedMatches=false")
.doTest();
}

@Test
public void negatedIf() {
helper
Expand Down Expand Up @@ -88,6 +118,27 @@ void test(Object o) {
.doTest();
}

@Test
public void negatedIf_disabledNegation() {
helper
.addInputLines(
"Test.java",
"""
class Test {
void test(Object o) {
if (!(o instanceof Test)) {
} else {
Test test = (Test) o;
test(test);
}
}
}
""")
.expectUnchanged()
.setArgs("-XepOpt:PatternMatchingInstanceof:EnableNegatedMatches=false")
.doTest();
}

@Test
public void negatedIf_withOrs() {
helper
Expand Down Expand Up @@ -150,6 +201,27 @@ void test(Object o) {
.doTest();
}

@Test
public void negatedIfWithReturn_disabledNegation() {
helper
.addInputLines(
"Test.java",
"""
class Test {
void test(Object o) {
if (!(o instanceof Test)) {
return;
}
Test test = (Test) o;
test(test);
}
}
""")
.expectUnchanged()
.setArgs("-XepOpt:PatternMatchingInstanceof:EnableNegatedMatches=false")
.doTest();
}

@Test
public void negatedIf_butNoDefiniteReturn_noFinding() {
helper
Expand Down Expand Up @@ -581,6 +653,47 @@ public boolean equals(Object o) {
.doTest();
}

@Test
public void withinIfCondition_andUsedAfter_disabledNegation() {
helper
.addInputLines(
"Test.java",
"""
class Test {
private final int x = 0;
private final int y = 1;

@Override
public boolean equals(Object o) {
if (!(o instanceof Test) || ((Test) o).x != this.x) {
return false;
}
Test other = (Test) o;
return other.y == this.y;
}
}
""")
.addOutputLines(
"Test.java",
"""
class Test {
private final int x = 0;
private final int y = 1;

@Override
public boolean equals(Object o) {
if (!(o instanceof Test test) || test.x != this.x) {
return false;
}
Test other = (Test) o;
return other.y == this.y;
}
}
""")
.setArgs("-XepOpt:PatternMatchingInstanceof:EnableNegatedMatches=false")
.doTest();
}

@Test
public void conditionalExpression() {
helper
Expand Down
6 changes: 6 additions & 0 deletions docs/bugpattern/PatternMatchingInstanceof.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,11 @@ void handle(Object o) {
}
```

If the flag `-XepOpt:PatternMatchingInstanceof:EnableNegatedMatches=false` is used,
only casts that are in the same expression as the instanceof
or in the block that starts with the instanceof are rewritten,
but casts inside else branches or below an if statement with a negated instanceof
are left unchanged.

For more information on pattern matching and `instanceof`, see
[Pattern Matching for the instanceof Operator](https://docs.oracle.com/en/java/javase/21/language/pattern-matching-instanceof.html)