MoveVariableDeclarationIntoWhenInspection: report it if initializer is single line even if property is multi line

#KT-39467 Fixed
This commit is contained in:
Toshiaki Kameyama
2020-07-17 11:48:14 +09:00
committed by Dmitry Gridin
parent 75d4c7e91c
commit 4569b85a16
6 changed files with 54 additions and 5 deletions
@@ -32,19 +32,21 @@ class MoveVariableDeclarationIntoWhenInspection : AbstractKotlinInspection(), Cl
whenExpressionVisitor(fun(expression: KtWhenExpression) {
val subjectExpression = expression.subjectExpression ?: return
val property = expression.findDeclarationNear() ?: return
if (!property.isOneLiner()) return
if (property.initializer?.anyDescendantOfType<KtExpression> {
val identifier = property.nameIdentifier ?: return
val initializer = property.initializer ?: return
if (!initializer.isOneLiner()) return
if (initializer.anyDescendantOfType<KtExpression> {
it is KtThrowExpression || it is KtReturnExpression || it is KtBreakExpression || it is KtContinueExpression
} == true) return
}) return
val action = property.action(expression)
if (action == Action.NOTHING) return
val identifier = property.nameIdentifier ?: return
holder.registerProblem(
property,
TextRange.from(identifier.startOffsetInParent, identifier.textLength),
action.description, action.createFix(subjectExpression.createSmartPointer())
action.description,
action.createFix(subjectExpression.createSmartPointer())
)
})
}
@@ -0,0 +1,10 @@
fun test() = 42
fun foo() {
val <caret>a =
test()
when (a) {
1 -> 0
else -> 24
}
}
@@ -0,0 +1,8 @@
fun test() = 42
fun foo() {
when (test()) {
1 -> 0
else -> 24
}
}
@@ -0,0 +1,10 @@
fun test() = 42
fun foo() {
val <caret>a =
test()
when (a) {
1 -> a
else -> 24
}
}
@@ -0,0 +1,9 @@
fun test() = 42
fun foo() {
when (val a =
test()) {
1 -> a
else -> 24
}
}
@@ -6885,6 +6885,16 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
runTest("idea/testData/inspectionsLocal/moveVariableDeclarationIntoWhen/inUnaryAndProperty.kt");
}
@TestMetadata("multiLinePropertywithSingleLineInitializer.kt")
public void testMultiLinePropertywithSingleLineInitializer() throws Exception {
runTest("idea/testData/inspectionsLocal/moveVariableDeclarationIntoWhen/multiLinePropertywithSingleLineInitializer.kt");
}
@TestMetadata("multiLinePropertywithSingleLineInitializer2.kt")
public void testMultiLinePropertywithSingleLineInitializer2() throws Exception {
runTest("idea/testData/inspectionsLocal/moveVariableDeclarationIntoWhen/multiLinePropertywithSingleLineInitializer2.kt");
}
@TestMetadata("notApplicableInBinaryExpression.kt")
public void testNotApplicableInBinaryExpression() throws Exception {
runTest("idea/testData/inspectionsLocal/moveVariableDeclarationIntoWhen/notApplicableInBinaryExpression.kt");