Don't suggest "if to ?." without else when used in expression position

This commit is contained in:
Mikhail Glukhikh
2017-05-11 20:35:02 +03:00
parent 326d850760
commit a1e00ed9f1
3 changed files with 24 additions and 2 deletions
@@ -18,13 +18,13 @@ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.*
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
class IfThenToSafeAccessInspection : IntentionBasedInspection<KtIfExpression>(IfThenToSafeAccessIntention::class) {
override fun inspectionTarget(element: KtIfExpression) = element.ifKeyword
@@ -70,7 +70,9 @@ class IfThenToSafeAccessIntention : SelfTargetingOffsetIndependentIntention<KtIf
}
private fun IfThenToSelectData.clausesReplaceableBySafeCall(): Boolean {
if (baseClause == null || negatedClause != null && !negatedClause.isNullExpression()) return false
if (baseClause == null) return false
if (negatedClause == null && baseClause.isUsedAsExpression(context)) return false
if (negatedClause != null && !negatedClause.isNullExpression()) return false
return baseClause.evaluatesTo(receiverExpression) ||
baseClause.hasFirstReceiverOf(receiverExpression) && !baseClause.hasNullableType(context)
}
@@ -0,0 +1,14 @@
// IS_APPLICABLE: false
// ERROR: 'if' must have both main and 'else' branches if used as an expression
// ERROR: Type mismatch: inferred type is Unit but Int was expected
fun maybeFoo(): String? {
return "foo"
}
fun bar(): Int {
val foo = maybeFoo()
return if (foo != null<caret>) {
foo.length
}
}
@@ -1838,6 +1838,12 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
doTest(fileName);
}
@TestMetadata("noElseBlockAsExpression.kt")
public void testNoElseBlockAsExpression() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/branched/ifThenToSafeAccess/noElseBlockAsExpression.kt");
doTest(fileName);
}
@TestMetadata("noNullInCondition.kt")
public void testNoNullInCondition() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/branched/ifThenToSafeAccess/noNullInCondition.kt");