From 3908faa66b70cd19de086c407a9ccceabc38a28c Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 15:22:11 +0300 Subject: [PATCH 01/14] Add some clippy lints --- Cargo.toml | 4 ++++ crates/stdlib/src/posixsubprocess.rs | 2 +- crates/vm/src/format.rs | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3262749b72c..9b3a3561425 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -252,6 +252,10 @@ 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" + perf = "warn" style = "warn" complexity = "warn" 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/vm/src/format.rs b/crates/vm/src/format.rs index ec92330e170..37b9d92eb89 100644 --- a/crates/vm/src/format.rs +++ b/crates/vm/src/format.rs @@ -57,7 +57,7 @@ unsafe fn parse_grouping(grouping: *const libc::c_char) -> Vec { unsafe { let mut ptr = grouping; while ![0, libc::c_char::MAX].contains(&*ptr) { - result.push(*ptr as u8); + result.push(*ptr); ptr = ptr.add(1); } } From defab7fd54c5e82603aabcbc2f904331563e0ceb Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 15:30:51 +0300 Subject: [PATCH 02/14] Remove redundunt clone --- Cargo.toml | 3 +++ crates/codegen/src/compile.rs | 4 ++-- crates/derive-impl/src/pystructseq.rs | 2 +- crates/stdlib/src/_asyncio.rs | 16 ++++++------- crates/stdlib/src/contextvars.rs | 6 ++--- crates/stdlib/src/csv.rs | 15 ++++++------ crates/stdlib/src/ssl.rs | 4 ++-- crates/stdlib/src/ssl/compat.rs | 8 +++---- crates/vm/src/builtins/function.rs | 5 ++-- crates/vm/src/builtins/set.rs | 24 ++++--------------- crates/vm/src/builtins/type.rs | 2 +- crates/vm/src/codecs.rs | 4 ++-- crates/vm/src/exception_group.rs | 4 ++-- crates/vm/src/exceptions.rs | 4 ++-- crates/vm/src/frame.rs | 28 ++++++++++------------- crates/vm/src/getpath.rs | 2 +- crates/vm/src/ospath.rs | 2 +- crates/vm/src/stdlib/_abc.rs | 2 +- crates/vm/src/stdlib/_ast/python.rs | 8 +++---- crates/vm/src/stdlib/_ctypes.rs | 2 +- crates/vm/src/stdlib/_ctypes/array.rs | 2 -- crates/vm/src/stdlib/_ctypes/base.rs | 4 ++-- crates/vm/src/stdlib/_ctypes/function.rs | 10 ++++---- crates/vm/src/stdlib/_ctypes/pointer.rs | 1 - crates/vm/src/stdlib/_ctypes/simple.rs | 4 +--- crates/vm/src/stdlib/_ctypes/structure.rs | 2 +- crates/vm/src/stdlib/_ctypes/union.rs | 2 +- crates/vm/src/stdlib/_io.rs | 2 +- crates/vm/src/stdlib/_sre.rs | 2 +- crates/vm/src/stdlib/_sysconfigdata.rs | 2 +- crates/vm/src/stdlib/_thread.rs | 2 +- crates/vm/src/stdlib/sys.rs | 2 +- crates/vm/src/stdlib/time.rs | 2 +- crates/vm/src/types/structseq.rs | 2 +- crates/vm/src/warn.rs | 2 +- 35 files changed, 81 insertions(+), 105 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9b3a3561425..0a9fa1a6c51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -255,6 +255,9 @@ 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" perf = "warn" style = "warn" diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index e79226cf141..630227950a8 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. 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/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index d58492a82a5..1f859e4ae8e 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) { @@ -1971,8 +1971,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 +1983,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 +2032,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/ssl.rs b/crates/stdlib/src/ssl.rs index 51f5bc042f4..d2d98b9f603 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()); } @@ -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/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 { 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()), diff --git a/crates/vm/src/builtins/set.rs b/crates/vm/src/builtins/set.rs index a6a58367f4f..7391b0b84ef 100644 --- a/crates/vm/src/builtins/set.rs +++ b/crates/vm/src/builtins/set.rs @@ -834,11 +834,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 +848,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 +862,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 +876,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..abd0d4dc941 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()) { @@ -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)?; diff --git a/crates/vm/src/exception_group.rs b/crates/vm/src/exception_group.rs index 02342e4003d..9bfa21882cc 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() { @@ -216,7 +216,7 @@ pub(super) mod types { 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..0f9c9f11e08 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 diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index f0116246164..c5e9fc8ce7b 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -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/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/_ctypes.rs b/crates/vm/src/stdlib/_ctypes.rs index 2534f6128e8..a4333c9971d 100644 --- a/crates/vm/src/stdlib/_ctypes.rs +++ b/crates/vm/src/stdlib/_ctypes.rs @@ -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..b5dbb818ce4 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) = { 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..e39baecdfd2 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, }); } @@ -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 @@ -427,7 +427,7 @@ impl ArgumentType for PyTypeRef { } // 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) @@ -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 diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 503af1f1d56..51c1bc38737 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"))?; diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index 3bf1f84fbc5..082a6bc2871 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)?, )) } 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..e48066292cf 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)), }; 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/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/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)? } From d8c032d11ff6efb645c1d856c9cb0dca3d5ae3ba Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 15:42:48 +0300 Subject: [PATCH 03/14] Add `or_fun_call` rule --- Cargo.toml | 2 ++ crates/vm/src/exceptions.rs | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 0a9fa1a6c51..74538763d17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -258,6 +258,8 @@ 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" perf = "warn" style = "warn" diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index 0f9c9f11e08..aa6f552e426 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -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); } From d10256127d61fbcdd0d497778b7074af4a387e51 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 16:24:02 +0300 Subject: [PATCH 04/14] Fix more clippy --- crates/common/src/format.rs | 4 ++-- crates/stdlib/src/_asyncio.rs | 6 ++++-- crates/stdlib/src/mmap.rs | 4 ++-- crates/stdlib/src/socket.rs | 3 ++- crates/stdlib/src/ssl.rs | 2 +- crates/vm/src/builtins/builtin_func.rs | 3 ++- crates/vm/src/builtins/function.rs | 4 +++- crates/vm/src/builtins/range.rs | 2 +- crates/vm/src/builtins/set.rs | 1 + crates/vm/src/codecs.rs | 6 +++--- crates/vm/src/exception_group.rs | 4 +++- crates/vm/src/frame.rs | 2 +- crates/vm/src/import.rs | 2 +- crates/vm/src/stdlib/_ctypes/function.rs | 22 +++++++++++----------- crates/vm/src/stdlib/_io.rs | 5 ++++- crates/vm/src/stdlib/builtins.rs | 8 +++++++- crates/vm/src/stdlib/itertools.rs | 2 +- crates/vm/src/vm/mod.rs | 21 +++++++++++++-------- 18 files changed, 62 insertions(+), 39 deletions(-) diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index fdf814cba91..c1c7909aa57 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -895,7 +895,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), } @@ -1014,7 +1014,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/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index 1f859e4ae8e..508947b561f 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -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, ">" )) 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/socket.rs b/crates/stdlib/src/socket.rs index fed5019c1b7..05b4fa15d84 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -2582,7 +2582,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 d2d98b9f603..cbc842538a9 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -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(), 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/function.rs b/crates/vm/src/builtins/function.rs index 5f70cdbc04d..e7ea9b581d3 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -1328,7 +1328,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!( " 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(),)), diff --git a/crates/vm/src/codecs.rs b/crates/vm/src/codecs.rs index abd0d4dc941..8e393ee7dc2 100644 --- a/crates/vm/src/codecs.rs +++ b/crates/vm/src/codecs.rs @@ -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)) @@ -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 9bfa21882cc..76558af1d35 100644 --- a/crates/vm/src/exception_group.rs +++ b/crates/vm/src/exception_group.rs @@ -211,7 +211,9 @@ 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) { diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index c5e9fc8ce7b..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 { 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/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index e39baecdfd2..79e5e6cb746 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -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 { @@ -422,7 +422,7 @@ 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); } @@ -431,7 +431,7 @@ impl ArgumentType for PyTypeRef { 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); } @@ -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(); @@ -2269,7 +2269,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 +2277,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/_io.rs b/crates/vm/src/stdlib/_io.rs index e48066292cf..96095f565f5 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -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/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/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 From bafa81ef39d1e1ec7e3e83d30336f4a30a5247da Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 16:32:34 +0300 Subject: [PATCH 05/14] Clippy `unnested_or_patterns` --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index 74538763d17..4e4092f3a5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -260,6 +260,7 @@ 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" From 2164341a55100d402e0fca9ee32949285ba9cf60 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 16:32:48 +0300 Subject: [PATCH 06/14] clippy fix --- crates/codegen/src/compile.rs | 10 ++--- crates/codegen/src/ir.rs | 53 +++++++++++------------- crates/codegen/src/symboltable.rs | 6 +-- crates/common/src/format.rs | 36 ++++++---------- crates/common/src/str.rs | 2 +- crates/derive-impl/src/pyclass.rs | 2 +- crates/stdlib/src/socket.rs | 2 +- crates/stdlib/src/ssl/cert.rs | 8 +--- crates/stdlib/src/unicodedata.rs | 2 +- crates/vm/src/buffer.rs | 2 +- crates/vm/src/builtins/code.rs | 2 +- crates/vm/src/builtins/interpolation.rs | 2 +- crates/vm/src/stdlib/_ctypes/array.rs | 6 +-- crates/vm/src/stdlib/_ctypes/function.rs | 6 +-- crates/vm/src/stdlib/_ctypes/pointer.rs | 31 +++++++------- crates/vm/src/stdlib/_ctypes/simple.rs | 4 +- 16 files changed, 74 insertions(+), 100 deletions(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 630227950a8..92d6090e714 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -14487,8 +14487,8 @@ 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 +14533,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 +16145,8 @@ _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..c420a9a80c0 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -2036,8 +2036,7 @@ 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 +2331,8 @@ 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,8 +2354,8 @@ impl CodeInfo { curr_instr, OpArg::new(u32::from(curr.arg) | oparg::COMPARE_OP_BOOL_MASK), )), - (Instruction::ContainsOp { .. }, Instruction::ToBool) - | (Instruction::IsOp { .. }, Instruction::ToBool) => { + (Instruction::ContainsOp { .. } | Instruction::IsOp { .. }, +Instruction::ToBool) => { Some((curr_instr, curr.arg)) } (Instruction::LoadConst { consti }, Instruction::UnaryNot) => { @@ -2434,8 +2433,8 @@ 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 +3756,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 => { @@ -4455,13 +4454,9 @@ impl CodeInfo { for info in block.instructions.iter().skip(current_start) { match info.instr.real() { Some(Instruction::ReturnValue) => return true, - Some( - Instruction::StoreFast { .. } - | Instruction::StoreFastLoadFast { .. } - | Instruction::StoreFastStoreFast { .. }, - ) - | Some(Instruction::DeleteFast { .. }) - | Some(Instruction::LoadFastAndClear { .. }) => return false, + Some(Instruction::StoreFast { .. } | Instruction::StoreFastLoadFast { .. } | +Instruction::StoreFastStoreFast { .. } | Instruction::DeleteFast { .. } | +Instruction::LoadFastAndClear { .. }) => return false, _ => {} } } @@ -4613,8 +4608,8 @@ 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 +4637,8 @@ 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 +4717,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 +4738,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 +4901,8 @@ 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 +4913,8 @@ 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 +6797,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 +6891,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 +6919,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..301b3742eb4 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -1410,10 +1410,8 @@ 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 c1c7909aa57..719e9119951 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,13 @@ 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 +830,8 @@ 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), }, @@ -934,15 +927,10 @@ 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 +940,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, diff --git a/crates/common/src/str.rs b/crates/common/src/str.rs index 38e73a683f2..28501244b5f 100644 --- a/crates/common/src/str.rs +++ b/crates/common/src/str.rs @@ -415,7 +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'-') => { + Some(_sign @ (b'+' | b'-')) => { (unsafe { bytes.get_unchecked(..1) }, &bytes[1..]) } _ => (&b""[..], bytes), diff --git a/crates/derive-impl/src/pyclass.rs b/crates/derive-impl/src/pyclass.rs index e675d6a9f73..d35cd9d3895 100644 --- a/crates/derive-impl/src/pyclass.rs +++ b/crates/derive-impl/src/pyclass.rs @@ -1951,7 +1951,7 @@ where { use AttrName::*; Ok(match attr_name { - attr_name @ Method | attr_name @ ClassMethod | attr_name @ StaticMethod => { + attr_name @ (Method | ClassMethod | StaticMethod) => { Box::new(MethodItem { inner: ContentItemInner { index, attr_name }, }) diff --git a/crates/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index 05b4fa15d84..b2b4e23fd99 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -1557,7 +1557,7 @@ mod _socket { if family == -1 || matches!( e.raw_os_error(), - Some(errcode!(ENOTSOCK)) | Some(errcode!(EBADF)) + Some(c::ENOTSOCK | c::EBADF) ) => { core::mem::forget(sock); diff --git a/crates/stdlib/src/ssl/cert.rs b/crates/stdlib/src/ssl/cert.rs index 0ae71208c5c..794c5aafba4 100644 --- a/crates/stdlib/src/ssl/cert.rs +++ b/crates/stdlib/src/ssl/cert.rs @@ -929,12 +929,8 @@ impl ServerCertVerifier for HostnameIgnoringVerifier { // Check if the error is a hostname mismatch // 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::Error::InvalidCertificate(rustls::CertificateError::NotValidForName | +rustls::CertificateError::NotValidForNameContext { .. }) => { // Hostname mismatch - this is expected and acceptable // The certificate chain, trust anchor, and expiry are valid Ok(ServerCertVerified::assertion()) diff --git a/crates/stdlib/src/unicodedata.rs b/crates/stdlib/src/unicodedata.rs index 6ee5b0c2ee8..afbdbe43881 100644 --- a/crates/stdlib/src/unicodedata.rs +++ b/crates/stdlib/src/unicodedata.rs @@ -302,7 +302,7 @@ mod unicodedata { if let Some(ch) = ch && matches!( ch.numeric_type(), - Some(NumericType::Decimal) | Some(NumericType::Digit) + Some(NumericType::Decimal | NumericType::Digit) ) && let Some(Number::Integer(n)) = ch.numeric_value() { diff --git a/crates/vm/src/buffer.rs b/crates/vm/src/buffer.rs index db58c909bca..9a47dd35858 100644 --- a/crates/vm/src/buffer.rs +++ b/crates/vm/src/buffer.rs @@ -37,7 +37,7 @@ impl Endianness { Some(b'@') => 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/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/interpolation.rs b/crates/vm/src/builtins/interpolation.rs index b429fb5b91c..327565263cf 100644 --- a/crates/vm/src/builtins/interpolation.rs +++ b/crates/vm/src/builtins/interpolation.rs @@ -44,7 +44,7 @@ impl PyInterpolation { let is_valid = vm.is_none(&conversion) || conversion .downcast_ref::() - .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/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index b5dbb818ce4..10ce7ef03be 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -555,7 +555,7 @@ impl PyCArray { // 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") + Some("B" | "H" | "I" | "L" | "Q") ); match (size, is_unsigned) { @@ -726,7 +726,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>() @@ -839,7 +839,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/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 79e5e6cb746..24365d65e06 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -2108,12 +2108,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 +2128,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); } diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 51c1bc38737..bc71bd2caf0 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -675,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()), @@ -695,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()), @@ -725,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 082a6bc2871..6d78a1704a1 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -273,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); } @@ -447,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 From 499a3440e452aa590532319f2993fa9a0b59a547 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 16:35:49 +0300 Subject: [PATCH 07/14] cargo fmt --- crates/codegen/src/compile.rs | 9 +++-- crates/codegen/src/ir.rs | 57 +++++++++++++++++---------- crates/codegen/src/symboltable.rs | 8 +++- crates/common/src/format.rs | 36 ++++++++++++----- crates/common/src/str.rs | 4 +- crates/derive-impl/src/pyclass.rs | 8 ++-- crates/stdlib/src/socket.rs | 5 +-- crates/stdlib/src/ssl/cert.rs | 6 ++- crates/vm/src/stdlib/_ctypes/array.rs | 5 +-- 9 files changed, 85 insertions(+), 53 deletions(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 92d6090e714..727df5b55c1 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -14487,8 +14487,7 @@ def outer(): assert!( matches!( ops.get(cleanup_idx + 1), - Some(Instruction::JumpBackwardNoInterrupt { .. } | Instruction::JumpForward { -.. }) + Some(Instruction::JumpBackwardNoInterrupt { .. } | Instruction::JumpForward { .. }) ), "expected CLEANUP_THROW to jump to shared END_SEND block, 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::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 c420a9a80c0..4e92610b15b 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -2036,7 +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 | Instruction::PopTop | Instruction::StoreFast { .. }) => { + Some( + Instruction::Nop | Instruction::PopTop | Instruction::StoreFast { .. }, + ) => { i -= 1; continue; } @@ -2331,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::LoadSmallInt { .. }, -Instruction::ToBool) => { + ( + Instruction::LoadConst { .. } | Instruction::LoadSmallInt { .. }, + Instruction::ToBool, + ) => { if let Some(value) = const_truthiness(curr_instr, curr.arg, &self.metadata) { @@ -2354,10 +2358,10 @@ Instruction::ToBool) => { curr_instr, OpArg::new(u32::from(curr.arg) | oparg::COMPARE_OP_BOOL_MASK), )), - (Instruction::ContainsOp { .. } | 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 { @@ -2433,8 +2437,10 @@ Instruction::ToBool) => { let redundant = matches!( (curr_instr, next_instr), - (Instruction::LoadConst { .. } | 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); @@ -4454,9 +4460,13 @@ Instruction::PopTop) for info in block.instructions.iter().skip(current_start) { match info.instr.real() { Some(Instruction::ReturnValue) => return true, - Some(Instruction::StoreFast { .. } | Instruction::StoreFastLoadFast { .. } | -Instruction::StoreFastStoreFast { .. } | Instruction::DeleteFast { .. } | -Instruction::LoadFastAndClear { .. }) => return false, + Some( + Instruction::StoreFast { .. } + | Instruction::StoreFastLoadFast { .. } + | Instruction::StoreFastStoreFast { .. } + | Instruction::DeleteFast { .. } + | Instruction::LoadFastAndClear { .. }, + ) => return false, _ => {} } } @@ -4608,8 +4618,10 @@ Instruction::LoadFastAndClear { .. }) => return false, { if matches!( extra_info.instr.real(), - Some(Instruction::LoadFastBorrow { .. } | -Instruction::LoadFastBorrowLoadFastBorrow { .. }) + Some( + Instruction::LoadFastBorrow { .. } + | Instruction::LoadFastBorrowLoadFastBorrow { .. } + ) ) { to_deopt.push(*extra_instr_idx); } @@ -4637,8 +4649,10 @@ Instruction::LoadFastBorrowLoadFastBorrow { .. }) { if matches!( tail_info.instr.real(), - Some(Instruction::LoadFastBorrow { .. } | -Instruction::LoadFastBorrowLoadFastBorrow { .. }) + Some( + Instruction::LoadFastBorrow { .. } + | Instruction::LoadFastBorrowLoadFastBorrow { .. } + ) ) { cross_block_deopts.push((tail_block_idx, tail_instr_idx)); } @@ -4901,8 +4915,9 @@ Instruction::LoadFastBorrowLoadFastBorrow { .. }) } new_instructions.push(info); } - Some(Instruction::LoadFast { var_num } | 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(); @@ -4913,8 +4928,10 @@ Instruction::LoadFastBorrowLoadFastBorrow { .. }) } new_instructions.push(info); } - Some(Instruction::LoadFastLoadFast { var_nums } | -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); diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index 301b3742eb4..bafc7c81cf1 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -1410,8 +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 | CompilerScope::Module | CompilerScope::Function | -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 719e9119951..58dae34b2ce 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -707,9 +707,16 @@ impl FormatSpec { *case, self.alternate_form, )), - Some(FormatType::Decimal | FormatType::Binary | FormatType::Octal | -FormatType::Hex(_) | FormatType::String | FormatType::Character | -FormatType::Number(Case::Upper) | 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")) } @@ -830,8 +837,12 @@ FormatType::Number(Case::Upper) | FormatType::Unknown(_)) => { Some(_) | None => Err(FormatSpecError::CodeNotInRange), }, }, - Some(FormatType::GeneralFormat(_) | FormatType::FixedPoint(_) | -FormatType::Exponent(_) | 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), }, @@ -927,10 +938,17 @@ FormatType::Exponent(_) | FormatType::Percentage) => match num.to_f64() { let precision = self.precision.unwrap_or(6); let magnitude = num.abs(); let magnitude_str = match &self.format_type { - Some(FormatType::Decimal | FormatType::Binary | FormatType::Octal | -FormatType::Hex(_) | FormatType::String | FormatType::Character | -FormatType::Number(Case::Upper) | FormatType::Percentage | -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")) } diff --git a/crates/common/src/str.rs b/crates/common/src/str.rs index 28501244b5f..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'+' | 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 d35cd9d3895..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 | ClassMethod | 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/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index b2b4e23fd99..a000ce11361 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -1555,10 +1555,7 @@ mod _socket { Ok(addr) if family == -1 => family = addr.family() as i32, Err(e) if family == -1 - || matches!( - e.raw_os_error(), - Some(c::ENOTSOCK | c::EBADF) - ) => + || matches!(e.raw_os_error(), Some(c::ENOTSOCK | c::EBADF)) => { core::mem::forget(sock); return Err(e.into()); diff --git a/crates/stdlib/src/ssl/cert.rs b/crates/stdlib/src/ssl/cert.rs index 794c5aafba4..f838733c03d 100644 --- a/crates/stdlib/src/ssl/cert.rs +++ b/crates/stdlib/src/ssl/cert.rs @@ -929,8 +929,10 @@ impl ServerCertVerifier for HostnameIgnoringVerifier { // Check if the error is a hostname mismatch // If so, ignore it (that's the whole point of HostnameIgnoringVerifier) match e { - rustls::Error::InvalidCertificate(rustls::CertificateError::NotValidForName | -rustls::CertificateError::NotValidForNameContext { .. }) => { + rustls::Error::InvalidCertificate( + rustls::CertificateError::NotValidForName + | rustls::CertificateError::NotValidForNameContext { .. }, + ) => { // Hostname mismatch - this is expected and acceptable // The certificate chain, trust anchor, and expiry are valid Ok(ServerCertVerified::assertion()) diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index 10ce7ef03be..d236f80f9cf 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -553,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" | "H" | "I" | "L" | "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(), From f2e0285746c734752fa8e5b44073f0052f176261 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 17:41:28 +0300 Subject: [PATCH 08/14] Allow cast to u8 --- crates/vm/src/format.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/vm/src/format.rs b/crates/vm/src/format.rs index 37b9d92eb89..ad66e696438 100644 --- a/crates/vm/src/format.rs +++ b/crates/vm/src/format.rs @@ -54,16 +54,20 @@ 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); + #[allow(clippy::unnecessary_cast, reason = "ptr is not u8 on all platforms")] + result.push(*ptr as u8); ptr = ptr.add(1); } } + if !result.is_empty() { result.push(0); } + result } From 599609c5686e0327f68493a2aa331bf1568b4bee Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 17:43:58 +0300 Subject: [PATCH 09/14] Use `as _` instead --- crates/vm/src/format.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/vm/src/format.rs b/crates/vm/src/format.rs index ad66e696438..e9db87fd121 100644 --- a/crates/vm/src/format.rs +++ b/crates/vm/src/format.rs @@ -58,8 +58,7 @@ unsafe fn parse_grouping(grouping: *const libc::c_char) -> Vec { unsafe { let mut ptr = grouping; while ![0, libc::c_char::MAX].contains(&*ptr) { - #[allow(clippy::unnecessary_cast, reason = "ptr is not u8 on all platforms")] - result.push(*ptr as u8); + result.push(*ptr as _); ptr = ptr.add(1); } } From 47c91f19a083a00a65ae7f1fec214a35aa90bc9a Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 17:53:50 +0300 Subject: [PATCH 10/14] Fix jit --- crates/jit/src/instructions.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/jit/src/instructions.rs b/crates/jit/src/instructions.rs index 88f6fe7411a..a63796512d9 100644 --- a/crates/jit/src/instructions.rs +++ b/crates/jit/src/instructions.rs @@ -580,10 +580,8 @@ 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(a) | JitValue::Int(a), JitValue::Bool(b)) => { let operand_one = match a_type.unwrap() { JitType::Bool => self.builder.ins().uextend(types::I64, a), _ => a, From 377a122e308e6b7703a66a1e269e739cacc0ee6c Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 17:56:20 +0300 Subject: [PATCH 11/14] fix wasm --- crates/wasm/src/convert.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 + ), .. }) ); From 346cea4dadb402f3f69aca5c58986dd29f7ed3e3 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 18:01:54 +0300 Subject: [PATCH 12/14] fix jit --- crates/jit/src/instructions.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/jit/src/instructions.rs b/crates/jit/src/instructions.rs index a63796512d9..ec9501d1fa8 100644 --- a/crates/jit/src/instructions.rs +++ b/crates/jit/src/instructions.rs @@ -580,8 +580,10 @@ impl<'a, 'b> FunctionCompiler<'a, 'b> { let b_type: Option = b.to_jit_type(); match (a, b) { - (JitValue::Int(a) | JitValue::Bool(a), JitValue::Int(b)) - | (JitValue::Bool(a) | 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, From 81d347d30d89941c22b9b6caf77ff0f03b305111 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 18:14:27 +0300 Subject: [PATCH 13/14] fix windows --- crates/vm/src/stdlib/_codecs.rs | 2 +- crates/vm/src/stdlib/_ctypes.rs | 2 +- crates/vm/src/stdlib/_ctypes/function.rs | 5 +---- crates/vm/src/stdlib/nt.rs | 10 +++++----- 4 files changed, 8 insertions(+), 11 deletions(-) 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 a4333c9971d..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)?; diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 24365d65e06..1e8e6309368 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -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); 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, )); } From ca99d5e9d4a9ff8e6ed790217d7aa03579de1454 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 1 May 2026 18:59:06 +0300 Subject: [PATCH 14/14] fix more --- crates/stdlib/src/socket.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index a000ce11361..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);