forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbool.rs
237 lines (216 loc) · 7.68 KB
/
bool.rs
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
use super::{PyInt, PyStrRef, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
convert::{ToPyObject, ToPyResult},
function::OptionalArg,
identifier,
protocol::PyNumberMethods,
types::{AsNumber, Constructor},
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject,
VirtualMachine,
};
use num_bigint::Sign;
use num_traits::Zero;
use once_cell::sync::Lazy;
use std::fmt::{Debug, Formatter};
impl ToPyObject for bool {
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.new_bool(self).into()
}
}
impl TryFromBorrowedObject for bool {
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &PyObject) -> PyResult<bool> {
if obj.fast_isinstance(vm.ctx.types.int_type) {
Ok(get_value(obj))
} else {
Err(vm.new_type_error(format!("Expected type bool, not {}", obj.class().name())))
}
}
}
impl PyObjectRef {
/// Convert Python bool into Rust bool.
pub fn try_to_bool(self, vm: &VirtualMachine) -> PyResult<bool> {
if self.is(&vm.ctx.true_value) {
return Ok(true);
}
if self.is(&vm.ctx.false_value) {
return Ok(false);
}
let rs_bool = match vm.get_method(self.clone(), identifier!(vm, __bool__)) {
Some(method_or_err) => {
// If descriptor returns Error, propagate it further
let method = method_or_err?;
let bool_obj = method.call((), vm)?;
if !bool_obj.fast_isinstance(vm.ctx.types.bool_type) {
return Err(vm.new_type_error(format!(
"__bool__ should return bool, returned type {}",
bool_obj.class().name()
)));
}
get_value(&bool_obj)
}
None => match vm.get_method(self, identifier!(vm, __len__)) {
Some(method_or_err) => {
let method = method_or_err?;
let bool_obj = method.call((), vm)?;
let int_obj = bool_obj.payload::<PyInt>().ok_or_else(|| {
vm.new_type_error(format!(
"'{}' object cannot be interpreted as an integer",
bool_obj.class().name()
))
})?;
let len_val = int_obj.as_bigint();
if len_val.sign() == Sign::Minus {
return Err(vm.new_value_error("__len__() should return >= 0".to_owned()));
}
!len_val.is_zero()
}
None => true,
},
};
Ok(rs_bool)
}
}
#[pyclass(name = "bool", module = false, base = "PyInt")]
pub struct PyBool;
impl PyPayload for PyBool {
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
vm.ctx.types.bool_type
}
}
impl Debug for PyBool {
fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
todo!()
}
}
impl Constructor for PyBool {
type Args = OptionalArg<PyObjectRef>;
fn py_new(zelf: PyTypeRef, x: Self::Args, vm: &VirtualMachine) -> PyResult {
if !zelf.fast_isinstance(vm.ctx.types.type_type) {
let actual_class = zelf.class();
let actual_type = &actual_class.name();
return Err(vm.new_type_error(format!(
"requires a 'type' object but received a '{actual_type}'"
)));
}
let val = x.map_or(Ok(false), |val| val.try_to_bool(vm))?;
Ok(vm.ctx.new_bool(val).into())
}
}
#[pyclass(with(Constructor, AsNumber))]
impl PyBool {
#[pymethod(magic)]
fn repr(zelf: bool, vm: &VirtualMachine) -> PyStrRef {
if zelf {
vm.ctx.names.True
} else {
vm.ctx.names.False
}
.to_owned()
}
#[pymethod(magic)]
fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if format_spec.is_empty() {
obj.str(vm)
} else {
Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_owned()))
}
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
fn or(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if lhs.fast_isinstance(vm.ctx.types.bool_type)
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
{
let lhs = get_value(&lhs);
let rhs = get_value(&rhs);
(lhs || rhs).to_pyobject(vm)
} else {
get_py_int(&lhs).or(rhs, vm).to_pyobject(vm)
}
}
#[pymethod(name = "__rand__")]
#[pymethod(magic)]
fn and(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if lhs.fast_isinstance(vm.ctx.types.bool_type)
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
{
let lhs = get_value(&lhs);
let rhs = get_value(&rhs);
(lhs && rhs).to_pyobject(vm)
} else {
get_py_int(&lhs).and(rhs, vm).to_pyobject(vm)
}
}
#[pymethod(name = "__rxor__")]
#[pymethod(magic)]
fn xor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if lhs.fast_isinstance(vm.ctx.types.bool_type)
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
{
let lhs = get_value(&lhs);
let rhs = get_value(&rhs);
(lhs ^ rhs).to_pyobject(vm)
} else {
get_py_int(&lhs).xor(rhs, vm).to_pyobject(vm)
}
}
}
macro_rules! int_method {
($method:ident) => {
PyInt::as_number().$method
};
}
impl AsNumber for PyBool {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: Lazy<PyNumberMethods> = Lazy::new(|| PyNumberMethods {
add: int_method!(add),
subtract: int_method!(subtract),
multiply: int_method!(multiply),
remainder: int_method!(remainder),
divmod: int_method!(divmod),
power: int_method!(power),
negative: int_method!(negative),
positive: int_method!(positive),
absolute: int_method!(absolute),
boolean: int_method!(boolean),
invert: int_method!(invert),
lshift: int_method!(lshift),
rshift: int_method!(rshift),
and: Some(|number, other, vm| {
PyBool::and(number.obj.to_owned(), other.to_owned(), vm).to_pyresult(vm)
}),
xor: Some(|number, other, vm| {
PyBool::xor(number.obj.to_owned(), other.to_owned(), vm).to_pyresult(vm)
}),
or: Some(|number, other, vm| {
PyBool::or(number.obj.to_owned(), other.to_owned(), vm).to_pyresult(vm)
}),
int: int_method!(int),
float: int_method!(float),
floor_divide: int_method!(floor_divide),
true_divide: int_method!(true_divide),
index: int_method!(index),
..PyNumberMethods::NOT_IMPLEMENTED
});
&AS_NUMBER
}
}
pub(crate) fn init(context: &Context) {
PyBool::extend_class(context, context.types.bool_type);
}
// pub fn not(vm: &VirtualMachine, obj: &PyObject) -> PyResult<bool> {
// if obj.fast_isinstance(vm.ctx.types.bool_type) {
// let value = get_value(obj);
// Ok(!value)
// } else {
// Err(vm.new_type_error(format!("Can only invert a bool, on {:?}", obj)))
// }
// }
// Retrieve inner int value:
pub(crate) fn get_value(obj: &PyObject) -> bool {
!obj.payload::<PyInt>().unwrap().as_bigint().is_zero()
}
fn get_py_int(obj: &PyObject) -> &PyInt {
obj.payload::<PyInt>().unwrap()
}