Skip to content

Commit 072a518

Browse files
committed
Some style issues and add __len__ to str
1 parent 2f39478 commit 072a518

9 files changed

Lines changed: 68 additions & 20 deletions

File tree

vm/src/builtins.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,6 @@ fn builtin_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
226226
match obj.borrow().kind {
227227
PyObjectKind::Dict { ref elements } => Ok(vm.context().new_int(elements.len() as i32)),
228228
PyObjectKind::Tuple { ref elements } => Ok(vm.context().new_int(elements.len() as i32)),
229-
PyObjectKind::String { ref value } => Ok(vm.context().new_int(value.len() as i32)),
230229
_ => {
231230
let len_method_name = "__len__".to_string();
232231
match vm.get_attribute(obj.clone(), &len_method_name) {
@@ -264,7 +263,7 @@ pub fn builtin_print(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
264263
trace!("print called with {:?}", args);
265264
for a in args.args {
266265
let s = match vm.to_str(a) {
267-
Ok(v) => objstr::get_value(v),
266+
Ok(v) => objstr::get_value(&v),
268267
Err(err) => return Err(err),
269268
};
270269
print!("{} ", s);

vm/src/exceptions.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
use super::objstr;
12
use super::pyobject::{
23
create_type, AttributeProtocol, PyContext, PyFuncArgs, PyObjectRef, PyResult,
34
};
4-
use super::objstr;
55
use super::vm::VirtualMachine;
66

77
fn exception_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
@@ -19,7 +19,7 @@ fn exception_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
1919

2020
pub fn print_exception(vm: &mut VirtualMachine, exc: &PyObjectRef) {
2121
match vm.to_str(exc.clone()) {
22-
Ok(txt) => println!("Error: {}", objstr::get_value(txt)),
22+
Ok(txt) => println!("Error: {}", objstr::get_value(&txt)),
2323
Err(err) => println!("Error during error {:?}", err),
2424
}
2525
}

vm/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,5 @@ mod traceback;
3737
mod vm;
3838

3939
// pub use self::pyobject::Executor;
40-
pub use self::vm::VirtualMachine;
4140
pub use self::exceptions::print_exception;
41+
pub use self::vm::VirtualMachine;

vm/src/objdict.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
use super::objstr;
2+
use super::objtype;
13
use super::pyobject::{
24
AttributeProtocol, PyContext, PyFuncArgs, PyObject, PyObjectKind, PyObjectRef, PyResult,
5+
TypeProtocol,
36
};
47
use super::vm::VirtualMachine;
58
use std::collections::HashMap;
@@ -23,10 +26,43 @@ pub fn new(dict_type: PyObjectRef) -> PyObjectRef {
2326
)
2427
}
2528

29+
fn get_elements(obj: &PyObjectRef) -> HashMap<String, PyObjectRef> {
30+
if let PyObjectKind::Dict { elements } = &obj.borrow().kind {
31+
elements.clone()
32+
} else {
33+
panic!("Cannot extract dict elements");
34+
}
35+
}
36+
2637
fn dict_new(_vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
2738
Ok(new(args.args[0].clone()))
2839
}
2940

41+
fn dict_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
42+
arg_check!(vm, args, required = [(o, Some(vm.ctx.dict_type()))]);
43+
let elements = get_elements(o);
44+
Ok(vm.ctx.new_int(elements.len() as i32))
45+
}
46+
47+
fn dict_str(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
48+
arg_check!(vm, args, required = [(o, Some(vm.ctx.dict_type()))]);
49+
50+
let elements = get_elements(o);
51+
let mut str_parts = vec![];
52+
for elem in elements {
53+
match vm.to_str(elem.1) {
54+
Ok(s) => {
55+
let value_str = objstr::get_value(&s);
56+
str_parts.push(format!("{}: {}", elem.0, value_str));
57+
}
58+
Err(err) => return Err(err),
59+
}
60+
}
61+
62+
let s = format!("{{ {} }}", str_parts.join(", "));
63+
Ok(vm.new_str(s))
64+
}
65+
3066
pub fn create_type(type_type: PyObjectRef, object_type: PyObjectRef, dict_type: PyObjectRef) {
3167
(*dict_type.borrow_mut()).kind = PyObjectKind::Class {
3268
name: String::from("dict"),
@@ -38,5 +74,7 @@ pub fn create_type(type_type: PyObjectRef, object_type: PyObjectRef, dict_type:
3874

3975
pub fn init(context: &PyContext) {
4076
let ref dict_type = context.dict_type;
77+
dict_type.set_attr("__len__", context.new_rustfunc(dict_len));
4178
dict_type.set_attr("__new__", context.new_rustfunc(dict_new));
79+
dict_type.set_attr("__str__", context.new_rustfunc(dict_str));
4280
}

vm/src/objlist.rs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -52,22 +52,18 @@ fn list_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
5252
}
5353

5454
fn list_str(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
55-
arg_check!(
56-
vm,
57-
args,
58-
required = [(o, Some(vm.ctx.list_type()))]
59-
);
55+
arg_check!(vm, args, required = [(o, Some(vm.ctx.list_type()))]);
6056

6157
let elements = get_elements(o.clone());
62-
let mut str_parts = vec!();
58+
let mut str_parts = vec![];
6359
for elem in elements {
6460
match vm.to_str(elem) {
65-
Ok(s) => str_parts.push(objstr::get_value(s)),
61+
Ok(s) => str_parts.push(objstr::get_value(&s)),
6662
Err(err) => return Err(err),
6763
}
6864
}
6965

70-
let s = format!( "[{}]", str_parts.join(", "));
66+
let s = format!("[{}]", str_parts.join(", "));
7167
Ok(vm.new_str(s))
7268
}
7369

vm/src/objobject.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use super::objdict;
22
use super::objtype;
33
use super::pyobject::{
4-
AttributeProtocol, IdProtocol, PyContext, PyFuncArgs, PyObject, PyObjectKind, PyObjectRef, PyResult, TypeProtocol,
4+
AttributeProtocol, IdProtocol, PyContext, PyFuncArgs, PyObject, PyObjectKind, PyObjectRef,
5+
PyResult, TypeProtocol,
56
};
67
use super::vm::VirtualMachine;
78

vm/src/objstr.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@ use super::vm::VirtualMachine;
99
pub fn init(context: &PyContext) {
1010
let ref str_type = context.str_type;
1111
str_type.set_attr("__add__", context.new_rustfunc(str_add));
12+
str_type.set_attr("__len__", context.new_rustfunc(str_len));
1213
str_type.set_attr("__mul__", context.new_rustfunc(str_mul));
1314
str_type.set_attr("__new__", context.new_rustfunc(str_new));
1415
str_type.set_attr("__str__", context.new_rustfunc(str_str));
1516
}
1617

17-
pub fn get_value(obj: PyObjectRef) -> String {
18+
pub fn get_value(obj: &PyObjectRef) -> String {
1819
if let PyObjectKind::String { value } = &obj.borrow().kind {
1920
value.to_string()
2021
} else {
@@ -36,20 +37,26 @@ fn str_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
3637
if objtype::isinstance(s2.clone(), vm.ctx.str_type()) {
3738
Ok(vm
3839
.ctx
39-
.new_str(format!("{}{}", get_value(s.clone()), get_value(s2.clone()))))
40+
.new_str(format!("{}{}", get_value(&s), get_value(&s2))))
4041
} else {
4142
Err(vm.new_type_error(format!("Cannot add {:?} and {:?}", s, s2)))
4243
}
4344
}
4445

46+
fn str_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
47+
arg_check!(vm, args, required = [(s, Some(vm.ctx.str_type()))]);
48+
let sv = get_value(s);
49+
Ok(vm.ctx.new_int(sv.len() as i32))
50+
}
51+
4552
fn str_mul(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
4653
arg_check!(
4754
vm,
4855
args,
4956
required = [(s, Some(vm.ctx.str_type())), (s2, None)]
5057
);
5158
if objtype::isinstance(s2.clone(), vm.ctx.int_type()) {
52-
let value1 = get_value(s.clone());
59+
let value1 = get_value(&s);
5360
let value2 = objint::get_value(s2.clone());
5461
let mut result = String::new();
5562
for _x in 0..value2 {

vm/src/objtype.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,12 @@ pub fn issubclass(typ: PyObjectRef, cls: PyObjectRef) -> bool {
5656
}
5757

5858
pub fn get_type_name(typ: &PyObjectRef) -> String {
59-
if let PyObjectKind::Class { name, dict: _, mro: _ } = &typ.borrow().kind {
59+
if let PyObjectKind::Class {
60+
name,
61+
dict: _,
62+
mro: _,
63+
} = &typ.borrow().kind
64+
{
6065
name.clone()
6166
} else {
6267
panic!("Cannot get type_name of non-type type");

vm/src/vm.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -693,8 +693,10 @@ impl VirtualMachine {
693693
};
694694
elements.insert(key, obj);
695695
}
696-
let map_obj =
697-
PyObject::new(PyObjectKind::Dict { elements: elements }, self.get_type());
696+
let map_obj = PyObject::new(
697+
PyObjectKind::Dict { elements: elements },
698+
self.ctx.dict_type(),
699+
);
698700
self.push_value(map_obj);
699701
None
700702
}

0 commit comments

Comments
 (0)