From 264fbee9bb1b39d5df9a2d07779409425fa79a3c Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 11:32:03 +0300 Subject: [PATCH 01/12] Clippy warn uninlined_format_args --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index 3a32af38496..01c4cd56a57 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -359,3 +359,4 @@ manual_is_variant_and = "warn" map_unwrap_or = "warn" must_use_candidate = "warn" unnecessary_wraps = "warn" +uninlined_format_args = "warn" From 6cd03800d4b85fab1e9b4e092d51b9f18c9e426a Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 11:32:16 +0300 Subject: [PATCH 02/12] Clippy fix --- crates/codegen/src/compile.rs | 6 ++---- crates/codegen/src/symboltable.rs | 11 ++++------- crates/common/src/format.rs | 2 +- crates/compiler/src/lib.rs | 2 +- crates/derive-impl/src/pystructseq.rs | 2 +- crates/host_env/src/fileutils.rs | 2 +- crates/stdlib/src/_asyncio.rs | 13 ++++++------- crates/stdlib/src/faulthandler.rs | 7 +++---- crates/stdlib/src/math.rs | 4 ++-- crates/stdlib/src/ssl.rs | 3 +-- crates/vm/src/builtins/bool.rs | 2 +- crates/vm/src/builtins/code.rs | 4 ++-- crates/vm/src/builtins/descriptor.rs | 2 +- crates/vm/src/builtins/function.rs | 2 +- crates/vm/src/builtins/type.rs | 2 +- crates/vm/src/exception_group.rs | 3 +-- crates/vm/src/exceptions.rs | 3 +-- crates/vm/src/frame.rs | 7 ++----- crates/vm/src/getpath.rs | 2 +- crates/vm/src/import.rs | 4 ++-- crates/vm/src/ospath.rs | 2 +- crates/vm/src/stdlib/_ast.rs | 9 +++------ crates/vm/src/stdlib/_ctypes.rs | 18 +++++++++--------- crates/vm/src/stdlib/_ctypes/base.rs | 7 +++---- crates/vm/src/stdlib/_ctypes/function.rs | 9 ++++----- crates/vm/src/stdlib/_ctypes/pointer.rs | 4 ++-- crates/vm/src/stdlib/_ctypes/simple.rs | 9 ++++----- crates/vm/src/stdlib/_ctypes/structure.rs | 5 ++--- crates/vm/src/stdlib/_ctypes/union.rs | 3 +-- crates/vm/src/stdlib/_functools.rs | 3 +-- crates/vm/src/stdlib/_signal.rs | 4 ++-- crates/vm/src/stdlib/_typing.rs | 4 ++-- crates/vm/src/stdlib/builtins.rs | 6 ++---- crates/vm/src/stdlib/gc.rs | 2 +- crates/vm/src/stdlib/posix.rs | 3 +-- crates/vm/src/stdlib/sys.rs | 2 +- crates/vm/src/types/slot.rs | 3 +-- crates/vm/src/types/structseq.rs | 4 ++-- crates/vm/src/vm/mod.rs | 4 ++-- 39 files changed, 79 insertions(+), 105 deletions(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 8877336b95f..3c6352b3994 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -1287,8 +1287,7 @@ impl Compiler { let name = current_table.name.clone(); let typ = current_table.typ; return Err(self.error(CodegenErrorType::SyntaxError(format!( - "no symbol table available in {} (type: {:?})", - name, typ + "no symbol table available in {name} (type: {typ:?})" )))); } @@ -9696,8 +9695,7 @@ impl Compiler { let name = current_table.name.clone(); let typ = current_table.typ; Err(self.error(CodegenErrorType::SyntaxError(format!( - "no symbol table available in {} (type: {:?})", - name, typ + "no symbol table available in {name} (type: {typ:?})" )))) } })(); diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index 4e762ff8b1e..57da8c30696 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -2418,7 +2418,7 @@ impl SymbolTableBuilder { }; if !seen_names.insert(name) { return Err(SymbolTableError { - error: format!("duplicate type parameter '{}'", name), + error: format!("duplicate type parameter '{name}'"), location: Some( self.source_file .to_source_code() @@ -2431,8 +2431,7 @@ impl SymbolTableBuilder { } else if default_seen { return Err(SymbolTableError { error: format!( - "non-default type parameter '{}' follows default type parameter", - name + "non-default type parameter '{name}' follows default type parameter" ), location: Some( self.source_file @@ -2743,8 +2742,7 @@ impl SymbolTableBuilder { { return Err(SymbolTableError { error: format!( - "assignment expression cannot rebind comprehension iteration variable '{}'", - mangled + "assignment expression cannot rebind comprehension iteration variable '{mangled}'" ), location, }); @@ -2868,8 +2866,7 @@ impl SymbolTableBuilder { { return Err(SymbolTableError { error: format!( - "comprehension inner loop cannot rebind assignment expression target '{}'", - name + "comprehension inner loop cannot rebind assignment expression target '{name}'" ), location, }); diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index a2d875d22db..ea4844c8ec7 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -763,7 +763,7 @@ impl FormatSpec { Ok("inf%".to_owned()) } else { let capped = float::clamp_fmt_precision(precision); - let mut result = format!("{:.*}", capped, scaled); + let mut result = format!("{scaled:.capped$}"); // Pad with '0's up to the requested precision to match // CPython byte-identically past the internal cap. let missing = precision.saturating_sub(capped); diff --git a/crates/compiler/src/lib.rs b/crates/compiler/src/lib.rs index 0be38ec15be..cf55d1a0f1c 100644 --- a/crates/compiler/src/lib.rs +++ b/crates/compiler/src/lib.rs @@ -65,7 +65,7 @@ impl CompileError { line: loc.line, character_offset: loc.character_offset.saturating_add(1), }; - let msg = format!("'{}' was never closed", bracket_char); + let msg = format!("'{bracket_char}' was never closed"); is_unclosed_bracket = true; (parser::ParseErrorType::OtherError(msg), loc, end_loc) } else { diff --git a/crates/derive-impl/src/pystructseq.rs b/crates/derive-impl/src/pystructseq.rs index 2e2ad566e82..4059aba63b7 100644 --- a/crates/derive-impl/src/pystructseq.rs +++ b/crates/derive-impl/src/pystructseq.rs @@ -550,7 +550,7 @@ pub(crate) fn impl_pystruct_sequence( }; let module_class_name = if let Some(ref m) = module_name { - format!("{}.{}", m, class_name) + format!("{m}.{class_name}") } else { class_name.clone() }; diff --git a/crates/host_env/src/fileutils.rs b/crates/host_env/src/fileutils.rs index f5a646c73c3..79cee1cb551 100644 --- a/crates/host_env/src/fileutils.rs +++ b/crates/host_env/src/fileutils.rs @@ -454,7 +454,7 @@ pub fn fopen(path: &std::path::Path, mode: &str) -> std::io::Result<*mut libc::F if mode != "rb" { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, - format!("unsupported mode: {}", mode), + format!("unsupported mode: {mode}"), )); } diff --git a/crates/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index f3911b1e595..22a1b6ea9fa 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -807,7 +807,7 @@ pub(crate) mod _asyncio { // Create context dict for call_exception_handler let context = PyDict::default().into_ref(&vm.ctx); let class_name = zelf.class().name().to_string(); - let message = format!("{} exception was never retrieved", class_name); + let message = format!("{class_name} exception was never retrieved"); context.set_item( vm.ctx.intern_str("message"), vm.ctx.new_str(message).into(), @@ -831,9 +831,9 @@ pub(crate) mod _asyncio { let class_name = zelf.class().name().to_string(); if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { let info = get_future_repr_info(zelf.as_object(), vm)?; - Ok(format!("<{} {}>", class_name, info)) + Ok(format!("<{class_name} {info}>")) } else { - Ok(format!("<{} ...>", class_name)) + Ok(format!("<{class_name} ...>")) } } } @@ -1851,7 +1851,7 @@ pub(crate) mod _asyncio { .repr(vm) .unwrap_or_else(|_| vm.ctx.new_str("")); let message = - format!("Task was destroyed but it is pending!\ntask: {}", task_repr); + format!("Task was destroyed but it is pending!\ntask: {task_repr}"); context.set_item( vm.ctx.intern_str("message"), vm.ctx.new_str(message).into(), @@ -1887,7 +1887,7 @@ pub(crate) mod _asyncio { // Create context dict for call_exception_handler let context = PyDict::default().into_ref(&vm.ctx); let class_name = zelf.class().name().to_string(); - let message = format!("{} exception was never retrieved", class_name); + let message = format!("{class_name} exception was never retrieved"); context.set_item( vm.ctx.intern_str("message"), vm.ctx.new_str(message).into(), @@ -2177,8 +2177,7 @@ pub(crate) mod _asyncio { .repr(vm) .unwrap_or_else(|_| vm.ctx.new_str("")); let msg = format!( - "Task {} got Future {} attached to a different loop", - task_repr, result_repr + "Task {task_repr} got Future {result_repr} attached to a different loop" ); task.base.fut_state.store(FutureState::Finished); *task.base.fut_exception.write() = Some(vm.new_runtime_error(msg).into()); diff --git a/crates/stdlib/src/faulthandler.rs b/crates/stdlib/src/faulthandler.rs index d3ec870003e..9ea970767a9 100644 --- a/crates/stdlib/src/faulthandler.rs +++ b/crates/stdlib/src/faulthandler.rs @@ -753,9 +753,9 @@ mod decl { // Match Python's timedelta str format: H:MM:SS.ffffff (no leading zero for hours) if us != 0 { - format!("Timeout ({}:{:02}:{:02}.{:06})!\n", hour, min, sec, us) + format!("Timeout ({hour}:{min:02}:{sec:02}.{us:06})!\n") } else { - format!("Timeout ({}:{:02}:{:02})!\n", hour, min, sec) + format!("Timeout ({hour}:{min:02}:{sec:02})!\n") } } @@ -1051,8 +1051,7 @@ mod decl { let is_fatal = unsafe { FAULTHANDLER_HANDLERS.iter().any(|h| h.signum == signum) }; if is_fatal { return Err(vm.new_runtime_error(format!( - "signal {} cannot be registered, use enable() instead", - signum + "signal {signum} cannot be registered, use enable() instead" ))); } diff --git a/crates/stdlib/src/math.rs b/crates/stdlib/src/math.rs index 12d2eeee8cf..92c2a66e93e 100644 --- a/crates/stdlib/src/math.rs +++ b/crates/stdlib/src/math.rs @@ -948,10 +948,10 @@ fn float_repr(value: f64) -> String { "-inf".to_owned() } } else { - let s = format!("{}", value); + let s = format!("{value}"); // If no decimal point and not in scientific notation, add .0 if !s.contains('.') && !s.contains('e') && !s.contains('E') { - format!("{}.0", s) + format!("{s}.0") } else { s } diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index b05bcea3c95..716a79d034a 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -4878,8 +4878,7 @@ mod _ssl { let path_str = path.as_str(); let cert_data = rustpython_host_env::fs::read(path_str).map_err(|e| { vm.new_os_error(format!( - "Failed to read certificate file {}: {}", - path_str, e + "Failed to read certificate file {path_str}: {e}" )) })?; diff --git a/crates/vm/src/builtins/bool.rs b/crates/vm/src/builtins/bool.rs index 2177a890877..a2bab0acf08 100644 --- a/crates/vm/src/builtins/bool.rs +++ b/crates/vm/src/builtins/bool.rs @@ -73,7 +73,7 @@ pub struct PyBool(pub PyInt); impl Debug for PyBool { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let value = !self.0.as_bigint().is_zero(); - write!(f, "PyBool({})", value) + write!(f, "PyBool({value})") } } diff --git a/crates/vm/src/builtins/code.rs b/crates/vm/src/builtins/code.rs index 8f0c8784dd9..292366ff473 100644 --- a/crates/vm/src/builtins/code.rs +++ b/crates/vm/src/builtins/code.rs @@ -748,7 +748,7 @@ impl Constructor for PyCode { // Parse and validate bytecode from bytes let bytecode_bytes = args.co_code.as_bytes(); let instructions = CodeUnits::try_from(bytecode_bytes) - .map_err(|e| vm.new_value_error(format!("invalid bytecode: {}", e)))?; + .map_err(|e| vm.new_value_error(format!("invalid bytecode: {e}")))?; // Convert constants let constants = args @@ -1342,7 +1342,7 @@ impl PyCode { OptionalArg::Present(code_bytes) => { // Parse and validate bytecode from bytes CodeUnits::try_from(code_bytes.as_bytes()) - .map_err(|e| vm.new_value_error(format!("invalid bytecode: {}", e)))? + .map_err(|e| vm.new_value_error(format!("invalid bytecode: {e}")))? } OptionalArg::Missing => self.code.instructions.clone(), }; diff --git a/crates/vm/src/builtins/descriptor.rs b/crates/vm/src/builtins/descriptor.rs index c8825572212..f8a54da1195 100644 --- a/crates/vm/src/builtins/descriptor.rs +++ b/crates/vm/src/builtins/descriptor.rs @@ -555,7 +555,7 @@ impl core::fmt::Debug for SlotFunc { SlotFunc::GetAttro(_) => write!(f, "SlotFunc::GetAttro(...)"), SlotFunc::SetAttro(_) => write!(f, "SlotFunc::SetAttro(...)"), SlotFunc::DelAttro(_) => write!(f, "SlotFunc::DelAttro(...)"), - SlotFunc::RichCompare(_, op) => write!(f, "SlotFunc::RichCompare(..., {:?})", op), + SlotFunc::RichCompare(_, op) => write!(f, "SlotFunc::RichCompare(..., {op:?})"), SlotFunc::DescrGet(_) => write!(f, "SlotFunc::DescrGet(...)"), SlotFunc::DescrSet(_) => write!(f, "SlotFunc::DescrSet(...)"), SlotFunc::DescrDel(_) => write!(f, "SlotFunc::DescrDel(...)"), diff --git a/crates/vm/src/builtins/function.rs b/crates/vm/src/builtins/function.rs index a057388666f..5b12401f5ac 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -268,7 +268,7 @@ impl PyFunction { .map_or(0, |d| d.len()); let n_required = n_expected_args - n_defaults; let takes_msg = if n_defaults > 0 { - format!("from {} to {}", n_required, n_expected_args) + format!("from {n_required} to {n_expected_args}") } else { n_expected_args.to_string() }; diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index 6cdeb7e659c..f5169568106 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -2949,7 +2949,7 @@ fn mangle_name(class_name: &str, name: &str) -> String { } // Strip leading underscores from class name let class_name = class_name.trim_start_matches('_'); - format!("_{}{}", class_name, name) + format!("_{class_name}{name}") } #[cfg(test)] diff --git a/crates/vm/src/exception_group.rs b/crates/vm/src/exception_group.rs index 4698aa4874a..24ab0275ff6 100644 --- a/crates/vm/src/exception_group.rs +++ b/crates/vm/src/exception_group.rs @@ -289,8 +289,7 @@ pub(super) mod types { for (i, exc) in exceptions.iter().enumerate() { if !exc.fast_isinstance(vm.ctx.exceptions.base_exception_type) { return Err(vm.new_value_error(format!( - "Item {} of second argument (exceptions) is not an exception", - i + "Item {i} of second argument (exceptions) is not an exception" ))); } // Check if any exception is not an Exception subclass diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index 6a1b8d48aed..107b3541716 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -2404,8 +2404,7 @@ pub(super) mod types { } _ => { return Err(vm.new_type_error(format!( - "function takes exactly 4 or 6 arguments ({} given)", - location_tup_len + "function takes exactly 4 or 6 arguments ({location_tup_len} given)" ))); } } diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index 3e5ca27ad4e..64206f8dce0 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -3104,8 +3104,7 @@ impl ExecutingFrame<'_> { .unwrap_or_else(|| String::from("?")); let match_args_type_name = match_args.class().__name__(vm); return Err(vm.new_type_error(format!( - "{}.__match_args__ must be a tuple (got {})", - type_name, match_args_type_name + "{type_name}.__match_args__ must be a tuple (got {match_args_type_name})" ))); } }; @@ -3569,9 +3568,7 @@ impl ExecutingFrame<'_> { // This means swap TOS with the element at index (len - n) debug_assert!( index_val <= len, - "SWAP index {} exceeds stack size {}", - index_val, - len + "SWAP index {index_val} exceeds stack size {len}" ); let j = len - index_val; self.localsplus.stack_swap(i, j); diff --git a/crates/vm/src/getpath.rs b/crates/vm/src/getpath.rs index 66c39613bfa..51f85046ea7 100644 --- a/crates/vm/src/getpath.rs +++ b/crates/vm/src/getpath.rs @@ -26,7 +26,7 @@ mod platform { pub(super) fn stdlib_landmarks() -> [String; 2] { let subdir = stdlib_subdir(); - [format!("{}/os.py", subdir), format!("{}/os.pyc", subdir)] + [format!("{subdir}/os.py"), format!("{subdir}/os.pyc")] } pub(super) fn platstdlib_landmark() -> String { diff --git a/crates/vm/src/import.rs b/crates/vm/src/import.rs index ebf1cac2a08..f33290ff83b 100644 --- a/crates/vm/src/import.rs +++ b/crates/vm/src/import.rs @@ -390,10 +390,10 @@ pub(crate) fn import_module_level( if level == 0 { let sys_modules = vm.sys_module.get_attr("modules", vm)?; return sys_modules.get_item(name, vm).map_err(|_| { - vm.new_import_error(format!("No module named '{}'", name), name.to_owned()) + vm.new_import_error(format!("No module named '{name}'"), name.to_owned()) }); } - return Err(vm.new_import_error(format!("No module named '{}'", name), name.to_owned())); + return Err(vm.new_import_error(format!("No module named '{name}'"), name.to_owned())); } }; diff --git a/crates/vm/src/ospath.rs b/crates/vm/src/ospath.rs index b0acb0d88a1..f2368a28826 100644 --- a/crates/vm/src/ospath.rs +++ b/crates/vm/src/ospath.rs @@ -51,7 +51,7 @@ impl PathConverter { /// Generate error message prefix like "rename: " fn error_prefix(&self) -> String { match self.function_name { - Some(func) => format!("{}: ", func), + Some(func) => format!("{func}: "), None => String::new(), } } diff --git a/crates/vm/src/stdlib/_ast.rs b/crates/vm/src/stdlib/_ast.rs index 9065d76fddd..57da9b3c3a8 100644 --- a/crates/vm/src/stdlib/_ast.rs +++ b/crates/vm/src/stdlib/_ast.rs @@ -239,22 +239,19 @@ fn range_from_object( if start_row_val > end_row_val { return Err(vm.new_value_error(format!( - "AST node line range ({}, {}) is not valid", - start_row_val, end_row_val + "AST node line range ({start_row_val}, {end_row_val}) is not valid" ))); } if (start_row_val < 0 && end_row_val != start_row_val) || (start_col_val < 0 && end_col_val != start_col_val) { return Err(vm.new_value_error(format!( - "AST node column range ({}, {}) for line range ({}, {}) is not valid", - start_col_val, end_col_val, start_row_val, end_row_val + "AST node column range ({start_col_val}, {end_col_val}) for line range ({start_row_val}, {end_row_val}) is not valid" ))); } if start_row_val == end_row_val && start_col_val > end_col_val { return Err(vm.new_value_error(format!( - "line {}, column {}-{} is not a valid range", - start_row_val, start_col_val, end_col_val + "line {start_row_val}, column {start_col_val}-{end_col_val} is not a valid range" ))); } diff --git a/crates/vm/src/stdlib/_ctypes.rs b/crates/vm/src/stdlib/_ctypes.rs index 97947bb2fed..1a3f454524a 100644 --- a/crates/vm/src/stdlib/_ctypes.rs +++ b/crates/vm/src/stdlib/_ctypes.rs @@ -286,7 +286,7 @@ pub(crate) mod _ctypes { FfiArgValue::I64(v) => v, _ => 0, }; - Ok(format!("", tag_char, n)) + Ok(format!("")) } b'B' | b'H' | b'I' | b'L' | b'Q' => { // Unsigned integers @@ -297,14 +297,14 @@ pub(crate) mod _ctypes { FfiArgValue::U64(v) => v, _ => 0, }; - Ok(format!("", tag_char, n)) + Ok(format!("")) } b'f' => { let v = match zelf.value { FfiArgValue::F32(v) => v as f64, _ => 0.0, }; - Ok(format!("", tag_char, v)) + Ok(format!("")) } b'd' | b'g' => { let v = match zelf.value { @@ -312,7 +312,7 @@ pub(crate) mod _ctypes { FfiArgValue::F32(v) => v as f64, _ => 0.0, }; - Ok(format!("", tag_char, v)) + Ok(format!("")) } b'c' => { // c_char - single byte @@ -324,7 +324,7 @@ pub(crate) mod _ctypes { if is_literal_char(byte) { Ok(format!("", tag_char, byte as char)) } else { - Ok(format!("", tag_char, byte)) + Ok(format!("")) } } b'z' | b'Z' | b'P' | b'V' => { @@ -334,16 +334,16 @@ pub(crate) mod _ctypes { _ => 0, }; if ptr == 0 { - Ok(format!("", tag_char)) + Ok(format!("")) } else { - Ok(format!("", tag_char, ptr)) + Ok(format!("")) } } _ => { // Default fallback let addr = zelf.get_id(); if is_literal_char(zelf.tag) { - Ok(format!("", tag_char, addr)) + Ok(format!("")) } else { Ok(format!("", zelf.tag, addr)) } @@ -575,7 +575,7 @@ pub(crate) mod _ctypes { .get_or_insert_lib_with_mode(&*os_str, mode, vm) .map_err(|e| { let name_str = os_str.to_string_lossy(); - vm.new_os_error(format!("{}: {}", name_str, e)) + vm.new_os_error(format!("{name_str}: {e}")) })?; Ok(id) } diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index ed0084025c8..0437766a895 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -358,7 +358,7 @@ pub(super) fn get_field_format( // For simple types, replace existing endian prefix with the correct one let base_fmt = fmt.trim_start_matches(['<', '>', '@', '=', '!']); if !base_fmt.is_empty() { - return format!("{}{}", endian_prefix, base_fmt); + return format!("{endian_prefix}{base_fmt}"); } return fmt.clone(); } @@ -370,7 +370,7 @@ pub(super) fn get_field_format( let s = type_str .to_str() .expect("_type_ is validated as ASCII at type creation"); - return format!("{}{}", endian_prefix, s); + return format!("{endian_prefix}{s}"); } // Default: single byte @@ -1509,8 +1509,7 @@ impl Constructor for PyCField { let type_bits = byte_size * 8; if bo + bs > type_bits { return Err(vm.new_value_error(format!( - "bit field '{}' overflows its type ({} + {} > {})", - name, bo, bs, type_bits + "bit field '{name}' overflows its type ({bo} + {bs} > {type_bits})" ))); } Ok(Self::new_bitfield( diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 6418158e913..ed7119149fb 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -1038,7 +1038,7 @@ impl Constructor for PyCFuncPtr { // dlsym can return NULL for symbols that resolve to NULL (e.g., GNU IFUNC) // Treat NULL addresses as errors if addr == 0 { - return Err(vm.new_attribute_error(format!("function '{}' not found", name))); + return Err(vm.new_attribute_error(format!("function '{name}' not found"))); } addr } else { @@ -1479,7 +1479,7 @@ fn build_callargs_with_paramflags( } else if let Some(def) = default { def.clone() } else { - return Err(vm.new_type_error(format!("required argument {} missing", param_idx))); + return Err(vm.new_type_error(format!("required argument {param_idx} missing"))); }; if is_out { @@ -1837,7 +1837,7 @@ impl Representable for PyCFuncPtr { let type_name = zelf.class().name(); // Use object id, not function pointer address let addr = zelf.get_id(); - Ok(format!("<{} object at {:#x}>", type_name, addr)) + Ok(format!("<{type_name} object at {addr:#x}>")) } } @@ -2183,8 +2183,7 @@ unsafe extern "C" fn thunk_callback( .repr(vm) .map_or_else(|_| "".to_string(), |s| s.to_string()); let msg = format!( - "Exception ignored while calling ctypes callback function {}", - repr + "Exception ignored while calling ctypes callback function {repr}" ); vm.run_unraisable(exc.clone(), Some(msg), vm.ctx.none()); } diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index b900f9fc569..8392b1bca54 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -65,7 +65,7 @@ impl Initializer for PyCPointerType { } else { String::new() }; - stg_info.format = Some(format!("&{}{}", shape_str, current_format)); + stg_info.format = Some(format!("&{shape_str}{current_format}")); } let _ = new_type.init_type_data(stg_info); @@ -204,7 +204,7 @@ impl PyCPointerType { } else { String::new() }; - stg_info.format = Some(format!("&{}{}", shape_str, current_format)); + stg_info.format = Some(format!("&{shape_str}{current_format}")); } // 4. Set _type_ attribute on the pointer type diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index f3ef925be04..b7e2a2c035e 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -56,7 +56,7 @@ fn ctypes_code_to_pep3118(code: char) -> char { fn alloc_format_string_for_type(code: char, big_endian: bool) -> String { let prefix = if big_endian { ">" } else { "<" }; let pep_code = ctypes_code_to_pep3118(code); - format!("{}{}", prefix, pep_code) + format!("{prefix}{pep_code}") } /// Create a new simple type instance from a class @@ -574,8 +574,7 @@ impl Initializer for PyCSimpleType { // Validate _type_ is a valid type character if !SIMPLE_TYPE_CHARS.contains(type_str.as_str()) { return Err(vm.new_attribute_error(format!( - "class must define a '_type_' attribute which must be a single character string containing one of '{}', currently it is '{}'.", - SIMPLE_TYPE_CHARS, type_str + "class must define a '_type_' attribute which must be a single character string containing one of '{SIMPLE_TYPE_CHARS}', currently it is '{type_str}'." ))); } @@ -1131,11 +1130,11 @@ impl Representable for PyCSimple { // Direct SimpleCData: "typename(repr(value))" let value = PyCSimple::value(zelf.to_owned().into(), vm)?; let value_repr = value.repr(vm)?.to_string(); - Ok(format!("{}({})", type_name, value_repr)) + Ok(format!("{type_name}({value_repr})")) } else { // Subclass: "" let addr = zelf.get_id(); - Ok(format!("<{} object at {:#x}>", type_name, addr)) + Ok(format!("<{type_name} object at {addr:#x}>")) } } } diff --git a/crates/vm/src/stdlib/_ctypes/structure.rs b/crates/vm/src/stdlib/_ctypes/structure.rs index a087fee2aed..f0a479d6fd8 100644 --- a/crates/vm/src/stdlib/_ctypes/structure.rs +++ b/crates/vm/src/stdlib/_ctypes/structure.rs @@ -405,7 +405,7 @@ impl PyCStructType { .map(|d| d.to_string()) .collect::>() .join(","); - format.push_str(&std::format!("({}){}", shape_str, field_format)); + format.push_str(&std::format!("({shape_str}){field_format}")); } else { format.push_str(&field_format); } @@ -750,8 +750,7 @@ impl PyCStructure { // Check for duplicate in kwargs if kwargs.contains_key(&field_name) { return Err(vm.new_type_error(format!( - "duplicate values for field {:?}", - field_name + "duplicate values for field {field_name:?}" ))); } self_obj.as_object().set_attr( diff --git a/crates/vm/src/stdlib/_ctypes/union.rs b/crates/vm/src/stdlib/_ctypes/union.rs index d2c0ce1a027..495e141dbac 100644 --- a/crates/vm/src/stdlib/_ctypes/union.rs +++ b/crates/vm/src/stdlib/_ctypes/union.rs @@ -621,8 +621,7 @@ impl PyCUnion { // Check for duplicate in kwargs if kwargs.contains_key(&field_name) { return Err(vm.new_type_error(format!( - "duplicate values for field {:?}", - field_name + "duplicate values for field {field_name:?}" ))); } self_obj.as_object().set_attr( diff --git a/crates/vm/src/stdlib/_functools.rs b/crates/vm/src/stdlib/_functools.rs index cd0c40de098..3ed2769d2e9 100644 --- a/crates/vm/src/stdlib/_functools.rs +++ b/crates/vm/src/stdlib/_functools.rs @@ -333,8 +333,7 @@ mod _functools { if is_placeholder(value) { return Err(vm.new_type_error(format!( "Placeholder cannot be passed as a keyword argument to partial(). \ - Did you mean partial(..., {}=Placeholder, ...)(value)?", - key + Did you mean partial(..., {key}=Placeholder, ...)(value)?" ))); } } diff --git a/crates/vm/src/stdlib/_signal.rs b/crates/vm/src/stdlib/_signal.rs index 93880b017f9..c2b53d70249 100644 --- a/crates/vm/src/stdlib/_signal.rs +++ b/crates/vm/src/stdlib/_signal.rs @@ -507,7 +507,7 @@ pub(crate) mod _signal { let res = unsafe { libc::raise(signalnum) }; if res != 0 { - return Err(vm.new_os_error(format!("raise_signal failed for signal {}", signalnum))); + return Err(vm.new_os_error(format!("raise_signal failed for signal {signalnum}"))); } // Check if a signal was triggered and handle it @@ -521,7 +521,7 @@ pub(crate) mod _signal { #[pyfunction] fn strsignal(signalnum: i32, vm: &VirtualMachine) -> PyResult> { if signalnum < 1 || signalnum >= signal::NSIG as i32 { - return Err(vm.new_value_error(format!("signal number {} out of range", signalnum))); + return Err(vm.new_value_error(format!("signal number {signalnum} out of range"))); } let s = unsafe { libc::strsignal(signalnum) }; if s.is_null() { diff --git a/crates/vm/src/stdlib/_typing.rs b/crates/vm/src/stdlib/_typing.rs index 5e1426b886f..45740f7ebad 100644 --- a/crates/vm/src/stdlib/_typing.rs +++ b/crates/vm/src/stdlib/_typing.rs @@ -172,7 +172,7 @@ pub(crate) mod decl { } else { parts.join(", ") }; - Ok(vm.ctx.new_str(format!("({})", inner)).into()) + Ok(vm.ctx.new_str(format!("({inner})")).into()) } else { Ok(vm.ctx.new_str(typing_type_repr(value, vm)?).into()) } @@ -181,7 +181,7 @@ pub(crate) mod decl { impl Representable for ConstEvaluator { fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { let value_repr = zelf.value.repr(vm)?; - Ok(format!("", value_repr)) + Ok(format!("")) } } diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index f39ae2d1e0b..e62131207dc 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -1336,15 +1336,13 @@ mod builtins { { let cell_value = classcell.get().ok_or_else(|| { vm.new_runtime_error(format!( - "__class__ not set defining {:?} as {:?}. Was __classcell__ propagated to type.__new__?", - name, class + "__class__ not set defining {name:?} as {class:?}. Was __classcell__ propagated to type.__new__?" )) })?; if !cell_value.is(&class) { return Err(vm.new_type_error(format!( - "__class__ set to {:?} defining {:?} as {:?}", - cell_value, name, class + "__class__ set to {cell_value:?} defining {name:?} as {class:?}" ))); } } diff --git a/crates/vm/src/stdlib/gc.rs b/crates/vm/src/stdlib/gc.rs index 9c568c67a62..00eea1b39d5 100644 --- a/crates/vm/src/stdlib/gc.rs +++ b/crates/vm/src/stdlib/gc.rs @@ -163,7 +163,7 @@ mod gc { if let Some(g) = generation_opt && !(0..=2).contains(&g) { - return Err(vm.new_value_error(format!("generation must be in range(0, 3), not {}", g))); + return Err(vm.new_value_error(format!("generation must be in range(0, 3), not {g}"))); } let objects = gc_state::gc_state().get_objects(generation_opt); Ok(vm.ctx.new_list(objects)) diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index 1d114071aad..aaa6612ea92 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -906,8 +906,7 @@ pub mod module { if num_threads > 1 { let pid = unsafe { libc::getpid() }; let msg = format!( - "This process (pid={}) is multi-threaded, use of {}() may lead to deadlocks in the child.", - pid, name + "This process (pid={pid}) is multi-threaded, use of {name}() may lead to deadlocks in the child." ); // Match PyErr_WarnFormat(..., stacklevel=1) in CPython. diff --git a/crates/vm/src/stdlib/sys.rs b/crates/vm/src/stdlib/sys.rs index 46875248a1f..02beec87bc5 100644 --- a/crates/vm/src/stdlib/sys.rs +++ b/crates/vm/src/stdlib/sys.rs @@ -1250,7 +1250,7 @@ pub mod sys { if let Ok(module_str) = module_name.downcast::() { let module = module_str.as_wtf8(); if module != "builtins" && module != "__main__" { - write!(stderr, "{}.", module); + write!(stderr, "{module}."); } } else { write!(stderr, "."); diff --git a/crates/vm/src/types/slot.rs b/crates/vm/src/types/slot.rs index 2e8f5cf58f6..63a053df597 100644 --- a/crates/vm/src/types/slot.rs +++ b/crates/vm/src/types/slot.rs @@ -1664,8 +1664,7 @@ pub trait Initializer: PyPayload { == 2; if double_appearance { panic!( - "This type `{}` doesn't seem to support `init`. Override `slot_init` instead: {}", - class_name_for_debug, msg + "This type `{class_name_for_debug}` doesn't seem to support `init`. Override `slot_init` instead: {msg}" ); } } diff --git a/crates/vm/src/types/structseq.rs b/crates/vm/src/types/structseq.rs index bc1a8fa608a..b7468d4a702 100644 --- a/crates/vm/src/types/structseq.rs +++ b/crates/vm/src/types/structseq.rs @@ -239,7 +239,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static { _ => alloc::borrow::Cow::Borrowed(Self::TP_NAME), } }; - let repr_str = format!("{}({}{})", type_name, body, suffix); + let repr_str = format!("{type_name}({body}{suffix})"); Ok(vm.ctx.new_str(repr_str)) } @@ -277,7 +277,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static { // Check for unexpected keyword arguments if !kwargs.is_empty() { let names: Vec<&str> = kwargs.keys().map(|k| k.as_str()).collect(); - return Err(vm.new_type_error(format!("Got unexpected field name(s): {:?}", names))); + return Err(vm.new_type_error(format!("Got unexpected field name(s): {names:?}"))); } PyTuple::new_unchecked(items.into_boxed_slice()) diff --git a/crates/vm/src/vm/mod.rs b/crates/vm/src/vm/mod.rs index 9148dfedd35..a5970ba194b 100644 --- a/crates/vm/src/vm/mod.rs +++ b/crates/vm/src/vm/mod.rs @@ -1168,7 +1168,7 @@ impl VirtualMachine { if let Some(stderr) = stderr { let _ = vm.call_method(stderr, "write", (s.to_owned(),)); } else { - eprint!("{}", s); + eprint!("{s}"); } }; @@ -1191,7 +1191,7 @@ impl VirtualMachine { Ok(exc_str) if !exc_str.as_wtf8().is_empty() => { format!("{}: {}\n", exc_type_name, exc_str.as_wtf8()) } - _ => format!("{}\n", exc_type_name), + _ => format!("{exc_type_name}\n"), }; write_to_stderr(&msg, &stderr, self); From 988f2d41aa89bbfd62d9a2cea1a06415d25eca61 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 11:32:57 +0300 Subject: [PATCH 03/12] cargo fmt --- crates/stdlib/src/ssl.rs | 4 +--- crates/vm/src/stdlib/_ctypes/function.rs | 4 +--- crates/vm/src/stdlib/_ctypes/structure.rs | 6 +++--- crates/vm/src/stdlib/_ctypes/union.rs | 6 +++--- 4 files changed, 8 insertions(+), 12 deletions(-) diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index 716a79d034a..fc978b22878 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -4877,9 +4877,7 @@ mod _ssl { // Read certificate file let path_str = path.as_str(); let cert_data = rustpython_host_env::fs::read(path_str).map_err(|e| { - vm.new_os_error(format!( - "Failed to read certificate file {path_str}: {e}" - )) + vm.new_os_error(format!("Failed to read certificate file {path_str}: {e}")) })?; // Auto-detect PEM vs DER format diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index ed7119149fb..4ed640270e9 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -2182,9 +2182,7 @@ unsafe extern "C" fn thunk_callback( .callable .repr(vm) .map_or_else(|_| "".to_string(), |s| s.to_string()); - let msg = format!( - "Exception ignored while calling ctypes callback function {repr}" - ); + let msg = format!("Exception ignored while calling ctypes callback function {repr}"); vm.run_unraisable(exc.clone(), Some(msg), vm.ctx.none()); } diff --git a/crates/vm/src/stdlib/_ctypes/structure.rs b/crates/vm/src/stdlib/_ctypes/structure.rs index f0a479d6fd8..1f515ce0402 100644 --- a/crates/vm/src/stdlib/_ctypes/structure.rs +++ b/crates/vm/src/stdlib/_ctypes/structure.rs @@ -749,9 +749,9 @@ impl PyCStructure { let field_name = name_str.as_str().to_owned(); // Check for duplicate in kwargs if kwargs.contains_key(&field_name) { - return Err(vm.new_type_error(format!( - "duplicate values for field {field_name:?}" - ))); + return Err( + vm.new_type_error(format!("duplicate values for field {field_name:?}")) + ); } self_obj.as_object().set_attr( vm.ctx.intern_str(field_name), diff --git a/crates/vm/src/stdlib/_ctypes/union.rs b/crates/vm/src/stdlib/_ctypes/union.rs index 495e141dbac..43a829c89fc 100644 --- a/crates/vm/src/stdlib/_ctypes/union.rs +++ b/crates/vm/src/stdlib/_ctypes/union.rs @@ -620,9 +620,9 @@ impl PyCUnion { let field_name = name_str.as_str().to_owned(); // Check for duplicate in kwargs if kwargs.contains_key(&field_name) { - return Err(vm.new_type_error(format!( - "duplicate values for field {field_name:?}" - ))); + return Err( + vm.new_type_error(format!("duplicate values for field {field_name:?}")) + ); } self_obj.as_object().set_attr( vm.ctx.intern_str(field_name), From 1cf4a39eb16a5b67da1a9cfcf15f85eac817eee9 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 11:42:36 +0300 Subject: [PATCH 04/12] Clippy warn redundant_else --- Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 01c4cd56a57..8dec0ae21f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -358,5 +358,6 @@ inconsistent_struct_constructor = "warn" manual_is_variant_and = "warn" map_unwrap_or = "warn" must_use_candidate = "warn" -unnecessary_wraps = "warn" +redundant_else = "warn" uninlined_format_args = "warn" +unnecessary_wraps = "warn" From 63dba817254922afe6409aac31e6b4bea926d739 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 13:37:27 +0300 Subject: [PATCH 05/12] fix --- crates/codegen/src/compile.rs | 17 ++++--- crates/common/src/cformat.rs | 32 +++++++------ crates/stdlib/src/binascii.rs | 26 ++++++----- crates/vm/src/builtins/complex.rs | 18 +++---- crates/vm/src/builtins/str.rs | 3 +- crates/vm/src/builtins/template.rs | 6 +-- crates/vm/src/bytes_inner.rs | 3 +- crates/vm/src/dict_inner.rs | 36 +++++++++----- crates/vm/src/stdlib/_ctypes/base.rs | 3 +- crates/vm/src/stdlib/_ctypes/pointer.rs | 3 +- crates/vm/src/stdlib/_io.rs | 62 ++++++++++++------------- crates/vm/src/stdlib/_warnings.rs | 8 ++-- crates/vm/src/stdlib/builtins.rs | 18 +++---- crates/vm/src/stdlib/itertools.rs | 34 +++++++------- crates/vm/src/vm/mod.rs | 7 ++- 15 files changed, 143 insertions(+), 133 deletions(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 3c6352b3994..7b47e7314ca 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -7955,21 +7955,20 @@ impl Compiler { if let ast::Expr::Starred(_) = &element { if seen_star { return Err(self.error(CodegenErrorType::MultipleStarArgs)); - } else { - seen_star = true; - let before = i; - let after = elts.len() - i - 1; - let (before, after) = (|| Some((before.to_u8()?, after.to_u8()?)))( - ) + } + + seen_star = true; + let before = i; + let after = elts.len() - i - 1; + let (before, after) = (|| Some((before.to_u8()?, after.to_u8()?)))() .ok_or_else(|| { self.error_ranged( CodegenErrorType::TooManyStarUnpack, target.range(), ) })?; - let counts = bytecode::UnpackExArgs { before, after }; - emit!(self, Instruction::UnpackEx { counts }); - } + let counts = bytecode::UnpackExArgs { before, after }; + emit!(self, Instruction::UnpackEx { counts }); } } diff --git a/crates/common/src/cformat.rs b/crates/common/src/cformat.rs index cea23d1cb54..183cc80e7e5 100644 --- a/crates/common/src/cformat.rs +++ b/crates/common/src/cformat.rs @@ -788,21 +788,23 @@ impl CFormatStrOrBytes { iter.next().unwrap(); literal.extend([second]); continue; - } else { - if !literal.is_empty() { - parts.push(( - part_index, - CFormatPart::Literal(core::mem::take(&mut literal)), - )); - } - let spec = CFormatSpecKeyed::parse(iter).map_err(|err| CFormatError { - typ: err.0, - index: err.1, - })?; - parts.push((index, CFormatPart::Spec(spec))); - if let Some(&(index, _)) = iter.peek() { - part_index = index; - } + } + + if !literal.is_empty() { + parts.push(( + part_index, + CFormatPart::Literal(core::mem::take(&mut literal)), + )); + } + + let spec = CFormatSpecKeyed::parse(iter).map_err(|err| CFormatError { + typ: err.0, + index: err.1, + })?; + + parts.push((index, CFormatPart::Spec(spec))); + if let Some(&(index, _)) = iter.peek() { + part_index = index; } } else { return Err(CFormatError { diff --git a/crates/stdlib/src/binascii.rs b/crates/stdlib/src/binascii.rs index 9af56d4eea7..5deae90d5a1 100644 --- a/crates/stdlib/src/binascii.rs +++ b/crates/stdlib/src/binascii.rs @@ -691,20 +691,22 @@ mod decl { out_data.push(RUN_CHAR); out_data.push(0); return Ok(out_data); + } + + let mut in_end = idx + 1; + while in_end < len && buffer[in_end] == ch && in_end < idx + 255 { + in_end += 1; + } + + if in_end - idx > 3 { + out_data.push(ch); + out_data.push(RUN_CHAR); + out_data.push(((in_end - idx) % 256) as u8); + idx = in_end - 1; } else { - let mut in_end = idx + 1; - while in_end < len && buffer[in_end] == ch && in_end < idx + 255 { - in_end += 1; - } - if in_end - idx > 3 { - out_data.push(ch); - out_data.push(RUN_CHAR); - out_data.push(((in_end - idx) % 256) as u8); - idx = in_end - 1; - } else { - out_data.push(ch); - } + out_data.push(ch); } + idx += 1; } Ok(out_data) diff --git a/crates/vm/src/builtins/complex.rs b/crates/vm/src/builtins/complex.rs index 7839c8a3724..764c0ea3c9d 100644 --- a/crates/vm/src/builtins/complex.rs +++ b/crates/vm/src/builtins/complex.rs @@ -107,24 +107,26 @@ impl PyObjectRef { )?; return Ok(Some((ret.value, true))); - } else { - return match result.downcast_ref::() { - Some(complex_obj) => Ok(Some((complex_obj.value, true))), - None => Err(vm.new_type_error(format!( - "__complex__ returned non-complex (type '{}')", - result.class().name() - ))), - }; } + + return match result.downcast_ref::() { + Some(complex_obj) => Ok(Some((complex_obj.value, true))), + None => Err(vm.new_type_error(format!( + "__complex__ returned non-complex (type '{}')", + result.class().name() + ))), + }; } // `complex` does not have a `__complex__` by default, so subclasses might not either, // use the actual stored value in this case if let Some(complex) = self.downcast_ref::() { return Ok(Some((complex.value, true))); } + if let Some(float) = self.try_float_opt(vm) { return Ok(Some((Complex64::new(float?.to_f64(), 0.0), false))); } + Ok(None) } } diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index 33b1e7bc924..149fefff343 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -1247,9 +1247,8 @@ impl PyStr { let first = first?; if first.as_object().class().is(vm.ctx.types.str_type) { return Ok(first); - } else { - first.as_wtf8().to_owned() } + first.as_wtf8().to_owned() } Err(iter) => zelf.as_wtf8().py_join(iter)?, }; diff --git a/crates/vm/src/builtins/template.rs b/crates/vm/src/builtins/template.rs index 45f83e25026..51d4a1d47b9 100644 --- a/crates/vm/src/builtins/template.rs +++ b/crates/vm/src/builtins/template.rs @@ -314,17 +314,15 @@ impl IterNext for PyTemplateIter { continue; } return Ok(PyIterReturn::Return(item.clone())); - } else { - return Ok(PyIterReturn::StopIteration(None)); } + return Ok(PyIterReturn::StopIteration(None)); } else if index < zelf.template.interpolations.len() { let item = zelf.template.interpolations.get(index).unwrap(); zelf.index.fetch_add(1, Ordering::SeqCst); zelf.from_strings.store(true, Ordering::SeqCst); return Ok(PyIterReturn::Return(item.clone())); - } else { - return Ok(PyIterReturn::StopIteration(None)); } + return Ok(PyIterReturn::StopIteration(None)); } } } diff --git a/crates/vm/src/bytes_inner.rs b/crates/vm/src/bytes_inner.rs index 46f1ebebdde..983e5f6328b 100644 --- a/crates/vm/src/bytes_inner.rs +++ b/crates/vm/src/bytes_inner.rs @@ -797,9 +797,8 @@ impl PyBytesInner { new[offset..offset + len].clone_from_slice(to.elements.as_slice()); if max_count == Some(1) { return new; - } else { - new } + new } else { return self.elements.clone(); }; diff --git a/crates/vm/src/dict_inner.rs b/crates/vm/src/dict_inner.rs index b21ba9882dd..6cf1d52e436 100644 --- a/crates/vm/src/dict_inner.rs +++ b/crates/vm/src/dict_inner.rs @@ -299,6 +299,10 @@ impl Dict { // but still possible continue; }; + #[expect( + clippy::redundant_else, + reason = "Keeping the empty `else` block here for documentation" + )] if entry.index == index_index { let removed = core::mem::replace(&mut entry.value, value); self.bump_version(); @@ -400,11 +404,11 @@ impl Dict { if let Some(index) = entry.index() { let inner = self.read(); if let Some(entry) = inner.get_entry_checked(index, index_index) { + // The dict was not changed since we did lookup break Some(entry.value.clone()); - } else { - // The dict was changed since we did lookup. Let's try again. - continue; } + + // The dict was changed since we did lookup. Let's try again. } else { break None; } @@ -511,15 +515,15 @@ impl Dict { ControlFlow::Break(Some(entry)) => break Some(entry), _ => continue, } - } else { - let mut inner = self.write(); - if inner.indices.get(index_index) != Some(&entry) { - continue; - } - inner.unchecked_push(index_index, hash, key.to_owned(), value, entry); - self.bump_version(); - break None; } + + let mut inner = self.write(); + if inner.indices.get(index_index) != Some(&entry) { + continue; + } + inner.unchecked_push(index_index, hash, key.to_owned(), value, entry); + self.bump_version(); + break None; }; Ok(()) } @@ -718,6 +722,11 @@ impl Dict { inner.entries.get_unchecked(i).as_ref().unwrap_unchecked() }; let ret = (idx, index_index); + + #[expect( + clippy::redundant_else, + reason = "Keeping the empty `else` block here for documentation" + )] if key.key_is(&entry.key) { break 'outer ret; } else if entry.hash == hash_value { @@ -730,6 +739,11 @@ impl Dict { // warn!("Perturb value: {}", i); } }; + + #[expect( + clippy::redundant_else, + reason = "Keeping the empty `else` block here for documentation" + )] // This comparison needs to be done outside the lock. if key.key_eq(vm, &entry_key)? { break 'outer ret; diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index 0437766a895..a301248181b 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -962,9 +962,8 @@ impl PyCData { self.write_bytes_at_offset(offset, &to_copy[..copy_len]); self.keep_ref(index, value, vm)?; return Ok(()); - } else { - return Err(vm.new_type_error("bytes expected instead of str instance")); } + return Err(vm.new_type_error("bytes expected instead of str instance")); } // For c_wchar arrays with str input, convert to wchar_t diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 8392b1bca54..3f051998946 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -648,9 +648,8 @@ impl PyCPointer { *(addr as *mut usize) = ptr_val; } return zelf.0.keep_ref(index as usize, holder, vm); - } else { - Self::write_value_at_address(addr, element_size, &value, type_code.as_deref(), vm)?; } + Self::write_value_at_address(addr, element_size, &value, type_code.as_deref(), vm)?; } // KeepRef: store reference to keep value alive using actual index diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index 2a26da72727..409761ad0f2 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -1153,41 +1153,41 @@ mod _io { } vm.check_signals()?; } - None => { + None if remaining > self.buffer.len() => { // raw file is non-blocking - if remaining > self.buffer.len() { - // can't buffer everything, buffer what we can and error - let buf = buffer.as_contiguous().unwrap(); - let buffer_len = self.buffer.len(); - self.buffer.copy_from_slice(&buf[written..][..buffer_len]); - self.raw_pos = 0; - let buffer_size = self.buffer.len() as _; - self.adjust_position(buffer_size); - self.write_end = buffer_size; - // BlockingIOError(errno, msg, characters_written) - let chars_written = written + buffer_len; - return Err(vm.invoke_exception( - vm.ctx.exceptions.blocking_io_error.to_owned(), - vec![ - vm.new_pyobj(EAGAIN), - vm.new_pyobj("write could not complete without blocking"), - vm.new_pyobj(chars_written), - ], - )?); - } else { - break; - } + // can't buffer everything, buffer what we can and error + let buf = buffer.as_contiguous().unwrap(); + let buffer_len = self.buffer.len(); + self.buffer.copy_from_slice(&buf[written..][..buffer_len]); + self.raw_pos = 0; + let buffer_size = self.buffer.len() as _; + self.adjust_position(buffer_size); + self.write_end = buffer_size; + // BlockingIOError(errno, msg, characters_written) + let chars_written = written + buffer_len; + return Err(vm.invoke_exception( + vm.ctx.exceptions.blocking_io_error.to_owned(), + vec![ + vm.new_pyobj(EAGAIN), + vm.new_pyobj("write could not complete without blocking"), + vm.new_pyobj(chars_written), + ], + )?); } + None => break, } } + if self.readable() { self.reset_read(); } + if remaining > 0 { let buf = buffer.as_contiguous().unwrap(); self.buffer[..remaining].copy_from_slice(&buf[written..][..remaining]); written += remaining; } + self.write_pos = 0; self.write_end = remaining as _; self.adjust_position(remaining as _); @@ -2340,11 +2340,10 @@ mod _io { let pos_after = p + 2; if ch_after_cr == b'\n' { break Ok(searched + pos_after); - } else { - searched += pos_after; - remaining = &remaining[pos_after..]; - continue; } + searched += pos_after; + remaining = &remaining[pos_after..]; + continue; } None => break Err(searched + p), }, @@ -3247,12 +3246,11 @@ mod _io { reset_encoder(encoder, start_of_stream)?; } return Ok(res); - } else { - return Err(new_unsupported_operation( - vm, - "can't do nonzero end-relative seeks".to_owned(), - )); } + return Err(new_unsupported_operation( + vm, + "can't do nonzero end-relative seeks".to_owned(), + )); } _ => { return Err( diff --git a/crates/vm/src/stdlib/_warnings.rs b/crates/vm/src/stdlib/_warnings.rs index a41ce2625c7..b600b111829 100644 --- a/crates/vm/src/stdlib/_warnings.rs +++ b/crates/vm/src/stdlib/_warnings.rs @@ -104,11 +104,11 @@ mod _warnings { let cat_obj = match category { Some(c) if !vm.is_none(&c) => c, _ => { - if message.fast_isinstance(vm.ctx.exceptions.warning) { - return Ok(Some(message.class().to_owned())); + return Ok(if message.fast_isinstance(vm.ctx.exceptions.warning) { + Some(message.class().to_owned()) } else { - return Ok(None); // will default to UserWarning in warn_explicit - } + None // will default to UserWarning in warn_explicit + }); } }; diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index e62131207dc..dba40d78f38 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -1121,6 +1121,10 @@ mod builtins { start: OptionalArg, } + #[expect( + clippy::redundant_else, + reason = "match_class! macro expansion arms has a `return` inside" + )] #[pyfunction] fn sum(SumArgs { iterable, start }: SumArgs, vm: &VirtualMachine) -> PyResult { // Start with zero and add at will: @@ -1130,17 +1134,13 @@ mod builtins { match_class!(match sum { PyStr => - return Err(vm.new_type_error( - "sum() can't sum strings [use ''.join(seq) instead]".to_owned() - )), + return Err(vm.new_type_error("sum() can't sum strings [use ''.join(seq) instead]")), PyBytes => - return Err(vm.new_type_error( - "sum() can't sum bytes [use b''.join(seq) instead]".to_owned() - )), + return Err(vm.new_type_error("sum() can't sum bytes [use b''.join(seq) instead]")), PyByteArray => - return Err(vm.new_type_error( - "sum() can't sum bytearray [use b''.join(seq) instead]".to_owned() - )), + return Err( + vm.new_type_error("sum() can't sum bytearray [use b''.join(seq) instead]") + ), _ => (), }); diff --git a/crates/vm/src/stdlib/itertools.rs b/crates/vm/src/stdlib/itertools.rs index f3dbf0ceb81..2cb23902ec9 100644 --- a/crates/vm/src/stdlib/itertools.rs +++ b/crates/vm/src/stdlib/itertools.rs @@ -1249,26 +1249,26 @@ mod decl { if idx < 0 { zelf.exhausted.store(true); return Ok(PyIterReturn::StopIteration(None)); - } else { - // Increment the current index which we know is not at its - // maximum. Then move back to the right setting each index - // to its lowest possible value (one higher than the index - // to its left -- this maintains the sort order invariant). - indices[idx as usize] += 1; - for j in idx as usize + 1..r { - indices[j] = indices[j - 1] + 1; - } + } - // Update the result tuple for the new indices - // starting with i, the leftmost index that changed - for i in idx as usize..r { - let index = indices[i]; - let elem = &zelf.pool[index]; - elem.clone_into(&mut result[i]); - } + // Increment the current index which we know is not at its + // maximum. Then move back to the right setting each index + // to its lowest possible value (one higher than the index + // to its left -- this maintains the sort order invariant). + indices[idx as usize] += 1; + for j in idx as usize + 1..r { + indices[j] = indices[j - 1] + 1; + } - result.to_vec() + // Update the result tuple for the new indices + // starting with i, the leftmost index that changed + for i in idx as usize..r { + let index = indices[i]; + let elem = &zelf.pool[index]; + elem.clone_into(&mut result[i]); } + + result.to_vec() } else { let res = zelf.pool[0..r].to_vec(); *result_lock = Some(res.clone()); diff --git a/crates/vm/src/vm/mod.rs b/crates/vm/src/vm/mod.rs index a5970ba194b..6778a84684b 100644 --- a/crates/vm/src/vm/mod.rs +++ b/crates/vm/src/vm/mod.rs @@ -1886,9 +1886,9 @@ impl VirtualMachine { if i >= elements.len() { results.shrink_to_fit(); return Ok(Ok(results)); - } else { - elements[i].clone() } + elements[i].clone() + // free the lock }; match f(elem) { @@ -2149,9 +2149,8 @@ impl VirtualMachine { arg => { if self.is_none(arg) { return 0; - } else { - arg.str(self).ok() } + arg.str(self).ok() } }), _ => args.as_object().repr(self).ok(), From f33bfcc89768fba01f492c7949a0cb2de70119fa Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 14:09:26 +0300 Subject: [PATCH 06/12] Fix little of needless_pass_by_value --- crates/codegen/src/compile.rs | 43 ++++++++++---------- crates/derive-impl/src/compile_bytecode.rs | 47 ++++++++++------------ crates/derive-impl/src/lib.rs | 2 +- crates/derive-impl/src/pyclass.rs | 20 ++++----- crates/derive/src/lib.rs | 4 +- crates/stdlib/src/unicodedata.rs | 1 + 6 files changed, 59 insertions(+), 58 deletions(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 7b47e7314ca..ae4692a04ea 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -289,7 +289,7 @@ pub fn compile_program( ) -> CompileResult { let symbol_table = SymbolTable::scan_program(ast, source_file.clone()) .map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?; - let mut compiler = Compiler::new(opts, source_file, "".to_owned()); + let mut compiler = Compiler::new(opts, source_file, ""); compiler.compile_program(ast, symbol_table)?; let code = compiler.exit_scope(); trace!("Compilation completed: {code:?}"); @@ -304,7 +304,7 @@ pub fn compile_program_single( ) -> CompileResult { let symbol_table = SymbolTable::scan_program(ast, source_file.clone()) .map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?; - let mut compiler = Compiler::new(opts, source_file, "".to_owned()); + let mut compiler = Compiler::new(opts, source_file, ""); compiler.compile_program_single(&ast.body, symbol_table)?; let code = compiler.exit_scope(); trace!("Compilation completed: {code:?}"); @@ -318,7 +318,7 @@ pub fn compile_block_expression( ) -> CompileResult { let symbol_table = SymbolTable::scan_program(ast, source_file.clone()) .map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?; - let mut compiler = Compiler::new(opts, source_file, "".to_owned()); + let mut compiler = Compiler::new(opts, source_file, ""); compiler.compile_block_expr(&ast.body, symbol_table)?; let code = compiler.exit_scope(); trace!("Compilation completed: {code:?}"); @@ -332,7 +332,7 @@ pub fn compile_expression( ) -> CompileResult { let symbol_table = SymbolTable::scan_expr(ast, source_file.clone()) .map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?; - let mut compiler = Compiler::new(opts, source_file, "".to_owned()); + let mut compiler = Compiler::new(opts, source_file, ""); compiler.compile_eval(ast, symbol_table)?; let code = compiler.exit_scope(); Ok(code) @@ -447,13 +447,14 @@ impl PatternContext { } } +#[derive(Clone, Copy, Eq, PartialEq)] enum JumpOp { Jump, PopJumpIfFalse, } /// Type of collection to build in starunpack_helper -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] enum CollectionType { Tuple, List, @@ -541,7 +542,7 @@ impl Compiler { } } - fn new(opts: CompileOpts, source_file: SourceFile, code_name: String) -> Self { + fn new(opts: CompileOpts, source_file: SourceFile, code_name: &str) -> Self { let module_code = ir::CodeInfo { // CPython convention: top-level module / interactive / // expression code does not carry CO_NEWLOCALS or CO_OPTIMIZED. @@ -558,8 +559,8 @@ impl Compiler { current_block: BlockIdx::new(0), annotations_blocks: None, metadata: ir::CodeUnitMetadata { - name: code_name.clone(), - qualname: Some(code_name), + name: code_name.to_string(), + qualname: Some(code_name.to_string()), consts: IndexSet::default(), names: IndexSet::default(), varnames: IndexSet::default(), @@ -1828,7 +1829,7 @@ impl Compiler { posonlyarg_count: u32, arg_count: u32, kwonlyarg_count: u32, - obj_name: String, + obj_name: &str, ) -> CompileResult<()> { // First push the symbol table let table = self.push_symbol_table()?; @@ -1841,7 +1842,7 @@ impl Compiler { let lineno = self.get_source_line_number().get(); // Call enter_scope which does most of the work - self.enter_scope(&obj_name, scope_type, key, lineno.to_u32())?; + self.enter_scope(obj_name, scope_type, key, lineno.to_u32())?; // Override the values that push_output sets explicitly // enter_scope sets default values based on scope_type, but push_output @@ -3399,7 +3400,7 @@ impl Compiler { parameters.posonlyargs.len().to_u32(), (parameters.posonlyargs.len() + parameters.args.len()).to_u32(), parameters.kwonlyargs.len().to_u32(), - name.to_owned(), + name, )?; let args_iter = core::iter::empty() @@ -5257,7 +5258,7 @@ impl Compiler { 0, num_typeparam_args as u32, 0, - type_params_name, + &type_params_name, )?; // TypeParams scope is function-like @@ -5819,7 +5820,7 @@ impl Compiler { 0, 0, 0, - type_params_name, + &type_params_name, )?; // Set private name for name mangling @@ -9712,14 +9713,14 @@ impl Compiler { posonlyarg_count: u32, arg_count: u32, kwonlyarg_count: u32, - obj_name: String, + obj_name: &str, ) -> CompileResult<()> { let scope_type = table.typ; self.symbol_table_stack.push(table); let key = self.symbol_table_stack.len() - 1; let lineno = self.get_source_line_number().get(); - self.enter_scope(&obj_name, scope_type, key, lineno.to_u32())?; + self.enter_scope(obj_name, scope_type, key, lineno.to_u32())?; if let Some(info) = self.code_stack.last_mut() { info.flags = flags | (info.flags & bytecode::CodeFlags::NESTED); @@ -9783,7 +9784,7 @@ impl Compiler { // and relies on the inlined path itself to handle GET_AITER / // async-comprehension cleanup. return self.compile_inlined_comprehension( - comp_table, + &comp_table, init_collection, generators, compile_element, @@ -9818,7 +9819,7 @@ impl Compiler { // scope itself. Peek past those nested scopes so we can enter the // correct comprehension table here, then let the real outermost // iterator compile consume its nested scopes later in parent scope. - self.push_output_with_symbol_table(comp_table, flags, 1, 1, 0, name.to_owned())?; + self.push_output_with_symbol_table(comp_table, flags, 1, 1, 0, name)?; // Set qualname for comprehension self.set_qualname(); @@ -10025,7 +10026,7 @@ impl Compiler { /// This generates bytecode inline without creating a new code object fn compile_inlined_comprehension( &mut self, - comp_table: SymbolTable, + comp_table: &SymbolTable, init_collection: Option, generators: &[ast::Comprehension], compile_element: &dyn Fn(&mut Self, usize) -> CompileResult<()>, @@ -12377,7 +12378,7 @@ mod tests { let symbol_table = SymbolTable::scan_program(&ast, source_file.clone()) .map_err(|e| e.into_codegen_error(source_file.name().to_owned())) .unwrap(); - let mut compiler = Compiler::new(opts, source_file, "".to_owned()); + let mut compiler = Compiler::new(opts, source_file, ""); compiler.compile_program(&ast, symbol_table).unwrap(); compiler.exit_scope() } @@ -12415,7 +12416,7 @@ mod tests { let symbol_table = SymbolTable::scan_program(&ast, source_file.clone()) .map_err(|e| e.into_codegen_error(source_file.name().to_owned())) .unwrap(); - let mut compiler = Compiler::new(opts, source_file, "".to_owned()); + let mut compiler = Compiler::new(opts, source_file, ""); compiler.compile_program(&ast, symbol_table).unwrap(); let _table = compiler.pop_symbol_table(); let stack_top = compiler.code_stack.pop().unwrap(); @@ -12456,7 +12457,7 @@ mod tests { let is_async = function.is_async; let range = function.range(); - let mut compiler = Compiler::new(opts, source_file, "".to_owned()); + let mut compiler = Compiler::new(opts, source_file, ""); compiler.future_annotations = symbol_table.future_annotations; compiler.symbol_table_stack.push(symbol_table); compiler.set_source_range(range); diff --git a/crates/derive-impl/src/compile_bytecode.rs b/crates/derive-impl/src/compile_bytecode.rs index 75c1db4145b..a640d59c577 100644 --- a/crates/derive-impl/src/compile_bytecode.rs +++ b/crates/derive-impl/src/compile_bytecode.rs @@ -52,7 +52,7 @@ pub trait Compiler { &self, source: &str, mode: Mode, - module_name: String, + module_name: &str, ) -> Result>; } @@ -61,7 +61,7 @@ impl CompilationSource { &self, source: &str, mode: Mode, - module_name: String, + module_name: &str, compiler: &dyn Compiler, origin: F, ) -> Result { @@ -76,15 +76,15 @@ impl CompilationSource { fn compile( &self, mode: Mode, - module_name: String, + module_name: &str, compiler: &dyn Compiler, ) -> Result, Diagnostic> { match &self.kind { CompilationSourceKind::Dir { base, rel_path } => { - self.compile_dir(base, &base.join(rel_path), String::new(), mode, compiler) + self.compile_dir(base, &base.join(rel_path), "", mode, compiler) } _ => Ok(hashmap! { - module_name.clone() => CompiledModule { + module_name.to_string() => CompiledModule { code: self.compile_single(mode, module_name, compiler)?, package: false, }, @@ -95,7 +95,7 @@ impl CompilationSource { fn compile_single( &self, mode: Mode, - module_name: String, + module_name: &str, compiler: &dyn Compiler, ) -> Result { match &self.kind { @@ -126,7 +126,7 @@ impl CompilationSource { &self, base: &Path, path: &Path, - parent: String, + parent: &str, mode: Mode, compiler: &dyn Compiler, ) -> Result, Diagnostic> { @@ -152,26 +152,21 @@ impl CompilationSource { Diagnostic::spans_error(self.span, format!("Invalid UTF-8 in file name {path:?}")) })?; if path.is_dir() { - code_map.extend(self.compile_dir( - base, - &path, - if parent.is_empty() { - file_name.to_string() - } else { - format!("{parent}.{file_name}") - }, - mode, - compiler, - )?); + let nparent = if parent.is_empty() { + file_name.to_string() + } else { + format!("{parent}.{file_name}") + }; + code_map.extend(self.compile_dir(base, &path, &nparent, mode, compiler)?); } else if file_name.ends_with(".py") { let stem = path.file_stem().unwrap().to_str().unwrap(); let is_init = stem == "__init__"; let module_name = if is_init { - parent.clone() + parent } else if parent.is_empty() { - stem.to_owned() + stem } else { - format!("{parent}.{stem}") + &format!("{parent}.{stem}") }; let compile_path = |src_path: &Path| { @@ -181,7 +176,7 @@ impl CompilationSource { format!("Error reading file {path:?}: {err}"), ) })?; - self.compile_string(&source, mode, module_name.clone(), compiler, || { + self.compile_string(&source, mode, module_name, compiler, || { path.strip_prefix(base).ok().unwrap_or(&path).display() }) }; @@ -211,7 +206,7 @@ impl CompilationSource { }; code_map.insert( - module_name, + module_name.to_string(), CompiledModule { code, package: is_init, @@ -343,7 +338,7 @@ pub(crate) fn impl_py_compile( let crate_name = args.crate_name; let code = args .source - .compile_single(args.mode, args.module_name, compiler)?; + .compile_single(args.mode, &args.module_name, compiler)?; let frozen = frozen::FrozenCodeObject::encode(&code); let bytes = LitByteStr::new(&frozen.bytes, Span::call_site()); @@ -362,7 +357,9 @@ pub(crate) fn impl_py_freeze( let args = PyCompileArgs::parse(input, true)?; let crate_name = args.crate_name; - let code_map = args.source.compile(args.mode, args.module_name, compiler)?; + let code_map = args + .source + .compile(args.mode, &args.module_name, compiler)?; let data = frozen::FrozenLib::encode(code_map.iter().map(|(k, v)| { let v = frozen::FrozenModule { diff --git a/crates/derive-impl/src/lib.rs b/crates/derive-impl/src/lib.rs index c1fc09d7c26..91f606bba1f 100644 --- a/crates/derive-impl/src/lib.rs +++ b/crates/derive-impl/src/lib.rs @@ -55,7 +55,7 @@ pub fn pyexception(attr: PunctuatedNestedMeta, item: Item) -> TokenStream { if matches!(item, syn::Item::Impl(_)) { pyclass::impl_pyexception_impl(attr, item) } else { - result_to_tokens(pyclass::impl_pyexception(attr, item)) + result_to_tokens(pyclass::impl_pyexception(attr, &item)) } } diff --git a/crates/derive-impl/src/pyclass.rs b/crates/derive-impl/src/pyclass.rs index 030e3eadd85..5e25e381df6 100644 --- a/crates/derive-impl/src/pyclass.rs +++ b/crates/derive-impl/src/pyclass.rs @@ -13,7 +13,7 @@ use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned}; use syn_ext::ext::*; use syn_ext::types::*; -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone, Debug, Eq, PartialEq)] enum AttrName { Method, ClassMethod, @@ -780,8 +780,8 @@ pub(crate) fn impl_pyclass(attr: PunctuatedNestedMeta, item: Item) -> Result Result { - let (ident, _attrs) = pyexception_ident_and_attrs(&item)?; +pub(crate) fn impl_pyexception(attr: PunctuatedNestedMeta, item: &Item) -> Result { + let (ident, _attrs) = pyexception_ident_and_attrs(item)?; let fake_ident = Ident::new("pyclass", item.span()); let class_meta = ExceptionItemMeta::from_nested(ident.clone(), fake_ident, attr.into_iter())?; let class_name = class_meta.class_name()?; @@ -1131,7 +1131,7 @@ where args.context .getset_items - .add_item(py_name, args.cfgs.to_vec(), kind, ident.clone())?; + .add_item(&py_name, args.cfgs.to_vec(), kind, ident.clone())?; Ok(()) } } @@ -1298,7 +1298,7 @@ where } args.context.member_items.add_item( - py_name, + &py_name, member_item_kind, member_kind, ident.clone(), @@ -1402,6 +1402,7 @@ struct GetSetNursery { validated: bool, } +#[derive(Clone, Copy, Eq, PartialEq)] enum GetSetItemKind { Get, Set, @@ -1410,7 +1411,7 @@ enum GetSetItemKind { impl GetSetNursery { fn add_item( &mut self, - name: String, + name: &str, cfgs: Vec, kind: GetSetItemKind, item_ident: Ident, @@ -1418,7 +1419,7 @@ impl GetSetNursery { assert!(!self.validated, "new item is not allowed after validation"); // Note: Both getter and setter can have #[cfg], but they must have matching cfgs // since the map key is (name, cfgs). This ensures getter and setter are paired correctly. - let entry = self.map.entry((name.clone(), cfgs)).or_default(); + let entry = self.map.entry((name.to_string(), cfgs)).or_default(); let func = match kind { GetSetItemKind::Get => &mut entry.0, GetSetItemKind::Set => &mut entry.1, @@ -1492,6 +1493,7 @@ struct MemberNurseryEntry { setter: Option, } +#[derive(Clone, Copy, Eq, PartialEq)] enum MemberItemKind { Get, Set, @@ -1500,7 +1502,7 @@ enum MemberItemKind { impl MemberNursery { fn add_item( &mut self, - name: String, + name: &str, kind: MemberItemKind, member_kind: MemberKindStr, item_ident: Ident, @@ -1508,7 +1510,7 @@ impl MemberNursery { assert!(!self.validated, "new item is not allowed after validation"); let entry = self .map - .entry(name.clone()) + .entry(name.to_string()) .or_insert_with(|| MemberNurseryEntry { kind: member_kind, getter: None, diff --git a/crates/derive/src/lib.rs b/crates/derive/src/lib.rs index 224aad4ea3c..af60a3cddda 100644 --- a/crates/derive/src/lib.rs +++ b/crates/derive/src/lib.rs @@ -273,10 +273,10 @@ impl derive_impl::Compiler for Compiler { &self, source: &str, mode: rustpython_compiler::Mode, - module_name: String, + module_name: &str, ) -> Result> { use rustpython_compiler::{CompileOpts, compile}; - Ok(compile(source, mode, &module_name, CompileOpts::default())?) + Ok(compile(source, mode, module_name, CompileOpts::default())?) } } diff --git a/crates/stdlib/src/unicodedata.rs b/crates/stdlib/src/unicodedata.rs index 97d09f88ff4..0c43f5a2290 100644 --- a/crates/stdlib/src/unicodedata.rs +++ b/crates/stdlib/src/unicodedata.rs @@ -10,6 +10,7 @@ use crate::vm::{ PyObject, PyResult, VirtualMachine, builtins::PyStr, convert::TryFromBorrowedObject, }; +#[derive(Clone, Copy, Eq, PartialEq)] enum NormalizeForm { Nfc, Nfkc, From e861f8ff85ab43c5a65d8a268255937cc6a6d97a Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 14:27:16 +0300 Subject: [PATCH 07/12] fix jit --- crates/jit/tests/common.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/jit/tests/common.rs b/crates/jit/tests/common.rs index ca761477f3c..fddf9c56f1c 100644 --- a/crates/jit/tests/common.rs +++ b/crates/jit/tests/common.rs @@ -123,8 +123,7 @@ fn extract_annotations_from_annotate_code(code: &CodeObject) -> HashMap panic!( - "Unsupported annotation const for '{:?}' at idx {}: {:?}", - param_name, val_idx, other + "Unsupported annotation const for '{param_name:?}' at idx {val_idx}: {other:?}" ), None => panic!( "Annotation const idx out of bounds for '{:?}': {} (len={})", From 8f61351546abb2c31652185ef4e348452e685259 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 14:28:12 +0300 Subject: [PATCH 08/12] thread --- crates/vm/src/stdlib/_thread.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/vm/src/stdlib/_thread.rs b/crates/vm/src/stdlib/_thread.rs index 8f25be9c388..1203b2b3930 100644 --- a/crates/vm/src/stdlib/_thread.rs +++ b/crates/vm/src/stdlib/_thread.rs @@ -863,11 +863,7 @@ pub(crate) mod _thread { }; let name = thread_name.unwrap_or_else(|| Wtf8Buf::from(format!("{}", get_ident()))); - let _ = vm.call_method( - &file, - "write", - (format!("Exception in thread {}:\n", name),), - ); + let _ = vm.call_method(&file, "write", (format!("Exception in thread {name}:\n"),)); // Display the traceback if let Ok(traceback_mod) = vm.import("traceback", 0) From 8e7c0888953f9e14b41c7f65334a88007a9ea8b1 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 14:35:33 +0300 Subject: [PATCH 09/12] fix some windows --- crates/vm/src/stdlib/_codecs.rs | 24 ++++++++++++------------ crates/vm/src/stdlib/_signal.rs | 4 ++-- crates/vm/src/stdlib/nt.rs | 4 ++-- crates/vm/src/stdlib/os.rs | 4 ++-- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/vm/src/stdlib/_codecs.rs b/crates/vm/src/stdlib/_codecs.rs index a91b490300a..0fc9c792b61 100644 --- a/crates/vm/src/stdlib/_codecs.rs +++ b/crates/vm/src/stdlib/_codecs.rs @@ -426,7 +426,7 @@ mod _codecs_windows { if size == 0 { let err = std::io::Error::last_os_error(); - return Err(vm.new_os_error(format!("mbcs_encode failed: {}", err))); + return Err(vm.new_os_error(format!("mbcs_encode failed: {err}"))); } let mut buffer = vec![0u8; size as usize]; @@ -515,7 +515,7 @@ mod _codecs_windows { }; if size == 0 { let err = std::io::Error::last_os_error(); - return Err(vm.new_os_error(format!("mbcs_decode failed: {}", err))); + return Err(vm.new_os_error(format!("mbcs_decode failed: {err}"))); } let mut buffer = vec![0u16; size as usize]; @@ -531,11 +531,11 @@ mod _codecs_windows { }; if result == 0 { let err = std::io::Error::last_os_error(); - return Err(vm.new_os_error(format!("mbcs_decode failed: {}", err))); + return Err(vm.new_os_error(format!("mbcs_decode failed: {err}"))); } buffer.truncate(result as usize); let s = String::from_utf16(&buffer) - .map_err(|e| vm.new_unicode_decode_error(format!("mbcs_decode failed: {}", e)))?; + .map_err(|e| vm.new_unicode_decode_error(format!("mbcs_decode failed: {e}")))?; return Ok((s, len)); } @@ -553,11 +553,11 @@ mod _codecs_windows { }; if result == 0 { let err = std::io::Error::last_os_error(); - return Err(vm.new_os_error(format!("mbcs_decode failed: {}", err))); + return Err(vm.new_os_error(format!("mbcs_decode failed: {err}"))); } buffer.truncate(result as usize); let s = String::from_utf16(&buffer) - .map_err(|e| vm.new_unicode_decode_error(format!("mbcs_decode failed: {}", e)))?; + .map_err(|e| vm.new_unicode_decode_error(format!("mbcs_decode failed: {e}")))?; Ok((s, len)) } @@ -612,7 +612,7 @@ mod _codecs_windows { if size == 0 { let err = std::io::Error::last_os_error(); - return Err(vm.new_os_error(format!("oem_encode failed: {}", err))); + return Err(vm.new_os_error(format!("oem_encode failed: {err}"))); } let mut buffer = vec![0u8; size as usize]; @@ -701,7 +701,7 @@ mod _codecs_windows { }; if size == 0 { let err = std::io::Error::last_os_error(); - return Err(vm.new_os_error(format!("oem_decode failed: {}", err))); + return Err(vm.new_os_error(format!("oem_decode failed: {err}"))); } let mut buffer = vec![0u16; size as usize]; @@ -717,11 +717,11 @@ mod _codecs_windows { }; if result == 0 { let err = std::io::Error::last_os_error(); - return Err(vm.new_os_error(format!("oem_decode failed: {}", err))); + return Err(vm.new_os_error(format!("oem_decode failed: {err}"))); } buffer.truncate(result as usize); let s = String::from_utf16(&buffer) - .map_err(|e| vm.new_unicode_decode_error(format!("oem_decode failed: {}", e)))?; + .map_err(|e| vm.new_unicode_decode_error(format!("oem_decode failed: {e}")))?; return Ok((s, len)); } @@ -739,11 +739,11 @@ mod _codecs_windows { }; if result == 0 { let err = std::io::Error::last_os_error(); - return Err(vm.new_os_error(format!("oem_decode failed: {}", err))); + return Err(vm.new_os_error(format!("oem_decode failed: {err}"))); } buffer.truncate(result as usize); let s = String::from_utf16(&buffer) - .map_err(|e| vm.new_unicode_decode_error(format!("oem_decode failed: {}", e)))?; + .map_err(|e| vm.new_unicode_decode_error(format!("oem_decode failed: {e}")))?; Ok((s, len)) } diff --git a/crates/vm/src/stdlib/_signal.rs b/crates/vm/src/stdlib/_signal.rs index c2b53d70249..235d184edb1 100644 --- a/crates/vm/src/stdlib/_signal.rs +++ b/crates/vm/src/stdlib/_signal.rs @@ -228,7 +228,7 @@ pub(crate) mod _signal { libc::SIGABRT, ]; if !VALID_SIGNALS.contains(&signalnum) { - return Err(vm.new_value_error(format!("signal number {} out of range", signalnum))); + return Err(vm.new_value_error(format!("signal number {signalnum} out of range"))); } } if !vm.is_main_thread() { @@ -536,7 +536,7 @@ pub(crate) mod _signal { #[pyfunction] fn strsignal(signalnum: i32, vm: &VirtualMachine) -> PyResult> { if signalnum < 1 || signalnum >= signal::NSIG as i32 { - return Err(vm.new_value_error(format!("signal number {} out of range", signalnum))); + return Err(vm.new_value_error(format!("signal number {signalnum} out of range"))); } // Windows doesn't have strsignal(), provide our own mapping let name = match signalnum { diff --git a/crates/vm/src/stdlib/nt.rs b/crates/vm/src/stdlib/nt.rs index ddba6028249..7b3dc5c8b4d 100644 --- a/crates/vm/src/stdlib/nt.rs +++ b/crates/vm/src/stdlib/nt.rs @@ -1087,7 +1087,7 @@ pub(crate) mod module { return Err(vm.new_value_error("illegal environment variable name")); } - let env_str = format!("{}={}", key_str, value_str); + let env_str = format!("{key_str}={value_str}"); env_strings.push( widestring::WideCString::from_os_str(&*std::ffi::OsString::from(env_str)) .map_err(|err| err.to_pyexception(vm))?, @@ -1209,7 +1209,7 @@ pub(crate) mod module { return Err(vm.new_value_error("illegal environment variable name")); } - let env_str = format!("{}={}", key_str, value_str); + let env_str = format!("{key_str}={value_str}"); env_strings.push(make_widestring(&env_str)?); } diff --git a/crates/vm/src/stdlib/os.rs b/crates/vm/src/stdlib/os.rs index 448e7471010..ad8d9af758d 100644 --- a/crates/vm/src/stdlib/os.rs +++ b/crates/vm/src/stdlib/os.rs @@ -515,7 +515,7 @@ pub(super) mod _os { { return Err(vm.new_value_error("illegal environment variable name")); } - let env_str = format!("{}={}", key_str, value_str); + let env_str = format!("{key_str}={value_str}"); let wide = env_str.to_wide_with_nul(); check_env_var_len(wide.len(), vm)?; @@ -562,7 +562,7 @@ pub(super) mod _os { return Err(vm.new_value_error("illegal environment variable name")); } // "key=" to unset (empty value removes the variable) - let env_str = format!("{}=", key_str); + let env_str = format!("{key_str}="); let wide = env_str.to_wide_with_nul(); check_env_var_len(wide.len(), vm)?; From cf9a116bc96eaa11c9ca4abafefe238bf046d0c0 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 15:26:06 +0300 Subject: [PATCH 10/12] sqlite --- crates/stdlib/src/_sqlite3.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/stdlib/src/_sqlite3.rs b/crates/stdlib/src/_sqlite3.rs index 21739a28c03..3cf93692c05 100644 --- a/crates/stdlib/src/_sqlite3.rs +++ b/crates/stdlib/src/_sqlite3.rs @@ -1736,8 +1736,7 @@ mod _sqlite3 { st.bind_parameters(¶meters, vm)?; } else if params_needed > 0 { let msg = format!( - "Incorrect number of bindings supplied. The current statement uses {}, and 0 were supplied.", - params_needed + "Incorrect number of bindings supplied. The current statement uses {params_needed}, and 0 were supplied." ); return Err(new_programming_error(vm, msg)); } @@ -3175,8 +3174,7 @@ mod _sqlite3 { return Err(new_programming_error( vm, format!( - "Incorrect number of bindings supplied. The current statement uses {}, and {} were supplied.", - num_needed, num_supplied + "Incorrect number of bindings supplied. The current statement uses {num_needed}, and {num_supplied} were supplied." ), )); } From 7c9297e29f7ce3a39aabfbe2bc8ef9cf387c28f7 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 15:27:40 +0300 Subject: [PATCH 11/12] more --- crates/vm/src/stdlib/_winapi.rs | 3 +-- crates/vm/src/stdlib/_wmi.rs | 7 +++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/vm/src/stdlib/_winapi.rs b/crates/vm/src/stdlib/_winapi.rs index 9edb740cdb0..941a294ca48 100644 --- a/crates/vm/src/stdlib/_winapi.rs +++ b/crates/vm/src/stdlib/_winapi.rs @@ -1599,8 +1599,7 @@ mod _winapi { let max_total_objects = (MAXIMUM_WAIT_OBJECTS - 1) * (MAXIMUM_WAIT_OBJECTS - 1); if nhandles > max_total_objects { return Err(vm.new_value_error(format!( - "need at most {} handles, got a sequence of length {}", - max_total_objects, nhandles + "need at most {max_total_objects} handles, got a sequence of length {nhandles}" ))); } diff --git a/crates/vm/src/stdlib/_wmi.rs b/crates/vm/src/stdlib/_wmi.rs index 927e68ce0c1..ce8898ae9fe 100644 --- a/crates/vm/src/stdlib/_wmi.rs +++ b/crates/vm/src/stdlib/_wmi.rs @@ -688,10 +688,9 @@ mod _wmi { } if err == ERROR_MORE_DATA { - return Err(vm.new_os_error(format!( - "Query returns more than {} characters", - BUFFER_SIZE, - ))); + return Err( + vm.new_os_error(format!("Query returns more than {BUFFER_SIZE} characters")) + ); } else if err != 0 { return Err(std::io::Error::from_raw_os_error(err as i32).to_pyexception(vm)); } From 82ab35cf9513f31ae23910723bf599243e62ef38 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 14 May 2026 16:10:18 +0300 Subject: [PATCH 12/12] more --- crates/stdlib/src/locale.rs | 2 +- crates/stdlib/src/mmap.rs | 2 +- crates/stdlib/src/overlapped.rs | 9 +++------ crates/stdlib/src/socket.rs | 7 +++---- crates/stdlib/src/ssl.rs | 6 ++---- 5 files changed, 10 insertions(+), 16 deletions(-) diff --git a/crates/stdlib/src/locale.rs b/crates/stdlib/src/locale.rs index 085d07b250c..251c9586e18 100644 --- a/crates/stdlib/src/locale.rs +++ b/crates/stdlib/src/locale.rs @@ -308,7 +308,7 @@ mod _locale { { // On Windows, use GetACP() to get the ANSI code page let acp = unsafe { GetACP() }; - format!("cp{}", acp) + format!("cp{acp}") } #[cfg(not(windows))] { diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index e5e77218a17..744bb7bb79a 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -579,7 +579,7 @@ mod mmap { let handle = unsafe { suppress_iph!(libc::get_osfhandle(fileno)) }; // Check for invalid handle value (-1 on Windows) if handle == -1 || handle == INVALID_HANDLE_VALUE as isize { - return Err(vm.new_os_error(format!("Invalid file descriptor: {}", fileno))); + return Err(vm.new_os_error(format!("Invalid file descriptor: {fileno}"))); } Some(handle as HANDLE) } else { diff --git a/crates/stdlib/src/overlapped.rs b/crates/stdlib/src/overlapped.rs index 77c3365186e..33a97a264b3 100644 --- a/crates/stdlib/src/overlapped.rs +++ b/crates/stdlib/src/overlapped.rs @@ -1555,13 +1555,11 @@ mod _overlapped { ERROR_SUCCESS | ERROR_NOT_FOUND | ERROR_OPERATION_ABORTED => {} _ => { let msg = format!( - "{:?} still has pending operation at deallocation, the process may crash", - zelf + "{zelf:?} still has pending operation at deallocation, the process may crash" ); let exc = vm.new_runtime_error(msg); let err_msg = Some(format!( - "Exception ignored while deallocating overlapped operation {:?}", - zelf + "Exception ignored while deallocating overlapped operation {zelf:?}" )); let obj: PyObjectRef = zelf.to_owned().into(); vm.run_unraisable(exc, err_msg, obj); @@ -1656,9 +1654,8 @@ mod _overlapped { if overlapped.is_null() { if err == Foundation::WAIT_TIMEOUT { return Ok(vm.ctx.none()); - } else { - return Err(set_from_windows_err(err, vm)); } + return Err(set_from_windows_err(err, vm)); } let value = vm.ctx.new_tuple(vec![ diff --git a/crates/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index 920a02a3d0c..ecedb136f53 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -1492,8 +1492,7 @@ mod _socket { if bytes_data.len() != expected_size { return Err(vm .new_value_error(format!( - "socket descriptor string has wrong size, should be {} bytes", - expected_size + "socket descriptor string has wrong size, should be {expected_size} bytes" )) .into()); } @@ -2393,7 +2392,7 @@ mod _socket { let cmd_val = cmd_int.as_bigint(); let cmd: u32 = cmd_val .to_u32() - .ok_or_else(|| vm.new_value_error(format!("invalid ioctl command {}", cmd_val)))?; + .ok_or_else(|| vm.new_value_error(format!("invalid ioctl command {cmd_val}")))?; match cmd { c::SIO_RCVALL | c::SIO_LOOPBACK_FAST_PATH => { @@ -2466,7 +2465,7 @@ mod _socket { Ok(recv) } _ => Err(vm - .new_value_error(format!("invalid ioctl command {}", cmd)) + .new_value_error(format!("invalid ioctl command {cmd}")) .into()), } } diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index fc978b22878..95321d37e52 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -4947,8 +4947,7 @@ mod _ssl { // If no stores could be opened, raise OSError if stores.is_empty() { return Err(vm.new_os_error(format!( - "failed to open certificate store {:?}", - store_name_str + "failed to open certificate store {store_name_str:?}" ))); } @@ -5000,8 +4999,7 @@ mod _ssl { if store.is_null() { return Err(vm.new_os_error(format!( - "failed to open certificate store {:?}", - store_name_str + "failed to open certificate store {store_name_str:?}" ))); }