"Redundant lambda arrow" inspection: Also report arrow with single underscore parameter #KT-24728 Fixed

This commit is contained in:
Toshiaki Kameyama
2018-06-08 11:20:12 +09:00
committed by asedunov
parent 20535feb31
commit b5ba475696
4 changed files with 34 additions and 5 deletions
@@ -11,21 +11,34 @@ import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.lambdaExpressionVisitor
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore
class RedundantLambdaArrowInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return lambdaExpressionVisitor { lambdaExpression ->
val functionLiteral = lambdaExpression.functionLiteral
if (functionLiteral.valueParameters.isNotEmpty()) return@lambdaExpressionVisitor
val arrow = functionLiteral.arrow ?: return@lambdaExpressionVisitor
val parameters = functionLiteral.valueParameters
val singleParameter = parameters.singleOrNull()
if (parameters.isNotEmpty() && singleParameter?.isSingleUnderscore != true) return@lambdaExpressionVisitor
val startOffset = functionLiteral.startOffset
holder.registerProblem(
arrow,
holder.manager.createProblemDescriptor(
functionLiteral,
TextRange((singleParameter?.startOffset ?: arrow.startOffset) - startOffset, arrow.endOffset - startOffset),
"Redundant lambda arrow",
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
DeleteFix())
isOnTheFly,
DeleteFix()
)
)
}
}
@@ -33,9 +46,10 @@ class RedundantLambdaArrowInspection : AbstractKotlinInspection() {
override fun getFamilyName() = "Remove arrow"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val element = descriptor.psiElement as? KtFunctionLiteral ?: return
FileModificationService.getInstance().preparePsiElementForWrite(element)
element.delete()
element.valueParameterList?.delete()
element.arrow?.delete()
}
}
}
@@ -0,0 +1,5 @@
fun foo(f: () -> Unit) {}
fun bar() {
foo { <caret>_ -> }
}
@@ -0,0 +1,5 @@
fun foo(f: () -> Unit) {}
fun bar() {
foo { <caret>}
}
@@ -3969,6 +3969,11 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
public void testSimple() throws Exception {
runTest("idea/testData/inspectionsLocal/redundantLambdaArrow/simple.kt");
}
@TestMetadata("underscore.kt")
public void testUnderscore() throws Exception {
runTest("idea/testData/inspectionsLocal/redundantLambdaArrow/underscore.kt");
}
}
@TestMetadata("idea/testData/inspectionsLocal/redundantObjectTypeCheck")