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
/*! The python `frame` type.

*/

use super::objcode::PyCodeRef;
use super::objdict::PyDictRef;
use crate::frame::FrameRef;
use crate::pyobject::{PyContext, PyObjectRef, PyResult};
use crate::vm::VirtualMachine;

pub fn init(context: &PyContext) {
    extend_class!(context, &context.types.frame_type, {
        "__new__" => context.new_rustfunc(FrameRef::new),
        "__repr__" => context.new_rustfunc(FrameRef::repr),
        "f_locals" => context.new_property(FrameRef::flocals),
        "f_globals" => context.new_property(FrameRef::f_globals),
        "f_code" => context.new_property(FrameRef::fcode),
        "f_back" => context.new_property(FrameRef::f_back),
        "f_lasti" => context.new_property(FrameRef::f_lasti),
    });
}

impl FrameRef {
    #[allow(clippy::new_ret_no_self)]
    fn new(_class: FrameRef, vm: &VirtualMachine) -> PyResult {
        Err(vm.new_type_error("Cannot directly create frame object".to_string()))
    }

    fn repr(self, _vm: &VirtualMachine) -> String {
        "<frame object at .. >".to_string()
    }

    fn f_globals(self, _vm: &VirtualMachine) -> PyDictRef {
        self.scope.globals.clone()
    }

    fn flocals(self, _vm: &VirtualMachine) -> PyDictRef {
        self.scope.get_locals()
    }

    fn fcode(self, vm: &VirtualMachine) -> PyCodeRef {
        vm.ctx.new_code_object(self.code.clone())
    }

    fn f_back(self, vm: &VirtualMachine) -> PyObjectRef {
        // TODO: how to retrieve the upper stack frame??
        vm.ctx.none()
    }

    fn f_lasti(self, vm: &VirtualMachine) -> PyObjectRef {
        vm.ctx.new_int(*self.lasti.borrow())
    }
}