KT-34572 Convert to block body action improperly works with suppress annotations (#2969)

* Convert to block body: place @Suppress annotation before return expression

#KT-34572 Fixed

* Convert to block body: place annotations before return expression
This commit is contained in:
Toshiaki Kameyama
2020-08-20 17:15:00 +09:00
committed by GitHub
parent 9e0bb4ce8e
commit 8ce9b2d061
5 changed files with 46 additions and 5 deletions
@@ -58,10 +58,20 @@ class ConvertToBlockBodyIntention : SelfTargetingIntention<KtDeclarationWithBody
val factory = KtPsiFactory(declaration)
if (bodyType != null && bodyType.isUnit() && body is KtNameReferenceExpression) return factory.createEmptyBody()
val unitWhenAsResult = (bodyType == null || bodyType.isUnit()) && body.resultingWhens().isNotEmpty()
val needReturn = returnsValue &&
(bodyType == null || (!bodyType.isUnit() && !bodyType.isNothing()))
val statement = if (needReturn || unitWhenAsResult) factory.createExpressionByPattern("return $0", body) else body
return factory.createSingleStatementBlock(statement)
val needReturn = returnsValue && (bodyType == null || (!bodyType.isUnit() && !bodyType.isNothing()))
return if (needReturn || unitWhenAsResult) {
val annotatedExpr = body as? KtAnnotatedExpression
val returnedExpr = annotatedExpr?.baseExpression ?: body
val block = factory.createSingleStatementBlock(factory.createExpressionByPattern("return $0", returnedExpr))
val statement = block.firstStatement
annotatedExpr?.annotationEntries?.forEach {
block.addBefore(it, statement)
block.addBefore(factory.createNewLine(), statement)
}
block
} else {
factory.createSingleStatementBlock(body)
}
}
val newBody = when (declaration) {
@@ -3,5 +3,6 @@
annotation class ann
fun foo(): Int {
return (@ann 1)
@ann
return 1
}
@@ -0,0 +1,12 @@
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class ann
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class ann2
fun test() =<caret>
@ann
@ann2
1
@@ -0,0 +1,13 @@
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class ann
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class ann2
fun test(): Int {
@ann
@ann2
return 1
}
@@ -6887,6 +6887,11 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
runTest("idea/testData/intentions/convertToBlockBody/annotatedExpr.kt");
}
@TestMetadata("annotatedExpr2.kt")
public void testAnnotatedExpr2() throws Exception {
runTest("idea/testData/intentions/convertToBlockBody/annotatedExpr2.kt");
}
@TestMetadata("explicitlyNonUnitFun.kt")
public void testExplicitlyNonUnitFun() throws Exception {
runTest("idea/testData/intentions/convertToBlockBody/explicitlyNonUnitFun.kt");