Add minor improvement to kotlin String literals in generated sources

This commit is contained in:
Svyatoslav Scherbina
2018-02-19 17:29:32 +03:00
committed by SvyatoslavScherbina
parent 29d77d3867
commit 4335f891b7
@@ -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, * Returns the expression to be parsed by Kotlin as string literal with given contents,
* i.e. transforms `foo$bar` to `"foo\$bar"`. * i.e. transforms `foo$bar` to `"foo\$bar"`.
*/ */
fun String.quoteAsKotlinLiteral(): KotlinExpression { fun String.quoteAsKotlinLiteral(): KotlinExpression = buildString {
val sb = StringBuilder() append('"')
sb.append('"')
this.forEach { c -> this@quoteAsKotlinLiteral.forEach { c ->
val escaped = when (c) { when (c) {
in 'a' .. 'z', in 'A' .. 'Z', in '0' .. '9', '_', '@', ':', '{', '}', '=', '[', ']', '^', '#', '*' -> c.toString() in charactersAllowedInKotlinStringLiterals -> append(c)
'$' -> "\\$" '$' -> append("\\$")
else -> "\\u" + "%04X".format(c.toInt()) // TODO: improve result readability by preserving more characters. else -> append("\\u" + "%04X".format(c.toInt()))
} }
sb.append(escaped)
} }
sb.append('"') append('"')
return sb.toString() }
// TODO: improve literal readability by preserving more characters.
private val charactersAllowedInKotlinStringLiterals: Set<Char> = mutableSetOf<Char>().apply {
addAll('a' .. 'z')
addAll('A' .. 'Z')
addAll('0' .. '9')
addAll(listOf('_', '@', ':', ';', '.', ',', '{', '}', '=', '[', ']', '^', '#', '*', ' '))
} }
fun block(header: String, lines: Iterable<String>) = block(header, lines.asSequence()) fun block(header: String, lines: Iterable<String>) = block(header, lines.asSequence())