From 1bac582921dc8cef7477958aea5d1cb583402f92 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Wed, 5 Feb 2020 19:15:18 +0900 Subject: [PATCH 1/2] &str::to_string -> &str::to_owned for literals --- benchmarks/bench.rs | 4 +- compiler/src/compile.rs | 22 +++++----- compiler/src/error.rs | 14 +++--- derive/src/compile_bytecode.rs | 2 +- derive/src/pyclass.rs | 2 +- examples/hello_embed.rs | 2 +- examples/mini_repl.rs | 2 +- examples/parse_folder.rs | 2 +- parser/src/error.rs | 2 +- parser/src/fstring.rs | 2 +- parser/src/lexer.rs | 12 +++--- parser/src/parser.rs | 2 +- src/main.rs | 2 +- src/shell.rs | 2 +- src/shell/rustyline_helper.rs | 2 +- vm/src/builtins.rs | 22 +++++----- vm/src/cformat.rs | 66 ++++++++++++++-------------- vm/src/dictdatatype.rs | 6 +-- vm/src/exceptions.rs | 2 +- vm/src/format.rs | 44 +++++++++---------- vm/src/frame.rs | 6 +-- vm/src/obj/objbool.rs | 8 ++-- vm/src/obj/objbytearray.rs | 14 +++--- vm/src/obj/objbyteinner.rs | 30 ++++++------- vm/src/obj/objbytes.rs | 4 +- vm/src/obj/objcode.rs | 2 +- vm/src/obj/objcomplex.rs | 6 +-- vm/src/obj/objcoroutine.rs | 2 +- vm/src/obj/objdict.rs | 12 +++--- vm/src/obj/objellipsis.rs | 4 +- vm/src/obj/objfloat.rs | 20 ++++----- vm/src/obj/objframe.rs | 4 +- vm/src/obj/objgenerator.rs | 2 +- vm/src/obj/objint.rs | 34 +++++++-------- vm/src/obj/objiter.rs | 6 +-- vm/src/obj/objlist.rs | 24 +++++------ vm/src/obj/objnone.rs | 2 +- vm/src/obj/objproperty.rs | 8 ++-- vm/src/obj/objrange.rs | 6 +-- vm/src/obj/objsequence.rs | 18 ++++---- vm/src/obj/objset.rs | 12 +++--- vm/src/obj/objslice.rs | 6 +-- vm/src/obj/objstr.rs | 70 +++++++++++++++--------------- vm/src/obj/objsuper.rs | 6 +-- vm/src/obj/objtuple.rs | 4 +- vm/src/obj/objtype.rs | 8 ++-- vm/src/obj/objweakproxy.rs | 4 +- vm/src/stdlib/binascii.rs | 6 +-- vm/src/stdlib/collections.rs | 10 ++--- vm/src/stdlib/csv.rs | 2 +- vm/src/stdlib/functools.rs | 2 +- vm/src/stdlib/hashlib.rs | 4 +- vm/src/stdlib/io.rs | 64 ++++++++++++++-------------- vm/src/stdlib/itertools.rs | 12 +++--- vm/src/stdlib/math.rs | 10 ++--- vm/src/stdlib/mod.rs | 78 +++++++++++++++++----------------- vm/src/stdlib/operator.rs | 7 ++- vm/src/stdlib/os.rs | 8 ++-- vm/src/stdlib/platform.rs | 2 +- vm/src/stdlib/pystruct.rs | 2 +- vm/src/stdlib/re.rs | 2 +- vm/src/stdlib/select.rs | 4 +- vm/src/stdlib/signal.rs | 2 +- vm/src/stdlib/socket.rs | 14 +++--- vm/src/stdlib/subprocess.rs | 12 +++--- vm/src/stdlib/time_module.rs | 4 +- vm/src/stdlib/unicodedata.rs | 8 ++-- vm/src/sysmodule.rs | 44 +++++++++---------- vm/src/version.rs | 2 +- vm/src/vm.rs | 4 +- wasm/lib/src/browser_module.rs | 4 +- wasm/lib/src/js_module.rs | 8 ++-- wasm/lib/src/vm_class.rs | 4 +- 73 files changed, 424 insertions(+), 431 deletions(-) diff --git a/benchmarks/bench.rs b/benchmarks/bench.rs index 60252ebe22..84c91be282 100644 --- a/benchmarks/bench.rs +++ b/benchmarks/bench.rs @@ -94,7 +94,7 @@ fn bench_rustpy_nbody(b: &mut test::Bencher) { let vm = VirtualMachine::default(); - let code = match vm.compile(source, compile::Mode::Single, "".to_string()) { + let code = match vm.compile(source, compile::Mode::Single, "".to_owned()) { Ok(code) => code, Err(e) => panic!("{:?}", e), }; @@ -113,7 +113,7 @@ fn bench_rustpy_mandelbrot(b: &mut test::Bencher) { let vm = VirtualMachine::default(); - let code = match vm.compile(source, compile::Mode::Single, "".to_string()) { + let code = match vm.compile(source, compile::Mode::Single, "".to_owned()) { Ok(code) => code, Err(e) => panic!("{:?}", e), }; diff --git a/compiler/src/compile.rs b/compiler/src/compile.rs index d02d3d3878..8ea3bc5207 100644 --- a/compiler/src/compile.rs +++ b/compiler/src/compile.rs @@ -88,7 +88,7 @@ fn with_compiler( ) -> Result { let mut compiler = Compiler::new(optimize); compiler.source_path = Some(source_path); - compiler.push_new_code_object("".to_string()); + compiler.push_new_code_object("".to_owned()); f(&mut compiler)?; let code = compiler.pop_code_object(); trace!("Compilation completed: {:?}", code); @@ -897,7 +897,7 @@ impl Compiler { // key: self.emit(Instruction::LoadConst { value: bytecode::Constant::String { - value: "return".to_string(), + value: "return".to_owned(), }, }); // value: @@ -989,11 +989,11 @@ impl Compiler { let (new_body, doc_str) = get_doc(body); self.emit(Instruction::LoadName { - name: "__name__".to_string(), + name: "__name__".to_owned(), scope: bytecode::NameScope::Global, }); self.emit(Instruction::StoreName { - name: "__module__".to_string(), + name: "__module__".to_owned(), scope: bytecode::NameScope::Free, }); self.emit(Instruction::LoadConst { @@ -1002,7 +1002,7 @@ impl Compiler { }, }); self.emit(Instruction::StoreName { - name: "__qualname__".to_string(), + name: "__qualname__".to_owned(), scope: bytecode::NameScope::Free, }); self.compile_statements(new_body)?; @@ -1090,7 +1090,7 @@ impl Compiler { self.emit(Instruction::Rotate { amount: 2 }); self.emit(Instruction::StoreAttr { - name: "__doc__".to_string(), + name: "__doc__".to_owned(), }); } @@ -1171,7 +1171,7 @@ impl Compiler { self.set_label(check_asynciter_label); self.emit(Instruction::Duplicate); self.emit(Instruction::LoadName { - name: "StopAsyncIteration".to_string(), + name: "StopAsyncIteration".to_owned(), scope: bytecode::NameScope::Global, }); self.emit(Instruction::CompareOperation { @@ -1732,7 +1732,7 @@ impl Compiler { func: FunctionContext::Function, }; - let name = "".to_string(); + let name = "".to_owned(); self.enter_function(&name, args)?; self.compile_expression(body)?; self.emit(Instruction::ReturnValue); @@ -1933,7 +1933,7 @@ impl Compiler { // Create magnificent function : self.push_output(CodeObject::new( Default::default(), - vec![".0".to_string()], + vec![".0".to_owned()], Varargs::None, vec![], Varargs::None, @@ -2264,8 +2264,8 @@ mod tests { fn compile_exec(source: &str) -> CodeObject { let mut compiler: Compiler = Default::default(); - compiler.source_path = Some("source_path".to_string()); - compiler.push_new_code_object("".to_string()); + compiler.source_path = Some("source_path".to_owned()); + compiler.push_new_code_object("".to_owned()); let ast = parser::parse_program(&source.to_string()).unwrap(); let symbol_scope = make_symbol_table(&ast).unwrap(); compiler.compile_program(&ast, symbol_scope).unwrap(); diff --git a/compiler/src/error.rs b/compiler/src/error.rs index ae53a0032e..836e479add 100644 --- a/compiler/src/error.rs +++ b/compiler/src/error.rs @@ -62,7 +62,7 @@ impl CompileError { match parse { ParseErrorType::Lexical(LexicalErrorType::IndentationError) => true, ParseErrorType::UnrecognizedToken(token, expected) => { - *token == Tok::Indent || expected.clone() == Some("Indent".to_string()) + *token == Tok::Indent || expected.clone() == Some("Indent".to_owned()) } _ => false, } @@ -88,14 +88,14 @@ impl fmt::Display for CompileError { let error_desc = match &self.error { CompileErrorType::Assign(target) => format!("can't assign to {}", target), CompileErrorType::Delete(target) => format!("can't delete {}", target), - CompileErrorType::ExpectExpr => "Expecting expression, got statement".to_string(), + CompileErrorType::ExpectExpr => "Expecting expression, got statement".to_owned(), CompileErrorType::Parse(err) => err.to_string(), CompileErrorType::SyntaxError(err) => err.to_string(), - CompileErrorType::StarArgs => "Two starred expressions in assignment".to_string(), - CompileErrorType::InvalidBreak => "'break' outside loop".to_string(), - CompileErrorType::InvalidContinue => "'continue' outside loop".to_string(), - CompileErrorType::InvalidReturn => "'return' outside function".to_string(), - CompileErrorType::InvalidYield => "'yield' outside function".to_string(), + CompileErrorType::StarArgs => "Two starred expressions in assignment".to_owned(), + CompileErrorType::InvalidBreak => "'break' outside loop".to_owned(), + CompileErrorType::InvalidContinue => "'continue' outside loop".to_owned(), + CompileErrorType::InvalidReturn => "'return' outside function".to_owned(), + CompileErrorType::InvalidYield => "'yield' outside function".to_owned(), }; if let Some(statement) = &self.statement { diff --git a/derive/src/compile_bytecode.rs b/derive/src/compile_bytecode.rs index e4382ee010..01f5226d60 100644 --- a/derive/src/compile_bytecode.rs +++ b/derive/src/compile_bytecode.rs @@ -235,7 +235,7 @@ impl PyCompileInput { })? .compile( mode.unwrap_or(compile::Mode::Exec), - module_name.unwrap_or_else(|| "frozen".to_string()), + module_name.unwrap_or_else(|| "frozen".to_owned()), ) } } diff --git a/derive/src/pyclass.rs b/derive/src/pyclass.rs index 17d76d6b42..fb6ac4b04e 100644 --- a/derive/src/pyclass.rs +++ b/derive/src/pyclass.rs @@ -224,7 +224,7 @@ impl Class { } else { Err(Diagnostic::span_error( span, - "Duplicate #[py*] attribute on pyimpl".to_string(), + "Duplicate #[py*] attribute on pyimpl".to_owned(), )) } } diff --git a/examples/hello_embed.rs b/examples/hello_embed.rs index 7db2174833..72b321a4fe 100644 --- a/examples/hello_embed.rs +++ b/examples/hello_embed.rs @@ -10,7 +10,7 @@ fn main() -> vm::pyobject::PyResult<()> { .compile( r#"print("Hello World!")"#, compiler::compile::Mode::Exec, - "".to_string(), + "".to_owned(), ) .map_err(|err| vm.new_syntax_error(&err))?; diff --git a/examples/mini_repl.rs b/examples/mini_repl.rs index 7a7da6088e..81a88c4fca 100644 --- a/examples/mini_repl.rs +++ b/examples/mini_repl.rs @@ -96,7 +96,7 @@ fn main() -> vm::pyobject::PyResult<()> { .compile( &input, compiler::compile::Mode::Single, - "".to_string(), + "".to_owned(), ) .map_err(|err| vm.new_syntax_error(&err)) .and_then(|code_obj| vm.run_code_obj(code_obj, scope.clone())) diff --git a/examples/parse_folder.rs b/examples/parse_folder.rs index ad0c5f8599..b0ab6251d9 100644 --- a/examples/parse_folder.rs +++ b/examples/parse_folder.rs @@ -78,7 +78,7 @@ fn parse_python_file(filename: &Path) -> ParsedFile { match std::fs::read_to_string(filename) { Err(e) => ParsedFile { // filename: Box::new(filename.to_path_buf()), - // code: "".to_string(), + // code: "".to_owned(), num_lines: 0, result: Err(e.to_string()), }, diff --git a/parser/src/error.rs b/parser/src/error.rs index 408fef3f6d..6afc4627b2 100644 --- a/parser/src/error.rs +++ b/parser/src/error.rs @@ -191,7 +191,7 @@ impl fmt::Display for ParseErrorType { ParseErrorType::UnrecognizedToken(ref tok, ref expected) => { if *tok == Tok::Indent { write!(f, "unexpected indent") - } else if expected.clone() == Some("Indent".to_string()) { + } else if expected.clone() == Some("Indent".to_owned()) { write!(f, "expected an indented block") } else { write!(f, "Got unexpected token {}", tok) diff --git a/parser/src/fstring.rs b/parser/src/fstring.rs index c983c7d8c9..7ecd8a1239 100644 --- a/parser/src/fstring.rs +++ b/parser/src/fstring.rs @@ -274,7 +274,7 @@ mod tests { value: Box::new(mk_ident("foo", 1, 1)), conversion: None, spec: Some(Box::new(Constant { - value: "spec".to_string(), + value: "spec".to_owned(), })), } ); diff --git a/parser/src/lexer.rs b/parser/src/lexer.rs index 45448737ee..581b388a4a 100644 --- a/parser/src/lexer.rs +++ b/parser/src/lexer.rs @@ -303,7 +303,7 @@ where if self.chr0 == Some('.') { if self.chr1 == Some('_') { return Err(LexicalError { - error: LexicalErrorType::OtherError("Invalid Syntax".to_string()), + error: LexicalErrorType::OtherError("Invalid Syntax".to_owned()), location: self.get_pos(), }); } @@ -352,7 +352,7 @@ where let value = value_text.parse::().unwrap(); if start_is_zero && !value.is_zero() { return Err(LexicalError { - error: LexicalErrorType::OtherError("Invalid Token".to_string()), + error: LexicalErrorType::OtherError("Invalid Token".to_owned()), location: self.get_pos(), }); } @@ -643,7 +643,7 @@ where // This is technically stricter than python3 but spaces after // tabs is even more insane than mixing spaces and tabs. return Some(Err(LexicalError { - error: LexicalErrorType::OtherError("Spaces not allowed as part of indentation after tabs".to_string()), + error: LexicalErrorType::OtherError("Spaces not allowed as part of indentation after tabs".to_owned()), location: self.get_pos(), })); } @@ -658,7 +658,7 @@ where // tabs is even more insane than mixing spaces and tabs. return Err(LexicalError { error: LexicalErrorType::OtherError( - "Tabs not allowed as part of indentation after spaces".to_string(), + "Tabs not allowed as part of indentation after spaces".to_owned(), ), location: self.get_pos(), }); @@ -1313,11 +1313,11 @@ mod tests { tokens, vec![ Tok::String { - value: "\\\\".to_string(), + value: "\\\\".to_owned(), is_fstring: false, }, Tok::String { - value: "\\".to_string(), + value: "\\".to_owned(), is_fstring: false, }, Tok::Newline, diff --git a/parser/src/parser.rs b/parser/src/parser.rs index 0f889c5af5..f3e994f10f 100644 --- a/parser/src/parser.rs +++ b/parser/src/parser.rs @@ -213,7 +213,7 @@ mod tests { function: Box::new(mk_ident("my_func", 1, 1)), args: vec![make_string("positional", 1, 10)], keywords: vec![ast::Keyword { - name: Some("keyword".to_string()), + name: Some("keyword".to_owned()), value: make_int(2, 1, 31), }], } diff --git a/src/main.rs b/src/main.rs index 013ef9de7f..9253e7f65f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -389,7 +389,7 @@ fn _run_string(vm: &VirtualMachine, scope: Scope, source: &str, source_path: Str fn run_command(vm: &VirtualMachine, scope: Scope, source: String) -> PyResult<()> { debug!("Running command {}", source); - _run_string(vm, scope, &source, "".to_string())?; + _run_string(vm, scope, &source, "".to_owned())?; Ok(()) } diff --git a/src/shell.rs b/src/shell.rs index af4f3c6cb8..aa31b3949e 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -21,7 +21,7 @@ enum ShellExecResult { } fn shell_exec(vm: &VirtualMachine, source: &str, scope: Scope) -> ShellExecResult { - match vm.compile(source, compile::Mode::Single, "".to_string()) { + match vm.compile(source, compile::Mode::Single, "".to_owned()) { Ok(code) => { match vm.run_code_obj(code, scope.clone()) { Ok(value) => { diff --git a/src/shell/rustyline_helper.rs b/src/shell/rustyline_helper.rs index c06f50ba63..45b3ca3246 100644 --- a/src/shell/rustyline_helper.rs +++ b/src/shell/rustyline_helper.rs @@ -159,7 +159,7 @@ impl Completer for ShellHelper<'_> { .complete_opt(&line[0..pos]) // as far as I can tell, there's no better way to do both completion // and indentation (or even just indentation) - .unwrap_or_else(|| (line.len(), vec!["\t".to_string()]))) + .unwrap_or_else(|| (line.len(), vec!["\t".to_owned()]))) } } diff --git a/vm/src/builtins.rs b/vm/src/builtins.rs index 78538e0fbf..3f545a79ef 100644 --- a/vm/src/builtins.rs +++ b/vm/src/builtins.rs @@ -105,7 +105,7 @@ fn builtin_callable(obj: PyObjectRef, vm: &VirtualMachine) -> bool { fn builtin_chr(i: u32, vm: &VirtualMachine) -> PyResult { match char::from_u32(i) { Some(value) => Ok(value.to_string()), - None => Err(vm.new_value_error("chr() arg not in range(0x110000)".to_string())), + None => Err(vm.new_value_error("chr() arg not in range(0x110000)".to_owned())), } } @@ -229,7 +229,7 @@ fn run_code( // Determine code object: let code_obj = match source { Either::A(string) => vm - .compile(string.as_str(), mode, "".to_string()) + .compile(string.as_str(), mode, "".to_owned()) .map_err(|err| vm.new_syntax_error(&err))?, Either::B(code_obj) => code_obj, }; @@ -400,14 +400,14 @@ fn builtin_max(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { std::cmp::Ordering::Equal => vm.extract_elements(&args.args[0])?, std::cmp::Ordering::Less => { // zero arguments means type error: - return Err(vm.new_type_error("Expected 1 or more arguments".to_string())); + return Err(vm.new_type_error("Expected 1 or more arguments".to_owned())); } }; if candidates.is_empty() { let default = args.get_optional_kwarg("default"); return default - .ok_or_else(|| vm.new_value_error("max() arg is an empty sequence".to_string())); + .ok_or_else(|| vm.new_value_error("max() arg is an empty sequence".to_owned())); } let key_func = args.get_optional_kwarg("key"); @@ -446,14 +446,14 @@ fn builtin_min(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { std::cmp::Ordering::Equal => vm.extract_elements(&args.args[0])?, std::cmp::Ordering::Less => { // zero arguments means type error: - return Err(vm.new_type_error("Expected 1 or more arguments".to_string())); + return Err(vm.new_type_error("Expected 1 or more arguments".to_owned())); } }; if candidates.is_empty() { let default = args.get_optional_kwarg("default"); return default - .ok_or_else(|| vm.new_value_error("min() arg is an empty sequence".to_string())); + .ok_or_else(|| vm.new_value_error("min() arg is an empty sequence".to_owned())); } let key_func = args.get_optional_kwarg("key"); @@ -540,7 +540,7 @@ fn builtin_ord(string: Either, vm: &VirtualMachine) -> match string.chars().next() { Some(character) => Ok(character as u32), None => Err(vm.new_type_error( - "ord() could not guess the integer representing this character".to_string(), + "ord() could not guess the integer representing this character".to_owned(), )), } } @@ -565,18 +565,18 @@ fn builtin_pow( && objtype::isinstance(&y, &vm.ctx.int_type())) { return Err(vm.new_type_error( - "pow() 3rd argument not allowed unless all arguments are integers".to_string(), + "pow() 3rd argument not allowed unless all arguments are integers".to_owned(), )); } let y = objint::get_value(&y); if y.sign() == Sign::Minus { return Err(vm.new_value_error( - "pow() 2nd argument cannot be negative when 3rd argument specified".to_string(), + "pow() 2nd argument cannot be negative when 3rd argument specified".to_owned(), )); } let m = m.as_bigint(); if m.is_zero() { - return Err(vm.new_value_error("pow() 3rd argument cannot be 0".to_string())); + return Err(vm.new_value_error("pow() 3rd argument cannot be 0".to_owned())); } let x = objint::get_value(&x); Ok(vm.new_int(x.modpow(&y, &m))) @@ -675,7 +675,7 @@ fn builtin_reversed(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { vm.invoke(&reversed_method?, PyFuncArgs::default()) } else { vm.get_method_or_type_error(obj.clone(), "__getitem__", || { - "argument to reversed() must be a sequence".to_string() + "argument to reversed() must be a sequence".to_owned() })?; let len = vm.call_method(&obj.clone(), "__len__", PyFuncArgs::default())?; let obj_iterator = objiter::PySequenceIterator { diff --git a/vm/src/cformat.rs b/vm/src/cformat.rs index 7b1b07120a..8fa85a8ee2 100644 --- a/vm/src/cformat.rs +++ b/vm/src/cformat.rs @@ -236,10 +236,10 @@ impl CFormatSpec { format!("{:.*}", precision, magnitude) } CFormatType::Float(CFloatType::Exponent(_)) => { - return Err("Not yet implemented for %e and %E".to_string()) + return Err("Not yet implemented for %e and %E".to_owned()) } CFormatType::Float(CFloatType::General(_)) => { - return Err("Not yet implemented for %g and %G".to_string()) + return Err("Not yet implemented for %g and %G".to_owned()) } _ => unreachable!(), }; @@ -623,36 +623,36 @@ mod tests { "%10s" .parse::() .unwrap() - .format_string("test".to_string()), - " test".to_string() + .format_string("test".to_owned()), + " test".to_owned() ); assert_eq!( "%-10s" .parse::() .unwrap() - .format_string("test".to_string()), - "test ".to_string() + .format_string("test".to_owned()), + "test ".to_owned() ); assert_eq!( "%#10x" .parse::() .unwrap() .format_number(&BigInt::from(0x1337)), - " 0x1337".to_string() + " 0x1337".to_owned() ); assert_eq!( "%-#10x" .parse::() .unwrap() .format_number(&BigInt::from(0x1337)), - "0x1337 ".to_string() + "0x1337 ".to_owned() ); } #[test] fn test_parse_key() { let expected = Ok(CFormatSpec { - mapping_key: Some("amount".to_string()), + mapping_key: Some("amount".to_owned()), format_type: CFormatType::Number(CNumberType::Decimal), format_char: 'd', chars_consumed: 10, @@ -663,7 +663,7 @@ mod tests { assert_eq!("%(amount)d".parse::(), expected); let expected = Ok(CFormatSpec { - mapping_key: Some("m((u(((l((((ti))))p)))l))e".to_string()), + mapping_key: Some("m((u(((l((((ti))))p)))l))e".to_owned()), format_type: CFormatType::Number(CNumberType::Decimal), format_char: 'd', chars_consumed: 30, @@ -725,7 +725,7 @@ mod tests { assert_eq!(parsed, expected); assert_eq!( parsed.unwrap().format_number(&BigInt::from(12)), - "+12 ".to_string() + "+12 ".to_owned() ); } @@ -735,15 +735,15 @@ mod tests { "%5.4s" .parse::() .unwrap() - .format_string("Hello, World!".to_string()), - " Hell".to_string() + .format_string("Hello, World!".to_owned()), + " Hell".to_owned() ); assert_eq!( "%-5.4s" .parse::() .unwrap() - .format_string("Hello, World!".to_string()), - "Hell ".to_string() + .format_string("Hello, World!".to_owned()), + "Hell ".to_owned() ); } @@ -753,8 +753,8 @@ mod tests { "%.2s" .parse::() .unwrap() - .format_string("❤❤❤❤❤❤❤❤".to_string()), - "❤❤".to_string() + .format_string("❤❤❤❤❤❤❤❤".to_owned()), + "❤❤".to_owned() ); } @@ -765,56 +765,56 @@ mod tests { .parse::() .unwrap() .format_number(&BigInt::from(27)), - "00027".to_string() + "00027".to_owned() ); assert_eq!( "%+05d" .parse::() .unwrap() .format_number(&BigInt::from(27)), - "+0027".to_string() + "+0027".to_owned() ); assert_eq!( "%-d" .parse::() .unwrap() .format_number(&BigInt::from(-27)), - "-27".to_string() + "-27".to_owned() ); assert_eq!( "% d" .parse::() .unwrap() .format_number(&BigInt::from(27)), - " 27".to_string() + " 27".to_owned() ); assert_eq!( "% d" .parse::() .unwrap() .format_number(&BigInt::from(-27)), - "-27".to_string() + "-27".to_owned() ); assert_eq!( "%08x" .parse::() .unwrap() .format_number(&BigInt::from(0x1337)), - "00001337".to_string() + "00001337".to_owned() ); assert_eq!( "%#010x" .parse::() .unwrap() .format_number(&BigInt::from(0x1337)), - "0x00001337".to_string() + "0x00001337".to_owned() ); assert_eq!( "%-#010x" .parse::() .unwrap() .format_number(&BigInt::from(0x1337)), - "0x1337 ".to_string() + "0x1337 ".to_owned() ); } @@ -825,7 +825,7 @@ mod tests { .unwrap() .format_float(f64::from(1.2345)) .ok(), - Some("1.234500".to_string()) + Some("1.234500".to_owned()) ); assert_eq!( "%+f" @@ -833,7 +833,7 @@ mod tests { .unwrap() .format_float(f64::from(1.2345)) .ok(), - Some("+1.234500".to_string()) + Some("+1.234500".to_owned()) ); assert_eq!( "% f" @@ -841,21 +841,21 @@ mod tests { .unwrap() .format_float(f64::from(1.2345)) .ok(), - Some(" 1.234500".to_string()) + Some(" 1.234500".to_owned()) ); assert_eq!( "%f".parse::() .unwrap() .format_float(f64::from(-1.2345)) .ok(), - Some("-1.234500".to_string()) + Some("-1.234500".to_owned()) ); assert_eq!( "%f".parse::() .unwrap() .format_float(f64::from(1.2345678901)) .ok(), - Some("1.234568".to_string()) + Some("1.234568".to_owned()) ); } @@ -864,7 +864,7 @@ mod tests { let fmt = "Hello, my name is %s and I'm %d years old"; let expected = Ok(CFormatString { format_parts: vec![ - (0, CFormatPart::Literal("Hello, my name is ".to_string())), + (0, CFormatPart::Literal("Hello, my name is ".to_owned())), ( 18, CFormatPart::Spec(CFormatSpec { @@ -877,7 +877,7 @@ mod tests { flags: CConversionFlags::empty(), }), ), - (20, CFormatPart::Literal(" and I'm ".to_string())), + (20, CFormatPart::Literal(" and I'm ".to_owned())), ( 29, CFormatPart::Spec(CFormatSpec { @@ -890,7 +890,7 @@ mod tests { flags: CConversionFlags::empty(), }), ), - (31, CFormatPart::Literal(" years old".to_string())), + (31, CFormatPart::Literal(" years old".to_owned())), ], }); let result = fmt.parse::(); diff --git a/vm/src/dictdatatype.rs b/vm/src/dictdatatype.rs index 279a41f97e..d7dcb8fc34 100644 --- a/vm/src/dictdatatype.rs +++ b/vm/src/dictdatatype.rs @@ -393,12 +393,12 @@ mod tests { assert_eq!(0, dict.len()); let key1 = vm.new_bool(true); - let value1 = vm.new_str("abc".to_string()); + let value1 = vm.new_str("abc".to_owned()); dict.insert(&vm, &key1, value1.clone()).unwrap(); assert_eq!(1, dict.len()); - let key2 = vm.new_str("x".to_string()); - let value2 = vm.new_str("def".to_string()); + let key2 = vm.new_str("x".to_owned()); + let value2 = vm.new_str("def".to_owned()); dict.insert(&vm, &key2, value2.clone()).unwrap(); assert_eq!(2, dict.len()); diff --git a/vm/src/exceptions.rs b/vm/src/exceptions.rs index ed616e9c11..208272bb19 100644 --- a/vm/src/exceptions.rs +++ b/vm/src/exceptions.rs @@ -347,7 +347,7 @@ impl ExceptionCtor { // both are instances; which would we choose? (Self::Instance(_exc_a), Some(_exc_b)) => { Err(vm - .new_type_error("instance exception may not have a separate value".to_string())) + .new_type_error("instance exception may not have a separate value".to_owned())) } // if the "type" is an instance and the value isn't, use the "type" (Self::Instance(exc), None) => Ok(exc), diff --git a/vm/src/format.rs b/vm/src/format.rs index 91c023a784..39c6ac2e7b 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -343,13 +343,13 @@ impl FormatSpec { let magnitude = num.abs(); let raw_magnitude_string_result: Result = match self.format_type { Some(FormatType::FixedPointUpper) => match magnitude { - magnitude if magnitude.is_nan() => Ok("NAN".to_string()), - magnitude if magnitude.is_infinite() => Ok("INF".to_string()), + magnitude if magnitude.is_nan() => Ok("NAN".to_owned()), + magnitude if magnitude.is_infinite() => Ok("INF".to_owned()), _ => Ok(format!("{:.*}", precision, magnitude)), }, Some(FormatType::FixedPointLower) => match magnitude { - magnitude if magnitude.is_nan() => Ok("nan".to_string()), - magnitude if magnitude.is_infinite() => Ok("inf".to_string()), + magnitude if magnitude.is_nan() => Ok("nan".to_owned()), + magnitude if magnitude.is_infinite() => Ok("inf".to_owned()), _ => Ok(format!("{:.*}", precision, magnitude)), }, Some(FormatType::Decimal) => Err("Unknown format code 'd' for object of type 'float'"), @@ -377,14 +377,14 @@ impl FormatSpec { Err("Format code 'e' for object of type 'float' not implemented yet") } Some(FormatType::Percentage) => match magnitude { - magnitude if magnitude.is_nan() => Ok("nan%".to_string()), - magnitude if magnitude.is_infinite() => Ok("inf%".to_string()), + magnitude if magnitude.is_nan() => Ok("nan%".to_owned()), + magnitude if magnitude.is_infinite() => Ok("inf%".to_owned()), _ => Ok(format!("{:.*}%", precision, magnitude * 100.0)), }, None => { match magnitude { - magnitude if magnitude.is_nan() => Ok("nan".to_string()), - magnitude if magnitude.is_infinite() => Ok("inf".to_string()), + magnitude if magnitude.is_nan() => Ok("nan".to_owned()), + magnitude if magnitude.is_infinite() => Ok("inf".to_owned()), // Using the Debug format here to prevent the automatic conversion of floats // ending in .0 to their integer representation (e.g., 1.0 -> 1) _ => Ok(format!("{:?}", magnitude)), @@ -625,7 +625,7 @@ impl FormatString { let arg_part = parts[0]; let preconversor_spec = if parts.len() > 1 { - "!".to_string() + parts[1] + "!".to_owned() + parts[1] } else { String::new() }; @@ -766,43 +766,43 @@ mod tests { parse_format_spec("d") .unwrap() .format_int(&BigInt::from_bytes_be(Sign::Plus, b"\x10")), - Ok("16".to_string()) + Ok("16".to_owned()) ); assert_eq!( parse_format_spec("x") .unwrap() .format_int(&BigInt::from_bytes_be(Sign::Plus, b"\x10")), - Ok("10".to_string()) + Ok("10".to_owned()) ); assert_eq!( parse_format_spec("b") .unwrap() .format_int(&BigInt::from_bytes_be(Sign::Plus, b"\x10")), - Ok("10000".to_string()) + Ok("10000".to_owned()) ); assert_eq!( parse_format_spec("o") .unwrap() .format_int(&BigInt::from_bytes_be(Sign::Plus, b"\x10")), - Ok("20".to_string()) + Ok("20".to_owned()) ); assert_eq!( parse_format_spec("+d") .unwrap() .format_int(&BigInt::from_bytes_be(Sign::Plus, b"\x10")), - Ok("+16".to_string()) + Ok("+16".to_owned()) ); assert_eq!( parse_format_spec("^ 5d") .unwrap() .format_int(&BigInt::from_bytes_be(Sign::Minus, b"\x10")), - Ok(" -16 ".to_string()) + Ok(" -16 ".to_owned()) ); assert_eq!( parse_format_spec("0>+#10x") .unwrap() .format_int(&BigInt::from_bytes_be(Sign::Plus, b"\x10")), - Ok("00000+0x10".to_string()) + Ok("00000+0x10".to_owned()) ); } @@ -810,10 +810,10 @@ mod tests { fn test_format_parse() { let expected = Ok(FormatString { format_parts: vec![ - FormatPart::Literal("abcd".to_string()), + FormatPart::Literal("abcd".to_owned()), FormatPart::IndexSpec(1, String::new()), - FormatPart::Literal(":".to_string()), - FormatPart::KeywordSpec("key".to_string(), String::new()), + FormatPart::Literal(":".to_owned()), + FormatPart::KeywordSpec("key".to_owned(), String::new()), ], }); @@ -832,9 +832,9 @@ mod tests { fn test_format_parse_escape() { let expected = Ok(FormatString { format_parts: vec![ - FormatPart::Literal("{".to_string()), - FormatPart::KeywordSpec("key".to_string(), String::new()), - FormatPart::Literal("}ddfe".to_string()), + FormatPart::Literal("{".to_owned()), + FormatPart::KeywordSpec("key".to_owned(), String::new()), + FormatPart::Literal("}ddfe".to_owned()), ], }); diff --git a/vm/src/frame.rs b/vm/src/frame.rs index a3ed5ffdb9..82b76b32d4 100644 --- a/vm/src/frame.rs +++ b/vm/src/frame.rs @@ -586,7 +586,7 @@ impl Frame { let value = self.pop_value(); let elements = vm.extract_elements(&value)?; if elements.len() != *size { - Err(vm.new_value_error("Wrong number of values to unpack".to_string())) + Err(vm.new_value_error("Wrong number of values to unpack".to_owned())) } else { for element in elements.into_iter().rev() { self.push_value(element); @@ -985,7 +985,7 @@ impl Frame { None => { return Err(vm.new_exception_msg( vm.ctx.exceptions.runtime_error.clone(), - "No active exception to reraise".to_string(), + "No active exception to reraise".to_owned(), )) } }, @@ -1390,7 +1390,7 @@ impl fmt::Debug for Frame { .iter() .map(|elem| { if elem.payload.as_any().is::() { - "\n > {frame}".to_string() + "\n > {frame}".to_owned() } else { format!("\n > {:?}", elem) } diff --git a/vm/src/obj/objbool.rs b/vm/src/obj/objbool.rs index 7c99fe6a10..a4b751c7e5 100644 --- a/vm/src/obj/objbool.rs +++ b/vm/src/obj/objbool.rs @@ -58,7 +58,7 @@ pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let len_val = int_obj.as_bigint(); if len_val.sign() == Sign::Minus { return Err( - vm.new_value_error("__len__() should return >= 0".to_string()) + vm.new_value_error("__len__() should return >= 0".to_owned()) ); } @@ -120,9 +120,9 @@ pub fn get_py_int(obj: &PyObjectRef) -> &PyInt { fn bool_repr(obj: bool, _vm: &VirtualMachine) -> String { if obj { - "True".to_string() + "True".to_owned() } else { - "False".to_string() + "False".to_owned() } } @@ -134,7 +134,7 @@ fn bool_format( if format_spec.as_str().is_empty() { vm.to_str(&obj) } else { - Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_string())) + Err(vm.new_type_error("unsupported format string passed to bool.__format__".to_owned())) } } diff --git a/vm/src/obj/objbytearray.rs b/vm/src/obj/objbytearray.rs index aa48bf6bb8..73e5d9d5d4 100644 --- a/vm/src/obj/objbytearray.rs +++ b/vm/src/obj/objbytearray.rs @@ -140,7 +140,7 @@ impl PyByteArray { #[pymethod(name = "__hash__")] fn hash(&self, vm: &VirtualMachine) -> PyResult<()> { - Err(vm.new_type_error("unhashable type: bytearray".to_string())) + Err(vm.new_type_error("unhashable type: bytearray".to_owned())) } #[pymethod(name = "__iter__")] @@ -331,7 +331,7 @@ impl PyByteArray { fn index(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { let res = self.inner.borrow().find(options, false, vm)?; if res == -1 { - return Err(vm.new_value_error("substring not found".to_string())); + return Err(vm.new_value_error("substring not found".to_owned())); } Ok(res) } @@ -345,7 +345,7 @@ impl PyByteArray { fn rindex(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { let res = self.inner.borrow().find(options, true, vm)?; if res == -1 { - return Err(vm.new_value_error("substring not found".to_string())); + return Err(vm.new_value_error("substring not found".to_owned())); } Ok(res) } @@ -358,7 +358,7 @@ impl PyByteArray { let pos = bytes .iter() .position(|b| *b == x) - .ok_or_else(|| vm.new_value_error("value not found in bytearray".to_string()))?; + .ok_or_else(|| vm.new_value_error("value not found in bytearray".to_owned()))?; bytes.remove(pos); @@ -529,7 +529,7 @@ impl PyByteArray { fn insert(&self, mut index: isize, x: PyIntRef, vm: &VirtualMachine) -> PyResult<()> { let bytes = &mut self.inner.borrow_mut().elements; let len = isize::try_from(bytes.len()) - .map_err(|_e| vm.new_overflow_error("bytearray too big".to_string()))?; + .map_err(|_e| vm.new_overflow_error("bytearray too big".to_owned()))?; let x = x.as_bigint().byte_or(vm)?; @@ -544,7 +544,7 @@ impl PyByteArray { } let index = usize::try_from(index) - .map_err(|_e| vm.new_overflow_error("overflow in index calculation".to_string()))?; + .map_err(|_e| vm.new_overflow_error("overflow in index calculation".to_owned()))?; bytes.insert(index, x); @@ -556,7 +556,7 @@ impl PyByteArray { let bytes = &mut self.inner.borrow_mut().elements; bytes .pop() - .ok_or_else(|| vm.new_index_error("pop from empty bytearray".to_string())) + .ok_or_else(|| vm.new_index_error("pop from empty bytearray".to_owned())) } #[pymethod(name = "title")] diff --git a/vm/src/obj/objbyteinner.rs b/vm/src/obj/objbyteinner.rs index 37c0616613..6a21f461fd 100644 --- a/vm/src/obj/objbyteinner.rs +++ b/vm/src/obj/objbyteinner.rs @@ -67,10 +67,10 @@ impl ByteInnerNewOptions { elements: bytes.get_value().to_vec(), }) } else { - Err(vm.new_type_error("encoding without a string argument".to_string())) + Err(vm.new_type_error("encoding without a string argument".to_owned())) } } else { - Err(vm.new_type_error("encoding without a string argument".to_string())) + Err(vm.new_type_error("encoding without a string argument".to_owned())) } // Only one argument } else { @@ -79,12 +79,12 @@ impl ByteInnerNewOptions { i @ PyInt => { let size = objint::get_value(&i.into_object()) .to_usize() - .ok_or_else(|| vm.new_value_error("negative count".to_string()))?; + .ok_or_else(|| vm.new_value_error("negative count".to_owned()))?; Ok(vec![0; size]) } _l @ PyString => { return Err( - vm.new_type_error("string argument without an encoding".to_string()) + vm.new_type_error("string argument without an encoding".to_owned()) ); } i @ PyBytes => Ok(i.get_value().to_vec()), @@ -108,9 +108,9 @@ impl ByteInnerNewOptions { if let Some(i) = v.to_u8() { data_bytes.push(i); } else { - return Err(vm.new_value_error( - "bytes must be in range(0, 256)".to_string(), - )); + return Err( + vm.new_value_error("bytes must be in range(0, 256)".to_owned()) + ); } } Ok(data_bytes) @@ -230,7 +230,7 @@ impl ByteInnerTranslateOptions { if table.len() != 256 { return Err( - vm.new_value_error("translation table must be 256 characters long".to_string()) + vm.new_value_error("translation table must be 256 characters long".to_owned()) ); } @@ -395,7 +395,7 @@ impl PyByteInner { if let Some(idx) = self.elements.get_pos(int) { Ok(vm.new_int(self.elements[idx])) } else { - Err(vm.new_index_error("index out of range".to_string())) + Err(vm.new_index_error("index out of range".to_owned())) } } Either::B(slice) => Ok(vm @@ -411,16 +411,16 @@ impl PyByteInner { if let Some(value) = i.as_bigint().to_u8() { Ok(value) } else { - Err(vm.new_value_error("byte must be in range(0, 256)".to_string())) + Err(vm.new_value_error("byte must be in range(0, 256)".to_owned())) } } - _ => Err(vm.new_type_error("an integer is required".to_string())), + _ => Err(vm.new_type_error("an integer is required".to_owned())), }); let value = result?; self.elements[idx] = value; Ok(vm.new_int(value)) } else { - Err(vm.new_index_error("index out of range".to_string())) + Err(vm.new_index_error("index out of range".to_owned())) } } @@ -479,7 +479,7 @@ impl PyByteInner { self.elements.remove(idx); Ok(()) } else { - Err(vm.new_index_error("index out of range".to_string())) + Err(vm.new_index_error("index out of range".to_owned())) } } Either::B(slice) => self.delslice(slice, vm), @@ -493,7 +493,7 @@ impl PyByteInner { let step = slice.step_index(vm)?.unwrap_or_else(BigInt::one); if step.is_zero() { - Err(vm.new_value_error("slice step cannot be zero".to_string())) + Err(vm.new_value_error("slice step cannot be zero".to_owned())) } else if step.is_positive() { let range = self.elements.get_slice_range(&start, &stop); if range.start < range.end { @@ -1215,7 +1215,7 @@ pub trait ByteOr: ToPrimitive { fn byte_or(&self, vm: &VirtualMachine) -> PyResult { match self.to_u8() { Some(value) => Ok(value), - None => Err(vm.new_value_error("byte must be in range(0, 256)".to_string())), + None => Err(vm.new_value_error("byte must be in range(0, 256)".to_owned())), } } } diff --git a/vm/src/obj/objbytes.rs b/vm/src/obj/objbytes.rs index e38b76353b..99a9c6a26f 100644 --- a/vm/src/obj/objbytes.rs +++ b/vm/src/obj/objbytes.rs @@ -301,7 +301,7 @@ impl PyBytes { fn index(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { let res = self.inner.find(options, false, vm)?; if res == -1 { - return Err(vm.new_value_error("substring not found".to_string())); + return Err(vm.new_value_error("substring not found".to_owned())); } Ok(res) } @@ -315,7 +315,7 @@ impl PyBytes { fn rindex(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { let res = self.inner.find(options, true, vm)?; if res == -1 { - return Err(vm.new_value_error("substring not found".to_string())); + return Err(vm.new_value_error("substring not found".to_owned())); } Ok(res) } diff --git a/vm/src/obj/objcode.rs b/vm/src/obj/objcode.rs index f1598ad8f3..cfb634c8b1 100644 --- a/vm/src/obj/objcode.rs +++ b/vm/src/obj/objcode.rs @@ -44,7 +44,7 @@ impl PyValue for PyCode { impl PyCodeRef { #[allow(clippy::new_ret_no_self)] fn new(_cls: PyClassRef, vm: &VirtualMachine) -> PyResult { - Err(vm.new_type_error("Cannot directly create code object".to_string())) + Err(vm.new_type_error("Cannot directly create code object".to_owned())) } fn repr(self, _vm: &VirtualMachine) -> String { diff --git a/vm/src/obj/objcomplex.rs b/vm/src/obj/objcomplex.rs index 1f90592364..24085c1412 100644 --- a/vm/src/obj/objcomplex.rs +++ b/vm/src/obj/objcomplex.rs @@ -155,7 +155,7 @@ impl PyComplex { #[pymethod(name = "__mod__")] fn mod_(&self, _other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - Err(vm.new_type_error("can't mod complex numbers.".to_string())) + Err(vm.new_type_error("can't mod complex numbers.".to_owned())) } #[pymethod(name = "__rmod__")] @@ -165,7 +165,7 @@ impl PyComplex { #[pymethod(name = "__floordiv__")] fn floordiv(&self, _other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - Err(vm.new_type_error("can't take floor of complex number.".to_string())) + Err(vm.new_type_error("can't take floor of complex number.".to_owned())) } #[pymethod(name = "__rfloordiv__")] @@ -175,7 +175,7 @@ impl PyComplex { #[pymethod(name = "__divmod__")] fn divmod(&self, _other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - Err(vm.new_type_error("can't take floor or mod of complex number.".to_string())) + Err(vm.new_type_error("can't take floor or mod of complex number.".to_owned())) } #[pymethod(name = "__rdivmod__")] diff --git a/vm/src/obj/objcoroutine.rs b/vm/src/obj/objcoroutine.rs index 4dad7d71d0..eb6f1faa2c 100644 --- a/vm/src/obj/objcoroutine.rs +++ b/vm/src/obj/objcoroutine.rs @@ -91,7 +91,7 @@ impl PyCoroutine { match result { Ok(ExecutionResult::Yield(_)) => Err(vm.new_exception_msg( vm.ctx.exceptions.runtime_error.clone(), - "generator ignored GeneratorExit".to_string(), + "generator ignored GeneratorExit".to_owned(), )), Err(e) => { if isinstance(&e, &vm.ctx.exceptions.generator_exit) { diff --git a/vm/src/obj/objdict.rs b/vm/src/obj/objdict.rs index c46c6a488e..d00e404a41 100644 --- a/vm/src/obj/objdict.rs +++ b/vm/src/obj/objdict.rs @@ -79,7 +79,7 @@ impl PyDictRef { let iter = objiter::get_iter(vm, &dict_obj)?; loop { fn err(vm: &VirtualMachine) -> PyBaseExceptionRef { - vm.new_type_error("Iterator must have exactly two elements".to_string()) + vm.new_type_error("Iterator must have exactly two elements".to_owned()) } let element = match objiter::get_next_object(vm, &iter)? { Some(obj) => obj, @@ -189,7 +189,7 @@ impl PyDictRef { format!("{{{}}}", str_parts.join(", ")) } else { - "{...}".to_string() + "{...}".to_owned() }; Ok(s) } @@ -343,7 +343,7 @@ impl PyDictRef { if let Some((key, value)) = entries.pop_front() { Ok(vm.ctx.new_tuple(vec![key, value])) } else { - let err_msg = vm.new_str("popitem(): dictionary is empty".to_string()); + let err_msg = vm.new_str("popitem(): dictionary is empty".to_owned()); Err(vm.new_key_error(err_msg)) } } @@ -371,7 +371,7 @@ impl PyDictRef { #[pymethod(magic)] fn hash(self, vm: &VirtualMachine) -> PyResult<()> { - Err(vm.new_type_error("unhashable type".to_string())) + Err(vm.new_type_error("unhashable type".to_owned())) } pub fn contains_key(&self, key: T, vm: &VirtualMachine) -> bool { @@ -528,7 +528,7 @@ macro_rules! dict_iterator { } format!("{}([{}])", $class_name, str_parts.join(", ")) } else { - "{...}".to_string() + "{...}".to_owned() }; Ok(s) } @@ -566,7 +566,7 @@ macro_rules! dict_iterator { if dict.has_changed_size(&self.size) { return Err(vm.new_exception_msg( vm.ctx.exceptions.runtime_error.clone(), - "dictionary changed size during iteration".to_string(), + "dictionary changed size during iteration".to_owned(), )); } match dict.next_entry(&mut position) { diff --git a/vm/src/obj/objellipsis.rs b/vm/src/obj/objellipsis.rs index a836ca58e4..a8a22a4da0 100644 --- a/vm/src/obj/objellipsis.rs +++ b/vm/src/obj/objellipsis.rs @@ -22,9 +22,9 @@ fn ellipsis_new(cls: PyClassRef, vm: &VirtualMachine) -> PyResult { } fn ellipsis_repr(_self: PyEllipsisRef, _vm: &VirtualMachine) -> String { - "Ellipsis".to_string() + "Ellipsis".to_owned() } fn ellipsis_reduce(_self: PyEllipsisRef, _vm: &VirtualMachine) -> String { - "Ellipsis".to_string() + "Ellipsis".to_owned() } diff --git a/vm/src/obj/objfloat.rs b/vm/src/obj/objfloat.rs index f6650ee4a7..2b660994b0 100644 --- a/vm/src/obj/objfloat.rs +++ b/vm/src/obj/objfloat.rs @@ -80,7 +80,7 @@ fn inner_div(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { if v2 != 0.0 { Ok(v1 / v2) } else { - Err(vm.new_zero_division_error("float division by zero".to_string())) + Err(vm.new_zero_division_error("float division by zero".to_owned())) } } @@ -88,7 +88,7 @@ fn inner_mod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { if v2 != 0.0 { Ok(v1 % v2) } else { - Err(vm.new_zero_division_error("float mod by zero".to_string())) + Err(vm.new_zero_division_error("float mod by zero".to_owned())) } } @@ -98,11 +98,11 @@ pub fn try_bigint(value: f64, vm: &VirtualMachine) -> PyResult { None => { if value.is_infinite() { Err(vm.new_overflow_error( - "OverflowError: cannot convert float infinity to integer".to_string(), + "OverflowError: cannot convert float infinity to integer".to_owned(), )) } else if value.is_nan() { Err(vm - .new_value_error("ValueError: cannot convert float NaN to integer".to_string())) + .new_value_error("ValueError: cannot convert float NaN to integer".to_owned())) } else { // unreachable unless BigInt has a bug unreachable!( @@ -118,7 +118,7 @@ fn inner_floordiv(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { if v2 != 0.0 { Ok((v1 / v2).floor()) } else { - Err(vm.new_zero_division_error("float floordiv by zero".to_string())) + Err(vm.new_zero_division_error("float floordiv by zero".to_owned())) } } @@ -126,7 +126,7 @@ fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> { if v2 != 0.0 { Ok(((v1 / v2).floor(), v1 % v2)) } else { - Err(vm.new_zero_division_error("float divmod()".to_string())) + Err(vm.new_zero_division_error("float divmod()".to_owned())) } } @@ -524,11 +524,11 @@ impl PyFloat { let value = self.value; if value.is_infinite() { return Err( - vm.new_overflow_error("cannot convert Infinity to integer ratio".to_string()) + vm.new_overflow_error("cannot convert Infinity to integer ratio".to_owned()) ); } if value.is_nan() { - return Err(vm.new_value_error("cannot convert NaN to integer ratio".to_string())); + return Err(vm.new_value_error("cannot convert NaN to integer ratio".to_owned())); } let ratio = Ratio::from_float(value).unwrap(); @@ -584,7 +584,7 @@ impl PyFloat { } hexf_parse::parse_hexf64(hex.as_str(), false).map_err(|_| { - vm.new_value_error("invalid hexadecimal floating-point string".to_string()) + vm.new_value_error("invalid hexadecimal floating-point string".to_owned()) }) } } @@ -661,7 +661,7 @@ fn to_hex(value: f64) -> String { match value { value if value.is_zero() => format!("{}0x0.0p+0", sign_fmt), value if value.is_infinite() => format!("{}inf", sign_fmt), - value if value.is_nan() => "nan".to_string(), + value if value.is_nan() => "nan".to_owned(), _ => { const BITS: i16 = 52; const FRACT_MASK: u64 = 0xf_ffff_ffff_ffff; diff --git a/vm/src/obj/objframe.rs b/vm/src/obj/objframe.rs index 46eaf52999..73067bd4bb 100644 --- a/vm/src/obj/objframe.rs +++ b/vm/src/obj/objframe.rs @@ -16,12 +16,12 @@ pub fn init(context: &PyContext) { impl FrameRef { #[pyslot] fn tp_new(_cls: FrameRef, vm: &VirtualMachine) -> PyResult { - Err(vm.new_type_error("Cannot directly create frame object".to_string())) + Err(vm.new_type_error("Cannot directly create frame object".to_owned())) } #[pymethod(name = "__repr__")] fn repr(self, _vm: &VirtualMachine) -> String { - "".to_string() + "".to_owned() } #[pymethod] diff --git a/vm/src/obj/objgenerator.rs b/vm/src/obj/objgenerator.rs index 56927bd19d..a42519d7fe 100644 --- a/vm/src/obj/objgenerator.rs +++ b/vm/src/obj/objgenerator.rs @@ -104,7 +104,7 @@ impl PyGenerator { match result { Ok(ExecutionResult::Yield(_)) => Err(vm.new_exception_msg( vm.ctx.exceptions.runtime_error.clone(), - "generator ignored GeneratorExit".to_string(), + "generator ignored GeneratorExit".to_owned(), )), Err(e) => { if isinstance(&e, &vm.ctx.exceptions.generator_exit) { diff --git a/vm/src/obj/objint.rs b/vm/src/obj/objint.rs index d84f060333..a54833528c 100644 --- a/vm/src/obj/objint.rs +++ b/vm/src/obj/objint.rs @@ -144,7 +144,7 @@ fn inner_pow(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { fn inner_mod(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { if int2.is_zero() { - Err(vm.new_zero_division_error("integer modulo by zero".to_string())) + Err(vm.new_zero_division_error("integer modulo by zero".to_owned())) } else { Ok(vm.ctx.new_int(int1.mod_floor(int2))) } @@ -152,7 +152,7 @@ fn inner_mod(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { fn inner_floordiv(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { if int2.is_zero() { - Err(vm.new_zero_division_error("integer division by zero".to_string())) + Err(vm.new_zero_division_error("integer division by zero".to_owned())) } else { Ok(vm.ctx.new_int(int1.div_floor(&int2))) } @@ -160,7 +160,7 @@ fn inner_floordiv(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult fn inner_divmod(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { if int2.is_zero() { - Err(vm.new_zero_division_error("integer division or modulo by zero".to_string())) + Err(vm.new_zero_division_error("integer division or modulo by zero".to_owned())) } else { let (div, modulo) = int1.div_mod_floor(int2); Ok(vm @@ -182,7 +182,7 @@ fn inner_rshift(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { #[inline] fn inner_truediv(i1: &BigInt, i2: &BigInt, vm: &VirtualMachine) -> PyResult { if i2.is_zero() { - return Err(vm.new_zero_division_error("integer division by zero".to_string())); + return Err(vm.new_zero_division_error("integer division by zero".to_owned())); } if let (Some(f1), Some(f2)) = (i1.to_f64(), i2.to_f64()) { @@ -206,7 +206,7 @@ fn inner_truediv(i1: &BigInt, i2: &BigInt, vm: &VirtualMachine) -> PyResult { Ok(vm.ctx.new_float(quotient + rem_part)) } else { - Err(vm.new_overflow_error("int too large to convert to float".to_string())) + Err(vm.new_overflow_error("int too large to convert to float".to_owned())) } } } @@ -555,7 +555,7 @@ impl PyInt { }, _ => { return Err( - vm.new_value_error("byteorder must be either 'little' or 'big'".to_string()) + vm.new_value_error("byteorder must be either 'little' or 'big'".to_owned()) ) } }; @@ -573,14 +573,14 @@ impl PyInt { let value = self.as_bigint(); if value.sign() == Sign::Minus && !signed { - return Err(vm.new_overflow_error("can't convert negative int to unsigned".to_string())); + return Err(vm.new_overflow_error("can't convert negative int to unsigned".to_owned())); } let byte_len = if let Some(byte_len) = args.length.as_bigint().to_usize() { byte_len } else { return Err( - vm.new_overflow_error("Python int too large to convert to C ssize_t".to_string()) + vm.new_overflow_error("Python int too large to convert to C ssize_t".to_owned()) ); }; @@ -595,14 +595,14 @@ impl PyInt { }, _ => { return Err( - vm.new_value_error("byteorder must be either 'little' or 'big'".to_string()) + vm.new_value_error("byteorder must be either 'little' or 'big'".to_owned()) ); } }; let origin_len = origin_bytes.len(); if origin_len > byte_len { - return Err(vm.new_overflow_error("int too big to convert".to_string())); + return Err(vm.new_overflow_error("int too big to convert".to_owned())); } let mut append_bytes = match value.sign() { @@ -661,7 +661,7 @@ impl IntOptions { || objtype::isinstance(&val, &vm.ctx.bytes_type())) { return Err(vm.new_type_error( - "int() can't convert non-string with explicit base".to_string(), + "int() can't convert non-string with explicit base".to_owned(), )); } base @@ -670,7 +670,7 @@ impl IntOptions { }; to_int(vm, &val, base.as_bigint()) } else if let OptionalArg::Present(_) = self.base { - Err(vm.new_type_error("int() missing string argument".to_string())) + Err(vm.new_type_error("int() missing string argument".to_owned())) } else { Ok(Zero::zero()) } @@ -702,11 +702,11 @@ pub fn to_int(vm: &VirtualMachine, obj: &PyObjectRef, base: &BigInt) -> PyResult let base_u32 = match base.to_u32() { Some(base_u32) => base_u32, None => { - return Err(vm.new_value_error("int() base must be >= 2 and <= 36, or 0".to_string())) + return Err(vm.new_value_error("int() base must be >= 2 and <= 36, or 0".to_owned())) } }; if base_u32 != 0 && (base_u32 < 2 || base_u32 > 36) { - return Err(vm.new_value_error("int() base must be >= 2 and <= 36, or 0".to_string())); + return Err(vm.new_value_error("int() base must be >= 2 and <= 36, or 0".to_owned())); } match_class!(match obj.clone() { @@ -834,7 +834,7 @@ pub fn get_value(obj: &PyObjectRef) -> &BigInt { pub fn try_float(int: &BigInt, vm: &VirtualMachine) -> PyResult { int.to_f64() - .ok_or_else(|| vm.new_overflow_error("int too large to convert to float".to_string())) + .ok_or_else(|| vm.new_overflow_error("int too large to convert to float".to_owned())) } fn get_shift_amount(amount: &BigInt, vm: &VirtualMachine) -> PyResult { @@ -842,9 +842,9 @@ fn get_shift_amount(amount: &BigInt, vm: &VirtualMachine) -> PyResult { Ok(n_bits) } else { match amount { - v if *v < BigInt::zero() => Err(vm.new_value_error("negative shift count".to_string())), + v if *v < BigInt::zero() => Err(vm.new_value_error("negative shift count".to_owned())), v if *v > BigInt::from(usize::max_value()) => { - Err(vm.new_overflow_error("the number is too large to convert to int".to_string())) + Err(vm.new_overflow_error("the number is too large to convert to int".to_owned())) } _ => panic!("Failed converting {} to rust usize", amount), } diff --git a/vm/src/obj/objiter.rs b/vm/src/obj/objiter.rs index 58bc61402d..2d98a04037 100644 --- a/vm/src/obj/objiter.rs +++ b/vm/src/obj/objiter.rs @@ -128,10 +128,10 @@ pub fn length_hint(vm: &VirtualMachine, iter: PyObjectRef) -> PyResult= 0".to_string())); + return Err(vm.new_value_error("__length_hint__() should return >= 0".to_owned())); } let hint = result.to_usize().ok_or_else(|| { - vm.new_value_error("Python int too large to convert to Rust usize".to_string()) + vm.new_value_error("Python int too large to convert to Rust usize".to_owned()) })?; Ok(Some(hint)) } @@ -185,7 +185,7 @@ impl PySequenceIterator { pos + 1 } else { let len = objsequence::opt_len(&self.obj, vm).unwrap_or_else(|| { - Err(vm.new_type_error("sequence has no __len__ method".to_string())) + Err(vm.new_type_error("sequence has no __len__ method".to_owned())) })?; len as isize - pos }; diff --git a/vm/src/obj/objlist.rs b/vm/src/obj/objlist.rs index 4caf5f3577..5dc58f26cd 100644 --- a/vm/src/obj/objlist.rs +++ b/vm/src/obj/objlist.rs @@ -119,9 +119,7 @@ impl PyList { Ok(result) => match result.as_bigint().to_u8() { Some(result) => elements.push(result), None => { - return Err( - vm.new_value_error("bytes must be in range (0, 256)".to_string()) - ) + return Err(vm.new_value_error("bytes must be in range (0, 256)".to_owned())) } }, _ => { @@ -272,7 +270,7 @@ impl PyList { if let Ok(sec) = PyIterable::try_from_object(vm, value) { return self.setslice(slice, sec, vm); } - Err(vm.new_type_error("can only assign an iterable to a slice".to_string())) + Err(vm.new_type_error("can only assign an iterable to a slice".to_owned())) } } } @@ -282,7 +280,7 @@ impl PyList { self.elements.borrow_mut()[pos_index] = value; Ok(vm.get_none()) } else { - Err(vm.new_index_error("list assignment index out of range".to_string())) + Err(vm.new_index_error("list assignment index out of range".to_owned())) } } @@ -290,7 +288,7 @@ impl PyList { let step = slice.step_index(vm)?.unwrap_or_else(BigInt::one); if step.is_zero() { - Err(vm.new_value_error("slice step cannot be zero".to_string())) + Err(vm.new_value_error("slice step cannot be zero".to_owned())) } else if step.is_positive() { let range = self.get_slice_range(&slice.start_index(vm)?, &slice.stop_index(vm)?); if range.start < range.end { @@ -459,14 +457,14 @@ impl PyList { } format!("[{}]", str_parts.join(", ")) } else { - "[...]".to_string() + "[...]".to_owned() }; Ok(s) } #[pymethod(name = "__hash__")] fn hash(&self, vm: &VirtualMachine) -> PyResult<()> { - Err(vm.new_type_error("unhashable type".to_string())) + Err(vm.new_type_error("unhashable type".to_owned())) } #[pymethod(name = "__mul__")] @@ -532,9 +530,9 @@ impl PyList { i += elements.len() as isize; } if elements.is_empty() { - Err(vm.new_index_error("pop from empty list".to_string())) + Err(vm.new_index_error("pop from empty list".to_owned())) } else if i < 0 || i as usize >= elements.len() { - Err(vm.new_index_error("pop index out of range".to_string())) + Err(vm.new_index_error("pop index out of range".to_owned())) } else { Ok(elements.remove(i as usize)) } @@ -627,7 +625,7 @@ impl PyList { self.elements.borrow_mut().remove(pos_index); Ok(()) } else { - Err(vm.new_index_error("Index out of bounds!".to_string())) + Err(vm.new_index_error("Index out of bounds!".to_owned())) } } @@ -637,7 +635,7 @@ impl PyList { let step = slice.step_index(vm)?.unwrap_or_else(BigInt::one); if step.is_zero() { - Err(vm.new_value_error("slice step cannot be zero".to_string())) + Err(vm.new_value_error("slice step cannot be zero".to_owned())) } else if step.is_positive() { let range = self.get_slice_range(&start, &stop); if range.start < range.end { @@ -756,7 +754,7 @@ impl PyList { let temp_elements = self.elements.replace(elements); if !temp_elements.is_empty() { - return Err(vm.new_value_error("list modified during sort".to_string())); + return Err(vm.new_value_error("list modified during sort".to_owned())); } Ok(()) diff --git a/vm/src/obj/objnone.rs b/vm/src/obj/objnone.rs index 57a6fcd8d5..51984923d0 100644 --- a/vm/src/obj/objnone.rs +++ b/vm/src/obj/objnone.rs @@ -44,7 +44,7 @@ impl PyNone { #[pymethod(name = "__repr__")] fn repr(&self, _vm: &VirtualMachine) -> PyResult { - Ok("None".to_string()) + Ok("None".to_owned()) } #[pymethod(name = "__bool__")] diff --git a/vm/src/obj/objproperty.rs b/vm/src/obj/objproperty.rs index 4660a3c650..d25feb227c 100644 --- a/vm/src/obj/objproperty.rs +++ b/vm/src/obj/objproperty.rs @@ -124,7 +124,7 @@ impl PyBuiltinDescriptor for PyProperty { vm.invoke(&getter, obj) } } else { - Err(vm.new_attribute_error("unreadable attribute".to_string())) + Err(vm.new_attribute_error("unreadable attribute".to_owned())) } } } @@ -149,7 +149,7 @@ impl PyProperty { if let Some(ref getter) = self.getter.as_ref() { vm.invoke(getter, obj) } else { - Err(vm.new_attribute_error("unreadable attribute".to_string())) + Err(vm.new_attribute_error("unreadable attribute".to_owned())) } } @@ -158,7 +158,7 @@ impl PyProperty { if let Some(ref setter) = self.setter.as_ref() { vm.invoke(setter, vec![obj, value]) } else { - Err(vm.new_attribute_error("can't set attribute".to_string())) + Err(vm.new_attribute_error("can't set attribute".to_owned())) } } @@ -167,7 +167,7 @@ impl PyProperty { if let Some(ref deleter) = self.deleter.as_ref() { vm.invoke(deleter, obj) } else { - Err(vm.new_attribute_error("can't delete attribute".to_string())) + Err(vm.new_attribute_error("can't delete attribute".to_owned())) } } diff --git a/vm/src/obj/objrange.rs b/vm/src/obj/objrange.rs index 28998962ea..569dc4b472 100644 --- a/vm/src/obj/objrange.rs +++ b/vm/src/obj/objrange.rs @@ -148,7 +148,7 @@ impl PyRange { ) -> PyResult { let step = step.unwrap_or_else(|| PyInt::new(BigInt::one()).into_ref(vm)); if step.as_bigint().is_zero() { - return Err(vm.new_value_error("range() arg 3 must not be zero".to_string())); + return Err(vm.new_value_error("range() arg 3 must not be zero".to_owned())); } PyRange { start, stop, step }.into_ref_with_type(vm, cls) } @@ -318,7 +318,7 @@ impl PyRange { None => Err(vm.new_value_error(format!("{} is not in range", int))), } } else { - Err(vm.new_value_error("sequence.index(x): x not in sequence".to_string())) + Err(vm.new_value_error("sequence.index(x): x not in sequence".to_owned())) } } @@ -358,7 +358,7 @@ impl PyRange { } RangeIndex::Int(index) => match self.get(index.as_bigint()) { Some(value) => Ok(PyInt::new(value).into_ref(vm).into_object()), - None => Err(vm.new_index_error("range object index out of range".to_string())), + None => Err(vm.new_index_error("range object index out of range".to_owned())), }, } } diff --git a/vm/src/obj/objsequence.rs b/vm/src/obj/objsequence.rs index aecfea2195..53bd6cacc9 100644 --- a/vm/src/obj/objsequence.rs +++ b/vm/src/obj/objsequence.rs @@ -73,7 +73,7 @@ pub trait PySliceableSequence { let stop = slice.stop_index(vm)?; let step = slice.step_index(vm)?.unwrap_or_else(BigInt::one); if step.is_zero() { - Err(vm.new_value_error("slice step cannot be zero".to_string())) + Err(vm.new_value_error("slice step cannot be zero".to_owned())) } else if step.is_positive() { let range = self.get_slice_range(&start, &stop); if range.start < range.end { @@ -182,7 +182,7 @@ pub fn get_sequence_index(vm: &VirtualMachine, index: &PyIntRef, length: usize) if value < 0 { let from_end: usize = -value as usize; if from_end > length { - Err(vm.new_index_error("Index out of bounds!".to_string())) + Err(vm.new_index_error("Index out of bounds!".to_owned())) } else { let index = length - from_end; Ok(index) @@ -190,13 +190,13 @@ pub fn get_sequence_index(vm: &VirtualMachine, index: &PyIntRef, length: usize) } else { let index = value as usize; if index >= length { - Err(vm.new_index_error("Index out of bounds!".to_string())) + Err(vm.new_index_error("Index out of bounds!".to_owned())) } else { Ok(index) } } } else { - Err(vm.new_index_error("cannot fit 'int' into an index-sized integer".to_string())) + Err(vm.new_index_error("cannot fit 'int' into an index-sized integer".to_owned())) } } @@ -213,11 +213,11 @@ pub fn get_item( let obj = elements[pos_index].clone(); Ok(obj) } else { - Err(vm.new_index_error("Index out of bounds!".to_string())) + Err(vm.new_index_error("Index out of bounds!".to_owned())) } } None => { - Err(vm.new_index_error("cannot fit 'int' into an index-sized integer".to_string())) + Err(vm.new_index_error("cannot fit 'int' into an index-sized integer".to_owned())) } }; } @@ -256,7 +256,7 @@ pub fn is_valid_slice_arg( i @ PyInt => Ok(Some(i.as_bigint().clone())), _obj @ PyNone => Ok(None), _ => Err(vm.new_type_error( - "slice indices must be integers or None or have an __index__ method".to_string() + "slice indices must be integers or None or have an __index__ method".to_owned() )), // TODO: check for an __index__ method }) } else { @@ -277,10 +277,10 @@ pub fn opt_len(obj: &PyObjectRef, vm: &VirtualMachine) -> Option })? .as_bigint(); if len.is_negative() { - return Err(vm.new_value_error("__len__() should return >= 0".to_string())); + return Err(vm.new_value_error("__len__() should return >= 0".to_owned())); } len.to_usize().ok_or_else(|| { - vm.new_overflow_error("cannot fit __len__() result into usize".to_string()) + vm.new_overflow_error("cannot fit __len__() result into usize".to_owned()) }) }) } diff --git a/vm/src/obj/objset.rs b/vm/src/obj/objset.rs index 6884cfa4cc..73e48ad247 100644 --- a/vm/src/obj/objset.rs +++ b/vm/src/obj/objset.rs @@ -275,7 +275,7 @@ impl PySetInner { if let Some((key, _)) = self.content.pop_front() { Ok(key) } else { - let err_msg = vm.new_str("pop from an empty set".to_string()); + let err_msg = vm.new_str("pop from an empty set".to_owned()); Err(vm.new_key_error(err_msg)) } } @@ -486,11 +486,11 @@ impl PySet { fn repr(zelf: PyRef, vm: &VirtualMachine) -> PyResult { let inner = zelf.inner.borrow(); let s = if inner.len() == 0 { - "set()".to_string() + "set()".to_owned() } else if let Some(_guard) = ReprGuard::enter(zelf.as_object()) { inner.repr(vm)? } else { - "set(...)".to_string() + "set(...)".to_owned() }; Ok(vm.new_str(s)) } @@ -580,7 +580,7 @@ impl PySet { #[pymethod(name = "__hash__")] fn hash(&self, vm: &VirtualMachine) -> PyResult<()> { - Err(vm.new_type_error("unhashable type".to_string())) + Err(vm.new_type_error("unhashable type".to_owned())) } } @@ -742,11 +742,11 @@ impl PyFrozenSet { fn repr(zelf: PyRef, vm: &VirtualMachine) -> PyResult { let inner = &zelf.inner; let s = if inner.len() == 0 { - "frozenset()".to_string() + "frozenset()".to_owned() } else if let Some(_guard) = ReprGuard::enter(zelf.as_object()) { format!("frozenset({})", inner.repr(vm)?) } else { - "frozenset(...)".to_string() + "frozenset(...)".to_owned() }; Ok(vm.new_str(s)) } diff --git a/vm/src/obj/objslice.rs b/vm/src/obj/objslice.rs index 42e3ba24aa..51ceb237da 100644 --- a/vm/src/obj/objslice.rs +++ b/vm/src/obj/objslice.rs @@ -302,7 +302,7 @@ impl PySlice { #[pymethod(name = "__hash__")] fn hash(&self, vm: &VirtualMachine) -> PyResult<()> { - Err(vm.new_type_error("unhashable type".to_string())) + Err(vm.new_type_error("unhashable type".to_owned())) } #[pymethod(name = "indices")] @@ -332,11 +332,11 @@ fn to_index_value(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult() { Ok(Some(val.as_bigint().clone())) } else { - Err(vm.new_type_error("__index__ method returned non integer".to_string())) + Err(vm.new_type_error("__index__ method returned non integer".to_owned())) } } else { Err(vm.new_type_error( - "slice indices must be integers or None or have an __index__ method".to_string(), + "slice indices must be integers or None or have an __index__ method".to_owned(), )) } } diff --git a/vm/src/obj/objstr.rs b/vm/src/obj/objstr.rs index a95ea3c377..10e6eba69d 100644 --- a/vm/src/obj/objstr.rs +++ b/vm/src/obj/objstr.rs @@ -266,12 +266,13 @@ impl PyString { if let Some(character) = self.value.chars().nth(index) { Ok(vm.new_str(character.to_string())) } else { - Err(vm.new_index_error("string index out of range".to_string())) + Err(vm.new_index_error("string index out of range".to_owned())) } } - None => Err( - vm.new_index_error("cannot fit 'int' into an index-sized integer".to_string()) - ), + None => { + Err(vm + .new_index_error("cannot fit 'int' into an index-sized integer".to_owned())) + } }, Either::B(slice) => { let string = self @@ -332,7 +333,7 @@ impl PyString { .to_usize() .map(|multiplier| self.value.repeat(multiplier)) .ok_or_else(|| { - vm.new_overflow_error("cannot fit 'int' into an index-sized integer".to_string()) + vm.new_overflow_error("cannot fit 'int' into an index-sized integer".to_owned()) }) } @@ -605,7 +606,7 @@ impl PyString { fn format(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { if args.args.is_empty() { return Err(vm.new_type_error( - "descriptor 'format' of 'str' object needs an argument".to_string(), + "descriptor 'format' of 'str' object needs an argument".to_owned(), )); } @@ -623,9 +624,9 @@ impl PyString { Ok(format_string) => perform_format(vm, &format_string, &args), Err(err) => match err { FormatParseError::UnmatchedBracket => { - Err(vm.new_value_error("expected '}' before end of string".to_string())) + Err(vm.new_value_error("expected '}' before end of string".to_owned())) } - _ => Err(vm.new_value_error("Unexpected error parsing format string".to_string())), + _ => Err(vm.new_value_error("Unexpected error parsing format string".to_owned())), }, } } @@ -649,9 +650,9 @@ impl PyString { Ok(format_string) => perform_format_map(vm, &format_string, &args.args[1]), Err(err) => match err { FormatParseError::UnmatchedBracket => { - Err(vm.new_value_error("expected '}' before end of string".to_string())) + Err(vm.new_value_error("expected '}' before end of string".to_owned())) } - _ => Err(vm.new_value_error("Unexpected error parsing format string".to_string())), + _ => Err(vm.new_value_error("Unexpected error parsing format string".to_owned())), }, } } @@ -786,7 +787,7 @@ impl PyString { fn splitlines(&self, args: SplitLineArgs, vm: &VirtualMachine) -> PyObjectRef { let keepends = args.keepends.unwrap_or(false); let mut elements = vec![]; - let mut curr = "".to_string(); + let mut curr = "".to_owned(); for ch in self.value.chars() { if ch == '\n' { if keepends { @@ -869,10 +870,10 @@ impl PyString { if let Some((start, end)) = adjust_indices(start, end, value.len()) { match value[start..end].find(&sub.value) { Some(num) => Ok(start + num), - None => Err(vm.new_value_error("substring not found".to_string())), + None => Err(vm.new_value_error("substring not found".to_owned())), } } else { - Err(vm.new_value_error("substring not found".to_string())) + Err(vm.new_value_error("substring not found".to_owned())) } } @@ -888,10 +889,10 @@ impl PyString { if let Some((start, end)) = adjust_indices(start, end, value.len()) { match value[start..end].rfind(&sub.value) { Some(num) => Ok(start + num), - None => Err(vm.new_value_error("substring not found".to_string())), + None => Err(vm.new_value_error("substring not found".to_owned())), } } else { - Err(vm.new_value_error("substring not found".to_string())) + Err(vm.new_value_error("substring not found".to_owned())) } } @@ -908,8 +909,8 @@ impl PyString { new_tup.insert(1, vm.ctx.new_str(sub.clone())); } else { new_tup.push(vm.ctx.new_str(value.clone())); - new_tup.push(vm.ctx.new_str("".to_string())); - new_tup.push(vm.ctx.new_str("".to_string())); + new_tup.push(vm.ctx.new_str("".to_owned())); + new_tup.push(vm.ctx.new_str("".to_owned())); } vm.ctx.new_tuple(new_tup) } @@ -927,8 +928,8 @@ impl PyString { new_tup.swap(0, 1); // so it's in the right order new_tup.insert(1, vm.ctx.new_str(sub.clone())); } else { - new_tup.push(vm.ctx.new_str("".to_string())); - new_tup.push(vm.ctx.new_str("".to_string())); + new_tup.push(vm.ctx.new_str("".to_owned())); + new_tup.push(vm.ctx.new_str("".to_owned())); new_tup.push(vm.ctx.new_str(value.clone())); } vm.ctx.new_tuple(new_tup) @@ -1001,9 +1002,8 @@ impl PyString { if rep_str.len() == 1 { Ok(rep_str) } else { - Err(vm.new_type_error( - "The fill character must be exactly one character long".to_string(), - )) + Err(vm + .new_type_error("The fill character must be exactly one character long".to_owned())) } } @@ -1381,20 +1381,20 @@ fn do_cformat_specifier( match objint::get_value(&obj).to_u32().and_then(char::from_u32) { Some(value) => Ok(value.to_string()), None => { - Err(vm.new_overflow_error("%c arg not in range(0x110000)".to_string())) + Err(vm.new_overflow_error("%c arg not in range(0x110000)".to_owned())) } } } else if objtype::isinstance(&obj, &vm.ctx.str_type()) { 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())) + Err(vm.new_type_error("%c requires int or char".to_owned())) } else { Ok(s.chars().next().unwrap().to_string()) } } else { // TODO re-arrange this block so this error is only created once - Err(vm.new_type_error("%c requires int or char".to_string())) + Err(vm.new_type_error("%c requires int or char".to_owned())) } }?; format_spec.precision = Some(CFormatQuantity::Amount(1)); @@ -1415,7 +1415,7 @@ fn try_update_quantity_from_tuple( Some(width_obj) => { tuple_index += 1; if !objtype::isinstance(&width_obj, &vm.ctx.int_type()) { - Err(vm.new_type_error("* wants int".to_string())) + Err(vm.new_type_error("* wants int".to_owned())) } else { // TODO: handle errors when truncating BigInt to usize *q = Some(CFormatQuantity::Amount( @@ -1424,9 +1424,7 @@ fn try_update_quantity_from_tuple( Ok(tuple_index) } } - None => { - Err(vm.new_type_error("not enough arguments for format string".to_string())) - } + None => Err(vm.new_type_error("not enough arguments for format string".to_owned())), } } _ => Ok(tuple_index), @@ -1456,7 +1454,7 @@ pub fn do_cformat_string( let values = if mapping_required { if !objtype::isinstance(&values_obj, &vm.ctx.dict_type()) { - return Err(vm.new_type_error("format requires a mapping".to_string())); + return Err(vm.new_type_error("format requires a mapping".to_owned())); } values_obj.clone() } else { @@ -1467,7 +1465,7 @@ pub fn do_cformat_string( && !objtype::isinstance(&values_obj, &vm.ctx.types.dict_type) { return Err(vm.new_type_error( - "not all arguments converted during string formatting".to_string(), + "not all arguments converted during string formatting".to_owned(), )); } @@ -1511,7 +1509,7 @@ pub fn do_cformat_string( let obj = match elements.next() { Some(obj) => Ok(obj), None => Err(vm.new_type_error( - "not enough arguments for format string".to_string(), + "not enough arguments for format string".to_owned(), )), }?; tuple_index += 1; @@ -1531,7 +1529,7 @@ pub fn do_cformat_string( && !objtype::isinstance(&values_obj, &vm.ctx.types.dict_type) { return Err( - vm.new_type_error("not all arguments converted during string formatting".to_string()) + vm.new_type_error("not all arguments converted during string formatting".to_owned()) ); } Ok(final_string) @@ -1568,7 +1566,7 @@ fn perform_format( let result = match arguments.args.get(auto_argument_index) { Some(argument) => call_object_format(vm, argument.clone(), &format_spec)?, None => { - return Err(vm.new_index_error("tuple index out of range".to_string())); + return Err(vm.new_index_error("tuple index out of range".to_owned())); } }; auto_argument_index += 1; @@ -1578,7 +1576,7 @@ fn perform_format( let result = match arguments.args.get(*index + 1) { Some(argument) => call_object_format(vm, argument.clone(), &format_spec)?, None => { - return Err(vm.new_index_error("tuple index out of range".to_string())); + return Err(vm.new_index_error("tuple index out of range".to_owned())); } }; clone_value(&result) @@ -1609,7 +1607,7 @@ fn perform_format_map( let result_string: String = match part { FormatPart::AutoSpec(_) | FormatPart::IndexSpec(_, _) => { return Err( - vm.new_value_error("Format string contains positional fields".to_string()) + vm.new_value_error("Format string contains positional fields".to_owned()) ); } FormatPart::KeywordSpec(keyword, format_spec) => { diff --git a/vm/src/obj/objsuper.rs b/vm/src/obj/objsuper.rs index ba8b596645..c47c64057c 100644 --- a/vm/src/obj/objsuper.rs +++ b/vm/src/obj/objsuper.rs @@ -39,7 +39,7 @@ impl PySuper { let class_type_str = if let Ok(type_class) = self.typ.clone().downcast::() { type_class.name.clone() } else { - "NONE".to_string() + "NONE".to_owned() }; match self.obj_type.clone().downcast::() { Ok(obj_class_typ) => format!( @@ -123,7 +123,7 @@ impl PySuper { } } else { return Err(vm.new_type_error( - "super must be called with 1 argument or from inside class method".to_string(), + "super must be called with 1 argument or from inside class method".to_owned(), )); } }; @@ -137,7 +137,7 @@ impl PySuper { }; if !is_subclass { return Err(vm.new_type_error( - "super(type, obj): obj must be an instance or subtype of type".to_string(), + "super(type, obj): obj must be an instance or subtype of type".to_owned(), )); } PyClassRef::try_from_object(vm, py_obj.clone())? diff --git a/vm/src/obj/objtuple.rs b/vm/src/obj/objtuple.rs index 154251f032..27be3b3607 100644 --- a/vm/src/obj/objtuple.rs +++ b/vm/src/obj/objtuple.rs @@ -185,7 +185,7 @@ impl PyTuple { format!("({})", str_parts.join(", ")) } } else { - "(...)".to_string() + "(...)".to_owned() }; Ok(s) } @@ -215,7 +215,7 @@ impl PyTuple { return Ok(index); } } - Err(vm.new_value_error("tuple.index(x): x not in tuple".to_string())) + Err(vm.new_value_error("tuple.index(x): x not in tuple".to_owned())) } #[pymethod(name = "__contains__")] diff --git a/vm/src/obj/objtype.rs b/vm/src/obj/objtype.rs index 1e61c6e4db..e7465e6ccf 100644 --- a/vm/src/obj/objtype.rs +++ b/vm/src/obj/objtype.rs @@ -87,7 +87,7 @@ impl PyClassRef { } fn _set_mro(self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - Err(vm.new_attribute_error("read-only attribute".to_string())) + Err(vm.new_attribute_error("read-only attribute".to_owned())) } #[pyproperty(magic)] @@ -261,7 +261,7 @@ impl PyClassRef { if args.args.len() != 3 { return Err(vm.new_type_error(if is_type_type { - "type() takes 1 or 3 arguments".to_string() + "type() takes 1 or 3 arguments".to_owned() } else { format!( "type.__new__() takes exactly 3 arguments ({} given)", @@ -322,7 +322,7 @@ impl PyClassRef { let init_method = init_method_or_err?; let res = vm.invoke(&init_method, args)?; if !res.is(&vm.get_none()) { - return Err(vm.new_type_error("__init__ must return None".to_string())); + return Err(vm.new_type_error("__init__ must return None".to_owned())); } } Ok(obj) @@ -408,7 +408,7 @@ fn type_dict_setter( vm: &VirtualMachine, ) -> PyResult<()> { Err(vm.new_not_implemented_error( - "Setting __dict__ attribute on a type isn't yet implemented".to_string(), + "Setting __dict__ attribute on a type isn't yet implemented".to_owned(), )) } diff --git a/vm/src/obj/objweakproxy.rs b/vm/src/obj/objweakproxy.rs index d4422868fe..d10f9fcc4a 100644 --- a/vm/src/obj/objweakproxy.rs +++ b/vm/src/obj/objweakproxy.rs @@ -43,7 +43,7 @@ impl PyWeakProxy { Some(obj) => vm.get_attribute(obj, attr_name), None => Err(vm.new_exception_msg( vm.ctx.exceptions.reference_error.clone(), - "weakly-referenced object no longer exists".to_string(), + "weakly-referenced object no longer exists".to_owned(), )), } } @@ -54,7 +54,7 @@ impl PyWeakProxy { Some(obj) => vm.set_attr(&obj, attr_name, value), None => Err(vm.new_exception_msg( vm.ctx.exceptions.reference_error.clone(), - "weakly-referenced object no longer exists".to_string(), + "weakly-referenced object no longer exists".to_owned(), )), } } diff --git a/vm/src/stdlib/binascii.rs b/vm/src/stdlib/binascii.rs index 782d902e0c..6b4469660d 100644 --- a/vm/src/stdlib/binascii.rs +++ b/vm/src/stdlib/binascii.rs @@ -25,7 +25,7 @@ impl TryFromObject for SerializedData { Ok(SerializedData::Ascii(a)) } else { Err(vm.new_value_error( - "string argument should contain only ASCII characters".to_string(), + "string argument should contain only ASCII characters".to_owned(), )) } } @@ -79,7 +79,7 @@ fn unhex_nibble(c: u8) -> Option { fn binascii_unhexlify(data: SerializedData, vm: &VirtualMachine) -> PyResult> { data.with_ref(|hex_bytes| { if hex_bytes.len() % 2 != 0 { - return Err(vm.new_value_error("Odd-length string".to_string())); + return Err(vm.new_value_error("Odd-length string".to_owned())); } let mut unhex = Vec::::with_capacity(hex_bytes.len() / 2); @@ -87,7 +87,7 @@ fn binascii_unhexlify(data: SerializedData, vm: &VirtualMachine) -> PyResult PyResul if let Ok(iterable) = PyIterable::::try_from_object(vm, fp) { build_reader(iterable, args, vm) } else { - Err(vm.new_type_error("argument 1 must be an iterator".to_string())) + Err(vm.new_type_error("argument 1 must be an iterator".to_owned())) } } diff --git a/vm/src/stdlib/functools.rs b/vm/src/stdlib/functools.rs index 283426b33c..a1164a71e8 100644 --- a/vm/src/stdlib/functools.rs +++ b/vm/src/stdlib/functools.rs @@ -28,7 +28,7 @@ fn functools_reduce( let exc_type = vm.ctx.exceptions.type_error.clone(); vm.new_exception_msg( exc_type, - "reduce() of empty sequence with no initial value".to_string(), + "reduce() of empty sequence with no initial value".to_owned(), ) } else { err diff --git a/vm/src/stdlib/hashlib.rs b/vm/src/stdlib/hashlib.rs index 5e4b493527..4b8f6b4122 100644 --- a/vm/src/stdlib/hashlib.rs +++ b/vm/src/stdlib/hashlib.rs @@ -158,11 +158,11 @@ fn sha3_512(data: OptionalArg, vm: &VirtualMachine) -> PyResult, vm: &VirtualMachine) -> PyResult { - Err(vm.new_not_implemented_error("shake256".to_string())) + Err(vm.new_not_implemented_error("shake256".to_owned())) } fn shake256(_data: OptionalArg, vm: &VirtualMachine) -> PyResult { - Err(vm.new_not_implemented_error("shake256".to_string())) + Err(vm.new_not_implemented_error("shake256".to_owned())) } fn blake2b(data: OptionalArg, vm: &VirtualMachine) -> PyResult { diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index f40e214755..ee4ec13d45 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -119,7 +119,7 @@ impl PyStringIORef { if buffer.is_some() { Ok(RefMut::map(buffer, |opt| opt.as_mut().unwrap())) } else { - Err(vm.new_value_error("I/O operation on closed file.".to_string())) + Err(vm.new_value_error("I/O operation on closed file.".to_owned())) } } @@ -129,7 +129,7 @@ impl PyStringIORef { match self.buffer(vm)?.write(bytes) { Some(value) => Ok(vm.ctx.new_int(value)), - None => Err(vm.new_type_error("Error Writing String".to_string())), + None => Err(vm.new_type_error("Error Writing String".to_owned())), } } @@ -137,7 +137,7 @@ impl PyStringIORef { fn getvalue(self, vm: &VirtualMachine) -> PyResult { match String::from_utf8(self.buffer(vm)?.getvalue()) { Ok(result) => Ok(vm.ctx.new_str(result)), - Err(_) => Err(vm.new_value_error("Error Retrieving Value".to_string())), + Err(_) => Err(vm.new_value_error("Error Retrieving Value".to_owned())), } } @@ -145,7 +145,7 @@ impl PyStringIORef { fn seek(self, offset: u64, vm: &VirtualMachine) -> PyResult { match self.buffer(vm)?.seek(offset) { Some(value) => Ok(vm.ctx.new_int(value)), - None => Err(vm.new_value_error("Error Performing Operation".to_string())), + None => Err(vm.new_value_error("Error Performing Operation".to_owned())), } } @@ -164,7 +164,7 @@ impl PyStringIORef { match String::from_utf8(data) { Ok(value) => Ok(vm.ctx.new_str(value)), - Err(_) => Err(vm.new_value_error("Error Retrieving Value".to_string())), + Err(_) => Err(vm.new_value_error("Error Retrieving Value".to_owned())), } } @@ -175,7 +175,7 @@ impl PyStringIORef { fn readline(self, vm: &VirtualMachine) -> PyResult { match self.buffer(vm)?.readline() { Some(line) => Ok(line), - None => Err(vm.new_value_error("Error Performing Operation".to_string())), + None => Err(vm.new_value_error("Error Performing Operation".to_owned())), } } @@ -237,7 +237,7 @@ impl PyBytesIORef { if buffer.is_some() { Ok(RefMut::map(buffer, |opt| opt.as_mut().unwrap())) } else { - Err(vm.new_value_error("I/O operation on closed file.".to_string())) + Err(vm.new_value_error("I/O operation on closed file.".to_owned())) } } @@ -245,7 +245,7 @@ impl PyBytesIORef { let mut buffer = self.buffer(vm)?; match data.with_ref(|b| buffer.write(b)) { Some(value) => Ok(value), - None => Err(vm.new_type_error("Error Writing Bytes".to_string())), + None => Err(vm.new_type_error("Error Writing Bytes".to_owned())), } } //Retrieves the entire bytes object value from the underlying buffer @@ -259,7 +259,7 @@ impl PyBytesIORef { fn read(self, bytes: OptionalOption, vm: &VirtualMachine) -> PyResult { match self.buffer(vm)?.read(byte_count(bytes)) { Some(value) => Ok(vm.ctx.new_bytes(value)), - None => Err(vm.new_value_error("Error Retrieving Value".to_string())), + None => Err(vm.new_value_error("Error Retrieving Value".to_owned())), } } @@ -267,7 +267,7 @@ impl PyBytesIORef { fn seek(self, offset: u64, vm: &VirtualMachine) -> PyResult { match self.buffer(vm)?.seek(offset) { Some(value) => Ok(vm.ctx.new_int(value)), - None => Err(vm.new_value_error("Error Performing Operation".to_string())), + None => Err(vm.new_value_error("Error Performing Operation".to_owned())), } } @@ -282,7 +282,7 @@ impl PyBytesIORef { fn readline(self, vm: &VirtualMachine) -> PyResult> { match self.buffer(vm)?.readline() { Some(line) => Ok(line.as_bytes().to_vec()), - None => Err(vm.new_value_error("Error Performing Operation".to_string())), + None => Err(vm.new_value_error("Error Performing Operation".to_owned())), } } @@ -383,7 +383,7 @@ fn io_base_checkclosed( if objbool::boolval(vm, vm.get_attribute(instance, "closed")?)? { let msg = msg .flat_option() - .unwrap_or_else(|| vm.new_str("I/O operation on closed file.".to_string())); + .unwrap_or_else(|| vm.new_str("I/O operation on closed file.".to_owned())); Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg])) } else { Ok(()) @@ -398,7 +398,7 @@ fn io_base_checkreadable( if !objbool::boolval(vm, vm.call_method(&instance, "readable", vec![])?)? { let msg = msg .flat_option() - .unwrap_or_else(|| vm.new_str("File or stream is not readable.".to_string())); + .unwrap_or_else(|| vm.new_str("File or stream is not readable.".to_owned())); Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg])) } else { Ok(()) @@ -413,7 +413,7 @@ fn io_base_checkwritable( if !objbool::boolval(vm, vm.call_method(&instance, "writable", vec![])?)? { let msg = msg .flat_option() - .unwrap_or_else(|| vm.new_str("File or stream is not writable.".to_string())); + .unwrap_or_else(|| vm.new_str("File or stream is not writable.".to_owned())); Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg])) } else { Ok(()) @@ -428,7 +428,7 @@ fn io_base_checkseekable( if !objbool::boolval(vm, vm.call_method(&instance, "seekable", vec![])?)? { let msg = msg .flat_option() - .unwrap_or_else(|| vm.new_str("File or stream is not seekable.".to_string())); + .unwrap_or_else(|| vm.new_str("File or stream is not seekable.".to_owned())); Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg])) } else { Ok(()) @@ -614,7 +614,7 @@ mod fileio { ) -> PyResult<()> { if !obj.readonly() { return Err(vm.new_type_error( - "readinto() argument must be read-write bytes-like object".to_string(), + "readinto() argument must be read-write bytes-like object".to_owned(), )); } @@ -632,7 +632,7 @@ mod fileio { value_mut.clear(); match f.read_to_end(value_mut) { Ok(_) => {} - Err(_) => return Err(vm.new_value_error("Error reading from Take".to_string())), + Err(_) => return Err(vm.new_value_error("Error reading from Take".to_owned())), } }; @@ -736,7 +736,7 @@ fn text_io_wrapper_read( if !objtype::isinstance(&raw, &buffered_reader_class) { // TODO: this should be io.UnsupportedOperation error which derives both from ValueError *and* OSError - return Err(vm.new_value_error("not readable".to_string())); + return Err(vm.new_value_error("not readable".to_owned())); } let bytes = vm.call_method( @@ -767,15 +767,15 @@ fn text_io_wrapper_write( if !objtype::isinstance(&raw, &buffered_writer_class) { // TODO: this should be io.UnsupportedOperation error which derives from ValueError and OSError - return Err(vm.new_value_error("not writable".to_string())); + return Err(vm.new_value_error("not writable".to_owned())); } let bytes = obj.as_str().to_string().into_bytes(); let len = vm.call_method(&raw, "write", vec![vm.ctx.new_bytes(bytes.clone())])?; - let len = objint::get_value(&len).to_usize().ok_or_else(|| { - vm.new_overflow_error("int to large to convert to Rust usize".to_string()) - })?; + let len = objint::get_value(&len) + .to_usize() + .ok_or_else(|| vm.new_overflow_error("int to large to convert to Rust usize".to_owned()))?; // returns the count of unicode code points written let len = from_utf8(&bytes[..len]) @@ -795,7 +795,7 @@ fn text_io_wrapper_readline( if !objtype::isinstance(&raw, &buffered_reader_class) { // TODO: this should be io.UnsupportedOperation error which derives both from ValueError *and* OSError - return Err(vm.new_value_error("not readable".to_string())); + return Err(vm.new_value_error("not readable".to_owned())); } let bytes = vm.call_method( @@ -833,7 +833,7 @@ fn split_mode_string(mode_string: &str) -> Result<(String, String), String> { // no duplicates allowed return Err(format!("invalid mode: '{}'", mode_string)); } else { - return Err("can't have text and binary mode at once".to_string()); + return Err("can't have text and binary mode at once".to_owned()); } } typ = ch; @@ -845,7 +845,7 @@ fn split_mode_string(mode_string: &str) -> Result<(String, String), String> { return Err(format!("invalid mode: '{}'", mode_string)); } else { return Err( - "must have exactly one of create/read/write/append mode".to_string() + "must have exactly one of create/read/write/append mode".to_owned() ); } } @@ -896,7 +896,7 @@ pub fn io_open(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { let file_io_class = vm.get_attribute(io_module.clone(), "FileIO").map_err(|_| { // TODO: UnsupportedOperation here vm.new_os_error( - "Couldn't get FileIO, io.open likely isn't supported on your platform".to_string(), + "Couldn't get FileIO, io.open likely isn't supported on your platform".to_owned(), ) })?; let file_io_obj = vm.invoke( @@ -1084,15 +1084,15 @@ mod tests { fn test_invalid_mode() { assert_eq!( split_mode_string("rbsss"), - Err("invalid mode: 'rbsss'".to_string()) + Err("invalid mode: 'rbsss'".to_owned()) ); assert_eq!( split_mode_string("rrb"), - Err("invalid mode: 'rrb'".to_string()) + Err("invalid mode: 'rrb'".to_owned()) ); assert_eq!( split_mode_string("rbb"), - Err("invalid mode: 'rbb'".to_string()) + Err("invalid mode: 'rbb'".to_owned()) ); } @@ -1125,7 +1125,7 @@ mod tests { fn test_text_and_binary_at_once() { assert_eq!( split_mode_string("rbt"), - Err("can't have text and binary mode at once".to_string()) + Err("can't have text and binary mode at once".to_owned()) ); } @@ -1133,7 +1133,7 @@ mod tests { fn test_exactly_one_mode() { assert_eq!( split_mode_string("rwb"), - Err("must have exactly one of create/read/write/append mode".to_string()) + Err("must have exactly one of create/read/write/append mode".to_owned()) ); } @@ -1141,7 +1141,7 @@ mod tests { fn test_at_most_one_plus() { assert_eq!( split_mode_string("a++"), - Err("invalid mode: 'a++'".to_string()) + Err("invalid mode: 'a++'".to_owned()) ); } diff --git a/vm/src/stdlib/itertools.rs b/vm/src/stdlib/itertools.rs index e2688b0639..79253a36d9 100644 --- a/vm/src/stdlib/itertools.rs +++ b/vm/src/stdlib/itertools.rs @@ -528,7 +528,7 @@ impl PyItertoolsIslice { let start = if !start.is(&vm.get_none()) { pyobject_to_opt_usize(start, &vm).ok_or_else(|| { vm.new_value_error( - "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.".to_string(), + "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.".to_owned(), ) })? } else { @@ -538,7 +538,7 @@ impl PyItertoolsIslice { let step = if !step.is(&vm.get_none()) { pyobject_to_opt_usize(step, &vm).ok_or_else(|| { vm.new_value_error( - "Step for islice() must be a positive integer or None.".to_string(), + "Step for islice() must be a positive integer or None.".to_owned(), ) })? } else { @@ -961,7 +961,7 @@ impl PyItertoolsCombinations { let r = r.as_bigint(); if r.is_negative() { - return Err(vm.new_value_error("r must be non-negative".to_string())); + return Err(vm.new_value_error("r must be non-negative".to_owned())); } let r = r.to_usize().unwrap(); @@ -1060,7 +1060,7 @@ impl PyItertoolsCombinationsWithReplacement { let r = r.as_bigint(); if r.is_negative() { - return Err(vm.new_value_error("r must be non-negative".to_string())); + return Err(vm.new_value_error("r must be non-negative".to_owned())); } let r = r.to_usize().unwrap(); @@ -1161,11 +1161,11 @@ impl PyItertoolsPermutations { Some(r) => { let val = r .payload::() - .ok_or_else(|| vm.new_type_error("Expected int as r".to_string()))? + .ok_or_else(|| vm.new_type_error("Expected int as r".to_owned()))? .as_bigint(); if val.is_negative() { - return Err(vm.new_value_error("r must be non-negative".to_string())); + return Err(vm.new_value_error("r must be non-negative".to_owned())); } val.to_usize().unwrap() } diff --git a/vm/src/stdlib/math.rs b/vm/src/stdlib/math.rs index e5e27e446b..608b968a14 100644 --- a/vm/src/stdlib/math.rs +++ b/vm/src/stdlib/math.rs @@ -72,7 +72,7 @@ fn math_isclose(args: IsCloseArgs, vm: &VirtualMachine) -> PyResult { }; if rel_tol < 0.0 || abs_tol < 0.0 { - return Err(vm.new_value_error("tolerances must be non-negative".to_string())); + return Err(vm.new_value_error("tolerances must be non-negative".to_owned())); } if a == b { @@ -273,7 +273,7 @@ fn math_gcd(a: PyIntRef, b: PyIntRef, _vm: &VirtualMachine) -> BigInt { fn math_factorial(value: PyIntRef, vm: &VirtualMachine) -> PyResult { let value = value.as_bigint(); if *value < BigInt::zero() { - return Err(vm.new_value_error("factorial() not defined for negative values".to_string())); + return Err(vm.new_value_error("factorial() not defined for negative values".to_owned())); } else if *value <= BigInt::one() { return Ok(BigInt::from(1u64)); } @@ -306,7 +306,7 @@ fn math_nextafter(x: IntoPyFloat, y: IntoPyFloat) -> PyResult { #[cfg(target_arch = "wasm32")] fn math_nextafter(x: IntoPyFloat, y: IntoPyFloat, vm: &VirtualMachine) -> PyResult { - Err(vm.new_not_implemented_error("not implemented for this platform".to_string())) + Err(vm.new_not_implemented_error("not implemented for this platform".to_owned())) } fn fmod(x: f64, y: f64) -> f64 { @@ -324,7 +324,7 @@ fn math_fmod(x: IntoPyFloat, y: IntoPyFloat, vm: &VirtualMachine) -> PyResult PyResu return Ok(std::f64::NAN); } if y.is_infinite() { - return Err(vm.new_value_error("math domain error".to_string())); + return Err(vm.new_value_error("math domain error".to_owned())); } Ok(x) } diff --git a/vm/src/stdlib/mod.rs b/vm/src/stdlib/mod.rs index 52ae1a2c9d..6baf8813f4 100644 --- a/vm/src/stdlib/mod.rs +++ b/vm/src/stdlib/mod.rs @@ -62,65 +62,65 @@ pub type StdlibInitFunc = Box PyObjectRef>; pub fn get_module_inits() -> HashMap { #[allow(unused_mut)] let mut modules = hashmap! { - "array".to_string() => Box::new(array::make_module) as StdlibInitFunc, - "binascii".to_string() => Box::new(binascii::make_module), - "dis".to_string() => Box::new(dis::make_module), - "_collections".to_string() => Box::new(collections::make_module), - "_csv".to_string() => Box::new(csv::make_module), - "_functools".to_string() => Box::new(functools::make_module), - "errno".to_string() => Box::new(errno::make_module), - "hashlib".to_string() => Box::new(hashlib::make_module), - "itertools".to_string() => Box::new(itertools::make_module), - "_io".to_string() => Box::new(io::make_module), - "json".to_string() => Box::new(json::make_module), - "marshal".to_string() => Box::new(marshal::make_module), - "math".to_string() => Box::new(math::make_module), - "_operator".to_string() => Box::new(operator::make_module), - "platform".to_string() => Box::new(platform::make_module), - "regex_crate".to_string() => Box::new(re::make_module), - "_random".to_string() => Box::new(random::make_module), - "_string".to_string() => Box::new(string::make_module), - "struct".to_string() => Box::new(pystruct::make_module), - "_thread".to_string() => Box::new(thread::make_module), - "time".to_string() => Box::new(time_module::make_module), - "_weakref".to_string() => Box::new(weakref::make_module), - "_imp".to_string() => Box::new(imp::make_module), - "unicodedata".to_string() => Box::new(unicodedata::make_module), - "_warnings".to_string() => Box::new(warnings::make_module), + "array".to_owned() => Box::new(array::make_module) as StdlibInitFunc, + "binascii".to_owned() => Box::new(binascii::make_module), + "dis".to_owned() => Box::new(dis::make_module), + "_collections".to_owned() => Box::new(collections::make_module), + "_csv".to_owned() => Box::new(csv::make_module), + "_functools".to_owned() => Box::new(functools::make_module), + "errno".to_owned() => Box::new(errno::make_module), + "hashlib".to_owned() => Box::new(hashlib::make_module), + "itertools".to_owned() => Box::new(itertools::make_module), + "_io".to_owned() => Box::new(io::make_module), + "json".to_owned() => Box::new(json::make_module), + "marshal".to_owned() => Box::new(marshal::make_module), + "math".to_owned() => Box::new(math::make_module), + "_operator".to_owned() => Box::new(operator::make_module), + "platform".to_owned() => Box::new(platform::make_module), + "regex_crate".to_owned() => Box::new(re::make_module), + "_random".to_owned() => Box::new(random::make_module), + "_string".to_owned() => Box::new(string::make_module), + "struct".to_owned() => Box::new(pystruct::make_module), + "_thread".to_owned() => Box::new(thread::make_module), + "time".to_owned() => Box::new(time_module::make_module), + "_weakref".to_owned() => Box::new(weakref::make_module), + "_imp".to_owned() => Box::new(imp::make_module), + "unicodedata".to_owned() => Box::new(unicodedata::make_module), + "_warnings".to_owned() => Box::new(warnings::make_module), }; // Insert parser related modules: #[cfg(feature = "rustpython-parser")] { modules.insert( - "_ast".to_string(), + "_ast".to_owned(), Box::new(ast::make_module) as StdlibInitFunc, ); - modules.insert("keyword".to_string(), Box::new(keyword::make_module)); - modules.insert("tokenize".to_string(), Box::new(tokenize::make_module)); + modules.insert("keyword".to_owned(), Box::new(keyword::make_module)); + modules.insert("tokenize".to_owned(), Box::new(tokenize::make_module)); } // Insert compiler related modules: #[cfg(feature = "rustpython-compiler")] { - modules.insert("symtable".to_string(), Box::new(symtable::make_module)); + modules.insert("symtable".to_owned(), Box::new(symtable::make_module)); } // disable some modules on WASM #[cfg(not(target_arch = "wasm32"))] { - modules.insert("_os".to_string(), Box::new(os::make_module)); - modules.insert("_socket".to_string(), Box::new(socket::make_module)); + modules.insert("_os".to_owned(), Box::new(os::make_module)); + modules.insert("_socket".to_owned(), Box::new(socket::make_module)); modules.insert( - "_multiprocessing".to_string(), + "_multiprocessing".to_owned(), Box::new(multiprocessing::make_module), ); - modules.insert("signal".to_string(), Box::new(signal::make_module)); - modules.insert("select".to_string(), Box::new(select::make_module)); - modules.insert("_subprocess".to_string(), Box::new(subprocess::make_module)); - modules.insert("zlib".to_string(), Box::new(zlib::make_module)); + modules.insert("signal".to_owned(), Box::new(signal::make_module)); + modules.insert("select".to_owned(), Box::new(select::make_module)); + modules.insert("_subprocess".to_owned(), Box::new(subprocess::make_module)); + modules.insert("zlib".to_owned(), Box::new(zlib::make_module)); modules.insert( - "faulthandler".to_string(), + "faulthandler".to_owned(), Box::new(faulthandler::make_module), ); } @@ -128,13 +128,13 @@ pub fn get_module_inits() -> HashMap { // Unix-only #[cfg(all(unix, not(any(target_os = "android", target_os = "redox"))))] { - modules.insert("pwd".to_string(), Box::new(pwd::make_module)); + modules.insert("pwd".to_owned(), Box::new(pwd::make_module)); } // Windows-only #[cfg(windows)] { - modules.insert("_winapi".to_string(), Box::new(winapi::make_module)); + modules.insert("_winapi".to_owned(), Box::new(winapi::make_module)); } modules diff --git a/vm/src/stdlib/operator.rs b/vm/src/stdlib/operator.rs index 103a49f4f0..11606cfe87 100644 --- a/vm/src/stdlib/operator.rs +++ b/vm/src/stdlib/operator.rs @@ -78,16 +78,15 @@ fn operator_compare_digest( (Either::A(a), Either::A(b)) => { if !a.as_str().is_ascii() || !b.as_str().is_ascii() { return Err(vm.new_type_error( - "comparing strings with non-ASCII characters is not supported".to_string(), + "comparing strings with non-ASCII characters is not supported".to_owned(), )); } timing_safe_cmp(a.as_str().as_bytes(), b.as_str().as_bytes()) } (Either::B(a), Either::B(b)) => a.with_ref(|a| b.with_ref(|b| timing_safe_cmp(a, b))), _ => { - return Err(vm.new_type_error( - "unsupported operand types(s) or combination of types".to_string(), - )) + return Err(vm + .new_type_error("unsupported operand types(s) or combination of types".to_owned())) } }; Ok(res) diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index 0c8056ec6b..a5b35ecacd 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -340,7 +340,7 @@ fn os_access(path: PyStringRef, mode: u8, vm: &VirtualMachine) -> PyResult } fn os_error(message: OptionalArg, vm: &VirtualMachine) -> PyResult { - let msg = message.map_or("".to_string(), |msg| msg.as_str().to_string()); + let msg = message.map_or("".to_owned(), |msg| msg.as_str().to_string()); Err(vm.new_os_error(msg)) } @@ -1150,7 +1150,7 @@ fn os_urandom(size: usize, vm: &VirtualMachine) -> PyResult> { Ok(()) => Ok(buf), Err(e) => match e.raw_os_error() { Some(errno) => Err(convert_io_error(vm, io::Error::from_raw_os_error(errno))), - None => Err(vm.new_os_error("Getting random failed".to_string())), + None => Err(vm.new_os_error("Getting random failed".to_owned())), }, } } @@ -1224,9 +1224,9 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { let ctx = &vm.ctx; let os_name = if cfg!(windows) { - "nt".to_string() + "nt".to_owned() } else { - "posix".to_string() + "posix".to_owned() }; let environ = _os_environ(vm); diff --git a/vm/src/stdlib/platform.rs b/vm/src/stdlib/platform.rs index 869e9bb914..26f4949273 100644 --- a/vm/src/stdlib/platform.rs +++ b/vm/src/stdlib/platform.rs @@ -15,7 +15,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { } fn platform_python_implementation(_vm: &VirtualMachine) -> String { - "RustPython".to_string() + "RustPython".to_owned() } fn platform_python_version(_vm: &VirtualMachine) -> String { diff --git a/vm/src/stdlib/pystruct.rs b/vm/src/stdlib/pystruct.rs index 7eec764f5c..34baea2987 100644 --- a/vm/src/stdlib/pystruct.rs +++ b/vm/src/stdlib/pystruct.rs @@ -252,7 +252,7 @@ fn struct_pack(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { ))) } } else { - Err(vm.new_type_error("First argument must be of str type".to_string())) + Err(vm.new_type_error("First argument must be of str type".to_owned())) } } } diff --git a/vm/src/stdlib/re.rs b/vm/src/stdlib/re.rs index a0a5141d48..9de904e414 100644 --- a/vm/src/stdlib/re.rs +++ b/vm/src/stdlib/re.rs @@ -266,7 +266,7 @@ fn do_split( fn make_regex(vm: &VirtualMachine, pattern: &str, flags: PyRegexFlags) -> PyResult { let unicode = if flags.unicode && flags.ascii { - return Err(vm.new_value_error("ASCII and UNICODE flags are incompatible".to_string())); + return Err(vm.new_value_error("ASCII and UNICODE flags are incompatible".to_owned())); } else { !flags.ascii }; diff --git a/vm/src/stdlib/select.rs b/vm/src/stdlib/select.rs index 836a172b95..0423ae43dc 100644 --- a/vm/src/stdlib/select.rs +++ b/vm/src/stdlib/select.rs @@ -56,7 +56,7 @@ impl TryFromObject for Selectable { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let fno = RawFd::try_from_object(vm, obj.clone()).or_else(|_| { let meth = vm.get_method_or_type_error(obj.clone(), "fileno", || { - "select arg must be an int or object with a fileno() method".to_string() + "select arg must be an int or object with a fileno() method".to_owned() })?; RawFd::try_from_object(vm, vm.invoke(&meth, vec![])?) })?; @@ -119,7 +119,7 @@ fn select_select( }); if let Some(timeout) = timeout { if timeout < 0.0 { - return Err(vm.new_value_error("timeout must be positive".to_string())); + return Err(vm.new_value_error("timeout must be positive".to_owned())); } } let deadline = timeout.map(|s| super::time_module::get_time() + s); diff --git a/vm/src/stdlib/signal.rs b/vm/src/stdlib/signal.rs index e266e3d0b5..62a388ac81 100644 --- a/vm/src/stdlib/signal.rs +++ b/vm/src/stdlib/signal.rs @@ -55,7 +55,7 @@ fn signal(signalnum: i32, handler: PyObjectRef, vm: &VirtualMachine) -> PyResult let old = unsafe { libc::signal(signalnum, sig_handler) }; if old == SIG_ERR { - return Err(vm.new_os_error("Failed to set signal".to_string())); + return Err(vm.new_os_error("Failed to set signal".to_owned())); } #[cfg(all(unix, not(target_os = "redox")))] { diff --git a/vm/src/stdlib/socket.rs b/vm/src/stdlib/socket.rs index 9ea6636529..220d01a8b4 100644 --- a/vm/src/stdlib/socket.rs +++ b/vm/src/stdlib/socket.rs @@ -332,7 +332,7 @@ impl PySocket { }, _ => { return Err( - vm.new_type_error("expected the value arg xor the optlen arg".to_string()) + vm.new_type_error("expected the value arg xor the optlen arg".to_owned()) ); } }; @@ -351,7 +351,7 @@ impl PySocket { c::SHUT_RDWR => Shutdown::Both, _ => { return Err( - vm.new_value_error("`how` must be SHUT_RD, SHUT_WR, or SHUT_RDWR".to_string()) + vm.new_value_error("`how` must be SHUT_RD, SHUT_WR, or SHUT_RDWR".to_owned()) ) } }; @@ -390,7 +390,7 @@ impl TryFromObject for Address { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let tuple = PyTupleRef::try_from_object(vm, obj)?; if tuple.as_slice().len() != 2 { - Err(vm.new_type_error("Address tuple should have only 2 values".to_string())) + Err(vm.new_type_error("Address tuple should have only 2 values".to_owned())) } else { let host = PyStringRef::try_from_object(vm, tuple.as_slice()[0].clone())?; let host = if host.as_str().is_empty() { @@ -434,12 +434,12 @@ fn socket_inet_aton(ip_string: PyStringRef, vm: &VirtualMachine) -> PyResult { .as_str() .parse::() .map(|ip_addr| vm.ctx.new_bytes(ip_addr.octets().to_vec())) - .map_err(|_| vm.new_os_error("illegal IP address string passed to inet_aton".to_string())) + .map_err(|_| vm.new_os_error("illegal IP address string passed to inet_aton".to_owned())) } fn socket_inet_ntoa(packed_ip: PyBytesRef, vm: &VirtualMachine) -> PyResult { if packed_ip.len() != 4 { - return Err(vm.new_os_error("packed IP wrong length for inet_ntoa".to_string())); + return Err(vm.new_os_error("packed IP wrong length for inet_ntoa".to_owned())); } let ip_num = BigEndian::read_u32(&packed_ip); Ok(vm.new_str(Ipv4Addr::from(ip_num).to_string())) @@ -545,7 +545,7 @@ where let error_type = vm.class("_socket", "gaierror"); Err(vm.new_exception_msg( error_type, - "nodename nor servname provided, or not known".to_string(), + "nodename nor servname provided, or not known".to_owned(), )) } else { Ok(sock_addrs.next().unwrap().into()) @@ -599,7 +599,7 @@ fn invalid_sock() -> Socket { fn convert_sock_error(vm: &VirtualMachine, err: io::Error) -> PyBaseExceptionRef { if err.kind() == io::ErrorKind::TimedOut { let socket_timeout = vm.class("_socket", "timeout"); - vm.new_exception_msg(socket_timeout, "Timed out".to_string()) + vm.new_exception_msg(socket_timeout, "Timed out".to_owned()) } else { convert_io_error(vm, err) } diff --git a/vm/src/stdlib/subprocess.rs b/vm/src/stdlib/subprocess.rs index b933ab14ce..57ddfc780b 100644 --- a/vm/src/stdlib/subprocess.rs +++ b/vm/src/stdlib/subprocess.rs @@ -55,7 +55,7 @@ impl IntoPyObject for subprocess::ExitStatus { subprocess::ExitStatus::Exited(status) => status as i32, subprocess::ExitStatus::Signaled(status) => -i32::from(status), subprocess::ExitStatus::Other(status) => status as i32, - _ => return Err(vm.new_os_error("Unknown exist status".to_string())), + _ => return Err(vm.new_os_error("Unknown exist status".to_owned())), }; Ok(vm.new_int(status)) } @@ -153,22 +153,22 @@ impl PopenRef { .map_err(|s| vm.new_os_error(format!("Could not start program: {}", s)))?; if timeout.is_none() { let timeout_expired = vm.try_class("_subprocess", "TimeoutExpired")?; - Err(vm.new_exception_msg(timeout_expired, "Timeout".to_string())) + Err(vm.new_exception_msg(timeout_expired, "Timeout".to_owned())) } else { Ok(()) } } fn stdin(self, vm: &VirtualMachine) -> PyResult { - convert_to_file_io(&self.process.borrow().stdin, "wb".to_string(), vm) + convert_to_file_io(&self.process.borrow().stdin, "wb".to_owned(), vm) } fn stdout(self, vm: &VirtualMachine) -> PyResult { - convert_to_file_io(&self.process.borrow().stdout, "rb".to_string(), vm) + convert_to_file_io(&self.process.borrow().stdout, "rb".to_owned(), vm) } fn stderr(self, vm: &VirtualMachine) -> PyResult { - convert_to_file_io(&self.process.borrow().stderr, "rb".to_string(), vm) + convert_to_file_io(&self.process.borrow().stderr, "rb".to_owned(), vm) } fn terminate(self, vm: &VirtualMachine) -> PyResult<()> { @@ -202,7 +202,7 @@ impl PopenRef { communicator.read().map_err(|err| { if err.error.kind() == ErrorKind::TimedOut { let timeout_expired = vm.try_class("_subprocess", "TimeoutExpired").unwrap(); - vm.new_exception_msg(timeout_expired, "Timeout".to_string()) + vm.new_exception_msg(timeout_expired, "Timeout".to_owned()) } else { convert_io_error(vm, err.error) } diff --git a/vm/src/stdlib/time_module.rs b/vm/src/stdlib/time_module.rs index fc9ce6b1e2..c51354a163 100644 --- a/vm/src/stdlib/time_module.rs +++ b/vm/src/stdlib/time_module.rs @@ -194,7 +194,7 @@ impl PyStructTime { } fn to_date_time(&self, vm: &VirtualMachine) -> PyResult { - let invalid = || vm.new_value_error("invalid struct_time parameter".to_string()); + let invalid = || vm.new_value_error("invalid struct_time parameter".to_owned()); macro_rules! field { ($field:ident) => { TryFromObject::try_from_object(vm, self.$field.clone())? @@ -225,7 +225,7 @@ impl TryFromObject for PyStructTime { let seq = vm.extract_elements::(&seq)?; if seq.len() != 9 { return Err( - vm.new_type_error("time.struct_time() takes a sequence of length 9".to_string()) + vm.new_type_error("time.struct_time() takes a sequence of length 9".to_owned()) ); } let mut i = seq.into_iter(); diff --git a/vm/src/stdlib/unicodedata.rs b/vm/src/stdlib/unicodedata.rs index 077b687a79..9507d337fb 100644 --- a/vm/src/stdlib/unicodedata.rs +++ b/vm/src/stdlib/unicodedata.rs @@ -84,7 +84,7 @@ impl PyUCD { fn extract_char(&self, character: PyStringRef, vm: &VirtualMachine) -> PyResult> { let c = character.as_str().chars().exactly_one().map_err(|_| { - vm.new_type_error("argument must be an unicode character, not str".to_string()) + vm.new_type_error("argument must be an unicode character, not str".to_owned()) })?; if self.check_age(c) { @@ -132,9 +132,7 @@ impl PyUCD { } match default { OptionalArg::Present(obj) => Ok(obj), - OptionalArg::Missing => { - Err(vm.new_value_error("character name not found!".to_string())) - } + OptionalArg::Missing => Err(vm.new_value_error("character name not found!".to_owned())), } } @@ -160,7 +158,7 @@ impl PyUCD { "NFKC" => text.nfkc().collect::(), "NFD" => text.nfd().collect::(), "NFKD" => text.nfkd().collect::(), - _ => return Err(vm.new_value_error("invalid normalization form".to_string())), + _ => return Err(vm.new_value_error("invalid normalization form".to_owned())), }; Ok(normalized_text) diff --git a/vm/src/sysmodule.rs b/vm/src/sysmodule.rs index 3570110c03..072fa59b88 100644 --- a/vm/src/sysmodule.rs +++ b/vm/src/sysmodule.rs @@ -35,7 +35,7 @@ fn executable(ctx: &PyContext) -> PyObjectRef { fn getframe(offset: OptionalArg, vm: &VirtualMachine) -> PyResult { let offset = offset.into_option().unwrap_or(0); if offset > vm.frames.borrow().len() - 1 { - return Err(vm.new_value_error("call stack is not deep enough".to_string())); + return Err(vm.new_value_error("call stack is not deep enough".to_owned())); } let idx = vm.frames.borrow().len() - offset - 1; let frame = &vm.frames.borrow()[idx]; @@ -108,21 +108,21 @@ fn sys_getsizeof(obj: PyObjectRef, _vm: &VirtualMachine) -> usize { fn sys_getfilesystemencoding(_vm: &VirtualMachine) -> String { // TODO: implement non-utf-8 mode. - "utf-8".to_string() + "utf-8".to_owned() } fn sys_getdefaultencoding(_vm: &VirtualMachine) -> String { - "utf-8".to_string() + "utf-8".to_owned() } #[cfg(not(windows))] fn sys_getfilesystemencodeerrors(_vm: &VirtualMachine) -> String { - "surrogateescape".to_string() + "surrogateescape".to_owned() } #[cfg(windows)] fn sys_getfilesystemencodeerrors(_vm: &VirtualMachine) -> String { - "surrogatepass".to_string() + "surrogatepass".to_owned() } fn sys_getprofile(vm: &VirtualMachine) -> PyObjectRef { @@ -190,7 +190,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_string()), + vm.ctx.new_str("RustPython".to_owned()), vm.ctx.new_str(version::get_git_identifier()), vm.ctx.new_str(version::get_git_revision()), ]) @@ -216,8 +216,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_string()), - "cache_tag" => ctx.new_str("rustpython-01".to_string()), + "name" => ctx.new_str("rustpython".to_owned()), + "cache_tag" => ctx.new_str("rustpython-01".to_owned()), }); let path = ctx.new_list( @@ -229,27 +229,27 @@ pub fn make_module(vm: &VirtualMachine, module: PyObjectRef, builtins: PyObjectR ); let platform = if cfg!(target_os = "linux") { - "linux".to_string() + "linux".to_owned() } else if cfg!(target_os = "macos") { - "darwin".to_string() + "darwin".to_owned() } else if cfg!(target_os = "windows") { - "win32".to_string() + "win32".to_owned() } else if cfg!(target_os = "android") { // Linux as well. see https://bugs.python.org/issue32637 - "linux".to_string() + "linux".to_owned() } else { - "unknown".to_string() + "unknown".to_owned() }; - let framework = "".to_string(); + let framework = "".to_owned(); // https://doc.rust-lang.org/reference/conditional-compilation.html#target_endian let bytorder = if cfg!(target_endian = "little") { - "little".to_string() + "little".to_owned() } else if cfg!(target_endian = "big") { - "big".to_string() + "big".to_owned() } else { - "unknown".to_string() + "unknown".to_owned() }; let copyright = "Copyright (c) 2019 RustPython Team"; @@ -324,8 +324,8 @@ setrecursionlimit() -- set the max recursion depth for the interpreter settrace() -- set the global debug tracing function "; let mut module_names: Vec = vm.stdlib_inits.borrow().keys().cloned().collect(); - module_names.push("sys".to_string()); - module_names.push("builtins".to_string()); + module_names.push("sys".to_owned()); + module_names.push("builtins".to_owned()); module_names.sort(); let builtin_module_names = ctx.new_tuple( module_names @@ -361,8 +361,8 @@ settrace() -- set the global debug tracing function "maxunicode" => ctx.new_int(0x0010_FFFF), "maxsize" => ctx.new_int(std::isize::MAX), "path" => path, - "ps1" => ctx.new_str(">>>>> ".to_string()), - "ps2" => ctx.new_str("..... ".to_string()), + "ps1" => ctx.new_str(">>>>> ".to_owned()), + "ps2" => ctx.new_str("..... ".to_owned()), "__doc__" => ctx.new_str(sys_doc.to_string()), "_getframe" => ctx.new_function(getframe), "modules" => modules.clone(), @@ -386,7 +386,7 @@ settrace() -- set the global debug tracing function "exec_prefix" => ctx.new_str(exec_prefix.to_string()), "base_exec_prefix" => ctx.new_str(base_exec_prefix.to_string()), "exit" => ctx.new_function(sys_exit), - "abiflags" => ctx.new_str("".to_string()), + "abiflags" => ctx.new_str("".to_owned()), }); modules.set_item("sys", module.clone(), vm).unwrap(); diff --git a/vm/src/version.rs b/vm/src/version.rs index 77ca12545e..c14f6c2943 100644 --- a/vm/src/version.rs +++ b/vm/src/version.rs @@ -59,7 +59,7 @@ pub fn get_build_info() -> String { format!( "{id}{sep}{revision}, {date:.20}, {time:.9}", id = if git_identifier.is_empty() { - "default".to_string() + "default".to_owned() } else { git_identifier }, diff --git a/vm/src/vm.rs b/vm/src/vm.rs index fa405e8073..7ea7215fbc 100644 --- a/vm/src/vm.rs +++ b/vm/src/vm.rs @@ -563,7 +563,7 @@ impl VirtualMachine { None => { let import_func = self .get_attribute(self.builtins.clone(), "__import__") - .map_err(|_| self.new_import_error("__import__ not found".to_string()))?; + .map_err(|_| self.new_import_error("__import__ not found".to_owned()))?; let (locals, globals) = if let Some(frame) = self.current_frame() { ( @@ -1213,7 +1213,7 @@ impl VirtualMachine { if let Some(hash_value) = hash_obj.payload_if_subclass::(self) { Ok(hash_value.hash(self)) } else { - Err(self.new_type_error("__hash__ method should return an integer".to_string())) + Err(self.new_type_error("__hash__ method should return an integer".to_owned())) } } diff --git a/wasm/lib/src/browser_module.rs b/wasm/lib/src/browser_module.rs index 8e7e169f8c..eefc39552c 100644 --- a/wasm/lib/src/browser_module.rs +++ b/wasm/lib/src/browser_module.rs @@ -328,7 +328,7 @@ fn browser_load_module(module: PyStringRef, path: PyStringRef, vm: &VirtualMachi .expect("that the vm is valid when the promise resolves"); let vm = &stored_vm.vm; let resp_text = text.as_string().unwrap(); - let res = import_file(vm, module.as_str(), "WEB".to_string(), resp_text); + let res = import_file(vm, module.as_str(), "WEB".to_owned(), resp_text); match res { Ok(_) => Ok(JsValue::null()), Err(err) => Err(convert::py_err_to_js_err(vm, &err)), @@ -370,7 +370,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { pub fn setup_browser_module(vm: &VirtualMachine) { vm.stdlib_inits .borrow_mut() - .insert("_browser".to_string(), Box::new(make_module)); + .insert("_browser".to_owned(), Box::new(make_module)); vm.frozen.borrow_mut().extend(py_compile_bytecode!( file = "src/browser.py", module_name = "browser", diff --git a/wasm/lib/src/js_module.rs b/wasm/lib/src/js_module.rs index f640b1d146..bd7e5250a9 100644 --- a/wasm/lib/src/js_module.rs +++ b/wasm/lib/src/js_module.rs @@ -99,7 +99,7 @@ impl PyJsValue { } else if proto.value.is_null() { Object::create(proto.value.unchecked_ref()) } else { - return Err(vm.new_value_error("prototype must be an Object or null".to_string())); + return Err(vm.new_value_error("prototype must be an Object or null".to_owned())); } } else { Object::new() @@ -140,7 +140,7 @@ impl PyJsValue { let func = self .value .dyn_ref::() - .ok_or_else(|| vm.new_type_error("JS value is not callable".to_string()))?; + .ok_or_else(|| vm.new_type_error("JS value is not callable".to_owned()))?; let this = opts .this .map(|this| this.value.clone()) @@ -164,7 +164,7 @@ impl PyJsValue { let ctor = self .value .dyn_ref::() - .ok_or_else(|| vm.new_type_error("JS value is not callable".to_string()))?; + .ok_or_else(|| vm.new_type_error("JS value is not callable".to_owned()))?; let proto = opts .prototype .as_ref() @@ -256,5 +256,5 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { pub fn setup_js_module(vm: &VirtualMachine) { vm.stdlib_inits .borrow_mut() - .insert("_js".to_string(), Box::new(make_module)); + .insert("_js".to_owned(), Box::new(make_module)); } diff --git a/wasm/lib/src/vm_class.rs b/wasm/lib/src/vm_class.rs index 8565884bd3..b7cf90d2ad 100644 --- a/wasm/lib/src/vm_class.rs +++ b/wasm/lib/src/vm_class.rs @@ -39,7 +39,7 @@ impl StoredVirtualMachine { js_module::setup_js_module(&vm); if inject_browser_module { vm.stdlib_inits.borrow_mut().insert( - "_window".to_string(), + "_window".to_owned(), Box::new(|vm| { py_module!(vm, "_window", { "window" => js_module::PyJsValue::new(wasm_builtins::window()).into_ref(vm), @@ -289,7 +289,7 @@ impl WASMVirtualMachine { |StoredVirtualMachine { ref vm, ref scope, .. }| { - let source_path = source_path.unwrap_or_else(|| "".to_string()); + let source_path = source_path.unwrap_or_else(|| "".to_owned()); let code = vm.compile(source, mode, source_path); let code = code.map_err(|err| { let js_err = SyntaxError::new(&format!("Error parsing Python code: {}", err)); From 7d0d313aa573bada831fa3d8181df3fc34212393 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Wed, 5 Feb 2020 22:03:36 +0900 Subject: [PATCH 2/2] &str::to_string -> &str::to_owned for variables --- compiler/src/compile.rs | 36 +++++++++++----------- compiler/src/symboltable.rs | 6 ++-- derive/src/compile_bytecode.rs | 2 +- derive/src/pyclass.rs | 2 +- parser/src/fstring.rs | 2 +- src/main.rs | 6 ++-- vm/src/builtins.rs | 4 +-- vm/src/dictdatatype.rs | 6 ++-- vm/src/eval.rs | 2 +- vm/src/exceptions.rs | 2 +- vm/src/format.rs | 4 +-- vm/src/frame.rs | 6 ++-- vm/src/import.rs | 2 +- vm/src/obj/objbool.rs | 2 +- vm/src/obj/objbyteinner.rs | 2 +- vm/src/obj/objdict.rs | 2 +- vm/src/obj/objint.rs | 2 +- vm/src/obj/objlist.rs | 2 +- vm/src/obj/objstr.rs | 55 +++++++++++++++++----------------- vm/src/obj/objsuper.rs | 4 +-- vm/src/obj/objtype.rs | 10 +++---- vm/src/py_serde.rs | 2 +- vm/src/stdlib/ast.rs | 32 +++++++++----------- vm/src/stdlib/csv.rs | 4 +-- vm/src/stdlib/dis.rs | 2 +- vm/src/stdlib/hashlib.rs | 2 +- vm/src/stdlib/io.rs | 10 +++---- vm/src/stdlib/itertools.rs | 2 +- vm/src/stdlib/keyword.rs | 2 +- vm/src/stdlib/os.rs | 8 ++--- vm/src/stdlib/re.rs | 2 +- vm/src/stdlib/subprocess.rs | 2 +- vm/src/stdlib/symtable.rs | 4 +-- vm/src/stdlib/zlib.rs | 2 +- vm/src/sysmodule.rs | 12 ++++---- vm/src/version.rs | 8 ++--- vm/src/vm.rs | 4 +-- 37 files changed, 126 insertions(+), 131 deletions(-) diff --git a/compiler/src/compile.rs b/compiler/src/compile.rs index 8ea3bc5207..dbe938fd16 100644 --- a/compiler/src/compile.rs +++ b/compiler/src/compile.rs @@ -290,7 +290,7 @@ impl Compiler { fn load_name(&mut self, name: &str) { let scope = self.scope_for_name(name); self.emit(Instruction::LoadName { - name: name.to_string(), + name: name.to_owned(), scope, }); } @@ -298,7 +298,7 @@ impl Compiler { fn store_name(&mut self, name: &str) { let scope = self.scope_for_name(name); self.emit(Instruction::StoreName { - name: name.to_string(), + name: name.to_owned(), scope, }); } @@ -359,7 +359,7 @@ impl Compiler { for name in names { // import symbol from module: self.emit(Instruction::ImportFrom { - name: name.symbol.to_string(), + name: name.symbol.to_owned(), }); // Store module under proper name: @@ -619,13 +619,13 @@ impl Compiler { match &expression.node { ast::ExpressionType::Identifier { name } => { self.emit(Instruction::DeleteName { - name: name.to_string(), + name: name.to_owned(), }); } ast::ExpressionType::Attribute { value, name } => { self.compile_expression(value)?; self.emit(Instruction::DeleteAttr { - name: name.to_string(), + name: name.to_owned(), }); } ast::ExpressionType::Subscript { a, b } => { @@ -701,7 +701,7 @@ impl Compiler { compile_varargs(&args.kwarg), self.source_path.clone().unwrap(), line_number, - name.to_string(), + name.to_owned(), )); self.enter_scope(); @@ -909,7 +909,7 @@ impl Compiler { if let Some(annotation) = &arg.annotation { self.emit(Instruction::LoadConst { value: bytecode::Constant::String { - value: arg.arg.to_string(), + value: arg.arg.to_owned(), }, }); self.compile_expression(&annotation)?; @@ -982,7 +982,7 @@ impl Compiler { Varargs::None, self.source_path.clone().unwrap(), line_number, - name.to_string(), + name.to_owned(), )); self.enter_scope(); @@ -1022,7 +1022,7 @@ impl Compiler { }); self.emit(Instruction::LoadConst { value: bytecode::Constant::String { - value: name.to_string(), + value: name.to_owned(), }, }); @@ -1044,7 +1044,7 @@ impl Compiler { for keyword in keywords { if let Some(name) = &keyword.name { kwarg_names.push(bytecode::Constant::String { - value: name.to_string(), + value: name.to_owned(), }); } else { // This means **kwargs! @@ -1308,7 +1308,7 @@ impl Compiler { }); self.emit(Instruction::LoadConst { value: bytecode::Constant::String { - value: name.to_string(), + value: name.to_owned(), }, }); self.emit(Instruction::StoreSubscript); @@ -1332,7 +1332,7 @@ impl Compiler { ast::ExpressionType::Attribute { value, name } => { self.compile_expression(value)?; self.emit(Instruction::StoreAttr { - name: name.to_string(), + name: name.to_owned(), }); } ast::ExpressionType::List { elements } | ast::ExpressionType::Tuple { elements } => { @@ -1605,7 +1605,7 @@ impl Compiler { Attribute { value, name } => { self.compile_expression(value)?; self.emit(Instruction::LoadAttr { - name: name.to_string(), + name: name.to_owned(), }); } Compare { vals, ops } => { @@ -1795,7 +1795,7 @@ impl Compiler { if let Some(name) = &keyword.name { self.emit(Instruction::LoadConst { value: bytecode::Constant::String { - value: name.to_string(), + value: name.to_owned(), }, }); self.compile_expression(&keyword.value)?; @@ -1858,7 +1858,7 @@ impl Compiler { for keyword in keywords { if let Some(name) = &keyword.name { kwarg_names.push(bytecode::Constant::String { - value: name.to_string(), + value: name.to_owned(), }); } else { // This means **kwargs! @@ -1927,7 +1927,7 @@ impl Compiler { ast::ComprehensionKind::Set { .. } => "", ast::ComprehensionKind::Dict { .. } => "", } - .to_string(); + .to_owned(); let line_number = self.get_source_line_number(); // Create magnificent function : @@ -2099,7 +2099,7 @@ impl Compiler { ast::StringGroup::Constant { value } => { self.emit(Instruction::LoadConst { value: bytecode::Constant::String { - value: value.to_string(), + value: value.to_owned(), }, }); } @@ -2266,7 +2266,7 @@ mod tests { let mut compiler: Compiler = Default::default(); compiler.source_path = Some("source_path".to_owned()); compiler.push_new_code_object("".to_owned()); - let ast = parser::parse_program(&source.to_string()).unwrap(); + let ast = parser::parse_program(source).unwrap(); let symbol_scope = make_symbol_table(&ast).unwrap(); compiler.compile_program(&ast, symbol_scope).unwrap(); compiler.pop_code_object() diff --git a/compiler/src/symboltable.rs b/compiler/src/symboltable.rs index c3e2099bcf..d08aa4f2e3 100644 --- a/compiler/src/symboltable.rs +++ b/compiler/src/symboltable.rs @@ -105,7 +105,7 @@ pub struct Symbol { impl Symbol { fn new(name: &str) -> Self { Symbol { - name: name.to_string(), + name: name.to_owned(), // table, scope: SymbolScope::Unknown, is_param: false, @@ -304,7 +304,7 @@ impl SymbolTableBuilder { } fn enter_scope(&mut self, name: &str, typ: SymbolTableType, line_number: usize) { - let table = SymbolTable::new(name.to_string(), typ, line_number); + let table = SymbolTable::new(name.to_owned(), typ, line_number); self.tables.push(table); } @@ -793,7 +793,7 @@ impl SymbolTableBuilder { // Insert symbol when required: if !containing { let symbol = Symbol::new(name); - table.symbols.insert(name.to_string(), symbol); + table.symbols.insert(name.to_owned(), symbol); } // Set proper flags on symbol: diff --git a/derive/src/compile_bytecode.rs b/derive/src/compile_bytecode.rs index 01f5226d60..1206469fa4 100644 --- a/derive/src/compile_bytecode.rs +++ b/derive/src/compile_bytecode.rs @@ -128,7 +128,7 @@ impl CompilationSource { let module_name = if is_init { parent.clone() } else if parent.is_empty() { - stem.to_string() + stem.to_owned() } else { format!("{}.{}", parent, stem) }; diff --git a/derive/src/pyclass.rs b/derive/src/pyclass.rs index fb6ac4b04e..006bd4e60a 100644 --- a/derive/src/pyclass.rs +++ b/derive/src/pyclass.rs @@ -620,7 +620,7 @@ fn generate_class_def( let meta = attr.parse_meta().expect("expected doc attr to be a meta"); if let Meta::NameValue(name_value) = meta { if let Lit::Str(s) = name_value.lit { - let val = s.value().trim().to_string(); + let val = s.value().trim().to_owned(); match doc { Some(ref mut doc) => doc.push(val), None => doc = Some(vec![val]), diff --git a/parser/src/fstring.rs b/parser/src/fstring.rs index 7ecd8a1239..5ca92c484b 100644 --- a/parser/src/fstring.rs +++ b/parser/src/fstring.rs @@ -83,7 +83,7 @@ impl<'a> FStringParser<'a> { })) } else { spec = Some(Box::new(Constant { - value: spec_expression.to_string(), + value: spec_expression.to_owned(), })) } } diff --git a/src/main.rs b/src/main.rs index 9253e7f65f..4b82077b31 100644 --- a/src/main.rs +++ b/src/main.rs @@ -364,7 +364,7 @@ fn run_rustpython(vm: &VirtualMachine, matches: &ArgMatches) -> PyResult<()> { // Figure out if a -c option was given: if let Some(command) = matches.value_of("c") { - run_command(&vm, scope, command.to_string())?; + run_command(&vm, scope, command.to_owned())?; } else if let Some(module) = matches.value_of("m") { run_module(&vm, module)?; } else if let Some(filename) = matches.value_of("script") { @@ -426,13 +426,13 @@ fn run_script(vm: &VirtualMachine, scope: Scope, script_file: &str) -> PyResult< process::exit(1); }; - let dir = file_path.parent().unwrap().to_str().unwrap().to_string(); + let dir = file_path.parent().unwrap().to_str().unwrap().to_owned(); let sys_path = vm.get_attribute(vm.sys_module.clone(), "path").unwrap(); vm.call_method(&sys_path, "insert", vec![vm.new_int(0), vm.new_str(dir)])?; match util::read_file(&file_path) { Ok(source) => { - _run_string(vm, scope, &source, file_path.to_str().unwrap().to_string())?; + _run_string(vm, scope, &source, file_path.to_str().unwrap().to_owned())?; } Err(err) => { error!( diff --git a/vm/src/builtins.rs b/vm/src/builtins.rs index 3f545a79ef..72891812cf 100644 --- a/vm/src/builtins.rs +++ b/vm/src/builtins.rs @@ -146,7 +146,7 @@ fn builtin_compile(args: CompileArgs, vm: &VirtualMachine) -> PyResult { .parse::() .map_err(|err| vm.new_value_error(err.to_string()))?; - vm.compile(&source, mode, args.filename.as_str().to_string()) + vm.compile(&source, mode, args.filename.as_str().to_owned()) .map(|o| o.into_object()) .map_err(|err| vm.new_syntax_error(&err)) } @@ -920,7 +920,7 @@ pub fn builtin_build_class_( vm: &VirtualMachine, ) -> PyResult { let name = qualified_name.as_str().split('.').next_back().unwrap(); - let name_obj = vm.new_str(name.to_string()); + let name_obj = vm.new_str(name.to_owned()); let mut metaclass = if let Some(metaclass) = kwargs.pop_kwarg("metaclass") { PyClassRef::try_from_object(vm, metaclass)? diff --git a/vm/src/dictdatatype.rs b/vm/src/dictdatatype.rs index d7dcb8fc34..5541f17583 100644 --- a/vm/src/dictdatatype.rs +++ b/vm/src/dictdatatype.rs @@ -344,7 +344,7 @@ impl DictKey for &PyObjectRef { impl DictKey for &str { fn do_hash(self, _vm: &VirtualMachine) -> PyResult { // follow a similar route as the hashing of PyStringRef - let raw_hash = pyhash::hash_value(&self.to_string()).to_bigint().unwrap(); + let raw_hash = pyhash::hash_value(&self.to_owned()).to_bigint().unwrap(); let raw_hash = pyhash::hash_bigint(&raw_hash); let mut hasher = DefaultHasher::new(); raw_hash.hash(&mut hasher); @@ -362,7 +362,7 @@ impl DictKey for &str { Ok(py_str_value.as_str() == self) } else { // Fall back to PyString implementation. - let s = vm.new_str(self.to_string()); + let s = vm.new_str(self.to_owned()); s.do_eq(vm, other_key) } } @@ -438,7 +438,7 @@ mod tests { fn check_hash_equivalence(text: &str) { let vm: VirtualMachine = Default::default(); let value1 = text; - let value2 = vm.new_str(value1.to_string()); + let value2 = vm.new_str(value1.to_owned()); let hash1 = value1.do_hash(&vm).expect("Hash should not fail."); let hash2 = value2.do_hash(&vm).expect("Hash should not fail."); diff --git a/vm/src/eval.rs b/vm/src/eval.rs index 3d998f8b40..68255302bd 100644 --- a/vm/src/eval.rs +++ b/vm/src/eval.rs @@ -4,7 +4,7 @@ use crate::vm::VirtualMachine; use rustpython_compiler::compile; pub fn eval(vm: &VirtualMachine, source: &str, scope: Scope, source_path: &str) -> PyResult { - match vm.compile(source, compile::Mode::Eval, source_path.to_string()) { + match vm.compile(source, compile::Mode::Eval, source_path.to_owned()) { Ok(bytecode) => { debug!("Code object: {:?}", bytecode); vm.run_code_obj(bytecode, scope) diff --git a/vm/src/exceptions.rs b/vm/src/exceptions.rs index 208272bb19..135cb0d6f4 100644 --- a/vm/src/exceptions.rs +++ b/vm/src/exceptions.rs @@ -225,7 +225,7 @@ fn print_source_line(output: &mut W, filename: &str, lineno: usize) -> /// Print exception occurrence location from traceback element fn write_traceback_entry(output: &mut W, tb_entry: &PyTracebackRef) -> io::Result<()> { - let filename = tb_entry.frame.code.source_path.to_string(); + let filename = tb_entry.frame.code.source_path.to_owned(); writeln!( output, r##" File "{}", line {}, in {}"##, diff --git a/vm/src/format.rs b/vm/src/format.rs index 39c6ac2e7b..73d444a8e9 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -614,7 +614,7 @@ impl FormatString { let arg_part = parts[0]; let format_spec = if parts.len() > 1 { - parts[1].to_string() + parts[1].to_owned() } else { String::new() }; @@ -638,7 +638,7 @@ impl FormatString { if let Ok(index) = arg_part.parse::() { Ok(FormatPart::IndexSpec(index, format_spec)) } else { - Ok(FormatPart::KeywordSpec(arg_part.to_string(), format_spec)) + Ok(FormatPart::KeywordSpec(arg_part.to_owned(), format_spec)) } } diff --git a/vm/src/frame.rs b/vm/src/frame.rs index 82b76b32d4..4466bc881f 100644 --- a/vm/src/frame.rs +++ b/vm/src/frame.rs @@ -1154,7 +1154,7 @@ impl Frame { .new_pyfunction(code_obj, scope, defaults, kw_only_defaults); let name = qualified_name.as_str().split('.').next_back().unwrap(); - vm.set_attr(&func_obj, "__name__", vm.new_str(name.to_string()))?; + vm.set_attr(&func_obj, "__name__", vm.new_str(name.to_owned()))?; vm.set_attr(&func_obj, "__qualname__", qualified_name)?; let module = self .scope @@ -1319,13 +1319,13 @@ impl Frame { fn store_attr(&self, vm: &VirtualMachine, attr_name: &str) -> FrameResult { let parent = self.pop_value(); let value = self.pop_value(); - vm.set_attr(&parent, vm.new_str(attr_name.to_string()), value)?; + vm.set_attr(&parent, vm.new_str(attr_name.to_owned()), value)?; Ok(None) } fn delete_attr(&self, vm: &VirtualMachine, attr_name: &str) -> FrameResult { let parent = self.pop_value(); - let name = vm.ctx.new_str(attr_name.to_string()); + let name = vm.ctx.new_str(attr_name.to_owned()); vm.del_attr(&parent, name)?; Ok(None) } diff --git a/vm/src/import.rs b/vm/src/import.rs index 866d8c04f1..bcfe4ba228 100644 --- a/vm/src/import.rs +++ b/vm/src/import.rs @@ -91,7 +91,7 @@ pub fn import_codeobj( set_file_attr: bool, ) -> PyResult { let attrs = vm.ctx.new_dict(); - attrs.set_item("__name__", vm.new_str(module_name.to_string()), vm)?; + attrs.set_item("__name__", vm.new_str(module_name.to_owned()), vm)?; if set_file_attr { attrs.set_item("__file__", vm.new_str(code_obj.source_path.to_owned()), vm)?; } diff --git a/vm/src/obj/objbool.rs b/vm/src/obj/objbool.rs index a4b751c7e5..264d305999 100644 --- a/vm/src/obj/objbool.rs +++ b/vm/src/obj/objbool.rs @@ -96,7 +96,7 @@ The class bool is a subclass of the class int, and cannot be subclassed."; "__rand__" => context.new_method(bool_and), "__xor__" => context.new_method(bool_xor), "__rxor__" => context.new_method(bool_xor), - "__doc__" => context.new_str(bool_doc.to_string()), + "__doc__" => context.new_str(bool_doc.to_owned()), }); } diff --git a/vm/src/obj/objbyteinner.rs b/vm/src/obj/objbyteinner.rs index 6a21f461fd..a507900e8b 100644 --- a/vm/src/obj/objbyteinner.rs +++ b/vm/src/obj/objbyteinner.rs @@ -442,7 +442,7 @@ impl PyByteInner { i @ PyMemoryView => Ok(i.try_value().unwrap()), _ => Err(vm.new_index_error( "can assign only bytes, buffers, or iterables of ints in range(0, 256)" - .to_string() + .to_owned() )), }), }; diff --git a/vm/src/obj/objdict.rs b/vm/src/obj/objdict.rs index d00e404a41..8eca812990 100644 --- a/vm/src/obj/objdict.rs +++ b/vm/src/obj/objdict.rs @@ -524,7 +524,7 @@ macro_rules! dict_iterator { let mut str_parts = vec![]; for (key, value) in zelf.dict.clone() { let s = vm.to_repr(&$result_fn(vm, &key, &value))?; - str_parts.push(s.as_str().to_string()); + str_parts.push(s.as_str().to_owned()); } format!("{}([{}])", $class_name, str_parts.join(", ")) } else { diff --git a/vm/src/obj/objint.rs b/vm/src/obj/objint.rs index a54833528c..acb2cc70cc 100644 --- a/vm/src/obj/objint.rs +++ b/vm/src/obj/objint.rs @@ -94,7 +94,7 @@ macro_rules! impl_try_from_object_int { vm.new_overflow_error(concat!( "Int value cannot fit into Rust ", stringify!($t) - ).to_string()) + ).to_owned()) ), } } diff --git a/vm/src/obj/objlist.rs b/vm/src/obj/objlist.rs index 5dc58f26cd..94b8548736 100644 --- a/vm/src/obj/objlist.rs +++ b/vm/src/obj/objlist.rs @@ -453,7 +453,7 @@ impl PyList { let mut str_parts = Vec::with_capacity(zelf.elements.borrow().len()); for elem in zelf.elements.borrow().iter() { let s = vm.to_repr(elem)?; - str_parts.push(s.as_str().to_string()); + str_parts.push(s.as_str().to_owned()); } format!("[{}]", str_parts.join(", ")) } else { diff --git a/vm/src/obj/objstr.rs b/vm/src/obj/objstr.rs index 10e6eba69d..9be0512307 100644 --- a/vm/src/obj/objstr.rs +++ b/vm/src/obj/objstr.rs @@ -61,7 +61,7 @@ impl PyString { impl From<&str> for PyString { fn from(s: &str) -> PyString { - s.to_string().into() + s.to_owned().into() } } @@ -277,7 +277,7 @@ impl PyString { Either::B(slice) => { let string = self .value - .to_string() + .to_owned() .get_slice_items(vm, slice.as_object())?; Ok(vm.new_str(string)) } @@ -419,21 +419,21 @@ impl PyString { let elements: Vec<_> = match (pattern, num_splits.is_negative()) { (Some(pattern), true) => value .split(pattern) - .map(|o| vm.ctx.new_str(o.to_string())) + .map(|o| vm.ctx.new_str(o.to_owned())) .collect(), (Some(pattern), false) => value .splitn(num_splits as usize + 1, pattern) - .map(|o| vm.ctx.new_str(o.to_string())) + .map(|o| vm.ctx.new_str(o.to_owned())) .collect(), (None, true) => value .split(|c: char| c.is_ascii_whitespace()) .filter(|s| !s.is_empty()) - .map(|o| vm.ctx.new_str(o.to_string())) + .map(|o| vm.ctx.new_str(o.to_owned())) .collect(), (None, false) => value .splitn(num_splits as usize + 1, |c: char| c.is_ascii_whitespace()) .filter(|s| !s.is_empty()) - .map(|o| vm.ctx.new_str(o.to_string())) + .map(|o| vm.ctx.new_str(o.to_owned())) .collect(), }; vm.ctx.new_list(elements) @@ -447,21 +447,21 @@ impl PyString { let mut elements: Vec<_> = match (pattern, num_splits.is_negative()) { (Some(pattern), true) => value .rsplit(pattern) - .map(|o| vm.ctx.new_str(o.to_string())) + .map(|o| vm.ctx.new_str(o.to_owned())) .collect(), (Some(pattern), false) => value .rsplitn(num_splits as usize + 1, pattern) - .map(|o| vm.ctx.new_str(o.to_string())) + .map(|o| vm.ctx.new_str(o.to_owned())) .collect(), (None, true) => value .rsplit(|c: char| c.is_ascii_whitespace()) .filter(|s| !s.is_empty()) - .map(|o| vm.ctx.new_str(o.to_string())) + .map(|o| vm.ctx.new_str(o.to_owned())) .collect(), (None, false) => value .rsplitn(num_splits as usize + 1, |c: char| c.is_ascii_whitespace()) .filter(|s| !s.is_empty()) - .map(|o| vm.ctx.new_str(o.to_string())) + .map(|o| vm.ctx.new_str(o.to_owned())) .collect(), }; // Unlike Python rsplit, Rust rsplitn returns an iterator that @@ -474,31 +474,31 @@ impl PyString { fn strip(&self, chars: OptionalArg, _vm: &VirtualMachine) -> String { let chars = match chars { OptionalArg::Present(ref chars) => &chars.value, - OptionalArg::Missing => return self.value.trim().to_string(), + OptionalArg::Missing => return self.value.trim().to_owned(), }; - self.value.trim_matches(|c| chars.contains(c)).to_string() + self.value.trim_matches(|c| chars.contains(c)).to_owned() } #[pymethod] fn lstrip(&self, chars: OptionalArg, _vm: &VirtualMachine) -> String { let chars = match chars { OptionalArg::Present(ref chars) => &chars.value, - OptionalArg::Missing => return self.value.trim_start().to_string(), + OptionalArg::Missing => return self.value.trim_start().to_owned(), }; self.value .trim_start_matches(|c| chars.contains(c)) - .to_string() + .to_owned() } #[pymethod] fn rstrip(&self, chars: OptionalArg, _vm: &VirtualMachine) -> String { let chars = match chars { OptionalArg::Present(ref chars) => &chars.value, - OptionalArg::Missing => return self.value.trim_end().to_string(), + OptionalArg::Missing => return self.value.trim_end().to_owned(), }; self.value .trim_end_matches(|c| chars.contains(c)) - .to_string() + .to_owned() } #[pymethod] @@ -904,7 +904,7 @@ impl PyString { if value.contains(sub) { new_tup = value .splitn(2, sub) - .map(|s| vm.ctx.new_str(s.to_string())) + .map(|s| vm.ctx.new_str(s.to_owned())) .collect(); new_tup.insert(1, vm.ctx.new_str(sub.clone())); } else { @@ -923,7 +923,7 @@ impl PyString { if value.contains(sub) { new_tup = value .rsplitn(2, sub) - .map(|s| vm.ctx.new_str(s.to_string())) + .map(|s| vm.ctx.new_str(s.to_owned())) .collect(); new_tup.swap(0, 1); // so it's in the right order new_tup.insert(1, vm.ctx.new_str(sub.clone())); @@ -985,7 +985,7 @@ impl PyString { fn zfill(&self, len: usize, _vm: &VirtualMachine) -> String { let value = &self.value; if len <= value.len() { - value.to_string() + value.to_owned() } else { format!("{}{}", "0".repeat(len - value.len()), value) } @@ -1017,7 +1017,7 @@ impl PyString { let value = &self.value; let rep_char = Self::get_fill_char(&rep, vm)?; if len <= value.len() { - Ok(value.to_string()) + Ok(value.to_owned()) } else { Ok(format!("{}{}", value, rep_char.repeat(len - value.len()))) } @@ -1033,7 +1033,7 @@ impl PyString { let value = &self.value; let rep_char = Self::get_fill_char(&rep, vm)?; if len <= value.len() { - Ok(value.to_string()) + Ok(value.to_owned()) } else { Ok(format!("{}{}", rep_char.repeat(len - value.len()), value)) } @@ -1051,7 +1051,7 @@ impl PyString { let value_len = self.value.chars().count(); if len <= value_len { - return Ok(value.to_string()); + return Ok(value.to_owned()); } let diff: usize = len - value_len; let mut left_buff: usize = diff / 2; @@ -1264,7 +1264,7 @@ impl IntoPyObject for String { impl IntoPyObject for &str { fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_str(self.to_string())) + Ok(vm.ctx.new_str(self.to_owned())) } } @@ -1314,7 +1314,7 @@ fn call_object_format(vm: &VirtualMachine, argument: PyObjectRef, format_spec: & Some(FormatPreconversor::Bytes) => vm.call_method(&argument, "decode", vec![])?, None => argument, }; - let returned_type = vm.ctx.new_str(new_format_spec.to_string()); + let returned_type = vm.ctx.new_str(new_format_spec.to_owned()); let result = vm.call_method(&argument, "__format__", vec![returned_type])?; if !objtype::isinstance(&result, &vm.ctx.str_type()) { @@ -1485,7 +1485,7 @@ pub fn do_cformat_string( let obj: PyObjectRef = match &format_spec.mapping_key { Some(key) => { // TODO: change the KeyError message to match the one in cpython - call_getitem(vm, &values, &vm.ctx.new_str(key.to_string()))? + call_getitem(vm, &values, &vm.ctx.new_str(key.to_owned()))? } None => { let mut elements = objtuple::get_value(&values) @@ -1555,8 +1555,7 @@ fn perform_format( && format_string.format_parts.iter().any(FormatPart::is_index) { return Err(vm.new_value_error( - "cannot switch from automatic field numbering to manual field specification" - .to_string(), + "cannot switch from automatic field numbering to manual field specification".to_owned(), )); } let mut auto_argument_index: usize = 1; @@ -1585,7 +1584,7 @@ fn perform_format( let result = match arguments.get_optional_kwarg(&keyword) { Some(argument) => call_object_format(vm, argument.clone(), &format_spec)?, None => { - return Err(vm.new_key_error(vm.new_str(keyword.to_string()))); + return Err(vm.new_key_error(vm.new_str(keyword.to_owned()))); } }; clone_value(&result) diff --git a/vm/src/obj/objsuper.rs b/vm/src/obj/objsuper.rs index c47c64057c..a9b5aed07e 100644 --- a/vm/src/obj/objsuper.rs +++ b/vm/src/obj/objsuper.rs @@ -92,7 +92,7 @@ impl PySuper { _ => { return Err(vm.new_type_error( "super must be called with 1 argument or from inside class method" - .to_string(), + .to_owned(), )); } } @@ -172,6 +172,6 @@ pub fn init(context: &PyContext) { super().cmeth(arg)\n"; extend_class!(context, super_type, { - "__doc__" => context.new_str(super_doc.to_string()), + "__doc__" => context.new_str(super_doc.to_owned()), }); } diff --git a/vm/src/obj/objtype.rs b/vm/src/obj/objtype.rs index e7465e6ccf..b4a0169417 100644 --- a/vm/src/obj/objtype.rs +++ b/vm/src/obj/objtype.rs @@ -101,7 +101,7 @@ impl PyClassRef { let attributes = self.get_attributes(); let attributes: Vec = attributes .keys() - .map(|k| vm.ctx.new_str(k.to_string())) + .map(|k| vm.ctx.new_str(k.to_owned())) .collect(); PyList::from(attributes) } @@ -220,7 +220,7 @@ impl PyClassRef { self.attributes.borrow_mut().remove(attr_name.as_str()); Ok(()) } else { - Err(vm.new_attribute_error(attr_name.as_str().to_string())) + Err(vm.new_attribute_error(attr_name.as_str().to_owned())) } } @@ -228,7 +228,7 @@ impl PyClassRef { pub fn set_str_attr>(&self, attr_name: &str, value: V) { self.attributes .borrow_mut() - .insert(attr_name.to_string(), value.into()); + .insert(attr_name.to_owned(), value.into()); } #[pymethod(magic)] @@ -448,7 +448,7 @@ impl PyClassRef { for bc in base_classes { for (name, value) in bc.attributes.borrow().iter() { - attributes.insert(name.to_string(), value.clone()); + attributes.insert(name.to_owned(), value.clone()); } } @@ -548,7 +548,7 @@ fn calculate_meta_class( return Err(vm.new_type_error( "metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass \ of the metaclasses of all its bases" - .to_string(), + .to_owned(), )); } Ok(winner) diff --git a/vm/src/py_serde.rs b/vm/src/py_serde.rs index 3bd8bedbf4..47520bb130 100644 --- a/vm/src/py_serde.rs +++ b/vm/src/py_serde.rs @@ -176,7 +176,7 @@ impl<'de> Visitor<'de> for PyObjectDeserializer<'de> { E: serde::de::Error, { // Owned value needed anyway, delegate to visit_string - self.visit_string(value.to_string()) + self.visit_string(value.to_owned()) } fn visit_string(self, value: String) -> Result diff --git a/vm/src/stdlib/ast.rs b/vm/src/stdlib/ast.rs index d25429dcb3..33b3ea6226 100644 --- a/vm/src/stdlib/ast.rs +++ b/vm/src/stdlib/ast.rs @@ -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_string())); + field_names.push($vm.ctx.new_str(field_name.to_owned())); )* $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_string()), + name => vm.ctx.new_str(name.to_owned()), 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_string()), + name => vm.ctx.new_str(name.to_owned()), 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_string()), + name => vm.ctx.new_str(name.to_owned()), 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 { Ok(node!(vm, alias, { - name => vm.ctx.new_str(alias.symbol.to_string()), + name => vm.ctx.new_str(alias.symbol.to_owned()), asname => optional_string_to_py_obj(vm, &alias.alias) })) } @@ -280,12 +280,8 @@ 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_string())) - .collect(), - ) + vm.ctx + .new_list(names.iter().map(|x| vm.ctx.new_str(x.to_owned())).collect()) } fn optional_expressions_to_ast( @@ -344,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_string()), + op => vm.ctx.new_str(op.to_owned()), operand => expression_to_ast(vm, a)?, }) } @@ -355,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_string()); + let py_op = vm.ctx.new_str(str_op.to_owned()); node!(vm, BoolOp, { op => py_op, @@ -380,7 +376,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes }; let ops = vm.ctx.new_list( ops.iter() - .map(|x| vm.ctx.new_str(to_operator(x).to_string())) + .map(|x| vm.ctx.new_str(to_operator(x).to_owned())) .collect(), ); @@ -510,7 +506,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_string()), + attr => vm.ctx.new_str(name.to_owned()), ctx => vm.ctx.none() }), Starred { value } => node!(vm, Starred, { @@ -545,7 +541,7 @@ fn operator_string(op: &ast::Operator) -> String { BitAnd => "BitAnd", FloorDiv => "FloorDiv", } - .to_string() + .to_owned() } fn parameters_to_ast(vm: &VirtualMachine, args: &ast::Parameters) -> PyResult { @@ -576,7 +572,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_string()), + arg => vm.ctx.new_str(parameter.arg.to_owned()), annotation => py_annotation }); @@ -588,7 +584,7 @@ fn parameter_to_ast(vm: &VirtualMachine, parameter: &ast::Parameter) -> PyResult fn optional_string_to_py_obj(vm: &VirtualMachine, name: &Option) -> PyObjectRef { if let Some(name) = name { - vm.ctx.new_str(name.to_string()) + vm.ctx.new_str(name.to_owned()) } else { vm.ctx.none() } diff --git a/vm/src/stdlib/csv.rs b/vm/src/stdlib/csv.rs index 5ed4d71ff5..fc42643a2a 100644 --- a/vm/src/stdlib/csv.rs +++ b/vm/src/stdlib/csv.rs @@ -35,7 +35,7 @@ impl ReaderOption { 1 => bytes[0], _ => { let msg = r#""delimiter" must be a 1-character string"#; - return Err(vm.new_type_error(msg.to_string())); + return Err(vm.new_type_error(msg.to_owned())); } } } else { @@ -48,7 +48,7 @@ impl ReaderOption { 1 => bytes[0], _ => { let msg = r#""quotechar" must be a 1-character string"#; - return Err(vm.new_type_error(msg.to_string())); + return Err(vm.new_type_error(msg.to_owned())); } } } else { diff --git a/vm/src/stdlib/dis.rs b/vm/src/stdlib/dis.rs index a3f0359855..adc31ff17e 100644 --- a/vm/src/stdlib/dis.rs +++ b/vm/src/stdlib/dis.rs @@ -23,7 +23,7 @@ fn dis_compiler_flag_names(vm: &VirtualMachine) -> PyObjectRef { for (name, flag) in CodeFlags::NAME_MAPPING { dict.set_item( &vm.ctx.new_int(flag.bits()), - vm.ctx.new_str((*name).to_string()), + vm.ctx.new_str((*name).to_owned()), vm, ) .unwrap(); diff --git a/vm/src/stdlib/hashlib.rs b/vm/src/stdlib/hashlib.rs index 4b8f6b4122..98a7ce9dd9 100644 --- a/vm/src/stdlib/hashlib.rs +++ b/vm/src/stdlib/hashlib.rs @@ -36,7 +36,7 @@ impl PyValue for PyHasher { impl PyHasher { fn new(name: &str, d: HashWrapper) -> Self { PyHasher { - name: name.to_string(), + name: name.to_owned(), buffer: RefCell::new(d), } } diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index ee4ec13d45..378fe5f4f1 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -770,7 +770,7 @@ fn text_io_wrapper_write( return Err(vm.new_value_error("not writable".to_owned())); } - let bytes = obj.as_str().to_string().into_bytes(); + let bytes = obj.as_str().to_owned().into_bytes(); let len = vm.call_method(&raw, "write", vec![vm.ctx.new_bytes(bytes.clone())])?; let len = objint::get_value(&len) @@ -858,7 +858,7 @@ fn split_mode_string(mode_string: &str) -> Result<(String, String), String> { if mode == '\0' { return Err( "Must have exactly one of create/read/write/append mode and at most one plus" - .to_string(), + .to_owned(), ); } let mut mode = mode.to_string(); @@ -1102,21 +1102,21 @@ mod tests { split_mode_string(""), Err( "Must have exactly one of create/read/write/append mode and at most one plus" - .to_string() + .to_owned() ) ); assert_eq!( split_mode_string("b"), Err( "Must have exactly one of create/read/write/append mode and at most one plus" - .to_string() + .to_owned() ) ); assert_eq!( split_mode_string("t"), Err( "Must have exactly one of create/read/write/append mode and at most one plus" - .to_string() + .to_owned() ) ); } diff --git a/vm/src/stdlib/itertools.rs b/vm/src/stdlib/itertools.rs index 79253a36d9..e0a104041d 100644 --- a/vm/src/stdlib/itertools.rs +++ b/vm/src/stdlib/itertools.rs @@ -553,7 +553,7 @@ impl PyItertoolsIslice { Some(pyobject_to_opt_usize(stop, &vm).ok_or_else(|| { vm.new_value_error( "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize." - .to_string(), + .to_owned(), ) })?) } else { diff --git a/vm/src/stdlib/keyword.rs b/vm/src/stdlib/keyword.rs index cede07e880..e22590ab4a 100644 --- a/vm/src/stdlib/keyword.rs +++ b/vm/src/stdlib/keyword.rs @@ -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_string())) + .map(|k| ctx.new_str(k.to_owned())) .collect(), ); diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index a5b35ecacd..a6be3e5262 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -312,7 +312,7 @@ fn os_access(path: PyStringRef, mode: u8, vm: &VirtualMachine) -> PyResult let flags = AccessFlags::from_bits(mode).ok_or_else(|| { vm.new_value_error( "One of the flags is wrong, there are only 4 possibilities F_OK, R_OK, W_OK and X_OK" - .to_string(), + .to_owned(), ) })?; @@ -340,7 +340,7 @@ fn os_access(path: PyStringRef, mode: u8, vm: &VirtualMachine) -> PyResult } fn os_error(message: OptionalArg, vm: &VirtualMachine) -> PyResult { - let msg = message.map_or("".to_owned(), |msg| msg.as_str().to_string()); + let msg = message.map_or("".to_owned(), |msg| msg.as_str().to_owned()); Err(vm.new_os_error(msg)) } @@ -524,7 +524,7 @@ impl DirEntryRef { } fn path(self, _vm: &VirtualMachine) -> String { - self.entry.path().to_str().unwrap().to_string() + self.entry.path().to_str().unwrap().to_owned() } #[allow(clippy::match_bool)] @@ -877,7 +877,7 @@ fn os_getcwd(vm: &VirtualMachine) -> PyResult { .as_path() .to_str() .unwrap() - .to_string()) + .to_owned()) } fn os_chdir(path: PyStringRef, vm: &VirtualMachine) -> PyResult<()> { diff --git a/vm/src/stdlib/re.rs b/vm/src/stdlib/re.rs index 9de904e414..25203ba1c2 100644 --- a/vm/src/stdlib/re.rs +++ b/vm/src/stdlib/re.rs @@ -283,7 +283,7 @@ fn make_regex(vm: &VirtualMachine, pattern: &str, flags: PyRegexFlags) -> PyResu })?; Ok(PyPattern { regex: r, - pattern: pattern.to_string(), + pattern: pattern.to_owned(), }) } diff --git a/vm/src/stdlib/subprocess.rs b/vm/src/stdlib/subprocess.rs index 57ddfc780b..78e8bfafc5 100644 --- a/vm/src/stdlib/subprocess.rs +++ b/vm/src/stdlib/subprocess.rs @@ -106,7 +106,7 @@ impl PopenRef { let stdout = convert_redirection(args.stdout, vm)?; let stderr = convert_redirection(args.stderr, vm)?; let command_list = match &args.args { - Either::A(command) => vec![command.as_str().to_string()], + Either::A(command) => vec![command.as_str().to_owned()], Either::B(command_list) => command_list .borrow_elements() .iter() diff --git a/vm/src/stdlib/symtable.rs b/vm/src/stdlib/symtable.rs index 0591b87496..d32afd44a2 100644 --- a/vm/src/stdlib/symtable.rs +++ b/vm/src/stdlib/symtable.rs @@ -110,7 +110,7 @@ impl PySymbolTable { } .into_ref(vm)) } else { - Err(vm.new_lookup_error(name.to_string())) + Err(vm.new_lookup_error(name.to_owned())) } } @@ -120,7 +120,7 @@ impl PySymbolTable { .symtable .symbols .keys() - .map(|s| vm.ctx.new_str(s.to_string())) + .map(|s| vm.ctx.new_str(s.to_owned())) .collect(); Ok(vm.ctx.new_list(symbols)) } diff --git a/vm/src/stdlib/zlib.rs b/vm/src/stdlib/zlib.rs index cebef22adf..b1b44b2bcb 100644 --- a/vm/src/stdlib/zlib.rs +++ b/vm/src/stdlib/zlib.rs @@ -121,5 +121,5 @@ fn zlib_error(message: &str, vm: &VirtualMachine) -> PyBaseExceptionRef { let zlib_error = vm.get_attribute(module, "error").unwrap(); let zlib_error = zlib_error.downcast().unwrap(); - vm.new_exception_msg(zlib_error, message.to_string()) + vm.new_exception_msg(zlib_error, message.to_owned()) } diff --git a/vm/src/sysmodule.rs b/vm/src/sysmodule.rs index 072fa59b88..fdb04de47e 100644 --- a/vm/src/sysmodule.rs +++ b/vm/src/sysmodule.rs @@ -345,7 +345,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_string()), + "copyright" => ctx.new_str(copyright.to_owned()), "executable" => executable(ctx), "flags" => flags, "getrefcount" => ctx.new_function(sys_getrefcount), @@ -363,7 +363,7 @@ settrace() -- set the global debug tracing function "path" => path, "ps1" => ctx.new_str(">>>>> ".to_owned()), "ps2" => ctx.new_str("..... ".to_owned()), - "__doc__" => ctx.new_str(sys_doc.to_string()), + "__doc__" => ctx.new_str(sys_doc.to_owned()), "_getframe" => ctx.new_function(getframe), "modules" => modules.clone(), "warnoptions" => ctx.new_list(vec![]), @@ -381,10 +381,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_string()), - "base_prefix" => ctx.new_str(base_prefix.to_string()), - "exec_prefix" => ctx.new_str(exec_prefix.to_string()), - "base_exec_prefix" => ctx.new_str(base_exec_prefix.to_string()), + "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()), "exit" => ctx.new_function(sys_exit), "abiflags" => ctx.new_str("".to_owned()), }); diff --git a/vm/src/version.rs b/vm/src/version.rs index c14f6c2943..5981d17c57 100644 --- a/vm/src/version.rs +++ b/vm/src/version.rs @@ -71,17 +71,17 @@ pub fn get_build_info() -> String { } pub fn get_git_revision() -> String { - option_env!("RUSTPYTHON_GIT_HASH").unwrap_or("").to_string() + option_env!("RUSTPYTHON_GIT_HASH").unwrap_or("").to_owned() } pub fn get_git_tag() -> String { - option_env!("RUSTPYTHON_GIT_TAG").unwrap_or("").to_string() + option_env!("RUSTPYTHON_GIT_TAG").unwrap_or("").to_owned() } pub fn get_git_branch() -> String { option_env!("RUSTPYTHON_GIT_BRANCH") .unwrap_or("") - .to_string() + .to_owned() } pub fn get_git_identifier() -> String { @@ -98,7 +98,7 @@ pub fn get_git_identifier() -> String { fn get_git_timestamp_datetime() -> DateTime { let timestamp = option_env!("RUSTPYTHON_GIT_TIMESTAMP") .unwrap_or("") - .to_string(); + .to_owned(); let timestamp = timestamp.parse::().unwrap_or(0); let datetime = UNIX_EPOCH + Duration::from_secs(timestamp); diff --git a/vm/src/vm.rs b/vm/src/vm.rs index 7ea7215fbc..8d573327da 100644 --- a/vm/src/vm.rs +++ b/vm/src/vm.rs @@ -576,7 +576,7 @@ impl VirtualMachine { let from_list = self.ctx.new_tuple( from_list .iter() - .map(|name| self.new_str(name.to_string())) + .map(|name| self.new_str(name.to_owned())) .collect(), ); self.invoke( @@ -908,7 +908,7 @@ impl VirtualMachine { compile::compile(source, mode, source_path, self.settings.optimize) .map(|codeobj| PyCode::new(codeobj).into_ref(self)) .map_err(|mut compile_error| { - compile_error.update_statement_info(source.trim_end().to_string()); + compile_error.update_statement_info(source.trim_end().to_owned()); compile_error }) }