From d935fbc445815e1df3f34a2817ffc61578ffaad3 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Mon, 5 Dec 2022 12:08:16 +0900 Subject: [PATCH] Fix nightly clippy warnings --- compiler/codegen/src/compile.rs | 2 +- compiler/codegen/src/error.rs | 6 ++--- compiler/codegen/src/symboltable.rs | 20 +++++++------- compiler/core/src/bytecode.rs | 28 ++++++++++---------- compiler/parser/src/error.rs | 21 +++++++-------- compiler/parser/src/fstring.rs | 2 +- compiler/parser/src/lexer.rs | 2 +- compiler/parser/src/token.rs | 12 ++++----- examples/dis.rs | 4 +-- examples/generator.rs | 2 +- examples/package_embed.rs | 2 +- examples/parse_folder.rs | 8 +++--- src/settings.rs | 2 +- src/shell.rs | 4 +-- stdlib/build.rs | 4 +-- stdlib/src/array.rs | 16 +++++------ stdlib/src/binascii.rs | 2 +- stdlib/src/grp.rs | 4 +-- stdlib/src/hashlib.rs | 2 +- stdlib/src/json/machinery.rs | 11 +++----- stdlib/src/mmap.rs | 5 +--- stdlib/src/pystruct.rs | 12 +++------ stdlib/src/scproxy.rs | 4 +-- stdlib/src/socket.rs | 4 +-- stdlib/src/ssl.rs | 8 +++--- stdlib/src/termios.rs | 3 +-- stdlib/src/unicodedata.rs | 2 +- vm/build.rs | 6 ++--- vm/src/builtins/bool.rs | 3 +-- vm/src/builtins/classmethod.rs | 2 +- vm/src/builtins/complex.rs | 2 +- vm/src/builtins/dict.rs | 2 +- vm/src/builtins/float.rs | 6 ++--- vm/src/builtins/function.rs | 6 ++--- vm/src/builtins/genericalias.rs | 2 +- vm/src/builtins/module.rs | 4 +-- vm/src/builtins/namespace.rs | 2 +- vm/src/builtins/object.rs | 3 +-- vm/src/builtins/range.rs | 2 +- vm/src/builtins/set.rs | 10 +++---- vm/src/builtins/staticmethod.rs | 2 +- vm/src/builtins/super.rs | 2 +- vm/src/builtins/union.rs | 2 +- vm/src/builtins/weakref.rs | 2 +- vm/src/bytesinner.rs | 3 +-- vm/src/cformat.rs | 20 +++++--------- vm/src/codecs.rs | 15 +++++------ vm/src/dictdatatype.rs | 4 +-- vm/src/exceptions.rs | 10 +++---- vm/src/format.rs | 5 +--- vm/src/frame.rs | 19 ++++++------- vm/src/function/argument.rs | 9 +++---- vm/src/import.rs | 9 ++++--- vm/src/protocol/buffer.rs | 2 +- vm/src/readline.rs | 2 +- vm/src/stdlib/ast.rs | 5 ++-- vm/src/stdlib/builtins.rs | 28 ++++++++------------ vm/src/stdlib/codecs.rs | 2 +- vm/src/stdlib/collections.rs | 6 ++--- vm/src/stdlib/imp.rs | 4 +-- vm/src/stdlib/io.rs | 41 +++++++++++++---------------- vm/src/stdlib/itertools.rs | 7 +++-- vm/src/stdlib/operator.rs | 8 +++--- vm/src/stdlib/os.rs | 6 ++--- vm/src/stdlib/posix.rs | 10 +++---- vm/src/stdlib/pwd.rs | 2 +- vm/src/stdlib/signal.rs | 4 +-- vm/src/stdlib/sre.rs | 4 +-- vm/src/stdlib/symtable.rs | 2 +- vm/src/stdlib/sys.rs | 5 ++-- vm/src/stdlib/sysconfigdata.rs | 2 +- vm/src/stdlib/time.rs | 4 +-- vm/src/types/structseq.rs | 2 +- vm/src/version.rs | 4 +-- vm/src/vm/mod.rs | 12 ++++----- vm/src/vm/vm_object.rs | 2 +- vm/src/warn.rs | 2 +- 77 files changed, 226 insertions(+), 284 deletions(-) diff --git a/compiler/codegen/src/compile.rs b/compiler/codegen/src/compile.rs index 602f9b7db2..ba3d54534f 100644 --- a/compiler/codegen/src/compile.rs +++ b/compiler/codegen/src/compile.rs @@ -457,7 +457,7 @@ impl Compiler { NameUsage::Delete if is_forbidden_name(name) => "cannot delete", _ => return Ok(()), }; - Err(self.error(CodegenErrorType::SyntaxError(format!("{} {}", msg, name)))) + Err(self.error(CodegenErrorType::SyntaxError(format!("{msg} {name}")))) } fn compile_name(&mut self, name: &str, usage: NameUsage) -> CompileResult<()> { diff --git a/compiler/codegen/src/error.rs b/compiler/codegen/src/error.rs index 9073abb5b6..648446f4f2 100644 --- a/compiler/codegen/src/error.rs +++ b/compiler/codegen/src/error.rs @@ -37,8 +37,8 @@ impl fmt::Display for CodegenErrorType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use CodegenErrorType::*; match self { - Assign(target) => write!(f, "cannot assign to {}", target), - Delete(target) => write!(f, "cannot delete {}", target), + Assign(target) => write!(f, "cannot assign to {target}"), + Delete(target) => write!(f, "cannot delete {target}"), SyntaxError(err) => write!(f, "{}", err.as_str()), MultipleStarArgs => { write!(f, "two starred expressions in assignment") @@ -59,7 +59,7 @@ impl fmt::Display for CodegenErrorType { "from __future__ imports must occur at the beginning of the file" ), InvalidFutureFeature(feat) => { - write!(f, "future feature {} is not defined", feat) + write!(f, "future feature {feat} is not defined") } FunctionImportStar => { write!(f, "import * only allowed at module level") diff --git a/compiler/codegen/src/symboltable.rs b/compiler/codegen/src/symboltable.rs index 9662707a3a..5a625b2552 100644 --- a/compiler/codegen/src/symboltable.rs +++ b/compiler/codegen/src/symboltable.rs @@ -1154,27 +1154,26 @@ impl SymbolTableBuilder { SymbolUsage::Global if !symbol.is_global() => { if flags.contains(SymbolFlags::PARAMETER) { return Err(SymbolTableError { - error: format!("name '{}' is parameter and global", name), + error: format!("name '{name}' is parameter and global"), location, }); } if flags.contains(SymbolFlags::REFERENCED) { return Err(SymbolTableError { - error: format!("name '{}' is used prior to global declaration", name), + error: format!("name '{name}' is used prior to global declaration"), location, }); } if flags.contains(SymbolFlags::ANNOTATED) { return Err(SymbolTableError { - error: format!("annotated name '{}' can't be global", name), + error: format!("annotated name '{name}' can't be global"), location, }); } if flags.contains(SymbolFlags::ASSIGNED) { return Err(SymbolTableError { error: format!( - "name '{}' is assigned to before global declaration", - name + "name '{name}' is assigned to before global declaration" ), location, }); @@ -1183,27 +1182,26 @@ impl SymbolTableBuilder { SymbolUsage::Nonlocal => { if flags.contains(SymbolFlags::PARAMETER) { return Err(SymbolTableError { - error: format!("name '{}' is parameter and nonlocal", name), + error: format!("name '{name}' is parameter and nonlocal"), location, }); } if flags.contains(SymbolFlags::REFERENCED) { return Err(SymbolTableError { - error: format!("name '{}' is used prior to nonlocal declaration", name), + error: format!("name '{name}' is used prior to nonlocal declaration"), location, }); } if flags.contains(SymbolFlags::ANNOTATED) { return Err(SymbolTableError { - error: format!("annotated name '{}' can't be nonlocal", name), + error: format!("annotated name '{name}' can't be nonlocal"), location, }); } if flags.contains(SymbolFlags::ASSIGNED) { return Err(SymbolTableError { error: format!( - "name '{}' is assigned to before nonlocal declaration", - name + "name '{name}' is assigned to before nonlocal declaration" ), location, }); @@ -1220,7 +1218,7 @@ impl SymbolTableBuilder { match role { SymbolUsage::Nonlocal if scope_depth < 2 => { return Err(SymbolTableError { - error: format!("cannot define nonlocal '{}' at top level.", name), + error: format!("cannot define nonlocal '{name}' at top level."), location, }) } diff --git a/compiler/core/src/bytecode.rs b/compiler/core/src/bytecode.rs index 9c3751cd1c..ea2477ae27 100644 --- a/compiler/core/src/bytecode.rs +++ b/compiler/core/src/bytecode.rs @@ -482,15 +482,15 @@ impl BorrowedConstant<'_, C> { // takes `self` because we need to consume the iterator pub fn fmt_display(self, f: &mut fmt::Formatter) -> fmt::Result { match self { - BorrowedConstant::Integer { value } => write!(f, "{}", value), - BorrowedConstant::Float { value } => write!(f, "{}", value), - BorrowedConstant::Complex { value } => write!(f, "{}", value), + BorrowedConstant::Integer { value } => write!(f, "{value}"), + BorrowedConstant::Float { value } => write!(f, "{value}"), + BorrowedConstant::Complex { value } => write!(f, "{value}"), BorrowedConstant::Boolean { value } => { write!(f, "{}", if value { "True" } else { "False" }) } - BorrowedConstant::Str { value } => write!(f, "{:?}", value), + BorrowedConstant::Str { value } => write!(f, "{value:?}"), BorrowedConstant::Bytes { value } => write!(f, "b{:?}", value.as_bstr()), - BorrowedConstant::Code { code } => write!(f, "{:?}", code), + BorrowedConstant::Code { code } => write!(f, "{code:?}"), BorrowedConstant::Tuple { elements } => { write!(f, "(")?; let mut first = true; @@ -852,7 +852,7 @@ impl fmt::Display for CodeObject { self.display_inner(f, false, 1)?; for constant in &*self.constants { if let BorrowedConstant::Code { code } = constant.borrow_constant() { - writeln!(f, "\nDisassembly of {:?}", code)?; + writeln!(f, "\nDisassembly of {code:?}")?; code.fmt(f)?; } } @@ -1118,14 +1118,14 @@ impl Instruction { } } } - UnaryOperation { op } => w!(UnaryOperation, format_args!("{:?}", op)), - BinaryOperation { op } => w!(BinaryOperation, format_args!("{:?}", op)), + UnaryOperation { op } => w!(UnaryOperation, format_args!("{op:?}")), + BinaryOperation { op } => w!(BinaryOperation, format_args!("{op:?}")), BinaryOperationInplace { op } => { - w!(BinaryOperationInplace, format_args!("{:?}", op)) + w!(BinaryOperationInplace, format_args!("{op:?}")) } LoadAttr { idx } => w!(LoadAttr, name(*idx)), - TestOperation { op } => w!(TestOperation, format_args!("{:?}", op)), - CompareOperation { op } => w!(CompareOperation, format_args!("{:?}", op)), + TestOperation { op } => w!(TestOperation, format_args!("{op:?}")), + CompareOperation { op } => w!(CompareOperation, format_args!("{op:?}")), Pop => w!(Pop), Rotate2 => w!(Rotate2), Rotate3 => w!(Rotate3), @@ -1139,7 +1139,7 @@ impl Instruction { JumpIfFalse { target } => w!(JumpIfFalse, target), JumpIfTrueOrPop { target } => w!(JumpIfTrueOrPop, target), JumpIfFalseOrPop { target } => w!(JumpIfFalseOrPop, target), - MakeFunction(flags) => w!(MakeFunction, format_args!("{:?}", flags)), + MakeFunction(flags) => w!(MakeFunction, format_args!("{flags:?}")), CallFunctionPositional { nargs } => w!(CallFunctionPositional, nargs), CallFunctionKeyword { nargs } => w!(CallFunctionKeyword, nargs), CallFunctionEx { has_kwargs } => w!(CallFunctionEx, has_kwargs), @@ -1163,7 +1163,7 @@ impl Instruction { BeforeAsyncWith => w!(BeforeAsyncWith), SetupAsyncWith { end } => w!(SetupAsyncWith, end), PopBlock => w!(PopBlock), - Raise { kind } => w!(Raise, format_args!("{:?}", kind)), + Raise { kind } => w!(Raise, format_args!("{kind:?}")), BuildString { size } => w!(BuildString, size), BuildTuple { size, unpack } => w!(BuildTuple, size, unpack), BuildList { size, unpack } => w!(BuildList, size, unpack), @@ -1182,7 +1182,7 @@ impl Instruction { LoadBuildClass => w!(LoadBuildClass), UnpackSequence { size } => w!(UnpackSequence, size), UnpackEx { before, after } => w!(UnpackEx, before, after), - FormatValue { conversion } => w!(FormatValue, format_args!("{:?}", conversion)), + FormatValue { conversion } => w!(FormatValue, format_args!("{conversion:?}")), PopException => w!(PopException), Reverse { amount } => w!(Reverse, amount), GetAwaitable => w!(GetAwaitable), diff --git a/compiler/parser/src/error.rs b/compiler/parser/src/error.rs index e835442131..89f5366828 100644 --- a/compiler/parser/src/error.rs +++ b/compiler/parser/src/error.rs @@ -34,7 +34,7 @@ impl fmt::Display for LexicalErrorType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { LexicalErrorType::StringError => write!(f, "Got unexpected string"), - LexicalErrorType::FStringError(error) => write!(f, "Got error in f-string: {}", error), + LexicalErrorType::FStringError(error) => write!(f, "Got error in f-string: {error}"), LexicalErrorType::UnicodeError => write!(f, "Got unexpected unicode"), LexicalErrorType::NestingError => write!(f, "Got unexpected nesting"), LexicalErrorType::IndentationError => { @@ -56,13 +56,13 @@ impl fmt::Display for LexicalErrorType { write!(f, "positional argument follows keyword argument") } LexicalErrorType::UnrecognizedToken { tok } => { - write!(f, "Got unexpected token {}", tok) + write!(f, "Got unexpected token {tok}") } LexicalErrorType::LineContinuationError => { write!(f, "unexpected character after line continuation character") } LexicalErrorType::Eof => write!(f, "unexpected EOF while parsing"), - LexicalErrorType::OtherError(msg) => write!(f, "{}", msg), + LexicalErrorType::OtherError(msg) => write!(f, "{msg}"), } } } @@ -97,17 +97,16 @@ impl fmt::Display for FStringErrorType { FStringErrorType::UnopenedRbrace => write!(f, "Unopened '}}'"), FStringErrorType::ExpectedRbrace => write!(f, "Expected '}}' after conversion flag."), FStringErrorType::InvalidExpression(error) => { - write!(f, "{}", error) + write!(f, "{error}") } FStringErrorType::InvalidConversionFlag => write!(f, "invalid conversion character"), FStringErrorType::EmptyExpression => write!(f, "empty expression not allowed"), FStringErrorType::MismatchedDelimiter(first, second) => write!( f, - "closing parenthesis '{}' does not match opening parenthesis '{}'", - second, first + "closing parenthesis '{second}' does not match opening parenthesis '{first}'" ), FStringErrorType::SingleRbrace => write!(f, "single '}}' is not allowed"), - FStringErrorType::Unmatched(delim) => write!(f, "unmatched '{}'", delim), + FStringErrorType::Unmatched(delim) => write!(f, "unmatched '{delim}'"), FStringErrorType::ExpressionNestedTooDeeply => { write!(f, "expressions nested too deeply") } @@ -118,7 +117,7 @@ impl fmt::Display for FStringErrorType { if *c == '\\' { write!(f, "f-string expression part cannot include a backslash") } else { - write!(f, "f-string expression part cannot include '{}'s", c) + write!(f, "f-string expression part cannot include '{c}'s") } } } @@ -198,7 +197,7 @@ impl fmt::Display for ParseErrorType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ParseErrorType::Eof => write!(f, "Got unexpected EOF"), - ParseErrorType::ExtraToken(ref tok) => write!(f, "Got extraneous token: {:?}", tok), + ParseErrorType::ExtraToken(ref tok) => write!(f, "Got extraneous token: {tok:?}"), ParseErrorType::InvalidToken => write!(f, "Got invalid token"), ParseErrorType::UnrecognizedToken(ref tok, ref expected) => { if *tok == Tok::Indent { @@ -206,10 +205,10 @@ impl fmt::Display for ParseErrorType { } else if expected.as_deref() == Some("Indent") { write!(f, "expected an indented block") } else { - write!(f, "invalid syntax. Got unexpected token {}", tok) + write!(f, "invalid syntax. Got unexpected token {tok}") } } - ParseErrorType::Lexical(ref error) => write!(f, "{}", error), + ParseErrorType::Lexical(ref error) => write!(f, "{error}"), } } } diff --git a/compiler/parser/src/fstring.rs b/compiler/parser/src/fstring.rs index 64cb7d3b21..a28383f104 100644 --- a/compiler/parser/src/fstring.rs +++ b/compiler/parser/src/fstring.rs @@ -344,7 +344,7 @@ impl FStringParser { } fn parse_fstring_expr(source: &str) -> Result { - let fstring_body = format!("({})", source); + let fstring_body = format!("({source})"); parse_expression(&fstring_body, "") } diff --git a/compiler/parser/src/lexer.rs b/compiler/parser/src/lexer.rs index 7d24aed86b..04140aa885 100644 --- a/compiler/parser/src/lexer.rs +++ b/compiler/parser/src/lexer.rs @@ -321,7 +321,7 @@ where let value_text = self.radix_run(radix); let end_pos = self.get_pos(); let value = BigInt::from_str_radix(&value_text, radix).map_err(|e| LexicalError { - error: LexicalErrorType::OtherError(format!("{:?}", e)), + error: LexicalErrorType::OtherError(format!("{e:?}")), location: start_pos, })?; Ok((start_pos, Tok::Int { value }, end_pos)) diff --git a/compiler/parser/src/token.rs b/compiler/parser/src/token.rs index ba76f6a4d6..14ffece5ce 100644 --- a/compiler/parser/src/token.rs +++ b/compiler/parser/src/token.rs @@ -118,17 +118,17 @@ impl fmt::Display for Tok { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Tok::*; match self { - Name { name } => write!(f, "'{}'", name), - Int { value } => write!(f, "'{}'", value), - Float { value } => write!(f, "'{}'", value), - Complex { real, imag } => write!(f, "{}j{}", real, imag), + Name { name } => write!(f, "'{name}'"), + Int { value } => write!(f, "'{value}'"), + Float { value } => write!(f, "'{value}'"), + Complex { real, imag } => write!(f, "{real}j{imag}"), String { value, kind } => { match kind { StringKind::F => f.write_str("f")?, StringKind::U => f.write_str("u")?, StringKind::Normal => {} } - write!(f, "{:?}", value) + write!(f, "{value:?}") } Bytes { value } => { write!(f, "b\"")?; @@ -138,7 +138,7 @@ impl fmt::Display for Tok { 10 => f.write_str("\\n")?, 13 => f.write_str("\\r")?, 32..=126 => f.write_char(*i as char)?, - _ => write!(f, "\\x{:02x}", i)?, + _ => write!(f, "\\x{i:02x}")?, } } f.write_str("\"") diff --git a/examples/dis.rs b/examples/dis.rs index d55977fe88..ef53bddfc5 100644 --- a/examples/dis.rs +++ b/examples/dis.rs @@ -73,7 +73,7 @@ fn main() { error!("Error while compiling {:?}: {}", script, e); } } else { - eprintln!("{:?} is not a file.", script); + eprintln!("{script:?} is not a file."); } } } @@ -90,7 +90,7 @@ fn display_script( if expand_codeobjects { println!("{}", code.display_expand_codeobjects()); } else { - println!("{}", code); + println!("{code}"); } Ok(()) } diff --git a/examples/generator.rs b/examples/generator.rs index 1fbdb6a228..010ccd3797 100644 --- a/examples/generator.rs +++ b/examples/generator.rs @@ -33,7 +33,7 @@ gen() PyResult::Ok(v) })?; match r { - PyIterReturn::Return(value) => println!("{}", value), + PyIterReturn::Return(value) => println!("{value}"), PyIterReturn::StopIteration(_) => break, } } diff --git a/examples/package_embed.rs b/examples/package_embed.rs index 7a7c5f293a..fe6b07cec1 100644 --- a/examples/package_embed.rs +++ b/examples/package_embed.rs @@ -20,7 +20,7 @@ fn main() -> ExitCode { }); let result = py_main(&interp); let result = result.map(|result| { - println!("name: {}", result); + println!("name: {result}"); }); ExitCode::from(interp.run(|_vm| result)) } diff --git a/examples/parse_folder.rs b/examples/parse_folder.rs index 823a244b43..89b7393f7d 100644 --- a/examples/parse_folder.rs +++ b/examples/parse_folder.rs @@ -32,7 +32,7 @@ fn main() { let folder = Path::new(matches.value_of("folder").unwrap()); if folder.exists() && folder.is_dir() { - println!("Parsing folder of python code: {:?}", folder); + println!("Parsing folder of python code: {folder:?}"); let t1 = Instant::now(); let parsed_files = parse_folder(folder).unwrap(); let t2 = Instant::now(); @@ -43,7 +43,7 @@ fn main() { }; statistics(results); } else { - println!("{:?} is not a folder.", folder); + println!("{folder:?} is not a folder."); } } @@ -111,13 +111,13 @@ fn statistics(results: ScanResult) { .iter() .filter(|p| p.result.is_ok()) .count(); - println!("Passed: {} Failed: {} Total: {}", passed, failed, total); + println!("Passed: {passed} Failed: {failed} Total: {total}"); println!( "That is {} % success rate.", (passed as f64 * 100.0) / total as f64 ); let duration = results.t2 - results.t1; - println!("Total time spend: {:?}", duration); + println!("Total time spend: {duration:?}"); println!( "Processed {} files. That's {} files/second", total, diff --git a/src/settings.rs b/src/settings.rs index 06542634b8..711ae00f3b 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -344,7 +344,7 @@ fn get_paths(env_variable_name: &str) -> impl Iterator + '_ { .map(|path| { path.into_os_string() .into_string() - .unwrap_or_else(|_| panic!("{} isn't valid unicode", env_variable_name)) + .unwrap_or_else(|_| panic!("{env_variable_name} isn't valid unicode")) }) .collect::>() }) diff --git a/src/shell.rs b/src/shell.rs index a3ef519348..5a9d887b4b 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -121,11 +121,11 @@ pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> { break; } ReadlineResult::Other(err) => { - eprintln!("Readline error: {:?}", err); + eprintln!("Readline error: {err:?}"); break; } ReadlineResult::Io(err) => { - eprintln!("IO error: {:?}", err); + eprintln!("IO error: {err:?}"); break; } }; diff --git a/stdlib/build.rs b/stdlib/build.rs index 135f71152a..baaa99c4c8 100644 --- a/stdlib/build.rs +++ b/stdlib/build.rs @@ -1,7 +1,7 @@ fn main() { #[allow(clippy::unusual_byte_groupings)] if let Ok(v) = std::env::var("DEP_OPENSSL_VERSION_NUMBER") { - println!("cargo:rustc-env=OPENSSL_API_VERSION={}", v); + println!("cargo:rustc-env=OPENSSL_API_VERSION={v}"); // cfg setup from openssl crate's build script let version = u64::from_str_radix(&v, 16).unwrap(); if version >= 0x1_00_01_00_0 { @@ -22,7 +22,7 @@ fn main() { } if let Ok(v) = std::env::var("DEP_OPENSSL_CONF") { for conf in v.split(',') { - println!("cargo:rustc-cfg=osslconf=\"{}\"", conf); + println!("cargo:rustc-cfg=osslconf=\"{conf}\""); } } } diff --git a/stdlib/src/array.rs b/stdlib/src/array.rs index 1188fc2a6c..cffaf3d36d 100644 --- a/stdlib/src/array.rs +++ b/stdlib/src/array.rs @@ -551,15 +551,13 @@ mod array { fn u32_to_char(ch: u32) -> Result { if ch > 0x10ffff { return Err(format!( - "character U+{:4x} is not in range [U+0000; U+10ffff]", - ch + "character U+{ch:4x} is not in range [U+0000; U+10ffff]" )); }; char::from_u32(ch).ok_or_else(|| { format!( - "'utf-8' codec can't encode character '\\u{:x}' \ - in position 0: surrogates not allowed", - ch + "'utf-8' codec can't encode character '\\u{ch:x}' \ + in position 0: surrogates not allowed" ) }) } @@ -638,8 +636,7 @@ mod array { (spec, ch) if spec == ch => array.frombytes(&init.get_bytes()), (spec, 'u') => { return Err(vm.new_type_error(format!( - "cannot use a unicode array to initialize an array with typecode '{}'", - spec + "cannot use a unicode array to initialize an array with typecode '{spec}'" ))) } _ => { @@ -654,8 +651,7 @@ mod array { array.frombytes_move(bytes); } else { return Err(vm.new_type_error(format!( - "cannot use a str to initialize an array with typecode '{}'", - spec + "cannot use a str to initialize an array with typecode '{spec}'" ))); } } else if init.payload_is::() || init.payload_is::() { @@ -1079,7 +1075,7 @@ mod array { let class_name = class.name(); if zelf.read().typecode() == 'u' { if zelf.len() == 0 { - return Ok(format!("{}('u')", class_name)); + return Ok(format!("{class_name}('u')")); } return Ok(format!( "{}('u', {})", diff --git a/stdlib/src/binascii.rs b/stdlib/src/binascii.rs index 35a4e268ad..d0bb23752c 100644 --- a/stdlib/src/binascii.rs +++ b/stdlib/src/binascii.rs @@ -184,7 +184,7 @@ mod decl { base64::decode(&buf) }) }) - .map_err(|err| new_binascii_error(format!("error decoding base64: {}", err), vm)) + .map_err(|err| new_binascii_error(format!("error decoding base64: {err}"), vm)) } #[pyfunction] diff --git a/stdlib/src/grp.rs b/stdlib/src/grp.rs index 78fd2f341d..86b826b79b 100644 --- a/stdlib/src/grp.rs +++ b/stdlib/src/grp.rs @@ -53,7 +53,7 @@ mod grp { let group = group.ok_or_else(|| { vm.new_key_error( vm.ctx - .new_str(format!("getgrgid: group id {} not found", gr_gid)) + .new_str(format!("getgrgid: group id {gr_gid} not found")) .into(), ) })?; @@ -70,7 +70,7 @@ mod grp { let group = group.ok_or_else(|| { vm.new_key_error( vm.ctx - .new_str(format!("getgrnam: group name {} not found", gr_name)) + .new_str(format!("getgrnam: group name {gr_name} not found")) .into(), ) })?; diff --git a/stdlib/src/hashlib.rs b/stdlib/src/hashlib.rs index e152eb9893..fd14e2989f 100644 --- a/stdlib/src/hashlib.rs +++ b/stdlib/src/hashlib.rs @@ -164,7 +164,7 @@ mod hashlib { data: args.data, usedforsecurity: args.usedforsecurity, }), - other => Err(vm.new_value_error(format!("Unknown hashing algorithm: {}", other))), + other => Err(vm.new_value_error(format!("Unknown hashing algorithm: {other}"))), } } diff --git a/stdlib/src/json/machinery.rs b/stdlib/src/json/machinery.rs index 7c9ac3ac4f..0568bab618 100644 --- a/stdlib/src/json/machinery.rs +++ b/stdlib/src/json/machinery.rs @@ -81,7 +81,7 @@ pub fn write_json_string(s: &str, ascii_only: bool, w: &mut W) -> write_start_idx = idx + c.len_utf8(); // codepoints outside the BMP get 2 '\uxxxx' sequences to represent them for point in c.encode_utf16(&mut [0; 2]) { - write!(w, "\\u{:04x}", point)?; + write!(w, "\\u{point:04x}")?; } } } @@ -195,19 +195,14 @@ pub fn scanstring<'a>( )); continue; } - _ => { - return Err(DecodeError::new( - format!("Invalid \\escape: {:?}", c), - char_i, - )) - } + _ => return Err(DecodeError::new(format!("Invalid \\escape: {c:?}"), char_i)), }; chunk_start = byte_i + 2; push_chunk(StrOrChar::Str(esc)); } '\x00'..='\x1f' if strict => { return Err(DecodeError::new( - format!("Invalid control character {:?} at", c), + format!("Invalid control character {c:?} at"), char_i, )); } diff --git a/stdlib/src/mmap.rs b/stdlib/src/mmap.rs index 32f5638aa4..06cc37d313 100644 --- a/stdlib/src/mmap.rs +++ b/stdlib/src/mmap.rs @@ -740,10 +740,7 @@ mod mmap { .map(|obj| { let name = obj.class().name().to_string(); obj.try_into_value::>(vm).map_err(|_| { - vm.new_type_error(format!( - "read argument must be int or None, not {}", - name, - )) + vm.new_type_error(format!("read argument must be int or None, not {name}",)) }) }) .transpose()? diff --git a/stdlib/src/pystruct.rs b/stdlib/src/pystruct.rs index 8d17a41116..e0200fc550 100644 --- a/stdlib/src/pystruct.rs +++ b/stdlib/src/pystruct.rs @@ -64,10 +64,7 @@ pub(crate) mod _struct { if (-offset) as usize > buffer_len { return Err(new_struct_error( vm, - format!( - "offset {} out of range for {}-byte buffer", - offset, buffer_len - ), + format!("offset {offset} out of range for {buffer_len}-byte buffer"), )); } buffer_len - (-offset as usize) @@ -98,12 +95,9 @@ pub(crate) mod _struct { Err(new_struct_error( vm, if is_pack { - format!("no space to pack {} bytes at offset {}", needed, offset) + format!("no space to pack {needed} bytes at offset {offset}") } else { - format!( - "not enough data to unpack {} bytes at offset {}", - needed, offset - ) + format!("not enough data to unpack {needed} bytes at offset {offset}") }, )) } else { diff --git a/stdlib/src/scproxy.rs b/stdlib/src/scproxy.rs index a9f1c14479..7108f50d8f 100644 --- a/stdlib/src/scproxy.rs +++ b/stdlib/src/scproxy.rs @@ -100,9 +100,9 @@ mod _scproxy { .and_then(|v| v.downcast::()) .and_then(|v| v.to_i32()) { - format!("http://{}:{}", h, port) + format!("http://{h}:{port}") } else { - format!("http://{}", h) + format!("http://{h}") }; result.set_item(proto, vm.new_pyobj(v), vm)?; } diff --git a/stdlib/src/socket.rs b/stdlib/src/socket.rs index af45753c83..8b9d4fb0c6 100644 --- a/stdlib/src/socket.rs +++ b/stdlib/src/socket.rs @@ -991,7 +991,7 @@ mod _socket { } Ok(addr6.into()) } - _ => Err(vm.new_os_error(format!("{}(): bad family", caller)).into()), + _ => Err(vm.new_os_error(format!("{caller}(): bad family")).into()), } } @@ -1954,7 +1954,7 @@ mod _socket { })?; Ok(get_ipv6_addr_str(Ipv6Addr::from(*packed_ip))) } - _ => Err(vm.new_value_error(format!("unknown address family {}", af_inet))), + _ => Err(vm.new_value_error(format!("unknown address family {af_inet}"))), } } diff --git a/stdlib/src/ssl.rs b/stdlib/src/ssl.rs index abb4ac95e6..9cca9db4fa 100644 --- a/stdlib/src/ssl.rs +++ b/stdlib/src/ssl.rs @@ -358,7 +358,7 @@ mod _ssl { _nid2obj(Nid::from_raw(nid)) .as_deref() .map(obj2py) - .ok_or_else(|| vm.new_value_error(format!("unknown NID {}", nid))) + .ok_or_else(|| vm.new_value_error(format!("unknown NID {nid}"))) } #[pyfunction] @@ -1153,9 +1153,9 @@ mod _ssl { // add `library` attribute let attr_name = vm.ctx.as_ref().intern_str("library"); cls.set_attr(attr_name, vm.ctx.new_str(lib).into()); - format!("[{}] {} ({}:{})", lib, errstr, file, line) + format!("[{lib}] {errstr} ({file}:{line})") } else { - format!("{} ({}:{})", errstr, file, line) + format!("{errstr} ({file}:{line})") }; // add `reason` attribute let attr_name = vm.ctx.as_ref().intern_str("reason"); @@ -1314,7 +1314,7 @@ mod _ssl { #[pyfunction] fn _test_decode_cert(path: PyPathLike, vm: &VirtualMachine) -> PyResult { - let pem = std::fs::read(&path).map_err(|e| e.to_pyexception(vm))?; + let pem = std::fs::read(path).map_err(|e| e.to_pyexception(vm))?; let x509 = X509::from_pem(&pem).map_err(|e| convert_openssl_error(vm, e))?; cert_to_py(vm, &x509, false) } diff --git a/stdlib/src/termios.rs b/stdlib/src/termios.rs index e0d2b10331..637e9185a6 100644 --- a/stdlib/src/termios.rs +++ b/stdlib/src/termios.rs @@ -211,8 +211,7 @@ mod termios { let cc = cc.borrow_vec(); let cc = <&[PyObjectRef; NCCS]>::try_from(&*cc).map_err(|_| { vm.new_type_error(format!( - "tcsetattr: attributes[6] must be {} element list", - NCCS + "tcsetattr: attributes[6] must be {NCCS} element list" )) })?; for (cc, x) in termios.c_cc.iter_mut().zip(cc.iter()) { diff --git a/stdlib/src/unicodedata.rs b/stdlib/src/unicodedata.rs index 6de44591fd..15ca35ed5c 100644 --- a/stdlib/src/unicodedata.rs +++ b/stdlib/src/unicodedata.rs @@ -82,7 +82,7 @@ mod unicodedata { return Ok(character.to_string()); } } - Err(vm.new_lookup_error(format!("undefined character name '{}'", name))) + Err(vm.new_lookup_error(format!("undefined character name '{name}'"))) } #[pymethod] diff --git a/vm/build.rs b/vm/build.rs index d13019ff64..c744c47440 100644 --- a/vm/build.rs +++ b/vm/build.rs @@ -31,7 +31,7 @@ fn main() { write!( f, "sysvars! {{ {} }}", - std::env::vars_os().format_with(", ", |(k, v), f| f(&format_args!("{:?} => {:?}", k, v))) + std::env::vars_os().format_with(", ", |(k, v), f| f(&format_args!("{k:?} => {v:?}"))) ) .unwrap(); } @@ -60,8 +60,8 @@ fn command(cmd: &str, args: &[&str]) -> String { match Command::new(cmd).args(args).output() { Ok(output) => match String::from_utf8(output.stdout) { Ok(s) => s, - Err(err) => format!("(output error: {})", err), + Err(err) => format!("(output error: {err})"), }, - Err(err) => format!("(command error: {})", err), + Err(err) => format!("(command error: {err})"), } } diff --git a/vm/src/builtins/bool.rs b/vm/src/builtins/bool.rs index a95488f31b..53085a963d 100644 --- a/vm/src/builtins/bool.rs +++ b/vm/src/builtins/bool.rs @@ -94,8 +94,7 @@ impl Constructor for PyBool { let actual_class = zelf.class(); let actual_type = &actual_class.name(); return Err(vm.new_type_error(format!( - "requires a 'type' object but received a '{}'", - actual_type + "requires a 'type' object but received a '{actual_type}'" ))); } let val = x.map_or(Ok(false), |val| val.try_to_bool(vm))?; diff --git a/vm/src/builtins/classmethod.rs b/vm/src/builtins/classmethod.rs index 76d44b9d86..fb11113051 100644 --- a/vm/src/builtins/classmethod.rs +++ b/vm/src/builtins/classmethod.rs @@ -150,7 +150,7 @@ impl PyClassMethod { ) { (None, _) => None, (Some(qualname), Some(module)) if module != "builtins" => { - Some(format!("<{}.{}({})>", module, qualname, callable)) + Some(format!("<{module}.{qualname}({callable})>")) } _ => Some(format!("<{}({})>", class.slot_name(), callable)), } diff --git a/vm/src/builtins/complex.rs b/vm/src/builtins/complex.rs index 8801f3f61f..4e39deed63 100644 --- a/vm/src/builtins/complex.rs +++ b/vm/src/builtins/complex.rs @@ -100,7 +100,7 @@ fn inner_div(v1: Complex64, v2: Complex64, vm: &VirtualMachine) -> PyResult PyResult { if v1.is_zero() { return if v2.im != 0.0 { - let msg = format!("{} cannot be raised to a negative or complex power", v1); + let msg = format!("{v1} cannot be raised to a negative or complex power"); Err(vm.new_zero_division_error(msg)) } else if v2.is_zero() { Ok(Complex64::new(1.0, 0.0)) diff --git a/vm/src/builtins/dict.rs b/vm/src/builtins/dict.rs index 06da56fba9..ba747bbf25 100644 --- a/vm/src/builtins/dict.rs +++ b/vm/src/builtins/dict.rs @@ -260,7 +260,7 @@ impl PyDict { for (key, value) in zelf { let key_repr = &key.repr(vm)?; let value_repr = value.repr(vm)?; - str_parts.push(format!("{}: {}", key_repr, value_repr)); + str_parts.push(format!("{key_repr}: {value_repr}")); } format!("{{{}}}", str_parts.join(", ")) diff --git a/vm/src/builtins/float.rs b/vm/src/builtins/float.rs index 1ba512f535..96b7f17a79 100644 --- a/vm/src/builtins/float.rs +++ b/vm/src/builtins/float.rs @@ -124,7 +124,7 @@ fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> { pub fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { if v1.is_zero() && v2.is_sign_negative() { - let msg = format!("{} cannot be raised to a negative power", v1); + let msg = format!("{v1} cannot be raised to a negative power"); Err(vm.new_zero_division_error(msg)) } else if v1.is_sign_negative() && (v2.floor() - v2).abs() > f64::EPSILON { let v1 = Complex64::new(v1, 0.); @@ -180,9 +180,7 @@ fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult { }; float_ops::parse_bytes(b).ok_or_else(|| { val.repr(vm) - .map(|repr| { - vm.new_value_error(format!("could not convert string to float: '{}'", repr)) - }) + .map(|repr| vm.new_value_error(format!("could not convert string to float: '{repr}'"))) .unwrap_or_else(|e| e) }) } diff --git a/vm/src/builtins/function.rs b/vm/src/builtins/function.rs index b23b0c8fee..3ad2ec6f5c 100644 --- a/vm/src/builtins/function.rs +++ b/vm/src/builtins/function.rs @@ -133,7 +133,7 @@ impl PyFunction { let slot = &mut fastlocals[pos]; if slot.is_some() { return Err( - vm.new_type_error(format!("Got multiple values for argument '{}'", name)) + vm.new_type_error(format!("Got multiple values for argument '{name}'")) ); } *slot = Some(value); @@ -143,7 +143,7 @@ impl PyFunction { posonly_passed_as_kwarg.push(name); } else { return Err( - vm.new_type_error(format!("got an unexpected keyword argument '{}'", name)) + vm.new_type_error(format!("got an unexpected keyword argument '{name}'")) ); } } @@ -251,7 +251,7 @@ impl PyFunction { // No default value and not specified. return Err( - vm.new_type_error(format!("Missing required kw only argument: '{}'", kwarg)) + vm.new_type_error(format!("Missing required kw only argument: '{kwarg}'")) ); } } diff --git a/vm/src/builtins/genericalias.rs b/vm/src/builtins/genericalias.rs index 082098643b..5214de37f4 100644 --- a/vm/src/builtins/genericalias.rs +++ b/vm/src/builtins/genericalias.rs @@ -106,7 +106,7 @@ impl PyGenericAlias { (Some(qualname), Some(module)) => Ok(if module == "builtins" { qualname } else { - format!("{}.{}", module, qualname) + format!("{module}.{qualname}") }), } } diff --git a/vm/src/builtins/module.rs b/vm/src/builtins/module.rs index df96d2dcbf..f907a538b0 100644 --- a/vm/src/builtins/module.rs +++ b/vm/src/builtins/module.rs @@ -53,11 +53,11 @@ impl PyModule { return vm.invoke(&getattr, (name,)); } let module_name = if let Some(name) = Self::name(zelf.to_owned(), vm) { - format!(" '{}'", name) + format!(" '{name}'") } else { "".to_owned() }; - Err(vm.new_attribute_error(format!("module{} has no attribute '{}'", module_name, name))) + Err(vm.new_attribute_error(format!("module{module_name} has no attribute '{name}'"))) } fn name(zelf: PyRef, vm: &VirtualMachine) -> Option { diff --git a/vm/src/builtins/namespace.rs b/vm/src/builtins/namespace.rs index aa13e2ee05..aec75659a0 100644 --- a/vm/src/builtins/namespace.rs +++ b/vm/src/builtins/namespace.rs @@ -61,7 +61,7 @@ impl PyNamespace { } format!("{}({})", name, parts.join(", ")) } else { - format!("{}(...)", name) + format!("{name}(...)") }; Ok(repr) } diff --git a/vm/src/builtins/object.rs b/vm/src/builtins/object.rs index 9c05f35f50..c30dcfeeb9 100644 --- a/vm/src/builtins/object.rs +++ b/vm/src/builtins/object.rs @@ -277,8 +277,7 @@ impl PyBaseObject { let value_class = value.class(); let type_repr = &value_class.name(); Err(vm.new_type_error(format!( - "__class__ must be set to a class, not '{}' object", - type_repr + "__class__ must be set to a class, not '{type_repr}' object" ))) } } diff --git a/vm/src/builtins/range.rs b/vm/src/builtins/range.rs index 1ff71081ee..1604dec9c0 100644 --- a/vm/src/builtins/range.rs +++ b/vm/src/builtins/range.rs @@ -308,7 +308,7 @@ impl PyRange { if let Ok(int) = needle.clone().downcast::() { match self.index_of(int.as_bigint()) { Some(idx) => Ok(idx), - None => Err(vm.new_value_error(format!("{} is not in range", int))), + None => Err(vm.new_value_error(format!("{int} is not in range"))), } } else { // Fallback to iteration. diff --git a/vm/src/builtins/set.rs b/vm/src/builtins/set.rs index 0fe511f589..c2ba6781f7 100644 --- a/vm/src/builtins/set.rs +++ b/vm/src/builtins/set.rs @@ -619,7 +619,7 @@ impl PySet { let borrowed_name = class.name(); let class_name = borrowed_name.deref(); let s = if zelf.inner.len() == 0 { - format!("{}()", class_name) + format!("{class_name}()") } else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { let name = if class_name != "set" { Some(class_name) @@ -628,7 +628,7 @@ impl PySet { }; zelf.inner.repr(name, vm)? } else { - format!("{}(...)", class_name) + format!("{class_name}(...)") }; Ok(s) } @@ -957,11 +957,11 @@ impl PyFrozenSet { let class = zelf.class(); let class_name = class.name(); let s = if inner.len() == 0 { - format!("{}()", class_name) + format!("{class_name}()") } else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { inner.repr(Some(&class_name), vm)? } else { - format!("{}(...)", class_name) + format!("{class_name}(...)") }; Ok(s) } @@ -1052,7 +1052,7 @@ impl TryFromObject for AnySet { { Ok(AnySet { object: obj }) } else { - Err(vm.new_type_error(format!("{} is not a subtype of set or frozenset", class))) + Err(vm.new_type_error(format!("{class} is not a subtype of set or frozenset"))) } } } diff --git a/vm/src/builtins/staticmethod.rs b/vm/src/builtins/staticmethod.rs index 1b27b9eaa0..44add3e4e0 100644 --- a/vm/src/builtins/staticmethod.rs +++ b/vm/src/builtins/staticmethod.rs @@ -152,7 +152,7 @@ impl PyStaticMethod { ) { (None, _) => None, (Some(qualname), Some(module)) if module != "builtins" => { - Some(format!("<{}.{}({})>", module, qualname, callable)) + Some(format!("<{module}.{qualname}({callable})>")) } _ => Some(format!("<{}({})>", class.slot_name(), callable)), } diff --git a/vm/src/builtins/super.rs b/vm/src/builtins/super.rs index 0ac178093d..7f2494292e 100644 --- a/vm/src/builtins/super.rs +++ b/vm/src/builtins/super.rs @@ -129,7 +129,7 @@ impl PySuper { let typname = &self.typ.name(); match self.obj { Some((_, ref ty)) => format!(", <{} object>>", typname, ty.name()), - None => format!(", NULL>", typname), + None => format!(", NULL>"), } } } diff --git a/vm/src/builtins/union.rs b/vm/src/builtins/union.rs index 7b9a65beff..29c9784f82 100644 --- a/vm/src/builtins/union.rs +++ b/vm/src/builtins/union.rs @@ -69,7 +69,7 @@ impl PyUnion { (Some(qualname), Some(module)) => Ok(if module == "builtins" { qualname } else { - format!("{}.{}", module, qualname) + format!("{module}.{qualname}") }), } } diff --git a/vm/src/builtins/weakref.rs b/vm/src/builtins/weakref.rs index 99fa681beb..8258280b8f 100644 --- a/vm/src/builtins/weakref.rs +++ b/vm/src/builtins/weakref.rs @@ -60,7 +60,7 @@ impl PyWeak { o.get_id(), ) } else { - format!("", id) + format!("") } } diff --git a/vm/src/bytesinner.rs b/vm/src/bytesinner.rs index c302381e34..24f539d527 100644 --- a/vm/src/bytesinner.rs +++ b/vm/src/bytesinner.rs @@ -450,8 +450,7 @@ impl PyBytesInner { }; Err(vm.new_value_error(format!( - "non-hexadecimal number found in fromhex() arg at position {}", - i + "non-hexadecimal number found in fromhex() arg at position {i}" ))) } diff --git a/vm/src/cformat.rs b/vm/src/cformat.rs index a9e1c95343..1281982b9f 100644 --- a/vm/src/cformat.rs +++ b/vm/src/cformat.rs @@ -192,9 +192,9 @@ impl CFormatSpec { // arguments, the LEFT_ADJUST flag will be used by a later call to fill_string with // the 0-filled string as the string param. if !fill_with_precision && self.flags.contains(CConversionFlags::LEFT_ADJUST) { - format!("{}{}", string, fill_string) + format!("{string}{fill_string}") } else { - format!("{}{}", fill_string, string) + format!("{fill_string}{string}") } } else { string @@ -286,7 +286,7 @@ impl CFormatSpec { } else { ' ' // '-' overrides the '0' conversion if both are given }; - let signed_prefix = format!("{}{}", sign_string, prefix); + let signed_prefix = format!("{sign_string}{prefix}"); format!( "{}{}", signed_prefix, @@ -299,7 +299,7 @@ impl CFormatSpec { ) } else { self.fill_string( - format!("{}{}{}", sign_string, prefix, padded_magnitude_string), + format!("{sign_string}{prefix}{padded_magnitude_string}"), ' ', None, false, @@ -371,12 +371,7 @@ impl CFormatSpec { ) ) } else { - self.fill_string( - format!("{}{}", sign_string, magnitude_string), - ' ', - None, - false, - ) + self.fill_string(format!("{sign_string}{magnitude_string}"), ' ', None, false) } } @@ -450,7 +445,7 @@ impl CFormatSpec { if e.fast_isinstance(vm.ctx.exceptions.type_error) { // formatfloat in bytesobject.c generates its own specific exception // text in this case, mirror it here. - vm.new_type_error(format!("float argument required, not {}", type_name)) + vm.new_type_error(format!("float argument required, not {type_name}")) } else { e } @@ -1366,8 +1361,7 @@ mod tests { let result = fmt.parse::(); assert_eq!( result, expected, - "left = {:#?} \n\n\n right = {:#?}", - result, expected + "left = {result:#?} \n\n\n right = {expected:#?}" ); } } diff --git a/vm/src/codecs.rs b/vm/src/codecs.rs index b0eac7ad85..af3563fbc1 100644 --- a/vm/src/codecs.rs +++ b/vm/src/codecs.rs @@ -242,7 +242,7 @@ impl CodecsRegistry { return Ok(codec.clone()); } } - Err(vm.new_lookup_error(format!("unknown encoding: {}", encoding))) + Err(vm.new_lookup_error(format!("unknown encoding: {encoding}"))) } fn _lookup_text_encoding( @@ -256,8 +256,7 @@ impl CodecsRegistry { Ok(codec) } else { Err(vm.new_lookup_error(format!( - "'{}' is not a text encoding; use {} to handle arbitrary codecs", - encoding, generic_func + "'{encoding}' is not a text encoding; use {generic_func} to handle arbitrary codecs" ))) } } @@ -338,7 +337,7 @@ impl CodecsRegistry { pub fn lookup_error(&self, name: &str, vm: &VirtualMachine) -> PyResult { self.lookup_error_opt(name) - .ok_or_else(|| vm.new_lookup_error(format!("unknown error handler name '{}'", name))) + .ok_or_else(|| vm.new_lookup_error(format!("unknown error handler name '{name}'"))) } } @@ -440,7 +439,7 @@ fn backslashreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(S let b = PyBytesRef::try_from_object(vm, err.get_attr("object", vm)?)?; let mut replace = String::with_capacity(4 * range.len()); for &c in &b[range.clone()] { - write!(replace, "\\x{:02x}", c).unwrap(); + write!(replace, "\\x{c:02x}").unwrap(); } return Ok((replace, range.end)); } else if !is_encode_ish_err(&err, vm) { @@ -455,11 +454,11 @@ fn backslashreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(S for c in s_after_start.chars().take(num_chars) { let c = c as u32; if c >= 0x10000 { - write!(out, "\\U{:08x}", c).unwrap(); + write!(out, "\\U{c:08x}").unwrap(); } else if c >= 0x100 { - write!(out, "\\u{:04x}", c).unwrap(); + write!(out, "\\u{c:04x}").unwrap(); } else { - write!(out, "\\x{:02x}", c).unwrap(); + write!(out, "\\x{c:02x}").unwrap(); } } Ok((out, range.end)) diff --git a/vm/src/dictdatatype.rs b/vm/src/dictdatatype.rs index 2a5f2bf014..8c35afba60 100644 --- a/vm/src/dictdatatype.rs +++ b/vm/src/dictdatatype.rs @@ -912,8 +912,8 @@ mod tests { dict.insert(vm, &*key1, value2.clone()).unwrap(); assert_eq!(2, dict.len()); - assert_eq!(true, dict.contains(vm, &*key1).unwrap()); - assert_eq!(true, dict.contains(vm, "x").unwrap()); + assert!(dict.contains(vm, &*key1).unwrap()); + assert!(dict.contains(vm, "x").unwrap()); let val = dict.get(vm, "x").unwrap().unwrap(); vm.bool_eq(&val, &value2) diff --git a/vm/src/exceptions.rs b/vm/src/exceptions.rs index 7a59a376f5..02c4d3ec2d 100644 --- a/vm/src/exceptions.rs +++ b/vm/src/exceptions.rs @@ -45,10 +45,10 @@ impl VirtualMachine { if let Ok(stderr) = sys::get_stderr(vm) { let mut stderr = py_io::PyWriter(stderr, vm); // if this fails stderr might be closed -- ignore it - let _ = writeln!(stderr, "{}", errstr); + let _ = writeln!(stderr, "{errstr}"); let _ = self.write_exception(&mut stderr, exc); } else { - eprintln!("{}\nlost sys.stderr", errstr); + eprintln!("{errstr}\nlost sys.stderr"); let _ = self.write_exception(&mut py_io::IoWriter(io::stderr()), exc); } }; @@ -106,7 +106,7 @@ impl VirtualMachine { } { if !seen.contains(&cause_or_context.get_id()) { self.write_exception_recursive(output, &cause_or_context, seen)?; - writeln!(output, "{}", msg)?; + writeln!(output, "{msg}")?; } else { seen.insert(cause_or_context.get_id()); } @@ -135,7 +135,7 @@ impl VirtualMachine { let exc_class = exc.class(); let exc_name = exc_class.name(); match args_repr.len() { - 0 => write!(output, "{}", exc_name), + 0 => write!(output, "{exc_name}"), 1 => write!(output, "{}: {}", exc_name, args_repr[0]), _ => write!( output, @@ -900,7 +900,7 @@ fn os_error_str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult format!("[Errno {}] {}: '{}'", errno, msg, filename.str(vm)?), }, Err(_) => { - format!("[Errno {}] {}", errno, msg) + format!("[Errno {errno}] {msg}") } }; Ok(vm.ctx.new_str(s)) diff --git a/vm/src/format.rs b/vm/src/format.rs index e3a27b65e9..1d4ab6c000 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -567,10 +567,7 @@ impl FormatSpec { FormatSpec::compute_fill_string(fill_char, left_fill_chars_needed); let right_fill_string = FormatSpec::compute_fill_string(fill_char, right_fill_chars_needed); - format!( - "{}{}{}{}", - left_fill_string, sign_str, magnitude_string, right_fill_string - ) + format!("{left_fill_string}{sign_str}{magnitude_string}{right_fill_string}") } }) } diff --git a/vm/src/frame.rs b/vm/src/frame.rs index bfe3dd6290..63089a48f2 100644 --- a/vm/src/frame.rs +++ b/vm/src/frame.rs @@ -463,15 +463,12 @@ impl ExecutingFrame<'_> { if let Some(&name) = self.code.cellvars.get(i) { vm.new_exception_msg( vm.ctx.exceptions.unbound_local_error.to_owned(), - format!("local variable '{}' referenced before assignment", name), + format!("local variable '{name}' referenced before assignment"), ) } else { let name = self.code.freevars[i - self.code.cellvars.len()]; vm.new_name_error( - format!( - "free variable '{}' referenced before assignment in enclosing scope", - name - ), + format!("free variable '{name}' referenced before assignment in enclosing scope"), name.to_owned(), ) } @@ -1063,7 +1060,7 @@ impl ExecutingFrame<'_> { self.globals .get_chain(self.builtins, name, vm)? .ok_or_else(|| { - vm.new_name_error(format!("name '{}' is not defined", name), name.to_owned()) + vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned()) }) } @@ -1103,7 +1100,7 @@ impl ExecutingFrame<'_> { fn import_from(&mut self, vm: &VirtualMachine, idx: bytecode::NameIdx) -> PyResult { let module = self.last_value(); let name = self.code.names[idx as usize]; - let err = || vm.new_import_error(format!("cannot import name '{}'", name), name); + let err = || vm.new_import_error(format!("cannot import name '{name}'"), name); // Load attribute, and transform any error into import error. if let Some(obj) = vm.get_attribute_opt(module.clone(), name)? { return Ok(obj); @@ -1113,7 +1110,7 @@ impl ExecutingFrame<'_> { .get_attr(identifier!(vm, __name__), vm) .map_err(|_| err())?; let mod_name = mod_name.downcast::().map_err(|_| err())?; - let full_mod_name = format!("{}.{}", mod_name, name); + let full_mod_name = format!("{mod_name}.{name}"); let sys_modules = vm .sys_module .clone() @@ -1706,7 +1703,7 @@ impl ExecutingFrame<'_> { return Ok(None); } std::cmp::Ordering::Greater => { - format!("too many values to unpack (expected {})", size) + format!("too many values to unpack (expected {size})") } std::cmp::Ordering::Less => format!( "not enough values to unpack (expected {}, got {})", @@ -1890,14 +1887,14 @@ impl fmt::Debug for Frame { if elem.payload_is::() { "\n > {frame}".to_owned() } else { - format!("\n > {:?}", elem) + format!("\n > {elem:?}") } }) .collect::(); let block_str = state .blocks .iter() - .map(|elem| format!("\n > {:?}", elem)) + .map(|elem| format!("\n > {elem:?}")) .collect::(); // TODO: fix this up let locals = self.locals.clone(); diff --git a/vm/src/function/argument.rs b/vm/src/function/argument.rs index 9e78714868..ab1eab6f42 100644 --- a/vm/src/function/argument.rs +++ b/vm/src/function/argument.rs @@ -158,8 +158,7 @@ impl FuncArgs { let kwarg_class = kwarg.class(); let actual_ty_name = &kwarg_class.name(); Err(vm.new_type_error(format!( - "argument of type {} is required for named parameter `{}` (got: {})", - expected_ty_name, key, actual_ty_name + "argument of type {expected_ty_name} is required for named parameter `{key}` (got: {actual_ty_name})" ))) } } @@ -217,7 +216,7 @@ impl FuncArgs { self.kwargs .keys() .next() - .map(|k| vm.new_type_error(format!("Unexpected keyword argument {}", k))) + .map(|k| vm.new_type_error(format!("Unexpected keyword argument {k}"))) } } @@ -262,10 +261,10 @@ impl ArgumentError { num_given )), ArgumentError::InvalidKeywordArgument(name) => { - vm.new_type_error(format!("{} is an invalid keyword argument", name)) + vm.new_type_error(format!("{name} is an invalid keyword argument")) } ArgumentError::RequiredKeywordArgument(name) => { - vm.new_type_error(format!("Required keyqord only argument {}", name)) + vm.new_type_error(format!("Required keyqord only argument {name}")) } ArgumentError::Exception(ex) => ex, } diff --git a/vm/src/import.rs b/vm/src/import.rs index b8b35d1772..2487908e54 100644 --- a/vm/src/import.rs +++ b/vm/src/import.rs @@ -73,9 +73,10 @@ pub(crate) fn init_importlib_package( } pub fn make_frozen(vm: &VirtualMachine, name: &str) -> PyResult> { - let frozen = vm.state.frozen.get(name).ok_or_else(|| { - vm.new_import_error(format!("No such frozen object named {}", name), name) - })?; + let frozen = + vm.state.frozen.get(name).ok_or_else(|| { + vm.new_import_error(format!("No such frozen object named {name}"), name) + })?; Ok(vm.ctx.new_code(frozen.code.clone())) } @@ -89,7 +90,7 @@ pub fn import_builtin(vm: &VirtualMachine, module_name: &str) -> PyResult { .get(module_name) .ok_or_else(|| { vm.new_import_error( - format!("Cannot import builtin module {}", module_name), + format!("Cannot import builtin module {module_name}"), module_name, ) }) diff --git a/vm/src/protocol/buffer.rs b/vm/src/protocol/buffer.rs index 4f8ec3aad7..14273b7137 100644 --- a/vm/src/protocol/buffer.rs +++ b/vm/src/protocol/buffer.rs @@ -255,7 +255,7 @@ impl BufferDescriptor { .zip_eq(self.dim_desc.iter().cloned()) { let i = i.wrapped_at(shape).ok_or_else(|| { - vm.new_index_error(format!("index out of bounds on dimension {}", i)) + vm.new_index_error(format!("index out of bounds on dimension {i}")) })?; pos += i as isize * stride + suboffset; } diff --git a/vm/src/readline.rs b/vm/src/readline.rs index 4e3db463bf..0b380e3156 100644 --- a/vm/src/readline.rs +++ b/vm/src/readline.rs @@ -41,7 +41,7 @@ mod basic_readline { pub fn readline(&mut self, prompt: &str) -> ReadlineResult { use std::io::prelude::*; - print!("{}", prompt); + print!("{prompt}"); if let Err(e) = io::stdout().flush() { return ReadlineResult::Io(e); } diff --git a/vm/src/stdlib/ast.rs b/vm/src/stdlib/ast.rs index 82710272fe..7f431e1cc0 100644 --- a/vm/src/stdlib/ast.rs +++ b/vm/src/stdlib/ast.rs @@ -78,9 +78,8 @@ mod _ast { } fn get_node_field(vm: &VirtualMachine, obj: &PyObject, field: &str, typ: &str) -> PyResult { - vm.get_attribute_opt(obj.to_owned(), field)?.ok_or_else(|| { - vm.new_type_error(format!("required field \"{}\" missing from {}", field, typ)) - }) + vm.get_attribute_opt(obj.to_owned(), field)? + .ok_or_else(|| vm.new_type_error(format!("required field \"{field}\" missing from {typ}"))) } fn get_node_field_opt( diff --git a/vm/src/stdlib/builtins.rs b/vm/src/stdlib/builtins.rs index 6c825c9006..9fb8e6d74a 100644 --- a/vm/src/stdlib/builtins.rs +++ b/vm/src/stdlib/builtins.rs @@ -73,7 +73,7 @@ mod builtins { if x.is_negative() { format!("-0b{:b}", x.abs()) } else { - format!("0b{:b}", x) + format!("0b{x:b}") } } @@ -303,8 +303,7 @@ mod builtins { if !code_obj.freevars.is_empty() { return Err(vm.new_type_error(format!( - "code object passed to {}() may not contain free variables", - func + "code object passed to {func}() may not contain free variables" ))); } @@ -368,7 +367,7 @@ mod builtins { #[pyfunction] fn hex(number: PyIntRef) -> String { let n = number.as_bigint(); - format!("{:#x}", n) + format!("{n:#x}") } #[pyfunction] @@ -478,8 +477,7 @@ mod builtins { std::cmp::Ordering::Greater => { if default.is_some() { return Err(vm.new_type_error(format!( - "Cannot specify a default for {}() with multiple positional arguments", - func_name + "Cannot specify a default for {func_name}() with multiple positional arguments" ))); } args.args @@ -488,7 +486,7 @@ mod builtins { std::cmp::Ordering::Less => { // zero arguments means type error: return Err( - vm.new_type_error(format!("{} expected at least 1 argument, got 0", func_name)) + vm.new_type_error(format!("{func_name} expected at least 1 argument, got 0")) ); } }; @@ -498,7 +496,7 @@ mod builtins { Some(x) => x, None => { return default.ok_or_else(|| { - vm.new_value_error(format!("{}() arg is an empty sequence", func_name)) + vm.new_value_error(format!("{func_name}() arg is an empty sequence")) }) } }; @@ -560,7 +558,7 @@ mod builtins { let s = if n.is_negative() { format!("-0o{:o}", n.abs()) } else { - format!("0o{:o}", n) + format!("0o{n:o}") }; Ok(vm.ctx.new_str(s).into()) @@ -573,8 +571,7 @@ mod builtins { let bytes_len = bytes.len(); if bytes_len != 1 { return Err(vm.new_type_error(format!( - "ord() expected a character, but string of length {} found", - bytes_len + "ord() expected a character, but string of length {bytes_len} found" ))); } Ok(u32::from(bytes[0])) @@ -584,8 +581,7 @@ mod builtins { let string_len = string.chars().count(); if string_len != 1 { return Err(vm.new_type_error(format!( - "ord() expected a character, but string of length {} found", - string_len + "ord() expected a character, but string of length {string_len} found" ))); } match string.chars().next() { @@ -939,15 +935,13 @@ mod builtins { if let Some(ref classcell) = classcell { let classcell = classcell.get().ok_or_else(|| { vm.new_type_error(format!( - "__class__ not set defining {:?} as {:?}. Was __classcell__ propagated to type.__new__?", - meta_name, class + "__class__ not set defining {meta_name:?} as {class:?}. Was __classcell__ propagated to type.__new__?" )) })?; if !classcell.is(&class) { return Err(vm.new_type_error(format!( - "__class__ set to {:?} defining {:?} as {:?}", - classcell, meta_name, class + "__class__ set to {classcell:?} defining {meta_name:?} as {class:?}" ))); } } diff --git a/vm/src/stdlib/codecs.rs b/vm/src/stdlib/codecs.rs index 478b0a7529..6e7779fa8c 100644 --- a/vm/src/stdlib/codecs.rs +++ b/vm/src/stdlib/codecs.rs @@ -212,7 +212,7 @@ mod _codecs { fn error_oob_restart(&self, i: usize) -> PyBaseExceptionRef { self.vm - .new_index_error(format!("position {} from error handler out of bounds", i)) + .new_index_error(format!("position {i} from error handler out of bounds")) } fn error_encoding( diff --git a/vm/src/stdlib/collections.rs b/vm/src/stdlib/collections.rs index 4f9c2226d1..3dda3eabb6 100644 --- a/vm/src/stdlib/collections.rs +++ b/vm/src/stdlib/collections.rs @@ -173,7 +173,7 @@ mod _collections { Err(vm.new_value_error( needle .repr(vm) - .map(|repr| format!("{} is not in deque", repr)) + .map(|repr| format!("{repr} is not in deque")) .unwrap_or_else(|_| String::new()), )) } @@ -302,11 +302,11 @@ mod _collections { let class_name = class.name(); let closing_part = zelf .maxlen - .map(|maxlen| format!("], maxlen={}", maxlen)) + .map(|maxlen| format!("], maxlen={maxlen}")) .unwrap_or_else(|| "]".to_owned()); let s = if zelf.len() == 0 { - format!("{}([{})", class_name, closing_part) + format!("{class_name}([{closing_part})") } else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { collection_repr(Some(&class_name), "[", &closing_part, deque.iter(), vm)? } else { diff --git a/vm/src/stdlib/imp.rs b/vm/src/stdlib/imp.rs index 376c02f83a..f5a1eddf2e 100644 --- a/vm/src/stdlib/imp.rs +++ b/vm/src/stdlib/imp.rs @@ -113,9 +113,7 @@ mod _imp { .frozen .get(name.as_str()) .map(|frozen| frozen.package) - .ok_or_else(|| { - vm.new_import_error(format!("No such frozen object named {}", name), name) - }) + .ok_or_else(|| vm.new_import_error(format!("No such frozen object named {name}"), name)) } #[pyfunction] diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index d5aef0327c..a5bff75ac4 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -88,8 +88,7 @@ impl TryFromObject for Fildes { let fd = int.try_to_primitive(vm)?; if fd < 0 { return Err(vm.new_value_error(format!( - "file descriptor cannot be a negative integer ({})", - fd + "file descriptor cannot be a negative integer ({fd})" ))); } Ok(Fildes(fd)) @@ -183,7 +182,7 @@ mod _io { if v >= 0 { Ok(v as usize) } else { - Err(vm.new_value_error(format!("Negative size value {}", v))) + Err(vm.new_value_error(format!("Negative size value {v}"))) } }) .transpose() @@ -843,7 +842,7 @@ mod _io { let offset = get_offset(ret, vm)?; if offset < 0 { return Err( - vm.new_os_error(format!("Raw stream returned invalid position {}", offset)) + vm.new_os_error(format!("Raw stream returned invalid position {offset}")) ); } self.abs_pos = offset; @@ -888,7 +887,7 @@ mod _io { let offset = get_offset(ret, vm)?; if offset < 0 { return Err( - vm.new_os_error(format!("Raw stream returned invalid position {}", offset)) + vm.new_os_error(format!("Raw stream returned invalid position {offset}")) ); } self.abs_pos = offset; @@ -941,8 +940,7 @@ mod _io { let n = isize::try_from_object(vm, res)?; if n < 0 || n as usize > len { return Err(vm.new_os_error(format!( - "raw write() returned invalid length {} (should have been between 0 and {})", - n, len + "raw write() returned invalid length {n} (should have been between 0 and {len})" ))); } if self.abs_pos != -1 { @@ -1173,8 +1171,7 @@ mod _io { let n = isize::try_from_object(vm, res)?; if n < 0 || n as usize > len { return Err(vm.new_os_error(format!( - "raw readinto() returned invalid length {} (should have been between 0 and {})", - n, len + "raw readinto() returned invalid length {n} (should have been between 0 and {len})" ))); } if n > 0 && self.abs_pos != -1 { @@ -1457,7 +1454,7 @@ mod _io { ) -> PyResult { let whence = whence.unwrap_or(0); if !validate_whence(whence) { - return Err(vm.new_value_error(format!("whence value {} unsupported", whence))); + return Err(vm.new_value_error(format!("whence value {whence} unsupported"))); } let mut data = self.lock(vm)?; let raw = data.check_init(vm)?; @@ -1540,9 +1537,9 @@ mod _io { let cls = zelf.class(); let slot_name = cls.slot_name(); let repr = if let Some(name_repr) = name_repr { - format!("<{} name={}>", slot_name, name_repr) + format!("<{slot_name} name={name_repr}>") } else { - format!("<{}>", slot_name) + format!("<{slot_name}>") }; Ok(repr) } @@ -1961,7 +1958,7 @@ mod _io { "\n" => Self::Lf, "\r" => Self::Cr, "\r\n" => Self::Crlf, - _ => return Err(vm.new_value_error(format!("illegal newline value: {}", s))), + _ => return Err(vm.new_value_error(format!("illegal newline value: {s}"))), } }; Ok(nl) @@ -2405,8 +2402,9 @@ mod _io { } } _ => { - return Err(vm - .new_value_error(format!("invalid whence ({}, should be 0, 1 or 2)", how))) + return Err( + vm.new_value_error(format!("invalid whence ({how}, should be 0, 1 or 2)")) + ) } }; use crate::types::PyComparisonOp; @@ -3480,7 +3478,7 @@ mod _io { impl ParseModeError { fn error_msg(&self, mode_string: &str) -> String { match self { - ParseModeError::InvalidMode => format!("invalid mode: '{}'", mode_string), + ParseModeError::InvalidMode => format!("invalid mode: '{mode_string}'"), ParseModeError::MultipleFile => { "must have exactly one of create/read/write/append mode".to_owned() } @@ -3759,7 +3757,7 @@ mod fileio { impl ModeError { fn error_msg(&self, mode_str: &str) -> String { match self { - ModeError::Invalid => format!("invalid mode: {}", mode_str), + ModeError::Invalid => format!("invalid mode: {mode_str}"), ModeError::BadRwa => { "Must have exactly one of create/read/write/append mode and at most one plus" .to_owned() @@ -3894,7 +3892,7 @@ mod fileio { } let fd = i32::try_from_object(vm, fd)?; if fd < 0 { - return Err(vm.new_value_error(format!("opener returned {}", fd))); + return Err(vm.new_value_error(format!("opener returned {fd}"))); } fd } else if let Some(i) = name.payload::() { @@ -3992,12 +3990,9 @@ mod fileio { let mode = zelf.mode(); let closefd = if zelf.closefd.load() { "True" } else { "False" }; let repr = if let Some(name_repr) = name_repr { - format!( - "<_io.FileIO name={} mode='{}' closefd={}>", - name_repr, mode, closefd - ) + format!("<_io.FileIO name={name_repr} mode='{mode}' closefd={closefd}>") } else { - format!("<_io.FileIO fd={} mode='{}' closefd={}>", fd, mode, closefd) + format!("<_io.FileIO fd={fd} mode='{mode}' closefd={closefd}>") }; Ok(repr) } diff --git a/vm/src/stdlib/itertools.rs b/vm/src/stdlib/itertools.rs index 9d45b26d80..2b605b920f 100644 --- a/vm/src/stdlib/itertools.rs +++ b/vm/src/stdlib/itertools.rs @@ -273,7 +273,7 @@ mod decl { let cur = format!("{}", self.cur.read().clone().repr(vm)?); let step = &self.step; if vm.bool_eq(step, vm.ctx.new_int(1).as_object())? { - return Ok(format!("count({})", cur)); + return Ok(format!("count({cur})")); } Ok(format!("count({}, {})", cur, step.repr(vm)?)) } @@ -404,7 +404,7 @@ mod decl { fmt.push_str(", "); fmt.push_str(×.read().to_string()); } - Ok(format!("repeat({})", fmt)) + Ok(format!("repeat({fmt})")) } } @@ -857,8 +857,7 @@ mod decl { } // We don't have an int or value was < 0 or > sys.maxsize Err(vm.new_value_error(format!( - "{} argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.", - name + "{name} argument for islice() must be None or an integer: 0 <= x <= sys.maxsize." ))) } diff --git a/vm/src/stdlib/operator.rs b/vm/src/stdlib/operator.rs index eb29b38677..f3cbfc4981 100644 --- a/vm/src/stdlib/operator.rs +++ b/vm/src/stdlib/operator.rs @@ -369,7 +369,7 @@ mod _operator { } else { "...".to_owned() }; - Ok(format!("operator.attrgetter({})", fmt)) + Ok(format!("operator.attrgetter({fmt})")) } #[pymethod(magic)] @@ -465,7 +465,7 @@ mod _operator { } else { "...".to_owned() }; - Ok(format!("operator.itemgetter({})", fmt)) + Ok(format!("operator.itemgetter({fmt})")) } #[pymethod(magic)] @@ -541,7 +541,7 @@ mod _operator { let mut parts = Vec::with_capacity(kwargs.len()); for (key, value) in kwargs { let value_repr = value.repr(vm)?; - parts.push(format!("{}={}", key, value_repr)); + parts.push(format!("{key}={value_repr}")); } fmt.push(parts.join(", ")); } @@ -549,7 +549,7 @@ mod _operator { } else { "...".to_owned() }; - Ok(format!("operator.methodcaller({})", fmt)) + Ok(format!("operator.methodcaller({fmt})")) } #[pymethod(magic)] diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index 78f3b71666..6862ad0af4 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -1609,7 +1609,7 @@ pub(super) mod _os { // TODO: just call libc::truncate() on POSIX let f = OpenOptions::new() .write(true) - .open(&path) + .open(path) .map_err(|e| e.into_pyexception(vm))?; f.set_len(length as u64) .map_err(|e| e.into_pyexception(vm))?; @@ -1637,7 +1637,7 @@ pub(super) mod _os { #[pyfunction] fn waitstatus_to_exitcode(status: i32, vm: &VirtualMachine) -> PyResult { let status = u32::try_from(status) - .map_err(|_| vm.new_value_error(format!("invalid WEXITSTATUS: {}", status)))?; + .map_err(|_| vm.new_value_error(format!("invalid WEXITSTATUS: {status}")))?; cfg_if::cfg_if! { if #[cfg(not(windows))] { @@ -1650,7 +1650,7 @@ pub(super) mod _os { return Ok(-libc::WTERMSIG(status)); } - Err(vm.new_value_error(format!("Invalid wait status: {}", status))) + Err(vm.new_value_error(format!("Invalid wait status: {status}"))) } else { i32::try_from(status.rotate_right(8)) .map_err(|_| vm.new_value_error(format!("invalid wait status: {}", status))) diff --git a/vm/src/stdlib/posix.rs b/vm/src/stdlib/posix.rs index dbdcc2f40c..728dbe833d 100644 --- a/vm/src/stdlib/posix.rs +++ b/vm/src/stdlib/posix.rs @@ -268,7 +268,7 @@ pub mod module { ) })?; - let metadata = fs::metadata(&path.path); + let metadata = fs::metadata(path.path); // if it's only checking for F_OK if flags == AccessFlags::F_OK { @@ -1012,10 +1012,10 @@ pub mod module { match i.cmp(&-1) { Ordering::Greater => Ok(Some(i.try_into().map_err(|_| { - vm.new_overflow_error(format!("{} is larger than maximum", typ_name)) + vm.new_overflow_error(format!("{typ_name} is larger than maximum")) })?)), Ordering::Less => { - Err(vm.new_overflow_error(format!("{} is less than minimum", typ_name))) + Err(vm.new_overflow_error(format!("{typ_name} is less than minimum"))) } Ordering::Equal => Ok(None), // -1 means does not change the value } @@ -1371,7 +1371,7 @@ pub mod module { for sig in sigs.iter(vm)? { let sig = sig?; let sig = signal::Signal::try_from(sig).map_err(|_| { - vm.new_value_error(format!("signal number {} out of range", sig)) + vm.new_value_error(format!("signal number {sig} out of range")) })?; set.add(sig); } @@ -1604,7 +1604,7 @@ pub mod module { slice .to_str() .map(|s| s.to_owned()) - .map_err(|e| vm.new_unicode_decode_error(format!("unable to decode login name: {}", e))) + .map_err(|e| vm.new_unicode_decode_error(format!("unable to decode login name: {e}"))) } // cfg from nix diff --git a/vm/src/stdlib/pwd.rs b/vm/src/stdlib/pwd.rs index a6a49dc1aa..f5d1e50a26 100644 --- a/vm/src/stdlib/pwd.rs +++ b/vm/src/stdlib/pwd.rs @@ -61,7 +61,7 @@ mod pwd { let user = user.ok_or_else(|| { vm.new_key_error( vm.ctx - .new_str(format!("getpwnam(): name not found: {}", pw_name)) + .new_str(format!("getpwnam(): name not found: {pw_name}")) .into(), ) })?; diff --git a/vm/src/stdlib/signal.rs b/vm/src/stdlib/signal.rs index 173dee28c3..c434108284 100644 --- a/vm/src/stdlib/signal.rs +++ b/vm/src/stdlib/signal.rs @@ -230,9 +230,7 @@ pub(crate) mod _signal { let nonblock = fcntl::OFlag::from_bits_truncate(oflags).contains(fcntl::OFlag::O_NONBLOCK); if !nonblock { - return Err( - vm.new_value_error(format!("the fd {} must be in non-blocking mode", fd)) - ); + return Err(vm.new_value_error(format!("the fd {fd} must be in non-blocking mode"))); } } diff --git a/vm/src/stdlib/sre.rs b/vm/src/stdlib/sre.rs index 725f4d950d..23e6725e5d 100644 --- a/vm/src/stdlib/sre.rs +++ b/vm/src/stdlib/sre.rs @@ -375,9 +375,9 @@ mod _sre { }; if flags.is_empty() { - Ok(format!("re.compile({})", s)) + Ok(format!("re.compile({s})")) } else { - Ok(format!("re.compile({}, {})", s, flags)) + Ok(format!("re.compile({s}, {flags})")) } } diff --git a/vm/src/stdlib/symtable.rs b/vm/src/stdlib/symtable.rs index dff69d8cc0..cf741a1b96 100644 --- a/vm/src/stdlib/symtable.rs +++ b/vm/src/stdlib/symtable.rs @@ -92,7 +92,7 @@ mod symtable { } .into_ref(vm)) } else { - Err(vm.new_key_error(vm.ctx.new_str(format!("lookup {} failed", name)).into())) + Err(vm.new_key_error(vm.ctx.new_str(format!("lookup {name} failed")).into())) } } diff --git a/vm/src/stdlib/sys.rs b/vm/src/stdlib/sys.rs index dc6ddc2b05..af64aab048 100644 --- a/vm/src/stdlib/sys.rs +++ b/vm/src/stdlib/sys.rs @@ -619,8 +619,7 @@ mod sys { Ok(()) } else { Err(vm.new_recursion_error(format!( - "cannot set the recursion limit to {} at the recursion depth {}: the limit is too low", - recursion_limit, recursion_depth + "cannot set the recursion limit to {recursion_limit} at the recursion depth {recursion_depth}: the limit is too low" ))) } } @@ -920,7 +919,7 @@ impl PyStderr<'_> { return; } } - eprint!("{}", args) + eprint!("{args}") } } diff --git a/vm/src/stdlib/sysconfigdata.rs b/vm/src/stdlib/sysconfigdata.rs index 4ed2c6123c..929227ac11 100644 --- a/vm/src/stdlib/sysconfigdata.rs +++ b/vm/src/stdlib/sysconfigdata.rs @@ -14,7 +14,7 @@ pub(crate) mod _sysconfigdata { } sysvars! { // fake shared module extension - "EXT_SUFFIX" => format!(".rustpython-{}", MULTIARCH), + "EXT_SUFFIX" => format!(".rustpython-{MULTIARCH}"), "MULTIARCH" => MULTIARCH, // enough for tests to stop expecting urandom() to fail after restricting file resources "HAVE_GETRANDOM" => 1, diff --git a/vm/src/stdlib/time.rs b/vm/src/stdlib/time.rs index e406c91785..ce1f4d88a0 100644 --- a/vm/src/stdlib/time.rs +++ b/vm/src/stdlib/time.rs @@ -52,7 +52,7 @@ mod time { SystemTime::now() .duration_since(UNIX_EPOCH) - .map_err(|e| vm.new_value_error(format!("Time error: {:?}", e))) + .map_err(|e| vm.new_value_error(format!("Time error: {e:?}"))) } // TODO: implement proper monotonic time for wasm/wasi. @@ -220,7 +220,7 @@ mod time { ) -> PyResult { let format = format.as_ref().map_or("%a %b %H:%M:%S %Y", |s| s.as_str()); let instant = NaiveDateTime::parse_from_str(string.as_str(), format) - .map_err(|e| vm.new_value_error(format!("Parse error: {:?}", e)))?; + .map_err(|e| vm.new_value_error(format!("Parse error: {e:?}")))?; Ok(PyStructTime::new(vm, instant, -1)) } diff --git a/vm/src/types/structseq.rs b/vm/src/types/structseq.rs index e2d01941e2..516e2085af 100644 --- a/vm/src/types/structseq.rs +++ b/vm/src/types/structseq.rs @@ -44,7 +44,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static { fn repr(zelf: PyRef, vm: &VirtualMachine) -> PyResult { let format_field = |(value, name): (&PyObjectRef, _)| { let s = value.repr(vm)?; - Ok(format!("{}={}", name, s)) + Ok(format!("{name}={s}")) }; let (body, suffix) = if let Some(_guard) = rustpython_vm::recursion::ReprGuard::enter(vm, zelf.as_object()) diff --git a/vm/src/version.rs b/vm/src/version.rs index 452f659efc..eb8f6a0c11 100644 --- a/vm/src/version.rs +++ b/vm/src/version.rs @@ -25,7 +25,7 @@ pub fn get_version() -> String { } pub fn get_version_number() -> String { - format!("{}.{}.{}{}", MAJOR, MINOR, MICRO, RELEASELEVEL) + format!("{MAJOR}.{MINOR}.{MICRO}{RELEASELEVEL}") } pub fn get_compiler() -> String { @@ -105,5 +105,5 @@ pub fn get_git_datetime() -> String { let date = get_git_date(); let time = get_git_time(); - format!("{} {}", date, time) + format!("{date} {time}") } diff --git a/vm/src/vm/mod.rs b/vm/src/vm/mod.rs index c43049a6d8..4432255243 100644 --- a/vm/src/vm/mod.rs +++ b/vm/src/vm/mod.rs @@ -261,7 +261,7 @@ impl VirtualMachine { self, )?; self.sys_module.set_attr( - format!("__{}__", name), // e.g. __stdin__ + format!("__{name}__"), // e.g. __stdin__ stdio.clone(), self, )?; @@ -405,7 +405,7 @@ impl VirtualMachine { // To be called right before raising the recursion depth. fn check_recursive_call(&self, _where: &str) -> PyResult<()> { if self.recursion_depth.get() >= self.recursion_limit.get() { - Err(self.new_recursion_error(format!("maximum recursion depth exceeded {}", _where))) + Err(self.new_recursion_error(format!("maximum recursion depth exceeded {_where}"))) } else { Ok(()) } @@ -447,10 +447,10 @@ impl VirtualMachine { pub fn class(&self, module: &str, class: &str) -> PyTypeRef { let module = self .import(module, None, 0) - .unwrap_or_else(|_| panic!("unable to import {}", module)); + .unwrap_or_else(|_| panic!("unable to import {module}")); let class = module .get_attr(class, self) - .unwrap_or_else(|_| panic!("module {:?} has no class {}", module, class)); + .unwrap_or_else(|_| panic!("module {module:?} has no class {class}")); class.downcast().expect("not a class") } @@ -487,7 +487,7 @@ impl VirtualMachine { Some(cached_module) => { if self.is_none(&cached_module) { Err(self.new_import_error( - format!("import of {} halted; None in sys.modules", module), + format!("import of {module} halted; None in sys.modules"), module, )) } else { @@ -754,7 +754,7 @@ impl VirtualMachine { }; if let Some(msg) = msg { let stderr = stdlib::sys::PyStderr(self); - writeln!(stderr, "{}", msg); + writeln!(stderr, "{msg}"); } 1 } else { diff --git a/vm/src/vm/vm_object.rs b/vm/src/vm/vm_object.rs index b2daca51c8..b20c446b96 100644 --- a/vm/src/vm/vm_object.rs +++ b/vm/src/vm/vm_object.rs @@ -38,7 +38,7 @@ impl VirtualMachine { } else { "run with RUST_BACKTRACE=1 to see Python backtrace" }; - panic!("{}; {}", msg, after) + panic!("{msg}; {after}") } #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] { diff --git a/vm/src/warn.rs b/vm/src/warn.rs index 177141493f..d6dfd7a8e1 100644 --- a/vm/src/warn.rs +++ b/vm/src/warn.rs @@ -117,7 +117,7 @@ fn get_filter( None }; let tmp_item = tmp_item.ok_or_else(|| { - vm.new_value_error(format!("_warnings.filters item {} isn't a 5-tuple", i)) + vm.new_value_error(format!("_warnings.filters item {i} isn't a 5-tuple")) })?; /* Python code: action, msg, cat, mod, ln = item */