From 96c73b286999ec05c0196eab4849f53e8be402ba Mon Sep 17 00:00:00 2001 From: Ilya Gorbunov Date: Fri, 13 Mar 2020 22:37:01 +0300 Subject: [PATCH] Support Throwable.addSuppressed/suppressedExceptions #KT-35013 (cherry picked from commit f790472260367a690c8a87da793bceaf65ad9567) --- backend.native/tests/stdlib_external/utils.kt | 2 ++ runtime/src/main/kotlin/kotlin/Throwable.kt | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/backend.native/tests/stdlib_external/utils.kt b/backend.native/tests/stdlib_external/utils.kt index 4ead55a24fd..6a5d6e51c6c 100644 --- a/backend.native/tests/stdlib_external/utils.kt +++ b/backend.native/tests/stdlib_external/utils.kt @@ -27,3 +27,5 @@ actual fun testOnJs(action: () -> Unit) {} public actual val isFloat32RangeEnforced: Boolean get() = true + +public actual val supportsSuppressedExceptions: Boolean get() = true \ No newline at end of file diff --git a/runtime/src/main/kotlin/kotlin/Throwable.kt b/runtime/src/main/kotlin/kotlin/Throwable.kt index 6ceaaca044a..816b61c57dc 100644 --- a/runtime/src/main/kotlin/kotlin/Throwable.kt +++ b/runtime/src/main/kotlin/kotlin/Throwable.kt @@ -6,6 +6,7 @@ package kotlin import kotlin.native.concurrent.freeze +import kotlin.native.concurrent.isFrozen import kotlin.native.internal.ExportForCppRuntime import kotlin.native.internal.ExportTypeInfo import kotlin.native.internal.NativePtrArray @@ -75,6 +76,8 @@ public open class Throwable(open val message: String?, open val cause: Throwable val s = kClass.qualifiedName ?: kClass.simpleName ?: "Throwable" return if (message != null) s + ": " + message.toString() else s } + + internal var suppressedExceptionsList: MutableList? = null } @SymbolName("Kotlin_getCurrentStackTrace") @@ -82,3 +85,30 @@ private external fun getCurrentStackTrace(): NativePtrArray @SymbolName("Kotlin_getStackTraceStrings") private external fun getStackTraceStrings(stackTrace: NativePtrArray): Array + + +/** + * Adds the specified exception to the list of exceptions that were + * suppressed in order to deliver this exception. + * + * Does nothing if this [Throwable] is frozen. + */ +@SinceKotlin("1.4") +public actual fun Throwable.addSuppressed(exception: Throwable) { + if (this !== exception && !this.isFrozen) { + val suppressed = suppressedExceptionsList + when { + suppressed == null -> suppressedExceptionsList = mutableListOf(exception) + suppressed.isFrozen -> suppressedExceptionsList = suppressed.toMutableList().apply { add(exception) } + else -> suppressed.add(exception) + } + } +} + +/** + * Returns a list of all exceptions that were suppressed in order to deliver this exception. + */ +@SinceKotlin("1.4") +public actual val Throwable.suppressedExceptions: List get() { + return this.suppressedExceptionsList ?: emptyList() +}