Add minor improvement to kotlin String literals in generated sources
This commit is contained in:
committed by
SvyatoslavScherbina
parent
29d77d3867
commit
4335f891b7
+17
-11
@@ -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<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())
|
||||
|
||||
Reference in New Issue
Block a user