forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjfunction.rs
More file actions
82 lines (71 loc) · 2.07 KB
/
objfunction.rs
File metadata and controls
82 lines (71 loc) · 2.07 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
use crate::frame::Scope;
use crate::pyobject::{
IdProtocol, PyContext, PyFuncArgs, PyObjectRef, PyResult, PyValue, TypeProtocol,
};
use crate::vm::VirtualMachine;
#[derive(Debug)]
pub struct PyFunction {
// TODO: these shouldn't be public
pub code: PyObjectRef,
pub scope: Scope,
pub defaults: PyObjectRef,
}
impl PyFunction {
pub fn new(code: PyObjectRef, scope: Scope, defaults: PyObjectRef) -> Self {
PyFunction {
code,
scope,
defaults,
}
}
}
impl PyValue for PyFunction {
fn class(vm: &mut VirtualMachine) -> PyObjectRef {
vm.ctx.function_type()
}
}
#[derive(Debug)]
pub struct PyMethod {
// TODO: these shouldn't be public
pub object: PyObjectRef,
pub function: PyObjectRef,
}
impl PyMethod {
pub fn new(object: PyObjectRef, function: PyObjectRef) -> Self {
PyMethod { object, function }
}
}
impl PyValue for PyMethod {
fn class(vm: &mut VirtualMachine) -> PyObjectRef {
vm.ctx.bound_method_type()
}
}
pub fn init(context: &PyContext) {
let function_type = &context.function_type;
extend_class!(context, function_type, {
"__get__" => context.new_rustfunc(bind_method),
"__code__" => context.new_property(function_code)
});
let builtin_function_or_method_type = &context.builtin_function_or_method_type;
extend_class!(context, builtin_function_or_method_type, {
"__get__" => context.new_rustfunc(bind_method)
});
}
fn bind_method(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(function, None), (obj, None), (cls, None)]
);
if obj.is(&vm.get_none()) && !cls.is(&obj.typ()) {
Ok(function.clone())
} else {
Ok(vm.ctx.new_bound_method(function.clone(), obj.clone()))
}
}
fn function_code(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
match args.args[0].payload() {
Some(PyFunction { ref code, .. }) => Ok(code.clone()),
None => Err(vm.new_type_error("no code".to_string())),
}
}