diff --git a/Cargo.toml b/Cargo.toml index 3262749b72c..4e4092f3a5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -252,6 +252,16 @@ elided_lifetimes_in_paths = "warn" alloc_instead_of_core = "warn" std_instead_of_alloc = "warn" std_instead_of_core = "warn" +format_collect = "warn" +from_iter_instead_of_collect = "warn" +inefficient_to_string = "warn" +redundant_clone = "warn" +debug_assert_with_mut_call = "warn" +unused_peekable = "warn" +manual_is_variant_and = "warn" +or_fun_call = "warn" +unnested_or_patterns = "warn" + perf = "warn" style = "warn" complexity = "warn" diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index e79226cf141..727df5b55c1 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -1374,7 +1374,7 @@ impl Compiler { // Create the new compilation unit let code_info = ir::CodeInfo { flags, - source_path: source_path.clone(), + source_path, private, blocks: vec![ir::Block::default()], current_block: BlockIdx::new(0), @@ -6718,7 +6718,7 @@ impl Compiler { } // Restore the original pattern context. - *pc = old_pc.clone(); + *pc = old_pc; // Simulate Py_INCREF on pc.stores. pc.stores = pc.stores.clone(); // In C, old_pc.fail_pop is set to NULL to avoid freeing it later. @@ -14487,8 +14487,7 @@ def outer(): assert!( matches!( ops.get(cleanup_idx + 1), - Some(Instruction::JumpBackwardNoInterrupt { .. }) - | Some(Instruction::JumpForward { .. }) + Some(Instruction::JumpBackwardNoInterrupt { .. } | Instruction::JumpForward { .. }) ), "expected CLEANUP_THROW to jump to shared END_SEND block, got ops={ops:?}" ); @@ -14533,7 +14532,7 @@ def f(): assert!( matches!( ops.get(first_pop_except + 1), - Some(Instruction::LoadSmallInt { .. }) | Some(Instruction::LoadConst { .. }) + Some(Instruction::LoadSmallInt { .. } | Instruction::LoadConst { .. }) ), "expected line-after-except code immediately after POP_EXCEPT, got ops={ops:?}" ); @@ -16145,8 +16144,10 @@ _pathseps_with_colon = {f':{s}' for s in path_separators} assert!( !ops.windows(2).any(|window| matches!( window, - [Instruction::LoadFast { .. }, Instruction::GetIter] - | [Instruction::LoadFastCheck { .. }, Instruction::GetIter] + [ + Instruction::LoadFast { .. } | Instruction::LoadFastCheck { .. }, + Instruction::GetIter + ] )), "module local outer iterable should not become a fast local, got ops={ops:?}" ); diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index 18d878c4901..4e92610b15b 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -2036,8 +2036,9 @@ impl CodeInfo { let idx = i as usize; let swap_arg = match instructions[idx].instr.real() { Some(Instruction::Swap { .. }) => u32::from(instructions[idx].arg), - Some(Instruction::Nop) - | Some(Instruction::PopTop | Instruction::StoreFast { .. }) => { + Some( + Instruction::Nop | Instruction::PopTop | Instruction::StoreFast { .. }, + ) => { i -= 1; continue; } @@ -2332,8 +2333,10 @@ impl CodeInfo { match (curr_instr, next_instr) { // Note: StoreFast + LoadFast → StoreFastLoadFast is done in a // later pass aligned with CPython insert_superinstructions(). - (Instruction::LoadConst { .. }, Instruction::ToBool) - | (Instruction::LoadSmallInt { .. }, Instruction::ToBool) => { + ( + Instruction::LoadConst { .. } | Instruction::LoadSmallInt { .. }, + Instruction::ToBool, + ) => { if let Some(value) = const_truthiness(curr_instr, curr.arg, &self.metadata) { @@ -2355,10 +2358,10 @@ impl CodeInfo { curr_instr, OpArg::new(u32::from(curr.arg) | oparg::COMPARE_OP_BOOL_MASK), )), - (Instruction::ContainsOp { .. }, Instruction::ToBool) - | (Instruction::IsOp { .. }, Instruction::ToBool) => { - Some((curr_instr, curr.arg)) - } + ( + Instruction::ContainsOp { .. } | Instruction::IsOp { .. }, + Instruction::ToBool, + ) => Some((curr_instr, curr.arg)), (Instruction::LoadConst { consti }, Instruction::UnaryNot) => { let constant = &self.metadata.consts[consti.get(curr.arg).as_usize()]; match constant { @@ -2434,8 +2437,10 @@ impl CodeInfo { let redundant = matches!( (curr_instr, next_instr), - (Instruction::LoadConst { .. }, Instruction::PopTop) - | (Instruction::LoadSmallInt { .. }, Instruction::PopTop) + ( + Instruction::LoadConst { .. } | Instruction::LoadSmallInt { .. }, + Instruction::PopTop + ) ) || matches!(curr_instr, Instruction::Copy { i } if i.get(curr.arg) == 1) && matches!(next_instr, Instruction::PopTop); @@ -3757,7 +3762,7 @@ impl CodeInfo { Some(Instruction::PushExcInfo) => { in_exception_state = true; } - Some(Instruction::PopExcept) | Some(Instruction::Reraise { .. }) => { + Some(Instruction::PopExcept | Instruction::Reraise { .. }) => { in_exception_state = false; } Some(Instruction::LoadFastBorrow { .. }) if in_exception_state => { @@ -4458,10 +4463,10 @@ impl CodeInfo { Some( Instruction::StoreFast { .. } | Instruction::StoreFastLoadFast { .. } - | Instruction::StoreFastStoreFast { .. }, - ) - | Some(Instruction::DeleteFast { .. }) - | Some(Instruction::LoadFastAndClear { .. }) => return false, + | Instruction::StoreFastStoreFast { .. } + | Instruction::DeleteFast { .. } + | Instruction::LoadFastAndClear { .. }, + ) => return false, _ => {} } } @@ -4613,8 +4618,10 @@ impl CodeInfo { { if matches!( extra_info.instr.real(), - Some(Instruction::LoadFastBorrow { .. }) - | Some(Instruction::LoadFastBorrowLoadFastBorrow { .. }) + Some( + Instruction::LoadFastBorrow { .. } + | Instruction::LoadFastBorrowLoadFastBorrow { .. } + ) ) { to_deopt.push(*extra_instr_idx); } @@ -4642,8 +4649,10 @@ impl CodeInfo { { if matches!( tail_info.instr.real(), - Some(Instruction::LoadFastBorrow { .. }) - | Some(Instruction::LoadFastBorrowLoadFastBorrow { .. }) + Some( + Instruction::LoadFastBorrow { .. } + | Instruction::LoadFastBorrowLoadFastBorrow { .. } + ) ) { cross_block_deopts.push((tail_block_idx, tail_instr_idx)); } @@ -4722,7 +4731,7 @@ impl CodeInfo { && predecessor_blocks.iter().copied().all(|pred_idx| { matches!( last_real_instr(&self.blocks[pred_idx]), - Some(Instruction::PopIter) | Some(Instruction::Swap { .. }) + Some(Instruction::PopIter | Instruction::Swap { .. }) ) }) }) @@ -4743,7 +4752,7 @@ impl CodeInfo { && (new_instructions.iter().all(|prev: &InstructionInfo| { matches!( prev.instr.real(), - Some(Instruction::Swap { .. }) | Some(Instruction::PopTop) + Some(Instruction::Swap { .. } | Instruction::PopTop) ) }) || is_cleanup_restore_prefix(&new_instructions)) { @@ -4906,8 +4915,9 @@ impl CodeInfo { } new_instructions.push(info); } - Some(Instruction::LoadFast { var_num }) - | Some(Instruction::LoadFastBorrow { var_num }) => { + Some( + Instruction::LoadFast { var_num } | Instruction::LoadFastBorrow { var_num }, + ) => { let var_idx = usize::from(var_num.get(info.arg)); if var_idx < nlocals && unsafe_mask[var_idx] { info.instr = Opcode::LoadFastCheck.into(); @@ -4918,8 +4928,10 @@ impl CodeInfo { } new_instructions.push(info); } - Some(Instruction::LoadFastLoadFast { var_nums }) - | Some(Instruction::LoadFastBorrowLoadFastBorrow { var_nums }) => { + Some( + Instruction::LoadFastLoadFast { var_nums } + | Instruction::LoadFastBorrowLoadFastBorrow { var_nums }, + ) => { let packed = var_nums.get(info.arg); let (idx1, idx2) = packed.indexes(); let idx1 = usize::from(idx1); @@ -6802,7 +6814,7 @@ fn deoptimize_borrow_after_push_exc_info_in_blocks(blocks: &mut [Block]) { Some(Instruction::PushExcInfo) => { in_exception_state = true; } - Some(Instruction::PopExcept) | Some(Instruction::Reraise { .. }) => { + Some(Instruction::PopExcept | Instruction::Reraise { .. }) => { in_exception_state = false; } Some(Instruction::LoadFastBorrow { .. }) if in_exception_state => { @@ -6896,7 +6908,7 @@ fn is_exit_without_lineno(block: &Block) -> bool { && prefix.iter().all(|info| { matches!( info.instr.real(), - Some(Instruction::PopExcept) | Some(Instruction::Nop) + Some(Instruction::PopExcept | Instruction::Nop) ) }) && prefix @@ -6924,7 +6936,7 @@ fn shared_jump_back_target(block: &Block) -> Option { if !prefix.iter().all(|info| { matches!( info.instr.real(), - Some(Instruction::PopExcept) | Some(Instruction::Nop) + Some(Instruction::PopExcept | Instruction::Nop) ) }) { return None; diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index 5cc24b4d4ce..bafc7c81cf1 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -1410,10 +1410,12 @@ impl SymbolTableBuilder { let parent_scope_typ = self.tables.last().map(|t| t.typ); let should_save_annotation_block = matches!( parent_scope_typ, - Some(CompilerScope::Class) - | Some(CompilerScope::Module) - | Some(CompilerScope::Function) - | Some(CompilerScope::AsyncFunction) + Some( + CompilerScope::Class + | CompilerScope::Module + | CompilerScope::Function + | CompilerScope::AsyncFunction + ) ); let saved_annotation_block = if should_save_annotation_block { self.tables.last_mut().unwrap().annotation_block.take() diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index fdf814cba91..58dae34b2ce 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -490,7 +490,7 @@ impl FormatSpec { pub fn is_decimal_int_format(&self) -> bool { matches!( self.format_type, - None | Some(FormatType::Decimal) | Some(FormatType::Number(Case::Lower)) + None | Some(FormatType::Decimal | FormatType::Number(Case::Lower)) ) } @@ -707,18 +707,20 @@ impl FormatSpec { *case, self.alternate_form, )), - Some(FormatType::Decimal) - | Some(FormatType::Binary) - | Some(FormatType::Octal) - | Some(FormatType::Hex(_)) - | Some(FormatType::String) - | Some(FormatType::Character) - | Some(FormatType::Number(Case::Upper)) - | Some(FormatType::Unknown(_)) => { + Some( + FormatType::Decimal + | FormatType::Binary + | FormatType::Octal + | FormatType::Hex(_) + | FormatType::String + | FormatType::Character + | FormatType::Number(Case::Upper) + | FormatType::Unknown(_), + ) => { let ch = char::from(self.format_type.as_ref().unwrap()); Err(FormatSpecError::UnknownFormatCode(ch, "float")) } - Some(FormatType::GeneralFormat(case)) | Some(FormatType::Number(case)) => { + Some(FormatType::GeneralFormat(case) | FormatType::Number(case)) => { let precision = if precision == 0 { 1 } else { precision }; Ok(float::format_general( precision, @@ -835,10 +837,12 @@ impl FormatSpec { Some(_) | None => Err(FormatSpecError::CodeNotInRange), }, }, - Some(FormatType::GeneralFormat(_)) - | Some(FormatType::FixedPoint(_)) - | Some(FormatType::Exponent(_)) - | Some(FormatType::Percentage) => match num.to_f64() { + Some( + FormatType::GeneralFormat(_) + | FormatType::FixedPoint(_) + | FormatType::Exponent(_) + | FormatType::Percentage, + ) => match num.to_f64() { Some(float) => return self.format_float(float), _ => Err(FormatSpecError::UnableToConvert), }, @@ -895,7 +899,7 @@ impl FormatSpec { if let Some(FormatAlign::AfterSign) = &self.align { return Err(FormatSpecError::AlignmentFlag); } - match &self.fill.unwrap_or(' '.into()).to_char() { + match &self.fill.unwrap_or_else(|| ' '.into()).to_char() { Some('0') => Err(FormatSpecError::ZeroPadding), _ => self.format_sign_and_align(&AsciiStr::new(&magnitude_str), "", FormatAlign::Right), } @@ -934,15 +938,17 @@ impl FormatSpec { let precision = self.precision.unwrap_or(6); let magnitude = num.abs(); let magnitude_str = match &self.format_type { - Some(FormatType::Decimal) - | Some(FormatType::Binary) - | Some(FormatType::Octal) - | Some(FormatType::Hex(_)) - | Some(FormatType::String) - | Some(FormatType::Character) - | Some(FormatType::Number(Case::Upper)) - | Some(FormatType::Percentage) - | Some(FormatType::Unknown(_)) => { + Some( + FormatType::Decimal + | FormatType::Binary + | FormatType::Octal + | FormatType::Hex(_) + | FormatType::String + | FormatType::Character + | FormatType::Number(Case::Upper) + | FormatType::Percentage + | FormatType::Unknown(_), + ) => { let ch = char::from(self.format_type.as_ref().unwrap()); Err(FormatSpecError::UnknownFormatCode(ch, "complex")) } @@ -952,7 +958,7 @@ impl FormatSpec { *case, self.alternate_form, )), - Some(FormatType::GeneralFormat(case)) | Some(FormatType::Number(case)) => { + Some(FormatType::GeneralFormat(case) | FormatType::Number(case)) => { let precision = if precision == 0 { 1 } else { precision }; Ok(float::format_general( precision, @@ -1014,7 +1020,7 @@ impl FormatSpec { let align = self.align.unwrap_or(default_align); let num_chars = magnitude_str.char_len(); - let fill_char = self.fill.unwrap_or(' '.into()); + let fill_char = self.fill.unwrap_or_else(|| ' '.into()); let fill_chars_needed: i32 = self.width.map_or(0, |w| { cmp::max(0, (w as i32) - (num_chars as i32) - (sign_str.len() as i32)) }); diff --git a/crates/common/src/str.rs b/crates/common/src/str.rs index 38e73a683f2..171dd80c7a6 100644 --- a/crates/common/src/str.rs +++ b/crates/common/src/str.rs @@ -415,9 +415,7 @@ pub fn zfill(bytes: &[u8], width: usize) -> Vec { bytes.to_vec() } else { let (sign, s) = match bytes.first() { - Some(_sign @ b'+') | Some(_sign @ b'-') => { - (unsafe { bytes.get_unchecked(..1) }, &bytes[1..]) - } + Some(_sign @ (b'+' | b'-')) => (unsafe { bytes.get_unchecked(..1) }, &bytes[1..]), _ => (&b""[..], bytes), }; let mut filled = Vec::new(); diff --git a/crates/derive-impl/src/pyclass.rs b/crates/derive-impl/src/pyclass.rs index e675d6a9f73..4ab63d6f9ca 100644 --- a/crates/derive-impl/src/pyclass.rs +++ b/crates/derive-impl/src/pyclass.rs @@ -1951,11 +1951,9 @@ where { use AttrName::*; Ok(match attr_name { - attr_name @ Method | attr_name @ ClassMethod | attr_name @ StaticMethod => { - Box::new(MethodItem { - inner: ContentItemInner { index, attr_name }, - }) - } + attr_name @ (Method | ClassMethod | StaticMethod) => Box::new(MethodItem { + inner: ContentItemInner { index, attr_name }, + }), GetSet => Box::new(GetSetItem { inner: ContentItemInner { index, attr_name }, }), diff --git a/crates/derive-impl/src/pystructseq.rs b/crates/derive-impl/src/pystructseq.rs index c59a1df2e31..51628d438f1 100644 --- a/crates/derive-impl/src/pystructseq.rs +++ b/crates/derive-impl/src/pystructseq.rs @@ -398,7 +398,7 @@ pub(crate) fn impl_pystruct_sequence_data( // For attribute macro, we need to output the original struct as well // But first, strip #[pystruct_sequence] attributes from fields - let mut clean_struct = item_struct.clone(); + let mut clean_struct = item_struct; if let syn::Fields::Named(ref mut fields) = clean_struct.fields { for field in &mut fields.named { field diff --git a/crates/jit/src/instructions.rs b/crates/jit/src/instructions.rs index 88f6fe7411a..ec9501d1fa8 100644 --- a/crates/jit/src/instructions.rs +++ b/crates/jit/src/instructions.rs @@ -580,10 +580,10 @@ impl<'a, 'b> FunctionCompiler<'a, 'b> { let b_type: Option = b.to_jit_type(); match (a, b) { - (JitValue::Int(a), JitValue::Int(b)) - | (JitValue::Bool(a), JitValue::Bool(b)) - | (JitValue::Bool(a), JitValue::Int(b)) - | (JitValue::Int(a), JitValue::Bool(b)) => { + ( + JitValue::Int(a) | JitValue::Bool(a), + JitValue::Int(b) | JitValue::Bool(b), + ) => { let operand_one = match a_type.unwrap() { JitType::Bool => self.builder.ins().uextend(types::I64, a), _ => a, diff --git a/crates/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index d58492a82a5..508947b561f 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -197,7 +197,7 @@ pub(crate) mod _asyncio { // Check if loop has get_debug method and call it if let Ok(Some(get_debug)) = - vm.get_attribute_opt(loop_obj.clone(), vm.ctx.intern_str("get_debug")) + vm.get_attribute_opt(loop_obj, vm.ctx.intern_str("get_debug")) && let Ok(debug) = get_debug.call((), vm) && debug.try_to_bool(vm).unwrap_or(false) { @@ -1923,8 +1923,10 @@ pub(crate) mod _asyncio { let state = zelf.base.fut_state.load().as_str().to_lowercase(); let name = zelf.task_name.read().as_ref().and_then(|n| n.str(vm).ok()); let coro_repr = zelf.task_coro.read().as_ref().and_then(|c| c.repr(vm).ok()); - let name = name.as_ref().map_or("?".as_ref(), |s| s.as_wtf8()); - let coro_repr = coro_repr.as_ref().map_or("?".as_ref(), |s| s.as_wtf8()); + let name = name.as_ref().map_or_else(|| "?".as_ref(), |s| s.as_wtf8()); + let coro_repr = coro_repr + .as_ref() + .map_or_else(|| "?".as_ref(), |s| s.as_wtf8()); Ok(wtf8_concat!( "<", class_name, " ", state, " name='", name, "' coro=", coro_repr, ">" )) @@ -1971,8 +1973,8 @@ pub(crate) mod _asyncio { let coro_ref = match coro { Some(c) => c, None => { - let _ = _swap_current_task(loop_obj.clone(), prev_task, vm); - _unregister_eager_task(task_obj.clone(), vm)?; + let _ = _swap_current_task(loop_obj, prev_task, vm); + _unregister_eager_task(task_obj, vm)?; return Ok(()); } }; @@ -1983,18 +1985,18 @@ pub(crate) mod _asyncio { match coro { Some(c) => vm.call_method(&c, "send", (vm.ctx.none(),)), None => { - let _ = _swap_current_task(loop_obj.clone(), prev_task, vm); - _unregister_eager_task(task_obj.clone(), vm)?; + let _ = _swap_current_task(loop_obj, prev_task, vm); + _unregister_eager_task(task_obj, vm)?; return Ok(()); } } }; // Restore previous task - let _ = _swap_current_task(loop_obj.clone(), prev_task, vm); + let _ = _swap_current_task(loop_obj, prev_task, vm); // Unregister from eager tasks - _unregister_eager_task(task_obj.clone(), vm)?; + _unregister_eager_task(task_obj, vm)?; // Handle the result match step_result { @@ -2032,7 +2034,7 @@ pub(crate) mod _asyncio { let exc = new_invalid_state_error(vm, "step(): already done"); let context = vm.ctx.new_dict(); context.set_item("message", vm.new_pyobj("step(): already done"), vm)?; - context.set_item("exception", exc.clone().into(), vm)?; + context.set_item("exception", exc.into(), vm)?; context.set_item("task", task.clone(), vm)?; let _ = vm.call_method(&loop_obj, "call_exception_handler", (context,)); } diff --git a/crates/stdlib/src/contextvars.rs b/crates/stdlib/src/contextvars.rs index 1fc98edb5a7..63807f1aafc 100644 --- a/crates/stdlib/src/contextvars.rs +++ b/crates/stdlib/src/contextvars.rs @@ -206,7 +206,7 @@ mod _contextvars { ) -> PyResult> { let found = self.get_inner(&key); let result = if let Some(found) = found { - Some(found.to_owned()) + Some(found) } else { default.into_option() }; @@ -254,7 +254,7 @@ mod _contextvars { let needle = needle.try_to_value(vm)?; let found = PyContext::mapping_downcast(mapping).get_inner(needle); if let Some(found) = found { - Ok(found.to_owned()) + Ok(found) } else { Err(vm.new_key_error(needle.to_owned().into())) } @@ -424,7 +424,7 @@ mod _contextvars { let old_value = ctx.borrow_vars().get(zelf).map(|v| v.to_owned()); let token = ContextToken { - ctx: ctx.to_owned(), + ctx, var: zelf.to_owned(), old_value, used: false.into(), diff --git a/crates/stdlib/src/csv.rs b/crates/stdlib/src/csv.rs index a1147fd1cbb..5c2d2662cc5 100644 --- a/crates/stdlib/src/csv.rs +++ b/crates/stdlib/src/csv.rs @@ -95,8 +95,8 @@ mod _csv { #[pygetset] fn lineterminator(&self, vm: &VirtualMachine) -> PyRef { match self.lineterminator { - Terminator::CRLF => vm.ctx.new_str("\r\n".to_string()).to_owned(), - Terminator::Any(t) => vm.ctx.new_str(format!("{}", t as char)).to_owned(), + Terminator::CRLF => vm.ctx.new_str("\r\n".to_string()), + Terminator::Any(t) => vm.ctx.new_str(format!("{}", t as char)), _ => unreachable!(), } } @@ -195,7 +195,7 @@ mod _csv { r#""escapechar" must be a unicode character or None, not {}"#, attr.class() ); - Err(vm.new_type_error(msg.to_owned())) + Err(vm.new_type_error(msg)) } }) } @@ -231,7 +231,7 @@ mod _csv { } attr => { let msg = format!(r#""quoting" must be string or None, not {}"#, attr.class()); - Err(vm.new_type_error(msg.to_owned())) + Err(vm.new_type_error(msg)) } }) } @@ -1025,10 +1025,9 @@ mod _csv { // Rustpython TODO! // Incomplete implementation if let QuoteStyle::Nonnumeric = zelf.dialect.quoting { - if let Ok(t) = - String::from_utf8(trim_spaces(&buffer[range.clone()]).to_vec()) - .unwrap() - .parse::() + if let Ok(t) = String::from_utf8(trim_spaces(&buffer[range]).to_vec()) + .unwrap() + .parse::() { Ok(vm.ctx.new_int(t).into()) } else { diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index c492c960750..ca666418a2d 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -983,7 +983,7 @@ mod mmap { let buf = &mmap.as_ref().unwrap().as_slice()[start..end]; let pos = buf.windows(sub.len()).position(|window| window == sub); - Ok(pos.map_or(PyInt::from(-1isize), |i| PyInt::from(start + i))) + Ok(pos.map_or_else(|| PyInt::from(-1isize), |i| PyInt::from(start + i))) } #[pymethod] @@ -1000,7 +1000,7 @@ mod mmap { let buf = &mmap.as_ref().unwrap().as_slice()[start..end]; let pos = buf.windows(sub.len()).rposition(|window| window == sub); - Ok(pos.map_or(PyInt::from(-1isize), |i| PyInt::from(start + i))) + Ok(pos.map_or_else(|| PyInt::from(-1isize), |i| PyInt::from(start + i))) } #[pymethod] diff --git a/crates/stdlib/src/posixsubprocess.rs b/crates/stdlib/src/posixsubprocess.rs index 01b0d466ffc..d81af198563 100644 --- a/crates/stdlib/src/posixsubprocess.rs +++ b/crates/stdlib/src/posixsubprocess.rs @@ -50,7 +50,7 @@ mod _posixsubprocess { .as_ref() .map(|l| Vec::::try_from_borrowed_object(vm, l.as_object())) .transpose()?; - let argv = CharPtrVec::from_iter(args.args.iter()); + let argv = args.args.iter().collect::>(); let envp = args.env_list.as_ref().map(CharPtrVec::from_iter); let procargs = ProcArgs { argv: &argv, diff --git a/crates/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index fed5019c1b7..baffbcaff7e 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -893,6 +893,7 @@ mod _socket { c::$e }; } + #[cfg(windows)] macro_rules! errcode { ($e:ident) => { @@ -1528,7 +1529,7 @@ mod _socket { if family == -1 || matches!( e.raw_os_error(), - Some(errcode!(ENOTSOCK)) | Some(errcode!(EBADF)) + Some(errcode!(ENOTSOCK) | errcode!(EBADF)) ) => { core::mem::forget(sock); @@ -1555,10 +1556,7 @@ mod _socket { Ok(addr) if family == -1 => family = addr.family() as i32, Err(e) if family == -1 - || matches!( - e.raw_os_error(), - Some(errcode!(ENOTSOCK)) | Some(errcode!(EBADF)) - ) => + || matches!(e.raw_os_error(), Some(c::ENOTSOCK | c::EBADF)) => { core::mem::forget(sock); return Err(e.into()); @@ -2582,7 +2580,8 @@ mod _socket { return vm.ctx.new_bytes([b"\0", abstractpath].concat()).into(); } // necessary on macos - let path = ffi::OsStr::as_bytes(addr.as_pathname().unwrap_or("".as_ref()).as_ref()); + let path = + ffi::OsStr::as_bytes(addr.as_pathname().unwrap_or_else(|| "".as_ref()).as_ref()); let nul_pos = memchr::memchr(b'\0', path).unwrap_or(path.len()); let path = ffi::OsStr::from_bytes(&path[..nul_pos]); return vm.fsdecode(path).into(); diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index 51f5bc042f4..cbc842538a9 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -1760,7 +1760,7 @@ mod _ssl { // Set filename attribute let _ = exc .as_object() - .set_attr("filename", vm.ctx.new_str(path_str.clone()), vm); + .set_attr("filename", vm.ctx.new_str(path_str), vm); return Err(exc.upcast()); } @@ -2690,7 +2690,7 @@ mod _ssl { .clone() .ok_or_else(|| vm.new_value_error("SNI callback not set"))?; - let ssl_sock = self.owner.read().clone().unwrap_or(vm.ctx.none()); + let ssl_sock = self.owner.read().clone().unwrap_or_else(|| vm.ctx.none()); let server_name_py: PyObjectRef = match sni_name { Some(name) => vm.ctx.new_str(name.to_string()).into(), None => vm.ctx.none(), @@ -2732,7 +2732,7 @@ mod _ssl { "servername callback must return None or an integer, not '{}'", result.class().name() )); - vm.run_unraisable(type_error, None, result.clone()); + vm.run_unraisable(type_error, None, result); // Return SSL error with reason set to TLSV1_ALERT_INTERNAL_ERROR // diff --git a/crates/stdlib/src/ssl/cert.rs b/crates/stdlib/src/ssl/cert.rs index 0ae71208c5c..f838733c03d 100644 --- a/crates/stdlib/src/ssl/cert.rs +++ b/crates/stdlib/src/ssl/cert.rs @@ -930,10 +930,8 @@ impl ServerCertVerifier for HostnameIgnoringVerifier { // If so, ignore it (that's the whole point of HostnameIgnoringVerifier) match e { rustls::Error::InvalidCertificate( - rustls::CertificateError::NotValidForName, - ) - | rustls::Error::InvalidCertificate( - rustls::CertificateError::NotValidForNameContext { .. }, + rustls::CertificateError::NotValidForName + | rustls::CertificateError::NotValidForNameContext { .. }, ) => { // Hostname mismatch - this is expected and acceptable // The certificate chain, trust anchor, and expiry are valid diff --git a/crates/stdlib/src/ssl/compat.rs b/crates/stdlib/src/ssl/compat.rs index 14812375a8b..a703ab4d8b0 100644 --- a/crates/stdlib/src/ssl/compat.rs +++ b/crates/stdlib/src/ssl/compat.rs @@ -725,7 +725,7 @@ pub(super) fn create_server_config(options: ServerConfigOptions) -> Result Result Result Result Self::Native, Some(b'=') => Self::Host, Some(b'<') => Self::Little, - Some(b'>') | Some(b'!') => Self::Big, + Some(b'>' | b'!') => Self::Big, _ => return Self::Native, }; chars.next().unwrap(); diff --git a/crates/vm/src/builtins/builtin_func.rs b/crates/vm/src/builtins/builtin_func.rs index a09fb60c15a..95c743b16ba 100644 --- a/crates/vm/src/builtins/builtin_func.rs +++ b/crates/vm/src/builtins/builtin_func.rs @@ -31,7 +31,8 @@ impl fmt::Debug for PyNativeFunction { write!( f, "builtin function {}.{} ({:?}) self as instance of {:?}", - self.module.map_or(Wtf8::new(""), |m| m.as_wtf8()), + self.module + .map_or_else(|| Wtf8::new(""), |m| m.as_wtf8()), self.value.name, self.value.flags, self.zelf.as_ref().map(|z| z.class().name().to_owned()) diff --git a/crates/vm/src/builtins/code.rs b/crates/vm/src/builtins/code.rs index dd5cb14f84b..d2da5fc5a70 100644 --- a/crates/vm/src/builtins/code.rs +++ b/crates/vm/src/builtins/code.rs @@ -1195,7 +1195,7 @@ impl PyCode { let target = after_cache + oparg as usize; let right = if matches!( instructions.get(target).map(|u| u.op), - Some(Instruction::EndFor) | Some(Instruction::InstrumentedEndFor) + Some(Instruction::EndFor | Instruction::InstrumentedEndFor) ) { (target + 1) * 2 } else { diff --git a/crates/vm/src/builtins/function.rs b/crates/vm/src/builtins/function.rs index 770af56217b..93ba3693b93 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -200,7 +200,7 @@ impl PyFunction { let qualname = vm.ctx.new_str(code.qualname.as_str()); let func = Self { - code: PyAtomicRef::from(code.clone()), + code: PyAtomicRef::from(code), globals, builtins, closure: None, @@ -493,7 +493,6 @@ impl PyFunction { } bytecode::MakeFunctionFlag::Closure => { let closure_tuple = attr_value - .clone() .downcast_exact::(vm) .map_err(|obj| { vm.new_type_error(format!( @@ -701,7 +700,7 @@ impl Py { }; let frame = Frame::new( - code.clone(), + code, Scope::new(locals, self.globals.clone()), self.builtins.clone(), self.closure.as_ref().map_or(&[], |c| c.as_slice()), @@ -1379,7 +1378,9 @@ impl Representable for PyBoundMethod { }; let func_name: Option = func_name.and_then(|o| o.downcast().ok()); let object_repr = zelf.object.repr(vm)?; - let name = func_name.as_ref().map_or("?".as_ref(), |s| s.as_wtf8()); + let name = func_name + .as_ref() + .map_or_else(|| "?".as_ref(), |s| s.as_wtf8()); Ok(wtf8_concat!( "() - .is_some_and(|s| matches!(s.to_str(), Some("s") | Some("r") | Some("a"))); + .is_some_and(|s| matches!(s.to_str(), Some("s" | "r" | "a"))); if !is_valid { return Err(vm.new_exception_msg( vm.ctx.exceptions.system_error.to_owned(), diff --git a/crates/vm/src/builtins/range.rs b/crates/vm/src/builtins/range.rs index 153a82bb43b..6e03ea8b482 100644 --- a/crates/vm/src/builtins/range.rs +++ b/crates/vm/src/builtins/range.rs @@ -55,7 +55,7 @@ fn iter_search( "{} not in range", item.repr(vm) .as_ref() - .map_or("value".as_ref(), |s| s.as_wtf8()) + .map_or_else(|_| "value".as_ref(), |s| s.as_wtf8()) .to_owned() ))), } diff --git a/crates/vm/src/builtins/set.rs b/crates/vm/src/builtins/set.rs index a6a58367f4f..fe1da1174d7 100644 --- a/crates/vm/src/builtins/set.rs +++ b/crates/vm/src/builtins/set.rs @@ -514,6 +514,7 @@ fn reduce_set( ) -> PyResult<(PyTypeRef, PyTupleRef, Option)> { Ok(( zelf.class().to_owned(), + #[expect(clippy::or_fun_call, reason = "changing this won't compile")] vm.new_tuple((extract_set(zelf) .unwrap_or(&PySetInner::default()) .elements(),)), @@ -834,11 +835,7 @@ impl AsNumber for PySet { } else if let Some(a) = a.downcast_ref::() { // When called via __rsub__, a might be PyFrozenSet a.__sub__(b.to_owned(), vm) - .map(|r| { - r.map(|s| PySet { - inner: s.inner.clone(), - }) - }) + .map(|r| r.map(|s| PySet { inner: s.inner })) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) @@ -852,11 +849,7 @@ impl AsNumber for PySet { a.__and__(b.to_owned(), vm).to_pyresult(vm) } else if let Some(a) = a.downcast_ref::() { a.__and__(b.to_owned(), vm) - .map(|r| { - r.map(|s| PySet { - inner: s.inner.clone(), - }) - }) + .map(|r| r.map(|s| PySet { inner: s.inner })) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) @@ -870,11 +863,7 @@ impl AsNumber for PySet { a.__xor__(b.to_owned(), vm).to_pyresult(vm) } else if let Some(a) = a.downcast_ref::() { a.__xor__(b.to_owned(), vm) - .map(|r| { - r.map(|s| PySet { - inner: s.inner.clone(), - }) - }) + .map(|r| r.map(|s| PySet { inner: s.inner })) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) @@ -888,11 +877,7 @@ impl AsNumber for PySet { a.__or__(b.to_owned(), vm).to_pyresult(vm) } else if let Some(a) = a.downcast_ref::() { a.__or__(b.to_owned(), vm) - .map(|r| { - r.map(|s| PySet { - inner: s.inner.clone(), - }) - }) + .map(|r| r.map(|s| PySet { inner: s.inner })) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index e900014b6e1..5c834919c01 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -1521,7 +1521,7 @@ impl PyType { if !vm.is_none(&value) { attrs.swap_remove(identifier!(vm, __annotations_cache__)); } - attrs.insert(identifier!(vm, __annotate_func__), value.clone()); + attrs.insert(identifier!(vm, __annotate_func__), value); Ok(()) } diff --git a/crates/vm/src/codecs.rs b/crates/vm/src/codecs.rs index e4e3faa5809..8e393ee7dc2 100644 --- a/crates/vm/src/codecs.rs +++ b/crates/vm/src/codecs.rs @@ -916,7 +916,7 @@ impl<'a> EncodeErrorHandler> for ErrorsHandler<'_> { ResolvedError::Handler(handler) => handler, }; let encode_exc = ctx.error_encoding(range.clone(), reason); - let res = handler.call((encode_exc.clone(),), vm)?; + let res = handler.call((encode_exc,), vm)?; let tuple_err = || vm.new_type_error("encoding error handler must return (str/bytes, int) tuple"); let (replace, restart) = match res.downcast_ref::().map(|tup| tup.as_slice()) { @@ -945,7 +945,7 @@ impl<'a> EncodeErrorHandler> for ErrorsHandler<'_> { .as_wtf8() .code_point_indices() .nth(restart) - .map_or(ctx.data.byte_len(), |(i, _)| i), + .map_or_else(|| ctx.data.byte_len(), |(i, _)| i), } }; Ok((replace, restart)) @@ -965,7 +965,7 @@ impl<'a> DecodeErrorHandler> for ErrorsHandler<'_> { } ResolvedError::Handler(handler) => handler, }; - let decode_exc = ctx.error_decoding(byte_range.clone(), reason); + let decode_exc = ctx.error_decoding(byte_range, reason); let data_bytes: PyObjectRef = decode_exc.as_object().get_attr("object", vm)?; let res = handler.call((decode_exc.clone(),), vm)?; let new_data = decode_exc.as_object().get_attr("object", vm)?; @@ -1025,7 +1025,7 @@ where let end = StrSize { chars: range.end, bytes: if let Some(n) = range.len().checked_sub(1) { - iter.nth(n).map_or(s.byte_len(), |(i, _)| i) + iter.nth(n).map_or_else(|| s.byte_len(), |(i, _)| i) } else { start.bytes }, @@ -1088,7 +1088,7 @@ where let end = StrSize { chars: range.end, bytes: if let Some(n) = range.len().checked_sub(1) { - iter.nth(n).map_or(s.byte_len(), |(i, _)| i) + iter.nth(n).map_or_else(|| s.byte_len(), |(i, _)| i) } else { start.bytes }, diff --git a/crates/vm/src/exception_group.rs b/crates/vm/src/exception_group.rs index 02342e4003d..76558af1d35 100644 --- a/crates/vm/src/exception_group.rs +++ b/crates/vm/src/exception_group.rs @@ -113,7 +113,7 @@ pub(super) mod types { } if !modified { - return Ok(zelf.clone().into()); + return Ok(zelf.into()); } if matching.is_empty() { @@ -211,12 +211,14 @@ pub(super) mod types { let mut result = Wtf8Buf::new(); write!(result, "{class_name}(").unwrap(); - let message_wtf8: &Wtf8 = message.as_ref().map_or("''".as_ref(), |s| s.as_wtf8()); + let message_wtf8: &Wtf8 = message + .as_ref() + .map_or_else(|| "''".as_ref(), |s| s.as_wtf8()); result.push_wtf8(message_wtf8); result.push_str(", ["); if let Some(exceptions_obj) = zelf.get_arg(1) { let iter: ArgIterable = - ArgIterable::try_from_object(vm, exceptions_obj.clone())?; + ArgIterable::try_from_object(vm, exceptions_obj)?; let mut first = true; for exc in iter.iter(vm)? { if !first { diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index ffab36bd01d..aa6f552e426 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -1613,7 +1613,7 @@ pub(super) mod types { } // Pass args without kwargs to BaseException_init - let base_args = FuncArgs::new(args.args.clone(), KwArgs::default()); + let base_args = FuncArgs::new(args.args, KwArgs::default()); PyBaseException::slot_init(zelf.clone(), base_args, vm)?; // Set attributes @@ -1754,7 +1754,7 @@ pub(super) mod types { } // Pass args without kwargs to BaseException_init - let base_args = FuncArgs::new(args.args.clone(), KwArgs::default()); + let base_args = FuncArgs::new(args.args, KwArgs::default()); PyBaseException::slot_init(zelf.clone(), base_args, vm)?; // Set name attribute if provided @@ -1960,7 +1960,11 @@ pub(super) mod types { // args are truncated to 2 for compatibility (only when 2-5 args and filename is not None) // truncation happens inside "if (filename && filename != Py_None)" block - let has_filename = exc.filename.to_owned().filter(|f| !vm.is_none(f)).is_some(); + let has_filename = exc + .filename + .to_owned() + .as_ref() + .is_some_and(|f| !vm.is_none(f)); if (3..=5).contains(&len) && has_filename { new_args.args.truncate(2); } diff --git a/crates/vm/src/format.rs b/crates/vm/src/format.rs index ec92330e170..e9db87fd121 100644 --- a/crates/vm/src/format.rs +++ b/crates/vm/src/format.rs @@ -54,16 +54,19 @@ unsafe fn parse_grouping(grouping: *const libc::c_char) -> Vec { if grouping.is_null() { return result; } + unsafe { let mut ptr = grouping; while ![0, libc::c_char::MAX].contains(&*ptr) { - result.push(*ptr as u8); + result.push(*ptr as _); ptr = ptr.add(1); } } + if !result.is_empty() { result.push(0); } + result } diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index f0116246164..4e7e24a7c45 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -6581,7 +6581,7 @@ impl ExecutingFrame<'_> { let repr_fallback = || { obj.repr(vm) .as_ref() - .map_or("?".as_ref(), |s| s.as_wtf8()) + .map_or_else(|_| "?".as_ref(), |s| s.as_wtf8()) .to_owned() }; let Ok(qualname) = obj.get_attr(vm.ctx.intern_str("__qualname__"), vm) else { @@ -9338,7 +9338,7 @@ impl ExecutingFrame<'_> { // Create super object - pass args based on has_class flag // When super is shadowed, has_class=false means call with 0 args let super_obj = if oparg.has_class() { - global_super.call((class.clone(), self_obj.clone()), vm)? + global_super.call((class, self_obj.clone()), vm)? } else { global_super.call((), vm)? }; @@ -9481,21 +9481,19 @@ impl ExecutingFrame<'_> { } bytecode::IntrinsicFunction1::TypeVar => { let type_var: PyObjectRef = - _typing::TypeVar::new(vm, arg.clone(), vm.ctx.none(), vm.ctx.none()) + _typing::TypeVar::new(vm, arg, vm.ctx.none(), vm.ctx.none()) .into_ref(&vm.ctx) .into(); Ok(type_var) } bytecode::IntrinsicFunction1::ParamSpec => { - let param_spec: PyObjectRef = _typing::ParamSpec::new(arg.clone(), vm) - .into_ref(&vm.ctx) - .into(); + let param_spec: PyObjectRef = + _typing::ParamSpec::new(arg, vm).into_ref(&vm.ctx).into(); Ok(param_spec) } bytecode::IntrinsicFunction1::TypeVarTuple => { - let type_var_tuple: PyObjectRef = _typing::TypeVarTuple::new(arg.clone(), vm) - .into_ref(&vm.ctx) - .into(); + let type_var_tuple: PyObjectRef = + _typing::TypeVarTuple::new(arg, vm).into_ref(&vm.ctx).into(); Ok(type_var_tuple) } bytecode::IntrinsicFunction1::TypeAlias => { @@ -9595,17 +9593,15 @@ impl ExecutingFrame<'_> { Ok(arg1) } bytecode::IntrinsicFunction2::TypeVarWithBound => { - let type_var: PyObjectRef = - _typing::TypeVar::new(vm, arg1.clone(), arg2, vm.ctx.none()) - .into_ref(&vm.ctx) - .into(); + let type_var: PyObjectRef = _typing::TypeVar::new(vm, arg1, arg2, vm.ctx.none()) + .into_ref(&vm.ctx) + .into(); Ok(type_var) } bytecode::IntrinsicFunction2::TypeVarWithConstraint => { - let type_var: PyObjectRef = - _typing::TypeVar::new(vm, arg1.clone(), vm.ctx.none(), arg2) - .into_ref(&vm.ctx) - .into(); + let type_var: PyObjectRef = _typing::TypeVar::new(vm, arg1, vm.ctx.none(), arg2) + .into_ref(&vm.ctx) + .into(); Ok(type_var) } bytecode::IntrinsicFunction2::PrepReraiseStar => { diff --git a/crates/vm/src/getpath.rs b/crates/vm/src/getpath.rs index 789fc72f62a..75b7c45a66e 100644 --- a/crates/vm/src/getpath.rs +++ b/crates/vm/src/getpath.rs @@ -133,7 +133,7 @@ pub fn init_path_config(settings: &Settings) -> Paths { // Step 2: Check for venv (pyvenv.cfg) and get 'home' let (venv_prefix, home_dir) = detect_venv(&exe_dir); - let search_dir = home_dir.clone().or(exe_dir.clone()); + let search_dir = home_dir.clone().or(exe_dir); // Step 3: Check for build directory let build_prefix = detect_build_directory(&search_dir); diff --git a/crates/vm/src/import.rs b/crates/vm/src/import.rs index 09033dd84f8..ebf1cac2a08 100644 --- a/crates/vm/src/import.rs +++ b/crates/vm/src/import.rs @@ -306,7 +306,7 @@ pub(crate) fn is_possibly_shadowing_path(origin: &str, vm: &VirtualMachine) -> b }; // For packages (__init__.py), look one directory further up let root = if origin_path.file_name() == Some("__init__.py".as_ref()) { - parent.parent().unwrap_or(Path::new("")) + parent.parent().unwrap_or_else(|| Path::new("")) } else { parent }; diff --git a/crates/vm/src/ospath.rs b/crates/vm/src/ospath.rs index 15cda4b82b5..c90d4789db3 100644 --- a/crates/vm/src/ospath.rs +++ b/crates/vm/src/ospath.rs @@ -110,7 +110,7 @@ impl PathConverter { vm: &VirtualMachine, ) -> PyResult { // Try direct str/bytes match - let obj = match self.try_match_str_bytes(obj.clone(), vm)? { + let obj = match self.try_match_str_bytes(obj, vm)? { Ok(path) => return Ok(path), Err(obj) => obj, }; diff --git a/crates/vm/src/stdlib/_abc.rs b/crates/vm/src/stdlib/_abc.rs index bb7fbb9bf3b..e0ba4e5c997 100644 --- a/crates/vm/src/stdlib/_abc.rs +++ b/crates/vm/src/stdlib/_abc.rs @@ -271,7 +271,7 @@ mod _abc { } // Call __subclasscheck__ on subclass - let result = vm.call_method(&cls, "__subclasscheck__", (subclass.clone(),))?; + let result = vm.call_method(&cls, "__subclasscheck__", (subclass,))?; match result.clone().try_to_bool(vm) { Ok(true) => Ok(result), diff --git a/crates/vm/src/stdlib/_ast/python.rs b/crates/vm/src/stdlib/_ast/python.rs index 9a70a4567b4..ee5588acb87 100644 --- a/crates/vm/src/stdlib/_ast/python.rs +++ b/crates/vm/src/stdlib/_ast/python.rs @@ -38,7 +38,7 @@ pub(crate) mod _ast { let empty_tuple = ctx.empty_tuple.clone(); class.set_str_attr("_fields", empty_tuple.clone(), ctx); class.set_str_attr("_attributes", empty_tuple.clone(), ctx); - class.set_str_attr("__match_args__", empty_tuple.clone(), ctx); + class.set_str_attr("__match_args__", empty_tuple, ctx); const AST_REDUCE: PyMethodDef = PyMethodDef::new_const( "__reduce__", @@ -217,7 +217,7 @@ pub(crate) mod _ast { let payload = vm.ctx.new_dict(); if let Some(dict) = dict { - if let Some(fields) = fields.clone() { + if let Some(fields) = fields { let fields: Vec = fields.try_to_value(vm)?; for field in fields { if let Some(value) = dict.get_item_opt::(field.as_wtf8(), vm)? { @@ -225,7 +225,7 @@ pub(crate) mod _ast { } } } - if let Some(attributes) = attributes.clone() { + if let Some(attributes) = attributes { let attributes: Vec = attributes.try_to_value(vm)?; for attr in attributes { if let Some(value) = dict.get_item_opt::(attr.as_wtf8(), vm)? { @@ -512,7 +512,7 @@ Support for arbitrary keyword arguments is deprecated and will be removed in Pyt let empty_tuple = ctx.empty_tuple.clone(); ast_type.set_str_attr("_fields", empty_tuple.clone(), ctx); ast_type.set_str_attr("_attributes", empty_tuple.clone(), ctx); - ast_type.set_str_attr("__match_args__", empty_tuple.clone(), ctx); + ast_type.set_str_attr("__match_args__", empty_tuple, ctx); const AST_REDUCE: PyMethodDef = PyMethodDef::new_const( "__reduce__", diff --git a/crates/vm/src/stdlib/_codecs.rs b/crates/vm/src/stdlib/_codecs.rs index 9253823d459..b2c0a220003 100644 --- a/crates/vm/src/stdlib/_codecs.rs +++ b/crates/vm/src/stdlib/_codecs.rs @@ -1019,7 +1019,7 @@ mod _codecs_windows { let rch = rcp.to_u32(); if rch > 127 { return Err(vm.new_unicode_encode_error_real( - encoding_str.clone(), + encoding_str, s.clone(), pos, pos + 1, diff --git a/crates/vm/src/stdlib/_ctypes.rs b/crates/vm/src/stdlib/_ctypes.rs index 2534f6128e8..0ffcb1e01ab 100644 --- a/crates/vm/src/stdlib/_ctypes.rs +++ b/crates/vm/src/stdlib/_ctypes.rs @@ -427,7 +427,7 @@ pub(crate) mod _ctypes { let details = details.unwrap_or_else(|| vm.ctx.none()); // Set instance attributes - zelf.set_attr("hresult", hresult.clone(), vm)?; + zelf.set_attr("hresult", hresult, vm)?; zelf.set_attr("text", text.clone(), vm)?; zelf.set_attr("details", details.clone(), vm)?; @@ -1027,7 +1027,7 @@ pub(crate) mod _ctypes { // Determine if obj is a type or an instance let is_type = obj.class().fast_issubclass(vm.ctx.types.type_type.as_ref()); let cls = if is_type { - obj.clone() + obj } else { obj.class().to_owned().into() }; diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index 568e2a4a0a9..d236f80f9cf 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -56,7 +56,6 @@ pub(super) fn array_type_from_ctype( // Cache miss - create new array type let itemtype_ref = itemtype - .clone() .downcast::() .map_err(|_| vm.new_type_error("Expected a type object"))?; @@ -217,7 +216,6 @@ impl Initializer for PyCArrayType { if let Some(type_attr) = direct_type { // Direct _type_ defined - validate it (PyStgInfo_FromType) let type_ref = type_attr - .clone() .downcast::() .map_err(|_| vm.new_type_error("_type_ must be a type"))?; let (size, align, format, shape, flags) = { @@ -555,10 +553,7 @@ impl PyCArray { vm: &VirtualMachine, ) -> PyObjectRef { // Unsigned type codes: B (uchar), H (ushort), I (uint), L (ulong), Q (ulonglong) - let is_unsigned = matches!( - type_code, - Some("B") | Some("H") | Some("I") | Some("L") | Some("Q") - ); + let is_unsigned = matches!(type_code, Some("B" | "H" | "I" | "L" | "Q")); match (size, is_unsigned) { (1, false) => vm.ctx.new_int(bytes[0] as i8).into(), @@ -728,7 +723,7 @@ impl PyCArray { .map_or(0.0, f32::from_ne_bytes); Ok(vm.ctx.new_float(val as f64).into()) } - Some("d") | Some("g") => { + Some("d" | "g") => { // c_double / c_longdouble - read f64 from first 8 bytes let val = buffer[offset..] .first_chunk::<8>() @@ -841,7 +836,7 @@ impl PyCArray { buffer[offset..offset + 4].copy_from_slice(&f32_val.to_ne_bytes()); } } - Some("d") | Some("g") => { + Some("d" | "g") => { // c_double / c_longdouble: convert int/float to f64 bytes let f64_val = if let Ok(float_val) = value.try_float(vm) { float_val.to_f64() diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index 0bfbe57bb04..8558e614474 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -1175,7 +1175,7 @@ impl PyCData { .is_ok(); let data = if needs_swap && size > 1 { - let mut swapped = buffer_data.clone(); + let mut swapped = buffer_data; swapped.reverse(); swapped } else { @@ -1187,7 +1187,7 @@ impl PyCData { // Complex types: create ctypes instance via PyCData_FromBaseObj let ptr = self.buffer.read().as_ptr().wrapping_add(offset) as *mut u8; - let cdata_obj = unsafe { Self::from_base_obj(ptr, size, base_obj.clone(), index) }; + let cdata_obj = unsafe { Self::from_base_obj(ptr, size, base_obj, index) }; if proto_metaclass.fast_issubclass(super::structure::PyCStructType::static_type()) || proto_metaclass.fast_issubclass(super::union::PyCUnionType::static_type()) diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 9136304c296..1e8e6309368 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -274,7 +274,7 @@ fn conv_param(value: &PyObject, vm: &VirtualMachine) -> PyResult { return Ok(Argument { ffi_type, keep: None, - value: carg.value.clone(), + value: carg.value, }); } @@ -371,14 +371,14 @@ impl ArgumentType for PyTypeRef { .as_object() .get_attr(vm.ctx.intern_str("_type_"), vm) .ok() - .ok_or(vm.new_type_error("Unsupported argument type"))?; + .ok_or_else(|| vm.new_type_error("Unsupported argument type"))?; let typ = typ .downcast_ref::() - .ok_or(vm.new_type_error("Unsupported argument type"))?; + .ok_or_else(|| vm.new_type_error("Unsupported argument type"))?; let typ = typ.to_string(); let typ = typ.as_str(); get_ffi_type(typ) - .ok_or_else(|| vm.new_type_error(format!("Unsupported argument type: {}", typ))) + .ok_or_else(|| vm.new_type_error(format!("Unsupported argument type: {typ}"))) } fn convert_object(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { @@ -388,7 +388,7 @@ impl ArgumentType for PyTypeRef { let from_param = self .as_object() .get_attr(vm.ctx.intern_str("from_param"), vm)?; - let converted = from_param.call((value.clone(),), vm)?; + let converted = from_param.call((value,), vm)?; // Then pass the converted value to ConvParam logic // CArgObject (from from_param) -> use stored value directly @@ -422,16 +422,16 @@ impl ArgumentType for PyTypeRef { .and_then(|t| t.downcast_ref::().map(|s| s.to_string())); // For pointer types (c_void_p, c_char_p, c_wchar_p), handle as pointer - if matches!(type_code.as_deref(), Some("P") | Some("z") | Some("Z")) { + if matches!(type_code.as_deref(), Some("P" | "z" | "Z")) { return convert_to_pointer(&converted, vm); } // PyCSimple (already a ctypes instance from from_param) - if let Ok(simple) = converted.clone().downcast::() { + if let Ok(simple) = converted.downcast::() { let typ = ArgumentType::to_ffi_type(self, vm)?; let ffi_value = simple .to_ffi_value(typ, vm) - .ok_or(vm.new_type_error("Unsupported argument type"))?; + .ok_or_else(|| vm.new_type_error("Unsupported argument type"))?; return Ok(ffi_value); } @@ -493,7 +493,7 @@ impl Initializer for PyCFuncPtrType { type Args = FuncArgs; fn init(zelf: PyRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - let obj: PyObjectRef = zelf.clone().into(); + let obj: PyObjectRef = zelf.into(); let new_type: PyTypeRef = obj .downcast() .map_err(|_| vm.new_type_error("expected type"))?; @@ -845,7 +845,7 @@ pub(super) fn cast_impl( // Add id(src): src to the shared dict if let Some(dict) = shared_objects.downcast_ref::() { let id_key: PyObjectRef = vm.ctx.new_int(src.get_id() as i64).into(); - let _ = dict.set_item(&*id_key, src.clone(), vm); + let _ = dict.set_item(&*id_key, src, vm); } // Set result's _objects to the shared dict @@ -997,14 +997,14 @@ impl Constructor for PyCFuncPtr { if let Some(tuple) = first_arg.downcast_ref::() { let name = tuple .first() - .ok_or(vm.new_type_error("Expected a tuple with at least 2 elements"))? + .ok_or_else(|| vm.new_type_error("Expected a tuple with at least 2 elements"))? .downcast_ref::() - .ok_or(vm.new_type_error("Expected a string"))? + .ok_or_else(|| vm.new_type_error("Expected a string"))? .to_string(); let dll = tuple .iter() .nth(1) - .ok_or(vm.new_type_error("Expected a tuple with at least 2 elements"))? + .ok_or_else(|| vm.new_type_error("Expected a tuple with at least 2 elements"))? .clone(); // Get library handle and load function @@ -1022,7 +1022,7 @@ impl Constructor for PyCFuncPtr { .get_lib( handle .to_usize() - .ok_or(vm.new_value_error("Invalid handle"))?, + .ok_or_else(|| vm.new_value_error("Invalid handle"))?, ) .ok_or_else(|| vm.new_value_error("Library not found"))?; let inner_lib = library.lib.lock(); @@ -1584,10 +1584,7 @@ fn check_hresult(hresult: i32, zelf: &Py, vm: &VirtualMachine) -> Py .new_str(format!("HRESULT: 0x{:08X}", hresult as u32)) .into(); let details: PyObjectRef = vm.ctx.none(); - let exc = vm.invoke_exception( - com_error_type.to_owned(), - vec![text.clone(), details.clone()], - )?; + let exc = vm.invoke_exception(com_error_type, vec![text.clone(), details.clone()])?; let _ = exc.as_object().set_attr("hresult", hresult_obj, vm); let _ = exc.as_object().set_attr("text", text, vm); let _ = exc.as_object().set_attr("details", details, vm); @@ -2108,12 +2105,12 @@ fn python_to_ffi(obj: PyResult, ty: &Py, result: *mut c_void, vm: &Virtu *(result as *mut u32) = i.as_bigint().to_u32().unwrap_or(0); } } - Some("l") | Some("q") => { + Some("l" | "q") => { if let Ok(i) = obj.try_int(vm) { *(result as *mut i64) = i.as_bigint().to_i64().unwrap_or(0); } } - Some("L") | Some("Q") => { + Some("L" | "Q") => { if let Ok(i) = obj.try_int(vm) { *(result as *mut u64) = i.as_bigint().to_u64().unwrap_or(0); } @@ -2128,7 +2125,7 @@ fn python_to_ffi(obj: PyResult, ty: &Py, result: *mut c_void, vm: &Virtu *(result as *mut f64) = f.to_f64(); } } - Some("P") | Some("z") | Some("Z") => { + Some("P" | "z" | "Z") => { if let Ok(i) = obj.try_int(vm) { *(result as *mut usize) = i.as_bigint().to_usize().unwrap_or(0); } @@ -2269,7 +2266,7 @@ impl PyCThunk { .map(|ty| { ty.type_code(vm) .and_then(|code| get_ffi_type(&code)) - .unwrap_or(Type::pointer()) + .unwrap_or_else(Type::pointer) }) .collect(); @@ -2277,7 +2274,7 @@ impl PyCThunk { .as_ref() .and_then(|ty| ty.type_code(vm)) .and_then(|code| get_ffi_type(&code)) - .unwrap_or(Type::void()); + .unwrap_or_else(Type::void); let cif = Cif::new(ffi_arg_types, ffi_res_type); diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 503af1f1d56..bc71bd2caf0 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -182,7 +182,6 @@ impl PyCPointerType { // 1. Validate that typ is a type let typ_type = typ - .clone() .downcast::() .map_err(|_| vm.new_type_error("_type_ must be a type"))?; @@ -676,11 +675,11 @@ impl PyCPointer { .ctx .new_int(core::ptr::read_unaligned(ptr as *const u16) as i32) .into()), - Some("i") | Some("l") => Ok(vm + Some("i" | "l") => Ok(vm .ctx .new_int(core::ptr::read_unaligned(ptr as *const i32)) .into()), - Some("I") | Some("L") => Ok(vm + Some("I" | "L") => Ok(vm .ctx .new_int(core::ptr::read_unaligned(ptr as *const u32)) .into()), @@ -696,11 +695,11 @@ impl PyCPointer { .ctx .new_float(core::ptr::read_unaligned(ptr as *const f32) as f64) .into()), - Some("d") | Some("g") => Ok(vm + Some("d" | "g") => Ok(vm .ctx .new_float(core::ptr::read_unaligned(ptr as *const f64)) .into()), - Some("P") | Some("z") | Some("Z") => Ok(vm + Some("P" | "z" | "Z") => Ok(vm .ctx .new_int(core::ptr::read_unaligned(ptr as *const usize)) .into()), @@ -726,19 +725,16 @@ impl PyCPointer { // Handle c_char_p (z) and c_wchar_p (Z) - store pointer address // Note: PyBytes/PyStr cases are handled by caller (setitem_by_index) - match type_code { - Some("z") | Some("Z") => { - let ptr_val = if vm.is_none(value) { - 0usize - } else if let Ok(int_val) = value.try_index(vm) { - int_val.as_bigint().to_usize().unwrap_or(0) - } else { - return Err(vm.new_type_error("bytes/string or integer address expected")); - }; - core::ptr::write_unaligned(ptr as *mut usize, ptr_val); - return Ok(()); - } - _ => {} + if let Some("z" | "Z") = type_code { + let ptr_val = if vm.is_none(value) { + 0usize + } else if let Ok(int_val) = value.try_index(vm) { + int_val.as_bigint().to_usize().unwrap_or(0) + } else { + return Err(vm.new_type_error("bytes/string or integer address expected")); + }; + core::ptr::write_unaligned(ptr as *mut usize, ptr_val); + return Ok(()); } // Try to get value as integer diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index 3bf1f84fbc5..6d78a1704a1 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -253,9 +253,7 @@ impl PyCSimpleType { #[pymethod] fn new(cls: PyTypeRef, _: OptionalArg, vm: &VirtualMachine) -> PyResult { Ok(PyObjectRef::from( - new_simple_type(Either::B(&cls), vm)? - .into_ref_with_type(vm, cls)? - .clone(), + new_simple_type(Either::B(&cls), vm)?.into_ref_with_type(vm, cls)?, )) } @@ -275,7 +273,7 @@ impl PyCSimpleType { let type_code = cls.type_code(vm); // 3. Handle None for pointer types (c_char_p, c_wchar_p, c_void_p) - if vm.is_none(&value) && matches!(type_code.as_deref(), Some("z") | Some("Z") | Some("P")) { + if vm.is_none(&value) && matches!(type_code.as_deref(), Some("z" | "Z" | "P")) { return Ok(value); } @@ -449,7 +447,7 @@ impl PyCSimpleType { // 7. c_char_p or c_wchar_p instance → extract pointer value if let Some(simple) = value.downcast_ref::() { let value_type_code = value.class().type_code(vm); - if matches!(value_type_code.as_deref(), Some("z") | Some("Z")) { + if matches!(value_type_code.as_deref(), Some("z" | "Z")) { let ptr_val = { let buffer = simple.0.buffer.read(); buffer diff --git a/crates/vm/src/stdlib/_ctypes/structure.rs b/crates/vm/src/stdlib/_ctypes/structure.rs index c9ab9205601..059b7a6b523 100644 --- a/crates/vm/src/stdlib/_ctypes/structure.rs +++ b/crates/vm/src/stdlib/_ctypes/structure.rs @@ -68,7 +68,7 @@ impl Initializer for PyCStructType { fn init(zelf: crate::PyRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // Get the type as PyTypeRef by converting PyRef -> PyObjectRef -> PyRef - let obj: PyObjectRef = zelf.clone().into(); + let obj: PyObjectRef = zelf.into(); let new_type: PyTypeRef = obj .downcast() .map_err(|_| vm.new_type_error("expected type"))?; diff --git a/crates/vm/src/stdlib/_ctypes/union.rs b/crates/vm/src/stdlib/_ctypes/union.rs index c1882141e98..0ac5f64bd21 100644 --- a/crates/vm/src/stdlib/_ctypes/union.rs +++ b/crates/vm/src/stdlib/_ctypes/union.rs @@ -69,7 +69,7 @@ impl Initializer for PyCUnionType { fn init(zelf: crate::PyRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // Get the type as PyTypeRef by converting PyRef -> PyObjectRef -> PyRef - let obj: PyObjectRef = zelf.clone().into(); + let obj: PyObjectRef = zelf.into(); let new_type: PyTypeRef = obj .downcast() .map_err(|_| vm.new_type_error("expected type"))?; diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index 7ffdcad4da1..96095f565f5 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -1348,7 +1348,7 @@ mod _io { return Ok(None); } // Try to convert to int; if it fails, treat as -1 and chain the TypeError - let (n, type_error) = match isize::try_from_object(vm, res.clone()) { + let (n, type_error) = match isize::try_from_object(vm, res) { Ok(n) => (n, None), Err(e) => (-1, Some(e)), }; @@ -1587,7 +1587,10 @@ mod _io { let str_repr = e .__str__(vm) .as_ref() - .map_or("".as_ref(), |s| s.as_wtf8()) + .map_or_else( + |_| "".as_ref(), + |s| s.as_wtf8(), + ) .to_owned(); let msg = format!("{}() {}", Self::CLASS_NAME, str_repr); vm.new_exception_msg(e.class().to_owned(), msg.into()) diff --git a/crates/vm/src/stdlib/_sre.rs b/crates/vm/src/stdlib/_sre.rs index ba7044fb5a9..2aac4bd92cc 100644 --- a/crates/vm/src/stdlib/_sre.rs +++ b/crates/vm/src/stdlib/_sre.rs @@ -129,7 +129,7 @@ mod _sre { ) -> PyResult> { let re = vm.import("re", 0)?; let func = re.get_attr("_compile_template", vm)?; - let result = func.call((pattern, repl.clone()), vm)?; + let result = func.call((pattern, repl), vm)?; result .downcast::() .map_err(|_| vm.new_runtime_error("expected SRE_Template")) diff --git a/crates/vm/src/stdlib/_sysconfigdata.rs b/crates/vm/src/stdlib/_sysconfigdata.rs index 99aab892e1c..a9871ec95dc 100644 --- a/crates/vm/src/stdlib/_sysconfigdata.rs +++ b/crates/vm/src/stdlib/_sysconfigdata.rs @@ -45,7 +45,7 @@ mod _sysconfigdata { sysvars! { // Extension module suffix in CPython-compatible format "EXT_SUFFIX" => format!(".rustpython313-{multiarch}.so"), - "MULTIARCH" => multiarch.clone(), + "MULTIARCH" => multiarch, "RUST_MULTIARCH" => RUST_MULTIARCH, // enough for tests to stop expecting urandom() to fail after restricting file resources "HAVE_GETRANDOM" => 1, diff --git a/crates/vm/src/stdlib/_thread.rs b/crates/vm/src/stdlib/_thread.rs index 73313c53e06..48e5a4a0823 100644 --- a/crates/vm/src/stdlib/_thread.rs +++ b/crates/vm/src/stdlib/_thread.rs @@ -672,7 +672,7 @@ pub(crate) mod _thread { let done_event = done_event_weak.upgrade()?; let guard = inner.lock(); if guard.state != ThreadHandleState::Done && guard.ident != current_ident { - Some((inner.clone(), done_event.clone())) + Some((inner.clone(), done_event)) } else { None } diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index 40f5ded5d44..fd35b287211 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -969,7 +969,13 @@ mod builtins { exp: y, modulus, } = args; - let modulus = modulus.as_ref().map_or(vm.ctx.none.as_object(), |m| m); + #[expect( + clippy::unnecessary_option_map_or_else, + reason = "changing this won't compile" + )] + let modulus = modulus + .as_ref() + .map_or_else(|| vm.ctx.none.as_object(), |m| m); vm._pow(&x, &y, modulus) } diff --git a/crates/vm/src/stdlib/itertools.rs b/crates/vm/src/stdlib/itertools.rs index 763c3ddce76..0566db1f612 100644 --- a/crates/vm/src/stdlib/itertools.rs +++ b/crates/vm/src/stdlib/itertools.rs @@ -1648,7 +1648,7 @@ mod decl { } let n = n .to_usize() - .ok_or(vm.new_overflow_error("Python int too large to convert to usize"))?; + .ok_or_else(|| vm.new_overflow_error("Python int too large to convert to usize"))?; let iterable = iterable_ref.get_iter(vm)?; Ok(Self { diff --git a/crates/vm/src/stdlib/nt.rs b/crates/vm/src/stdlib/nt.rs index 809e26249c3..554012987aa 100644 --- a/crates/vm/src/stdlib/nt.rs +++ b/crates/vm/src/stdlib/nt.rs @@ -381,7 +381,7 @@ pub(crate) mod module { .to_str() .ok_or_else(|| vm.new_unicode_decode_error("filename contains invalid UTF-8"))?; - Ok(vm.ctx.new_str(filename_str).to_owned()) + Ok(vm.ctx.new_str(filename_str)) } #[derive(FromArgs)] @@ -1292,7 +1292,7 @@ pub(crate) mod module { }; if ret == 0 { let err = io::Error::last_os_error(); - return Err(OSErrorBuilder::with_filename(&err, path.clone(), vm)); + return Err(OSErrorBuilder::with_filename(&err, path, vm)); } if ret as usize > buffer.len() { buffer.resize(ret as usize, 0); @@ -1306,7 +1306,7 @@ pub(crate) mod module { }; if ret == 0 { let err = io::Error::last_os_error(); - return Err(OSErrorBuilder::with_filename(&err, path.clone(), vm)); + return Err(OSErrorBuilder::with_filename(&err, path, vm)); } } let buffer = widestring::WideCString::from_vec_truncate(buffer); @@ -2125,7 +2125,7 @@ pub(crate) mod module { if handle == INVALID_HANDLE_VALUE { return Err(OSErrorBuilder::with_filename( &io::Error::last_os_error(), - path.clone(), + path, vm, )); } @@ -2153,7 +2153,7 @@ pub(crate) mod module { if result == 0 { return Err(OSErrorBuilder::with_filename( &io::Error::last_os_error(), - path.clone(), + path, vm, )); } diff --git a/crates/vm/src/stdlib/sys.rs b/crates/vm/src/stdlib/sys.rs index 9f36f9768e0..b385e244203 100644 --- a/crates/vm/src/stdlib/sys.rs +++ b/crates/vm/src/stdlib/sys.rs @@ -834,7 +834,7 @@ mod sys { vm: &VirtualMachine, ) -> PyResult<()> { let stderr = super::get_stderr(vm)?; - match vm.normalize_exception(exc_type.clone(), exc_val.clone(), exc_tb) { + match vm.normalize_exception(exc_type, exc_val.clone(), exc_tb) { Ok(exc) => { // PyErr_Display: try traceback._print_exception_bltin first if let Ok(tb_mod) = vm.import("traceback", 0) diff --git a/crates/vm/src/stdlib/time.rs b/crates/vm/src/stdlib/time.rs index a630e3ac506..5e3cfb36fca 100644 --- a/crates/vm/src/stdlib/time.rs +++ b/crates/vm/src/stdlib/time.rs @@ -97,7 +97,7 @@ mod decl { #[pyfunction] fn sleep(seconds: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let seconds_type_name = seconds.clone().class().name().to_owned(); + let seconds_type_name = seconds.class().name().to_owned(); let dur = seconds.try_into_value::(vm).map_err(|e| { if e.class().is(vm.ctx.exceptions.value_error) && let Some(s) = e.args().first().and_then(|arg| arg.str(vm).ok()) diff --git a/crates/vm/src/types/structseq.rs b/crates/vm/src/types/structseq.rs index 02d1a4d6349..bc1a8fa608a 100644 --- a/crates/vm/src/types/structseq.rs +++ b/crates/vm/src/types/structseq.rs @@ -260,7 +260,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static { Self::Data::REQUIRED_FIELD_NAMES.len() + Self::Data::OPTIONAL_FIELD_NAMES.len(); let mut items: Vec = zelf.as_slice()[..n_fields].to_vec(); - let mut kwargs = args.kwargs.clone(); + let mut kwargs = args.kwargs; // Replace fields from kwargs let all_field_names: Vec<&str> = Self::Data::REQUIRED_FIELD_NAMES diff --git a/crates/vm/src/vm/mod.rs b/crates/vm/src/vm/mod.rs index 267382ed34d..4106908ea1a 100644 --- a/crates/vm/src/vm/mod.rs +++ b/crates/vm/src/vm/mod.rs @@ -944,13 +944,18 @@ impl VirtualMachine { let errors = if fd == 2 { Some("backslashreplace") } else { - self.state.config.settings.stdio_errors.as_deref().or( - if self.state.config.settings.stdio_encoding.is_some() { - Some("strict") - } else { - Some("surrogateescape") - }, - ) + self.state + .config + .settings + .stdio_errors + .as_deref() + .or_else(|| { + Some(if self.state.config.settings.stdio_encoding.is_some() { + "strict" + } else { + "surrogateescape" + }) + }) }; let stdio = self.call_method( @@ -1177,7 +1182,7 @@ impl VirtualMachine { let repr_result = object.repr(self); let repr_wtf8 = repr_result .as_ref() - .map_or("".as_ref(), |s| s.as_wtf8()); + .map_or_else(|_| "".as_ref(), |s| s.as_wtf8()); write_to_stderr(&format!("{repr_wtf8}\n"), &stderr, self); // Write exception type and message diff --git a/crates/vm/src/warn.rs b/crates/vm/src/warn.rs index 0bae7a9619a..5dbf3fce780 100644 --- a/crates/vm/src/warn.rs +++ b/crates/vm/src/warn.rs @@ -413,7 +413,7 @@ pub(crate) fn warn_explicit( let reg = if vm.is_none(®istry) { get_once_registry(vm)? } else { - registry.clone() + registry }; update_registry(®, text.as_ref(), category.as_object(), false, vm)? } diff --git a/crates/wasm/src/convert.rs b/crates/wasm/src/convert.rs index bbf263975f3..aaf0e6e2549 100644 --- a/crates/wasm/src/convert.rs +++ b/crates/wasm/src/convert.rs @@ -270,8 +270,9 @@ pub fn syntax_err(err: CompileError) -> SyntaxError { let can_continue = matches!( &err, CompileError::Parse(ParseError { - error: ParseErrorType::Lexical(LexicalErrorType::Eof) - | ParseErrorType::Lexical(LexicalErrorType::IndentationError), + error: ParseErrorType::Lexical( + LexicalErrorType::Eof | LexicalErrorType::IndentationError + ), .. }) );