From 7bc6c05c41ebf31faa41b9f3df184f2337a5d249 Mon Sep 17 00:00:00 2001 From: Tagir Valeev Date: Fri, 22 Jun 2018 09:53:48 +0700 Subject: [PATCH] RedundantCastUtil#isCastRedundant: skip further checks if cast operand type equals to cast type Fixes IDEA-194278 "Too weak variable type leads to unnecessary cast" does not detect some cases --- .../src/com/intellij/psi/util/RedundantCastUtil.java | 2 ++ .../afterIncomplete.java | 9 +++++++++ .../beforeIncomplete.java | 9 +++++++++ 3 files changed, 20 insertions(+) create mode 100644 java/java-tests/testData/inspection/castCanBeRemovedNarrowingVariableType/afterIncomplete.java create mode 100644 java/java-tests/testData/inspection/castCanBeRemovedNarrowingVariableType/beforeIncomplete.java diff --git a/java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java b/java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java index 8032c035d75e..a11cd1c4c12c 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java @@ -46,6 +46,8 @@ public class RedundantCastUtil { public static boolean isCastRedundant (PsiTypeCastExpression typeCast) { PsiElement parent = typeCast.getParent(); + PsiExpression operand = typeCast.getOperand(); + if (operand != null && operand.getType() != null && operand.getType().equals(typeCast.getType())) return true; while(parent instanceof PsiParenthesizedExpression) parent = parent.getParent(); if (parent instanceof PsiExpressionList) parent = parent.getParent(); if (parent instanceof PsiReferenceExpression) parent = parent.getParent(); diff --git a/java/java-tests/testData/inspection/castCanBeRemovedNarrowingVariableType/afterIncomplete.java b/java/java-tests/testData/inspection/castCanBeRemovedNarrowingVariableType/afterIncomplete.java new file mode 100644 index 000000000000..1c1e55d80fd8 --- /dev/null +++ b/java/java-tests/testData/inspection/castCanBeRemovedNarrowingVariableType/afterIncomplete.java @@ -0,0 +1,9 @@ +// "Change type of 'list' to 'ArrayList' and remove cast" "true" +import java.util.*; + +class Test { + void test() { + ArrayList list = new ArrayList<>(); + list.ensureCapacity(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/castCanBeRemovedNarrowingVariableType/beforeIncomplete.java b/java/java-tests/testData/inspection/castCanBeRemovedNarrowingVariableType/beforeIncomplete.java new file mode 100644 index 000000000000..fb33241082e0 --- /dev/null +++ b/java/java-tests/testData/inspection/castCanBeRemovedNarrowingVariableType/beforeIncomplete.java @@ -0,0 +1,9 @@ +// "Change type of 'list' to 'ArrayList' and remove cast" "true" +import java.util.*; + +class Test { + void test() { + List list = new ArrayList<>(); + ((ArrayList) list).ensureCapacity(); + } +} \ No newline at end of file