KT-18715: don't swallow comments for if->elvis
Adds a CommentSaver to the IfThenToElvis intention that will save and restore comments when converting an if expression to elvis expression.
This commit is contained in:
committed by
Mikhail Glukhikh
parent
05c25342ad
commit
a71bb70901
+8
-1
@@ -26,6 +26,7 @@ import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
|
||||
import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection
|
||||
import org.jetbrains.kotlin.idea.intentions.SelfTargetingOffsetIndependentIntention
|
||||
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.*
|
||||
import org.jetbrains.kotlin.idea.util.CommentSaver
|
||||
import org.jetbrains.kotlin.idea.util.application.runWriteAction
|
||||
import org.jetbrains.kotlin.psi.*
|
||||
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
|
||||
@@ -78,6 +79,9 @@ class IfThenToElvisIntention : SelfTargetingOffsetIndependentIntention<KtIfExpre
|
||||
val ifThenToSelectData = element.buildSelectTransformationData() ?: return
|
||||
|
||||
val factory = KtPsiFactory(element)
|
||||
|
||||
val commentSaver = CommentSaver(element, saveLineBreaks = true)
|
||||
|
||||
val elvis = runWriteAction {
|
||||
val replacedBaseClause = ifThenToSelectData.replacedBaseClause(factory)
|
||||
val newExpr = element.replaced(
|
||||
@@ -87,7 +91,10 @@ class IfThenToElvisIntention : SelfTargetingOffsetIndependentIntention<KtIfExpre
|
||||
ifThenToSelectData.negatedClause!!
|
||||
)
|
||||
)
|
||||
KtPsiUtil.deparenthesize(newExpr) as KtBinaryExpression
|
||||
|
||||
(KtPsiUtil.deparenthesize(newExpr) as KtBinaryExpression).also {
|
||||
commentSaver.restore(it)
|
||||
}
|
||||
}
|
||||
|
||||
if (editor != null) {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
fun foo(arg: Any): Int {
|
||||
// 1
|
||||
return <caret>if (arg is Int) arg
|
||||
// 2
|
||||
else 10
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
fun foo(arg: Any): Int {
|
||||
// 1
|
||||
return arg as? Int
|
||||
// 2
|
||||
?: 10
|
||||
}
|
||||
@@ -2499,6 +2499,11 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
|
||||
runTest("idea/testData/intentions/branched/ifThenToElvis/ifAsPartOfExpression.kt");
|
||||
}
|
||||
|
||||
@TestMetadata("ifToElvisSwallowComments.kt")
|
||||
public void testIfToElvisSwallowComments() throws Exception {
|
||||
runTest("idea/testData/intentions/branched/ifThenToElvis/ifToElvisSwallowComments.kt");
|
||||
}
|
||||
|
||||
@TestMetadata("implicitReceiver.kt")
|
||||
public void testImplicitReceiver() throws Exception {
|
||||
runTest("idea/testData/intentions/branched/ifThenToElvis/implicitReceiver.kt");
|
||||
|
||||
Reference in New Issue
Block a user