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
84 lines (74 loc) · 2.35 KB
/
objgenerator.rs
File metadata and controls
84 lines (74 loc) · 2.35 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
/*
* The mythical generator.
*/
use crate::frame::{ExecutionResult, Frame};
use crate::function::PyFuncArgs;
use crate::pyobject::{PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol};
use crate::vm::VirtualMachine;
#[derive(Debug)]
pub struct PyGenerator {
frame: PyObjectRef,
}
type PyGeneratorRef = PyRef<PyGenerator>;
impl PyValue for PyGenerator {
fn class(vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.generator_type()
}
}
pub fn init(context: &PyContext) {
let generator_type = &context.generator_type;
context.set_attr(
&generator_type,
"__iter__",
context.new_rustfunc(generator_iter),
);
context.set_attr(
&generator_type,
"__next__",
context.new_rustfunc(generator_next),
);
context.set_attr(
&generator_type,
"send",
context.new_rustfunc(generator_send),
);
}
pub fn new_generator(frame: PyObjectRef, vm: &VirtualMachine) -> PyGeneratorRef {
PyGenerator { frame }.into_ref(vm)
}
fn generator_iter(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(o, Some(vm.ctx.generator_type()))]);
Ok(o.clone())
}
fn generator_next(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(o, Some(vm.ctx.generator_type()))]);
let value = vm.get_none();
send(vm, o, &value)
}
fn generator_send(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(o, Some(vm.ctx.generator_type())), (value, None)]
);
send(vm, o, value)
}
fn send(vm: &VirtualMachine, gen: &PyObjectRef, value: &PyObjectRef) -> PyResult {
if let Some(PyGenerator { ref frame }) = gen.payload() {
if let Some(frame) = frame.payload::<Frame>() {
frame.push_value(value.clone());
} else {
panic!("Generator frame isn't a frame.");
}
match vm.run_frame(frame.clone())? {
ExecutionResult::Yield(value) => Ok(value),
ExecutionResult::Return(_value) => {
// Stop iteration!
let stop_iteration = vm.ctx.exceptions.stop_iteration.clone();
Err(vm.new_exception(stop_iteration, "End of generator".to_string()))
}
}
} else {
panic!("Cannot extract frame from non-generator");
}
}