ReplaceToStringWithStringTemplateInspection: insert curly braces if needed

#KT-36735 Fixed
This commit is contained in:
Toshiaki Kameyama
2020-02-18 01:20:24 +09:00
committed by Vladimir Dolzhenko
parent c87bc2123c
commit ef1e54eda9
4 changed files with 17 additions and 5 deletions
@@ -7,11 +7,10 @@ package org.jetbrains.kotlin.idea.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.core.canDropBraces
import org.jetbrains.kotlin.idea.core.dropBraces
import org.jetbrains.kotlin.idea.intentions.isToString
import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.*
class ReplaceToStringWithStringTemplateInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
@@ -24,7 +23,9 @@ class ReplaceToStringWithStringTemplateInspection : AbstractApplicabilityBasedIn
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val variable = element.receiverExpression.text
element.replace(KtPsiFactory(element).createExpression("\"$$variable\""))
val replaced = element.replace(KtPsiFactory(element).createExpression("\"\${$variable}\""))
val blockStringTemplateEntry = (replaced as? KtStringTemplateExpression)?.entries?.firstOrNull() as? KtBlockStringTemplateEntry
if (blockStringTemplateEntry?.canDropBraces() == true) blockStringTemplateEntry.dropBraces()
}
override fun inspectionText(element: KtDotQualifiedExpression) = "Call of 'toString' could be replaced with string template"
@@ -0,0 +1,3 @@
data class Num(val x: Int)
fun demo(x: Int) = Num(x).toString()<caret>
@@ -0,0 +1,3 @@
data class Num(val x: Int)
fun demo(x: Int) = "${Num(x)}"
@@ -11001,6 +11001,11 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("idea/testData/inspectionsLocal/replaceToStringWithStringTemplate"), Pattern.compile("^([\\w\\-_]+)\\.(kt|kts)$"), null, true);
}
@TestMetadata("callExpression.kt")
public void testCallExpression() throws Exception {
runTest("idea/testData/inspectionsLocal/replaceToStringWithStringTemplate/callExpression.kt");
}
@TestMetadata("nonReference.kt")
public void testNonReference() throws Exception {
runTest("idea/testData/inspectionsLocal/replaceToStringWithStringTemplate/nonReference.kt");