"Cascade if" inspection: don't highlight for complex logical conditions
Related to KT-18615
This commit is contained in:
@@ -23,6 +23,7 @@ import com.intellij.codeInspection.ProblemsHolder
|
||||
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.IfToWhenIntention
|
||||
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isIfBranch
|
||||
import org.jetbrains.kotlin.idea.intentions.branches
|
||||
import org.jetbrains.kotlin.lexer.KtTokens
|
||||
import org.jetbrains.kotlin.psi.*
|
||||
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
|
||||
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
|
||||
@@ -46,6 +47,20 @@ class CascadeIfInspection : AbstractKotlinInspection() {
|
||||
it is KtBreakExpression || it is KtContinueExpression
|
||||
}) return
|
||||
|
||||
var current: KtIfExpression? = expression
|
||||
while (current != null) {
|
||||
val condition = current.condition
|
||||
when (condition) {
|
||||
is KtBinaryExpression -> when (condition.operationToken) {
|
||||
KtTokens.ANDAND, KtTokens.OROR -> return
|
||||
}
|
||||
is KtUnaryExpression -> when (condition.operationToken) {
|
||||
KtTokens.EXCL -> return
|
||||
}
|
||||
}
|
||||
current = current.`else` as? KtIfExpression
|
||||
}
|
||||
|
||||
holder.registerProblem(
|
||||
expression.ifKeyword,
|
||||
"Cascade if can be replaced with when",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// PROBLEM: none
|
||||
|
||||
fun foo(a: Boolean, b: Boolean, c: Boolean) {
|
||||
<caret>if (a) {
|
||||
|
||||
}
|
||||
else if (b && c) {
|
||||
|
||||
}
|
||||
else if (!c) {
|
||||
|
||||
}
|
||||
else {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,12 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
|
||||
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/inspectionsLocal/cascadeIf"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), TargetBackend.ANY, true);
|
||||
}
|
||||
|
||||
@TestMetadata("complex.kt")
|
||||
public void testComplex() throws Exception {
|
||||
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/cascadeIf/complex.kt");
|
||||
doTest(fileName);
|
||||
}
|
||||
|
||||
@TestMetadata("four.kt")
|
||||
public void testFour() throws Exception {
|
||||
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/cascadeIf/four.kt");
|
||||
|
||||
Reference in New Issue
Block a user