Skip to content

Commit 70f6d73

Browse files
committed
Add __repr__ to objstr.
1 parent c8d8528 commit 70f6d73

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

vm/src/obj/objstr.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pub fn init(context: &PyContext) {
1414
str_type.set_attr("__mul__", context.new_rustfunc(str_mul));
1515
str_type.set_attr("__new__", context.new_rustfunc(str_new));
1616
str_type.set_attr("__str__", context.new_rustfunc(str_str));
17+
str_type.set_attr("__repr__", context.new_rustfunc(str_repr));
1718
}
1819

1920
pub fn get_value(obj: &PyObjectRef) -> String {
@@ -44,6 +45,25 @@ fn str_str(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
4445
Ok(s.clone())
4546
}
4647

48+
fn str_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
49+
arg_check!(vm, args, required = [(s, Some(vm.ctx.str_type()))]);
50+
let value = get_value(s);
51+
let mut formatted = String::from("'");
52+
for c in value.chars() {
53+
match c {
54+
'\'' | '\\' => {
55+
formatted.push('\\');
56+
formatted.push(c);
57+
}
58+
_ => {
59+
formatted.push(c);
60+
}
61+
}
62+
}
63+
formatted.push('\'');
64+
Ok(vm.ctx.new_str(formatted))
65+
}
66+
4767
fn str_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
4868
arg_check!(
4969
vm,

0 commit comments

Comments
 (0)