Introduce "Call chain on collection should be converted into 'Sequence'"

So #KT-15476 Fixed
This commit is contained in:
Toshiaki Kameyama
2018-06-29 18:52:14 +03:00
committed by Mikhail Glukhikh
parent 76a98c8e67
commit 108dea5b46
42 changed files with 668 additions and 0 deletions
@@ -0,0 +1,5 @@
<html>
<body>
This inspection reports call chain on collection should be converted into <b>Sequence</b>.
</body>
</html>
+9
View File
@@ -2967,6 +2967,15 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.collections.ConvertCallChainIntoSequenceInspection"
displayName="Call chain on collection should be converted into 'Sequence'"
groupPath="Kotlin"
groupName="Style issues"
enabledByDefault="true"
level="WEAK WARNING"
language="kotlin"
/>
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
+9
View File
@@ -2966,6 +2966,15 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.collections.ConvertCallChainIntoSequenceInspection"
displayName="Call chain on collection should be converted into 'Sequence'"
groupPath="Kotlin"
groupName="Style issues"
enabledByDefault="true"
level="WEAK WARNING"
language="kotlin"
/>
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
+9
View File
@@ -2966,6 +2966,15 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.collections.ConvertCallChainIntoSequenceInspection"
displayName="Call chain on collection should be converted into 'Sequence'"
groupPath="Kotlin"
groupName="Style issues"
enabledByDefault="true"
level="WEAK WARNING"
language="kotlin"
/>
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
+9
View File
@@ -2966,6 +2966,15 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.collections.ConvertCallChainIntoSequenceInspection"
displayName="Call chain on collection should be converted into 'Sequence'"
groupPath="Kotlin"
groupName="Style issues"
enabledByDefault="true"
level="WEAK WARNING"
language="kotlin"
/>
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
+9
View File
@@ -2966,6 +2966,15 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.collections.ConvertCallChainIntoSequenceInspection"
displayName="Call chain on collection should be converted into 'Sequence'"
groupPath="Kotlin"
groupName="Style issues"
enabledByDefault="true"
level="WEAK WARNING"
language="kotlin"
/>
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
+9
View File
@@ -2967,6 +2967,15 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.collections.ConvertCallChainIntoSequenceInspection"
displayName="Call chain on collection should be converted into 'Sequence'"
groupPath="Kotlin"
groupName="Style issues"
enabledByDefault="true"
level="WEAK WARNING"
language="kotlin"
/>
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
@@ -0,0 +1,171 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.inspections.collections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
class ConvertCallChainIntoSequenceInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
qualifiedExpressionVisitor(fun(expression) {
val (targetQualified, targetCall) = expression.findTarget() ?: return
val rangeInElement = targetCall.calleeExpression?.textRange?.shiftRight(-targetQualified.startOffset) ?: return
holder.registerProblem(
holder.manager.createProblemDescriptor(
targetQualified,
rangeInElement,
"Call chain on collection should be converted into 'Sequence'",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
ConvertCallChainIntoSequenceFix()
)
)
})
}
private class ConvertCallChainIntoSequenceFix : LocalQuickFix {
override fun getName() = "Convert call chain into 'Sequence'"
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtQualifiedExpression ?: return
val calls = expression.collectCallExpression().reversed()
val firstCall = calls.firstOrNull() ?: return
val lastCall = calls.lastOrNull() ?: return
val first = firstCall.parent as? KtQualifiedExpression ?: return
val last = lastCall.parent as? KtQualifiedExpression ?: return
val next = last.parent as? KtQualifiedExpression
val nextType = next?.getCallableDescriptor()?.returnType
val psiFactory = KtPsiFactory(expression)
val dot = buildString {
if (first.receiverExpression.siblings().filterIsInstance<PsiWhiteSpace>().any { it.textContains('\n') }) append("\n")
if (first is KtSafeQualifiedExpression) append("?")
append(".")
}
val firstCommentSaver = CommentSaver(first)
val firstReplaced = first.replaced(
psiFactory.buildExpression {
appendExpression(first.receiverExpression)
appendFixedText(dot)
appendExpression(psiFactory.createExpression("asSequence()"))
appendFixedText(dot)
appendExpression(firstCall)
}
)
firstCommentSaver.restore(firstReplaced)
val nextDescriptor = next?.getCallableDescriptor()
if (nextDescriptor == null
|| !nextDescriptor.fqNameSafe.asString().startsWith("kotlin.sequences.")
|| nextDescriptor.returnType != nextType
) {
val lastCommentSaver = CommentSaver(last)
val lastReplaced = last.replace(
psiFactory.buildExpression {
appendExpression(last)
appendFixedText(dot)
appendExpression(psiFactory.createExpression("toList()"))
}
)
lastCommentSaver.restore(lastReplaced)
}
}
}
private fun KtQualifiedExpression.findTarget(): Pair<KtQualifiedExpression, KtCallExpression>? {
if (parent is KtQualifiedExpression) return null
val calls = collectCallExpression()
if (calls.isEmpty()) return null
val qualified = calls.first().parent as? KtQualifiedExpression ?: return null
val fqName = qualified.getCallableDescriptor()?.returnType?.constructor?.declarationDescriptor?.fqNameSafe
if (fqName != KotlinBuiltIns.FQ_NAMES.list) return null
return qualified to calls.last()
}
private fun KtQualifiedExpression.collectCallExpression(): List<KtCallExpression> {
val calls = mutableListOf<KtCallExpression>()
fun collect(qualified: KtQualifiedExpression) {
val call = qualified.callExpression ?: return
calls.add(call)
val receiver = qualified.receiverExpression
if (receiver is KtQualifiedExpression) collect(receiver)
}
collect(this)
if (calls.size < 2) return emptyList()
val transformationCalls = calls
.asSequence()
.dropWhile { !it.isTransformation() }
.takeWhile { it.isTransformation() && !it.hasReturn() }
.toList()
if (transformationCalls.size < 2) return emptyList()
return transformationCalls
}
private fun KtCallExpression.hasReturn(): Boolean = valueArguments.any { arg ->
arg.anyDescendantOfType<KtReturnExpression> { it.labelQualifier == null }
}
private fun KtCallExpression.isTransformation(): Boolean {
val fqName = transformations[calleeExpression?.text] ?: return false
return fqName == getCallableDescriptor()?.fqNameSafe
}
private val transformations = listOf(
"chunked",
"distinct",
"distinctBy",
"drop",
"dropWhile",
"filter",
"filterIndexed",
"filterIsInstance",
"filterNot",
"filterNotNull",
"map",
"mapIndexed",
"mapIndexedNotNull",
"mapNotNull",
"minus",
"minusElement",
"onEach",
"plus",
"plusElement",
"requireNoNulls",
"sorted",
"sortedBy",
"sortedByDescending",
"sortedDescending",
"sortedWith",
"take",
"takeWhile",
"windowed",
"zipWithNext"
).associate { it to FqName("kotlin.collections.$it") }
@@ -0,0 +1 @@
org.jetbrains.kotlin.idea.inspections.collections.ConvertCallChainIntoSequenceInspection
@@ -0,0 +1,35 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Pair<List<Int>, List<Int>>> {
return list
.<caret>chunked(1)
.distinct()
.distinctBy { it }
.drop(1)
.dropWhile { true }
.filter { true }
.filterIndexed { index, list -> true }
.filterIsInstance<Int>()
.filterNot { true }
.filterNotNull()
.map { it }
.mapIndexed { index, i -> i }
.mapIndexedNotNull { index, i -> i }
.mapNotNull { it }
.minus(1)
.minusElement(1)
.onEach {}
.plus(1)
.plusElement(1)
.requireNoNulls()
.sorted()
.sortedBy { it }
.sortedByDescending { it }
.sortedDescending()
.sortedWith(Comparator { o1, o2 -> 0 })
.take(1)
.takeWhile { true }
.windowed(1, 1, true)
.zipWithNext()
.zipWithNext { a, b -> a }
}
@@ -0,0 +1,37 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Pair<List<Int>, List<Int>>> {
return list
.asSequence()
.chunked(1)
.distinct()
.distinctBy { it }
.drop(1)
.dropWhile { true }
.filter { true }
.filterIndexed { index, list -> true }
.filterIsInstance<Int>()
.filterNot { true }
.filterNotNull()
.map { it }
.mapIndexed { index, i -> i }
.mapIndexedNotNull { index, i -> i }
.mapNotNull { it }
.minus(1)
.minusElement(1)
.onEach {}
.plus(1)
.plusElement(1)
.requireNoNulls()
.sorted()
.sortedBy { it }
.sortedByDescending { it }
.sortedDescending()
.sortedWith(Comparator { o1, o2 -> 0 })
.take(1)
.takeWhile { true }
.windowed(1, 1, true)
.zipWithNext()
.zipWithNext { a, b -> a }
.toList()
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun test(list: List<Int>): Int {
return list // comment1
.<caret>filter { it > 1 } // comment2
.map { it * 2 } // comment3
.sum() // comment4
}
@@ -0,0 +1,9 @@
// WITH_RUNTIME
fun test(list: List<Int>): Int {
return list // comment1
.asSequence()
.filter { it > 1 } // comment2
.map { it * 2 } // comment3
.sum() // comment4
}
@@ -0,0 +1,7 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list // comment1
.<caret>filter { it > 1 } // comment2
.map { it * 2 } // comment3
}
@@ -0,0 +1,9 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list // comment1
.asSequence()
.filter { it > 1 } // comment2
.map { it * 2 }
.toList() // comment3
}
@@ -0,0 +1,6 @@
// PROBLEM: none
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list.<caret>filter { it > 1 }
}
@@ -0,0 +1,6 @@
// PROBLEM: none
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list.filter { it > 2 }.dropLast(1).<caret>filter { it > 2 }
}
@@ -0,0 +1,11 @@
// PROBLEM: none
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list
.reversed()
.map { it + 1 }
.<caret>map { it + 1 }
.dropLast(1)
.takeLast(2)
}
@@ -0,0 +1,7 @@
// WITH_RUNTIME
fun test(list: List<Int>?): List<Int>? {
return list
?.<caret>filter { it > 1 }
?.map { it * 2 }
}
@@ -0,0 +1,9 @@
// WITH_RUNTIME
fun test(list: List<Int>?): List<Int>? {
return list
?.asSequence()
?.filter { it > 1 }
?.map { it * 2 }
?.toList()
}
@@ -0,0 +1,5 @@
// WITH_RUNTIME
fun test(list: List<Int>?): List<Int>? {
return list?.filter { it > 1 }!!.<caret>filter { it > 2 }.filter { it > 3 }
}
@@ -0,0 +1,5 @@
// WITH_RUNTIME
fun test(list: List<Int>?): List<Int>? {
return list?.filter { it > 1 }!!.asSequence().filter { it > 2 }.filter { it > 3 }.toList()
}
@@ -0,0 +1,11 @@
// PROBLEM: none
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list
.<caret>filter { it > 1 }
.mapNotNull {
if (it == 2) return emptyList()
it * 2
}
}
@@ -0,0 +1,10 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list
.<caret>filter { it > 1 }
.mapNotNull {
if (it == 2) return@mapNotNull null
it * 2
}
}
@@ -0,0 +1,12 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list
.asSequence()
.filter { it > 1 }
.mapNotNull {
if (it == 2) return@mapNotNull null
it * 2
}
.toList()
}
@@ -0,0 +1,5 @@
// WITH_RUNTIME
fun test(): List<Int> {
return listOf(1, 2, 3).<caret>filter { it > 1 }.map { it * 2 }
}
@@ -0,0 +1,5 @@
// WITH_RUNTIME
fun test(): List<Int> {
return listOf(1, 2, 3).asSequence().filter { it > 1 }.map { it * 2 }.toList()
}
@@ -0,0 +1,7 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list
.filter<caret> { it > 1 }
.map { it * 2 }
}
@@ -0,0 +1,9 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list
.asSequence()
.filter { it > 1 }
.map { it * 2 }
.toList()
}
@@ -0,0 +1,10 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list
.reversed()
.<caret>map { it + 1 }
.map { it + 1 }
.dropLast(1)
.takeLast(2)
}
@@ -0,0 +1,12 @@
// WITH_RUNTIME
fun test(list: List<Int>): List<Int> {
return list
.reversed()
.asSequence()
.map { it + 1 }
.map { it + 1 }
.toList()
.dropLast(1)
.takeLast(2)
}
@@ -0,0 +1,11 @@
// WITH_RUNTIME
fun test(foo: Foo): List<Int> {
return foo.getList()
.<caret>filter { it > 1 }
.map { it * 2 }
}
class Foo {
fun getList(): List<Int> = listOf(1, 2, 3)
}
@@ -0,0 +1,13 @@
// WITH_RUNTIME
fun test(foo: Foo): List<Int> {
return foo.getList()
.asSequence()
.filter { it > 1 }
.map { it * 2 }
.toList()
}
class Foo {
fun getList(): List<Int> = listOf(1, 2, 3)
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun test(): Int {
return listOf(1, 2, 3)
.<caret>filter { it > 1 }
.map { it * 2 }
.sum()
}
@@ -0,0 +1,9 @@
// WITH_RUNTIME
fun test(): Int {
return listOf(1, 2, 3)
.asSequence()
.filter { it > 1 }
.map { it * 2 }
.sum()
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun test(): Int {
return listOf(1, 2, 3)
.<caret>filter { it > 1 }
.map { it * 2 }
.binarySearch(4)
}
@@ -0,0 +1,10 @@
// WITH_RUNTIME
fun test(): Int {
return listOf(1, 2, 3)
.asSequence()
.filter { it > 1 }
.map { it * 2 }
.toList()
.binarySearch(4)
}
@@ -0,0 +1,10 @@
// WITH_RUNTIME
fun test(): Int {
return listOf(1, 2, 3)
.<caret>filter { it > 1 }
.map { it * 2 }
.let {
it.binarySearch(1)
}
}
@@ -0,0 +1,12 @@
// WITH_RUNTIME
fun test(): Int {
return listOf(1, 2, 3)
.asSequence()
.filter { it > 1 }
.map { it * 2 }
.toList()
.let {
it.binarySearch(1)
}
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun test(list: List<List<Int>>): List<Int> {
return list
.<caret>filter { it.count() > 2 }
.map { it + it }
.flatMap { it + it }
}
@@ -0,0 +1,10 @@
// WITH_RUNTIME
fun test(list: List<List<Int>>): List<Int> {
return list
.asSequence()
.filter { it.count() > 2 }
.map { it + it }
.toList()
.flatMap { it + it }
}
@@ -492,6 +492,109 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/inspectionsLocal/collections"), Pattern.compile("^([\\w\\-_]+)\\.(kt|kts)$"), TargetBackend.ANY, true);
}
@TestMetadata("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class ConvertCallChainIntoSequence extends AbstractLocalInspectionTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, TargetBackend.ANY, testDataFilePath);
}
@TestMetadata("all.kt")
public void testAll() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/all.kt");
}
public void testAllFilesPresentInConvertCallChainIntoSequence() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence"), Pattern.compile("^([\\w\\-_]+)\\.(kt|kts)$"), TargetBackend.ANY, true);
}
@TestMetadata("comment.kt")
public void testComment() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/comment.kt");
}
@TestMetadata("comment2.kt")
public void testComment2() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/comment2.kt");
}
@TestMetadata("noTargetCallChain.kt")
public void testNoTargetCallChain() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/noTargetCallChain.kt");
}
@TestMetadata("noTargetCallChain2.kt")
public void testNoTargetCallChain2() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/noTargetCallChain2.kt");
}
@TestMetadata("noTargetCallChain3.kt")
public void testNoTargetCallChain3() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/noTargetCallChain3.kt");
}
@TestMetadata("nullable.kt")
public void testNullable() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/nullable.kt");
}
@TestMetadata("nullable2.kt")
public void testNullable2() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/nullable2.kt");
}
@TestMetadata("return.kt")
public void testReturn() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/return.kt");
}
@TestMetadata("returnAtLabels.kt")
public void testReturnAtLabels() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/returnAtLabels.kt");
}
@TestMetadata("simple.kt")
public void testSimple() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/simple.kt");
}
@TestMetadata("simple2.kt")
public void testSimple2() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/simple2.kt");
}
@TestMetadata("simple3.kt")
public void testSimple3() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/simple3.kt");
}
@TestMetadata("simple4.kt")
public void testSimple4() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/simple4.kt");
}
@TestMetadata("termination.kt")
public void testTermination() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination.kt");
}
@TestMetadata("termination2.kt")
public void testTermination2() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination2.kt");
}
@TestMetadata("termination3.kt")
public void testTermination3() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination3.kt");
}
@TestMetadata("termination4.kt")
public void testTermination4() throws Exception {
runTest("idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination4.kt");
}
}
@TestMetadata("idea/testData/inspectionsLocal/collections/simplifiableCallChain")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)