New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add UseSumOfInsteadOfFlatMapSize rule #5405
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
87 changes: 87 additions & 0 deletions
87
...e/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseSumOfInsteadOfFlatMapSize.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
package io.gitlab.arturbosch.detekt.rules.style | ||
|
||
import io.gitlab.arturbosch.detekt.api.CodeSmell | ||
import io.gitlab.arturbosch.detekt.api.Config | ||
import io.gitlab.arturbosch.detekt.api.Debt | ||
import io.gitlab.arturbosch.detekt.api.Entity | ||
import io.gitlab.arturbosch.detekt.api.Issue | ||
import io.gitlab.arturbosch.detekt.api.Rule | ||
import io.gitlab.arturbosch.detekt.api.Severity | ||
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution | ||
import io.gitlab.arturbosch.detekt.rules.isCalling | ||
import io.gitlab.arturbosch.detekt.rules.safeAs | ||
import org.jetbrains.kotlin.builtins.DefaultBuiltIns | ||
import org.jetbrains.kotlin.descriptors.ClassDescriptor | ||
import org.jetbrains.kotlin.name.FqName | ||
import org.jetbrains.kotlin.psi.KtCallExpression | ||
import org.jetbrains.kotlin.psi.KtExpression | ||
import org.jetbrains.kotlin.psi.KtNameReferenceExpression | ||
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver | ||
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis | ||
import org.jetbrains.kotlin.resolve.calls.util.getType | ||
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf | ||
|
||
/** | ||
* Turn on this rule to flag `flatMap` and `size/count` calls that can be replaced with a `sumOf` call. | ||
* | ||
* <noncompliant> | ||
* class Foo(val foo: List<Int>) | ||
* list.flatMap { it.foo }.size | ||
* list.flatMap { it.foo }.count() | ||
* list.flatMap { it.foo }.count { it > 2 } | ||
* listOf(listOf(1), listOf(2, 3)).flatten().size | ||
* </noncompliant> | ||
* | ||
* <compliant> | ||
* list.sumOf { it.foo.size } | ||
* list.sumOf { it.foo.count() } | ||
* list.sumOf { it.foo.count { foo -> foo > 2 } } | ||
* listOf(listOf(1), listOf(2, 3)).sumOf { it.size } | ||
* </compliant> | ||
*/ | ||
@RequiresTypeResolution | ||
class UseSumOfInsteadOfFlatMapSize(config: Config = Config.empty) : Rule(config) { | ||
override val issue: Issue = Issue( | ||
javaClass.simpleName, | ||
Severity.Style, | ||
"Use `sumOf` instead of `flatMap` and `size/count` calls", | ||
Debt.FIVE_MINS | ||
) | ||
|
||
@Suppress("ReturnCount") | ||
override fun visitCallExpression(expression: KtCallExpression) { | ||
super.visitCallExpression(expression) | ||
|
||
val calleeText = expression.calleeExpression?.text ?: return | ||
if (!expression.isFlatMapOrFlatten()) return | ||
|
||
val receiver = expression.getQualifiedExpressionForSelectorOrThis() | ||
val selector = receiver.getQualifiedExpressionForReceiver()?.selectorExpression ?: return | ||
if (!selector.isSizeOrCount(receiver)) return | ||
|
||
val selectorText = selector.safeAs<KtCallExpression>()?.calleeExpression?.text ?: selector.text | ||
val message = "Use 'sumOf' instead of '$calleeText' and '$selectorText'" | ||
report(CodeSmell(issue, Entity.from(expression), message)) | ||
} | ||
|
||
private fun KtCallExpression.isFlatMapOrFlatten(): Boolean = isCalling(flatMapAndFlattenFqName, bindingContext) | ||
|
||
@Suppress("ReturnCount") | ||
private fun KtExpression.isSizeOrCount(receiver: KtExpression): Boolean { | ||
if (safeAs<KtNameReferenceExpression>()?.text == "size") { | ||
val receiverType = receiver.getType(bindingContext) ?: return false | ||
val descriptor = receiverType.constructor.declarationDescriptor?.safeAs<ClassDescriptor>() ?: return false | ||
return descriptor.isSubclassOf(DefaultBuiltIns.Instance.list) | ||
} | ||
return safeAs<KtCallExpression>()?.isCalling(countFqName, bindingContext) == true | ||
} | ||
|
||
companion object { | ||
private val flatMapAndFlattenFqName = listOf( | ||
FqName("kotlin.collections.flatMap"), | ||
FqName("kotlin.collections.flatten"), | ||
) | ||
|
||
private val countFqName = FqName("kotlin.collections.count") | ||
} | ||
} |
161 changes: 161 additions & 0 deletions
161
...c/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseSumOfInsteadOfFlatMapSizeSpec.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
package io.gitlab.arturbosch.detekt.rules.style | ||
|
||
import io.gitlab.arturbosch.detekt.rules.KotlinCoreEnvironmentTest | ||
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext | ||
import org.assertj.core.api.Assertions.assertThat | ||
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment | ||
import org.junit.jupiter.api.DisplayName | ||
import org.junit.jupiter.api.Test | ||
|
||
@KotlinCoreEnvironmentTest | ||
class UseSumOfInsteadOfFlatMapSizeSpec(val env: KotlinCoreEnvironment) { | ||
val subject = UseSumOfInsteadOfFlatMapSize() | ||
|
||
@Test | ||
@DisplayName("Reports flatMap and size") | ||
fun reportFlatMapAndSize() { | ||
val code = """ | ||
fun test(list: List<Foo>) { | ||
list.flatMap { it.foo }.size | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).hasSize(1) | ||
assertThat(actual[0].message).isEqualTo("Use 'sumOf' instead of 'flatMap' and 'size'") | ||
} | ||
|
||
@Test | ||
@DisplayName("Reports flatMap and count") | ||
fun reportFlatMapAndCount() { | ||
val code = """ | ||
fun test(list: List<Foo>) { | ||
list.flatMap { it.foo }.count() | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).hasSize(1) | ||
assertThat(actual[0].message).isEqualTo("Use 'sumOf' instead of 'flatMap' and 'count'") | ||
} | ||
|
||
@Test | ||
@DisplayName("Reports flatMap and count with a argument") | ||
fun reportFlatMapAndCountWithArgument() { | ||
val code = """ | ||
fun test(list: List<Foo>) { | ||
list.flatMap { it.foo }.count { it > 2 } | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).hasSize(1) | ||
assertThat(actual[0].message).isEqualTo("Use 'sumOf' instead of 'flatMap' and 'count'") | ||
} | ||
|
||
@Test | ||
@DisplayName("Reports flatten and size") | ||
fun reportFlattenAndSize() { | ||
val code = """ | ||
fun test(list: List<List<Int>>) { | ||
list.flatten().size | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).hasSize(1) | ||
assertThat(actual[0].message).isEqualTo("Use 'sumOf' instead of 'flatten' and 'size'") | ||
} | ||
|
||
@Test | ||
@DisplayName("Reports flatMap and size on nullable list") | ||
fun reportFlatMapAndSizeOnNullableList() { | ||
val code = """ | ||
fun test(list: List<Foo>?) { | ||
list?.flatMap { it.foo }?.size | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).hasSize(1) | ||
} | ||
|
||
@Test | ||
@DisplayName("Reports flatMap and size on implicit list receiver") | ||
fun reportFlatMapAndSizeOnImplicitListReceiver() { | ||
val code = """ | ||
fun List<Foo>.test() { | ||
flatMap { it.foo }.size | ||
sumOf { it.foo.size } | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).hasSize(1) | ||
} | ||
|
||
@Test | ||
@DisplayName("Reports flatMap and count on Set") | ||
fun reportFlatMapAndCountOnSet() { | ||
val code = """ | ||
fun test(set: Set<Bar>) { | ||
set.flatMap { it.bar }.count() | ||
} | ||
class Bar(val bar: Set<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).hasSize(1) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you add some tests to ensure that this rule doesn't flag all the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
} | ||
|
||
@Test | ||
@DisplayName("Does not report flatMap") | ||
fun noReportFlatMap() { | ||
val code = """ | ||
fun test(list: List<Foo>) { | ||
list.flatMap { it.foo } | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).isEmpty() | ||
} | ||
|
||
@Test | ||
@DisplayName("Does not report flatMap and first") | ||
fun noReportFlatMapAndFirst() { | ||
val code = """ | ||
fun test(list: List<Foo>) { | ||
list.flatMap { it.foo }.first() | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).isEmpty() | ||
} | ||
|
||
@Test | ||
@DisplayName("Does not report flatten") | ||
fun noReportFlatten() { | ||
val code = """ | ||
fun test(list: List<List<Int>>) { | ||
list.flatten() | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).isEmpty() | ||
} | ||
|
||
@Test | ||
@DisplayName("Does not report flatten and last") | ||
fun noReportFlattenAndLast() { | ||
val code = """ | ||
fun test(list: List<List<Int>>) { | ||
list.flatten().last() | ||
} | ||
class Foo(val foo: List<Int>) | ||
""".trimIndent() | ||
val actual = subject.compileAndLintWithContext(env, code) | ||
assertThat(actual).isEmpty() | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What's the reason why this is not:
It seems like this goes a bit against the rest of the codebase convention.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#5416