From 4335f891b7bbbfc2880ce1661a7ff80926b93412 Mon Sep 17 00:00:00 2001 From: Svyatoslav Scherbina Date: Mon, 19 Feb 2018 17:29:32 +0300 Subject: [PATCH] Add minor improvement to kotlin String literals in generated sources --- .../kotlin/native/interop/gen/CodeUtils.kt | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/CodeUtils.kt b/Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/CodeUtils.kt index 35677719d03..9517a26a6e2 100644 --- a/Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/CodeUtils.kt +++ b/Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/CodeUtils.kt @@ -48,21 +48,27 @@ fun String.asSimpleName(): String = if (this in kotlinKeywords) { * Returns the expression to be parsed by Kotlin as string literal with given contents, * i.e. transforms `foo$bar` to `"foo\$bar"`. */ -fun String.quoteAsKotlinLiteral(): KotlinExpression { - val sb = StringBuilder() - sb.append('"') +fun String.quoteAsKotlinLiteral(): KotlinExpression = buildString { + append('"') - this.forEach { c -> - val escaped = when (c) { - in 'a' .. 'z', in 'A' .. 'Z', in '0' .. '9', '_', '@', ':', '{', '}', '=', '[', ']', '^', '#', '*' -> c.toString() - '$' -> "\\$" - else -> "\\u" + "%04X".format(c.toInt()) // TODO: improve result readability by preserving more characters. + this@quoteAsKotlinLiteral.forEach { c -> + when (c) { + in charactersAllowedInKotlinStringLiterals -> append(c) + '$' -> append("\\$") + else -> append("\\u" + "%04X".format(c.toInt())) } - sb.append(escaped) } - sb.append('"') - return sb.toString() + append('"') +} + +// TODO: improve literal readability by preserving more characters. + +private val charactersAllowedInKotlinStringLiterals: Set = mutableSetOf().apply { + addAll('a' .. 'z') + addAll('A' .. 'Z') + addAll('0' .. '9') + addAll(listOf('_', '@', ':', ';', '.', ',', '{', '}', '=', '[', ']', '^', '#', '*', ' ')) } fun block(header: String, lines: Iterable) = block(header, lines.asSequence())