Skip to content

Commit

Permalink
Support special characters in coroutine names in JSON dumps (#3747)
Browse files Browse the repository at this point in the history
  • Loading branch information
dkhalanskyjb authored May 12, 2023
1 parent c8b3e5e commit 1aacb04
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
24 changes: 20 additions & 4 deletions kotlinx-coroutines-core/jvm/src/debug/internal/DebugProbesImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,8 @@ internal object DebugProbesImpl {
val coroutinesInfoAsJson = ArrayList<String>(size)
for (info in coroutinesInfo) {
val context = info.context
val name = context[CoroutineName.Key]?.name?.toStringWithQuotes()
val dispatcher = context[CoroutineDispatcher.Key]?.toStringWithQuotes()
val name = context[CoroutineName.Key]?.name?.toStringRepr()
val dispatcher = context[CoroutineDispatcher.Key]?.toStringRepr()
coroutinesInfoAsJson.add(
"""
{
Expand Down Expand Up @@ -219,7 +219,7 @@ internal object DebugProbesImpl {
{
"declaringClass": "${element.className}",
"methodName": "${element.methodName}",
"fileName": ${element.fileName?.toStringWithQuotes()},
"fileName": ${element.fileName?.toStringRepr()},
"lineNumber": ${element.lineNumber}
}
""".trimIndent()
Expand All @@ -229,7 +229,7 @@ internal object DebugProbesImpl {
return "[${stackTraceElementsInfoAsJson.joinToString()}]"
}

private fun Any.toStringWithQuotes() = "\"$this\""
private fun Any.toStringRepr() = toString().repr()

/*
* Internal (JVM-public) method used by IDEA debugger as of 1.4-M3.
Expand Down Expand Up @@ -590,3 +590,19 @@ internal object DebugProbesImpl {

private val StackTraceElement.isInternalMethod: Boolean get() = className.startsWith("kotlinx.coroutines")
}

private fun String.repr(): String = buildString {
append('"')
for (c in this@repr) {
when (c) {
'"' -> append("\\\"")
'\\' -> append("\\\\")
'\b' -> append("\\b")
'\n' -> append("\\n")
'\r' -> append("\\r")
'\t' -> append("\\t")
else -> append(c)
}
}
append('"')
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ class DumpCoroutineInfoAsJsonAndReferencesTest : DebugTestBase() {
fun testDumpOfNamedCoroutine() =
runTestWithNamedDeferred("Name")

@Test
fun testDumpOfNamedCoroutineWithSpecialCharacters() =
runTestWithNamedDeferred("Name with\n \"special\" characters\\/\t\b")

@Test
fun testDumpWithNoCoroutines() {
val dumpResult = DebugProbesImpl.dumpCoroutinesInfoAsJsonAndReferences()
Expand Down

0 comments on commit 1aacb04

Please sign in to comment.