new_str allows &str and &String

This commit is contained in:
Jeong YunWon committed 2020-08-10 02:16:50 +09:00
1 parent eba638ec9b
commit e253095f75
20 files changed
+74 -97

No files matched your search

+1 -1
View File
@@ -409,7 +409,7 @@ fn run_module(vm: &VirtualMachine, module: &str) -> PyResult<()> {
debug!("Running module {}", module);
let runpy = vm.import("runpy", &[], 0)?;
let run_module_as_main = vm.get_attribute(runpy, "_run_module_as_main")?;
vm.invoke(&run_module_as_main, vec![vm.ctx.new_str(module.to_owned())])?;
vm.invoke(&run_module_as_main, vec![vm.ctx.new_str(module)])?;
Ok(())
}
+1 -1
View File
@@ -784,7 +784,7 @@ mod decl {
.split('.')
.next_back()
.unwrap();
let name_obj = vm.ctx.new_str(name.to_owned());
let name_obj = vm.ctx.new_str(name);
let mut metaclass = if let Some(metaclass) = kwargs.pop_kwarg("metaclass") {
PyClassRef::try_from_object(vm, metaclass)?
+3 -3
View File
@@ -492,12 +492,12 @@ mod tests {
assert_eq!(0, dict.len());
let key1 = vm.ctx.new_bool(true);
let value1 = vm.ctx.new_str("abc".to_owned());
let value1 = vm.ctx.new_str("abc");
dict.insert(&vm, key1.clone(), value1.clone()).unwrap();
assert_eq!(1, dict.len());
let key2 = vm.ctx.new_str("x".to_owned());
let value2 = vm.ctx.new_str("def".to_owned());
let key2 = vm.ctx.new_str("x");
let value2 = vm.ctx.new_str("def");
dict.insert(&vm, key2.clone(), value2.clone()).unwrap();
assert_eq!(2, dict.len());
+3 -3
View File
@@ -1291,7 +1291,7 @@ impl ExecutingFrame<'_> {
.split('.')
.next_back()
.unwrap();
vm.set_attr(&func_obj, "__name__", vm.ctx.new_str(name.to_owned()))?;
vm.set_attr(&func_obj, "__name__", vm.ctx.new_str(name))?;
vm.set_attr(&func_obj, "__qualname__", qualified_name)?;
let module = self
.scope
@@ -1439,13 +1439,13 @@ impl ExecutingFrame<'_> {
fn store_attr(&mut self, vm: &VirtualMachine, attr_name: &str) -> FrameResult {
let parent = self.pop_value();
let value = self.pop_value();
vm.set_attr(&parent, vm.ctx.new_str(attr_name.to_owned()), value)?;
vm.set_attr(&parent, vm.ctx.new_str(attr_name), value)?;
Ok(None)
}
fn delete_attr(&mut self, vm: &VirtualMachine, attr_name: &str) -> FrameResult {
let parent = self.pop_value();
let name = vm.ctx.new_str(attr_name.to_owned());
let name = vm.ctx.new_str(attr_name);
vm.del_attr(&parent, name)?;
Ok(None)
}
+2 -6
View File
@@ -106,13 +106,9 @@ pub fn import_codeobj(
set_file_attr: bool,
) -> PyResult {
let attrs = vm.ctx.new_dict();
attrs.set_item("__name__", vm.ctx.new_str(module_name.to_owned()), vm)?;
attrs.set_item("__name__", vm.ctx.new_str(module_name), vm)?;
if set_file_attr {
attrs.set_item(
"__file__",
vm.ctx.new_str(code_obj.source_path.to_owned()),
vm,
)?;
attrs.set_item("__file__", vm.ctx.new_str(&code_obj.source_path), vm)?;
}
let module = vm.new_module(module_name, attrs.clone());
+1 -5
View File
@@ -108,11 +108,7 @@ impl PyCodeRef {
#[pyproperty]
fn co_varnames(self, vm: &VirtualMachine) -> PyObjectRef {
let varnames = self
.code
.varnames()
.map(|s| vm.ctx.new_str(s.to_owned()))
.collect();
let varnames = self.code.varnames().map(|s| vm.ctx.new_str(s)).collect();
vm.ctx.new_tuple(varnames)
}
}
+1 -1
View File
@@ -392,7 +392,7 @@ impl PyDictRef {
if let Some((key, value)) = self.entries.pop_front() {
Ok(vm.ctx.new_tuple(vec![key, value]))
} else {
let err_msg = vm.ctx.new_str("popitem(): dictionary is empty".to_owned());
let err_msg = vm.ctx.new_str("popitem(): dictionary is empty");
Err(vm.new_key_error(err_msg))
}
}
+1 -1
View File
@@ -281,7 +281,7 @@ impl PySetInner {
if let Some((key, _)) = self.content.pop_front() {
Ok(key)
} else {
let err_msg = vm.ctx.new_str("pop from an empty set".to_owned());
let err_msg = vm.ctx.new_str("pop from an empty set");
Err(vm.new_key_error(err_msg))
}
}
+6 -12
View File
@@ -66,7 +66,7 @@ impl AsRef<str> for PyString {
impl<T> From<&T> for PyString
where
T: AsRef<T> + ?Sized,
T: AsRef<str> + ?Sized,
{
fn from(s: &T) -> PyString {
s.as_ref().to_owned().into()
@@ -745,10 +745,8 @@ impl PyString {
#[pymethod]
fn splitlines(&self, args: pystr::SplitLinesArgs, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.new_list(
self.value
.py_splitlines(args, |s| vm.ctx.new_str(s.to_owned())),
)
vm.ctx
.new_list(self.value.py_splitlines(args, |s| vm.ctx.new_str(s)))
}
#[pymethod]
@@ -1124,7 +1122,7 @@ impl IntoPyObject for String {
impl IntoPyObject for &str {
fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.new_str(self.to_owned())
vm.ctx.new_str(self)
}
}
@@ -1308,13 +1306,9 @@ mod tests {
let vm: VirtualMachine = Default::default();
let table = vm.context().new_dict();
table
.set_item("a", vm.ctx.new_str("🎅".to_owned()), &vm)
.unwrap();
table.set_item("a", vm.ctx.new_str("🎅"), &vm).unwrap();
table.set_item("b", vm.get_none(), &vm).unwrap();
table
.set_item("c", vm.ctx.new_str("xda".to_owned()), &vm)
.unwrap();
table.set_item("c", vm.ctx.new_str("xda"), &vm).unwrap();
let translated = PyString::maketrans(
table.into_object(),
OptionalArg::Missing,
+1 -1
View File
@@ -200,6 +200,6 @@ pub fn init(context: &PyContext) {
super().cmeth(arg)\n";
extend_class!(context, super_type, {
"__doc__" => context.new_str(super_doc.to_owned()),
"__doc__" => context.new_str(super_doc),
});
}
+1 -1
View File
@@ -112,7 +112,7 @@ impl PyClassRef {
.read()
.get("__module__")
.cloned()
.unwrap_or_else(|| vm.ctx.new_str("builtins".to_owned()))
.unwrap_or_else(|| vm.ctx.new_str("builtins"))
}
#[pyproperty(magic, setter)]
+16 -20
View File
@@ -35,7 +35,7 @@ macro_rules! node {
$(
let field_name = stringify!($attr_name);
$vm.set_attr(node.as_object(), field_name, $attr_value)?;
field_names.push($vm.ctx.new_str(field_name.to_owned()));
field_names.push($vm.ctx.new_str(field_name));
)*
$vm.set_attr(node.as_object(), "_fields", $vm.ctx.new_tuple(field_names))?;
node
@@ -81,7 +81,7 @@ fn statement_to_ast(vm: &VirtualMachine, statement: &ast::Statement) -> PyResult
decorator_list,
..
} => node!(vm, ClassDef, {
name => vm.ctx.new_str(name.to_owned()),
name => vm.ctx.new_str(name),
keywords => map_ast(keyword_to_ast, vm, keywords)?,
body => statements_to_ast(vm, body)?,
decorator_list => expressions_to_ast(vm, decorator_list)?,
@@ -96,7 +96,7 @@ fn statement_to_ast(vm: &VirtualMachine, statement: &ast::Statement) -> PyResult
} => {
if *is_async {
node!(vm, AsyncFunctionDef, {
name => vm.ctx.new_str(name.to_owned()),
name => vm.ctx.new_str(name),
args => parameters_to_ast(vm, args)?,
body => statements_to_ast(vm, body)?,
decorator_list => expressions_to_ast(vm, decorator_list)?,
@@ -104,7 +104,7 @@ fn statement_to_ast(vm: &VirtualMachine, statement: &ast::Statement) -> PyResult
})
} else {
node!(vm, FunctionDef, {
name => vm.ctx.new_str(name.to_owned()),
name => vm.ctx.new_str(name),
args => parameters_to_ast(vm, args)?,
body => statements_to_ast(vm, body)?,
decorator_list => expressions_to_ast(vm, decorator_list)?,
@@ -245,7 +245,7 @@ fn statement_to_ast(vm: &VirtualMachine, statement: &ast::Statement) -> PyResult
fn alias_to_ast(vm: &VirtualMachine, alias: &ast::ImportSymbol) -> PyResult<AstNodeRef> {
Ok(node!(vm, alias, {
name => vm.ctx.new_str(alias.symbol.to_owned()),
name => vm.ctx.new_str(&alias.symbol),
asname => optional_string_to_py_obj(vm, &alias.alias)
}))
}
@@ -281,7 +281,7 @@ fn handler_to_ast(vm: &VirtualMachine, handler: &ast::ExceptHandler) -> PyResult
fn make_string_list(vm: &VirtualMachine, names: &[String]) -> PyObjectRef {
vm.ctx
.new_list(names.iter().map(|x| vm.ctx.new_str(x.to_owned())).collect())
.new_list(names.iter().map(|x| vm.ctx.new_str(x)).collect())
}
fn optional_expressions_to_ast(
@@ -340,7 +340,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
ast::UnaryOperator::Pos => "UAdd",
};
node!(vm, UnaryOp, {
op => vm.ctx.new_str(op.to_owned()),
op => vm.ctx.new_str(op),
operand => expression_to_ast(vm, a)?,
})
}
@@ -351,7 +351,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
ast::BooleanOperator::And => "And",
ast::BooleanOperator::Or => "Or",
};
let py_op = vm.ctx.new_str(str_op.to_owned());
let py_op = vm.ctx.new_str(str_op);
node!(vm, BoolOp, {
op => py_op,
@@ -374,11 +374,9 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
ast::Comparison::Is => "Is",
ast::Comparison::IsNot => "IsNot",
};
let ops = vm.ctx.new_list(
ops.iter()
.map(|x| vm.ctx.new_str(to_operator(x).to_owned()))
.collect(),
);
let ops = vm
.ctx
.new_list(ops.iter().map(|x| vm.ctx.new_str(to_operator(x))).collect());
let comparators: PyResult<_> = vals
.iter()
@@ -393,7 +391,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
})
}
Identifier { name } => node!(vm, Name, {
id => vm.ctx.new_str(name.clone()),
id => vm.ctx.new_str(name),
ctx => vm.ctx.none() // TODO: add context.
}),
Lambda { args, body } => node!(vm, Lambda, {
@@ -506,7 +504,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
}),
Attribute { value, name } => node!(vm, Attribute, {
value => expression_to_ast(vm, value)?,
attr => vm.ctx.new_str(name.to_owned()),
attr => vm.ctx.new_str(name),
ctx => vm.ctx.none()
}),
Starred { value } => node!(vm, Starred, {
@@ -575,7 +573,7 @@ fn parameter_to_ast(vm: &VirtualMachine, parameter: &ast::Parameter) -> PyResult
};
let py_node = node!(vm, arg, {
arg => vm.ctx.new_str(parameter.arg.to_owned()),
arg => vm.ctx.new_str(&parameter.arg),
annotation => py_annotation
});
@@ -587,7 +585,7 @@ fn parameter_to_ast(vm: &VirtualMachine, parameter: &ast::Parameter) -> PyResult
fn optional_string_to_py_obj(vm: &VirtualMachine, name: &Option<String>) -> PyObjectRef {
if let Some(name) = name {
vm.ctx.new_str(name.to_owned())
vm.ctx.new_str(name)
} else {
vm.ctx.none()
}
@@ -624,9 +622,7 @@ fn comprehension_to_ast(
fn string_to_ast(vm: &VirtualMachine, string: &ast::StringGroup) -> PyResult<AstNodeRef> {
let string = match string {
ast::StringGroup::Constant { value } => {
node!(vm, Str, { s => vm.ctx.new_str(value.clone()) })
}
ast::StringGroup::Constant { value } => node!(vm, Str, { s => vm.ctx.new_str(value) }),
ast::StringGroup::FormattedValue { value, .. } => {
node!(vm, FormattedValue, { value => expression_to_ast(vm, value)? })
}
+5 -5
View File
@@ -469,7 +469,7 @@ fn io_base_checkclosed(
if objbool::boolval(vm, vm.get_attribute(instance, "closed")?)? {
let msg = msg
.flatten()
.unwrap_or_else(|| vm.ctx.new_str("I/O operation on closed file.".to_owned()));
.unwrap_or_else(|| vm.ctx.new_str("I/O operation on closed file."));
Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg]))
} else {
Ok(())
@@ -484,7 +484,7 @@ fn io_base_checkreadable(
if !objbool::boolval(vm, vm.call_method(&instance, "readable", vec![])?)? {
let msg = msg
.flatten()
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not readable.".to_owned()));
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not readable."));
Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg]))
} else {
Ok(())
@@ -499,7 +499,7 @@ fn io_base_checkwritable(
if !objbool::boolval(vm, vm.call_method(&instance, "writable", vec![])?)? {
let msg = msg
.flatten()
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not writable.".to_owned()));
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not writable."));
Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg]))
} else {
Ok(())
@@ -514,7 +514,7 @@ fn io_base_checkseekable(
if !objbool::boolval(vm, vm.call_method(&instance, "seekable", vec![])?)? {
let msg = msg
.flatten()
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not seekable.".to_owned()));
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not seekable."));
Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg]))
} else {
Ok(())
@@ -1205,7 +1205,7 @@ pub fn io_open(
)),
)?;
vm.set_attr(&file_io_obj, "mode", vm.ctx.new_str(mode_string.to_owned()))?;
vm.set_attr(&file_io_obj, "mode", vm.ctx.new_str(mode_string))?;
// Create Buffered class to consume FileIO. The type of buffered class depends on
// the operation in the mode.
+3 -3
View File
@@ -179,12 +179,12 @@ impl JsonScanner {
let ret = if has_decimal || has_exponent {
// float
if let Some(ref parse_float) = self.parse_float {
vm.invoke(parse_float, vec![vm.ctx.new_str(buf.to_owned())])
vm.invoke(parse_float, vec![vm.ctx.new_str(buf)])
} else {
Ok(vm.ctx.new_float(f64::from_str(buf).unwrap()))
}
} else if let Some(ref parse_int) = self.parse_int {
vm.invoke(parse_int, vec![vm.ctx.new_str(buf.to_owned())])
vm.invoke(parse_int, vec![vm.ctx.new_str(buf)])
} else {
Ok(vm.ctx.new_int(BigInt::from_str(buf).unwrap()))
};
@@ -233,7 +233,7 @@ fn _json_encode_basestring_ascii(s: PyStringRef) -> String {
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
let ctx = &vm.ctx;
let scanner_cls = JsonScanner::make_class(ctx);
scanner_cls.set_str_attr("__module__", vm.ctx.new_str("_json".to_owned()));
scanner_cls.set_str_attr("__module__", vm.ctx.new_str("_json"));
py_module!(vm, "_json", {
"make_scanner" => scanner_cls,
"encode_basestring" => named_function!(ctx, _json, encode_basestring),
+1 -1
View File
@@ -21,7 +21,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
let keyword_kwlist = ctx.new_list(
lexer::get_keywords()
.keys()
.map(|k| ctx.new_str(k.to_owned()))
.map(|k| ctx.new_str(k))
.collect(),
);
+1 -1
View File
@@ -1567,7 +1567,7 @@ mod posix {
Err(errno_err(vm))
} else {
let name = unsafe { ffi::CStr::from_ptr(name) }.to_str().unwrap();
Ok(vm.ctx.new_str(name.to_owned()))
Ok(vm.ctx.new_str(name))
}
}
+11 -11
View File
@@ -130,8 +130,8 @@ fn ssl_enum_certificates(store_name: PyStringRef, vm: &VirtualMachine) -> PyResu
(*ptr).dwCertEncodingType
};
let enc_type = match enc_type {
wincrypt::X509_ASN_ENCODING => vm.ctx.new_str("x509_asn".to_owned()),
wincrypt::PKCS_7_ASN_ENCODING => vm.ctx.new_str("pkcs_7_asn".to_owned()),
wincrypt::X509_ASN_ENCODING => vm.ctx.new_str("x509_asn"),
wincrypt::PKCS_7_ASN_ENCODING => vm.ctx.new_str("pkcs_7_asn"),
other => vm.ctx.new_int(other),
};
let usage = match c.valid_uses()? {
@@ -705,18 +705,18 @@ fn cert_to_py(vm: &VirtualMachine, cert: &X509Ref, binary: bool) -> PyResult {
.iter()
.filter_map(|gen_name| {
if let Some(email) = gen_name.email() {
Some(vm.ctx.new_tuple(vec![
vm.ctx.new_str("email".to_owned()),
vm.ctx.new_str(email.to_owned()),
]))
Some(
vm.ctx
.new_tuple(vec![vm.ctx.new_str("email"), vm.ctx.new_str(email)]),
)
} else if let Some(dnsname) = gen_name.dnsname() {
Some(vm.ctx.new_tuple(vec![
vm.ctx.new_str("DNS".to_owned()),
vm.ctx.new_str(dnsname.to_owned()),
]))
Some(
vm.ctx
.new_tuple(vec![vm.ctx.new_str("DNS"), vm.ctx.new_str(dnsname)]),
)
} else if let Some(ip) = gen_name.ipaddress() {
Some(vm.ctx.new_tuple(vec![
vm.ctx.new_str("IP Address".to_owned()),
vm.ctx.new_str("IP Address"),
vm.ctx.new_str(String::from_utf8_lossy(ip).into_owned()),
]))
} else {
+1 -1
View File
@@ -129,7 +129,7 @@ impl PySymbolTable {
.symtable
.symbols
.keys()
.map(|s| vm.ctx.new_str(s.to_owned()))
.map(|s| vm.ctx.new_str(s))
.collect();
Ok(vm.ctx.new_list(symbols))
}
+13 -13
View File
@@ -21,7 +21,7 @@ fn argv(vm: &VirtualMachine) -> PyObjectRef {
.settings
.argv
.iter()
.map(|arg| vm.ctx.new_str(arg.to_owned()))
.map(|arg| vm.ctx.new_str(arg))
.collect(),
)
}
@@ -214,7 +214,7 @@ fn sys_exc_info(vm: &VirtualMachine) -> PyObjectRef {
fn sys_git_info(vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.new_tuple(vec![
vm.ctx.new_str("RustPython".to_owned()),
vm.ctx.new_str("RustPython"),
vm.ctx.new_str(version::get_git_identifier()),
vm.ctx.new_str(version::get_git_revision()),
])
@@ -472,8 +472,8 @@ pub fn make_module(vm: &VirtualMachine, module: PyObjectRef, builtins: PyObjectR
// TODO Add crate version to this namespace
let implementation = py_namespace!(vm, {
"name" => ctx.new_str("rustpython".to_owned()),
"cache_tag" => ctx.new_str("rustpython-01".to_owned()),
"name" => ctx.new_str("rustpython"),
"cache_tag" => ctx.new_str("rustpython-01"),
"_multiarch" => ctx.new_str(MULTIARCH.to_owned()),
"version" => version_info.clone(),
"hexversion" => ctx.new_int(version::VERSION_HEX),
@@ -590,7 +590,7 @@ settrace() -- set the global debug tracing function
"argv" => argv(vm),
"builtin_module_names" => builtin_module_names,
"byteorder" => ctx.new_str(bytorder),
"copyright" => ctx.new_str(copyright.to_owned()),
"copyright" => ctx.new_str(copyright),
"_base_executable" => _base_executable(ctx),
"executable" => executable(ctx),
"flags" => flags,
@@ -608,9 +608,9 @@ settrace() -- set the global debug tracing function
"maxunicode" => ctx.new_int(std::char::MAX as u32),
"maxsize" => ctx.new_int(std::isize::MAX),
"path" => path,
"ps1" => ctx.new_str(">>>>> ".to_owned()),
"ps2" => ctx.new_str("..... ".to_owned()),
"__doc__" => ctx.new_str(sys_doc.to_owned()),
"ps1" => ctx.new_str(">>>>> "),
"ps2" => ctx.new_str("..... "),
"__doc__" => ctx.new_str(sys_doc),
"_getframe" => ctx.new_function(getframe),
"modules" => modules.clone(),
"warnoptions" => ctx.new_list(vec![]),
@@ -628,10 +628,10 @@ settrace() -- set the global debug tracing function
"version_info" => version_info,
"_git" => sys_git_info(vm),
"exc_info" => ctx.new_function(sys_exc_info),
"prefix" => ctx.new_str(prefix.to_owned()),
"base_prefix" => ctx.new_str(base_prefix.to_owned()),
"exec_prefix" => ctx.new_str(exec_prefix.to_owned()),
"base_exec_prefix" => ctx.new_str(base_exec_prefix.to_owned()),
"prefix" => ctx.new_str(prefix),
"base_prefix" => ctx.new_str(base_prefix),
"exec_prefix" => ctx.new_str(exec_prefix),
"base_exec_prefix" => ctx.new_str(base_exec_prefix),
"exit" => ctx.new_function(sys_exit),
"abiflags" => ctx.new_str(ABIFLAGS.to_owned()),
"audit" => ctx.new_function(sys_audit),
@@ -643,7 +643,7 @@ settrace() -- set the global debug tracing function
"api_version" => ctx.new_int(0x0), // what C api?
"float_info" => float_info,
"int_info" => int_info,
"float_repr_style" => ctx.new_str("short".to_owned()),
"float_repr_style" => ctx.new_str("short"),
});
#[cfg(windows)]
+2 -7
View File
@@ -214,15 +214,10 @@ impl VirtualMachine {
objmodule::init_module_dict(
&vm,
&builtins_dict,
vm.ctx.new_str("builtins".to_owned()),
vm.get_none(),
);
objmodule::init_module_dict(
&vm,
&sysmod_dict,
vm.ctx.new_str("sys".to_owned()),
vm.ctx.new_str("builtins"),
vm.get_none(),
);
objmodule::init_module_dict(&vm, &sysmod_dict, vm.ctx.new_str("sys"), vm.get_none());
vm.initialize(initialize_parameter);
vm
}