From 85476b16665765479077d036b7dafd33748d8479 Mon Sep 17 00:00:00 2001 From: Marharyta Nedzelska Date: Thu, 28 Nov 2024 17:43:05 +0100 Subject: [PATCH] Fix findReceiverScopeFunctionLiteral to only resolve scope functions if their argument is used --- .../checks/CollectionInappropriateCallsCheckSample.kt | 11 +++++++++++ .../sonarsource/kotlin/api/checks/ApiExtensions.kt | 9 ++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/kotlin-checks-test-sources/src/main/kotlin/checks/CollectionInappropriateCallsCheckSample.kt b/kotlin-checks-test-sources/src/main/kotlin/checks/CollectionInappropriateCallsCheckSample.kt index 65a4965cf..432832a94 100644 --- a/kotlin-checks-test-sources/src/main/kotlin/checks/CollectionInappropriateCallsCheckSample.kt +++ b/kotlin-checks-test-sources/src/main/kotlin/checks/CollectionInappropriateCallsCheckSample.kt @@ -108,4 +108,15 @@ class CollectionInappropriateCallsCheckSample { intArray.lastIndexOf(10) } + // The collection type was resolved incorrectly and led to java.lang.IndexOutOfBoundsException + // We should only resolve let/apply/with if its argument was used as a receiver + fun bugWithLetApplyWithResolution(s: String?, params: Map>) = s?.let { + val params1 = params.get("ABC")!! + mutableListOf(params1.indexOf(it)) + } + + fun bugWithLetApplyWithResolution(s: String?, params: Array?) = params?.let { + mutableListOf(it.indexOf(s)) + } + } diff --git a/sonar-kotlin-api/src/main/java/org/sonarsource/kotlin/api/checks/ApiExtensions.kt b/sonar-kotlin-api/src/main/java/org/sonarsource/kotlin/api/checks/ApiExtensions.kt index c9f3b7ca5..099ac452f 100644 --- a/sonar-kotlin-api/src/main/java/org/sonarsource/kotlin/api/checks/ApiExtensions.kt +++ b/sonar-kotlin-api/src/main/java/org/sonarsource/kotlin/api/checks/ApiExtensions.kt @@ -380,9 +380,12 @@ private fun KaImplicitReceiverValue.findReceiverScopeFunctionLiteral( @Rewritten private fun KtReferenceExpression.findReceiverScopeFunctionLiteral(): KtFunctionLiteral? = analyze { - this@findReceiverScopeFunctionLiteral.mainReference.resolveToSymbol()?.containingSymbol?.findFunctionLiteral( - this@findReceiverScopeFunctionLiteral - ) + when (val resolvedSymbol = this@findReceiverScopeFunctionLiteral.mainReference.resolveToSymbol()) { + is KaValueParameterSymbol -> resolvedSymbol.containingSymbol?.findFunctionLiteral( + this@findReceiverScopeFunctionLiteral + ) + else -> null + } }