forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsysmodule.rs
More file actions
76 lines (65 loc) · 2.34 KB
/
sysmodule.rs
File metadata and controls
76 lines (65 loc) · 2.34 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
use num_bigint::ToBigInt;
use obj::objtype;
use pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol};
use std::rc::Rc;
use std::{env, mem};
use vm::VirtualMachine;
/*
* The magic sys module.
*/
fn argv(ctx: &PyContext) -> PyObjectRef {
let mut argv: Vec<PyObjectRef> = env::args().map(|x| ctx.new_str(x)).collect();
argv.remove(0);
ctx.new_list(argv)
}
fn getframe(vm: &mut VirtualMachine, _args: PyFuncArgs) -> PyResult {
if let Some(frame) = &vm.current_frame {
Ok(frame.clone())
} else {
panic!("Current frame is undefined!")
}
}
fn sys_getrefcount(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(object, None)]);
let size = Rc::strong_count(&object);
Ok(vm.ctx.new_int(size.to_bigint().unwrap()))
}
fn sys_getsizeof(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(object, None)]);
// TODO: implement default optional argument.
let size = mem::size_of_val(&object.borrow());
Ok(vm.ctx.new_int(size.to_bigint().unwrap()))
}
pub fn mk_module(ctx: &PyContext) -> PyObjectRef {
let path_list = match env::var_os("PYTHONPATH") {
Some(paths) => env::split_paths(&paths)
.map(|path| {
ctx.new_str(
path.to_str()
.expect("PYTHONPATH isn't valid unicode")
.to_string(),
)
})
.collect(),
None => vec![],
};
let path = ctx.new_list(path_list);
let modules = ctx.new_dict();
let sys_name = "sys";
let sys_mod = ctx.new_module(&sys_name, ctx.new_scope(None));
ctx.set_item(&modules, sys_name, sys_mod.clone());
ctx.set_item(&sys_mod, "modules", modules);
ctx.set_item(&sys_mod, "argv", argv(ctx));
ctx.set_item(&sys_mod, "getrefcount", ctx.new_rustfunc(sys_getrefcount));
ctx.set_item(&sys_mod, "getsizeof", ctx.new_rustfunc(sys_getsizeof));
ctx.set_item(
&sys_mod,
"maxsize",
ctx.new_int(std::usize::MAX.to_bigint().unwrap()),
);
ctx.set_item(&sys_mod, "path", path);
ctx.set_item(&sys_mod, "ps1", ctx.new_str(">>>>> ".to_string()));
ctx.set_item(&sys_mod, "ps2", ctx.new_str("..... ".to_string()));
ctx.set_item(&sys_mod, "_getframe", ctx.new_rustfunc(getframe));
sys_mod
}