Repository navigation
Expand file tree
/
Copy pathcoroutine.rs
More file actions
314 lines (286 loc) · 9.96 KB
/
Copy pathcoroutine.rs
File metadata and controls
314 lines (286 loc) · 9.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyResult, VirtualMachine,
builtins::{PyBaseExceptionRef, PyStrRef},
common::lock::PyMutex,
exceptions::types::PyBaseException,
frame::{ExecutionResult, FrameRef},
function::OptionalArg,
object::{Traverse, TraverseFn},
protocol::PyIterReturn,
};
use crossbeam_utils::atomic::AtomicCell;
impl ExecutionResult {
/// Turn an ExecutionResult into a PyResult that would be returned from a generator or coroutine
fn into_iter_return(self, vm: &VirtualMachine) -> PyIterReturn {
match self {
Self::Yield(value) => PyIterReturn::Return(value),
Self::Return(value) => {
let arg = if vm.is_none(&value) {
None
} else {
Some(value)
};
PyIterReturn::StopIteration(arg)
}
}
}
}
#[derive(Debug)]
pub struct Coro {
frame: FrameRef,
pub closed: AtomicCell<bool>, // TODO: https://github.com/RustPython/RustPython/pull/3183#discussion_r720560652
running: AtomicCell<bool>,
// code
// _weakreflist
name: PyMutex<PyStrRef>,
qualname: PyMutex<PyStrRef>,
exception: PyMutex<Option<PyBaseExceptionRef>>, // exc_state
}
unsafe impl Traverse for Coro {
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
self.frame.traverse(tracer_fn);
self.name.traverse(tracer_fn);
self.qualname.traverse(tracer_fn);
self.exception.traverse(tracer_fn);
}
}
fn gen_name(jen: &PyObject, vm: &VirtualMachine) -> &'static str {
let typ = jen.class();
if typ.is(vm.ctx.types.coroutine_type) {
"coroutine"
} else if typ.is(vm.ctx.types.async_generator) {
"async generator"
} else {
"generator"
}
}
impl Coro {
pub fn new(frame: FrameRef, name: PyStrRef, qualname: PyStrRef) -> Self {
Self {
frame,
closed: AtomicCell::new(false),
running: AtomicCell::new(false),
exception: PyMutex::default(),
name: PyMutex::new(name),
qualname: PyMutex::new(qualname),
}
}
fn maybe_close(&self, res: &PyResult<ExecutionResult>) {
match res {
Ok(ExecutionResult::Return(_)) | Err(_) => self.closed.store(true),
Ok(ExecutionResult::Yield(_)) => {}
}
}
fn run_with_context<F>(
&self,
jen: &PyObject,
vm: &VirtualMachine,
func: F,
) -> PyResult<ExecutionResult>
where
F: FnOnce(FrameRef) -> PyResult<ExecutionResult>,
{
if self.running.compare_exchange(false, true).is_err() {
return Err(vm.new_value_error(format!("{} already executing", gen_name(jen, vm))));
}
// swap exception state
// Get generator's saved exception state from last yield
let gen_exc = self.exception.lock().take();
// Use a slot to capture generator's exception state before with_frame pops
let exception_slot = &self.exception;
// Run the generator frame
// with_frame does push_exception(None) which creates a new exception context
// The caller's exception remains in the chain via prev, so topmost_exception()
// will find it if generator's exception is None
let result = vm.with_frame(self.frame.clone(), |f| {
// with_frame pushed None, creating: { exc: None, prev: caller's exc_info }
// Pop None and push generator's exception instead
// This maintains the chain: { exc: gen_exc, prev: caller's exc_info }
vm.pop_exception();
vm.push_exception(gen_exc);
let result = func(f);
// Save generator's exception state BEFORE with_frame pops
// This is the generator's current exception context
*exception_slot.lock() = vm.current_exception();
result
});
self.running.store(false);
result
}
pub fn send(
&self,
jen: &PyObject,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyIterReturn> {
if self.closed.load() {
return Ok(PyIterReturn::StopIteration(None));
}
let value = if self.frame.lasti() > 0 {
Some(value)
} else if !vm.is_none(&value) {
return Err(vm.new_type_error(format!(
"can't send non-None value to a just-started {}",
gen_name(jen, vm),
)));
} else {
None
};
let result = self.run_with_context(jen, vm, |f| f.resume(value, vm));
self.maybe_close(&result);
match result {
Ok(exec_res) => Ok(exec_res.into_iter_return(vm)),
Err(e) => {
if e.fast_isinstance(vm.ctx.exceptions.stop_iteration) {
let err =
vm.new_runtime_error(format!("{} raised StopIteration", gen_name(jen, vm)));
err.set___cause__(Some(e));
Err(err)
} else if jen.class().is(vm.ctx.types.async_generator)
&& e.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
{
let err = vm.new_runtime_error("async generator raised StopAsyncIteration");
err.set___cause__(Some(e));
Err(err)
} else {
Err(e)
}
}
}
}
pub fn throw(
&self,
jen: &PyObject,
exc_type: PyObjectRef,
exc_val: PyObjectRef,
exc_tb: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyIterReturn> {
if self.closed.load() {
return Err(vm.normalize_exception(exc_type, exc_val, exc_tb)?);
}
let result = self.run_with_context(jen, vm, |f| f.gen_throw(vm, exc_type, exc_val, exc_tb));
self.maybe_close(&result);
Ok(result?.into_iter_return(vm))
}
pub fn close(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
if self.closed.load() {
return Ok(());
}
// If generator hasn't started (FRAME_CREATED), just mark as closed
if self.frame.lasti() == 0 {
self.closed.store(true);
return Ok(());
}
let result = self.run_with_context(jen, vm, |f| {
f.gen_throw(
vm,
vm.ctx.exceptions.generator_exit.to_owned().into(),
vm.ctx.none(),
vm.ctx.none(),
)
});
self.closed.store(true);
match result {
Ok(ExecutionResult::Yield(_)) => {
Err(vm.new_runtime_error(format!("{} ignored GeneratorExit", gen_name(jen, vm))))
}
Err(e) if !is_gen_exit(&e, vm) => Err(e),
_ => Ok(()),
}
}
pub fn running(&self) -> bool {
self.running.load()
}
pub fn closed(&self) -> bool {
self.closed.load()
}
pub fn frame(&self) -> FrameRef {
self.frame.clone()
}
pub fn name(&self) -> PyStrRef {
self.name.lock().clone()
}
pub fn set_name(&self, name: PyStrRef) {
*self.name.lock() = name;
}
pub fn qualname(&self) -> PyStrRef {
self.qualname.lock().clone()
}
pub fn set_qualname(&self, qualname: PyStrRef) {
*self.qualname.lock() = qualname;
}
pub fn repr(&self, jen: &PyObject, id: usize, vm: &VirtualMachine) -> String {
format!(
"<{} object {} at {:#x}>",
gen_name(jen, vm),
self.name.lock(),
id
)
}
}
pub fn is_gen_exit(exc: &Py<PyBaseException>, vm: &VirtualMachine) -> bool {
exc.fast_isinstance(vm.ctx.exceptions.generator_exit)
}
/// Get an awaitable iterator from an object.
///
/// Returns the object itself if it's a coroutine or iterable coroutine (generator with
/// CO_ITERABLE_COROUTINE flag). Otherwise calls `__await__()` and validates the result.
pub fn get_awaitable_iter(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
use crate::builtins::{PyCoroutine, PyGenerator};
use crate::protocol::PyIter;
if obj.downcastable::<PyCoroutine>()
|| obj.downcast_ref::<PyGenerator>().is_some_and(|g| {
g.as_coro()
.frame()
.code
.flags
.contains(crate::bytecode::CodeFlags::ITERABLE_COROUTINE)
})
{
return Ok(obj);
}
if let Some(await_method) = vm.get_method(obj.clone(), identifier!(vm, __await__)) {
let result = await_method?.call((), vm)?;
// __await__() must NOT return a coroutine (PEP 492)
if result.downcastable::<PyCoroutine>()
|| result.downcast_ref::<PyGenerator>().is_some_and(|g| {
g.as_coro()
.frame()
.code
.flags
.contains(crate::bytecode::CodeFlags::ITERABLE_COROUTINE)
})
{
return Err(vm.new_type_error("__await__() returned a coroutine".to_owned()));
}
if !PyIter::check(&result) {
return Err(vm.new_type_error(format!(
"__await__() returned non-iterator of type '{}'",
result.class().name()
)));
}
return Ok(result);
}
Err(vm.new_type_error(format!("'{}' object can't be awaited", obj.class().name())))
}
/// Emit DeprecationWarning for the deprecated 3-argument throw() signature.
pub fn warn_deprecated_throw_signature(
exc_val: &OptionalArg,
exc_tb: &OptionalArg,
vm: &VirtualMachine,
) -> PyResult<()> {
if exc_val.is_present() || exc_tb.is_present() {
crate::warn::warn(
vm.ctx.new_str(
"the (type, val, tb) signature of throw() is deprecated, \
use throw(val) instead",
),
Some(vm.ctx.exceptions.deprecation_warning.to_owned()),
1,
None,
vm,
)?;
}
Ok(())
}