Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions vm/src/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ impl Frame {
let s = self
.pop_multiple(*size)
.into_iter()
.map(|pyobj| objstr::get_value(&pyobj))
.map(|pyobj| objstr::clone_value(&pyobj))
.collect::<String>();
let str_obj = vm.ctx.new_str(s);
self.push_value(str_obj);
Expand Down Expand Up @@ -929,7 +929,7 @@ impl Frame {
let kwarg_names = vm
.extract_elements(&kwarg_names)?
.iter()
.map(|pyobj| objstr::get_value(pyobj))
.map(|pyobj| objstr::clone_value(pyobj))
.collect();
PyFuncArgs::new(args, kwarg_names)
}
Expand All @@ -939,7 +939,7 @@ impl Frame {
self.pop_value().downcast().expect("Kwargs must be a dict.");
kw_dict
.into_iter()
.map(|elem| (objstr::get_value(&elem.0), elem.1))
.map(|elem| (objstr::clone_value(&elem.0), elem.1))
.collect()
} else {
IndexMap::new()
Expand Down
2 changes: 1 addition & 1 deletion vm/src/obj/objdict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ impl PyDictRef {
pub fn to_attributes(self) -> PyAttributes {
let mut attrs = PyAttributes::new();
for (key, value) in self {
let key = objstr::get_value(&key);
let key = objstr::clone_value(&key);
attrs.insert(key, value);
}
attrs
Expand Down
28 changes: 14 additions & 14 deletions vm/src/obj/objstr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ impl PyString {
#[pymethod(name = "__add__")]
fn add(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
Ok(format!("{}{}", self.value, get_value(&rhs)))
Ok(format!("{}{}", self.value, borrow_value(&rhs)))
} else {
Err(vm.new_type_error(format!("Cannot add {} and {}", self, rhs)))
}
Expand All @@ -228,7 +228,7 @@ impl PyString {
#[pymethod(name = "__eq__")]
fn eq(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
vm.new_bool(self.value == get_value(&rhs))
vm.new_bool(self.value == borrow_value(&rhs))
} else {
vm.ctx.not_implemented()
}
Expand All @@ -237,7 +237,7 @@ impl PyString {
#[pymethod(name = "__ne__")]
fn ne(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if objtype::isinstance(&rhs, &vm.ctx.str_type()) {
vm.new_bool(self.value != get_value(&rhs))
vm.new_bool(self.value != borrow_value(&rhs))
} else {
vm.ctx.not_implemented()
}
Expand Down Expand Up @@ -623,8 +623,8 @@ impl PyString {
actual_type
)));
}
let format_string_text = get_value(zelf);
match FormatString::from_str(format_string_text.as_str()) {
let format_string_text = borrow_value(zelf);
match FormatString::from_str(format_string_text) {
Ok(format_string) => perform_format(vm, &format_string, &args),
Err(err) => match err {
FormatParseError::UnmatchedBracket => {
Expand All @@ -649,8 +649,8 @@ impl PyString {
}

let zelf = &args.args[0];
let format_string_text = get_value(zelf);
match FormatString::from_str(format_string_text.as_str()) {
let format_string_text = borrow_value(zelf);
match FormatString::from_str(format_string_text) {
Ok(format_string) => perform_format_map(vm, &format_string, &args.args[1]),
Err(err) => match err {
FormatParseError::UnmatchedBracket => {
Expand Down Expand Up @@ -1288,7 +1288,7 @@ pub fn init(ctx: &PyContext) {
PyStringReverseIterator::extend_class(ctx, &ctx.types.strreverseiterator_type);
}

pub fn get_value(obj: &PyObjectRef) -> String {
pub fn clone_value(obj: &PyObjectRef) -> String {
obj.payload::<PyString>().unwrap().value.clone()
}

Expand Down Expand Up @@ -1341,7 +1341,7 @@ fn do_cformat_specifier(
CFormatPreconversor::Ascii => vm.call_method(&obj.clone(), "__repr__", vec![])?,
CFormatPreconversor::Bytes => vm.call_method(&obj.clone(), "decode", vec![])?,
};
Ok(format_spec.format_string(get_value(&result)))
Ok(format_spec.format_string(clone_value(&result)))
}
CFormatType::Number(_) => {
if !objtype::isinstance(&obj, &vm.ctx.int_type()) {
Expand Down Expand Up @@ -1384,7 +1384,7 @@ fn do_cformat_specifier(
}
}
} else if objtype::isinstance(&obj, &vm.ctx.str_type()) {
let s: String = get_value(&obj);
let s = borrow_value(&obj);
let num_chars = s.chars().count();
if num_chars != 1 {
Err(vm.new_type_error("%c requires int or char".to_string()))
Expand Down Expand Up @@ -1573,7 +1573,7 @@ fn perform_format(
}
};
auto_argument_index += 1;
get_value(&result)
clone_value(&result)
}
FormatPart::IndexSpec(index, format_spec) => {
let result = match arguments.args.get(*index + 1) {
Expand All @@ -1582,7 +1582,7 @@ fn perform_format(
return Err(vm.new_index_error("tuple index out of range".to_string()));
}
};
get_value(&result)
clone_value(&result)
}
FormatPart::KeywordSpec(keyword, format_spec) => {
let result = match arguments.get_optional_kwarg(&keyword) {
Expand All @@ -1591,7 +1591,7 @@ fn perform_format(
return Err(vm.new_key_error(vm.new_str(keyword.to_string())));
}
};
get_value(&result)
clone_value(&result)
}
FormatPart::Literal(literal) => literal.clone(),
};
Expand All @@ -1616,7 +1616,7 @@ fn perform_format_map(
FormatPart::KeywordSpec(keyword, format_spec) => {
let argument = dict.get_item(keyword, &vm)?;
let result = call_object_format(vm, argument.clone(), &format_spec)?;
get_value(&result)
clone_value(&result)
}
FormatPart::Literal(literal) => literal.clone(),
};
Expand Down
2 changes: 1 addition & 1 deletion vm/src/py_serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl<'s> serde::Serialize for PyObjectSerializer<'s> {
seq.end()
};
if objtype::isinstance(self.pyobject, &self.vm.ctx.str_type()) {
serializer.serialize_str(&objstr::get_value(&self.pyobject))
serializer.serialize_str(objstr::borrow_value(&self.pyobject))
} else if objtype::isinstance(self.pyobject, &self.vm.ctx.float_type()) {
serializer.serialize_f64(objfloat::get_value(self.pyobject))
} else if objtype::isinstance(self.pyobject, &self.vm.ctx.bool_type()) {
Expand Down
20 changes: 8 additions & 12 deletions vm/src/stdlib/csv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,34 +29,30 @@ struct ReaderOption {

impl ReaderOption {
fn new(args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<Self> {
let delimiter = {
let bytes = args
.get_optional_kwarg("delimiter")
.map_or(",".to_string(), |pyobj| objstr::get_value(&pyobj))
.into_bytes();

let delimiter = if let Some(delimiter) = args.get_optional_kwarg("delimiter") {
let bytes = objstr::borrow_value(&delimiter).as_bytes();
match bytes.len() {
1 => bytes[0],
_ => {
let msg = r#""delimiter" must be a 1-character string"#;
return Err(vm.new_type_error(msg.to_string()));
}
}
} else {
b','
};

let quotechar = {
let bytes = args
.get_optional_kwarg("quotechar")
.map_or("\"".to_string(), |pyobj| objstr::get_value(&pyobj))
.into_bytes();

let quotechar = if let Some(quotechar) = args.get_optional_kwarg("quotechar") {
let bytes = objstr::borrow_value(&quotechar).as_bytes();
match bytes.len() {
1 => bytes[0],
_ => {
let msg = r#""quotechar" must be a 1-character string"#;
return Err(vm.new_type_error(msg.to_string()));
}
}
} else {
b'"'
};

Ok(ReaderOption {
Expand Down
4 changes: 2 additions & 2 deletions vm/src/stdlib/imp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ fn imp_is_frozen(name: PyStringRef, vm: &VirtualMachine) -> bool {

fn imp_create_builtin(spec: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let sys_modules = vm.get_attribute(vm.sys_module.clone(), "modules").unwrap();

let name = &objstr::get_value(&vm.get_attribute(spec.clone(), "name")?);
let spec = vm.get_attribute(spec.clone(), "name")?;
let name = objstr::borrow_value(&spec);

if let Ok(module) = sys_modules.get_item(name, vm) {
Ok(module)
Expand Down
32 changes: 15 additions & 17 deletions vm/src/stdlib/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,11 @@ fn string_io_new(
_args: StringIOArgs,
vm: &VirtualMachine,
) -> PyResult<PyStringIORef> {
let raw_string = match object {
OptionalArg::Present(Some(ref input)) => objstr::get_value(input),
_ => String::new(),
};
let flatten = object.flat_option();
let input = flatten.map_or_else(Vec::new, |v| objstr::borrow_value(&v).as_bytes().to_vec());

PyStringIO {
buffer: RefCell::new(Some(BufferedIO::new(Cursor::new(raw_string.into_bytes())))),
buffer: RefCell::new(Some(BufferedIO::new(Cursor::new(input)))),
}
.into_ref_with_type(vm, cls)
}
Expand Down Expand Up @@ -816,7 +814,7 @@ fn text_io_wrapper_readline(
Ok(rust_string)
}

fn split_mode_string(mode_string: String) -> Result<(String, String), String> {
fn split_mode_string(mode_string: &str) -> Result<(String, String), String> {
let mut mode: char = '\0';
let mut typ: char = '\0';
let mut plus_is_set = false;
Expand Down Expand Up @@ -882,7 +880,7 @@ pub fn io_open(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
);

// mode is optional: 'rt' is the default mode (open from reading text)
let mode_string = mode.map_or("rt".to_string(), objstr::get_value);
let mode_string = mode.map_or("rt", objstr::borrow_value);

let (mode, typ) = match split_mode_string(mode_string) {
Ok((mode, typ)) => (mode, typ),
Expand Down Expand Up @@ -1066,7 +1064,7 @@ mod tests {
use super::*;

fn assert_mode_split_into(mode_string: &str, expected_mode: &str, expected_typ: &str) {
let (mode, typ) = split_mode_string(mode_string.to_string()).unwrap();
let (mode, typ) = split_mode_string(mode_string).unwrap();
assert_eq!(mode, expected_mode);
assert_eq!(typ, expected_typ);
}
Expand All @@ -1085,37 +1083,37 @@ mod tests {
#[test]
fn test_invalid_mode() {
assert_eq!(
split_mode_string("rbsss".to_string()),
split_mode_string("rbsss"),
Err("invalid mode: 'rbsss'".to_string())
);
assert_eq!(
split_mode_string("rrb".to_string()),
split_mode_string("rrb"),
Err("invalid mode: 'rrb'".to_string())
);
assert_eq!(
split_mode_string("rbb".to_string()),
split_mode_string("rbb"),
Err("invalid mode: 'rbb'".to_string())
);
}

#[test]
fn test_mode_not_specified() {
assert_eq!(
split_mode_string("".to_string()),
split_mode_string(""),
Err(
"Must have exactly one of create/read/write/append mode and at most one plus"
.to_string()
)
);
assert_eq!(
split_mode_string("b".to_string()),
split_mode_string("b"),
Err(
"Must have exactly one of create/read/write/append mode and at most one plus"
.to_string()
)
);
assert_eq!(
split_mode_string("t".to_string()),
split_mode_string("t"),
Err(
"Must have exactly one of create/read/write/append mode and at most one plus"
.to_string()
Expand All @@ -1126,23 +1124,23 @@ mod tests {
#[test]
fn test_text_and_binary_at_once() {
assert_eq!(
split_mode_string("rbt".to_string()),
split_mode_string("rbt"),
Err("can't have text and binary mode at once".to_string())
);
}

#[test]
fn test_exactly_one_mode() {
assert_eq!(
split_mode_string("rwb".to_string()),
split_mode_string("rwb"),
Err("must have exactly one of create/read/write/append mode".to_string())
);
}

#[test]
fn test_at_most_one_plus() {
assert_eq!(
split_mode_string("a++".to_string()),
split_mode_string("a++"),
Err("invalid mode: 'a++'".to_string())
);
}
Expand Down
4 changes: 2 additions & 2 deletions vm/src/stdlib/pystruct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ fn struct_pack(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
} else {
let fmt_arg = args.args[0].clone();
if objtype::isinstance(&fmt_arg, &vm.ctx.str_type()) {
let fmt_str = objstr::get_value(&fmt_arg);
let fmt_str = objstr::clone_value(&fmt_arg);

let format_spec = parse_format_string(fmt_str).map_err(|e| vm.new_value_error(e))?;

Expand Down Expand Up @@ -364,7 +364,7 @@ fn struct_unpack(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
]
);

let fmt_str = objstr::get_value(&fmt);
let fmt_str = objstr::clone_value(&fmt);

let format_spec = parse_format_string(fmt_str).map_err(|e| vm.new_value_error(e))?;
let data = objbytes::get_value(buffer).to_vec();
Expand Down
2 changes: 1 addition & 1 deletion vm/src/stdlib/subprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl PopenRef {
Either::A(command) => vec![command.as_str().to_string()],
Either::B(command_list) => objsequence::get_elements_list(command_list.as_object())
.iter()
.map(|x| objstr::get_value(x))
.map(|x| objstr::clone_value(x))
.collect(),
};
let cwd = args.cwd.map(|x| OsString::from(x.as_str()));
Expand Down
4 changes: 2 additions & 2 deletions vm/src/stdlib/tokenize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ use crate::vm::VirtualMachine;

fn tokenize_tokenize(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(readline, Some(vm.ctx.str_type()))]);
let source = objstr::get_value(readline);
let source = objstr::borrow_value(readline);

// TODO: implement generator when the time has come.
let lexer1 = lexer::make_tokenizer(&source);
let lexer1 = lexer::make_tokenizer(source);

let tokens = lexer1.map(|st| vm.ctx.new_str(format!("{:?}", st.unwrap().1)));
let tokens = Vec::from_iter(tokens);
Expand Down
2 changes: 1 addition & 1 deletion vm/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1523,7 +1523,7 @@ mod tests {
let a = vm.ctx.new_str(String::from("Hello "));
let b = vm.ctx.new_int(4_i32);
let res = vm._mul(a, b).unwrap();
let value = objstr::get_value(&res);
let value = objstr::borrow_value(&res);
assert_eq!(value, String::from("Hello Hello Hello Hello "))
}
}