UnnecessaryVariableInspection: fix false positive in lambda

#KT-32565 Fixed
This commit is contained in:
Toshiaki Kameyama
2020-02-01 23:00:02 +09:00
committed by Yan Zhulanow
parent 64f6ed586b
commit 7c0af78b08
6 changed files with 86 additions and 0 deletions
@@ -90,6 +90,11 @@ class UnnecessaryVariableInspection : AbstractApplicabilityBasedInspection<KtPro
) )
) )
if (!validator(copyName)) return false if (!validator(copyName)) return false
if (containingDeclaration is KtClassOrObject) {
val enclosingBlock = enclosingElement as? KtBlockExpression
val initializerDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(initializerDescriptor)
if (enclosingBlock?.statements?.none { it == initializerDeclaration } == true) return false
}
} }
return true return true
} }
@@ -0,0 +1,16 @@
// PROBLEM: none
// WITH_RUNTIME
fun findCredentials() = 1
fun println(i: Int) {}
fun test() {
val data = run {
val credentials = findCredentials()
object {
val <caret>foundCredentials = credentials
}
}
println(data.foundCredentials)
}
@@ -0,0 +1,19 @@
// PROBLEM: none
// WITH_RUNTIME
fun findCredentials() = 1
fun println(i: Int) {}
fun test() {
val data = run {
val credentials = findCredentials()
class Foo {
val <caret>foundCredentials = credentials
}
Foo()
}
val foundCredentials = data.foundCredentials
}
@@ -0,0 +1,16 @@
// WITH_RUNTIME
fun findCredentials() = 1
fun println(i: Int) {}
fun test() {
val credentials = findCredentials()
val data = run {
object {
val <caret>foundCredentials = credentials
}
}
println(data.foundCredentials)
}
@@ -0,0 +1,15 @@
// WITH_RUNTIME
fun findCredentials() = 1
fun println(i: Int) {}
fun test() {
val credentials = findCredentials()
val data = run {
object {
}
}
println(credentials)
}
@@ -13201,6 +13201,21 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
runTest("idea/testData/inspectionsLocal/unnecessaryVariable/copyOfVal.kt"); runTest("idea/testData/inspectionsLocal/unnecessaryVariable/copyOfVal.kt");
} }
@TestMetadata("copyOfValInLambda.kt")
public void testCopyOfValInLambda() throws Exception {
runTest("idea/testData/inspectionsLocal/unnecessaryVariable/copyOfValInLambda.kt");
}
@TestMetadata("copyOfValInLambda2.kt")
public void testCopyOfValInLambda2() throws Exception {
runTest("idea/testData/inspectionsLocal/unnecessaryVariable/copyOfValInLambda2.kt");
}
@TestMetadata("copyOfValInLambda3.kt")
public void testCopyOfValInLambda3() throws Exception {
runTest("idea/testData/inspectionsLocal/unnecessaryVariable/copyOfValInLambda3.kt");
}
@TestMetadata("copyOfValUnused.kt") @TestMetadata("copyOfValUnused.kt")
public void testCopyOfValUnused() throws Exception { public void testCopyOfValUnused() throws Exception {
runTest("idea/testData/inspectionsLocal/unnecessaryVariable/copyOfValUnused.kt"); runTest("idea/testData/inspectionsLocal/unnecessaryVariable/copyOfValUnused.kt");