forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjbool.rs
More file actions
88 lines (76 loc) · 2.52 KB
/
objbool.rs
File metadata and controls
88 lines (76 loc) · 2.52 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
use num_traits::Zero;
use crate::function::PyFuncArgs;
use crate::pyobject::{IntoPyObject, PyContext, PyObjectRef, PyResult, TryFromObject};
use crate::vm::VirtualMachine;
use super::objint::PyInt;
use super::objtype;
impl IntoPyObject for bool {
fn into_pyobject(self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bool(self))
}
}
impl TryFromObject for bool {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
boolval(vm, obj)
}
}
pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
Ok(if let Ok(f) = vm.get_method(obj.clone(), "__bool__") {
let bool_res = vm.invoke(f, PyFuncArgs::default())?;
match bool_res.payload::<PyInt>() {
Some(i) => !i.as_bigint().is_zero(),
None => return Err(vm.new_type_error(String::from("TypeError"))),
}
} else {
true
})
}
pub fn init(context: &PyContext) {
let bool_doc = "bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.";
let bool_type = &context.bool_type;
extend_class!(context, bool_type, {
"__new__" => context.new_rustfunc(bool_new),
"__repr__" => context.new_rustfunc(bool_repr),
"__doc__" => context.new_str(bool_doc.to_string())
});
}
pub fn not(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult {
if objtype::isinstance(obj, &vm.ctx.bool_type()) {
let value = get_value(obj);
Ok(vm.ctx.new_bool(!value))
} else {
Err(vm.new_type_error(format!("Can only invert a bool, on {:?}", obj)))
}
}
// Retrieve inner int value:
pub fn get_value(obj: &PyObjectRef) -> bool {
!obj.payload::<PyInt>().unwrap().as_bigint().is_zero()
}
fn bool_repr(vm: &VirtualMachine, args: PyFuncArgs) -> Result<PyObjectRef, PyObjectRef> {
arg_check!(vm, args, required = [(obj, Some(vm.ctx.bool_type()))]);
let v = get_value(obj);
let s = if v {
"True".to_string()
} else {
"False".to_string()
};
Ok(vm.new_str(s))
}
fn bool_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(_zelf, Some(vm.ctx.type_type()))],
optional = [(val, None)]
);
Ok(match val {
Some(val) => {
let bv = boolval(vm, val.clone())?;
vm.new_bool(bv)
}
None => vm.context().new_bool(false),
})
}