Replace 'if' with 'when': don't swallow comments if there is no synthetic else branch

#KT-34640 Fixed
This commit is contained in:
Toshiaki Kameyama
2020-01-17 19:34:47 +09:00
committed by Vladimir Dolzhenko
parent f487118be5
commit 699ea0aa2b
4 changed files with 36 additions and 1 deletions
@@ -168,7 +168,11 @@ class IfToWhenIntention : SelfTargetingRangeIntention<KtIfExpression>(KtIfExpres
val currentElseBranch = currentIfExpression.`else` val currentElseBranch = currentIfExpression.`else`
if (currentElseBranch == null) { if (currentElseBranch == null) {
// Try to build synthetic if / else according to KT-10750 // Try to build synthetic if / else according to KT-10750
val syntheticElseBranch = if (canPassThrough) break else buildNextBranch(baseIfExpressionForSyntheticBranch) ?: break val syntheticElseBranch = if (canPassThrough) null else buildNextBranch(baseIfExpressionForSyntheticBranch)
if (syntheticElseBranch == null) {
applyFullCommentSaver = false
break
}
toDelete.addAll(baseIfExpressionForSyntheticBranch.siblingsUpTo(syntheticElseBranch)) toDelete.addAll(baseIfExpressionForSyntheticBranch.siblingsUpTo(syntheticElseBranch))
if (syntheticElseBranch is KtIfExpression) { if (syntheticElseBranch is KtIfExpression) {
baseIfExpressionForSyntheticBranch = syntheticElseBranch baseIfExpressionForSyntheticBranch = syntheticElseBranch
@@ -0,0 +1,12 @@
fun test(foo: String) {
<caret>if (foo == "1") {
println("1")
}
if (foo == "a") {
// some comments for "a"
println("a");
}
}
fun println(s: String) {}
@@ -0,0 +1,14 @@
fun test(foo: String) {
when (foo) {
"1" -> {
println("1")
}
}
if (foo == "a") {
// some comments for "a"
println("a");
}
}
fun println(s: String) {}
@@ -2327,6 +2327,11 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
runTest("idea/testData/intentions/branched/ifWhen/ifToWhen/comment.kt"); runTest("idea/testData/intentions/branched/ifWhen/ifToWhen/comment.kt");
} }
@TestMetadata("doNotSwallowComment.kt")
public void testDoNotSwallowComment() throws Exception {
runTest("idea/testData/intentions/branched/ifWhen/ifToWhen/doNotSwallowComment.kt");
}
@TestMetadata("ifElseSwallowComments.kt") @TestMetadata("ifElseSwallowComments.kt")
public void testIfElseSwallowComments() throws Exception { public void testIfElseSwallowComments() throws Exception {
runTest("idea/testData/intentions/branched/ifWhen/ifToWhen/ifElseSwallowComments.kt"); runTest("idea/testData/intentions/branched/ifWhen/ifToWhen/ifElseSwallowComments.kt");