redundant cast: ensure that temp variable would have unique name (IDEA-118197)

This commit is contained in:
Anna Kozlova
2013-12-16 16:57:22 +04:00
parent a449241577
commit 7ca0d0b0d5
4 changed files with 18 additions and 2 deletions

View File

@@ -17,10 +17,12 @@ package com.intellij.psi.util;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
@@ -465,9 +467,11 @@ public class RedundantCastUtil {
final PsiType expectedTypeByParent = PsiTypesUtil.getExpectedTypeByParent(typeCast);
if (expectedTypeByParent != null) {
try {
final Project project = operand.getProject();
final String uniqueVariableName = JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName("l", parent, false);
final PsiDeclarationStatement declarationStatement =
(PsiDeclarationStatement)JavaPsiFacade.getElementFactory(operand.getProject()).createStatementFromText(
expectedTypeByParent.getCanonicalText() + " l = " + operand.getText() + ";", parent);
(PsiDeclarationStatement)JavaPsiFacade.getElementFactory(project).createStatementFromText(
expectedTypeByParent.getCanonicalText() + " " + uniqueVariableName + " = " + operand.getText() + ";", parent);
final PsiExpression initializer = ((PsiLocalVariable)declarationStatement.getDeclaredElements()[0]).getInitializer();
LOG.assertTrue(initializer != null, operand.getText());
opType = initializer.getType();

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<problems/>

View File

@@ -0,0 +1,9 @@
import java.util.*;
public class RedundantCast{
<T> void foo2(List<Object[]> x) {
for (Object[] l : x) {
String[] s = (String[]) l;
}
}
}

View File

@@ -50,6 +50,7 @@ public class RedundantCast15Test extends InspectionTestCase {
public void testInstanceOfChecks() throws Exception { doTest();}
public void testForEachValue() throws Exception { doTest();}
public void testCaseThrowable() throws Exception { doTest();}
public void testSafeTempVarName() throws Exception { doTest();}
public void testTypeParameterAccessChecksJava7() throws Exception {
IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_7, getModule(), getTestRootDisposable());