Skip to content

Commit

Permalink
NamedArguments: fix false positive on spread varargs (detekt#7283)
Browse files Browse the repository at this point in the history
  • Loading branch information
t-kameyama authored May 11, 2024
1 parent 633d458 commit b553d95
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.config
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.resolve.calls.components.isVararg
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall

Expand Down Expand Up @@ -58,17 +59,14 @@ class NamedArguments(config: Config) : Rule(
val unnamedArguments = valueArguments.mapNotNull { argument ->
if (argument.isNamed() || argument is KtLambdaArgument) return@mapNotNull null
val parameter = resolvedCall.getParameterForArgument(argument) ?: return@mapNotNull null
if (ignoreArgumentsMatchingNames &&
parameter.name.asString() == argument.getArgumentExpression()?.text
) {
if (ignoreArgumentsMatchingNames && parameter.name.asString() == argument.getArgumentExpression()?.text) {
return@mapNotNull null
}
argument to parameter
}
if (unnamedArguments.isEmpty()) return false

return unnamedArguments.all { (argument, parameter) ->
argument.getSpreadElement() != null || parameter.varargElementType == null
}
return unnamedArguments.isNotEmpty() &&
unnamedArguments.count { (argument, _) -> argument.isSpread } <= 1 &&
unnamedArguments.all { (argument, parameter) -> argument.isSpread || !parameter.isVararg }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,21 @@ class NamedArgumentsSpec(val env: KotlinCoreEnvironment) {
assertThat(findings).isEmpty()
}

@Test
fun `invocation with spread varargs should not be flagged`() {
val code = """
fun varargFun(str: String, vararg nums: Int) {}
fun call() {
val nums1 = intArrayOf(1, 2, 3)
val nums2 = intArrayOf(4, 5, 6)
val nums3 = intArrayOf(7, 8, 9)
varargFun("a", *nums1, *nums2, *nums3)
}
""".trimIndent()
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}

@Test
fun `invocation with spread operator should be flagged`() {
val code = """
Expand Down

0 comments on commit b553d95

Please sign in to comment.