@@ -2,6 +2,7 @@ package python.multiplatform.ffi.upcall
22
33import python.multiplatform.ffi.PyLong_Check
44import python.multiplatform.ffi.PyObject
5+ import python.multiplatform.ffi.exceptions.PyException
56import python.multiplatform.ffi.getThreadGILState
67import python.multiplatform.ffi.types.basic.PyNone
78import python.multiplatform.reflection.CallableHandle
@@ -10,20 +11,26 @@ import python.multiplatform.reflection.HandleTable
1011import python.multiplatform.reflection.ObjectReference
1112import python.multiplatform.reflection.TypeTag
1213import python.multiplatform.reflection.UpcallTable
14+ import kotlin.coroutines.cancellation.CancellationException
1315import python.native.ffi.NativePointer
1416import python.native.ffi.PyBool_FromLong
1517import python.native.ffi.PyBytes_FromObject
1618import python.native.ffi.PyDict_GetItemString
1719import python.native.ffi.PyErr_Clear
1820import python.native.ffi.PyErr_Occurred
21+ import python.native.ffi.PyErr_SetRaisedException
1922import python.native.ffi.PyErr_SetString
2023import python.native.ffi.PyEval_GetBuiltins
24+ import python.native.ffi.PyException_SetCause
2125import python.native.ffi.PyFloat_AsDouble
2226import python.native.ffi.PyGILState_Ensure
2327import python.native.ffi.PyGILState_Release
2428import python.native.ffi.PyFloat_FromDouble
29+ import python.native.ffi.PyImport_ImportModule
2530import python.native.ffi.PyLong_AsLongLong
2631import python.native.ffi.PyLong_FromLongLong
32+ import python.native.ffi.PyObject_CallObject
33+ import python.native.ffi.PyObject_GetAttrString
2734import python.native.ffi.PyObject_GetItem
2835import python.native.ffi.PyObject_IsTrue
2936import python.native.ffi.PyObject_Size
@@ -379,19 +386,173 @@ object UpcallTrampoline {
379386 private fun raiseInPython (t : Throwable ) {
380387 try {
381388 if (PyErr_Occurred () != null ) return
382- val message = t.message ? : t::class .simpleName ? : " upcall failed"
383- PyErr_SetString (runtimeErrorType, message)
389+ val excPtr = buildPythonExceptionPointer(t)
390+ if (excPtr != null ) {
391+ PyErr_SetRaisedException (excPtr)
392+ } else {
393+ val message = t.message ? : t::class .simpleName ? : " upcall failed"
394+ PyErr_SetString (runtimeErrorType, message)
395+ }
384396 } catch (_: Throwable ) {
385397 // Reporting the failure failed. Returning NULL with no indicator set is still a
386398 // Python-level error ("SystemError: returned NULL without setting an exception"),
387399 // which is strictly better than unwinding into C.
388400 }
389401 }
390402
403+ /* *
404+ * Builds a **new** reference to the Python `BaseException` instance [t] maps to (SPEC U-2, U-5;
405+ * issue #164). Caller must hold the GIL.
406+ *
407+ * - A [PyException] with a live [PyException.value] returns an incremented reference to that
408+ * original Python exception instance.
409+ * - A Kotlin [CancellationException] whose [Throwable.cause] is a [PyException] with
410+ * [PyException.isCancelledError] and a live value returns an incremented reference to that
411+ * original Python `CancelledError`.
412+ * - Any other Kotlin [CancellationException] builds an `asyncio.CancelledError`
413+ * (`concurrent.futures.CancelledError`), attaching any non-null [Throwable.cause] as
414+ * `__cause__`.
415+ * - Any other Kotlin [Throwable] builds a `RuntimeError(message)` and attaches a cause chain
416+ * representing [t] (and its nested [Throwable.cause] chain) onto `__cause__`.
417+ */
418+ internal fun buildPythonExceptionPointer (t : Throwable ): NativePointer ? {
419+ if (t is PyException ) {
420+ val liveValue = t.value
421+ if (liveValue != null ) {
422+ Py_IncRef (liveValue.pointer)
423+ return liveValue.pointer
424+ }
425+ }
426+ if (t is CancellationException ) {
427+ val pyCause = t.cause as ? PyException
428+ if (pyCause != null && pyCause.isCancelledError()) {
429+ val liveValue = pyCause.value
430+ if (liveValue != null ) {
431+ Py_IncRef (liveValue.pointer)
432+ return liveValue.pointer
433+ }
434+ }
435+ val message = t.message ? : t::class .simpleName ? : " the Kotlin call was cancelled"
436+ val cancelledType = resolveCancelledErrorType()
437+ val excType = cancelledType ? : runtimeErrorType
438+ val excPtr = instantiateException(excType, message)
439+ if (cancelledType != null ) Py_DecRef (cancelledType)
440+ if (excPtr == null ) return null
441+ val kotlinCause = t.cause
442+ if (kotlinCause != null ) {
443+ val causePtr = buildKotlinCausePointer(kotlinCause, depth = 0 )
444+ if (causePtr != null ) {
445+ PyException_SetCause (excPtr, causePtr)
446+ }
447+ }
448+ return excPtr
449+ }
450+ val message = t.message ? : t::class .simpleName ? : " upcall failed"
451+ val excPtr = instantiateException(runtimeErrorType, message) ? : return null
452+ val causePtr = buildKotlinCausePointer(t, depth = 0 )
453+ if (causePtr != null ) {
454+ PyException_SetCause (excPtr, causePtr)
455+ }
456+ return excPtr
457+ }
458+
459+ /* *
460+ * Wraps [buildPythonExceptionPointer] as an owned [PyObject] for [AsyncUpcall]'s
461+ * `Future.set_exception`, falling back to `RuntimeError(message)` if construction fails.
462+ */
463+ internal fun pythonExceptionObjectFor (t : Throwable ): PyObject {
464+ val ptr = buildPythonExceptionPointer(t)
465+ if (ptr != null ) return PyObject (ptr, borrowed = false )
466+ val message = t.message ? : t::class .simpleName ? : " the exposed suspending function failed"
467+ return runtimeErrorClass().invoke(python.multiplatform.ffi.types.basic.PyString .from(message))
468+ }
469+
470+ /* *
471+ * Builds a **new** reference to the `BaseException` placed on `__cause__` for a Kotlin
472+ * [Throwable] (SPEC U-2, issue #164).
473+ */
474+ private fun buildKotlinCausePointer (t : Throwable , depth : Int ): NativePointer ? {
475+ if (depth >= MAX_CAUSE_DEPTH ) return null
476+ if (t is PyException ) {
477+ val liveValue = t.value
478+ if (liveValue != null ) {
479+ Py_IncRef (liveValue.pointer)
480+ return liveValue.pointer
481+ }
482+ }
483+ val className = t::class .simpleName ? : " Throwable"
484+ val msg = t.message
485+ val summary = if (msg.isNullOrEmpty()) className else " $className : $msg "
486+ val causePtr = instantiateException(runtimeErrorType, summary) ? : return null
487+ val nested = t.cause
488+ if (nested != null && nested != = t) {
489+ val nestedPtr = buildKotlinCausePointer(nested, depth + 1 )
490+ if (nestedPtr != null ) {
491+ PyException_SetCause (causePtr, nestedPtr)
492+ }
493+ }
494+ return causePtr
495+ }
496+
497+ /* * Calls `excType(message)` and returns the new exception reference, clearing any error on failure. */
498+ private fun instantiateException (excType : NativePointer , message : String ): NativePointer ? {
499+ val msgPtr = PyUnicode_FromString (message) ? : run {
500+ PyErr_Clear ()
501+ return null
502+ }
503+ val tuple = PyTuple_New (1 ) ? : run {
504+ Py_DecRef (msgPtr)
505+ PyErr_Clear ()
506+ return null
507+ }
508+ // PyTuple_SetItem steals msgPtr.
509+ PyTuple_SetItem (tuple, 0 , msgPtr)
510+ val instance = try {
511+ PyObject_CallObject (excType, tuple)
512+ } finally {
513+ Py_DecRef (tuple)
514+ }
515+ if (instance == null ) {
516+ PyErr_Clear ()
517+ }
518+ return instance
519+ }
520+
521+ /* *
522+ * Resolves Python's `CancelledError` type as a **new** reference by importing
523+ * `concurrent.futures._base` (pure Python, does not load `selectors`, so it is safe on every
524+ * target including `wasmJs`; in CPython 3.8+, `asyncio.CancelledError` is
525+ * `concurrent.futures.CancelledError`). Caller must `Py_DecRef` the returned non-null pointer.
526+ */
527+ private fun resolveCancelledErrorType (): NativePointer ? {
528+ val mod = PyImport_ImportModule (" concurrent.futures._base" )
529+ ? : run {
530+ PyErr_Clear ()
531+ PyImport_ImportModule (" asyncio.exceptions" )
532+ }
533+ ? : run {
534+ PyErr_Clear ()
535+ return null
536+ }
537+ return try {
538+ val attr = PyObject_GetAttrString (mod, " CancelledError" )
539+ if (attr == null ) {
540+ PyErr_Clear ()
541+ null
542+ } else {
543+ attr
544+ }
545+ } finally {
546+ Py_DecRef (mod)
547+ }
548+ }
549+
550+ private const val MAX_CAUSE_DEPTH = 16
551+
391552 /* * Raises whatever Python already put on the indicator as a Kotlin exception, or a fallback. */
392553 private fun failFromPython (what : String ): Nothing {
393- val pending = python.multiplatform.ffi.exceptions. PyException .fromCurrentError()
394- throw pending ? : IllegalArgumentException (what)
554+ val pending = PyException .fromCurrentError()
555+ throw pending?.toKotlinException() ? : IllegalArgumentException (what)
395556 }
396557
397558 /* *
@@ -400,9 +561,9 @@ object UpcallTrampoline {
400561 */
401562 private fun checkPythonError (what : String ) {
402563 if (PyErr_Occurred () == null ) return
403- val pending = python.multiplatform.ffi.exceptions. PyException .fromCurrentError()
564+ val pending = PyException .fromCurrentError()
404565 PyErr_Clear ()
405- throw pending ? : IllegalArgumentException (what)
566+ throw pending?.toKotlinException() ? : IllegalArgumentException (what)
406567 }
407568
408569 // ---------------------------------------------------------------------------------------
0 commit comments