Add `Name.renderForSource` util
diff --git a/compiler/tests/org/jetbrains/kotlin/renderer/RenderingUtilsTest.kt b/compiler/tests/org/jetbrains/kotlin/renderer/RenderingUtilsTest.kt index c63ae3b..3d1ed41 100644 --- a/compiler/tests/org/jetbrains/kotlin/renderer/RenderingUtilsTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/renderer/RenderingUtilsTest.kt
@@ -9,6 +9,7 @@ import org.jetbrains.kotlin.name.SpecialNames.NO_NAME_PROVIDED import org.jetbrains.kotlin.name.SpecialNames.UNDERSCORE_FOR_UNUSED_VAR import org.jetbrains.kotlin.name.render +import org.jetbrains.kotlin.name.renderForSource import org.junit.jupiter.api.Test import kotlin.test.assertEquals @@ -34,4 +35,26 @@ assertEquals("`return`", keywordIdentifier.render(stipSpecialMarkers = true)) assertEquals("`return`", keywordIdentifier.render(stipSpecialMarkers = false)) } + + @Test + fun testRenderForSource() { + assertEquals("_", UNDERSCORE_FOR_UNUSED_VAR.renderForSource()) + assertEquals("_", UNDERSCORE_FOR_UNUSED_VAR.renderForSource(stripSpecialMarker = true)) + + val normalIdentifier = Name.identifier("normal") + assertEquals("normal", normalIdentifier.render(stipSpecialMarkers = true)) + assertEquals("normal", normalIdentifier.render(stipSpecialMarkers = false)) + + val escapedIdentifier = Name.identifier("`escaped`") + assertEquals("``escaped``", escapedIdentifier.render(stipSpecialMarkers = true)) + assertEquals("``escaped``", escapedIdentifier.render(stipSpecialMarkers = false)) + + assertEquals("no name provided", NO_NAME_PROVIDED.render(stipSpecialMarkers = true)) + assertEquals("`<no name provided>`", NO_NAME_PROVIDED.render(stipSpecialMarkers = false)) + + // Check a keyword + val keywordIdentifier = Name.identifier("return") + assertEquals("`return`", keywordIdentifier.render(stipSpecialMarkers = true)) + assertEquals("`return`", keywordIdentifier.render(stipSpecialMarkers = false)) + } }
diff --git a/core/names/src/org/jetbrains/kotlin/name/nameRenderingUtils.kt b/core/names/src/org/jetbrains/kotlin/name/nameRenderingUtils.kt index 5242f9a..87500ba 100644 --- a/core/names/src/org/jetbrains/kotlin/name/nameRenderingUtils.kt +++ b/core/names/src/org/jetbrains/kotlin/name/nameRenderingUtils.kt
@@ -14,6 +14,12 @@ return if ((!stipSpecialMarkers || !isSpecial) && shouldBeEscaped(string)) '`' + string + '`' else string } +fun Name.renderForSource(stripSpecialMarker: Boolean = false): String { + if (this == SpecialNames.UNDERSCORE_FOR_UNUSED_VAR) return "_" + + return render(stripSpecialMarker) +} + private fun shouldBeEscaped(string: String): Boolean { return string in KeywordStringsGenerated.KEYWORDS || string.any { !Character.isLetterOrDigit(it) && it != '_' } || @@ -38,4 +44,4 @@ append(element.render()) } } -} \ No newline at end of file +}