1use alloc::sync::Arc;
4use core::{
5 future::Future,
6 pin::Pin,
7 task::{Context, Poll, Waker},
8};
9
10use pyo3_macros::{pyclass, pymethods};
11
12#[cfg(all(wip_feature_std, panic = "unwind"))]
13use crate::panic::PanicException;
14use crate::platform::prelude::*;
15use crate::{
16 Bound, Py, PyAny, PyErr, PyResult, Python,
17 coroutine::{cancel::ThrowCallback, waker::AsyncioWaker},
18 exceptions::{PyAttributeError, PyRuntimeError, PyStopIteration},
19 types::{PyIterator, PyString, string::PyStringMethods},
20};
21
22pub(crate) mod cancel;
23mod waker;
24
25pub use cancel::CancelHandle;
26
27const COROUTINE_REUSED_ERROR: &str = "cannot reuse already awaited coroutine";
28
29#[pyclass(crate = "crate")]
31pub struct Coroutine {
32 name: Option<Py<PyString>>,
33 qualname_prefix: Option<&'static str>,
34 throw_callback: Option<ThrowCallback>,
35 #[expect(clippy::type_complexity)]
36 future: Option<Pin<Box<dyn Future<Output = PyResult<Py<PyAny>>> + Send>>>,
37 waker: Option<Arc<AsyncioWaker>>,
38}
39
40unsafe impl Sync for Coroutine {}
43
44impl Coroutine {
45 pub(crate) fn new<'py, F>(
52 name: Option<Bound<'py, PyString>>,
53 qualname_prefix: Option<&'static str>,
54 throw_callback: Option<ThrowCallback>,
55 future: F,
56 ) -> Self
57 where
58 F: Future<Output = Result<Py<PyAny>, PyErr>> + Send + 'static,
59 {
60 Self {
61 name: name.map(Bound::unbind),
62 qualname_prefix,
63 throw_callback,
64 future: Some(Box::pin(future)),
65 waker: None,
66 }
67 }
68
69 fn poll(&mut self, py: Python<'_>, throw: Option<Py<PyAny>>) -> PyResult<Py<PyAny>> {
70 let future_rs = match self.future {
72 Some(ref mut fut) => fut,
73 None => return Err(PyRuntimeError::new_err(COROUTINE_REUSED_ERROR)),
74 };
75 match (throw, &self.throw_callback) {
77 (Some(exc), Some(cb)) => cb.throw(exc),
78 (Some(exc), None) => {
79 self.close();
80 return Err(PyErr::from_value(exc.into_bound(py)));
81 }
82 (None, _) => {}
83 }
84 if let Some(waker) = self.waker.as_mut().and_then(Arc::get_mut) {
86 waker.reset();
87 } else {
88 self.waker = Some(Arc::new(AsyncioWaker::new()));
89 }
90 let waker = Waker::from(self.waker.clone().unwrap());
91 #[allow(unused_mut, reason = "conditional compilation")]
94 let mut poll = || future_rs.as_mut().poll(&mut Context::from_waker(&waker));
95 let res = cfg_select! {
96 all(wip_feature_std, panic = "unwind") => {
97 std::panic::catch_unwind(core::panic::AssertUnwindSafe(poll)).map_err(|payload| {
98 self.close();
99 PanicException::from_panic_payload(payload)
100 })?
101 },
102
103 _ => poll(),
104 };
105 if let Poll::Ready(res) = res {
106 self.close();
107 return Err(PyStopIteration::new_err((res?,)));
108 }
109
110 if let Some(future) = self.waker.as_ref().unwrap().initialize_future(py)? {
112 if let Some(future) = PyIterator::from_object(future).unwrap().next() {
115 return Ok(future.unwrap().into());
118 }
119 }
120 Ok(py.None())
123 }
124}
125
126#[pymethods(crate = "crate")]
127impl Coroutine {
128 #[getter]
129 fn __name__(&self, py: Python<'_>) -> PyResult<Py<PyString>> {
130 match &self.name {
131 Some(name) => Ok(name.clone_ref(py)),
132 None => Err(PyAttributeError::new_err("__name__")),
133 }
134 }
135
136 #[getter]
137 fn __qualname__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
138 match (&self.name, &self.qualname_prefix) {
139 (Some(name), Some(prefix)) => Ok(PyString::new(
140 py,
141 &format!("{}.{}", prefix, name.bind(py).to_cow()?),
142 )),
143 (Some(name), None) => Ok(name.bind(py).clone()),
144 (None, _) => Err(PyAttributeError::new_err("__qualname__")),
145 }
146 }
147
148 fn send(&mut self, py: Python<'_>, _value: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
149 self.poll(py, None)
150 }
151
152 fn throw(&mut self, py: Python<'_>, exc: Py<PyAny>) -> PyResult<Py<PyAny>> {
153 self.poll(py, Some(exc))
154 }
155
156 fn close(&mut self) {
157 drop(self.future.take());
160 }
161
162 fn __await__(self_: Py<Self>) -> Py<Self> {
163 self_
164 }
165
166 fn __next__(&mut self, py: Python<'_>) -> PyResult<Py<PyAny>> {
167 self.poll(py, None)
168 }
169}