If to when: do not add label to outer loop if not necessary
So #KT-24767 Fixed
This commit is contained in:
+4
-1
@@ -89,11 +89,14 @@ class IfToWhenIntention : SelfTargetingRangeIntention<KtIfExpression>(KtIfExpres
|
||||
}
|
||||
}
|
||||
|
||||
var labelRequired = false
|
||||
|
||||
fun KtExpressionWithLabel.addLabelIfNecessary(): KtExpressionWithLabel {
|
||||
if (this.getLabelName() != null) return this
|
||||
if (this.getStrictParentOfType<KtLoopExpression>() != nearestLoopIfAny) return this
|
||||
if (labelName != null) {
|
||||
val jumpWithLabel = KtPsiFactory(project).createExpression("$text@$labelName") as KtExpressionWithLabel
|
||||
labelRequired = true
|
||||
return replaced(jumpWithLabel)
|
||||
}
|
||||
return this
|
||||
@@ -187,7 +190,7 @@ class IfToWhenIntention : SelfTargetingRangeIntention<KtIfExpression>(KtIfExpres
|
||||
|
||||
result.accept(loopJumpVisitor)
|
||||
val labelName = loopJumpVisitor.labelName
|
||||
if (loop != null && labelName != null && loop.parent !is KtLabeledExpression) {
|
||||
if (loop != null && loopJumpVisitor.labelRequired && labelName != null && loop.parent !is KtLabeledExpression) {
|
||||
val labeledLoopExpression = KtPsiFactory(result).createLabeledExpression(labelName)
|
||||
labeledLoopExpression.baseExpression!!.replace(loop)
|
||||
val replacedLabeledLoopExpression = loop.replace(labeledLoopExpression)
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
fun test() {
|
||||
for (i in -2..2) {
|
||||
<caret>if (i > 0) i.hashCode()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
fun test() {
|
||||
for (i in -2..2) {
|
||||
when {
|
||||
i > 0 -> i.hashCode()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2619,6 +2619,11 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
|
||||
runTest("idea/testData/intentions/branched/ifWhen/ifToWhen/withLoopExistingLabel.kt");
|
||||
}
|
||||
|
||||
@TestMetadata("withLoopNoJumps.kt")
|
||||
public void testWithLoopNoJumps() throws Exception {
|
||||
runTest("idea/testData/intentions/branched/ifWhen/ifToWhen/withLoopNoJumps.kt");
|
||||
}
|
||||
|
||||
@TestMetadata("withLoopOriginal.kt")
|
||||
public void testWithLoopOriginal() throws Exception {
|
||||
runTest("idea/testData/intentions/branched/ifWhen/ifToWhen/withLoopOriginal.kt");
|
||||
|
||||
Reference in New Issue
Block a user