-
Notifications
You must be signed in to change notification settings - Fork 747
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add an initial check to simplify pattern matching instanceofs.
This only handles the simplest case of, ``` if (x instanceof Foo) { var foo = (Foo) x; ... } ``` While we should also be catching: ``` if (!(x instanceof Foo)) { ... } ... var foo = (Foo) x; ``` That's certainly a bit harder to do, though! PiperOrigin-RevId: 627010635
- Loading branch information
1 parent
bc3309a
commit e3f218a
Showing
4 changed files
with
279 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
121 changes: 121 additions & 0 deletions
121
core/src/main/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceof.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
/* | ||
* Copyright 2024 The Error Prone Authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.google.errorprone.bugpatterns; | ||
|
||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; | ||
import static com.google.errorprone.matchers.Description.NO_MATCH; | ||
import static com.google.errorprone.util.ASTHelpers.getSymbol; | ||
import static com.google.errorprone.util.ASTHelpers.getType; | ||
import static com.google.errorprone.util.ASTHelpers.isSameType; | ||
import static com.google.errorprone.util.SourceVersion.supportsPatternMatchingInstanceof; | ||
|
||
import com.google.common.collect.ImmutableSet; | ||
import com.google.errorprone.BugPattern; | ||
import com.google.errorprone.VisitorState; | ||
import com.google.errorprone.bugpatterns.BugChecker.IfTreeMatcher; | ||
import com.google.errorprone.fixes.SuggestedFix; | ||
import com.google.errorprone.matchers.Description; | ||
import com.sun.source.tree.BinaryTree; | ||
import com.sun.source.tree.BlockTree; | ||
import com.sun.source.tree.ExpressionTree; | ||
import com.sun.source.tree.IfTree; | ||
import com.sun.source.tree.InstanceOfTree; | ||
import com.sun.source.tree.ParenthesizedTree; | ||
import com.sun.source.tree.Tree.Kind; | ||
import com.sun.source.tree.TypeCastTree; | ||
import com.sun.source.tree.VariableTree; | ||
import com.sun.source.util.SimpleTreeVisitor; | ||
import com.sun.tools.javac.code.Symbol.VarSymbol; | ||
|
||
/** A BugPattern; see the summary. */ | ||
@BugPattern( | ||
severity = WARNING, | ||
summary = "This code can be simplified to use a pattern-matching instanceof.") | ||
public final class PatternMatchingInstanceof extends BugChecker implements IfTreeMatcher { | ||
@Override | ||
public Description matchIf(IfTree tree, VisitorState state) { | ||
if (!supportsPatternMatchingInstanceof(state.context)) { | ||
return NO_MATCH; | ||
} | ||
ImmutableSet<InstanceOfTree> instanceofChecks = scanForInstanceOf(tree.getCondition()); | ||
if (instanceofChecks.isEmpty()) { | ||
return NO_MATCH; | ||
} | ||
var body = tree.getThenStatement(); | ||
if (!(body instanceof BlockTree)) { | ||
return NO_MATCH; | ||
} | ||
var block = (BlockTree) body; | ||
if (block.getStatements().isEmpty()) { | ||
return NO_MATCH; | ||
} | ||
var firstStatement = block.getStatements().get(0); | ||
if (!(firstStatement instanceof VariableTree)) { | ||
return NO_MATCH; | ||
} | ||
var variableTree = (VariableTree) firstStatement; | ||
if (!(variableTree.getInitializer() instanceof TypeCastTree)) { | ||
return NO_MATCH; | ||
} | ||
var typeCast = (TypeCastTree) variableTree.getInitializer(); | ||
var matchingInstanceof = | ||
instanceofChecks.stream() | ||
.filter( | ||
i -> | ||
isSameType(getType(i.getType()), getType(typeCast.getType()), state) | ||
&& getSymbol(i.getExpression()) instanceof VarSymbol | ||
&& getSymbol(i.getExpression()).equals(getSymbol(typeCast.getExpression()))) | ||
.findFirst() | ||
.orElse(null); | ||
if (matchingInstanceof == null) { | ||
return NO_MATCH; | ||
} | ||
return describeMatch( | ||
firstStatement, | ||
SuggestedFix.builder() | ||
.delete(variableTree) | ||
.postfixWith(matchingInstanceof, " " + variableTree.getName().toString()) | ||
.build()); | ||
} | ||
|
||
private ImmutableSet<InstanceOfTree> scanForInstanceOf(ExpressionTree condition) { | ||
ImmutableSet.Builder<InstanceOfTree> instanceOfs = ImmutableSet.builder(); | ||
new SimpleTreeVisitor<Void, Void>() { | ||
@Override | ||
public Void visitParenthesized(ParenthesizedTree tree, Void unused) { | ||
return visit(tree.getExpression(), null); | ||
} | ||
|
||
@Override | ||
public Void visitBinary(BinaryTree tree, Void unused) { | ||
if (tree.getKind() != Kind.CONDITIONAL_AND) { | ||
return null; | ||
} | ||
visit(tree.getLeftOperand(), null); | ||
visit(tree.getRightOperand(), null); | ||
return null; | ||
} | ||
|
||
@Override | ||
public Void visitInstanceOf(InstanceOfTree tree, Void unused) { | ||
instanceOfs.add(tree); | ||
return null; | ||
} | ||
}.visit(condition, null); | ||
return instanceOfs.build(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
151 changes: 151 additions & 0 deletions
151
core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
/* | ||
* Copyright 2024 The Error Prone Authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.google.errorprone.bugpatterns; | ||
|
||
import static com.google.common.truth.TruthJUnit.assume; | ||
|
||
import com.google.errorprone.BugCheckerRefactoringTestHelper; | ||
import com.google.errorprone.util.RuntimeVersion; | ||
import org.junit.Test; | ||
import org.junit.runner.RunWith; | ||
import org.junit.runners.JUnit4; | ||
|
||
@RunWith(JUnit4.class) | ||
public final class PatternMatchingInstanceofTest { | ||
private final BugCheckerRefactoringTestHelper helper = | ||
BugCheckerRefactoringTestHelper.newInstance(PatternMatchingInstanceof.class, getClass()); | ||
|
||
@Test | ||
public void positive() { | ||
assume().that(RuntimeVersion.isAtLeast21()).isTrue(); | ||
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);", | ||
" }", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void notDefinitelyChecked_noFinding() { | ||
helper | ||
.addInputLines( | ||
"Test.java", | ||
"class Test {", | ||
" void test(Object o) {", | ||
" if (o instanceof Test || o.hashCode() > 0) {", | ||
" Test test = (Test) o;", | ||
" test(test);", | ||
" }", | ||
" }", | ||
"}") | ||
.expectUnchanged() | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void moreChecksInIf_stillMatches() { | ||
assume().that(RuntimeVersion.isAtLeast21()).isTrue(); | ||
helper | ||
.addInputLines( | ||
"Test.java", | ||
"class Test {", | ||
" void test(Object o) {", | ||
" if (o instanceof Test && o.hashCode() != 1) {", | ||
" Test test = (Test) o;", | ||
" test(test);", | ||
" }", | ||
" }", | ||
"}") | ||
.addOutputLines( | ||
"Test.java", | ||
"class Test {", | ||
" void test(Object o) {", | ||
" if (o instanceof Test test && o.hashCode() != 1) {", | ||
" test(test);", | ||
" }", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void differentTypeToCheck_noFinding() { | ||
helper | ||
.addInputLines( | ||
"Test.java", | ||
"class Test {", | ||
" void test(Object o) {", | ||
" if (o instanceof Test) {", | ||
" Integer test = (Integer) o;", | ||
" test(test);", | ||
" }", | ||
" }", | ||
"}") | ||
.expectUnchanged() | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void noInstanceofAtAll_noFinding() { | ||
helper | ||
.addInputLines( | ||
"Test.java", | ||
"class Test {", | ||
" void test(Object o) {", | ||
" if (o.hashCode() > 0) {", | ||
" Integer test = (Integer) o;", | ||
" test(test);", | ||
" }", | ||
" }", | ||
"}") | ||
.expectUnchanged() | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
public void differentVariable() { | ||
helper | ||
.addInputLines( | ||
"Test.java", | ||
"class Test {", | ||
" void test(Object x, Object y) {", | ||
" if (x instanceof Test) {", | ||
" Test test = (Test) y;", | ||
" test(test, null);", | ||
" }", | ||
" }", | ||
"}") | ||
.expectUnchanged() | ||
.doTest(); | ||
} | ||
} |