diff --git a/Cargo.toml b/Cargo.toml index da9defcbbf..80976b1e1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -335,17 +335,24 @@ if_not_else = "allow" # Not always more readable single_match_else = "allow" similar_names = "allow" +# restriction lints alloc_instead_of_core = "warn" std_instead_of_alloc = "warn" std_instead_of_core = "warn" -format_collect = "warn" -from_iter_instead_of_collect = "warn" -inefficient_to_string = "warn" -redundant_clone = "warn" + +# nursery lints to enforce gradually debug_assert_with_mut_call = "warn" -unused_peekable = "warn" +derive_partial_eq_without_eq = "warn" +imprecise_flops = "warn" or_fun_call = "warn" -unnested_or_patterns = "warn" +redundant_clone = "warn" +search_is_some = "warn" +single_option_map = "warn" +trait_duplication_in_bounds = "warn" +unused_peekable = "warn" +unused_rounding = "warn" +use_self = "warn" +useless_let_if_seq = "warn" # pedantic lints to enforce gradually cloned_instead_of_copied = "warn" @@ -355,10 +362,14 @@ explicit_into_iter_loop = "warn" explicit_iter_loop = "warn" filter_map_next = "warn" flat_map_option = "warn" +format_collect = "warn" +from_iter_instead_of_collect = "warn" inconsistent_struct_constructor = "warn" +inefficient_to_string = "warn" manual_is_variant_and = "warn" map_unwrap_or = "warn" must_use_candidate = "warn" redundant_else = "warn" uninlined_format_args = "warn" unnecessary_wraps = "warn" +unnested_or_patterns = "warn" diff --git a/crates/capi/src/util.rs b/crates/capi/src/util.rs index 95e11ff576..6137ca9029 100644 --- a/crates/capi/src/util.rs +++ b/crates/capi/src/util.rs @@ -86,17 +86,17 @@ impl FfiResult for usize { } impl FfiResult for c_long { - const ERR_VALUE: c_long = -1; + const ERR_VALUE: Self = -1; - fn into_output(self, _vm: &VirtualMachine) -> c_long { + fn into_output(self, _vm: &VirtualMachine) -> Self { self } } impl FfiResult for c_double { - const ERR_VALUE: c_double = -1.0; + const ERR_VALUE: Self = -1.0; - fn into_output(self, _vm: &VirtualMachine) -> c_double { + fn into_output(self, _vm: &VirtualMachine) -> Self { self } } diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index ae4692a04e..3873736c22 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -51,18 +51,18 @@ impl ExprExt for ast::Expr { fn is_constant(&self) -> bool { matches!( self, - ast::Expr::NumberLiteral(_) - | ast::Expr::StringLiteral(_) - | ast::Expr::BytesLiteral(_) - | ast::Expr::NoneLiteral(_) - | ast::Expr::BooleanLiteral(_) - | ast::Expr::EllipsisLiteral(_) + Self::NumberLiteral(_) + | Self::StringLiteral(_) + | Self::BytesLiteral(_) + | Self::NoneLiteral(_) + | Self::BooleanLiteral(_) + | Self::EllipsisLiteral(_) ) } fn is_constant_slice(&self) -> bool { match self { - ast::Expr::Slice(s) => { + Self::Slice(s) => { let lower_const = s.lower.is_none() || s.lower.as_deref().is_some_and(|e| e.is_constant()); let upper_const = @@ -76,7 +76,7 @@ impl ExprExt for ast::Expr { } fn should_use_slice_optimization(&self) -> bool { - !self.is_constant_slice() && matches!(self, ast::Expr::Slice(s) if s.step.is_none()) + !self.is_constant_slice() && matches!(self, Self::Slice(s) if s.step.is_none()) } } diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index 17aaf2fa79..231da704f6 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -1231,6 +1231,7 @@ impl CodeInfo { op: oparg::BinaryOperator, ) -> Option { use oparg::BinaryOperator as BinOp; + fn repeat_wtf8(value: &Wtf8Buf, n: usize) -> Wtf8Buf { let mut result = Wtf8Buf::with_capacity(value.len().saturating_mul(n)); for _ in 0..n { @@ -1238,6 +1239,7 @@ impl CodeInfo { } result } + fn checked_repeat_count(n: &BigInt, item_size: usize) -> Option { let n = n.to_isize()?; if item_size != 0 && (n < 0 || n as usize > MAX_STR_SIZE / item_size) { @@ -1245,6 +1247,7 @@ impl CodeInfo { } Some(n.max(0) as usize) } + fn eval_complex_binop( left: Complex, right: Complex, @@ -1259,17 +1262,18 @@ impl CodeInfo { BinOp::Add => left + right, BinOp::Subtract => { let re = left.re - right.re; - let mut im = left.im - right.im; // Preserve CPython's signed-zero behavior for real-zero // minus zero-complex expressions such as `0 - 0j`. - if left.re == 0.0 + let im = if left.re == 0.0 && left.im == 0.0 && right.re == 0.0 && right.im == 0.0 && !right.im.is_sign_negative() { - im = -0.0; - } + -0.0 + } else { + left.im - right.im + }; Complex::new(re, im) } BinOp::Multiply => left * right, @@ -1284,12 +1288,14 @@ impl CodeInfo { if right.im != 0.0 || right.re < 0.0 { return None; } + return complex_const(if right.re == 0.0 { Complex::new(1.0, 0.0) } else { Complex::new(0.0, 0.0) }); } + if right.im == 0.0 && right.re.fract() == 0.0 && right.re >= f64::from(i32::MIN) @@ -1304,6 +1310,7 @@ impl CodeInfo { }; complex_const(value) } + fn float_div_mod(left: f64, right: f64) -> Option<(f64, f64)> { if right == 0.0 { return None; @@ -1330,6 +1337,7 @@ impl CodeInfo { Some((floordiv, modulo)) } + fn constant_as_index(value: &ConstantData) -> Option { match value { ConstantData::Integer { value } => value.to_i64().or_else(|| { @@ -1343,12 +1351,14 @@ impl CodeInfo { _ => None, } } + fn slice_bound(value: &ConstantData) -> Option> { match value { ConstantData::None => Some(None), _ => constant_as_index(value).map(Some), } } + fn adjusted_slice_indices(len: usize, slice: &[ConstantData; 3]) -> Option> { let len = i64::try_from(len).ok()?; let start = slice_bound(&slice[0])?; @@ -1393,6 +1403,7 @@ impl CodeInfo { } Some(indices) } + fn adjusted_const_index(len: usize, index: &ConstantData) -> Option { let len = i64::try_from(len).ok()?; let index = constant_as_index(index)?; @@ -1406,6 +1417,7 @@ impl CodeInfo { } usize::try_from(index).ok() } + fn eval_const_subscript( container: &ConstantData, index: &ConstantData, @@ -1472,9 +1484,11 @@ impl CodeInfo { _ => None, } } + if matches!(op, BinOp::Subscr) { return eval_const_subscript(left, right); } + match (left, right) { (ConstantData::Integer { value: l }, ConstantData::Integer { value: r }) => { let result = match op { diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index 57da8c3069..60c8d2734a 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -37,7 +37,7 @@ pub struct SymbolTable { /// A list of sub-scopes in the order as found in the /// AST nodes. - pub sub_tables: Vec, + pub sub_tables: Vec, /// Cursor pointing to the next sub-table to consume during compilation. pub next_sub_table: usize, @@ -63,7 +63,7 @@ pub struct SymbolTable { /// PEP 649: Reference to annotation scope for this block /// Annotations are compiled as a separate `__annotate__` function - pub annotation_block: Option>, + pub annotation_block: Option>, /// True only for deferred function/class/module annotation scopes that /// should resolve outer names as if they were siblings of the owning @@ -177,7 +177,7 @@ pub enum SymbolScope { } bitflags! { - #[derive(Copy, Clone, Debug, PartialEq)] + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct SymbolFlags: u16 { const REFERENCED = 0x001; // USE const ASSIGNED = 0x002; // DEF_LOCAL diff --git a/crates/common/src/cformat.rs b/crates/common/src/cformat.rs index 183cc80e7e..5d24b30ce0 100644 --- a/crates/common/src/cformat.rs +++ b/crates/common/src/cformat.rs @@ -14,7 +14,7 @@ use rustpython_literal::{float, format::Case}; use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf}; -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CFormatErrorType { UnmatchedKeyParentheses, MissingModuloSign, @@ -27,7 +27,7 @@ pub enum CFormatErrorType { // also contains how many chars the parsing function consumed pub type ParsingError = (CFormatErrorType, usize); -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct CFormatError { pub typ: CFormatErrorType, // FIXME pub index: usize, @@ -54,7 +54,7 @@ impl fmt::Display for CFormatError { pub type CFormatConversion = super::format::FormatConversion; -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[repr(u8)] pub enum CNumberType { DecimalD = b'd', @@ -65,7 +65,7 @@ pub enum CNumberType { HexUpper = b'X', } -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[repr(u8)] pub enum CFloatType { ExponentLower = b'e', @@ -87,13 +87,13 @@ impl CFloatType { } } -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[repr(u8)] pub enum CCharacterType { Character = b'c', } -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum CFormatType { Number(CNumberType), Float(CFloatType), @@ -113,7 +113,7 @@ impl CFormatType { } } -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum CFormatPrecision { Quantity(CFormatQuantity), Dot, @@ -126,7 +126,7 @@ impl From for CFormatPrecision { } bitflags! { - #[derive(Copy, Clone, Debug, PartialEq)] + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct CConversionFlags: u32 { const ALTERNATE_FORM = 0b0000_0001; const ZERO_PAD = 0b0000_0010; @@ -150,7 +150,7 @@ impl CConversionFlags { } } -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum CFormatQuantity { Amount(usize), FromValuesTuple, @@ -254,7 +254,7 @@ impl FormatChar for u8 { } } -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct CFormatSpec { pub flags: CConversionFlags, pub min_field_width: Option, @@ -263,7 +263,7 @@ pub struct CFormatSpec { // chars_consumed: usize, } -#[derive(Debug, PartialEq)] +#[derive(Debug, Eq, PartialEq)] pub struct CFormatSpecKeyed { pub mapping_key: Option, pub spec: CFormatSpec, @@ -718,7 +718,7 @@ where Some(contained_text) } -#[derive(Debug, PartialEq)] +#[derive(Debug, Eq, PartialEq)] pub enum CFormatPart { Literal(T), Spec(CFormatSpecKeyed), @@ -739,7 +739,7 @@ impl CFormatPart { } } -#[derive(Debug, PartialEq)] +#[derive(Debug, Eq, PartialEq)] pub struct CFormatStrOrBytes { parts: Vec<(usize, CFormatPart)>, } diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index ea4844c8ec..8992eb9ca3 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -31,7 +31,7 @@ trait FormatParse { Self: Sized; } -#[derive(Debug, Copy, Clone, PartialEq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(u8)] pub enum FormatConversion { Str = b's', @@ -74,7 +74,7 @@ impl FormatConversion { } } -#[derive(Debug, Copy, Clone, PartialEq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum FormatAlign { Left, Right, @@ -105,7 +105,7 @@ impl FormatParse for FormatAlign { } } -#[derive(Debug, Copy, Clone, PartialEq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum FormatSign { Plus, Minus, @@ -124,7 +124,7 @@ impl FormatParse for FormatSign { } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FormatGrouping { Comma, Underscore, @@ -150,7 +150,7 @@ impl From<&FormatGrouping> for char { } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FormatType { String, Binary, @@ -216,7 +216,7 @@ impl FormatParse for FormatType { } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct FormatSpec { conversion: Option, fill: Option, @@ -644,7 +644,7 @@ impl FormatSpec { // Reuse format_complex_re_im with 'g' type to get the base formatted parts, // then apply locale grouping. This matches CPython's format_complex_internal: // 'n' → 'g', add_parens=0, skip_re=0. - let locale_spec = FormatSpec { + let locale_spec = Self { format_type: Some(FormatType::GeneralFormat(Case::Lower)), ..*self }; @@ -933,20 +933,23 @@ impl FormatSpec { fn format_complex_re_im(&self, num: &Complex64) -> Result<(String, String), FormatSpecError> { // Format real part - let mut formatted_re = String::new(); - if num.re != 0.0 || num.re.is_negative_zero() || self.format_type.is_some() { - let sign_re = if num.re.is_sign_negative() && !num.is_nan() { - "-" + let formatted_re = + if num.re != 0.0 || num.re.is_negative_zero() || self.format_type.is_some() { + let sign_re = if num.re.is_sign_negative() && !num.is_nan() { + "-" + } else { + match self.sign.unwrap_or(FormatSign::Minus) { + FormatSign::Plus => "+", + FormatSign::Minus => "", + FormatSign::MinusOrSpace => " ", + } + }; + let re = self.format_complex_float(num.re)?; + format!("{sign_re}{re}") } else { - match self.sign.unwrap_or(FormatSign::Minus) { - FormatSign::Plus => "+", - FormatSign::Minus => "", - FormatSign::MinusOrSpace => " ", - } + String::new() }; - let re = self.format_complex_float(num.re)?; - formatted_re = format!("{sign_re}{re}"); - } + // Format imaginary part let sign_im = if num.im.is_sign_negative() && !num.im.is_nan() { "-" @@ -1118,7 +1121,7 @@ impl Deref for AsciiStr<'_> { } } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FormatSpecError { DecimalDigitsTooMany, PrecisionTooBig, @@ -1135,7 +1138,7 @@ pub enum FormatSpecError { NotImplemented(char, &'static str), } -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FormatParseError { UnmatchedBracket, MissingStartBracket, @@ -1155,7 +1158,7 @@ impl FromStr for FormatSpec { } } -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Eq)] pub enum FieldNamePart { Attribute(Wtf8Buf), Index(usize), @@ -1202,14 +1205,14 @@ impl FieldNamePart { } } -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Eq)] pub enum FieldType { Auto, Index(usize), Keyword(Wtf8Buf), } -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Eq)] pub struct FieldName { pub field_type: FieldType, pub parts: Vec, @@ -1255,7 +1258,7 @@ impl FieldName { } } -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Eq)] pub enum FormatPart { Field { field_name: Wtf8Buf, @@ -1265,7 +1268,7 @@ pub enum FormatPart { Literal(Wtf8Buf), } -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Eq)] pub struct FormatString { pub format_parts: Vec, } diff --git a/crates/compiler-core/src/bytecode.rs b/crates/compiler-core/src/bytecode.rs index eb33a526a1..86723f4002 100644 --- a/crates/compiler-core/src/bytecode.rs +++ b/crates/compiler-core/src/bytecode.rs @@ -450,7 +450,7 @@ pub struct CodeObject { } bitflags! { - #[derive(Copy, Clone, Debug, PartialEq)] + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct CodeFlags: u32 { const OPTIMIZED = 0x0001; const NEWLOCALS = 0x0002; @@ -866,7 +866,7 @@ impl CodeUnits { #[derive(Debug, Clone)] pub enum ConstantData { Tuple { - elements: Vec, + elements: Vec, }, Integer { value: BigInt, @@ -891,10 +891,10 @@ pub enum ConstantData { }, /// Constant slice(start, stop, step) Slice { - elements: Box<[ConstantData; 3]>, + elements: Box<[Self; 3]>, }, Frozenset { - elements: Vec, + elements: Vec, }, None, Ellipsis, diff --git a/crates/compiler-core/src/bytecode/instruction.rs b/crates/compiler-core/src/bytecode/instruction.rs index 0a08aa1152..6293706979 100644 --- a/crates/compiler-core/src/bytecode/instruction.rs +++ b/crates/compiler-core/src/bytecode/instruction.rs @@ -535,7 +535,7 @@ impl StackEffect { impl From for i32 { fn from(effect: StackEffect) -> Self { - (effect.pushed() as i32) - (effect.popped() as i32) + (effect.pushed() as Self) - (effect.popped() as Self) } } diff --git a/crates/compiler-core/src/bytecode/oparg.rs b/crates/compiler-core/src/bytecode/oparg.rs index 50829c5df0..6cb58b1a68 100644 --- a/crates/compiler-core/src/bytecode/oparg.rs +++ b/crates/compiler-core/src/bytecode/oparg.rs @@ -485,7 +485,7 @@ impl TryFrom for MakeFunctionFlag { impl From for u32 { /// Encode as CPython-compatible power-of-two value fn from(flag: MakeFunctionFlag) -> Self { - 1u32 << (flag as u32) + 1u32 << (flag as Self) } } diff --git a/crates/compiler/src/lib.rs b/crates/compiler/src/lib.rs index cf55d1a0f1..1193661843 100644 --- a/crates/compiler/src/lib.rs +++ b/crates/compiler/src/lib.rs @@ -137,8 +137,8 @@ impl CompileError { #[must_use] pub fn python_end_location(&self) -> Option<(usize, usize)> { match self { - CompileError::Codegen(_) => None, - CompileError::Parse(parse_error) => Some(( + Self::Codegen(_) => None, + Self::Parse(parse_error) => Some(( parse_error.end_location.line.get(), parse_error.end_location.character_offset.get(), )), diff --git a/crates/derive-impl/src/pymodule.rs b/crates/derive-impl/src/pymodule.rs index f51d6955f8..cee8b1be4a 100644 --- a/crates/derive-impl/src/pymodule.rs +++ b/crates/derive-impl/src/pymodule.rs @@ -32,7 +32,7 @@ impl syn::parse::Parse for WithItem { } } let path = input.parse()?; - Ok(WithItem { cfg_attrs, path }) + Ok(Self { cfg_attrs, path }) } } @@ -75,7 +75,7 @@ impl syn::parse::Parse for PyModuleArgs { input.parse::()?; } - Ok(PyModuleArgs { metas, with_items }) + Ok(Self { metas, with_items }) } } diff --git a/crates/host_env/src/windows.rs b/crates/host_env/src/windows.rs index a934a118ec..9667edf914 100644 --- a/crates/host_env/src/windows.rs +++ b/crates/host_env/src/windows.rs @@ -48,9 +48,10 @@ where { fn from_wides_until_nul(wide: &[u16]) -> Self; } + impl FromWideString for OsString { - fn from_wides_until_nul(wide: &[u16]) -> OsString { + fn from_wides_until_nul(wide: &[u16]) -> Self { let len = wide.iter().take_while(|&&c| c != 0).count(); - OsString::from_wide(&wide[..len]) + Self::from_wide(&wide[..len]) } } diff --git a/crates/jit/src/instructions.rs b/crates/jit/src/instructions.rs index 35ffdbe95a..61780a243c 100644 --- a/crates/jit/src/instructions.rs +++ b/crates/jit/src/instructions.rs @@ -29,32 +29,32 @@ enum JitValue { Bool(Value), None, Null, - Tuple(Vec), + Tuple(Vec), FuncRef(FuncRef), } impl JitValue { - fn from_type_and_value(ty: JitType, val: Value) -> JitValue { + fn from_type_and_value(ty: JitType, val: Value) -> Self { match ty { - JitType::Int => JitValue::Int(val), - JitType::Float => JitValue::Float(val), - JitType::Bool => JitValue::Bool(val), + JitType::Int => Self::Int(val), + JitType::Float => Self::Float(val), + JitType::Bool => Self::Bool(val), } } fn to_jit_type(&self) -> Option { match self { - JitValue::Int(_) => Some(JitType::Int), - JitValue::Float(_) => Some(JitType::Float), - JitValue::Bool(_) => Some(JitType::Bool), - JitValue::None | JitValue::Null | JitValue::Tuple(_) | JitValue::FuncRef(_) => None, + Self::Int(_) => Some(JitType::Int), + Self::Float(_) => Some(JitType::Float), + Self::Bool(_) => Some(JitType::Bool), + Self::None | Self::Null | Self::Tuple(_) | Self::FuncRef(_) => None, } } fn into_value(self) -> Option { match self { - JitValue::Int(val) | JitValue::Float(val) | JitValue::Bool(val) => Some(val), - JitValue::None | JitValue::Null | JitValue::Tuple(_) | JitValue::FuncRef(_) => None, + Self::Int(val) | Self::Float(val) | Self::Bool(val) => Some(val), + Self::None | Self::Null | Self::Tuple(_) | Self::FuncRef(_) => None, } } } @@ -80,8 +80,8 @@ impl<'a, 'b> FunctionCompiler<'a, 'b> { arg_types: &[JitType], ret_type: Option, entry_block: Block, - ) -> FunctionCompiler<'a, 'b> { - let mut compiler = FunctionCompiler { + ) -> Self { + let mut compiler = Self { builder, stack: Vec::new(), variables: vec![None; num_variables].into_boxed_slice(), diff --git a/crates/jit/src/lib.rs b/crates/jit/src/lib.rs index 73dce1fede..dbaa4a3eb2 100644 --- a/crates/jit/src/lib.rs +++ b/crates/jit/src/lib.rs @@ -224,28 +224,28 @@ pub enum AbiValue { impl AbiValue { fn to_libffi_arg(&self) -> libffi::middle::Arg<'_> { match self { - AbiValue::Int(i) => libffi::middle::Arg::new(i), - AbiValue::Float(f) => libffi::middle::Arg::new(f), - AbiValue::Bool(b) => libffi::middle::Arg::new(b), + Self::Int(i) => libffi::middle::Arg::new(i), + Self::Float(f) => libffi::middle::Arg::new(f), + Self::Bool(b) => libffi::middle::Arg::new(b), } } } impl From for AbiValue { fn from(i: i64) -> Self { - AbiValue::Int(i) + Self::Int(i) } } impl From for AbiValue { fn from(f: f64) -> Self { - AbiValue::Float(f) + Self::Float(f) } } impl From for AbiValue { fn from(b: bool) -> Self { - AbiValue::Bool(b) + Self::Bool(b) } } diff --git a/crates/jit/tests/common.rs b/crates/jit/tests/common.rs index fddf9c56f1..fe0e4bd33d 100644 --- a/crates/jit/tests/common.rs +++ b/crates/jit/tests/common.rs @@ -47,27 +47,27 @@ impl Function { enum StackValue { String(String), None, - Map(HashMap), + Map(HashMap), Code(Box), Function(Function), - Slice(Box<[StackValue; 3]>), - Frozenset(Vec), + Slice(Box<[Self; 3]>), + Frozenset(Vec), } impl From for StackValue { fn from(value: ConstantData) -> Self { match value { ConstantData::Str { value } => { - StackValue::String(value.into_string().expect("surrogate in test code")) + Self::String(value.into_string().expect("surrogate in test code")) } - ConstantData::None => StackValue::None, - ConstantData::Code { code } => StackValue::Code(code), + ConstantData::None => Self::None, + ConstantData::Code { code } => Self::Code(code), ConstantData::Slice { elements } => { let [start, stop, step] = *elements; - StackValue::Slice(Box::new([start.into(), stop.into(), step.into()])) + Self::Slice(Box::new([start.into(), stop.into(), step.into()])) } ConstantData::Frozenset { elements } => { - StackValue::Frozenset(elements.into_iter().map(Into::into).collect()) + Self::Frozenset(elements.into_iter().map(Into::into).collect()) } c => unimplemented!("constant {:?} isn't yet supported in py_function!", c), } @@ -178,8 +178,8 @@ pub(crate) struct StackMachine { } impl StackMachine { - pub(crate) fn new() -> StackMachine { - StackMachine { + pub(crate) fn new() -> Self { + Self { stack: Vec::new(), locals: HashMap::new(), } diff --git a/crates/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index 22a1b6ea9f..90114900e8 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -103,9 +103,9 @@ pub(crate) mod _asyncio { impl FutureState { fn as_str(&self) -> &'static str { match self { - FutureState::Pending => "PENDING", - FutureState::Cancelled => "CANCELLED", - FutureState::Finished => "FINISHED", + Self::Pending => "PENDING", + Self::Cancelled => "CANCELLED", + Self::Finished => "FINISHED", } } } @@ -140,7 +140,7 @@ pub(crate) mod _asyncio { type Args = FuncArgs; fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { - Ok(PyFuture::new_empty()) + Ok(Self::new_empty()) } } @@ -154,7 +154,7 @@ pub(crate) mod _asyncio { } // Extract only 'loop' keyword argument let loop_ = args.kwargs.get("loop").cloned(); - PyFuture::py_init(&zelf, loop_, vm) + Self::py_init(&zelf, loop_, vm) } } @@ -1148,7 +1148,7 @@ pub(crate) mod _asyncio { type Args = TaskInitArgs; fn init(zelf: PyRef, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - PyTask::py_init(&zelf, args, vm) + Self::py_init(&zelf, args, vm) } } diff --git a/crates/stdlib/src/_sqlite3.rs b/crates/stdlib/src/_sqlite3.rs index 3cf93692c0..fd7fec4feb 100644 --- a/crates/stdlib/src/_sqlite3.rs +++ b/crates/stdlib/src/_sqlite3.rs @@ -897,11 +897,11 @@ mod _sqlite3 { // For non-subclassed Connection, initialize in __new__ // For subclassed Connection, leave db as None and require __init__ to be called - let is_base_class = cls.is(Connection::class(&vm.ctx)); + let is_base_class = cls.is(Self::class(&vm.ctx)); let db = if is_base_class { // Initialize immediately for base class - Some(Connection::initialize_db(&args, vm)?) + Some(Self::initialize_db(&args, vm)?) } else { // For subclasses, require __init__ to be called None @@ -1903,7 +1903,7 @@ mod _sqlite3 { let mut list = vec![]; let mut remaining = max_rows; while remaining > 0 { - match Cursor::next(zelf, vm)? { + match Self::next(zelf, vm)? { PyIterReturn::Return(row) => { list.push(row); remaining -= 1; @@ -1945,6 +1945,7 @@ mod _sqlite3 { #[pymethod] fn setinputsizes(&self, _sizes: PyObjectRef) {} + #[pymethod] fn setoutputsize(&self, _size: PyObjectRef, _column: OptionalArg) {} @@ -3033,7 +3034,7 @@ mod _sqlite3 { impl From<*mut sqlite3_stmt> for SqliteStatementRaw { fn from(st: *mut sqlite3_stmt) -> Self { - SqliteStatementRaw { st } + Self { st } } } diff --git a/crates/stdlib/src/grp.rs b/crates/stdlib/src/grp.rs index 0e09c69562..70aa7d4e4c 100644 --- a/crates/stdlib/src/grp.rs +++ b/crates/stdlib/src/grp.rs @@ -34,7 +34,7 @@ mod grp { s.into_string() .unwrap_or_else(|e| e.into_cstring().to_string_lossy().into_owned()) }; - GroupData { + Self { gr_name: group.name, gr_passwd: cstr_lossy(group.passwd), gr_gid: group.gid.as_raw(), diff --git a/crates/stdlib/src/hashlib.rs b/crates/stdlib/src/hashlib.rs index 8f37407c35..bbe81cc823 100644 --- a/crates/stdlib/src/hashlib.rs +++ b/crates/stdlib/src/hashlib.rs @@ -281,7 +281,7 @@ pub(crate) mod _hashlib { } fn dyn_clone(&self) -> Box { - Box::new(TypedHmac(self.0.clone())) + Box::new(Self(self.0.clone())) } } diff --git a/crates/stdlib/src/lzma.rs b/crates/stdlib/src/lzma.rs index 7ff8a95203..7abfc97251 100644 --- a/crates/stdlib/src/lzma.rs +++ b/crates/stdlib/src/lzma.rs @@ -201,7 +201,7 @@ mod _lzma { impl DecompressStatus for Status { fn is_stream_end(&self) -> bool { - *self == Status::StreamEnd + *self == Self::StreamEnd } } @@ -671,7 +671,7 @@ mod _lzma { } impl CompressStatusKind for Status { - const EOF: Self = Status::StreamEnd; + const EOF: Self = Self::StreamEnd; fn to_usize(self) -> usize { self as usize @@ -679,8 +679,8 @@ mod _lzma { } impl CompressFlushKind for Action { - const NONE: Self = Action::Run; - const FINISH: Self = Action::Finish; + const NONE: Self = Self::Run; + const FINISH: Self = Self::Finish; fn to_usize(self) -> usize { self as usize diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index 744bb7bb79..9cb84b4efa 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -253,10 +253,10 @@ mod mmap { impl MmapObj { fn as_slice(&self) -> &[u8] { match self { - MmapObj::Read(mmap) => &mmap[..], - MmapObj::Write(mmap) => &mmap[..], + Self::Read(mmap) => &mmap[..], + Self::Write(mmap) => &mmap[..], #[cfg(windows)] - MmapObj::Named(named) => unsafe { + Self::Named(named) => unsafe { core::slice::from_raw_parts(named.view_ptr, named.len) }, } diff --git a/crates/stdlib/src/multiprocessing.rs b/crates/stdlib/src/multiprocessing.rs index fe30abfdcb..36f3991022 100644 --- a/crates/stdlib/src/multiprocessing.rs +++ b/crates/stdlib/src/multiprocessing.rs @@ -71,7 +71,7 @@ mod _multiprocessing { if handle == 0 as HANDLE { return Err(vm.new_last_os_error()); } - Ok(SemHandle { raw: handle }) + Ok(Self { raw: handle }) } #[inline] @@ -272,7 +272,7 @@ mod _multiprocessing { vm: &VirtualMachine, ) -> PyResult { // On Windows, _rebuild receives the handle directly (no sem_open) - let zelf = SemLock { + let zelf = Self { handle: SemHandle { raw: handle as HANDLE, }, @@ -349,7 +349,7 @@ mod _multiprocessing { let handle = SemHandle::create(args.value, args.maxvalue, vm)?; let name = if args.unlink { None } else { Some(args.name) }; - Ok(SemLock { + Ok(Self { handle, kind: args.kind, maxvalue: args.maxvalue, @@ -569,9 +569,9 @@ mod _multiprocessing { unsafe { libc::sem_unlink(cname.as_ptr()); } - Ok((SemHandle { raw }, None)) + Ok((Self { raw }, None)) } else { - Ok((SemHandle { raw }, Some(name.to_owned()))) + Ok((Self { raw }, Some(name.to_owned()))) } } @@ -582,7 +582,7 @@ mod _multiprocessing { let err = Errno::last(); return Err(os_error(vm, err)); } - Ok(SemHandle { raw }) + Ok(Self { raw }) } #[inline] @@ -928,7 +928,7 @@ mod _multiprocessing { }; let handle = SemHandle::open_existing(name_str, vm)?; // return newsemlockobject(type, handle, kind, maxvalue, name_copy); - let zelf = SemLock { + let zelf = Self { handle, kind, maxvalue, @@ -1060,7 +1060,7 @@ mod _multiprocessing { let (handle, name) = SemHandle::create(&args.name, value, args.unlink, vm)?; // return newsemlockobject(type, handle, kind, maxvalue, name_copy); - Ok(SemLock { + Ok(Self { handle, kind: args.kind, maxvalue: args.maxvalue, diff --git a/crates/stdlib/src/overlapped.rs b/crates/stdlib/src/overlapped.rs index 33a97a264b..bc1fb62341 100644 --- a/crates/stdlib/src/overlapped.rs +++ b/crates/stdlib/src/overlapped.rs @@ -1515,7 +1515,7 @@ mod _overlapped { error: 0, data: OverlappedData::None, }; - Ok(Overlapped { + Ok(Self { inner: PyMutex::new(inner), }) } diff --git a/crates/stdlib/src/posixsubprocess.rs b/crates/stdlib/src/posixsubprocess.rs index d81af19856..059e07e2d3 100644 --- a/crates/stdlib/src/posixsubprocess.rs +++ b/crates/stdlib/src/posixsubprocess.rs @@ -185,9 +185,9 @@ impl TryFromObject for MaybeFd { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let fd = i32::try_from_object(vm, obj)?; Ok(if fd == -1 { - MaybeFd::Invalid + Self::Invalid } else { - MaybeFd::Valid(Fd(unsafe { BorrowedFd::borrow_raw(fd) })) + Self::Valid(Fd(unsafe { BorrowedFd::borrow_raw(fd) })) }) } } @@ -195,8 +195,8 @@ impl TryFromObject for MaybeFd { impl AsRawFd for MaybeFd { fn as_raw_fd(&self) -> RawFd { match self { - MaybeFd::Valid(fd) => fd.as_raw_fd(), - MaybeFd::Invalid => -1, + Self::Valid(fd) => fd.as_raw_fd(), + Self::Invalid => -1, } } } diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index 95321d37e5..a7aacf2d1a 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -2265,7 +2265,7 @@ mod _ssl { session_cache: shared_session_cache.clone(), }); - Ok(PySSLContext { + Ok(Self { protocol, check_hostname: PyRwLock::new(protocol == PROTOCOL_TLS_CLIENT), verify_mode: PyRwLock::new(default_verify_mode), @@ -4667,7 +4667,7 @@ mod _ssl { type Args = (); fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { - Ok(PyMemoryBIO { + Ok(Self { buffer: PyMutex::new(Vec::new()), eof: PyRwLock::new(false), }) diff --git a/crates/stdlib/src/ssl/compat.rs b/crates/stdlib/src/ssl/compat.rs index 079e7f7629..ed3880940b 100644 --- a/crates/stdlib/src/ssl/compat.rs +++ b/crates/stdlib/src/ssl/compat.rs @@ -274,64 +274,64 @@ impl TlsConnection { /// Check if handshake is in progress pub(super) fn is_handshaking(&self) -> bool { match self { - TlsConnection::Client(conn) => conn.is_handshaking(), - TlsConnection::Server(conn) => conn.is_handshaking(), + Self::Client(conn) => conn.is_handshaking(), + Self::Server(conn) => conn.is_handshaking(), } } /// Check if connection wants to read data pub(super) fn wants_read(&self) -> bool { match self { - TlsConnection::Client(conn) => conn.wants_read(), - TlsConnection::Server(conn) => conn.wants_read(), + Self::Client(conn) => conn.wants_read(), + Self::Server(conn) => conn.wants_read(), } } /// Check if connection wants to write data pub(super) fn wants_write(&self) -> bool { match self { - TlsConnection::Client(conn) => conn.wants_write(), - TlsConnection::Server(conn) => conn.wants_write(), + Self::Client(conn) => conn.wants_write(), + Self::Server(conn) => conn.wants_write(), } } /// Read TLS data from socket pub(super) fn read_tls(&mut self, reader: &mut dyn std::io::Read) -> std::io::Result { match self { - TlsConnection::Client(conn) => conn.read_tls(reader), - TlsConnection::Server(conn) => conn.read_tls(reader), + Self::Client(conn) => conn.read_tls(reader), + Self::Server(conn) => conn.read_tls(reader), } } /// Write TLS data to socket pub(super) fn write_tls(&mut self, writer: &mut dyn std::io::Write) -> std::io::Result { match self { - TlsConnection::Client(conn) => conn.write_tls(writer), - TlsConnection::Server(conn) => conn.write_tls(writer), + Self::Client(conn) => conn.write_tls(writer), + Self::Server(conn) => conn.write_tls(writer), } } /// Process new TLS packets pub(super) fn process_new_packets(&mut self) -> Result { match self { - TlsConnection::Client(conn) => conn.process_new_packets(), - TlsConnection::Server(conn) => conn.process_new_packets(), + Self::Client(conn) => conn.process_new_packets(), + Self::Server(conn) => conn.process_new_packets(), } } /// Get reader for plaintext data (rustls native type) pub(super) fn reader(&mut self) -> rustls::Reader<'_> { match self { - TlsConnection::Client(conn) => conn.reader(), - TlsConnection::Server(conn) => conn.reader(), + Self::Client(conn) => conn.reader(), + Self::Server(conn) => conn.reader(), } } /// Get writer for plaintext data (rustls native type) pub(super) fn writer(&mut self) -> rustls::Writer<'_> { match self { - TlsConnection::Client(conn) => conn.writer(), - TlsConnection::Server(conn) => conn.writer(), + Self::Client(conn) => conn.writer(), + Self::Server(conn) => conn.writer(), } } @@ -339,10 +339,10 @@ impl TlsConnection { pub(super) fn is_session_resumed(&self) -> bool { use rustls::HandshakeKind; match self { - TlsConnection::Client(conn) => { + Self::Client(conn) => { matches!(conn.handshake_kind(), Some(HandshakeKind::Resumed)) } - TlsConnection::Server(conn) => { + Self::Server(conn) => { matches!(conn.handshake_kind(), Some(HandshakeKind::Resumed)) } } @@ -351,24 +351,24 @@ impl TlsConnection { /// Send close_notify alert pub(super) fn send_close_notify(&mut self) { match self { - TlsConnection::Client(conn) => conn.send_close_notify(), - TlsConnection::Server(conn) => conn.send_close_notify(), + Self::Client(conn) => conn.send_close_notify(), + Self::Server(conn) => conn.send_close_notify(), } } /// Get negotiated ALPN protocol pub(super) fn alpn_protocol(&self) -> Option<&[u8]> { match self { - TlsConnection::Client(conn) => conn.alpn_protocol(), - TlsConnection::Server(conn) => conn.alpn_protocol(), + Self::Client(conn) => conn.alpn_protocol(), + Self::Server(conn) => conn.alpn_protocol(), } } /// Get negotiated cipher suite pub(super) fn negotiated_cipher_suite(&self) -> Option { match self { - TlsConnection::Client(conn) => conn.negotiated_cipher_suite(), - TlsConnection::Server(conn) => conn.negotiated_cipher_suite(), + Self::Client(conn) => conn.negotiated_cipher_suite(), + Self::Server(conn) => conn.negotiated_cipher_suite(), } } @@ -377,8 +377,8 @@ impl TlsConnection { &self, ) -> Option<&[rustls::pki_types::CertificateDer<'static>]> { match self { - TlsConnection::Client(conn) => conn.peer_certificates(), - TlsConnection::Server(conn) => conn.peer_certificates(), + Self::Client(conn) => conn.peer_certificates(), + Self::Server(conn) => conn.peer_certificates(), } } } @@ -427,19 +427,19 @@ impl SslError { /// Convert rustls error to SslError pub(super) fn from_rustls(err: rustls::Error) -> Self { match err { - rustls::Error::InvalidCertificate(cert_err) => SslError::CertVerification(cert_err), + rustls::Error::InvalidCertificate(cert_err) => Self::CertVerification(cert_err), rustls::Error::AlertReceived(alert_desc) => { // Map TLS alerts to OpenSSL-compatible error codes // lib = 20 (ERR_LIB_SSL), reason = 1000 + alert_code match alert_desc { rustls::AlertDescription::CloseNotify => { // Special case: close_notify is handled as ZeroReturn - SslError::ZeroReturn + Self::ZeroReturn } _ => { // All other alerts: convert to OpenSSL error code // This includes InternalError (80 -> reason 1080) - SslError::AlertReceived { + Self::AlertReceived { lib: ERR_LIB_SSL, reason: Self::alert_to_openssl_reason(alert_desc), } @@ -452,7 +452,7 @@ impl SslError { rustls::Error::InvalidMessage(_) => { // UnexpectedMessage, CorruptMessage, etc. → SSLEOFError // Matches CPython's "EOF occurred in violation of protocol" - SslError::Eof + Self::Eof } rustls::Error::PeerIncompatible(peer_err) => { // Check for specific incompatibility types @@ -460,15 +460,15 @@ impl SslError { match peer_err { PeerIncompatible::NoCipherSuitesInCommon => { // Maps to OpenSSL SSL_R_NO_SHARED_CIPHER (lib=20, reason=193) - SslError::NoCipherSuites + Self::NoCipherSuites } _ => { // Other protocol incompatibilities → SSLEOFError - SslError::Eof + Self::Eof } } } - _ => SslError::Ssl(format!("{err}")), + _ => Self::Ssl(format!("{err}")), } } @@ -555,23 +555,23 @@ impl SslError { /// Convert to Python exception pub(super) fn into_py_err(self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { - SslError::WantRead => create_ssl_want_read_error(vm).upcast(), - SslError::WantWrite => create_ssl_want_write_error(vm).upcast(), - SslError::Timeout(msg) => timeout_error_msg(vm, msg).upcast(), - SslError::Syscall(msg) => { + Self::WantRead => create_ssl_want_read_error(vm).upcast(), + Self::WantWrite => create_ssl_want_write_error(vm).upcast(), + Self::Timeout(msg) => timeout_error_msg(vm, msg).upcast(), + Self::Syscall(msg) => { // SSLSyscallError with errno=SSL_ERROR_SYSCALL (5) create_ssl_syscall_error(vm, msg).upcast() } - SslError::Ssl(msg) => vm + Self::Ssl(msg) => vm .new_os_subtype_error( PySSLError::class(&vm.ctx).to_owned(), None, format!("SSL error: {msg}"), ) .upcast(), - SslError::ZeroReturn => create_ssl_zero_return_error(vm).upcast(), - SslError::Eof => create_ssl_eof_error(vm).upcast(), - SslError::PreauthData => { + Self::ZeroReturn => create_ssl_zero_return_error(vm).upcast(), + Self::Eof => create_ssl_eof_error(vm).upcast(), + Self::PreauthData => { // Non-TLS data received before handshake Self::create_ssl_error_with_reason( vm, @@ -580,20 +580,20 @@ impl SslError { "before TLS handshake with data", ) } - SslError::CertVerification(cert_err) => { + Self::CertVerification(cert_err) => { // Use the proper cert verification error creator create_ssl_cert_verification_error(vm, &cert_err).expect("unlikely to happen") } - SslError::Io(err) => err.into_pyexception(vm), - SslError::SniCallbackRestart => { + Self::Io(err) => err.into_pyexception(vm), + Self::SniCallbackRestart => { // This should be handled at PySSLSocket level unreachable!("SniCallbackRestart should not reach Python layer") } - SslError::Py(exc) => exc, - SslError::AlertReceived { lib, reason } => { + Self::Py(exc) => exc, + Self::AlertReceived { lib, reason } => { Self::create_ssl_error_from_codes(vm, lib, reason) } - SslError::NoCipherSuites => { + Self::NoCipherSuites => { // OpenSSL error: lib=20 (ERR_LIB_SSL), reason=193 (SSL_R_NO_SHARED_CIPHER) Self::create_ssl_error_from_codes(vm, ERR_LIB_SSL, SSL_R_NO_SHARED_CIPHER) } diff --git a/crates/stdlib/src/statistics.rs b/crates/stdlib/src/statistics.rs index 2f7eb85284..9c9e018fab 100644 --- a/crates/stdlib/src/statistics.rs +++ b/crates/stdlib/src/statistics.rs @@ -53,75 +53,86 @@ mod _statistics { if r <= 0.0 || r >= 1.0 { return None; } + let r = (-(r.ln())).sqrt(); - let num; - let den; - #[allow( + + #[expect( clippy::excessive_precision, reason = "piecewise polynomial coefficients match CPython" )] - if r <= 5.0 { + let (num, den) = if r <= 5.0 { let r = r - 1.6; // Hash sum-49.33206503301610289036 - num = ((((((7.74545014278341407640e-4 * r + 2.27238449892691845833e-2) * r - + 2.41780725177450611770e-1) - * r - + 1.27045825245236838258e+0) - * r - + 3.64784832476320460504e+0) - * r - + 5.76949722146069140550e+0) - * r - + 4.63033784615654529590e+0) - * r - + 1.42343711074968357734e+0; - den = ((((((1.05075007164441684324e-9 * r + 5.47593808499534494600e-4) * r - + 1.51986665636164571966e-2) - * r - + 1.48103976427480074590e-1) - * r - + 6.89767334985100004550e-1) - * r - + 1.67638483018380384940e+0) - * r - + 2.05319162663775882187e+0) - * r - + 1.0; + ( + // num + ((((((7.74545014278341407640e-4 * r + 2.27238449892691845833e-2) * r + + 2.41780725177450611770e-1) + * r + + 1.27045825245236838258e+0) + * r + + 3.64784832476320460504e+0) + * r + + 5.76949722146069140550e+0) + * r + + 4.63033784615654529590e+0) + * r + + 1.42343711074968357734e+0, + // den + ((((((1.05075007164441684324e-9 * r + 5.47593808499534494600e-4) * r + + 1.51986665636164571966e-2) + * r + + 1.48103976427480074590e-1) + * r + + 6.89767334985100004550e-1) + * r + + 1.67638483018380384940e+0) + * r + + 2.05319162663775882187e+0) + * r + + 1.0, + ) } else { let r = r - 5.0; // Hash sum-47.52583317549289671629 - num = ((((((2.01033439929228813265e-7 * r + 2.71155556874348757815e-5) * r - + 1.24266094738807843860e-3) - * r - + 2.65321895265761230930e-2) - * r - + 2.96560571828504891230e-1) - * r - + 1.78482653991729133580e+0) - * r - + 5.46378491116411436990e+0) - * r - + 6.65790464350110377720e+0; - den = ((((((2.04426310338993978564e-15 * r + 1.42151175831644588870e-7) * r - + 1.84631831751005468180e-5) - * r - + 7.86869131145613259100e-4) - * r - + 1.48753612908506148525e-2) - * r - + 1.36929880922735805310e-1) - * r - + 5.99832206555887937690e-1) - * r - + 1.0; - } + ( + // num + ((((((2.01033439929228813265e-7 * r + 2.71155556874348757815e-5) * r + + 1.24266094738807843860e-3) + * r + + 2.65321895265761230930e-2) + * r + + 2.96560571828504891230e-1) + * r + + 1.78482653991729133580e+0) + * r + + 5.46378491116411436990e+0) + * r + + 6.65790464350110377720e+0, + // den + ((((((2.04426310338993978564e-15 * r + 1.42151175831644588870e-7) * r + + 1.84631831751005468180e-5) + * r + + 7.86869131145613259100e-4) + * r + + 1.48753612908506148525e-2) + * r + + 1.36929880922735805310e-1) + * r + + 5.99832206555887937690e-1) + * r + + 1.0, + ) + }; + if den == 0.0 { return None; } + let mut x = num / den; if q < 0.0 { x = -x; } + Some(mu + (x * sigma)) } diff --git a/crates/vm/src/builtins/bytes.rs b/crates/vm/src/builtins/bytes.rs index 3b6b425c03..f28e8ddbbd 100644 --- a/crates/vm/src/builtins/bytes.rs +++ b/crates/vm/src/builtins/bytes.rs @@ -111,7 +111,7 @@ impl Constructor for PyBytes { if let OptionalArg::Present(ref obj) = options.source && options.encoding.is_missing() && options.errors.is_missing() - && let Ok(b) = obj.clone().downcast_exact::(vm) + && let Ok(b) = obj.clone().downcast_exact::(vm) { return Ok(b.into_pyref().into()); } @@ -126,7 +126,7 @@ impl Constructor for PyBytes { let bytes = bytes_method?.call((), vm)?; // If exact bytes type and __bytes__ returns bytes, use it directly if cls.is(vm.ctx.types.bytes_type) - && let Ok(b) = bytes.clone().downcast::() + && let Ok(b) = bytes.clone().downcast::() { return Ok(b.into()); } diff --git a/crates/vm/src/builtins/code.rs b/crates/vm/src/builtins/code.rs index 292366ff47..44d8c61342 100644 --- a/crates/vm/src/builtins/code.rs +++ b/crates/vm/src/builtins/code.rs @@ -198,7 +198,7 @@ impl From for PyObjectRef { impl From for Literal { fn from(obj: PyObjectRef) -> Self { - Literal(obj) + Self(obj) } } @@ -505,7 +505,7 @@ impl PyCode { } pub fn new_ref_with_bag(vm: &VirtualMachine, code: CodeObject) -> PyRef { - PyRef::new_ref(PyCode::new(code), vm.ctx.types.code_type.to_owned(), None) + PyRef::new_ref(Self::new(code), vm.ctx.types.code_type.to_owned(), None) } pub fn new_ref_from_bytecode(vm: &VirtualMachine, code: bytecode::CodeObject) -> PyRef { @@ -836,7 +836,7 @@ impl Constructor for PyCode { exceptiontable: args.exceptiontable.as_bytes().to_vec().into_boxed_slice(), }; - Ok(PyCode::new(code)) + Ok(Self::new(code)) } } @@ -1418,7 +1418,7 @@ impl PyCode { exceptiontable, }; - Ok(PyCode::new(new_code)) + Ok(Self::new(new_code)) } #[pymethod] diff --git a/crates/vm/src/builtins/complex.rs b/crates/vm/src/builtins/complex.rs index 764c0ea3c9..c54b3bc173 100644 --- a/crates/vm/src/builtins/complex.rs +++ b/crates/vm/src/builtins/complex.rs @@ -310,7 +310,7 @@ impl PyComplex { RCF: FnOnce(f64, Complex64) -> R, R: ToPyResult, { - let value = match (a.downcast_ref::(), b.downcast_ref::()) { + let value = match (a.downcast_ref::(), b.downcast_ref::()) { // complex + complex (Some(a_complex), Some(b_complex)) => cc_op(a_complex.value, b_complex.value), (Some(a_complex), None) => { diff --git a/crates/vm/src/builtins/descriptor.rs b/crates/vm/src/builtins/descriptor.rs index f8a54da119..350adf6d76 100644 --- a/crates/vm/src/builtins/descriptor.rs +++ b/crates/vm/src/builtins/descriptor.rs @@ -544,41 +544,41 @@ pub enum SlotFunc { impl core::fmt::Debug for SlotFunc { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { - SlotFunc::Init(_) => write!(f, "SlotFunc::Init(...)"), - SlotFunc::Hash(_) => write!(f, "SlotFunc::Hash(...)"), - SlotFunc::Str(_) => write!(f, "SlotFunc::Str(...)"), - SlotFunc::Repr(_) => write!(f, "SlotFunc::Repr(...)"), - SlotFunc::Iter(_) => write!(f, "SlotFunc::Iter(...)"), - SlotFunc::IterNext(_) => write!(f, "SlotFunc::IterNext(...)"), - SlotFunc::Call(_) => write!(f, "SlotFunc::Call(...)"), - SlotFunc::Del(_) => write!(f, "SlotFunc::Del(...)"), - SlotFunc::GetAttro(_) => write!(f, "SlotFunc::GetAttro(...)"), - SlotFunc::SetAttro(_) => write!(f, "SlotFunc::SetAttro(...)"), - SlotFunc::DelAttro(_) => write!(f, "SlotFunc::DelAttro(...)"), - SlotFunc::RichCompare(_, op) => write!(f, "SlotFunc::RichCompare(..., {op:?})"), - SlotFunc::DescrGet(_) => write!(f, "SlotFunc::DescrGet(...)"), - SlotFunc::DescrSet(_) => write!(f, "SlotFunc::DescrSet(...)"), - SlotFunc::DescrDel(_) => write!(f, "SlotFunc::DescrDel(...)"), + Self::Init(_) => write!(f, "SlotFunc::Init(...)"), + Self::Hash(_) => write!(f, "SlotFunc::Hash(...)"), + Self::Str(_) => write!(f, "SlotFunc::Str(...)"), + Self::Repr(_) => write!(f, "SlotFunc::Repr(...)"), + Self::Iter(_) => write!(f, "SlotFunc::Iter(...)"), + Self::IterNext(_) => write!(f, "SlotFunc::IterNext(...)"), + Self::Call(_) => write!(f, "SlotFunc::Call(...)"), + Self::Del(_) => write!(f, "SlotFunc::Del(...)"), + Self::GetAttro(_) => write!(f, "SlotFunc::GetAttro(...)"), + Self::SetAttro(_) => write!(f, "SlotFunc::SetAttro(...)"), + Self::DelAttro(_) => write!(f, "SlotFunc::DelAttro(...)"), + Self::RichCompare(_, op) => write!(f, "SlotFunc::RichCompare(..., {op:?})"), + Self::DescrGet(_) => write!(f, "SlotFunc::DescrGet(...)"), + Self::DescrSet(_) => write!(f, "SlotFunc::DescrSet(...)"), + Self::DescrDel(_) => write!(f, "SlotFunc::DescrDel(...)"), // Sequence sub-slots - SlotFunc::SeqLength(_) => write!(f, "SlotFunc::SeqLength(...)"), - SlotFunc::SeqConcat(_) => write!(f, "SlotFunc::SeqConcat(...)"), - SlotFunc::SeqRepeat(_) => write!(f, "SlotFunc::SeqRepeat(...)"), - SlotFunc::SeqItem(_) => write!(f, "SlotFunc::SeqItem(...)"), - SlotFunc::SeqSetItem(_) => write!(f, "SlotFunc::SeqSetItem(...)"), - SlotFunc::SeqDelItem(_) => write!(f, "SlotFunc::SeqDelItem(...)"), - SlotFunc::SeqContains(_) => write!(f, "SlotFunc::SeqContains(...)"), + Self::SeqLength(_) => write!(f, "SlotFunc::SeqLength(...)"), + Self::SeqConcat(_) => write!(f, "SlotFunc::SeqConcat(...)"), + Self::SeqRepeat(_) => write!(f, "SlotFunc::SeqRepeat(...)"), + Self::SeqItem(_) => write!(f, "SlotFunc::SeqItem(...)"), + Self::SeqSetItem(_) => write!(f, "SlotFunc::SeqSetItem(...)"), + Self::SeqDelItem(_) => write!(f, "SlotFunc::SeqDelItem(...)"), + Self::SeqContains(_) => write!(f, "SlotFunc::SeqContains(...)"), // Mapping sub-slots - SlotFunc::MapLength(_) => write!(f, "SlotFunc::MapLength(...)"), - SlotFunc::MapSubscript(_) => write!(f, "SlotFunc::MapSubscript(...)"), - SlotFunc::MapSetSubscript(_) => write!(f, "SlotFunc::MapSetSubscript(...)"), - SlotFunc::MapDelSubscript(_) => write!(f, "SlotFunc::MapDelSubscript(...)"), + Self::MapLength(_) => write!(f, "SlotFunc::MapLength(...)"), + Self::MapSubscript(_) => write!(f, "SlotFunc::MapSubscript(...)"), + Self::MapSetSubscript(_) => write!(f, "SlotFunc::MapSetSubscript(...)"), + Self::MapDelSubscript(_) => write!(f, "SlotFunc::MapDelSubscript(...)"), // Number sub-slots - SlotFunc::NumBoolean(_) => write!(f, "SlotFunc::NumBoolean(...)"), - SlotFunc::NumUnary(_) => write!(f, "SlotFunc::NumUnary(...)"), - SlotFunc::NumBinary(_) => write!(f, "SlotFunc::NumBinary(...)"), - SlotFunc::NumBinaryRight(_) => write!(f, "SlotFunc::NumBinaryRight(...)"), - SlotFunc::NumTernary(_) => write!(f, "SlotFunc::NumTernary(...)"), - SlotFunc::NumTernaryRight(_) => write!(f, "SlotFunc::NumTernaryRight(...)"), + Self::NumBoolean(_) => write!(f, "SlotFunc::NumBoolean(...)"), + Self::NumUnary(_) => write!(f, "SlotFunc::NumUnary(...)"), + Self::NumBinary(_) => write!(f, "SlotFunc::NumBinary(...)"), + Self::NumBinaryRight(_) => write!(f, "SlotFunc::NumBinaryRight(...)"), + Self::NumTernary(_) => write!(f, "SlotFunc::NumTernary(...)"), + Self::NumTernaryRight(_) => write!(f, "SlotFunc::NumTernaryRight(...)"), } } } @@ -587,22 +587,22 @@ impl SlotFunc { /// Call the wrapped slot function with proper type handling pub fn call(&self, obj: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { match self { - SlotFunc::Init(func) => { + Self::Init(func) => { func(obj, args, vm)?; Ok(vm.ctx.none()) } - SlotFunc::Hash(func) => { + Self::Hash(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err(vm.new_type_error("__hash__() takes no arguments (1 given)")); } let hash = func(&obj, vm)?; Ok(vm.ctx.new_int(hash).into()) } - SlotFunc::Repr(func) | SlotFunc::Str(func) => { + Self::Repr(func) | Self::Str(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { let name = match self { - SlotFunc::Repr(_) => "__repr__", - SlotFunc::Str(_) => "__str__", + Self::Repr(_) => "__repr__", + Self::Str(_) => "__str__", _ => unreachable!(), }; return Err(vm.new_type_error(format!("{name}() takes no arguments (1 given)"))); @@ -610,48 +610,48 @@ impl SlotFunc { let s = func(&obj, vm)?; Ok(s.into()) } - SlotFunc::Iter(func) => { + Self::Iter(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err(vm.new_type_error("__iter__() takes no arguments (1 given)")); } func(obj, vm) } - SlotFunc::IterNext(func) => { + Self::IterNext(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err(vm.new_type_error("__next__() takes no arguments (1 given)")); } func(&obj, vm).to_pyresult(vm) } - SlotFunc::Call(func) => func(&obj, args, vm), - SlotFunc::Del(func) => { + Self::Call(func) => func(&obj, args, vm), + Self::Del(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err(vm.new_type_error("__del__() takes no arguments (1 given)")); } func(&obj, vm)?; Ok(vm.ctx.none()) } - SlotFunc::GetAttro(func) => { + Self::GetAttro(func) => { let (name,): (PyRef,) = args.bind(vm)?; func(&obj, &name, vm) } - SlotFunc::SetAttro(func) => { + Self::SetAttro(func) => { let (name, value): (PyRef, PyObjectRef) = args.bind(vm)?; func(&obj, &name, PySetterValue::Assign(value), vm)?; Ok(vm.ctx.none()) } - SlotFunc::DelAttro(func) => { + Self::DelAttro(func) => { let (name,): (PyRef,) = args.bind(vm)?; func(&obj, &name, PySetterValue::Delete, vm)?; Ok(vm.ctx.none()) } - SlotFunc::RichCompare(func, op) => { + Self::RichCompare(func, op) => { let (other,): (PyObjectRef,) = args.bind(vm)?; func(&obj, &other, *op, vm).map(|r| match r { crate::function::Either::A(obj) => obj, crate::function::Either::B(cmp_val) => cmp_val.to_pyobject(vm), }) } - SlotFunc::DescrGet(func) => { + Self::DescrGet(func) => { let (instance, owner): (PyObjectRef, crate::function::OptionalArg) = args.bind(vm)?; let owner = owner.into_option(); @@ -662,94 +662,94 @@ impl SlotFunc { }; func(obj, instance_opt, owner, vm) } - SlotFunc::DescrSet(func) => { + Self::DescrSet(func) => { let (instance, value): (PyObjectRef, PyObjectRef) = args.bind(vm)?; func(&obj, instance, PySetterValue::Assign(value), vm)?; Ok(vm.ctx.none()) } - SlotFunc::DescrDel(func) => { + Self::DescrDel(func) => { let (instance,): (PyObjectRef,) = args.bind(vm)?; func(&obj, instance, PySetterValue::Delete, vm)?; Ok(vm.ctx.none()) } // Sequence sub-slots - SlotFunc::SeqLength(func) => { + Self::SeqLength(func) => { args.bind::<()>(vm)?; let len = func(obj.sequence_unchecked(), vm)?; Ok(vm.ctx.new_int(len).into()) } - SlotFunc::SeqConcat(func) => { + Self::SeqConcat(func) => { let (other,): (PyObjectRef,) = args.bind(vm)?; func(obj.sequence_unchecked(), &other, vm) } - SlotFunc::SeqRepeat(func) => { + Self::SeqRepeat(func) => { let (n,): (ArgSize,) = args.bind(vm)?; func(obj.sequence_unchecked(), n.into(), vm) } - SlotFunc::SeqItem(func) => { + Self::SeqItem(func) => { let (index,): (isize,) = args.bind(vm)?; func(obj.sequence_unchecked(), index, vm) } - SlotFunc::SeqSetItem(func) => { + Self::SeqSetItem(func) => { let (index, value): (isize, PyObjectRef) = args.bind(vm)?; func(obj.sequence_unchecked(), index, Some(value), vm)?; Ok(vm.ctx.none()) } - SlotFunc::SeqDelItem(func) => { + Self::SeqDelItem(func) => { let (index,): (isize,) = args.bind(vm)?; func(obj.sequence_unchecked(), index, None, vm)?; Ok(vm.ctx.none()) } - SlotFunc::SeqContains(func) => { + Self::SeqContains(func) => { let (item,): (PyObjectRef,) = args.bind(vm)?; let result = func(obj.sequence_unchecked(), &item, vm)?; Ok(vm.ctx.new_bool(result).into()) } // Mapping sub-slots - SlotFunc::MapLength(func) => { + Self::MapLength(func) => { args.bind::<()>(vm)?; let len = func(obj.mapping_unchecked(), vm)?; Ok(vm.ctx.new_int(len).into()) } - SlotFunc::MapSubscript(func) => { + Self::MapSubscript(func) => { let (key,): (PyObjectRef,) = args.bind(vm)?; func(obj.mapping_unchecked(), &key, vm) } - SlotFunc::MapSetSubscript(func) => { + Self::MapSetSubscript(func) => { let (key, value): (PyObjectRef, PyObjectRef) = args.bind(vm)?; func(obj.mapping_unchecked(), &key, Some(value), vm)?; Ok(vm.ctx.none()) } - SlotFunc::MapDelSubscript(func) => { + Self::MapDelSubscript(func) => { let (key,): (PyObjectRef,) = args.bind(vm)?; func(obj.mapping_unchecked(), &key, None, vm)?; Ok(vm.ctx.none()) } // Number sub-slots - SlotFunc::NumBoolean(func) => { + Self::NumBoolean(func) => { args.bind::<()>(vm)?; let result = func(obj.number(), vm)?; Ok(vm.ctx.new_bool(result).into()) } - SlotFunc::NumUnary(func) => { + Self::NumUnary(func) => { args.bind::<()>(vm)?; func(obj.number(), vm) } - SlotFunc::NumBinary(func) => { + Self::NumBinary(func) => { let (other,): (PyObjectRef,) = args.bind(vm)?; func(&obj, &other, vm) } - SlotFunc::NumBinaryRight(func) => { + Self::NumBinaryRight(func) => { let (other,): (PyObjectRef,) = args.bind(vm)?; func(&other, &obj, vm) // Swapped: other op obj } - SlotFunc::NumTernary(func) => { + Self::NumTernary(func) => { let (y, z): (PyObjectRef, crate::function::OptionalArg) = args.bind(vm)?; let z = z.unwrap_or_else(|| vm.ctx.none()); func(&obj, &y, &z, vm) } - SlotFunc::NumTernaryRight(func) => { + Self::NumTernaryRight(func) => { let (y, z): (PyObjectRef, crate::function::OptionalArg) = args.bind(vm)?; let z = z.unwrap_or_else(|| vm.ctx.none()); diff --git a/crates/vm/src/builtins/frame.rs b/crates/vm/src/builtins/frame.rs index 9dcbacec8e..62af017663 100644 --- a/crates/vm/src/builtins/frame.rs +++ b/crates/vm/src/builtins/frame.rs @@ -45,11 +45,11 @@ pub(crate) mod stack_analysis { impl Kind { fn from_i64(v: i64) -> Option { match v { - 1 => Some(Kind::Iterator), - 2 => Some(Kind::Except), - 3 => Some(Kind::Object), - 4 => Some(Kind::Null), - 5 => Some(Kind::Lasti), + 1 => Some(Self::Iterator), + 2 => Some(Self::Except), + 3 => Some(Self::Object), + 4 => Some(Self::Null), + 5 => Some(Self::Lasti), _ => None, } } @@ -722,7 +722,7 @@ impl Py { .iter() .find(|fp| { // SAFETY: the caller keeps the FrameRef alive while it's in the Vec - let py: &crate::Py = unsafe { fp.as_ref() }; + let py: &Self = unsafe { fp.as_ref() }; let ptr: *const Frame = &**py; core::ptr::eq(ptr, previous) }) diff --git a/crates/vm/src/builtins/interpolation.rs b/crates/vm/src/builtins/interpolation.rs index 25c5e034cd..8ce1714937 100644 --- a/crates/vm/src/builtins/interpolation.rs +++ b/crates/vm/src/builtins/interpolation.rs @@ -88,7 +88,7 @@ impl Constructor for PyInterpolation { .format_spec .unwrap_or_else(|| vm.ctx.empty_str.to_owned()); - Ok(PyInterpolation { + Ok(Self { value: args.value, expression, conversion, diff --git a/crates/vm/src/builtins/set.rs b/crates/vm/src/builtins/set.rs index 064521e7ce..f730049ff0 100644 --- a/crates/vm/src/builtins/set.rs +++ b/crates/vm/src/builtins/set.rs @@ -947,7 +947,7 @@ impl Constructor for PyFrozenSet { if cls.is(vm.ctx.types.frozenset_type) { // Return exact frozenset as-is if let OptionalArg::Present(ref input) = iterable - && let Ok(fs) = input.clone().downcast_exact::(vm) + && let Ok(fs) = input.clone().downcast_exact::(vm) { return Ok(fs.into_pyref().into()); } diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index 149fefff34..960c358130 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -1057,10 +1057,10 @@ impl PyStr { #[pymethod] fn __format__( - zelf: PyRef, + zelf: PyRef, spec: PyUtf8StrRef, vm: &VirtualMachine, - ) -> PyResult> { + ) -> PyResult> { if spec.is_empty() { return if zelf.class().is(vm.ctx.types.str_type) { Ok(zelf) @@ -1577,7 +1577,7 @@ impl PyStr { zelf.to_owned() } else { // Subclass, create a new exact str - PyStr::from(zelf.data.clone()).into_ref(&vm.ctx) + Self::from(zelf.data.clone()).into_ref(&vm.ctx) } } } diff --git a/crates/vm/src/builtins/template.rs b/crates/vm/src/builtins/template.rs index 51d4a1d47b..30812b4f17 100644 --- a/crates/vm/src/builtins/template.rs +++ b/crates/vm/src/builtins/template.rs @@ -89,7 +89,7 @@ impl Constructor for PyTemplate { strings.push(vm.ctx.empty_str.to_owned().into()); } - Ok(PyTemplate { + Ok(Self { strings: vm.ctx.new_tuple(strings), interpolations: vm.ctx.new_tuple(interpolations), }) @@ -123,7 +123,7 @@ impl PyTemplate { } fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult> { - let other = other.downcast_ref::().ok_or_else(|| { + let other = other.downcast_ref::().ok_or_else(|| { vm.new_type_error(format!( "can only concatenate Template (not '{}') to Template", other.class().name() @@ -173,7 +173,7 @@ impl PyTemplate { new_interps.push(interp.clone()); } - let template = PyTemplate { + let template = Self { strings: vm.ctx.new_tuple(new_strings), interpolations: vm.ctx.new_tuple(new_interps), }; diff --git a/crates/vm/src/builtins/tuple.rs b/crates/vm/src/builtins/tuple.rs index cfb7179409..81e7ce6f9f 100644 --- a/crates/vm/src/builtins/tuple.rs +++ b/crates/vm/src/builtins/tuple.rs @@ -108,9 +108,7 @@ impl PyPayload for PyTuple { #[inline] unsafe fn freelist_push(obj: *mut PyObject) -> bool { - let len = unsafe { &*(obj as *const crate::Py) } - .elements - .len(); + let len = unsafe { &*(obj as *const crate::Py) }.elements.len(); if len == 0 || len > TupleFreeList::MAX_SAVE_SIZE { return false; } @@ -225,7 +223,7 @@ impl Constructor for PyTuple { if cls.is(vm.ctx.types.tuple_type) { // Return exact tuple as-is if let OptionalArg::Present(ref input) = iterable - && let Ok(tuple) = input.clone().downcast_exact::(vm) + && let Ok(tuple) = input.clone().downcast_exact::(vm) { return Ok(tuple.into_pyref().into()); } diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index f516956810..8b920c2fee 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -506,14 +506,14 @@ impl PyType { let subclasses = self.subclasses.read(); for weak_ref in subclasses.iter() { if let Some(sub) = weak_ref.upgrade() { - sub.downcast_ref::().unwrap().modified(); + sub.downcast_ref::().unwrap().modified(); } } } pub fn new_simple_heap( name: &str, - base: &Py, + base: &Py, ctx: &Context, ) -> Result, String> { Self::new_heap( diff --git a/crates/vm/src/builtins/union.rs b/crates/vm/src/builtins/union.rs index a5c373ea3a..cb6dd0d655 100644 --- a/crates/vm/src/builtins/union.rs +++ b/crates/vm/src/builtins/union.rs @@ -379,18 +379,16 @@ impl PyUnion { needle, vm, )?; - let res; - if new_args.is_empty() { - res = make_union(&new_args, vm)?; + + Ok(if new_args.is_empty() { + make_union(&new_args, vm)? } else { let mut tmp = new_args[0].to_owned(); for arg in new_args.iter().skip(1) { tmp = vm._or(&tmp, arg)?; } - res = tmp; - } - - Ok(res) + tmp + }) } } diff --git a/crates/vm/src/datastack.rs b/crates/vm/src/datastack.rs index 40d94d0818..f2ffb74894 100644 --- a/crates/vm/src/datastack.rs +++ b/crates/vm/src/datastack.rs @@ -23,7 +23,7 @@ const ALIGN: usize = 16; #[repr(C)] struct DataStackChunk { /// Previous chunk in the linked list (NULL for the root chunk). - previous: *mut DataStackChunk, + previous: *mut Self, /// Total allocation size in bytes (including this header). size: usize, /// Saved `top` offset when a newer chunk was pushed. Used to restore diff --git a/crates/vm/src/exception_group.rs b/crates/vm/src/exception_group.rs index 24ab0275ff..198273a691 100644 --- a/crates/vm/src/exception_group.rs +++ b/crates/vm/src/exception_group.rs @@ -433,9 +433,9 @@ pub(super) mod types { impl ConditionMatcher { fn check(&self, exc: &PyObject, vm: &VirtualMachine) -> PyResult { match self { - ConditionMatcher::Type(typ) => Ok(exc.fast_isinstance(typ)), - ConditionMatcher::Types(types) => Ok(types.iter().any(|t| exc.fast_isinstance(t))), - ConditionMatcher::Callable(func) => { + Self::Type(typ) => Ok(exc.fast_isinstance(typ)), + Self::Types(types) => Ok(types.iter().any(|t| exc.fast_isinstance(t))), + Self::Callable(func) => { let result = func.call((exc.to_owned(),), vm)?; result.try_to_bool(vm) } diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index 107b354171..51ce99de82 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -1331,7 +1331,7 @@ impl OSErrorBuilder { pub(crate) fn build(self, vm: &VirtualMachine) -> PyRef { use types::PyOSError; - let OSErrorBuilder { + let Self { exc_type, errno, strerror, @@ -1889,7 +1889,7 @@ pub(super) mod types { // SAFETY: All OSError subclasses (FileNotFoundError, etc.) are // #[repr(transparent)] wrappers around PyOSError with identical memory layout #[allow(deprecated)] - let exc: &Py = zelf.downcast_ref::().unwrap(); + let exc: &Py = zelf.downcast_ref::().unwrap(); // Check if this is BlockingIOError - need to handle characters_written let is_blocking_io_error = diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index 64206f8dce..1bafe7f26a 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -835,7 +835,7 @@ impl Frame { } /// Get the previous frame pointer for signal-safe traceback walking. - pub fn previous_frame(&self) -> *const Frame { + pub fn previous_frame(&self) -> *const Self { self.previous.load(atomic::Ordering::Relaxed) } diff --git a/crates/vm/src/function/method.rs b/crates/vm/src/function/method.rs index 95635d0a0e..6c59172b63 100644 --- a/crates/vm/src/function/method.rs +++ b/crates/vm/src/function/method.rs @@ -10,7 +10,7 @@ use crate::{ bitflags::bitflags! { // METH_XXX flags in CPython - #[derive(Copy, Clone, Debug, PartialEq)] + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct PyMethodFlags: u32 { const VARARGS = 0x0001; const KEYWORDS = 0x0002; diff --git a/crates/vm/src/object/core.rs b/crates/vm/src/object/core.rs index 110325a9a9..837023fa38 100644 --- a/crates/vm/src/object/core.rs +++ b/crates/vm/src/object/core.rs @@ -812,7 +812,7 @@ unsafe impl Link for WeakLink { #[pyclass(name = "weakref", module = false)] #[derive(Debug)] pub struct PyWeak { - pointers: Pointers>, + pointers: Pointers>, /// Direct pointer to the referent object, null when dead. /// Equivalent to wr_object in PyWeakReference. wr_object: PyAtomic<*mut PyObject>, @@ -1376,7 +1376,7 @@ impl PyObject { /// Returns the first weakref in the weakref list, if any. pub(crate) fn get_weakrefs(&self) -> Option { let wrl = self.weak_ref_list()?; - let _lock = weakref_lock::lock(self as *const PyObject as usize); + let _lock = weakref_lock::lock(self as *const Self as usize); let head_ptr = wrl.head.load(Ordering::Relaxed); if head_ptr.is_null() { None @@ -1734,7 +1734,7 @@ impl PyObject { /// Uses the full traverse including dict and slots. pub fn gc_get_referents(&self) -> Vec { let mut result = Vec::new(); - self.0.traverse(&mut |child: &PyObject| { + self.0.traverse(&mut |child: &Self| { result.push(child.to_owned()); }); result @@ -1782,10 +1782,10 @@ impl PyObject { /// # Safety /// The returned pointers are only valid as long as the object is alive /// and its contents haven't been modified. - pub unsafe fn gc_get_referent_ptrs(&self) -> Vec> { + pub unsafe fn gc_get_referent_ptrs(&self) -> Vec> { let mut result = Vec::new(); // Traverse the entire object including dict and slots - self.0.traverse(&mut |child: &PyObject| { + self.0.traverse(&mut |child: &Self| { result.push(NonNull::from(child)); }); result @@ -1799,7 +1799,7 @@ impl PyObject { /// - ptr must be a valid pointer to a PyObject /// - The caller must have exclusive access (no other references exist) /// - This is only safe during GC when the object is unreachable - pub unsafe fn gc_clear_raw(ptr: *mut PyObject) -> Vec { + pub unsafe fn gc_clear_raw(ptr: *mut Self) -> Vec { let mut result = Vec::new(); let obj = unsafe { &*ptr }; @@ -1849,7 +1849,7 @@ impl PyObject { // SAFETY: During GC collection, this object is unreachable (gc_refs == 0), // meaning no other code has a reference to it. The only references are // internal cycle references which we're about to break. - unsafe { Self::gc_clear_raw(self as *const _ as *mut PyObject) } + unsafe { Self::gc_clear_raw(self as *const _ as *mut Self) } } /// Check if this object has clear capability (tp_clear) @@ -2319,7 +2319,7 @@ impl Py { debug_assert!(self.as_object().downcast_ref::().is_some()); // SAFETY: T is #[repr(transparent)] over T::Base, // so Py and Py have the same layout. - unsafe { &*(self as *const Py as *const Py) } + unsafe { &*(self as *const Self as *const Py) } } /// Converts `&Py` to `&Py` where U is an ancestor type. @@ -2330,7 +2330,7 @@ impl Py { { debug_assert!(T::static_type().is_subtype(U::static_type())); // SAFETY: T is a subtype of U, so Py can be viewed as Py. - unsafe { &*(self as *const Py as *const Py) } + unsafe { &*(self as *const Self as *const Py) } } } diff --git a/crates/vm/src/object/ext.rs b/crates/vm/src/object/ext.rs index f3170db98f..d400de29c3 100644 --- a/crates/vm/src/object/ext.rs +++ b/crates/vm/src/object/ext.rs @@ -40,19 +40,13 @@ Basically reference counting, but then done by rust. /// since exceptions are also python objects. pub type PyResult = Result; // A valid value, or an exception -impl fmt::Display for PyRef -where - T: PyPayload + fmt::Display, -{ +impl fmt::Display for PyRef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } -impl fmt::Display for Py -where - T: PyPayload + fmt::Display, -{ +impl fmt::Display for Py { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } diff --git a/crates/vm/src/protocol/number.rs b/crates/vm/src/protocol/number.rs index 3f1a0cba18..448ec85a43 100644 --- a/crates/vm/src/protocol/number.rs +++ b/crates/vm/src/protocol/number.rs @@ -268,8 +268,8 @@ impl PyNumberTernaryOp { vm: &VirtualMachine, ) -> Option<&'static crate::builtins::PyStrInterned> { Some(match self { - PyNumberTernaryOp::Power => identifier!(vm, __rpow__), - PyNumberTernaryOp::InplacePower => return None, + Self::Power => identifier!(vm, __rpow__), + Self::InplacePower => return None, }) } } diff --git a/crates/vm/src/stdlib/_abc.rs b/crates/vm/src/stdlib/_abc.rs index e0ba4e5c99..f9906956f9 100644 --- a/crates/vm/src/stdlib/_abc.rs +++ b/crates/vm/src/stdlib/_abc.rs @@ -43,7 +43,7 @@ mod _abc { #[pyclass(with(Constructor))] impl AbcData { fn new() -> Self { - AbcData { + Self { registry: PyRwLock::new(None), cache: PyRwLock::new(None), negative_cache: PyRwLock::new(None), @@ -68,7 +68,7 @@ mod _abc { _args: Self::Args, _vm: &VirtualMachine, ) -> PyResult { - Ok(AbcData::new()) + Ok(Self::new()) } } diff --git a/crates/vm/src/stdlib/_ast/constant.rs b/crates/vm/src/stdlib/_ast/constant.rs index 1030a037f1..b1a8a01568 100644 --- a/crates/vm/src/stdlib/_ast/constant.rs +++ b/crates/vm/src/stdlib/_ast/constant.rs @@ -86,8 +86,8 @@ pub(crate) enum ConstantLiteral { }, Bytes(Box<[u8]>), Int(ast::Int), - Tuple(Vec), - FrozenSet(Vec), + Tuple(Vec), + FrozenSet(Vec), Float(f64), Complex { real: f64, diff --git a/crates/vm/src/stdlib/_ast/pattern.rs b/crates/vm/src/stdlib/_ast/pattern.rs index 11f758f020..a383c25a6b 100644 --- a/crates/vm/src/stdlib/_ast/pattern.rs +++ b/crates/vm/src/stdlib/_ast/pattern.rs @@ -201,9 +201,9 @@ impl Node for ast::PatternMatchSingleton { impl Node for ast::Singleton { fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { match self { - ast::Singleton::None => vm.ctx.none(), - ast::Singleton::True => vm.ctx.new_bool(true).into(), - ast::Singleton::False => vm.ctx.new_bool(false).into(), + Self::None => vm.ctx.none(), + Self::True => vm.ctx.new_bool(true).into(), + Self::False => vm.ctx.new_bool(false).into(), } } @@ -213,11 +213,11 @@ impl Node for ast::Singleton { object: PyObjectRef, ) -> PyResult { if vm.is_none(&object) { - Ok(ast::Singleton::None) + Ok(Self::None) } else if object.is(&vm.ctx.true_value) { - Ok(ast::Singleton::True) + Ok(Self::True) } else if object.is(&vm.ctx.false_value) { - Ok(ast::Singleton::False) + Ok(Self::False) } else { Err(vm.new_value_error(format!( "Expected None, True, or False, got {:?}", diff --git a/crates/vm/src/stdlib/_ast/statement.rs b/crates/vm/src/stdlib/_ast/statement.rs index 32ee5273dc..4c78ad4b73 100644 --- a/crates/vm/src/stdlib/_ast/statement.rs +++ b/crates/vm/src/stdlib/_ast/statement.rs @@ -1250,15 +1250,16 @@ impl Node for ast::StmtPass { let start_row = location.start.row.get(); let start_col = location.start.column.get(); let mut end_row = location.end.row.get(); - let mut end_col = location.end.column.get(); // Align with CPython: when docstring optimization replaces a lone // docstring with `pass`, the end position is on the same line even if // it extends past the physical line length. - if end_row != start_row && _range.len() == TextSize::from(4) { + let end_col = if end_row != start_row && _range.len() == TextSize::from(4) { end_row = start_row; - end_col = start_col + 4; - } + start_col + 4 + } else { + location.end.column.get() + }; dict.set_item("lineno", _vm.ctx.new_int(start_row).into(), _vm) .unwrap(); diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index 11695f4e49..4c7f870867 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -332,7 +332,7 @@ impl PyCArrayType { // 3. Check for _as_parameter_ attribute if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return PyCArrayType::from_param(cls.as_object().to_owned(), as_parameter, vm); + return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); } Err(vm.new_type_error(format!( @@ -424,12 +424,12 @@ impl Constructor for PyCArray { // Create array with zero-initialized buffer let buffer = vec![0u8; total_size]; - let instance = PyCArray(PyCData::from_bytes_with_length(buffer, None, length)) + let instance = Self(PyCData::from_bytes_with_length(buffer, None, length)) .into_ref_with_type(vm, cls)?; // Initialize elements using setitem_by_index (Array_init pattern) for (i, value) in args.args.iter().enumerate() { - PyCArray::setitem_by_index(&instance, i as isize, value.clone(), vm)?; + Self::setitem_by_index(&instance, i as isize, value.clone(), vm)?; } Ok(instance.into()) @@ -446,7 +446,7 @@ impl Initializer for PyCArray { fn init(zelf: PyRef, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // Re-initialize array elements when __init__ is called for (i, value) in args.args.iter().enumerate() { - PyCArray::setitem_by_index(&zelf, i as isize, value.clone(), vm)?; + Self::setitem_by_index(&zelf, i as isize, value.clone(), vm)?; } Ok(()) } @@ -589,7 +589,7 @@ impl PyCArray { } } - fn getitem_by_index(zelf: &Py, i: isize, vm: &VirtualMachine) -> PyResult { + fn getitem_by_index(zelf: &Py, i: isize, vm: &VirtualMachine) -> PyResult { let stg = zelf.class().stg_info_opt(); let length = stg.as_ref().map_or(0, |i| i.length) as isize; let index = if i < 0 { length + i } else { i }; @@ -756,7 +756,7 @@ impl PyCArray { element_size: usize, type_code: Option<&str>, value: &PyObject, - zelf: &Py, + zelf: &Py, index: usize, vm: &VirtualMachine, ) -> PyResult<()> { @@ -885,7 +885,7 @@ impl PyCArray { } fn setitem_by_index( - zelf: &Py, + zelf: &Py, i: isize, value: PyObjectRef, vm: &VirtualMachine, diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index a301248181..d70178be4e 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -134,7 +134,7 @@ impl core::fmt::Debug for StgInfo { impl Default for StgInfo { fn default() -> Self { - StgInfo { + Self { initialized: false, size: 0, align: 1, @@ -155,7 +155,7 @@ impl Default for StgInfo { impl StgInfo { pub(crate) fn new(size: usize, align: usize) -> Self { - StgInfo { + Self { initialized: true, size, align, @@ -207,7 +207,7 @@ impl StgInfo { StgInfoFlags::empty() }; - StgInfo { + Self { initialized: true, size, align, @@ -476,7 +476,7 @@ pub(crate) struct PyCData { impl PyCData { /// Create from StgInfo (PyCData_MallocBuffer pattern) pub(crate) fn from_stg_info(stg_info: &StgInfo) -> Self { - PyCData { + Self { buffer: PyRwLock::new(Cow::Owned(vec![0u8; stg_info.size])), base: PyRwLock::new(None), base_offset: AtomicCell::new(0), @@ -489,7 +489,7 @@ impl PyCData { /// Create from existing bytes (copies data) pub(crate) fn from_bytes(data: Vec, objects: Option) -> Self { - PyCData { + Self { buffer: PyRwLock::new(Cow::Owned(data)), base: PyRwLock::new(None), base_offset: AtomicCell::new(0), @@ -506,7 +506,7 @@ impl PyCData { objects: Option, length: usize, ) -> Self { - PyCData { + Self { buffer: PyRwLock::new(Cow::Owned(data)), base: PyRwLock::new(None), base_offset: AtomicCell::new(0), @@ -527,7 +527,7 @@ impl PyCData { // = PyCData_AtAddress // SAFETY: Caller must ensure ptr is valid for the lifetime of returned PyCData let slice: &'static [u8] = unsafe { core::slice::from_raw_parts(ptr, size) }; - PyCData { + Self { buffer: PyRwLock::new(Cow::Borrowed(slice)), base: PyRwLock::new(None), base_offset: AtomicCell::new(0), @@ -550,7 +550,7 @@ impl PyCData { length: usize, data: Vec, ) -> Self { - PyCData { + Self { buffer: PyRwLock::new(Cow::Owned(data)), // Has its own buffer copy base: PyRwLock::new(Some(base_obj)), // But still tracks base base_offset: AtomicCell::new(offset), // And offset for writes @@ -577,7 +577,7 @@ impl PyCData { // = PyCData_FromBaseObj // SAFETY: ptr points into base_obj's buffer, kept alive via base reference let slice: &'static [u8] = unsafe { core::slice::from_raw_parts(ptr, size) }; - PyCData { + Self { buffer: PyRwLock::new(Cow::Borrowed(slice)), base: PyRwLock::new(Some(base_obj)), base_offset: AtomicCell::new(0), @@ -612,7 +612,7 @@ impl PyCData { .set_item("-1", source, vm) .expect("Failed to store buffer reference"); - PyCData { + Self { buffer: PyRwLock::new(Cow::Borrowed(slice)), base: PyRwLock::new(None), base_offset: AtomicCell::new(0), @@ -854,7 +854,7 @@ impl PyCData { let key = self.unique_key(index); if let Some(base_obj) = self.base.read().clone() { let root = Self::find_root_object(&base_obj); - if let Some(cdata) = root.downcast_ref::() { + if let Some(cdata) = root.downcast_ref::() { cdata.kept_refs.write().insert(key, obj); return; } @@ -865,7 +865,7 @@ impl PyCData { /// Find the root object (one without a base) by walking up the base chain fn find_root_object(obj: &PyObject) -> PyObjectRef { // Try to get base from different ctypes types - let base = if let Some(cdata) = obj.downcast_ref::() { + let base = if let Some(cdata) = obj.downcast_ref::() { cdata.base.read().clone() } else { None @@ -887,7 +887,7 @@ impl PyCData { vm: &VirtualMachine, ) -> PyResult<()> { // Get the objects dict from the object - let objects_lock = if let Some(cdata) = obj.downcast_ref::() { + let objects_lock = if let Some(cdata) = obj.downcast_ref::() { &cdata.objects } else { return Ok(()); // Unknown type, skip @@ -925,7 +925,7 @@ impl PyCData { /// Returns the _objects of the CData, or an empty dict if None. pub(crate) fn get_kept_objects(value: &PyObject, vm: &VirtualMachine) -> PyObjectRef { value - .downcast_ref::() + .downcast_ref::() .and_then(|cdata| cdata.objects.read().clone()) .unwrap_or_else(|| vm.ctx.new_dict().into()) } @@ -933,7 +933,7 @@ impl PyCData { /// Check if a value should be stored in _objects /// Returns true for ctypes objects and bytes (for c_char_p) pub(crate) fn should_keep_ref(value: &PyObject) -> bool { - value.downcast_ref::().is_some() || value.downcast_ref::().is_some() + value.downcast_ref::().is_some() || value.downcast_ref::().is_some() } /// PyCData_set @@ -1405,11 +1405,7 @@ impl PyCField { /// Create a new CField from an existing field with adjusted offset and index /// Used by MakeFields to promote anonymous fields - pub(crate) fn new_from_field( - fdescr: &PyCField, - index_offset: usize, - offset_delta: isize, - ) -> Self { + pub(crate) fn new_from_field(fdescr: &Self, index_offset: usize, offset_delta: isize) -> Self { Self { name: fdescr.name.clone(), offset: fdescr.offset + offset_delta, @@ -1556,7 +1552,7 @@ impl GetDescriptor for PyCField { vm: &VirtualMachine, ) -> PyResult { let zelf = zelf - .downcast::() + .downcast::() .map_err(|_| vm.new_type_error("expected CField"))?; // If obj is None, return the descriptor itself (class attribute access) @@ -1569,7 +1565,7 @@ impl GetDescriptor for PyCField { let size = zelf.get_byte_size(); // Get PyCData from obj (works for both Structure and Union) - let cdata = PyCField::get_cdata_from_obj(&obj, vm)?; + let cdata = Self::get_cdata_from_obj(&obj, vm)?; // PyCData_get cdata.get_field( @@ -1709,7 +1705,7 @@ impl PyCField { if vm.is_none(value) { return Ok((vec![0u8; size], None)); } - Ok((PyCField::value_to_bytes(value, size, vm), None)) + Ok((Self::value_to_bytes(value, size, vm), None)) } "Z" => { // c_wchar_p: store pointer to null-terminated wchar_t buffer @@ -1734,7 +1730,7 @@ impl PyCField { if vm.is_none(value) { return Ok((vec![0u8; size], None)); } - Ok((PyCField::value_to_bytes(value, size, vm), None)) + Ok((Self::value_to_bytes(value, size, vm), None)) } "P" => { // c_void_p: store integer as pointer @@ -1750,9 +1746,9 @@ impl PyCField { if vm.is_none(value) { return Ok((vec![0u8; size], None)); } - Ok((PyCField::value_to_bytes(value, size, vm), None)) + Ok((Self::value_to_bytes(value, size, vm), None)) } - _ => Ok((PyCField::value_to_bytes(value, size, vm), None)), + _ => Ok((Self::value_to_bytes(value, size, vm), None)), } } @@ -1827,7 +1823,7 @@ impl PyCField { vm: &VirtualMachine, ) -> PyResult<()> { let zelf = zelf - .downcast_ref::() + .downcast_ref::() .ok_or_else(|| vm.new_type_error("expected CField"))?; let offset = zelf.offset as usize; @@ -2071,18 +2067,18 @@ impl FfiArgValue { /// Create an Arg reference to this owned value pub(crate) fn as_arg(&self) -> libffi::middle::Arg<'_> { match self { - FfiArgValue::U8(v) => libffi::middle::Arg::new(v), - FfiArgValue::I8(v) => libffi::middle::Arg::new(v), - FfiArgValue::U16(v) => libffi::middle::Arg::new(v), - FfiArgValue::I16(v) => libffi::middle::Arg::new(v), - FfiArgValue::U32(v) => libffi::middle::Arg::new(v), - FfiArgValue::I32(v) => libffi::middle::Arg::new(v), - FfiArgValue::U64(v) => libffi::middle::Arg::new(v), - FfiArgValue::I64(v) => libffi::middle::Arg::new(v), - FfiArgValue::F32(v) => libffi::middle::Arg::new(v), - FfiArgValue::F64(v) => libffi::middle::Arg::new(v), - FfiArgValue::Pointer(v) => libffi::middle::Arg::new(v), - FfiArgValue::OwnedPointer(v, _) => libffi::middle::Arg::new(v), + Self::U8(v) => libffi::middle::Arg::new(v), + Self::I8(v) => libffi::middle::Arg::new(v), + Self::U16(v) => libffi::middle::Arg::new(v), + Self::I16(v) => libffi::middle::Arg::new(v), + Self::U32(v) => libffi::middle::Arg::new(v), + Self::I32(v) => libffi::middle::Arg::new(v), + Self::U64(v) => libffi::middle::Arg::new(v), + Self::I64(v) => libffi::middle::Arg::new(v), + Self::F32(v) => libffi::middle::Arg::new(v), + Self::F64(v) => libffi::middle::Arg::new(v), + Self::Pointer(v) => libffi::middle::Arg::new(v), + Self::OwnedPointer(v, _) => libffi::middle::Arg::new(v), } } } diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 4ed640270e..e188a67d8c 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -905,7 +905,7 @@ impl Constructor for PyCFuncPtr { let ptr_size = core::mem::size_of::(); if args.args.is_empty() { - return PyCFuncPtr { + return Self { _base: PyCData::from_bytes(vec![0u8; ptr_size], None), thunk: PyRwLock::new(None), callable: PyRwLock::new(None), @@ -952,7 +952,7 @@ impl Constructor for PyCFuncPtr { // args[2] is paramflags (tuple or None) let paramflags = args.args.get(2).filter(|arg| !vm.is_none(arg)).cloned(); - return PyCFuncPtr { + return Self { _base: PyCData::from_bytes(vec![0u8; ptr_size], None), thunk: PyRwLock::new(None), callable: PyRwLock::new(None), @@ -974,7 +974,7 @@ impl Constructor for PyCFuncPtr { // Check if first argument is an integer (function address) if let Ok(addr) = first_arg.try_int(vm) { let ptr_val = addr.as_bigint().to_usize().unwrap_or(0); - return PyCFuncPtr { + return Self { _base: PyCData::from_bytes(Self::make_ptr_buffer(ptr_val), None), thunk: PyRwLock::new(None), callable: PyRwLock::new(None), @@ -1045,7 +1045,7 @@ impl Constructor for PyCFuncPtr { 0 }; - return PyCFuncPtr { + return Self { _base: PyCData::from_bytes(Self::make_ptr_buffer(ptr_val), None), thunk: PyRwLock::new(None), callable: PyRwLock::new(None), @@ -1088,7 +1088,7 @@ impl Constructor for PyCFuncPtr { // Store the thunk as a Python object to keep it alive let thunk_ref: PyRef = thunk.into_ref(&vm.ctx); - return PyCFuncPtr { + return Self { _base: PyCData::from_bytes(Self::make_ptr_buffer(ptr_val), None), thunk: PyRwLock::new(Some(thunk_ref)), callable: PyRwLock::new(Some(first_arg.clone())), @@ -1805,7 +1805,7 @@ impl Callable for PyCFuncPtr { }; // 7. Get flags to check for use_last_error/use_errno - let flags = PyCFuncPtr::_flags_(zelf, vm); + let flags = Self::_flags_(zelf, vm); // 8. Call the function (with use_last_error/use_errno handling) #[cfg(not(windows))] diff --git a/crates/vm/src/stdlib/_ctypes/library.rs b/crates/vm/src/stdlib/_ctypes/library.rs index c662d32e1d..ac9059864d 100644 --- a/crates/vm/src/stdlib/_ctypes/library.rs +++ b/crates/vm/src/stdlib/_ctypes/library.rs @@ -41,7 +41,7 @@ impl SharedLibrary { /// Create a SharedLibrary from a raw dlopen handle (for pythonapi / dlopen(NULL)) #[cfg(unix)] pub(super) fn from_raw_handle(handle: *mut libc::c_void) -> Self { - SharedLibrary { + Self { lib: PyMutex::new(Some(unsafe { UnixLibrary::from_raw(handle).into() })), } } diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 3f05199894..71b8455b83 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -155,7 +155,7 @@ impl PyCPointerType { // 5. Check for _as_parameter_ attribute if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return PyCPointerType::from_param(cls.as_object().to_owned(), as_parameter, vm); + return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); } Err(vm.new_type_error(format!( @@ -266,9 +266,7 @@ impl Constructor for PyCPointer { let cdata = PyCData::from_bytes(vec![0u8; core::mem::size_of::()], None); // pointer instance has b_length set to 2 (for index 0 and 1) cdata.length.store(2); - PyCPointer(cdata) - .into_ref_with_type(vm, cls) - .map(Into::into) + Self(cdata).into_ref_with_type(vm, cls).map(Into::into) } fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index b7e2a2c035..e50985c2ab 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -488,7 +488,7 @@ impl PyCSimpleType { // 5. Check for _as_parameter_ attribute if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return PyCSimpleType::from_param(cls.as_object().to_owned(), as_parameter, vm); + return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); } // 6. Type-specific error messages @@ -1052,7 +1052,7 @@ impl Constructor for PyCSimple { let buffer = ptr.to_ne_bytes().to_vec(); let cdata = PyCData::from_bytes(buffer, Some(v.clone())); *cdata.base.write() = Some(kept_alive); - return PyCSimple(cdata).into_ref_with_type(vm, cls).map(Into::into); + return Self(cdata).into_ref_with_type(vm, cls).map(Into::into); } } else if _type_ == "Z" && let Some(s) = v.downcast_ref::() @@ -1060,7 +1060,7 @@ impl Constructor for PyCSimple { let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm); let buffer = ptr.to_ne_bytes().to_vec(); let cdata = PyCData::from_bytes(buffer, Some(holder)); - return PyCSimple(cdata).into_ref_with_type(vm, cls).map(Into::into); + return Self(cdata).into_ref_with_type(vm, cls).map(Into::into); } } @@ -1091,7 +1091,7 @@ impl Constructor for PyCSimple { None }; - PyCSimple(PyCData::from_bytes(buffer, objects)) + Self(PyCData::from_bytes(buffer, objects)) .into_ref_with_type(vm, cls) .map(Into::into) } @@ -1107,7 +1107,7 @@ impl Initializer for PyCSimple { fn init(zelf: PyRef, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // If an argument is provided, update the value if let Some(value) = args.0.into_option() { - PyCSimple::set_value(zelf.into(), value, vm)?; + Self::set_value(zelf.into(), value, vm)?; } Ok(()) } @@ -1128,7 +1128,7 @@ impl Representable for PyCSimple { if is_direct_simple { // Direct SimpleCData: "typename(repr(value))" - let value = PyCSimple::value(zelf.to_owned().into(), vm)?; + let value = Self::value(zelf.to_owned().into(), vm)?; let value_repr = value.repr(vm)?.to_string(); Ok(format!("{type_name}({value_repr})")) } else { @@ -1365,7 +1365,7 @@ impl PyCSimple { Ok(zelf.into()) } else { // Direct simple type (e.g., c_int): return value - PyCSimple::value(zelf.into(), vm) + Self::value(zelf.into(), vm) } } } diff --git a/crates/vm/src/stdlib/_ctypes/structure.rs b/crates/vm/src/stdlib/_ctypes/structure.rs index 1f515ce040..96321cd7d5 100644 --- a/crates/vm/src/stdlib/_ctypes/structure.rs +++ b/crates/vm/src/stdlib/_ctypes/structure.rs @@ -155,7 +155,7 @@ impl PyCStructType { // 2. Check for _as_parameter_ attribute if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return PyCStructType::from_param(cls.as_object().to_owned(), as_parameter, vm); + return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); } Err(vm.new_type_error(format!( @@ -622,7 +622,7 @@ impl SetAttr for PyCStructType { return Err(vm.new_attribute_error("cannot delete _fields_")); }; // Process fields (this will also set DICTFLAG_FINAL) - PyCStructType::process_fields(pytype, fields_value.clone(), vm)?; + Self::process_fields(pytype, fields_value.clone(), vm)?; // Set the _fields_ attribute on the type pytype .attributes @@ -695,7 +695,7 @@ impl Constructor for PyCStructure { // Initialize buffer with zeros using computed size let mut new_stg_info = StgInfo::new(total_size, total_align); new_stg_info.length = length; - PyCStructure(PyCData::from_stg_info(&new_stg_info)) + Self(PyCData::from_stg_info(&new_stg_info)) .into_ref_with_type(vm, cls) .map(Into::into) } @@ -776,8 +776,7 @@ impl Initializer for PyCStructure { // 1. Process positional arguments recursively through inheritance chain if !args.args.is_empty() { - let consumed = - PyCStructure::init_pos_args(&zelf, &cls, &args.args, &args.kwargs, 0, vm)?; + let consumed = Self::init_pos_args(&zelf, &cls, &args.args, &args.kwargs, 0, vm)?; if consumed < args.args.len() { return Err(vm.new_type_error("too many initializers")); diff --git a/crates/vm/src/stdlib/_ctypes/union.rs b/crates/vm/src/stdlib/_ctypes/union.rs index 43a829c89f..e0b4900cbd 100644 --- a/crates/vm/src/stdlib/_ctypes/union.rs +++ b/crates/vm/src/stdlib/_ctypes/union.rs @@ -403,7 +403,7 @@ impl PyCUnionType { // 3. Check for _as_parameter_ attribute if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return PyCUnionType::from_param(cls.as_object().to_owned(), as_parameter, vm); + return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); } Err(vm.new_type_error(format!( @@ -495,7 +495,7 @@ impl SetAttr for PyCUnionType { if attr_name.as_bytes() == b"_fields_" && let PySetterValue::Assign(fields_value) = value { - PyCUnionType::process_fields(pytype, fields_value, vm)?; + Self::process_fields(pytype, fields_value, vm)?; } return Ok(()); } @@ -506,7 +506,7 @@ impl SetAttr for PyCUnionType { if attr_name.as_bytes() == b"_fields_" && let PySetterValue::Assign(ref fields_value) = value { - PyCUnionType::process_fields(pytype, fields_value.clone(), vm)?; + Self::process_fields(pytype, fields_value.clone(), vm)?; } // Store in type's attributes dict @@ -564,7 +564,7 @@ impl Constructor for PyCUnion { // Initialize buffer with zeros using computed size let mut new_stg_info = StgInfo::new(total_size, total_align); new_stg_info.length = length; - PyCUnion(PyCData::from_stg_info(&new_stg_info)) + Self(PyCData::from_stg_info(&new_stg_info)) .into_ref_with_type(vm, cls) .map(Into::into) } @@ -647,7 +647,7 @@ impl Initializer for PyCUnion { // 1. Process positional arguments recursively through inheritance chain if !args.args.is_empty() { - let consumed = PyCUnion::init_pos_args(&zelf, &cls, &args.args, &args.kwargs, 0, vm)?; + let consumed = Self::init_pos_args(&zelf, &cls, &args.args, &args.kwargs, 0, vm)?; if consumed < args.args.len() { return Err(vm.new_type_error("too many initializers")); diff --git a/crates/vm/src/stdlib/_functools.rs b/crates/vm/src/stdlib/_functools.rs index 3ed2769d2e..3007a4d12a 100644 --- a/crates/vm/src/stdlib/_functools.rs +++ b/crates/vm/src/stdlib/_functools.rs @@ -88,12 +88,12 @@ mod _functools { return Ok(instance); } // Fallback: create a new instance (shouldn't happen for base type after module init) - Ok(PyPlaceholderType.into_pyobject(vm)) + Ok(Self.into_pyobject(vm)) } fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { // This is never called because we override slot_new - Ok(PyPlaceholderType) + Ok(Self) } } diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index 409761ad0f..a005652374 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -1988,7 +1988,7 @@ mod _io { impl Destructor for BufferedReader { fn slot_del(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - if let Some(buf) = zelf.downcast_ref::() { + if let Some(buf) = zelf.downcast_ref::() { buf.finalizing.store(true, Ordering::Relaxed); } iobase_finalize(zelf, vm); @@ -2092,7 +2092,7 @@ mod _io { impl Destructor for BufferedWriter { fn slot_del(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - if let Some(buf) = zelf.downcast_ref::() { + if let Some(buf) = zelf.downcast_ref::() { buf.finalizing.store(true, Ordering::Relaxed); } iobase_finalize(zelf, vm); @@ -2166,7 +2166,7 @@ mod _io { impl Destructor for BufferedRandom { fn slot_del(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - if let Some(buf) = zelf.downcast_ref::() { + if let Some(buf) = zelf.downcast_ref::() { buf.finalizing.store(true, Ordering::Relaxed); } iobase_finalize(zelf, vm); @@ -3823,7 +3823,7 @@ mod _io { #[pymethod] fn __reduce_ex__(zelf: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult { - if zelf.class().is(TextIOWrapper::static_type()) { + if zelf.class().is(Self::static_type()) { return Err( vm.new_type_error(format!("cannot pickle '{}' object", zelf.class().name())) ); @@ -3988,7 +3988,7 @@ mod _io { impl Destructor for TextIOWrapper { fn slot_del(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - if let Some(wrapper) = zelf.downcast_ref::() { + if let Some(wrapper) = zelf.downcast_ref::() { wrapper.finalizing.store(true, Ordering::Relaxed); } iobase_finalize(zelf, vm); @@ -4068,8 +4068,7 @@ mod _io { impl IterNext for TextIOWrapper { fn slot_iternext(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { // Set telling = false during iteration (matches CPython behavior) - let textio_ref: PyRef = - zelf.downcast_ref::().unwrap().to_owned(); + let textio_ref: PyRef = zelf.downcast_ref::().unwrap().to_owned(); { let mut textio = textio_ref.lock(vm)?; textio.telling = false; @@ -5974,7 +5973,7 @@ mod fileio { impl Destructor for FileIO { fn slot_del(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - if let Some(fileio) = zelf.downcast_ref::() { + if let Some(fileio) = zelf.downcast_ref::() { fileio.finalizing.store(true); } iobase_finalize(zelf, vm); @@ -6259,8 +6258,6 @@ mod winconsoleio { zelf.readable.store(readable); zelf.writable.store(writable); - let mut _name_wide: Option> = None; - if fd < 0 { // Get console type from name console_type = pyio_get_console_type(&nameobj, vm); @@ -6279,11 +6276,11 @@ mod winconsoleio { } let name_str = nameobj.str(vm)?; - let wide: Vec = name_str + let wide = name_str .as_wtf8() .encode_wide() .chain(core::iter::once(0)) - .collect(); + .collect::>(); let access = if writable { GENERIC_WRITE @@ -6334,8 +6331,6 @@ mod winconsoleio { } return Err(std::io::Error::last_os_error().to_pyexception(vm)); } - - _name_wide = Some(wide); } else { // When opened by fd, never close the fd (user owns it) zelf.closefd.store(false); @@ -7021,7 +7016,7 @@ mod winconsoleio { impl Destructor for WindowsConsoleIO { fn slot_del(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - if let Some(cio) = zelf.downcast_ref::() { + if let Some(cio) = zelf.downcast_ref::() { cio.finalizing.store(true); } iobase_finalize(zelf, vm); diff --git a/crates/vm/src/stdlib/_signal.rs b/crates/vm/src/stdlib/_signal.rs index 235d184edb..3c05f867d6 100644 --- a/crates/vm/src/stdlib/_signal.rs +++ b/crates/vm/src/stdlib/_signal.rs @@ -38,9 +38,9 @@ pub(crate) mod _signal { let fd: &crate::Py = obj.try_to_value(vm)?; match fd.try_to_primitive::(vm) { - Ok(fd) => Ok(WakeupFd(fd as _)), + Ok(fd) => Ok(Self(fd as _)), Err(e) => if (-fd.as_bigint()).is_one() { - Ok(WakeupFd(INVALID_WAKEUP)) + Ok(Self(INVALID_WAKEUP)) } else { Err(e) }, diff --git a/crates/vm/src/stdlib/_thread.rs b/crates/vm/src/stdlib/_thread.rs index 1203b2b393..c9589c1ec5 100644 --- a/crates/vm/src/stdlib/_thread.rs +++ b/crates/vm/src/stdlib/_thread.rs @@ -1456,9 +1456,7 @@ pub(crate) mod _thread { #[pyslot] fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { - ThreadHandle::new(vm) - .into_ref_with_type(vm, cls) - .map(Into::into) + Self::new(vm).into_ref_with_type(vm, cls).map(Into::into) } } diff --git a/crates/vm/src/stdlib/_winapi.rs b/crates/vm/src/stdlib/_winapi.rs index 941a294ca4..113d5bd2de 100644 --- a/crates/vm/src/stdlib/_winapi.rs +++ b/crates/vm/src/stdlib/_winapi.rs @@ -912,7 +912,7 @@ mod _winapi { unsafe { core::mem::zeroed() }; overlapped.hEvent = event; - Overlapped { + Self { inner: PyMutex::new(OverlappedInner { overlapped: Box::new(overlapped), handle, @@ -1022,7 +1022,7 @@ mod _winapi { _args: Self::Args, _vm: &VirtualMachine, ) -> PyResult { - Ok(Overlapped::new_with_handle(null_mut())) + Ok(Self::new_with_handle(null_mut())) } } diff --git a/crates/vm/src/stdlib/_wmi.rs b/crates/vm/src/stdlib/_wmi.rs index ce8898ae9f..7236c74809 100644 --- a/crates/vm/src/stdlib/_wmi.rs +++ b/crates/vm/src/stdlib/_wmi.rs @@ -24,7 +24,7 @@ mod wmi_ffi { impl VARIANT { pub(super) fn zeroed() -> Self { - VARIANT([0u64; 3]) + Self([0u64; 3]) } } diff --git a/crates/vm/src/stdlib/os.rs b/crates/vm/src/stdlib/os.rs index ad8d9af758..ea9918b91c 100644 --- a/crates/vm/src/stdlib/os.rs +++ b/crates/vm/src/stdlib/os.rs @@ -127,7 +127,7 @@ impl TryFromObject for crt_fd::Owned { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { warn_if_bool_fd(&obj, vm)?; let fd = crt_fd::Raw::try_from_object(vm, obj)?; - unsafe { crt_fd::Owned::try_from_raw(fd) }.map_err(|e| e.into_pyexception(vm)) + unsafe { Self::try_from_raw(fd) }.map_err(|e| e.into_pyexception(vm)) } } diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index aaa6612ea9..ca3a9a2dc4 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -376,7 +376,7 @@ pub mod module { // Flags for os_access bitflags! { - #[derive(Copy, Clone, Debug, PartialEq)] + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct AccessFlags: u8 { const F_OK = _os::F_OK; const R_OK = _os::R_OK; diff --git a/crates/vm/src/stdlib/pwd.rs b/crates/vm/src/stdlib/pwd.rs index 726c9ad7e5..b898625906 100644 --- a/crates/vm/src/stdlib/pwd.rs +++ b/crates/vm/src/stdlib/pwd.rs @@ -46,7 +46,7 @@ mod pwd { .into_string() .unwrap_or_else(|s| s.to_string_lossy().into_owned()) }; - PasswdData { + Self { pw_name: user.name, pw_passwd: cstr_lossy(user.passwd), pw_uid: user.uid.as_raw(), diff --git a/crates/vm/src/stdlib/typevar.rs b/crates/vm/src/stdlib/typevar.rs index 260cd8eaaf..81d32f852b 100644 --- a/crates/vm/src/stdlib/typevar.rs +++ b/crates/vm/src/stdlib/typevar.rs @@ -944,7 +944,7 @@ pub(crate) mod typevar { ) -> PyResult { op.eq_only(|| { if other.class().is(zelf.class()) - && let Some(other_args) = other.downcast_ref::() + && let Some(other_args) = other.downcast_ref::() { let eq = zelf.__origin__.rich_compare_bool( &other_args.__origin__, @@ -1007,7 +1007,7 @@ pub(crate) mod typevar { ) -> PyResult { op.eq_only(|| { if other.class().is(zelf.class()) - && let Some(other_kwargs) = other.downcast_ref::() + && let Some(other_kwargs) = other.downcast_ref::() { let eq = zelf.__origin__.rich_compare_bool( &other_kwargs.__origin__, diff --git a/crates/vm/src/stdlib/winreg.rs b/crates/vm/src/stdlib/winreg.rs index ffe6351409..4e0725141d 100644 --- a/crates/vm/src/stdlib/winreg.rs +++ b/crates/vm/src/stdlib/winreg.rs @@ -52,11 +52,11 @@ mod winreg { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { // Try PyHkey first if let Some(hkey_obj) = obj.downcast_ref::() { - return Ok(HKEYArg(hkey_obj.hkey.load())); + return Ok(Self(hkey_obj.hkey.load())); } // Then try int let handle = usize::try_from_object(vm, obj)?; - Ok(HKEYArg(handle as Registry::HKEY)) + Ok(Self(handle as Registry::HKEY)) } } diff --git a/crates/vm/src/types/slot.rs b/crates/vm/src/types/slot.rs index 63a053df59..c982811fc3 100644 --- a/crates/vm/src/types/slot.rs +++ b/crates/vm/src/types/slot.rs @@ -678,7 +678,7 @@ impl PyType { let Some(subclass) = weak_ref.upgrade() else { continue; }; - let Some(subclass) = subclass.downcast_ref::() else { + let Some(subclass) = subclass.downcast_ref::() else { continue; }; @@ -1527,14 +1527,14 @@ impl PyType { use crate::builtins::descriptor::PyWrapper; // Helper to check if a class is a subclass of another by checking MRO - let is_subclass_of = |subclass_mro: &[PyRef], superclass: &Py| -> bool { + let is_subclass_of = |subclass_mro: &[PyRef], superclass: &Py| -> bool { subclass_mro.iter().any(|c| c.is(superclass)) }; // Helper to extract slot from an attribute if it's a wrapper descriptor // and the wrapper's type is compatible with the given class. // bpo-37619: wrapper descriptor from wrong class should not be used directly. - let try_extract = |attr: &PyObjectRef, for_class_mro: &[PyRef]| -> Option { + let try_extract = |attr: &PyObjectRef, for_class_mro: &[PyRef]| -> Option { if attr.class().is(ctx.types.wrapper_descriptor_type) { attr.downcast_ref::().and_then(|wrapper| { // Only extract slot if for_class is a subclass of wrapper.typ diff --git a/crates/vm/src/vm/context.rs b/crates/vm/src/vm/context.rs index 2d03199f77..8d20e75070 100644 --- a/crates/vm/src/vm/context.rs +++ b/crates/vm/src/vm/context.rs @@ -297,7 +297,7 @@ impl Context { let ctx = PyRc::new(Self::init_genesis()); // SAFETY: ctx is heap-allocated via PyRc and will be stored in // the CONTEXT static cell, so the Context lives for 'static. - let ctx_ref: &'static Context = unsafe { &*PyRc::as_ptr(&ctx) }; + let ctx_ref: &'static Self = unsafe { &*PyRc::as_ptr(&ctx) }; crate::types::TypeZoo::extend(ctx_ref); crate::exceptions::ExceptionZoo::extend(ctx_ref); ctx diff --git a/crates/vm/src/vm/mod.rs b/crates/vm/src/vm/mod.rs index 6778a84684..44842a866a 100644 --- a/crates/vm/src/vm/mod.rs +++ b/crates/vm/src/vm/mod.rs @@ -1164,7 +1164,7 @@ impl VirtualMachine { // Get stderr once and reuse it let stderr = crate::stdlib::sys::get_stderr(self).ok(); - let write_to_stderr = |s: &str, stderr: &Option, vm: &VirtualMachine| { + let write_to_stderr = |s: &str, stderr: &Option, vm: &Self| { if let Some(stderr) = stderr { let _ = vm.call_method(stderr, "write", (s.to_owned(),)); } else { @@ -1398,7 +1398,7 @@ impl VirtualMachine { /// 2-pass module dict clearing (_PyModule_ClearDict algorithm). /// Pass 1: Set names starting with '_' (except __builtins__) to None. /// Pass 2: Set all remaining names (except __builtins__) to None. - pub(crate) fn module_clear_dict(dict: &Py, vm: &VirtualMachine) { + pub(crate) fn module_clear_dict(dict: &Py, vm: &Self) { let none = vm.ctx.none(); // Pass 1: names starting with '_' (except __builtins__) diff --git a/crates/vm/src/vm/thread.rs b/crates/vm/src/vm/thread.rs index 850015171f..a81396bff3 100644 --- a/crates/vm/src/vm/thread.rs +++ b/crates/vm/src/vm/thread.rs @@ -724,7 +724,7 @@ impl VirtualMachine { state: self.state.clone(), initialized: self.initialized, recursion_depth: Cell::new(0), - c_stack_soft_limit: Cell::new(VirtualMachine::calculate_c_stack_soft_limit()), + c_stack_soft_limit: Cell::new(Self::calculate_c_stack_soft_limit()), async_gen_firstiter: RefCell::new(None), async_gen_finalizer: RefCell::new(None), asyncio_running_loop: RefCell::new(None), diff --git a/crates/vm/src/vm/vm_object.rs b/crates/vm/src/vm/vm_object.rs index d599a781bd..8a7be140dc 100644 --- a/crates/vm/src/vm/vm_object.rs +++ b/crates/vm/src/vm/vm_object.rs @@ -53,15 +53,17 @@ impl VirtualMachine { pub(crate) fn flush_std(&self) -> i32 { let vm = self; - let mut status = 0; - if let Ok(stdout) = sys::get_stdout(vm) + let status = if let Ok(stdout) = sys::get_stdout(vm) && !vm.is_none(&stdout) && !vm.file_is_closed(&stdout) && let Err(e) = vm.call_method(&stdout, identifier!(vm, flush).as_str(), ()) { vm.run_unraisable(e, None, stdout); - status = -1; - } + -1 + } else { + 0 + }; + if let Ok(stderr) = sys::get_stderr(vm) && !vm.is_none(&stderr) && !vm.file_is_closed(&stderr) @@ -80,6 +82,7 @@ impl VirtualMachine { } } } + #[track_caller] pub fn expect_pyresult(&self, result: PyResult, msg: &str) -> T { match result { @@ -92,9 +95,11 @@ impl VirtualMachine { pub fn is_none(&self, obj: &PyObject) -> bool { obj.is(&self.ctx.none) } + pub fn option_if_none(&self, obj: PyObjectRef) -> Option { if self.is_none(&obj) { None } else { Some(obj) } } + pub fn unwrap_or_none(&self, obj: Option) -> PyObjectRef { obj.unwrap_or_else(|| self.ctx.none()) } diff --git a/crates/vm/src/vm/vm_ops.rs b/crates/vm/src/vm/vm_ops.rs index 9cc2853a09..d25e7119df 100644 --- a/crates/vm/src/vm/vm_ops.rs +++ b/crates/vm/src/vm/vm_ops.rs @@ -182,21 +182,20 @@ impl VirtualMachine { let slot_a = class_a.slots.as_number.left_binary_op(op_slot); let slot_a_addr = slot_a.map(|x| x as usize); let mut slot_b = None; - let left_b_addr; - - if !class_a.is(class_b) { + let left_b_addr = if class_a.is(class_b) { + slot_a_addr + } else { let slot_bb = class_b.slots.as_number.right_binary_op(op_slot); if slot_bb.map(|x| x as usize) != slot_a_addr { slot_b = slot_bb; } - left_b_addr = class_b + + class_b .slots .as_number .left_binary_op(op_slot) - .map(|x| x as usize); - } else { - left_b_addr = slot_a_addr; - } + .map(|x| x as usize) + }; if let Some(slot_a) = slot_a { if let Some(slot_bb) = slot_b @@ -305,21 +304,20 @@ impl VirtualMachine { let slot_a = class_a.slots.as_number.left_ternary_op(op_slot); let slot_a_addr = slot_a.map(|x| x as usize); let mut slot_b = None; - let left_b_addr; - - if !class_a.is(class_b) { + let left_b_addr = if class_a.is(class_b) { + slot_a_addr + } else { let slot_bb = class_b.slots.as_number.right_ternary_op(op_slot); if slot_bb.map(|x| x as usize) != slot_a_addr { slot_b = slot_bb; } - left_b_addr = class_b + + class_b .slots .as_number .left_ternary_op(op_slot) - .map(|x| x as usize); - } else { - left_b_addr = slot_a_addr; - } + .map(|x| x as usize) + }; if let Some(slot_a) = slot_a { if let Some(slot_bb) = slot_b diff --git a/crates/vm/src/windows.rs b/crates/vm/src/windows.rs index bb65ce29aa..1d858310ff 100644 --- a/crates/vm/src/windows.rs +++ b/crates/vm/src/windows.rs @@ -73,7 +73,7 @@ type HandleInt = isize; impl TryFromObject for WinHandle { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let handle = HandleInt::try_from_object(vm, obj)?; - Ok(WinHandle(handle as HANDLE)) + Ok(Self(handle as HANDLE)) } } diff --git a/crates/wasm/src/browser_module.rs b/crates/wasm/src/browser_module.rs index 59ca55f45c..445a54ed41 100644 --- a/crates/wasm/src/browser_module.rs +++ b/crates/wasm/src/browser_module.rs @@ -23,18 +23,19 @@ mod _browser { impl FetchResponseFormat { fn from_str(vm: &VirtualMachine, s: &str) -> PyResult { - match s { - "json" => Ok(FetchResponseFormat::Json), - "text" => Ok(FetchResponseFormat::Text), - "array_buffer" => Ok(FetchResponseFormat::ArrayBuffer), - _ => Err(vm.new_type_error("Unknown fetch response_format")), - } + Ok(match s { + "json" => Self::Json, + "text" => Self::Text, + "array_buffer" => Self::ArrayBuffer, + _ => return Err(vm.new_type_error("Unknown fetch response_format")), + }) } + fn get_response(&self, response: &web_sys::Response) -> Result { match self { - FetchResponseFormat::Json => response.json(), - FetchResponseFormat::Text => response.text(), - FetchResponseFormat::ArrayBuffer => response.array_buffer(), + Self::Json => response.json(), + Self::Text => response.text(), + Self::ArrayBuffer => response.array_buffer(), } } } diff --git a/crates/wasm/src/js_module.rs b/crates/wasm/src/js_module.rs index 7d53125204..84a5a37e4e 100644 --- a/crates/wasm/src/js_module.rs +++ b/crates/wasm/src/js_module.rs @@ -37,18 +37,25 @@ mod _js { extern "C" { #[wasm_bindgen(catch)] fn has_prop(target: &JsValue, prop: &JsValue) -> Result; + #[wasm_bindgen(catch)] fn get_prop(target: &JsValue, prop: &JsValue) -> Result; + #[wasm_bindgen(catch)] fn set_prop(target: &JsValue, prop: &JsValue, value: &JsValue) -> Result<(), JsValue>; + #[wasm_bindgen] fn type_of(a: &JsValue) -> String; + #[wasm_bindgen(catch)] fn instance_of(lhs: &JsValue, rhs: &JsValue) -> Result; + #[wasm_bindgen(catch)] fn call_func(func: &JsValue, args: &Array) -> Result; + #[wasm_bindgen(catch)] fn call_method(obj: &JsValue, method: &JsValue, args: &Array) -> Result; + #[wasm_bindgen] fn wrap_closure(closure: &JsValue) -> JsValue; } @@ -76,16 +83,16 @@ mod _js { impl TryFromObject for JsProperty { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { PyStrRef::try_from_object(vm, obj.clone()) - .map(JsProperty::Str) - .or_else(|_| PyJsValueRef::try_from_object(vm, obj).map(JsProperty::Js)) + .map(Self::Str) + .or_else(|_| PyJsValueRef::try_from_object(vm, obj).map(Self::Js)) } } impl JsProperty { fn into_js_value(self) -> JsValue { match self { - JsProperty::Str(s) => s.expect_str().into(), - JsProperty::Js(value) => value.value.clone(), + Self::Str(s) => s.expect_str().into(), + Self::Js(value) => value.value.clone(), } } } @@ -93,29 +100,29 @@ mod _js { #[pyclass(with(Representable))] impl PyJsValue { #[inline] - pub(crate) fn new(value: impl Into) -> PyJsValue { + pub(crate) fn new(value: impl Into) -> Self { let value = value.into(); - PyJsValue { value } + Self { value } } #[pymethod] - fn null(&self) -> PyJsValue { - PyJsValue::new(JsValue::NULL) + fn null(&self) -> Self { + Self::new(JsValue::NULL) } #[pymethod] - fn undefined(&self) -> PyJsValue { - PyJsValue::new(JsValue::UNDEFINED) + fn undefined(&self) -> Self { + Self::new(JsValue::UNDEFINED) } #[pymethod] - fn new_from_str(&self, s: PyStrRef) -> PyJsValue { - PyJsValue::new(s.expect_str()) + fn new_from_str(&self, s: PyStrRef) -> Self { + Self::new(s.expect_str()) } #[pymethod] - fn new_from_float(&self, n: PyRef) -> PyJsValue { - PyJsValue::new(n.to_f64()) + fn new_from_float(&self, n: PyRef) -> Self { + Self::new(n.to_f64()) } #[pymethod] @@ -129,7 +136,7 @@ mod _js { } #[pymethod] - fn new_object(&self, opts: NewObjectOptions, vm: &VirtualMachine) -> PyResult { + fn new_object(&self, opts: NewObjectOptions, vm: &VirtualMachine) -> PyResult { let value = if let Some(proto) = opts.prototype { if let Some(proto) = proto.value.dyn_ref::() { Object::create(proto) @@ -141,7 +148,8 @@ mod _js { } else { Object::new() }; - Ok(PyJsValue::new(value)) + + Ok(Self::new(value)) } #[pymethod] @@ -150,11 +158,11 @@ mod _js { } #[pymethod] - fn get_prop(&self, name: JsProperty, vm: &VirtualMachine) -> PyResult { + fn get_prop(&self, name: JsProperty, vm: &VirtualMachine) -> PyResult { let name = &name.into_js_value(); if has_prop(&self.value, name).map_err(|err| new_js_error(vm, err))? { get_prop(&self.value, name) - .map(PyJsValue::new) + .map(Self::new) .map_err(|err| new_js_error(vm, err)) } else { Err(vm.new_attribute_error(format!("No attribute {name:?} on JS value"))) @@ -178,17 +186,17 @@ mod _js { args: PosArgs, opts: CallOptions, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { let func = self .value .dyn_ref::() .ok_or_else(|| vm.new_type_error("JS value is not callable"))?; - let js_args = args.iter().map(|x| -> &PyJsValue { x }).collect::(); + let js_args = args.iter().map(|x| -> &Self { x }).collect::(); let res = match opts.this { Some(this) => Reflect::apply(func, &this.value, &js_args), None => call_func(func, &js_args), }; - res.map(PyJsValue::new).map_err(|err| new_js_error(vm, err)) + res.map(Self::new).map_err(|err| new_js_error(vm, err)) } #[pymethod] @@ -197,10 +205,10 @@ mod _js { name: JsProperty, args: PosArgs, vm: &VirtualMachine, - ) -> PyResult { - let js_args = args.iter().map(|x| -> &PyJsValue { x }).collect::(); + ) -> PyResult { + let js_args = args.iter().map(|x| -> &Self { x }).collect::(); call_method(&self.value, &name.into_js_value(), &js_args) - .map(PyJsValue::new) + .map(Self::new) .map_err(|err| new_js_error(vm, err)) } @@ -210,7 +218,7 @@ mod _js { args: PosArgs, opts: NewObjectOptions, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { let ctor = self .value .dyn_ref::() @@ -219,7 +227,7 @@ mod _js { .prototype .as_ref() .and_then(|proto| proto.value.dyn_ref::()); - let js_args = args.iter().map(|x| -> &PyJsValue { x }).collect::(); + let js_args = args.iter().map(|x| -> &Self { x }).collect::(); let constructed_result = if let Some(proto) = proto { Reflect::construct_with_new_target(ctor, &js_args, proto) } else { @@ -227,7 +235,7 @@ mod _js { }; constructed_result - .map(PyJsValue::new) + .map(Self::new) .map_err(|err| new_js_error(vm, err)) } @@ -333,7 +341,7 @@ mod _js { Closure::once(Box::new(f)) }; let wrapped = PyJsValue::new(wrap_closure(closure.as_ref())).into_ref(&vm.ctx); - Ok(JsClosure { + Ok(Self { closure: Some((closure, wrapped)).into(), destroyed: false.into(), detached: false.into(), @@ -347,10 +355,12 @@ mod _js { .as_ref() .map(|(_, js_val)| js_val.clone()) } + #[pygetset] fn destroyed(&self) -> bool { self.destroyed.get() } + #[pygetset] fn detached(&self) -> bool { self.detached.get() @@ -365,6 +375,7 @@ mod _js { self.destroyed.set(true); Ok(()) } + #[pymethod] fn detach(&self, vm: &VirtualMachine) -> PyResult { let (closure, js_val) = self.closure.replace(None).ok_or_else(|| { @@ -393,17 +404,17 @@ mod _js { #[pyclass] impl PyPromise { - pub(crate) fn new(value: Promise) -> PyPromise { - PyPromise { + pub(crate) fn new(value: Promise) -> Self { + Self { value: PromiseKind::Js(value), } } - pub(crate) fn from_future(future: F) -> PyPromise + pub(crate) fn from_future(future: F) -> Self where F: future::Future> + 'static, { - PyPromise::new(future_to_promise(future)) + Self::new(future_to_promise(future)) } pub(crate) fn as_js(&self, vm: &VirtualMachine) -> Promise { @@ -476,7 +487,7 @@ mod _js { on_fulfill: OptionalOption, on_reject: OptionalOption, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { let (on_fulfill, on_reject) = (on_fulfill.flatten(), on_reject.flatten()); if on_fulfill.is_none() && on_reject.is_none() { return Ok(self.clone()); @@ -511,7 +522,7 @@ mod _js { } }; - Ok(PyPromise::from_future(ret_future)) + Ok(Self::from_future(ret_future)) } PromiseKind::PyProm { then } => Self::cast_result( then.call( @@ -539,7 +550,7 @@ mod _js { &self, on_reject: OptionalOption, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { self.then(OptionalArg::Present(None), on_reject, vm) } diff --git a/crates/wasm/src/vm_class.rs b/crates/wasm/src/vm_class.rs index 1d0b8701c3..cface5b386 100644 --- a/crates/wasm/src/vm_class.rs +++ b/crates/wasm/src/vm_class.rs @@ -37,7 +37,7 @@ mod _window { } impl StoredVirtualMachine { - fn new(id: String, inject_browser_module: bool) -> StoredVirtualMachine { + fn new(id: String, inject_browser_module: bool) -> Self { let mut settings = Settings::default(); settings.allow_external_library = false; @@ -71,7 +71,7 @@ impl StoredVirtualMachine { let scope = interp.enter(|vm| vm.new_scope_with_builtins()); - StoredVirtualMachine { + Self { interp, scope, held_objects: RefCell::new(Vec::new()),