forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjdict.rs
More file actions
193 lines (167 loc) · 5.49 KB
/
objdict.rs
File metadata and controls
193 lines (167 loc) · 5.49 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
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
use super::super::pyobject::{
AttributeProtocol, PyContext, PyFuncArgs, PyObject, PyObjectKind, PyObjectRef, PyResult,
TypeProtocol,
};
use super::super::vm::VirtualMachine;
use super::objstr;
use super::objtype;
use num_bigint::ToBigInt;
use std::cell::{Ref, RefMut};
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
pub fn new(dict_type: PyObjectRef) -> PyObjectRef {
PyObject::new(
PyObjectKind::Dict {
elements: HashMap::new(),
},
dict_type.clone(),
)
}
pub fn get_elements<'a>(
obj: &'a PyObjectRef,
) -> impl Deref<Target = HashMap<String, PyObjectRef>> + 'a {
Ref::map(obj.borrow(), |py_obj| {
if let PyObjectKind::Dict { ref elements } = py_obj.kind {
elements
} else {
panic!("Cannot extract dict elements");
}
})
}
fn get_mut_elements<'a>(
obj: &'a PyObjectRef,
) -> impl DerefMut<Target = HashMap<String, PyObjectRef>> + 'a {
RefMut::map(obj.borrow_mut(), |py_obj| {
if let PyObjectKind::Dict { ref mut elements } = py_obj.kind {
elements
} else {
panic!("Cannot extract dict elements");
}
})
}
fn dict_new(_vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
Ok(new(args.args[0].clone()))
}
fn dict_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(o, Some(vm.ctx.dict_type()))]);
let elements = get_elements(o);
Ok(vm.ctx.new_int(elements.len().to_bigint().unwrap()))
}
fn dict_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(o, Some(vm.ctx.dict_type()))]);
let elements = get_elements(o);
let mut str_parts = vec![];
for elem in elements.iter() {
let s = vm.to_repr(&elem.1)?;
let value_str = objstr::get_value(&s);
str_parts.push(format!("{}: {}", elem.0, value_str));
}
let s = format!("{{{}}}", str_parts.join(", "));
Ok(vm.new_str(s))
}
pub fn dict_contains(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [
(dict, Some(vm.ctx.dict_type())),
(needle, Some(vm.ctx.str_type()))
]
);
let needle = objstr::get_value(&needle);
for element in get_elements(dict).iter() {
if &needle == element.0 {
return Ok(vm.new_bool(true));
}
}
Ok(vm.new_bool(false))
}
fn dict_delitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [
(dict, Some(vm.ctx.dict_type())),
(needle, Some(vm.ctx.str_type()))
]
);
// What we are looking for:
let needle = objstr::get_value(&needle);
// Delete the item:
let mut elements = get_mut_elements(dict);
match elements.remove(&needle) {
Some(_) => Ok(vm.get_none()),
None => Err(vm.new_value_error(format!("Key not found: {}", needle))),
}
}
/// When iterating over a dictionary, we iterate over the keys of it.
fn dict_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(dict, Some(vm.ctx.dict_type()))]);
let keys = get_elements(dict)
.keys()
.map(|k| vm.ctx.new_str(k.to_string()))
.collect();
let key_list = vm.ctx.new_list(keys);
let iter_obj = PyObject::new(
PyObjectKind::Iterator {
position: 0,
iterated_obj: key_list,
},
vm.ctx.iter_type(),
);
Ok(iter_obj)
}
fn dict_setitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [
(dict, Some(vm.ctx.dict_type())),
(needle, Some(vm.ctx.str_type())),
(value, None)
]
);
// What we are looking for:
let needle = objstr::get_value(&needle);
// Delete the item:
let mut elements = get_mut_elements(dict);
elements.insert(needle, value.clone());
Ok(vm.get_none())
}
fn dict_getitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [
(dict, Some(vm.ctx.dict_type())),
(needle, Some(vm.ctx.str_type()))
]
);
// What we are looking for:
let needle = objstr::get_value(&needle);
let elements = get_elements(dict);
if elements.contains_key(&needle) {
Ok(elements[&needle].clone())
} else {
Err(vm.new_value_error(format!("Key not found: {}", needle)))
}
}
pub fn create_type(type_type: PyObjectRef, object_type: PyObjectRef, dict_type: PyObjectRef) {
(*dict_type.borrow_mut()).kind = PyObjectKind::Class {
name: String::from("dict"),
dict: new(dict_type.clone()),
mro: vec![object_type],
};
(*dict_type.borrow_mut()).typ = Some(type_type.clone());
}
pub fn init(context: &PyContext) {
let ref dict_type = context.dict_type;
dict_type.set_attr("__len__", context.new_rustfunc(dict_len));
dict_type.set_attr("__contains__", context.new_rustfunc(dict_contains));
dict_type.set_attr("__delitem__", context.new_rustfunc(dict_delitem));
dict_type.set_attr("__getitem__", context.new_rustfunc(dict_getitem));
dict_type.set_attr("__iter__", context.new_rustfunc(dict_iter));
dict_type.set_attr("__new__", context.new_rustfunc(dict_new));
dict_type.set_attr("__repr__", context.new_rustfunc(dict_repr));
dict_type.set_attr("__setitem__", context.new_rustfunc(dict_setitem));
}