diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java b/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java index 8aa398165e28..d9bb153a5896 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditions.java @@ -120,6 +120,11 @@ public boolean matches(Tree tree, VisitorState state) { Types types = state.getTypes(); + // Pattern matching instanceofs can have null type. + if (instanceOfTree.getType() == null) { + return false; + } + boolean isCastable = types.isCastable( types.erasure(ASTHelpers.getType(instanceOfTree.getType())), diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditionsTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditionsTest.java index 817782e711b7..44bdbbb7c66f 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditionsTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/NestedInstanceOfConditionsTest.java @@ -16,7 +16,10 @@ package com.google.errorprone.bugpatterns; +import static com.google.common.truth.TruthJUnit.assume; + import com.google.errorprone.CompilationTestHelper; +import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -40,4 +43,21 @@ public void positiveCase() { public void negativeCase() { compilationHelper.addSourceFile("NestedInstanceOfConditionsNegativeCases.java").doTest(); } + + @Test + public void patternMatchingInstanceof() { + assume().that(RuntimeVersion.isAtLeast21()).isTrue(); + compilationHelper + .addSourceLines( + "Test.java", + "public class Test {", + " record Struct(Object a) {}", + " public void test(Object x, Object y) {", + " if (x instanceof Struct(Integer a1)) {", + " if (y instanceof Struct(Integer a2)) {}", + " }", + " }", + "}") + .doTest(); + } }