forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjgenerator.rs
More file actions
102 lines (88 loc) · 2.4 KB
/
objgenerator.rs
File metadata and controls
102 lines (88 loc) · 2.4 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
/*
* The mythical generator.
*/
use super::objcode::PyCodeRef;
use super::objcoroinner::{Coro, Variant};
use super::objtype::PyClassRef;
use crate::frame::FrameRef;
use crate::function::OptionalArg;
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
pub type PyGeneratorRef = PyRef<PyGenerator>;
#[pyclass(name = "generator")]
#[derive(Debug)]
pub struct PyGenerator {
inner: Coro,
}
impl PyValue for PyGenerator {
fn class(vm: &VirtualMachine) -> PyClassRef {
vm.ctx.generator_type()
}
}
#[pyimpl]
impl PyGenerator {
pub fn as_coro(&self) -> &Coro {
&self.inner
}
pub fn new(frame: FrameRef, vm: &VirtualMachine) -> PyGeneratorRef {
PyGenerator {
inner: Coro::new(frame, Variant::Gen),
}
.into_ref(vm)
}
// TODO: fix function names situation
#[pyproperty(magic)]
fn name(&self, vm: &VirtualMachine) -> PyObjectRef {
vm.get_none()
}
#[pymethod(name = "__iter__")]
fn iter(zelf: PyGeneratorRef) -> PyGeneratorRef {
zelf
}
#[pymethod(name = "__next__")]
fn next(&self, vm: &VirtualMachine) -> PyResult {
self.send(vm.get_none(), vm)
}
#[pymethod]
fn send(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.inner.send(value, vm)
}
#[pymethod]
fn throw(
&self,
exc_type: PyObjectRef,
exc_val: OptionalArg,
exc_tb: OptionalArg,
vm: &VirtualMachine,
) -> PyResult {
self.inner.throw(
exc_type,
exc_val.unwrap_or_else(|| vm.get_none()),
exc_tb.unwrap_or_else(|| vm.get_none()),
vm,
)
}
#[pymethod]
fn close(&self, vm: &VirtualMachine) -> PyResult<()> {
self.inner.close(vm)
}
#[pyproperty]
fn gi_frame(&self, _vm: &VirtualMachine) -> FrameRef {
self.inner.frame()
}
#[pyproperty]
fn gi_running(&self, _vm: &VirtualMachine) -> bool {
self.inner.running()
}
#[pyproperty]
fn gi_code(&self, _vm: &VirtualMachine) -> PyCodeRef {
self.inner.frame().code.clone()
}
#[pyproperty]
fn gi_yieldfrom(&self, _vm: &VirtualMachine) -> Option<PyObjectRef> {
self.inner.frame().yield_from_target()
}
}
pub fn init(ctx: &PyContext) {
PyGenerator::extend_class(ctx, &ctx.types.generator_type);
}