From 0336d47119f09958ae7708fcf2691647d3cad6de Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 09:30:08 +0300 Subject: [PATCH 01/12] Add clippy rule `map_unwrap_or` --- Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 53886778bab..9250f1e33bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -338,10 +338,11 @@ 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" # pedantic lints to enforce gradually cloned_instead_of_copied = "warn" +manual_is_variant_and = "warn" +map_unwrap_or = "warn" must_use_candidate = "warn" From fb83586ce45d64a5eb14ea6f2adf20c5836c6c45 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 09:30:23 +0300 Subject: [PATCH 02/12] Clippy fix --- crates/common/src/cformat.rs | 2 +- crates/derive-impl/src/pyclass.rs | 4 +--- crates/sre_engine/src/string.rs | 30 ++++++++---------------- crates/stdlib/src/_asyncio.rs | 4 +--- crates/stdlib/src/_opcode.rs | 25 +++++++------------- crates/stdlib/src/bisect.rs | 8 +++---- crates/stdlib/src/csv.rs | 3 +-- crates/stdlib/src/faulthandler.rs | 9 ++++--- crates/stdlib/src/json.rs | 3 +-- crates/stdlib/src/math.rs | 3 +-- crates/stdlib/src/mmap.rs | 10 +++----- crates/stdlib/src/ssl.rs | 24 +++++++------------ crates/stdlib/src/ssl/compat.rs | 6 ++--- crates/vm/src/builtins/float.rs | 4 +--- crates/vm/src/builtins/frame.rs | 5 ++-- crates/vm/src/builtins/function.rs | 4 +--- crates/vm/src/builtins/iter.rs | 4 +--- crates/vm/src/builtins/module.rs | 3 +-- crates/vm/src/builtins/object.rs | 4 +--- crates/vm/src/builtins/singletons.rs | 3 +-- crates/vm/src/builtins/str.rs | 6 ++--- crates/vm/src/builtins/template.rs | 4 +--- crates/vm/src/builtins/type.rs | 8 +++---- crates/vm/src/exceptions.rs | 8 ++----- crates/vm/src/frame.rs | 23 ++++++------------ crates/vm/src/getpath.rs | 4 +--- crates/vm/src/object/ext.rs | 12 ++++------ crates/vm/src/stdlib/_ast/statement.rs | 20 ++++------------ crates/vm/src/stdlib/_codecs.rs | 3 +-- crates/vm/src/stdlib/_collections.rs | 8 ++----- crates/vm/src/stdlib/_ctypes/array.rs | 6 ++--- crates/vm/src/stdlib/_ctypes/base.rs | 4 ++-- crates/vm/src/stdlib/_ctypes/function.rs | 12 ++++------ crates/vm/src/stdlib/_ctypes/pointer.rs | 3 +-- crates/vm/src/stdlib/_ctypes/simple.rs | 3 +-- crates/vm/src/stdlib/_functools.rs | 8 ++----- crates/vm/src/stdlib/_io.rs | 6 ++--- crates/vm/src/stdlib/_sre.rs | 12 +++------- crates/vm/src/stdlib/_typing.rs | 4 +--- crates/vm/src/stdlib/builtins.rs | 12 ++++------ crates/vm/src/types/slot.rs | 4 +--- crates/vm/src/warn.rs | 3 +-- 42 files changed, 107 insertions(+), 224 deletions(-) diff --git a/crates/common/src/cformat.rs b/crates/common/src/cformat.rs index 3b7ac5d76ec..cea23d1cb54 100644 --- a/crates/common/src/cformat.rs +++ b/crates/common/src/cformat.rs @@ -620,7 +620,7 @@ where let (index, c) = iter.next().ok_or_else(|| { ( CFormatErrorType::IncompleteFormat, - iter.peek().map(|x| x.0).unwrap_or(0), + iter.peek().map_or(0, |x| x.0), ) })?; let format_type = match c.to_char_lossy() { diff --git a/crates/derive-impl/src/pyclass.rs b/crates/derive-impl/src/pyclass.rs index aa87b193932..6c6baec0aa0 100644 --- a/crates/derive-impl/src/pyclass.rs +++ b/crates/derive-impl/src/pyclass.rs @@ -330,9 +330,7 @@ fn validate_base_field(item: &Item, base_path: &syn::Path) -> Result { diff --git a/crates/sre_engine/src/string.rs b/crates/sre_engine/src/string.rs index 9639be117a7..67068158c98 100644 --- a/crates/sre_engine/src/string.rs +++ b/crates/sre_engine/src/string.rs @@ -341,27 +341,23 @@ const fn is_py_ascii_whitespace(b: u8) -> bool { pub(crate) fn is_word(ch: u32) -> bool { ch == '_' as u32 || u8::try_from(ch) - .map(|x| x.is_ascii_alphanumeric()) - .unwrap_or(false) + .is_ok_and(|x| x.is_ascii_alphanumeric()) } #[inline] pub(crate) fn is_space(ch: u32) -> bool { u8::try_from(ch) - .map(is_py_ascii_whitespace) - .unwrap_or(false) + .is_ok_and(is_py_ascii_whitespace) } #[inline] pub(crate) fn is_digit(ch: u32) -> bool { u8::try_from(ch) - .map(|x| x.is_ascii_digit()) - .unwrap_or(false) + .is_ok_and(|x| x.is_ascii_digit()) } #[inline] pub(crate) fn is_loc_alnum(ch: u32) -> bool { // FIXME: Ignore the locales u8::try_from(ch) - .map(|x| x.is_ascii_alphanumeric()) - .unwrap_or(false) + .is_ok_and(|x| x.is_ascii_alphanumeric()) } #[inline] pub(crate) fn is_loc_word(ch: u32) -> bool { @@ -375,8 +371,7 @@ pub(crate) const fn is_linebreak(ch: u32) -> bool { #[must_use] pub fn lower_ascii(ch: u32) -> u32 { u8::try_from(ch) - .map(|x| x.to_ascii_lowercase() as u32) - .unwrap_or(ch) + .map_or(ch, |x| x.to_ascii_lowercase() as u32) } #[inline] pub(crate) fn lower_locate(ch: u32) -> u32 { @@ -387,15 +382,13 @@ pub(crate) fn lower_locate(ch: u32) -> u32 { pub(crate) fn upper_locate(ch: u32) -> u32 { // FIXME: Ignore the locales u8::try_from(ch) - .map(|x| x.to_ascii_uppercase() as u32) - .unwrap_or(ch) + .map_or(ch, |x| x.to_ascii_uppercase() as u32) } #[inline] pub(crate) fn is_uni_digit(ch: u32) -> bool { // TODO: check with cpython char::try_from(ch) - .map(|x| x.is_ascii_digit()) - .unwrap_or(false) + .is_ok_and(|x| x.is_ascii_digit()) } #[inline] pub(crate) fn is_uni_space(ch: u32) -> bool { @@ -445,12 +438,11 @@ pub(crate) const fn is_uni_linebreak(ch: u32) -> bool { pub(crate) fn is_uni_alnum(ch: u32) -> bool { // TODO: check with cpython char::try_from(ch) - .map(|c| { + .is_ok_and(|c| { GeneralCategoryGroup::Letter .union(GeneralCategoryGroup::Number) .contains(GeneralCategory::for_char(c)) }) - .unwrap_or(false) } #[inline] pub(crate) fn is_uni_word(ch: u32) -> bool { @@ -461,14 +453,12 @@ pub(crate) fn is_uni_word(ch: u32) -> bool { pub fn lower_unicode(ch: u32) -> u32 { // TODO: check with cpython char::try_from(ch) - .map(|x| x.to_lowercase().next().unwrap() as u32) - .unwrap_or(ch) + .map_or(ch, |x| x.to_lowercase().next().unwrap() as u32) } #[inline] #[must_use] pub fn upper_unicode(ch: u32) -> u32 { // TODO: check with cpython char::try_from(ch) - .map(|x| x.to_uppercase().next().unwrap() as u32) - .unwrap_or(ch) + .map_or(ch, |x| x.to_uppercase().next().unwrap() as u32) } diff --git a/crates/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index 508947b561f..6f1318e393a 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -899,9 +899,7 @@ pub(crate) mod _asyncio { vm.get_attribute_opt(future.to_owned(), vm.ctx.intern_str("_state")) { let s = state - .str(vm) - .map(|s| s.as_wtf8().to_lowercase()) - .unwrap_or_else(|_| Wtf8Buf::from("unknown")); + .str(vm).map_or_else(|_| Wtf8Buf::from("unknown"), |s| s.as_wtf8().to_lowercase()); return Ok(s); } Ok(Wtf8Buf::from("state=unknown")) diff --git a/crates/stdlib/src/_opcode.rs b/crates/stdlib/src/_opcode.rs index a57a275b76d..dcf40aedaf9 100644 --- a/crates/stdlib/src/_opcode.rs +++ b/crates/stdlib/src/_opcode.rs @@ -36,7 +36,7 @@ mod _opcode { fn stack_effect(args: StackEffectArgs, vm: &VirtualMachine) -> PyResult { let oparg = args .oparg - .map(|v| { + .map_or(Ok(0), |v| { if !v.fast_isinstance(vm.ctx.types.int_type) { return Err(vm.new_type_error(format!( "'{}' object cannot be interpreted as an integer", @@ -51,8 +51,7 @@ mod _opcode { )) })? .try_to_primitive::(vm) - }) - .unwrap_or(Ok(0))?; + })?; let jump: Option = match args.jump { Some(v) => { @@ -99,49 +98,43 @@ mod _opcode { #[pyfunction] fn has_arg(opcode: i32) -> bool { - try_from_i32(opcode).map(|op| op.has_arg()).unwrap_or(false) + try_from_i32(opcode).is_ok_and(|op| op.has_arg()) } #[pyfunction] fn has_const(opcode: i32) -> bool { try_from_i32(opcode) - .map(|op| op.has_const()) - .unwrap_or(false) + .is_ok_and(|op| op.has_const()) } #[pyfunction] fn has_name(opcode: i32) -> bool { try_from_i32(opcode) - .map(|op| op.has_name()) - .unwrap_or(false) + .is_ok_and(|op| op.has_name()) } #[pyfunction] fn has_jump(opcode: i32) -> bool { try_from_i32(opcode) - .map(|op| op.has_jump()) - .unwrap_or(false) + .is_ok_and(|op| op.has_jump()) } #[pyfunction] fn has_free(opcode: i32) -> bool { try_from_i32(opcode) - .map(|op| op.has_free()) - .unwrap_or(false) + .is_ok_and(|op| op.has_free()) } #[pyfunction] fn has_local(opcode: i32) -> bool { try_from_i32(opcode) - .map(|op| op.has_local()) - .unwrap_or(false) + .is_ok_and(|op| op.has_local()) } #[pyfunction] fn has_exc(opcode: i32) -> bool { try_from_i32(opcode) - .map(|op| op.is_block_push()) - .unwrap_or(false) + .is_ok_and(|op| op.is_block_push()) } #[pyfunction] diff --git a/crates/stdlib/src/bisect.rs b/crates/stdlib/src/bisect.rs index 69b6e8aee46..ad2966c528d 100644 --- a/crates/stdlib/src/bisect.rs +++ b/crates/stdlib/src/bisect.rs @@ -45,13 +45,11 @@ mod _bisect { // We only deal with positives for lo, try_from can't fail. // Default is always a Some so we can safely unwrap. let lo = handle_default(lo, vm)? - .map(|value| { + .map_or(Ok(0), |value| { usize::try_from(value).map_err(|_| vm.new_value_error("lo must be non-negative")) - }) - .unwrap_or(Ok(0))?; + })?; let hi = handle_default(hi, vm)? - .map(|value| usize::try_from(value).unwrap_or(0)) - .unwrap_or(seq_len); + .map_or(seq_len, |value| usize::try_from(value).unwrap_or(0)); Ok((lo, hi)) } diff --git a/crates/stdlib/src/csv.rs b/crates/stdlib/src/csv.rs index 5c2d2662cc5..7fac2983833 100644 --- a/crates/stdlib/src/csv.rs +++ b/crates/stdlib/src/csv.rs @@ -967,8 +967,7 @@ mod _csv { let trimmed_end = input .iter() .rposition(|&x| x != b' ') - .map(|i| i + 1) - .unwrap_or(0); + .map_or(0, |i| i + 1); &input[trimmed_start..trimmed_end] } let input = if *skipinitialspace { diff --git a/crates/stdlib/src/faulthandler.rs b/crates/stdlib/src/faulthandler.rs index 3c3533d9914..2b59ae85f81 100644 --- a/crates/stdlib/src/faulthandler.rs +++ b/crates/stdlib/src/faulthandler.rs @@ -218,13 +218,13 @@ mod decl { let funcname = frame.code.obj_name.as_str(); let lasti = frame.lasti(); let lineno = if lasti == 0 { - frame.code.first_line_number.map(|n| n.get()).unwrap_or(1) as u32 + frame.code.first_line_number.map_or(1, |n| n.get()) as u32 } else { let idx = (lasti as usize).saturating_sub(1); if idx < frame.code.locations.len() { frame.code.locations[idx].0.line.get() as u32 } else { - frame.code.first_line_number.map(|n| n.get()).unwrap_or(0) as u32 + frame.code.first_line_number.map_or(0, |n| n.get()) as u32 } }; @@ -292,7 +292,7 @@ mod decl { let funcname = frame.code.obj_name.as_str(); let filename = frame.code.source_path().as_str(); let lineno = if frame.lasti() == 0 { - frame.code.first_line_number.map(|n| n.get()).unwrap_or(1) as u32 + frame.code.first_line_number.map_or(1, |n| n.get()) as u32 } else { frame.current_location().line.get() as u32 }; @@ -1112,8 +1112,7 @@ mod decl { } else { // Already registered, keep previous handler user_signals::get_user_signal(signum) - .map(|u| u.previous) - .unwrap_or(unsafe { core::mem::zeroed() }) + .map_or(unsafe { core::mem::zeroed() }, |u| u.previous) }; user_signals::set_user_signal( diff --git a/crates/stdlib/src/json.rs b/crates/stdlib/src/json.rs index 8b3ef8d2e9c..a32397ad59d 100644 --- a/crates/stdlib/src/json.rs +++ b/crates/stdlib/src/json.rs @@ -616,8 +616,7 @@ mod _json { let end_byte_idx = wtf8 .code_point_indices() .nth(end_char_idx as usize) - .map(|(i, _)| i) - .unwrap_or(wtf8.len()); + .map_or(wtf8.len(), |(i, _)| i); Ok((value, end_char_idx as usize, end_byte_idx)) } Err(err) if err.fast_isinstance(vm.ctx.exceptions.stop_iteration) => { diff --git a/crates/stdlib/src/math.rs b/crates/stdlib/src/math.rs index b2ef4a42ba7..3e3793107a7 100644 --- a/crates/stdlib/src/math.rs +++ b/crates/stdlib/src/math.rs @@ -560,8 +560,7 @@ mod math { f.to_f64() } else if start_is_float && let OptionalArg::Present(s) = &start { s.downcast_ref::() - .map(|f| f.to_f64()) - .unwrap_or(1.0) + .map_or(1.0, |f| f.to_f64()) } else { 1.0 }; diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index d360a2c2ada..c589f668cfd 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -958,13 +958,10 @@ mod mmap { fn get_find_range(&self, options: FindOptions) -> (usize, usize) { let size = self.__len__(); let start = options - .start - .map(|start| start.saturated_at(size)) - .unwrap_or_else(|| self.pos()); + .start.map_or_else(|| self.pos(), |start| start.saturated_at(size)); let end = options .end - .map(|end| end.saturated_at(size)) - .unwrap_or(size); + .map_or(size, |end| end.saturated_at(size)); (start, end) } @@ -1121,8 +1118,7 @@ mod mmap { let remaining = self.__len__().saturating_sub(pos); let num_bytes = num_bytes .filter(|&n| n >= 0 && (n as usize) <= remaining) - .map(|n| n as usize) - .unwrap_or(remaining); + .map_or(remaining, |n| n as usize); let end_pos = pos + num_bytes; let bytes = mmap.deref().as_ref().unwrap().as_slice()[pos..end_pos].to_vec(); diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index caaf9b70f29..1322a831111 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -2558,8 +2558,7 @@ mod _ssl { .connection .lock() .as_ref() - .map(|conn| conn.is_session_resumed()) - .unwrap_or(false); + .is_some_and(|conn| conn.is_session_resumed()); *self.session_was_reused.lock() = was_resumed; @@ -2835,7 +2834,7 @@ mod _ssl { } let socket_timeout = self.get_socket_timeout(vm)?; - let is_non_blocking = socket_timeout.map(|t| t.is_zero()).unwrap_or(false); + let is_non_blocking = socket_timeout.is_some_and(|t| t.is_zero()); let mut sent_total = 0; @@ -2918,7 +2917,7 @@ mod _ssl { } let timeout = self.get_socket_timeout(vm)?; - let is_non_blocking = timeout.map(|t| t.is_zero()).unwrap_or(false); + let is_non_blocking = timeout.is_some_and(|t| t.is_zero()); let mut sent_total = 0; while sent_total < buf.len() { @@ -2976,7 +2975,7 @@ mod _ssl { pub(crate) fn blocking_flush_all_pending(&self, vm: &VirtualMachine) -> PyResult<()> { // Get socket timeout to respect during flush let timeout = self.get_socket_timeout(vm)?; - if timeout.map(|t| t.is_zero()).unwrap_or(false) { + if timeout.is_some_and(|t| t.is_zero()) { return self.flush_pending_tls_output(vm, None); } @@ -3581,7 +3580,7 @@ mod _ssl { }; let mut reader = conn.reader(); - reader.fill_buf().map(|buf| buf.len()).unwrap_or(0) + reader.fill_buf().map_or(0, |buf| buf.len()) }; if pending > 0 { let mut buf = vec![0u8; pending.min(len)]; @@ -3610,7 +3609,7 @@ mod _ssl { }; let mut reader = conn.reader(); - reader.fill_buf().map(|buf| buf.len()).unwrap_or(0) + reader.fill_buf().map_or(0, |buf| buf.len()) }; if pending > 0 { let mut buf = vec![0u8; pending.min(len)]; @@ -4779,8 +4778,7 @@ mod _ssl { let entry = if txt .chars() .next() - .map(|c| c.is_ascii_digit()) - .unwrap_or(false) + .is_some_and(|c| c.is_ascii_digit()) { // Looks like an OID string (starts with digit) oid::find_by_oid_string(txt) @@ -4848,13 +4846,9 @@ mod _ssl { let tuple = vm.ctx.new_tuple(vec![ vm.ctx.new_str("SSL_CERT_FILE").into(), // openssl_cafile_env - default_cafile - .map(|s| vm.ctx.new_str(s).into()) - .unwrap_or_else(|| vm.ctx.none()), // openssl_cafile + default_cafile.map_or_else(|| vm.ctx.none(), |s| vm.ctx.new_str(s).into()), // openssl_cafile vm.ctx.new_str("SSL_CERT_DIR").into(), // openssl_capath_env - default_capath - .map(|s| vm.ctx.new_str(s).into()) - .unwrap_or_else(|| vm.ctx.none()), // openssl_capath + default_capath.map_or_else(|| vm.ctx.none(), |s| vm.ctx.new_str(s).into()), // openssl_capath ]); Ok(tuple.into()) } diff --git a/crates/stdlib/src/ssl/compat.rs b/crates/stdlib/src/ssl/compat.rs index 3cf7db49c5a..29e3687e9d6 100644 --- a/crates/stdlib/src/ssl/compat.rs +++ b/crates/stdlib/src/ssl/compat.rs @@ -1754,8 +1754,7 @@ pub(super) fn ssl_read( let bytes_read = data .clone() .try_into_value::(vm) - .map(|b| b.as_bytes().len()) - .unwrap_or(0); + .map_or(0, |b| b.as_bytes().len()); if bytes_read == 0 { // No more data available - check if this is clean shutdown or unexpected EOF @@ -2177,8 +2176,7 @@ fn ssl_ensure_data_available( let bytes_read = data .clone() .try_into_value::(vm) - .map(|b| b.as_bytes().len()) - .unwrap_or(0); + .map_or(0, |b| b.as_bytes().len()); // Check if BIO has EOF set (incoming BIO closed) let is_eof = if is_bio { diff --git a/crates/vm/src/builtins/float.rs b/crates/vm/src/builtins/float.rs index cfce960c18d..111fcd147c8 100644 --- a/crates/vm/src/builtins/float.rs +++ b/crates/vm/src/builtins/float.rs @@ -247,9 +247,7 @@ fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult { ))); }; crate::literal::float::parse_bytes(b).ok_or_else(|| { - val.repr(vm) - .map(|repr| vm.new_value_error(format!("could not convert string to float: {repr}"))) - .unwrap_or_else(|e| e) + val.repr(vm).map_or_else(|e| e, |repr| vm.new_value_error(format!("could not convert string to float: {repr}"))) }) } diff --git a/crates/vm/src/builtins/frame.rs b/crates/vm/src/builtins/frame.rs index 3c1c48b66f0..60519dcaad2 100644 --- a/crates/vm/src/builtins/frame.rs +++ b/crates/vm/src/builtins/frame.rs @@ -474,7 +474,7 @@ impl Frame { // If lasti is 0, execution hasn't started yet - use first line number // Similar to PyCode_Addr2Line which returns co_firstlineno for addr_q < 0 if self.lasti() == 0 { - self.code.first_line_number.map(|n| n.get()).unwrap_or(1) + self.code.first_line_number.map_or(1, |n| n.get()) } else { self.current_location().line.get() } @@ -499,8 +499,7 @@ impl Frame { let first_line = self .code .first_line_number - .map(|n| n.get() as i32) - .unwrap_or(1); + .map_or(1, |n| n.get() as i32); if l_new_lineno < first_line { return Err(vm.new_value_error(format!( diff --git a/crates/vm/src/builtins/function.rs b/crates/vm/src/builtins/function.rs index 10f96fd70c9..0a7fa5a26b6 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -191,9 +191,7 @@ impl PyFunction { let doc = if code.code.flags.contains(bytecode::CodeFlags::HAS_DOCSTRING) { code.code .constants - .first() - .map(|c| c.as_object().to_owned()) - .unwrap_or_else(|| vm.ctx.none()) + .first().map_or_else(|| vm.ctx.none(), |c| c.as_object().to_owned()) } else { vm.ctx.none() }; diff --git a/crates/vm/src/builtins/iter.rs b/crates/vm/src/builtins/iter.rs index a5b4fe0d3cc..34f6dff8459 100644 --- a/crates/vm/src/builtins/iter.rs +++ b/crates/vm/src/builtins/iter.rs @@ -188,9 +188,7 @@ impl PySequenceIterator { let internal = self.internal.lock(); if let IterStatus::Active(obj) = &internal.status { let seq = obj.sequence_unchecked(); - seq.length(vm) - .map(|x| PyInt::from(x).into_pyobject(vm)) - .unwrap_or_else(|_| vm.ctx.not_implemented()) + seq.length(vm).map_or_else(|_| vm.ctx.not_implemented(), |x| PyInt::from(x).into_pyobject(vm)) } else { PyInt::from(0).into_pyobject(vm) } diff --git a/crates/vm/src/builtins/module.rs b/crates/vm/src/builtins/module.rs index 9ddf27e1297..f9d3df8df97 100644 --- a/crates/vm/src/builtins/module.rs +++ b/crates/vm/src/builtins/module.rs @@ -185,8 +185,7 @@ impl Py { let is_possibly_shadowing = origin .as_ref() - .map(|o| is_possibly_shadowing_path(o, vm)) - .unwrap_or(false); + .is_some_and(|o| is_possibly_shadowing_path(o, vm)); // Use the ORIGINAL __name__ object for stdlib check (may raise TypeError // if __name__ is an unhashable str subclass) let is_possibly_shadowing_stdlib = if is_possibly_shadowing { diff --git a/crates/vm/src/builtins/object.rs b/crates/vm/src/builtins/object.rs index 6670d64d588..31ee89e36ac 100644 --- a/crates/vm/src/builtins/object.rs +++ b/crates/vm/src/builtins/object.rs @@ -756,9 +756,7 @@ fn reduce_newobj(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Use copyreg.__newobj_ex__ let newobj = copyreg.get_attr("__newobj_ex__", vm)?; let args_tuple: PyObjectRef = args.into(); - let kwargs_dict: PyObjectRef = kwargs - .map(|k| k.into()) - .unwrap_or_else(|| vm.ctx.new_dict().into()); + let kwargs_dict: PyObjectRef = kwargs.map_or_else(|| vm.ctx.new_dict().into(), |k| k.into()); let newargs = vm .ctx diff --git a/crates/vm/src/builtins/singletons.rs b/crates/vm/src/builtins/singletons.rs index 31dbf1666f1..7a042b221d4 100644 --- a/crates/vm/src/builtins/singletons.rs +++ b/crates/vm/src/builtins/singletons.rs @@ -84,8 +84,7 @@ impl Comparable for PyNone { ) -> PyResult { Ok(op .identical_optimization(zelf, other) - .map(PyComparisonValue::Implemented) - .unwrap_or(PyComparisonValue::NotImplemented)) + .map_or(PyComparisonValue::NotImplemented, PyComparisonValue::Implemented)) } } diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index 60c588ba47c..9ffe9663536 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -452,7 +452,7 @@ impl Constructor for PyStr { input.class().name() ))); } - let enc_str = encoding.as_ref().map(|e| e.as_str()).unwrap_or("utf-8"); + let enc_str = encoding.as_ref().map_or("utf-8", |e| e.as_str()); let s = vm .state .codec_registry @@ -549,9 +549,7 @@ impl PyStr { } pub fn to_string_lossy(&self) -> Cow<'_, str> { - self.to_str() - .map(Cow::Borrowed) - .unwrap_or_else(|| self.as_wtf8().to_string_lossy()) + self.to_str().map_or_else(|| self.as_wtf8().to_string_lossy(), Cow::Borrowed) } pub const fn kind(&self) -> StrKind { diff --git a/crates/vm/src/builtins/template.rs b/crates/vm/src/builtins/template.rs index ba5e9c5eb0c..ac8b190f6b0 100644 --- a/crates/vm/src/builtins/template.rs +++ b/crates/vm/src/builtins/template.rs @@ -115,9 +115,7 @@ impl PyTemplate { .iter() .map(|interp| { interp - .downcast_ref::() - .map(|i| i.value.clone()) - .unwrap_or_else(|| interp.clone()) + .downcast_ref::().map_or_else(|| interp.clone(), |i| i.value.clone()) }) .collect(); vm.ctx.new_tuple(values) diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index 6208bc5ebfe..94574dc375b 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -862,8 +862,7 @@ impl PyType { } else if slots.new.load().is_none() { slots.new.store( base.as_ref() - .map(|base| base.slots.new.load()) - .unwrap_or(None), + .and_then(|base| base.slots.new.load()), ) } } @@ -872,8 +871,7 @@ impl PyType { if slots.alloc.load().is_none() { slots.alloc.store( base.as_ref() - .map(|base| base.slots.alloc.load()) - .unwrap_or(None), + .and_then(|base| base.slots.alloc.load()), ); } } @@ -2072,7 +2070,7 @@ impl Constructor for PyType { .map(|base| base.slots.member_count) .max() .unwrap(); - let heaptype_member_count = heaptype_slots.as_ref().map(|x| x.len()).unwrap_or(0); + let heaptype_member_count = heaptype_slots.as_ref().map_or(0, |x| x.len()); let member_count: usize = base_member_count + heaptype_member_count; let mut flags = PyTypeFlags::heap_type_flags(); diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index 230ea182df6..ad0283f1fb9 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -2033,15 +2033,11 @@ pub(super) mod types { let errno_str = errno_field .as_ref() .map(|e| e.str(vm)) - .transpose()? - .map(|s| s.to_string()) - .unwrap_or_else(|| "None".to_owned()); + .transpose()?.map_or_else(|| "None".to_owned(), |s| s.to_string()); let msg = strerror .as_ref() .map(|s| s.str(vm)) - .transpose()? - .map(|s| s.to_string()) - .unwrap_or_else(|| "None".to_owned()); + .transpose()?.map_or_else(|| "None".to_owned(), |s| s.to_string()); if let Some(ref f2) = filename2 { return Ok(vm.ctx.new_str(format!( "[Errno {}] {}: {} -> {}", diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index c87341de32a..f93dad2b609 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -1503,9 +1503,7 @@ impl ExecutingFrame<'_> { let exc_type: PyObjectRef = exc.class().to_owned().into(); let exc_value: PyObjectRef = exc.clone().into(); let exc_tb: PyObjectRef = exc - .__traceback__() - .map(|tb| -> PyObjectRef { tb.into() }) - .unwrap_or_else(|| vm.ctx.none()); + .__traceback__().map_or_else(|| vm.ctx.none(), |tb| -> PyObjectRef { tb.into() }); let tuple = vm.ctx.new_tuple(vec![exc_type, exc_value, exc_tb]).into(); vm.trace_event(crate::protocol::TraceEvent::Exception, Some(tuple))?; } @@ -3425,9 +3423,7 @@ impl ExecutingFrame<'_> { // Stack: [exc] -> [prev_exc, exc] let exc = self.pop_value(); let prev_exc = vm - .current_exception() - .map(|e| e.into()) - .unwrap_or_else(|| vm.ctx.none()); + .current_exception().map_or_else(|| vm.ctx.none(), |e| e.into()); // Set exc as the current exception if let Some(exc_ref) = exc.downcast_ref::() { @@ -6089,13 +6085,12 @@ impl ExecutingFrame<'_> { // because a callback may de-instrument and clear the tables. let (real_op_byte, also_instruction) = { let data = self.code.monitoring_data.lock(); - let line_op = data.as_ref().map(|d| d.line_opcodes[idx]).unwrap_or(0); + let line_op = data.as_ref().map_or(0, |d| d.line_opcodes[idx]); if line_op == u8::from(Instruction::InstrumentedInstruction) { // LINE wraps INSTRUCTION: resolve the INSTRUCTION side-table too let inst_op = data .as_ref() - .map(|d| d.per_instruction_opcodes[idx]) - .unwrap_or(0); + .map_or(0, |d| d.per_instruction_opcodes[idx]); (inst_op, true) } else { (line_op, false) @@ -6144,8 +6139,7 @@ impl ExecutingFrame<'_> { let original_op_byte = { let data = self.code.monitoring_data.lock(); data.as_ref() - .map(|d| d.per_instruction_opcodes[idx]) - .unwrap_or(0) + .map_or(0, |d| d.per_instruction_opcodes[idx]) }; debug_assert!( original_op_byte != 0, @@ -6282,8 +6276,7 @@ impl ExecutingFrame<'_> { let is_possibly_shadowing = origin .as_ref() - .map(|o| is_possibly_shadowing_path(o, vm)) - .unwrap_or(false); + .is_some_and(|o| is_possibly_shadowing_path(o, vm)); let is_possibly_shadowing_stdlib = if is_possibly_shadowing { if let Some(ref mod_name) = mod_name_obj { is_stdlib_module_name(mod_name, vm)? @@ -9618,9 +9611,7 @@ impl ExecutingFrame<'_> { let stack_len = self.localsplus.stack_len(); if count > stack_len { let instr = self.code.instructions.get(self.lasti() as usize); - let op_name = instr - .map(|i| format!("{:?}", i.op)) - .unwrap_or_else(|| "None".to_string()); + let op_name = instr.map_or_else(|| "None".to_string(), |i| format!("{:?}", i.op)); panic!( "Stack underflow in pop_multiple: trying to pop {} elements from stack with {} elements. lasti={}, code={}, op={}, source_path={}", count, diff --git a/crates/vm/src/getpath.rs b/crates/vm/src/getpath.rs index 0ed62136088..2dc2cda0e57 100644 --- a/crates/vm/src/getpath.rs +++ b/crates/vm/src/getpath.rs @@ -146,9 +146,7 @@ pub fn init_path_config(settings: &Settings) -> Paths { if venv_prefix.is_some() { // In venv: prefix = venv directory, base_prefix = original Python's prefix paths.prefix = venv_prefix - .as_ref() - .map(|p| p.to_string_lossy().into_owned()) - .unwrap_or_else(|| calculated_prefix.clone()); + .as_ref().map_or_else(|| calculated_prefix.clone(), |p| p.to_string_lossy().into_owned()); paths.base_prefix = calculated_prefix; } else { // Not in venv: prefix == base_prefix diff --git a/crates/vm/src/object/ext.rs b/crates/vm/src/object/ext.rs index dc4a7bd4fd4..91c6e9756ed 100644 --- a/crates/vm/src/object/ext.rs +++ b/crates/vm/src/object/ext.rs @@ -347,8 +347,7 @@ impl PyAtomicRef { impl From>> for PyAtomicRef> { fn from(opt_ref: Option>) -> Self { let val = opt_ref - .map(|x| PyRef::leak(x) as *const Py as *mut _) - .unwrap_or(null_mut()); + .map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); Self { inner: Radium::new(val), _phantom: Default::default(), @@ -379,8 +378,7 @@ impl PyAtomicRef> { #[must_use] pub unsafe fn swap(&self, opt_ref: Option>) -> Option> { let val = opt_ref - .map(|x| PyRef::leak(x) as *const Py as *mut _) - .unwrap_or(null_mut()); + .map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); unsafe { old.cast::>().as_ref().map(|x| PyRef::from_raw(x)) } } @@ -441,8 +439,7 @@ impl PyAtomicRef { impl From> for PyAtomicRef> { fn from(obj: Option) -> Self { let val = obj - .map(|x| x.into_raw().as_ptr().cast()) - .unwrap_or(null_mut()); + .map_or(null_mut(), |x| x.into_raw().as_ptr().cast()); Self { inner: Radium::new(val), _phantom: Default::default(), @@ -473,8 +470,7 @@ impl PyAtomicRef> { #[must_use] pub unsafe fn swap(&self, obj: Option) -> Option { let val = obj - .map(|x| x.into_raw().as_ptr().cast()) - .unwrap_or(null_mut()); + .map_or(null_mut(), |x| x.into_raw().as_ptr().cast()); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); unsafe { NonNull::new(old.cast::()).map(|x| PyObjectRef::from_raw(x)) } } diff --git a/crates/vm/src/stdlib/_ast/statement.rs b/crates/vm/src/stdlib/_ast/statement.rs index 386f4d8cc93..4eca89f7454 100644 --- a/crates/vm/src/stdlib/_ast/statement.rs +++ b/crates/vm/src/stdlib/_ast/statement.rs @@ -191,9 +191,7 @@ impl Node for ast::StmtFunctionDef { dict.set_item("type_comment", vm.ctx.none(), vm).unwrap(); dict.set_item( "type_params", - type_params - .map(|tp| tp.ast_to_object(vm, source_file)) - .unwrap_or_else(|| vm.ctx.new_list(vec![]).into()), + type_params.map_or_else(|| vm.ctx.new_list(vec![]).into(), |tp| tp.ast_to_object(vm, source_file)), vm, ) .unwrap(); @@ -273,17 +271,13 @@ impl Node for ast::StmtClassDef { .unwrap(); dict.set_item( "bases", - bases - .map(|b| b.ast_to_object(_vm, source_file)) - .unwrap_or_else(|| _vm.ctx.new_list(vec![]).into()), + bases.map_or_else(|| _vm.ctx.new_list(vec![]).into(), |b| b.ast_to_object(_vm, source_file)), _vm, ) .unwrap(); dict.set_item( "keywords", - keywords - .map(|k| k.ast_to_object(_vm, source_file)) - .unwrap_or_else(|| _vm.ctx.new_list(vec![]).into()), + keywords.map_or_else(|| _vm.ctx.new_list(vec![]).into(), |k| k.ast_to_object(_vm, source_file)), _vm, ) .unwrap(); @@ -297,9 +291,7 @@ impl Node for ast::StmtClassDef { .unwrap(); dict.set_item( "type_params", - type_params - .map(|tp| tp.ast_to_object(_vm, source_file)) - .unwrap_or_else(|| _vm.ctx.new_list(vec![]).into()), + type_params.map_or_else(|| _vm.ctx.new_list(vec![]).into(), |tp| tp.ast_to_object(_vm, source_file)), _vm, ) .unwrap(); @@ -480,9 +472,7 @@ impl Node for ast::StmtTypeAlias { .unwrap(); dict.set_item( "type_params", - type_params - .map(|tp| tp.ast_to_object(_vm, source_file)) - .unwrap_or_else(|| _vm.ctx.new_list(Vec::new()).into()), + type_params.map_or_else(|| _vm.ctx.new_list(Vec::new()).into(), |tp| tp.ast_to_object(_vm, source_file)), _vm, ) .unwrap(); diff --git a/crates/vm/src/stdlib/_codecs.rs b/crates/vm/src/stdlib/_codecs.rs index b2c0a220003..e1708602d07 100644 --- a/crates/vm/src/stdlib/_codecs.rs +++ b/crates/vm/src/stdlib/_codecs.rs @@ -62,8 +62,7 @@ mod _codecs { let encoding = self .encoding .as_deref() - .map(|s| s.as_str()) - .unwrap_or(codecs::DEFAULT_ENCODING); + .map_or(codecs::DEFAULT_ENCODING, |s| s.as_str()); f( &vm.state.codec_registry, self.obj, diff --git a/crates/vm/src/stdlib/_collections.rs b/crates/vm/src/stdlib/_collections.rs index 8eacc69f039..0a6c007d4bc 100644 --- a/crates/vm/src/stdlib/_collections.rs +++ b/crates/vm/src/stdlib/_collections.rs @@ -180,9 +180,7 @@ mod _collections { } else { Err(vm.new_value_error( needle - .repr(vm) - .map(|repr| format!("{repr} is not in deque")) - .unwrap_or_else(|_| String::new()), + .repr(vm).map_or_else(|_| String::new(), |repr| format!("{repr} is not in deque")), )) } } @@ -568,9 +566,7 @@ mod _collections { let class = zelf.class(); let class_name = class.name(); let closing_part = zelf - .maxlen - .map(|maxlen| format!("], maxlen={maxlen}")) - .unwrap_or_else(|| "]".to_owned()); + .maxlen.map_or_else(|| "]".to_owned(), |maxlen| format!("], maxlen={maxlen}")); if zelf.__len__() == 0 { return Ok(vm.ctx.new_str(format!("{class_name}([{closing_part})"))); diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index c04e342547a..7be413a74bc 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -26,8 +26,7 @@ fn get_size_from_format(fmt: &str) -> usize { .chars() .next() .map(|c| c.to_string()); - code.map(|c| type_info(&c).map(|t| t.size).unwrap_or(1)) - .unwrap_or(1) + code.map_or(1, |c| type_info(&c).map_or(1, |t| t.size)) } /// Creates array type for (element_type, length) @@ -774,8 +773,7 @@ impl PyCArray { .as_wtf8() .code_points() .next() - .map(|c| c.to_u32()) - .unwrap_or(0); + .map_or(0, |c| c.to_u32()); if offset + WCHAR_SIZE <= buffer.len() { wchar_to_bytes(code, &mut buffer[offset..]); } diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index 7d611c27b0f..9eda289b548 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -2098,7 +2098,7 @@ impl FfiArgValue { pub(super) fn buffer_to_ffi_value(type_code: &str, buffer: &[u8]) -> FfiArgValue { match type_code { "c" | "b" => { - let v = buffer.first().map(|&b| b as i8).unwrap_or(0); + let v = buffer.first().map_or(0, |&b| b as i8); FfiArgValue::I8(v) } "B" => { @@ -2157,7 +2157,7 @@ pub(super) fn buffer_to_ffi_value(type_code: &str, buffer: &[u8]) -> FfiArgValue } "z" | "Z" | "P" | "O" => FfiArgValue::Pointer(read_ptr_from_buffer(buffer)), "?" => { - let v = buffer.first().map(|&b| b != 0).unwrap_or(false); + let v = buffer.first().is_some_and(|&b| b != 0); FfiArgValue::U8(if v { 1 } else { 0 }) } "u" => { diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 0577bdc83bd..a77c8e3d108 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -1760,7 +1760,7 @@ fn build_result( // Handle OUT parameter return values if out_buffers.is_empty() { - return result.map(Ok).unwrap_or_else(|| Ok(vm.ctx.none())); + return result.map_or_else(|| Ok(vm.ctx.none()), Ok); } let out_values = extract_out_values(out_buffers, vm); @@ -1851,8 +1851,7 @@ impl AsBuffer for PyCFuncPtr { stg_info .format .clone() - .map(Cow::Owned) - .unwrap_or(Cow::Borrowed("X{}")), + .map_or(Cow::Borrowed("X{}"), Cow::Owned), stg_info.size, ) } else { @@ -1946,8 +1945,7 @@ impl PyCFuncPtr { // Fallback to StgInfo for native types zelf.class() .stg_info_opt() - .map(|stg| stg.flags.bits()) - .unwrap_or(StgInfoFlags::empty().bits()) + .map_or(StgInfoFlags::empty().bits(), |stg| stg.flags.bits()) } } @@ -2183,9 +2181,7 @@ unsafe extern "C" fn thunk_callback( if let Err(exc) = &py_result { let repr = userdata .callable - .repr(vm) - .map(|s| s.to_string()) - .unwrap_or_else(|_| "".to_string()); + .repr(vm).map_or_else(|_| "".to_string(), |s| s.to_string()); let msg = format!( "Exception ignored while calling ctypes callback function {}", repr diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 1e704a1e4ad..57535c175ca 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -845,8 +845,7 @@ impl AsBuffer for PyCPointer { let format = stg_info .format .clone() - .map(Cow::Owned) - .unwrap_or(Cow::Borrowed("&B")); + .map_or(Cow::Borrowed("&B"), Cow::Owned); let itemsize = stg_info.size; // Pointer types are scalars with ndim=0, shape=() let desc = BufferDescriptor { diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index 1dd2001335f..bb00d4830ce 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -1424,8 +1424,7 @@ impl AsBuffer for PyCSimple { let format = stg_info .format .clone() - .map(Cow::Owned) - .unwrap_or(Cow::Borrowed("B")); + .map_or(Cow::Borrowed("B"), Cow::Owned); let itemsize = stg_info.size; // Simple types are scalars with ndim=0, shape=() let desc = BufferDescriptor { diff --git a/crates/vm/src/stdlib/_functools.rs b/crates/vm/src/stdlib/_functools.rs index 7e648bae259..28d1bb1f9ae 100644 --- a/crates/vm/src/stdlib/_functools.rs +++ b/crates/vm/src/stdlib/_functools.rs @@ -163,9 +163,7 @@ mod _functools { #[pygetset] fn __dict__(zelf: &Py, vm: &VirtualMachine) -> PyDictRef { zelf.as_object() - .instance_dict() - .map(|d| d.get_or_insert(vm)) - .unwrap_or_else(|| vm.ctx.new_dict()) + .instance_dict().map_or_else(|| vm.ctx.new_dict(), |d| d.get_or_insert(vm)) } #[pygetset(setter)] @@ -491,9 +489,7 @@ mod _functools { let qualname = zelf.class().__qualname__(vm); let qualname_wtf8 = qualname - .downcast_ref::() - .map(|s| s.as_wtf8().to_owned()) - .unwrap_or_else(|| Wtf8Buf::from(zelf.class().name().to_owned())); + .downcast_ref::().map_or_else(|| Wtf8Buf::from(zelf.class().name().to_owned()), |s| s.as_wtf8().to_owned()); let module = zelf.class().__module__(vm); let mut result = Wtf8Buf::new(); diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index 5295dba5012..b5c4bc3ef31 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -1856,7 +1856,7 @@ mod _io { fn read(&self, size: OptionalSize, vm: &VirtualMachine) -> PyResult> { let mut data = self.reader().lock(vm)?; let raw = data.check_init(vm)?; - let n = size.size.map(|s| *s).unwrap_or(-1); + let n = size.size.map_or(-1, |s| *s); if n < -1 { return Err(vm.new_value_error("read length must be non-negative or -1")); } @@ -5967,9 +5967,7 @@ mod fileio { fn dealloc_warn(zelf: &Py, source: PyObjectRef, vm: &VirtualMachine) { if zelf.fd.load() >= 0 && zelf.closefd.load() { let repr = source - .repr(vm) - .map(|s| s.as_wtf8().to_owned()) - .unwrap_or_else(|_| Wtf8Buf::from("")); + .repr(vm).map_or_else(|_| Wtf8Buf::from(""), |s| s.as_wtf8().to_owned()); if let Err(e) = crate::stdlib::_warnings::warn( vm.ctx.exceptions.resource_warning, format!("unclosed file {repr}"), diff --git a/crates/vm/src/stdlib/_sre.rs b/crates/vm/src/stdlib/_sre.rs index becf2453e7a..5e148c6bbc8 100644 --- a/crates/vm/src/stdlib/_sre.rs +++ b/crates/vm/src/stdlib/_sre.rs @@ -722,9 +722,7 @@ mod _sre { self.get_index(x, vm) .ok_or_else(|| vm.new_index_error("no such group")) .map(|index| { - self.get_slice(index, str_drive, vm) - .map(|x| x.to_pyobject(vm)) - .unwrap_or_else(|| vm.ctx.none()) + self.get_slice(index, str_drive, vm).map_or_else(|| vm.ctx.none(), |x| x.to_pyobject(vm)) }) }) .try_collect()?; @@ -760,9 +758,7 @@ mod _sre { with_sre_str!(self.pattern, &self.string, vm, |str_drive| { let v: Vec = (1..self.regs.len()) .map(|i| { - self.get_slice(i, str_drive, vm) - .map(|s| s.to_pyobject(vm)) - .unwrap_or_else(|| default.clone()) + self.get_slice(i, str_drive, vm).map_or_else(|| default.clone(), |s| s.to_pyobject(vm)) }) .collect(); Ok(PyTuple::new_ref(v, &vm.ctx)) @@ -783,9 +779,7 @@ mod _sre { for (key, index) in self.pattern.groupindex.clone() { let value = self .get_index(index, vm) - .and_then(|x| self.get_slice(x, str_drive, vm)) - .map(|x| x.to_pyobject(vm)) - .unwrap_or_else(|| default.clone()); + .and_then(|x| self.get_slice(x, str_drive, vm)).map_or_else(|| default.clone(), |x| x.to_pyobject(vm)); dict.set_item(&*key, value, vm)?; } Ok(dict) diff --git a/crates/vm/src/stdlib/_typing.rs b/crates/vm/src/stdlib/_typing.rs index 70554037d46..1a3d52a1f89 100644 --- a/crates/vm/src/stdlib/_typing.rs +++ b/crates/vm/src/stdlib/_typing.rs @@ -326,9 +326,7 @@ pub(crate) mod decl { vm.new_type_error(format!( "Expected a type param, got {}", param - .repr(vm) - .map(|s| s.to_string()) - .unwrap_or_else(|_| "?".to_owned()) + .repr(vm).map_or_else(|_| "?".to_owned(), |s| s.to_string()) )) })?; let is_no_default = dflt.is(no_default); diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index 1c83bac3ec6..a97ec0da228 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -1226,19 +1226,17 @@ mod builtins { // Use downcast_exact to keep ref to old object on error. let metaclass = kwargs - .pop_kwarg("metaclass") - .map(|metaclass| { - metaclass - .downcast_exact::(vm) - .map(|m| m.into_pyref()) - }) - .unwrap_or_else(|| { + .pop_kwarg("metaclass").map_or_else(|| { // if there are no bases, use type; else get the type of the first base Ok(if bases.is_empty() { vm.ctx.types.type_type.to_owned() } else { bases.first().unwrap().class().to_owned() }) + }, |metaclass| { + metaclass + .downcast_exact::(vm) + .map(|m| m.into_pyref()) }); let (metaclass, meta_name) = match metaclass { diff --git a/crates/vm/src/types/slot.rs b/crates/vm/src/types/slot.rs index bfcd7a8798d..7f3ed0b48ee 100644 --- a/crates/vm/src/types/slot.rs +++ b/crates/vm/src/types/slot.rs @@ -498,9 +498,7 @@ fn hash_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { .ok_or_else(|| vm.new_type_error("__hash__ method should return an integer"))?; let big_int = py_int.as_bigint(); let hash = big_int - .to_i64() - .map(fix_sentinel) - .unwrap_or_else(|| hash_bigint(big_int)); + .to_i64().map_or_else(|| hash_bigint(big_int), fix_sentinel); Ok(hash) } diff --git a/crates/vm/src/warn.rs b/crates/vm/src/warn.rs index 5dbf3fce780..cde821cfaa3 100644 --- a/crates/vm/src/warn.rs +++ b/crates/vm/src/warn.rs @@ -196,8 +196,7 @@ fn already_warned( let version_matches = version_obj.as_ref().is_some_and(|v| { v.try_int(vm) - .map(|i| i.as_u32_mask() as usize == current_version) - .unwrap_or(false) + .is_ok_and(|i| i.as_u32_mask() as usize == current_version) }); if version_matches { From 9dd74b61cff332cf45450fb3acaf8ada8e554a77 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 09:31:48 +0300 Subject: [PATCH 03/12] caego fmt --- crates/derive-impl/src/pyclass.rs | 3 +- crates/sre_engine/src/string.rs | 39 +++++++------------ crates/stdlib/src/_asyncio.rs | 3 +- crates/stdlib/src/_opcode.rs | 48 ++++++++++-------------- crates/stdlib/src/bisect.rs | 11 +++--- crates/stdlib/src/csv.rs | 5 +-- crates/stdlib/src/math.rs | 3 +- crates/stdlib/src/mmap.rs | 7 ++-- crates/stdlib/src/ssl.rs | 8 +--- crates/vm/src/builtins/float.rs | 5 ++- crates/vm/src/builtins/frame.rs | 5 +-- crates/vm/src/builtins/function.rs | 3 +- crates/vm/src/builtins/iter.rs | 5 ++- crates/vm/src/builtins/object.rs | 3 +- crates/vm/src/builtins/singletons.rs | 7 ++-- crates/vm/src/builtins/str.rs | 3 +- crates/vm/src/builtins/template.rs | 3 +- crates/vm/src/builtins/type.rs | 14 +++---- crates/vm/src/exceptions.rs | 6 ++- crates/vm/src/frame.rs | 13 +++---- crates/vm/src/getpath.rs | 6 ++- crates/vm/src/object/ext.rs | 12 ++---- crates/vm/src/stdlib/_ast/statement.rs | 25 +++++++++--- crates/vm/src/stdlib/_collections.rs | 6 ++- crates/vm/src/stdlib/_ctypes/array.rs | 6 +-- crates/vm/src/stdlib/_ctypes/function.rs | 3 +- crates/vm/src/stdlib/_functools.rs | 9 ++++- crates/vm/src/stdlib/_io.rs | 3 +- crates/vm/src/stdlib/_sre.rs | 9 +++-- crates/vm/src/stdlib/_typing.rs | 3 +- crates/vm/src/stdlib/builtins.rs | 10 +++-- crates/vm/src/types/slot.rs | 3 +- 32 files changed, 147 insertions(+), 142 deletions(-) diff --git a/crates/derive-impl/src/pyclass.rs b/crates/derive-impl/src/pyclass.rs index 6c6baec0aa0..625bbd0baf9 100644 --- a/crates/derive-impl/src/pyclass.rs +++ b/crates/derive-impl/src/pyclass.rs @@ -330,7 +330,8 @@ fn validate_base_field(item: &Item, base_path: &syn::Path) -> Result { diff --git a/crates/sre_engine/src/string.rs b/crates/sre_engine/src/string.rs index 67068158c98..83b80ad81f9 100644 --- a/crates/sre_engine/src/string.rs +++ b/crates/sre_engine/src/string.rs @@ -339,25 +339,20 @@ const fn is_py_ascii_whitespace(b: u8) -> bool { #[inline] pub(crate) fn is_word(ch: u32) -> bool { - ch == '_' as u32 - || u8::try_from(ch) - .is_ok_and(|x| x.is_ascii_alphanumeric()) + ch == '_' as u32 || u8::try_from(ch).is_ok_and(|x| x.is_ascii_alphanumeric()) } #[inline] pub(crate) fn is_space(ch: u32) -> bool { - u8::try_from(ch) - .is_ok_and(is_py_ascii_whitespace) + u8::try_from(ch).is_ok_and(is_py_ascii_whitespace) } #[inline] pub(crate) fn is_digit(ch: u32) -> bool { - u8::try_from(ch) - .is_ok_and(|x| x.is_ascii_digit()) + u8::try_from(ch).is_ok_and(|x| x.is_ascii_digit()) } #[inline] pub(crate) fn is_loc_alnum(ch: u32) -> bool { // FIXME: Ignore the locales - u8::try_from(ch) - .is_ok_and(|x| x.is_ascii_alphanumeric()) + u8::try_from(ch).is_ok_and(|x| x.is_ascii_alphanumeric()) } #[inline] pub(crate) fn is_loc_word(ch: u32) -> bool { @@ -370,8 +365,7 @@ pub(crate) const fn is_linebreak(ch: u32) -> bool { #[inline] #[must_use] pub fn lower_ascii(ch: u32) -> u32 { - u8::try_from(ch) - .map_or(ch, |x| x.to_ascii_lowercase() as u32) + u8::try_from(ch).map_or(ch, |x| x.to_ascii_lowercase() as u32) } #[inline] pub(crate) fn lower_locate(ch: u32) -> u32 { @@ -381,14 +375,12 @@ pub(crate) fn lower_locate(ch: u32) -> u32 { #[inline] pub(crate) fn upper_locate(ch: u32) -> u32 { // FIXME: Ignore the locales - u8::try_from(ch) - .map_or(ch, |x| x.to_ascii_uppercase() as u32) + u8::try_from(ch).map_or(ch, |x| x.to_ascii_uppercase() as u32) } #[inline] pub(crate) fn is_uni_digit(ch: u32) -> bool { // TODO: check with cpython - char::try_from(ch) - .is_ok_and(|x| x.is_ascii_digit()) + char::try_from(ch).is_ok_and(|x| x.is_ascii_digit()) } #[inline] pub(crate) fn is_uni_space(ch: u32) -> bool { @@ -437,12 +429,11 @@ pub(crate) const fn is_uni_linebreak(ch: u32) -> bool { #[inline] pub(crate) fn is_uni_alnum(ch: u32) -> bool { // TODO: check with cpython - char::try_from(ch) - .is_ok_and(|c| { - GeneralCategoryGroup::Letter - .union(GeneralCategoryGroup::Number) - .contains(GeneralCategory::for_char(c)) - }) + char::try_from(ch).is_ok_and(|c| { + GeneralCategoryGroup::Letter + .union(GeneralCategoryGroup::Number) + .contains(GeneralCategory::for_char(c)) + }) } #[inline] pub(crate) fn is_uni_word(ch: u32) -> bool { @@ -452,13 +443,11 @@ pub(crate) fn is_uni_word(ch: u32) -> bool { #[must_use] pub fn lower_unicode(ch: u32) -> u32 { // TODO: check with cpython - char::try_from(ch) - .map_or(ch, |x| x.to_lowercase().next().unwrap() as u32) + char::try_from(ch).map_or(ch, |x| x.to_lowercase().next().unwrap() as u32) } #[inline] #[must_use] pub fn upper_unicode(ch: u32) -> u32 { // TODO: check with cpython - char::try_from(ch) - .map_or(ch, |x| x.to_uppercase().next().unwrap() as u32) + char::try_from(ch).map_or(ch, |x| x.to_uppercase().next().unwrap() as u32) } diff --git a/crates/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index 6f1318e393a..29bbe39a0f5 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -899,7 +899,8 @@ pub(crate) mod _asyncio { vm.get_attribute_opt(future.to_owned(), vm.ctx.intern_str("_state")) { let s = state - .str(vm).map_or_else(|_| Wtf8Buf::from("unknown"), |s| s.as_wtf8().to_lowercase()); + .str(vm) + .map_or_else(|_| Wtf8Buf::from("unknown"), |s| s.as_wtf8().to_lowercase()); return Ok(s); } Ok(Wtf8Buf::from("state=unknown")) diff --git a/crates/stdlib/src/_opcode.rs b/crates/stdlib/src/_opcode.rs index dcf40aedaf9..80f422d69d2 100644 --- a/crates/stdlib/src/_opcode.rs +++ b/crates/stdlib/src/_opcode.rs @@ -34,24 +34,22 @@ mod _opcode { #[pyfunction] fn stack_effect(args: StackEffectArgs, vm: &VirtualMachine) -> PyResult { - let oparg = args - .oparg - .map_or(Ok(0), |v| { - if !v.fast_isinstance(vm.ctx.types.int_type) { - return Err(vm.new_type_error(format!( + let oparg = args.oparg.map_or(Ok(0), |v| { + if !v.fast_isinstance(vm.ctx.types.int_type) { + return Err(vm.new_type_error(format!( + "'{}' object cannot be interpreted as an integer", + v.class().name() + ))); + } + v.downcast_ref::() + .ok_or_else(|| { + vm.new_type_error(format!( "'{}' object cannot be interpreted as an integer", v.class().name() - ))); - } - v.downcast_ref::() - .ok_or_else(|| { - vm.new_type_error(format!( - "'{}' object cannot be interpreted as an integer", - v.class().name() - )) - })? - .try_to_primitive::(vm) - })?; + )) + })? + .try_to_primitive::(vm) + })?; let jump: Option = match args.jump { Some(v) => { @@ -103,38 +101,32 @@ mod _opcode { #[pyfunction] fn has_const(opcode: i32) -> bool { - try_from_i32(opcode) - .is_ok_and(|op| op.has_const()) + try_from_i32(opcode).is_ok_and(|op| op.has_const()) } #[pyfunction] fn has_name(opcode: i32) -> bool { - try_from_i32(opcode) - .is_ok_and(|op| op.has_name()) + try_from_i32(opcode).is_ok_and(|op| op.has_name()) } #[pyfunction] fn has_jump(opcode: i32) -> bool { - try_from_i32(opcode) - .is_ok_and(|op| op.has_jump()) + try_from_i32(opcode).is_ok_and(|op| op.has_jump()) } #[pyfunction] fn has_free(opcode: i32) -> bool { - try_from_i32(opcode) - .is_ok_and(|op| op.has_free()) + try_from_i32(opcode).is_ok_and(|op| op.has_free()) } #[pyfunction] fn has_local(opcode: i32) -> bool { - try_from_i32(opcode) - .is_ok_and(|op| op.has_local()) + try_from_i32(opcode).is_ok_and(|op| op.has_local()) } #[pyfunction] fn has_exc(opcode: i32) -> bool { - try_from_i32(opcode) - .is_ok_and(|op| op.is_block_push()) + try_from_i32(opcode).is_ok_and(|op| op.is_block_push()) } #[pyfunction] diff --git a/crates/stdlib/src/bisect.rs b/crates/stdlib/src/bisect.rs index ad2966c528d..7cb965cd5f9 100644 --- a/crates/stdlib/src/bisect.rs +++ b/crates/stdlib/src/bisect.rs @@ -44,12 +44,11 @@ mod _bisect { ) -> PyResult<(usize, usize)> { // We only deal with positives for lo, try_from can't fail. // Default is always a Some so we can safely unwrap. - let lo = handle_default(lo, vm)? - .map_or(Ok(0), |value| { - usize::try_from(value).map_err(|_| vm.new_value_error("lo must be non-negative")) - })?; - let hi = handle_default(hi, vm)? - .map_or(seq_len, |value| usize::try_from(value).unwrap_or(0)); + let lo = handle_default(lo, vm)?.map_or(Ok(0), |value| { + usize::try_from(value).map_err(|_| vm.new_value_error("lo must be non-negative")) + })?; + let hi = + handle_default(hi, vm)?.map_or(seq_len, |value| usize::try_from(value).unwrap_or(0)); Ok((lo, hi)) } diff --git a/crates/stdlib/src/csv.rs b/crates/stdlib/src/csv.rs index 7fac2983833..dab50799308 100644 --- a/crates/stdlib/src/csv.rs +++ b/crates/stdlib/src/csv.rs @@ -964,10 +964,7 @@ mod _csv { #[inline] fn trim_spaces(input: &[u8]) -> &[u8] { let trimmed_start = input.iter().position(|&x| x != b' ').unwrap_or(input.len()); - let trimmed_end = input - .iter() - .rposition(|&x| x != b' ') - .map_or(0, |i| i + 1); + let trimmed_end = input.iter().rposition(|&x| x != b' ').map_or(0, |i| i + 1); &input[trimmed_start..trimmed_end] } let input = if *skipinitialspace { diff --git a/crates/stdlib/src/math.rs b/crates/stdlib/src/math.rs index 3e3793107a7..12d2eeee8cf 100644 --- a/crates/stdlib/src/math.rs +++ b/crates/stdlib/src/math.rs @@ -559,8 +559,7 @@ mod math { let mut flt_result: f64 = if let Some(ref f) = obj_float { f.to_f64() } else if start_is_float && let OptionalArg::Present(s) = &start { - s.downcast_ref::() - .map_or(1.0, |f| f.to_f64()) + s.downcast_ref::().map_or(1.0, |f| f.to_f64()) } else { 1.0 }; diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index c589f668cfd..2d1fd512480 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -958,10 +958,9 @@ mod mmap { fn get_find_range(&self, options: FindOptions) -> (usize, usize) { let size = self.__len__(); let start = options - .start.map_or_else(|| self.pos(), |start| start.saturated_at(size)); - let end = options - .end - .map_or(size, |end| end.saturated_at(size)); + .start + .map_or_else(|| self.pos(), |start| start.saturated_at(size)); + let end = options.end.map_or(size, |end| end.saturated_at(size)); (start, end) } diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index 1322a831111..b523c29a65b 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -4775,11 +4775,7 @@ mod _ssl { // If name=False (default), only accept OID strings // If name=True, accept both names and OID strings - let entry = if txt - .chars() - .next() - .is_some_and(|c| c.is_ascii_digit()) - { + let entry = if txt.chars().next().is_some_and(|c| c.is_ascii_digit()) { // Looks like an OID string (starts with digit) oid::find_by_oid_string(txt) } else if name { @@ -4847,7 +4843,7 @@ mod _ssl { let tuple = vm.ctx.new_tuple(vec![ vm.ctx.new_str("SSL_CERT_FILE").into(), // openssl_cafile_env default_cafile.map_or_else(|| vm.ctx.none(), |s| vm.ctx.new_str(s).into()), // openssl_cafile - vm.ctx.new_str("SSL_CERT_DIR").into(), // openssl_capath_env + vm.ctx.new_str("SSL_CERT_DIR").into(), // openssl_capath_env default_capath.map_or_else(|| vm.ctx.none(), |s| vm.ctx.new_str(s).into()), // openssl_capath ]); Ok(tuple.into()) diff --git a/crates/vm/src/builtins/float.rs b/crates/vm/src/builtins/float.rs index 111fcd147c8..f36f9de79d4 100644 --- a/crates/vm/src/builtins/float.rs +++ b/crates/vm/src/builtins/float.rs @@ -247,7 +247,10 @@ fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult { ))); }; crate::literal::float::parse_bytes(b).ok_or_else(|| { - val.repr(vm).map_or_else(|e| e, |repr| vm.new_value_error(format!("could not convert string to float: {repr}"))) + val.repr(vm).map_or_else( + |e| e, + |repr| vm.new_value_error(format!("could not convert string to float: {repr}")), + ) }) } diff --git a/crates/vm/src/builtins/frame.rs b/crates/vm/src/builtins/frame.rs index 60519dcaad2..bfce1ba8291 100644 --- a/crates/vm/src/builtins/frame.rs +++ b/crates/vm/src/builtins/frame.rs @@ -496,10 +496,7 @@ impl Frame { } }; - let first_line = self - .code - .first_line_number - .map_or(1, |n| n.get() as i32); + let first_line = self.code.first_line_number.map_or(1, |n| n.get() as i32); if l_new_lineno < first_line { return Err(vm.new_value_error(format!( diff --git a/crates/vm/src/builtins/function.rs b/crates/vm/src/builtins/function.rs index 0a7fa5a26b6..9b34aa8bff3 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -191,7 +191,8 @@ impl PyFunction { let doc = if code.code.flags.contains(bytecode::CodeFlags::HAS_DOCSTRING) { code.code .constants - .first().map_or_else(|| vm.ctx.none(), |c| c.as_object().to_owned()) + .first() + .map_or_else(|| vm.ctx.none(), |c| c.as_object().to_owned()) } else { vm.ctx.none() }; diff --git a/crates/vm/src/builtins/iter.rs b/crates/vm/src/builtins/iter.rs index 34f6dff8459..322eef15cd1 100644 --- a/crates/vm/src/builtins/iter.rs +++ b/crates/vm/src/builtins/iter.rs @@ -188,7 +188,10 @@ impl PySequenceIterator { let internal = self.internal.lock(); if let IterStatus::Active(obj) = &internal.status { let seq = obj.sequence_unchecked(); - seq.length(vm).map_or_else(|_| vm.ctx.not_implemented(), |x| PyInt::from(x).into_pyobject(vm)) + seq.length(vm).map_or_else( + |_| vm.ctx.not_implemented(), + |x| PyInt::from(x).into_pyobject(vm), + ) } else { PyInt::from(0).into_pyobject(vm) } diff --git a/crates/vm/src/builtins/object.rs b/crates/vm/src/builtins/object.rs index 31ee89e36ac..7ee22e5cbda 100644 --- a/crates/vm/src/builtins/object.rs +++ b/crates/vm/src/builtins/object.rs @@ -756,7 +756,8 @@ fn reduce_newobj(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Use copyreg.__newobj_ex__ let newobj = copyreg.get_attr("__newobj_ex__", vm)?; let args_tuple: PyObjectRef = args.into(); - let kwargs_dict: PyObjectRef = kwargs.map_or_else(|| vm.ctx.new_dict().into(), |k| k.into()); + let kwargs_dict: PyObjectRef = + kwargs.map_or_else(|| vm.ctx.new_dict().into(), |k| k.into()); let newargs = vm .ctx diff --git a/crates/vm/src/builtins/singletons.rs b/crates/vm/src/builtins/singletons.rs index 7a042b221d4..2928c523b1b 100644 --- a/crates/vm/src/builtins/singletons.rs +++ b/crates/vm/src/builtins/singletons.rs @@ -82,9 +82,10 @@ impl Comparable for PyNone { op: PyComparisonOp, _vm: &VirtualMachine, ) -> PyResult { - Ok(op - .identical_optimization(zelf, other) - .map_or(PyComparisonValue::NotImplemented, PyComparisonValue::Implemented)) + Ok(op.identical_optimization(zelf, other).map_or( + PyComparisonValue::NotImplemented, + PyComparisonValue::Implemented, + )) } } diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index 9ffe9663536..8a36d9350ba 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -549,7 +549,8 @@ impl PyStr { } pub fn to_string_lossy(&self) -> Cow<'_, str> { - self.to_str().map_or_else(|| self.as_wtf8().to_string_lossy(), Cow::Borrowed) + self.to_str() + .map_or_else(|| self.as_wtf8().to_string_lossy(), Cow::Borrowed) } pub const fn kind(&self) -> StrKind { diff --git a/crates/vm/src/builtins/template.rs b/crates/vm/src/builtins/template.rs index ac8b190f6b0..92734e13424 100644 --- a/crates/vm/src/builtins/template.rs +++ b/crates/vm/src/builtins/template.rs @@ -115,7 +115,8 @@ impl PyTemplate { .iter() .map(|interp| { interp - .downcast_ref::().map_or_else(|| interp.clone(), |i| i.value.clone()) + .downcast_ref::() + .map_or_else(|| interp.clone(), |i| i.value.clone()) }) .collect(); vm.ctx.new_tuple(values) diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index 94574dc375b..a0d1cf8802b 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -860,19 +860,17 @@ impl PyType { if slots.flags.contains(PyTypeFlags::DISALLOW_INSTANTIATION) { slots.new.store(None) } else if slots.new.load().is_none() { - slots.new.store( - base.as_ref() - .and_then(|base| base.slots.new.load()), - ) + slots + .new + .store(base.as_ref().and_then(|base| base.slots.new.load())) } } fn set_alloc(slots: &PyTypeSlots, base: &Option) { if slots.alloc.load().is_none() { - slots.alloc.store( - base.as_ref() - .and_then(|base| base.slots.alloc.load()), - ); + slots + .alloc + .store(base.as_ref().and_then(|base| base.slots.alloc.load())); } } diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index ad0283f1fb9..4ff1be71ff2 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -2033,11 +2033,13 @@ pub(super) mod types { let errno_str = errno_field .as_ref() .map(|e| e.str(vm)) - .transpose()?.map_or_else(|| "None".to_owned(), |s| s.to_string()); + .transpose()? + .map_or_else(|| "None".to_owned(), |s| s.to_string()); let msg = strerror .as_ref() .map(|s| s.str(vm)) - .transpose()?.map_or_else(|| "None".to_owned(), |s| s.to_string()); + .transpose()? + .map_or_else(|| "None".to_owned(), |s| s.to_string()); if let Some(ref f2) = filename2 { return Ok(vm.ctx.new_str(format!( "[Errno {}] {}: {} -> {}", diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index f93dad2b609..ba007622187 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -1503,7 +1503,8 @@ impl ExecutingFrame<'_> { let exc_type: PyObjectRef = exc.class().to_owned().into(); let exc_value: PyObjectRef = exc.clone().into(); let exc_tb: PyObjectRef = exc - .__traceback__().map_or_else(|| vm.ctx.none(), |tb| -> PyObjectRef { tb.into() }); + .__traceback__() + .map_or_else(|| vm.ctx.none(), |tb| -> PyObjectRef { tb.into() }); let tuple = vm.ctx.new_tuple(vec![exc_type, exc_value, exc_tb]).into(); vm.trace_event(crate::protocol::TraceEvent::Exception, Some(tuple))?; } @@ -3423,7 +3424,8 @@ impl ExecutingFrame<'_> { // Stack: [exc] -> [prev_exc, exc] let exc = self.pop_value(); let prev_exc = vm - .current_exception().map_or_else(|| vm.ctx.none(), |e| e.into()); + .current_exception() + .map_or_else(|| vm.ctx.none(), |e| e.into()); // Set exc as the current exception if let Some(exc_ref) = exc.downcast_ref::() { @@ -6088,9 +6090,7 @@ impl ExecutingFrame<'_> { let line_op = data.as_ref().map_or(0, |d| d.line_opcodes[idx]); if line_op == u8::from(Instruction::InstrumentedInstruction) { // LINE wraps INSTRUCTION: resolve the INSTRUCTION side-table too - let inst_op = data - .as_ref() - .map_or(0, |d| d.per_instruction_opcodes[idx]); + let inst_op = data.as_ref().map_or(0, |d| d.per_instruction_opcodes[idx]); (inst_op, true) } else { (line_op, false) @@ -6138,8 +6138,7 @@ impl ExecutingFrame<'_> { // Get original opcode from side-table let original_op_byte = { let data = self.code.monitoring_data.lock(); - data.as_ref() - .map_or(0, |d| d.per_instruction_opcodes[idx]) + data.as_ref().map_or(0, |d| d.per_instruction_opcodes[idx]) }; debug_assert!( original_op_byte != 0, diff --git a/crates/vm/src/getpath.rs b/crates/vm/src/getpath.rs index 2dc2cda0e57..66c39613bfa 100644 --- a/crates/vm/src/getpath.rs +++ b/crates/vm/src/getpath.rs @@ -145,8 +145,10 @@ pub fn init_path_config(settings: &Settings) -> Paths { // Step 5: Set prefix and base_prefix if venv_prefix.is_some() { // In venv: prefix = venv directory, base_prefix = original Python's prefix - paths.prefix = venv_prefix - .as_ref().map_or_else(|| calculated_prefix.clone(), |p| p.to_string_lossy().into_owned()); + paths.prefix = venv_prefix.as_ref().map_or_else( + || calculated_prefix.clone(), + |p| p.to_string_lossy().into_owned(), + ); paths.base_prefix = calculated_prefix; } else { // Not in venv: prefix == base_prefix diff --git a/crates/vm/src/object/ext.rs b/crates/vm/src/object/ext.rs index 91c6e9756ed..f3170db98fa 100644 --- a/crates/vm/src/object/ext.rs +++ b/crates/vm/src/object/ext.rs @@ -346,8 +346,7 @@ impl PyAtomicRef { impl From>> for PyAtomicRef> { fn from(opt_ref: Option>) -> Self { - let val = opt_ref - .map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); + let val = opt_ref.map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); Self { inner: Radium::new(val), _phantom: Default::default(), @@ -377,8 +376,7 @@ impl PyAtomicRef> { /// until no more reference can be used via PyAtomicRef::deref() #[must_use] pub unsafe fn swap(&self, opt_ref: Option>) -> Option> { - let val = opt_ref - .map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); + let val = opt_ref.map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); unsafe { old.cast::>().as_ref().map(|x| PyRef::from_raw(x)) } } @@ -438,8 +436,7 @@ impl PyAtomicRef { impl From> for PyAtomicRef> { fn from(obj: Option) -> Self { - let val = obj - .map_or(null_mut(), |x| x.into_raw().as_ptr().cast()); + let val = obj.map_or(null_mut(), |x| x.into_raw().as_ptr().cast()); Self { inner: Radium::new(val), _phantom: Default::default(), @@ -469,8 +466,7 @@ impl PyAtomicRef> { /// until no more reference can be used via PyAtomicRef::deref() #[must_use] pub unsafe fn swap(&self, obj: Option) -> Option { - let val = obj - .map_or(null_mut(), |x| x.into_raw().as_ptr().cast()); + let val = obj.map_or(null_mut(), |x| x.into_raw().as_ptr().cast()); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); unsafe { NonNull::new(old.cast::()).map(|x| PyObjectRef::from_raw(x)) } } diff --git a/crates/vm/src/stdlib/_ast/statement.rs b/crates/vm/src/stdlib/_ast/statement.rs index 4eca89f7454..32ee5273dcb 100644 --- a/crates/vm/src/stdlib/_ast/statement.rs +++ b/crates/vm/src/stdlib/_ast/statement.rs @@ -191,7 +191,10 @@ impl Node for ast::StmtFunctionDef { dict.set_item("type_comment", vm.ctx.none(), vm).unwrap(); dict.set_item( "type_params", - type_params.map_or_else(|| vm.ctx.new_list(vec![]).into(), |tp| tp.ast_to_object(vm, source_file)), + type_params.map_or_else( + || vm.ctx.new_list(vec![]).into(), + |tp| tp.ast_to_object(vm, source_file), + ), vm, ) .unwrap(); @@ -271,13 +274,19 @@ impl Node for ast::StmtClassDef { .unwrap(); dict.set_item( "bases", - bases.map_or_else(|| _vm.ctx.new_list(vec![]).into(), |b| b.ast_to_object(_vm, source_file)), + bases.map_or_else( + || _vm.ctx.new_list(vec![]).into(), + |b| b.ast_to_object(_vm, source_file), + ), _vm, ) .unwrap(); dict.set_item( "keywords", - keywords.map_or_else(|| _vm.ctx.new_list(vec![]).into(), |k| k.ast_to_object(_vm, source_file)), + keywords.map_or_else( + || _vm.ctx.new_list(vec![]).into(), + |k| k.ast_to_object(_vm, source_file), + ), _vm, ) .unwrap(); @@ -291,7 +300,10 @@ impl Node for ast::StmtClassDef { .unwrap(); dict.set_item( "type_params", - type_params.map_or_else(|| _vm.ctx.new_list(vec![]).into(), |tp| tp.ast_to_object(_vm, source_file)), + type_params.map_or_else( + || _vm.ctx.new_list(vec![]).into(), + |tp| tp.ast_to_object(_vm, source_file), + ), _vm, ) .unwrap(); @@ -472,7 +484,10 @@ impl Node for ast::StmtTypeAlias { .unwrap(); dict.set_item( "type_params", - type_params.map_or_else(|| _vm.ctx.new_list(Vec::new()).into(), |tp| tp.ast_to_object(_vm, source_file)), + type_params.map_or_else( + || _vm.ctx.new_list(Vec::new()).into(), + |tp| tp.ast_to_object(_vm, source_file), + ), _vm, ) .unwrap(); diff --git a/crates/vm/src/stdlib/_collections.rs b/crates/vm/src/stdlib/_collections.rs index 0a6c007d4bc..03438f28c08 100644 --- a/crates/vm/src/stdlib/_collections.rs +++ b/crates/vm/src/stdlib/_collections.rs @@ -180,7 +180,8 @@ mod _collections { } else { Err(vm.new_value_error( needle - .repr(vm).map_or_else(|_| String::new(), |repr| format!("{repr} is not in deque")), + .repr(vm) + .map_or_else(|_| String::new(), |repr| format!("{repr} is not in deque")), )) } } @@ -566,7 +567,8 @@ mod _collections { let class = zelf.class(); let class_name = class.name(); let closing_part = zelf - .maxlen.map_or_else(|| "]".to_owned(), |maxlen| format!("], maxlen={maxlen}")); + .maxlen + .map_or_else(|| "]".to_owned(), |maxlen| format!("], maxlen={maxlen}")); if zelf.__len__() == 0 { return Ok(vm.ctx.new_str(format!("{class_name}([{closing_part})"))); diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index 7be413a74bc..657f0a2146f 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -769,11 +769,7 @@ impl PyCArray { } Some("u") => { if let Some(s) = value.downcast_ref::() { - let code = s - .as_wtf8() - .code_points() - .next() - .map_or(0, |c| c.to_u32()); + let code = s.as_wtf8().code_points().next().map_or(0, |c| c.to_u32()); if offset + WCHAR_SIZE <= buffer.len() { wchar_to_bytes(code, &mut buffer[offset..]); } diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index a77c8e3d108..00bbe2ad523 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -2181,7 +2181,8 @@ unsafe extern "C" fn thunk_callback( if let Err(exc) = &py_result { let repr = userdata .callable - .repr(vm).map_or_else(|_| "".to_string(), |s| s.to_string()); + .repr(vm) + .map_or_else(|_| "".to_string(), |s| s.to_string()); let msg = format!( "Exception ignored while calling ctypes callback function {}", repr diff --git a/crates/vm/src/stdlib/_functools.rs b/crates/vm/src/stdlib/_functools.rs index 28d1bb1f9ae..b36fbbcddbb 100644 --- a/crates/vm/src/stdlib/_functools.rs +++ b/crates/vm/src/stdlib/_functools.rs @@ -163,7 +163,8 @@ mod _functools { #[pygetset] fn __dict__(zelf: &Py, vm: &VirtualMachine) -> PyDictRef { zelf.as_object() - .instance_dict().map_or_else(|| vm.ctx.new_dict(), |d| d.get_or_insert(vm)) + .instance_dict() + .map_or_else(|| vm.ctx.new_dict(), |d| d.get_or_insert(vm)) } #[pygetset(setter)] @@ -489,7 +490,11 @@ mod _functools { let qualname = zelf.class().__qualname__(vm); let qualname_wtf8 = qualname - .downcast_ref::().map_or_else(|| Wtf8Buf::from(zelf.class().name().to_owned()), |s| s.as_wtf8().to_owned()); + .downcast_ref::() + .map_or_else( + || Wtf8Buf::from(zelf.class().name().to_owned()), + |s| s.as_wtf8().to_owned(), + ); let module = zelf.class().__module__(vm); let mut result = Wtf8Buf::new(); diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index b5c4bc3ef31..30401caf19e 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -5967,7 +5967,8 @@ mod fileio { fn dealloc_warn(zelf: &Py, source: PyObjectRef, vm: &VirtualMachine) { if zelf.fd.load() >= 0 && zelf.closefd.load() { let repr = source - .repr(vm).map_or_else(|_| Wtf8Buf::from(""), |s| s.as_wtf8().to_owned()); + .repr(vm) + .map_or_else(|_| Wtf8Buf::from(""), |s| s.as_wtf8().to_owned()); if let Err(e) = crate::stdlib::_warnings::warn( vm.ctx.exceptions.resource_warning, format!("unclosed file {repr}"), diff --git a/crates/vm/src/stdlib/_sre.rs b/crates/vm/src/stdlib/_sre.rs index 5e148c6bbc8..1f62b48b137 100644 --- a/crates/vm/src/stdlib/_sre.rs +++ b/crates/vm/src/stdlib/_sre.rs @@ -722,7 +722,8 @@ mod _sre { self.get_index(x, vm) .ok_or_else(|| vm.new_index_error("no such group")) .map(|index| { - self.get_slice(index, str_drive, vm).map_or_else(|| vm.ctx.none(), |x| x.to_pyobject(vm)) + self.get_slice(index, str_drive, vm) + .map_or_else(|| vm.ctx.none(), |x| x.to_pyobject(vm)) }) }) .try_collect()?; @@ -758,7 +759,8 @@ mod _sre { with_sre_str!(self.pattern, &self.string, vm, |str_drive| { let v: Vec = (1..self.regs.len()) .map(|i| { - self.get_slice(i, str_drive, vm).map_or_else(|| default.clone(), |s| s.to_pyobject(vm)) + self.get_slice(i, str_drive, vm) + .map_or_else(|| default.clone(), |s| s.to_pyobject(vm)) }) .collect(); Ok(PyTuple::new_ref(v, &vm.ctx)) @@ -779,7 +781,8 @@ mod _sre { for (key, index) in self.pattern.groupindex.clone() { let value = self .get_index(index, vm) - .and_then(|x| self.get_slice(x, str_drive, vm)).map_or_else(|| default.clone(), |x| x.to_pyobject(vm)); + .and_then(|x| self.get_slice(x, str_drive, vm)) + .map_or_else(|| default.clone(), |x| x.to_pyobject(vm)); dict.set_item(&*key, value, vm)?; } Ok(dict) diff --git a/crates/vm/src/stdlib/_typing.rs b/crates/vm/src/stdlib/_typing.rs index 1a3d52a1f89..3eff99f6c45 100644 --- a/crates/vm/src/stdlib/_typing.rs +++ b/crates/vm/src/stdlib/_typing.rs @@ -326,7 +326,8 @@ pub(crate) mod decl { vm.new_type_error(format!( "Expected a type param, got {}", param - .repr(vm).map_or_else(|_| "?".to_owned(), |s| s.to_string()) + .repr(vm) + .map_or_else(|_| "?".to_owned(), |s| s.to_string()) )) })?; let is_no_default = dflt.is(no_default); diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index a97ec0da228..bf047ade300 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -1225,19 +1225,21 @@ mod builtins { }; // Use downcast_exact to keep ref to old object on error. - let metaclass = kwargs - .pop_kwarg("metaclass").map_or_else(|| { + let metaclass = kwargs.pop_kwarg("metaclass").map_or_else( + || { // if there are no bases, use type; else get the type of the first base Ok(if bases.is_empty() { vm.ctx.types.type_type.to_owned() } else { bases.first().unwrap().class().to_owned() }) - }, |metaclass| { + }, + |metaclass| { metaclass .downcast_exact::(vm) .map(|m| m.into_pyref()) - }); + }, + ); let (metaclass, meta_name) = match metaclass { Ok(mut metaclass) => { diff --git a/crates/vm/src/types/slot.rs b/crates/vm/src/types/slot.rs index 7f3ed0b48ee..3d64d121b6a 100644 --- a/crates/vm/src/types/slot.rs +++ b/crates/vm/src/types/slot.rs @@ -498,7 +498,8 @@ fn hash_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { .ok_or_else(|| vm.new_type_error("__hash__ method should return an integer"))?; let big_int = py_int.as_bigint(); let hash = big_int - .to_i64().map_or_else(|| hash_bigint(big_int), fix_sentinel); + .to_i64() + .map_or_else(|| hash_bigint(big_int), fix_sentinel); Ok(hash) } From 97dfbce7c8b308128518ed96c567850fffd6b552 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 09:39:09 +0300 Subject: [PATCH 04/12] Ignore bad change --- crates/codegen/src/compile.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 3f53fe10e15..e7a5374132b 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -5412,6 +5412,7 @@ impl Compiler { self.prepare_decorators(decorator_list)?; let is_generic = type_params.is_some(); + #[expect(clippy::map_unwrap_or, reason = "Chaning this will not compile")] let firstlineno = decorator_list .first() .map(|decorator| { From a57fa6c3cb45ff34987e9727d651b49c27228349 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 09:43:21 +0300 Subject: [PATCH 05/12] clippy fix --- crates/codegen/src/compile.rs | 6 ++---- crates/codegen/src/ir.rs | 22 +++++++--------------- crates/codegen/src/symboltable.rs | 5 ++--- 3 files changed, 11 insertions(+), 22 deletions(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index e7a5374132b..faf91e9f404 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -6885,8 +6885,7 @@ impl Compiler { // star wildcard check star_wildcard = pattern .as_match_star() - .map(|m| m.name.is_none()) - .unwrap_or(false); + .is_some_and(|m| m.name.is_none()); only_wildcard &= star_wildcard; star = Some(i); continue; @@ -6894,8 +6893,7 @@ impl Compiler { // wildcard check only_wildcard &= pattern .as_match_as() - .map(|m| m.name.is_none()) - .unwrap_or(false); + .is_some_and(|m| m.name.is_none()); } // Keep the subject on top during the sequence and length checks. diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index 17764a99206..db38799a519 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -8907,8 +8907,7 @@ impl CodeInfo { if let DeoptKind::ReturnIter { tail_start_idx } = deopt_kind { let tail_instr_idx = real_instrs .get(tail_start_idx) - .map(|(instr_idx, _)| *instr_idx) - .unwrap_or(block_instr_len); + .map_or(block_instr_len, |(instr_idx, _)| *instr_idx); if !tail_returns_without_store( &self.blocks, &is_pre_handler, @@ -9471,9 +9470,7 @@ impl CodeInfo { block.preserve_lasti, block.disable_load_fast_borrow, block - .start_depth - .map(|depth| depth.to_string()) - .unwrap_or_else(|| String::from("None")), + .start_depth.map_or_else(|| String::from("None"), |depth| depth.to_string()), ); for info in &block.instructions { let lineno = instruction_lineno(info); @@ -10169,8 +10166,7 @@ fn mark_cold(blocks: &mut [Block]) { let has_fallthrough = block .instructions .last() - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true); + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()); if has_fallthrough && block.next != BlockIdx::NULL { let next_idx = block.next.idx(); if !blocks[next_idx].except_handler && !warm[next_idx] { @@ -10212,8 +10208,7 @@ fn push_cold_blocks_to_end(blocks: &mut Vec) { && block .instructions .last() - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true) + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) }) .map(|(idx, block)| (idx, block.next)) .collect(); @@ -13343,8 +13338,7 @@ fn duplicate_end_returns(blocks: &mut Vec, metadata: &CodeUnitMetadata) { if current != last_block && !block.cold { let last_ins = block.instructions.last(); let has_fallthrough = last_ins - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true); + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()); // Don't duplicate if block already ends with the same return pattern let already_has_return = block.instructions.len() >= 2 && { let n = block.instructions.len(); @@ -13518,8 +13512,7 @@ fn duplicate_named_except_cleanup_returns(blocks: &mut Vec, metadata: &Co let fallthroughs_into_target = blocks[layout_pred.idx()] .instructions .last() - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true); + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()); if !fallthroughs_into_target || predecessors[target.idx()] < 2 { continue; } @@ -13765,8 +13758,7 @@ pub(crate) fn label_exception_targets(blocks: &mut [Block]) { let has_fallthrough = blocks[bi] .instructions .last() - .map(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) - .unwrap_or(true); // Empty block falls through + .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()); // Empty block falls through if has_fallthrough { visited[next.idx()] = true; block_stacks[next.idx()] = Some(stack); diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index 448e22d256e..1c79e545578 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -1088,14 +1088,13 @@ impl SymbolTableBuilder { let is_nested = self .tables .last() - .map(|table| { + .is_some_and(|table| { table.is_nested || matches!( table.typ, CompilerScope::Function | CompilerScope::AsyncFunction ) - }) - .unwrap_or(false); + }); // Inherit mangled_names from parent for non-class scopes let inherited_mangled_names = self .tables From 821a6bd56a4a68b543d495ee1a540ec091e30cf8 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 09:43:50 +0300 Subject: [PATCH 06/12] cargo fmt --- crates/codegen/src/compile.rs | 8 ++------ crates/codegen/src/ir.rs | 10 +++++----- crates/codegen/src/symboltable.rs | 17 +++++++---------- 3 files changed, 14 insertions(+), 21 deletions(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index faf91e9f404..4ab52e52f0d 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -6883,17 +6883,13 @@ impl Compiler { return Err(self.error(CodegenErrorType::MultipleStarArgs)); } // star wildcard check - star_wildcard = pattern - .as_match_star() - .is_some_and(|m| m.name.is_none()); + star_wildcard = pattern.as_match_star().is_some_and(|m| m.name.is_none()); only_wildcard &= star_wildcard; star = Some(i); continue; } // wildcard check - only_wildcard &= pattern - .as_match_as() - .is_some_and(|m| m.name.is_none()); + only_wildcard &= pattern.as_match_as().is_some_and(|m| m.name.is_none()); } // Keep the subject on top during the sequence and length checks. diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index db38799a519..8d77b4688b9 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -9470,7 +9470,8 @@ impl CodeInfo { block.preserve_lasti, block.disable_load_fast_borrow, block - .start_depth.map_or_else(|| String::from("None"), |depth| depth.to_string()), + .start_depth + .map_or_else(|| String::from("None"), |depth| depth.to_string()), ); for info in &block.instructions { let lineno = instruction_lineno(info); @@ -10205,10 +10206,9 @@ fn push_cold_blocks_to_end(blocks: &mut Vec) { block.cold && block.next != BlockIdx::NULL && !blocks[block.next.idx()].cold - && block - .instructions - .last() - .is_none_or(|ins| !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump()) + && block.instructions.last().is_none_or(|ins| { + !ins.instr.is_scope_exit() && !ins.instr.is_unconditional_jump() + }) }) .map(|(idx, block)| (idx, block.next)) .collect(); diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index 1c79e545578..31da7c164e8 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -1085,16 +1085,13 @@ impl SymbolTableBuilder { } fn enter_scope(&mut self, name: &str, typ: CompilerScope, line_number: u32) { - let is_nested = self - .tables - .last() - .is_some_and(|table| { - table.is_nested - || matches!( - table.typ, - CompilerScope::Function | CompilerScope::AsyncFunction - ) - }); + let is_nested = self.tables.last().is_some_and(|table| { + table.is_nested + || matches!( + table.typ, + CompilerScope::Function | CompilerScope::AsyncFunction + ) + }); // Inherit mangled_names from parent for non-class scopes let inherited_mangled_names = self .tables From fef6a3596ccb2b5eb36c921c407b921bf846ab37 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 09:45:24 +0300 Subject: [PATCH 07/12] fix typo --- crates/codegen/src/compile.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 4ab52e52f0d..61473687366 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -5412,7 +5412,7 @@ impl Compiler { self.prepare_decorators(decorator_list)?; let is_generic = type_params.is_some(); - #[expect(clippy::map_unwrap_or, reason = "Chaning this will not compile")] + #[expect(clippy::map_unwrap_or, reason = "Changing this will not compile")] let firstlineno = decorator_list .first() .map(|decorator| { From 90e352c9741ce60cfee294f981b8957f2dfe65f8 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 09:59:37 +0300 Subject: [PATCH 08/12] fix jit --- crates/jit/tests/common.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/jit/tests/common.rs b/crates/jit/tests/common.rs index 6066ebc4307..ca761477f3c 100644 --- a/crates/jit/tests/common.rs +++ b/crates/jit/tests/common.rs @@ -116,10 +116,12 @@ fn extract_annotations_from_annotate_code(code: &CodeObject) -> HashMap value - .as_str() - .map(|s| s.to_owned()) - .unwrap_or_else(|_| value.to_string_lossy().into_owned()), + Some(ConstantData::Str { value }) => { + value.as_str().map_or_else( + |_| value.to_string_lossy().into_owned(), + |s| s.to_owned(), + ) + } Some(other) => panic!( "Unsupported annotation const for '{:?}' at idx {}: {:?}", param_name, val_idx, other From 3a72bee7f544f4c529785691efd37e46c01d57ec Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 10:31:09 +0300 Subject: [PATCH 09/12] fix windows clippy --- crates/vm/src/exceptions.rs | 4 ++-- crates/vm/src/stdlib/_codecs.rs | 14 ++++++++------ crates/vm/src/stdlib/_io.rs | 7 +++---- crates/vm/src/stdlib/posix.rs | 3 +-- crates/vm/src/windows.rs | 4 +--- 5 files changed, 15 insertions(+), 17 deletions(-) diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index 4ff1be71ff2..538b60c6d49 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -2002,8 +2002,8 @@ pub(super) mod types { .as_ref() .map(|s| s.str(vm)) .transpose()? - .map(|s| s.to_string()) - .unwrap_or_else(|| "None".to_owned()); + .map_or_else(|| "None".to_owned(), |s| s.to_string()); + if let Some(ref f2) = filename2 { return Ok(vm.ctx.new_str(format!( "[WinError {}] {}: {} -> {}", diff --git a/crates/vm/src/stdlib/_codecs.rs b/crates/vm/src/stdlib/_codecs.rs index e1708602d07..adab1915095 100644 --- a/crates/vm/src/stdlib/_codecs.rs +++ b/crates/vm/src/stdlib/_codecs.rs @@ -391,7 +391,7 @@ mod _codecs_windows { CP_ACP, WC_NO_BEST_FIT_CHARS, WideCharToMultiByte, }; - let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let s = match args.s.to_str() { Some(s) => s, None => { @@ -481,7 +481,7 @@ mod _codecs_windows { CP_ACP, MB_ERR_INVALID_CHARS, MultiByteToWideChar, }; - let _errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + let _errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let data = args.data.borrow_buf(); let len = data.len(); @@ -577,7 +577,7 @@ mod _codecs_windows { CP_OEMCP, WC_NO_BEST_FIT_CHARS, WideCharToMultiByte, }; - let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let s = match args.s.to_str() { Some(s) => s, None => { @@ -667,7 +667,7 @@ mod _codecs_windows { CP_OEMCP, MB_ERR_INVALID_CHARS, MultiByteToWideChar, }; - let _errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + let _errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let data = args.data.borrow_buf(); let len = data.len(); @@ -1053,7 +1053,8 @@ mod _codecs_windows { if args.code_page < 0 { return Err(vm.new_value_error("invalid code page number")); } - let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + + let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let code_page = args.code_page as u32; let char_len = args.s.char_len(); @@ -1366,7 +1367,8 @@ mod _codecs_windows { if args.code_page < 0 { return Err(vm.new_value_error("invalid code page number")); } - let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict"); + + let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let code_page = args.code_page as u32; let data = args.data.borrow_buf(); let is_final = args.r#final; diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index 30401caf19e..640bd80fd11 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -6229,8 +6229,7 @@ mod winconsoleio { let mode_str: &str = args .mode .as_ref() - .map(|s: &PyUtf8StrRef| s.as_str()) - .unwrap_or("r"); + .map_or("r", |s: &PyUtf8StrRef| s.as_str()); let mut rwa = false; let mut readable = false; @@ -6520,8 +6519,8 @@ mod winconsoleio { if zelf.fd.load() >= 0 && zelf.closefd.load() { let repr = source .repr(vm) - .map(|s| s.as_wtf8().to_owned()) - .unwrap_or_else(|_| Wtf8Buf::from("")); + .map_or_else(|_| Wtf8Buf::from(""), |s| s.as_wtf8().to_owned()); + if let Err(e) = crate::stdlib::_warnings::warn( vm.ctx.exceptions.resource_warning, format!("unclosed file {repr}"), diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index 95abf264fbf..604a4f945a9 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -2590,8 +2590,7 @@ pub mod module { let headers = _extract_vec_bytes(args.headers, vm)?; let count = headers .as_ref() - .map(|v| v.iter().map(|s| s.len()).sum()) - .unwrap_or(0) as i64 + .map_or(0, |v| v.iter().map(|s| s.len()).sum() as i64) + args.count; let headers = headers diff --git a/crates/vm/src/windows.rs b/crates/vm/src/windows.rs index 30686412612..bb65ce29aa5 100644 --- a/crates/vm/src/windows.rs +++ b/crates/vm/src/windows.rs @@ -153,9 +153,7 @@ fn attribute_data_to_stat( let mut st_mode = attributes_to_mode(info.dwFileAttributes); let st_size = ((info.nFileSizeHigh as u64) << 32) | (info.nFileSizeLow as u64); - let st_dev = id_info - .map(|id| id.VolumeSerialNumber as u32) - .unwrap_or(info.dwVolumeSerialNumber); + let st_dev = id_info.map_or(info.dwVolumeSerialNumber, |id| id.VolumeSerialNumber as u32); let st_nlink = info.nNumberOfLinks as i32; // Convert FILETIME/LARGE_INTEGER to (time_t, nsec) From 61f822508a8782eaa2ce78bd6a81b2c247c8cd27 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 10:34:55 +0300 Subject: [PATCH 10/12] fix --- crates/vm/src/stdlib/posix.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index 604a4f945a9..4d4a53de90e 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -2590,7 +2590,7 @@ pub mod module { let headers = _extract_vec_bytes(args.headers, vm)?; let count = headers .as_ref() - .map_or(0, |v| v.iter().map(|s| s.len()).sum() as i64) + .map_or(0, |v| v.iter().map(|s| s.len()).sum::()) + args.count; let headers = headers From 741204ce8598ab7affc9c0e75864bf0ab80cede4 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 10:48:13 +0300 Subject: [PATCH 11/12] fix types --- crates/vm/src/stdlib/posix.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index 4d4a53de90e..1d114071aad 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -2590,7 +2590,7 @@ pub mod module { let headers = _extract_vec_bytes(args.headers, vm)?; let count = headers .as_ref() - .map_or(0, |v| v.iter().map(|s| s.len()).sum::()) + .map_or(0, |v| v.iter().map(|s| s.len()).sum()) as i64 + args.count; let headers = headers From 4611245fd0d82061e9ddcb265123856ac937a774 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Mon, 11 May 2026 10:57:53 +0300 Subject: [PATCH 12/12] fix windows clippy --- crates/stdlib/src/overlapped.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/stdlib/src/overlapped.rs b/crates/stdlib/src/overlapped.rs index 2230991b643..86238ed9ea4 100644 --- a/crates/stdlib/src/overlapped.rs +++ b/crates/stdlib/src/overlapped.rs @@ -1949,10 +1949,7 @@ mod _overlapped { let name_wide: Option> = name.map(|n| n.encode_utf16().chain(core::iter::once(0)).collect()); - let name_ptr = name_wide - .as_ref() - .map(|n| n.as_ptr()) - .unwrap_or(core::ptr::null()); + let name_ptr = name_wide.as_ref().map_or(core::ptr::null(), |n| n.as_ptr()); let event = unsafe { windows_sys::Win32::System::Threading::CreateEventW(