[java-inspections] PatternVariableCanBeUsed: equivalence check should be performed in narrowing cast as well

Fixes IDEA-348779 "Pattern variable can be used" inspection false positive

GitOrigin-RevId: a1ac8fe39011db2127d8d6d627cfae913320995a
This commit is contained in:
Tagir Valeev
2024-03-13 21:17:22 +00:00
committed by intellij-monorepo-bot
parent fb960d5691
commit 97b7d32eb0
2 changed files with 15 additions and 6 deletions
@@ -360,12 +360,11 @@ public final class InstanceOfUtils {
PsiType type = typeElement.getType();
PsiType castType = Objects.requireNonNull(cast.getCastType()).getType();
PsiExpression castOperand = Objects.requireNonNull(cast.getOperand());
if (typeCompatible(type, castType, castOperand) &&
PsiEquivalenceUtil.areElementsEquivalent(instanceOf.getOperand(), castOperand)) {
return instanceOf;
}
if (PsiUtil.isJvmLocalVariable(variable) && isSafeToNarrowType(variable, cast, type)) {
return instanceOf;
if (PsiEquivalenceUtil.areElementsEquivalent(instanceOf.getOperand(), castOperand)) {
if (typeCompatible(type, castType, castOperand) ||
PsiUtil.isJvmLocalVariable(variable) && isSafeToNarrowType(variable, cast, type)) {
return instanceOf;
}
}
}
}
@@ -0,0 +1,10 @@
// "Replace 'number' with pattern variable" "false"
class X {
public static void main(String[] args) {
Object o1 = 1.0;
Object o2 = 2;
if (!(o1 instanceof Double)) return;
Number n<caret>umber = (Number) o2;
System.out.println("number = " + number);
}
}