Safe cast with return: fix false negative on lambda last statement #KT-27906 Fixed
This commit is contained in:
committed by
Mikhail Glukhikh
parent
e49789f819
commit
e8e51d1db4
@@ -30,7 +30,12 @@ class SafeCastWithReturnInspection : AbstractKotlinInspection() {
|
||||
if (KtPsiUtil.deparenthesize(parent.right) !is KtReturnExpression) return
|
||||
|
||||
val context = expression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
|
||||
if (context[BindingContext.USED_AS_EXPRESSION, parent] == true) return
|
||||
if (context[BindingContext.USED_AS_EXPRESSION, parent] == true) {
|
||||
val lambda = expression.getStrictParentOfType<KtLambdaExpression>() ?: return
|
||||
if (lambda.functionLiteral.bodyExpression?.statements?.lastOrNull() != parent) return
|
||||
val call = lambda.getStrictParentOfType<KtCallExpression>() ?: return
|
||||
if (context[BindingContext.USED_AS_EXPRESSION, call] == true) return
|
||||
}
|
||||
if (context.diagnostics.forElement(expression.operationReference).any { it.factory == Errors.CAST_NEVER_SUCCEEDS }) return
|
||||
|
||||
holder.registerProblem(
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// PROBLEM: none
|
||||
// WITH_RUNTIME
|
||||
fun test(x: Any) {
|
||||
val s = run {
|
||||
<caret>x as? String ?: return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// WITH_RUNTIME
|
||||
fun test(x: Any) {
|
||||
run {
|
||||
<caret>x as? String ?: return
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// WITH_RUNTIME
|
||||
fun test(x: Any) {
|
||||
run {
|
||||
if (x !is String) return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// WITH_RUNTIME
|
||||
fun test(x: Any) {
|
||||
run {
|
||||
<caret>x as? String ?: return@run
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// WITH_RUNTIME
|
||||
fun test(x: Any) {
|
||||
run {
|
||||
if (x !is String) return@run
|
||||
}
|
||||
}
|
||||
+15
@@ -5593,6 +5593,21 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
|
||||
runTest("idea/testData/inspectionsLocal/safeCastWithReturn/labeledReturn.kt");
|
||||
}
|
||||
|
||||
@TestMetadata("lambdaLastStatement.kt")
|
||||
public void testLambdaLastStatement() throws Exception {
|
||||
runTest("idea/testData/inspectionsLocal/safeCastWithReturn/lambdaLastStatement.kt");
|
||||
}
|
||||
|
||||
@TestMetadata("lambdaLastStatement2.kt")
|
||||
public void testLambdaLastStatement2() throws Exception {
|
||||
runTest("idea/testData/inspectionsLocal/safeCastWithReturn/lambdaLastStatement2.kt");
|
||||
}
|
||||
|
||||
@TestMetadata("lambdaLastStatement3.kt")
|
||||
public void testLambdaLastStatement3() throws Exception {
|
||||
runTest("idea/testData/inspectionsLocal/safeCastWithReturn/lambdaLastStatement3.kt");
|
||||
}
|
||||
|
||||
@TestMetadata("simple.kt")
|
||||
public void testSimple() throws Exception {
|
||||
runTest("idea/testData/inspectionsLocal/safeCastWithReturn/simple.kt");
|
||||
|
||||
Reference in New Issue
Block a user