From 211252f1972bdd36eff85a515f7f4a4e8595a503 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:30:46 +0300 Subject: [PATCH 01/11] Use `Self` in derive-impl --- derive-impl/src/compile_bytecode.rs | 4 ++-- derive-impl/src/error.rs | 16 ++++++++-------- derive-impl/src/from_args.rs | 14 +++++++------- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/derive-impl/src/compile_bytecode.rs b/derive-impl/src/compile_bytecode.rs index fc349a7ed4..edd746f1e1 100644 --- a/derive-impl/src/compile_bytecode.rs +++ b/derive-impl/src/compile_bytecode.rs @@ -234,7 +234,7 @@ impl CompilationSource { } impl PyCompileArgs { - fn parse(input: TokenStream, allow_dir: bool) -> Result { + fn parse(input: TokenStream, allow_dir: bool) -> Result { let mut module_name = None; let mut mode = None; let mut source: Option = None; @@ -307,7 +307,7 @@ impl PyCompileArgs { ) })?; - Ok(PyCompileArgs { + Ok(Self { source, mode: mode.unwrap_or(Mode::Exec), module_name: module_name.unwrap_or_else(|| "frozen".to_owned()), diff --git a/derive-impl/src/error.rs b/derive-impl/src/error.rs index 2313e529a9..2fdf7a4b4a 100644 --- a/derive-impl/src/error.rs +++ b/derive-impl/src/error.rs @@ -75,8 +75,8 @@ enum Repr { } impl Diagnostic { - pub fn error>(text: T) -> Diagnostic { - Diagnostic { + pub fn error>(text: T) -> Self { + Self { inner: Repr::Single { text: text.into(), span: None, @@ -84,8 +84,8 @@ impl Diagnostic { } } - pub(crate) fn spans_error>(spans: (Span, Span), text: T) -> Diagnostic { - Diagnostic { + pub(crate) fn spans_error>(spans: (Span, Span), text: T) -> Self { + Self { inner: Repr::Single { text: text.into(), span: Some(spans), @@ -93,11 +93,11 @@ impl Diagnostic { } } - pub fn from_vec(diagnostics: Vec) -> Result<(), Diagnostic> { + pub fn from_vec(diagnostics: Vec) -> Result<(), Self> { if diagnostics.is_empty() { Ok(()) } else { - Err(Diagnostic { + Err(Self { inner: Repr::Multi { diagnostics }, }) } @@ -113,8 +113,8 @@ impl Diagnostic { } impl From for Diagnostic { - fn from(err: Error) -> Diagnostic { - Diagnostic { + fn from(err: Error) -> Self { + Self { inner: Repr::SynError(err), } } diff --git a/derive-impl/src/from_args.rs b/derive-impl/src/from_args.rs index 9b06da85e3..8339be5df6 100644 --- a/derive-impl/src/from_args.rs +++ b/derive-impl/src/from_args.rs @@ -14,12 +14,12 @@ enum ParameterKind { } impl ParameterKind { - fn from_ident(ident: &Ident) -> Option { + fn from_ident(ident: &Ident) -> Option { match ident.to_string().as_str() { - "positional" => Some(ParameterKind::PositionalOnly), - "any" => Some(ParameterKind::PositionalOrKeyword), - "named" => Some(ParameterKind::KeywordOnly), - "flatten" => Some(ParameterKind::Flatten), + "positional" => Some(Self::PositionalOnly), + "any" => Some(Self::PositionalOrKeyword), + "named" => Some(Self::KeywordOnly), + "flatten" => Some(Self::Flatten), _ => None, } } @@ -34,7 +34,7 @@ struct ArgAttribute { type DefaultValue = Option; impl ArgAttribute { - fn from_attribute(attr: &Attribute) -> Option> { + fn from_attribute(attr: &Attribute) -> Option> { if !attr.path().is_ident("pyarg") { return None; } @@ -52,7 +52,7 @@ impl ArgAttribute { either 'positional', 'any', 'named', or 'flatten'.", ) })?; - arg_attr = Some(ArgAttribute { + arg_attr = Some(Self { name: None, kind, default: None, From 9a4ba95ed8e00146a3d2c50b495ef673d4c008d2 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:37:02 +0300 Subject: [PATCH 02/11] compiler --- compiler/codegen/src/compile.rs | 2 +- compiler/codegen/src/ir.rs | 6 ++-- compiler/codegen/src/lib.rs | 54 ++++++++++++++--------------- compiler/codegen/src/symboltable.rs | 16 ++++----- 4 files changed, 39 insertions(+), 39 deletions(-) diff --git a/compiler/codegen/src/compile.rs b/compiler/codegen/src/compile.rs index 2bdc5de393..caca71cef8 100644 --- a/compiler/codegen/src/compile.rs +++ b/compiler/codegen/src/compile.rs @@ -283,7 +283,7 @@ impl Default for PatternContext { impl PatternContext { pub fn new() -> Self { - PatternContext { + Self { stores: Vec::new(), allow_irrefutable: false, fail_pop: Vec::new(), diff --git a/compiler/codegen/src/ir.rs b/compiler/codegen/src/ir.rs index bb1f8b7564..7acd9d7f6a 100644 --- a/compiler/codegen/src/ir.rs +++ b/compiler/codegen/src/ir.rs @@ -11,7 +11,7 @@ use rustpython_compiler_core::bytecode::{ #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct BlockIdx(pub u32); impl BlockIdx { - pub const NULL: BlockIdx = BlockIdx(u32::MAX); + pub const NULL: Self = Self(u32::MAX); const fn idx(self) -> usize { self.0 as usize } @@ -58,7 +58,7 @@ pub struct Block { } impl Default for Block { fn default() -> Self { - Block { + Self { instructions: Vec::new(), next: BlockIdx::NULL, } @@ -91,7 +91,7 @@ impl CodeInfo { let max_stackdepth = self.max_stackdepth()?; let cell2arg = self.cell2arg(); - let CodeInfo { + let Self { flags, posonlyarg_count, arg_count, diff --git a/compiler/codegen/src/lib.rs b/compiler/codegen/src/lib.rs index 3ef6a7456f..9b444de994 100644 --- a/compiler/codegen/src/lib.rs +++ b/compiler/codegen/src/lib.rs @@ -28,39 +28,39 @@ pub trait ToPythonName { impl ToPythonName for Expr { fn python_name(&self) -> &'static str { match self { - Expr::BoolOp { .. } | Expr::BinOp { .. } | Expr::UnaryOp { .. } => "operator", - Expr::Subscript { .. } => "subscript", - Expr::Await { .. } => "await expression", - Expr::Yield { .. } | Expr::YieldFrom { .. } => "yield expression", - Expr::Compare { .. } => "comparison", - Expr::Attribute { .. } => "attribute", - Expr::Call { .. } => "function call", - Expr::BooleanLiteral(b) => { + Self::BoolOp { .. } | Self::BinOp { .. } | Self::UnaryOp { .. } => "operator", + Self::Subscript { .. } => "subscript", + Self::Await { .. } => "await expression", + Self::Yield { .. } | Self::YieldFrom { .. } => "yield expression", + Self::Compare { .. } => "comparison", + Self::Attribute { .. } => "attribute", + Self::Call { .. } => "function call", + Self::BooleanLiteral(b) => { if b.value { "True" } else { "False" } } - Expr::EllipsisLiteral(_) => "ellipsis", - Expr::NoneLiteral(_) => "None", - Expr::NumberLiteral(_) | Expr::BytesLiteral(_) | Expr::StringLiteral(_) => "literal", - Expr::Tuple(_) => "tuple", - Expr::List { .. } => "list", - Expr::Dict { .. } => "dict display", - Expr::Set { .. } => "set display", - Expr::ListComp { .. } => "list comprehension", - Expr::DictComp { .. } => "dict comprehension", - Expr::SetComp { .. } => "set comprehension", - Expr::Generator { .. } => "generator expression", - Expr::Starred { .. } => "starred", - Expr::Slice { .. } => "slice", - Expr::FString { .. } => "f-string expression", - Expr::Name { .. } => "name", - Expr::Lambda { .. } => "lambda", - Expr::If { .. } => "conditional expression", - Expr::Named { .. } => "named expression", - Expr::IpyEscapeCommand(_) => todo!(), + Self::EllipsisLiteral(_) => "ellipsis", + Self::NoneLiteral(_) => "None", + Self::NumberLiteral(_) | Self::BytesLiteral(_) | Self::StringLiteral(_) => "literal", + Self::Tuple(_) => "tuple", + Self::List { .. } => "list", + Self::Dict { .. } => "dict display", + Self::Set { .. } => "set display", + Self::ListComp { .. } => "list comprehension", + Self::DictComp { .. } => "dict comprehension", + Self::SetComp { .. } => "set comprehension", + Self::Generator { .. } => "generator expression", + Self::Starred { .. } => "starred", + Self::Slice { .. } => "slice", + Self::FString { .. } => "f-string expression", + Self::Name { .. } => "name", + Self::Lambda { .. } => "lambda", + Self::If { .. } => "conditional expression", + Self::Named { .. } => "named expression", + Self::IpyEscapeCommand(_) => todo!(), } } } diff --git a/compiler/codegen/src/symboltable.rs b/compiler/codegen/src/symboltable.rs index 385abfd72f..c1c75a5d53 100644 --- a/compiler/codegen/src/symboltable.rs +++ b/compiler/codegen/src/symboltable.rs @@ -49,7 +49,7 @@ pub struct SymbolTable { impl SymbolTable { fn new(name: String, typ: SymbolTableType, line_number: u32, is_nested: bool) -> Self { - SymbolTable { + Self { name, typ, line_number, @@ -87,11 +87,11 @@ pub enum SymbolTableType { impl fmt::Display for SymbolTableType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - SymbolTableType::Module => write!(f, "module"), - SymbolTableType::Class => write!(f, "class"), - SymbolTableType::Function => write!(f, "function"), - SymbolTableType::Comprehension => write!(f, "comprehension"), - SymbolTableType::TypeParams => write!(f, "type parameter"), + Self::Module => write!(f, "module"), + Self::Class => write!(f, "class"), + Self::Function => write!(f, "function"), + Self::Comprehension => write!(f, "comprehension"), + Self::TypeParams => write!(f, "type parameter"), // TODO missing types from the C implementation // if self._table.type == _symtable.TYPE_ANNOTATION: // return "annotation" @@ -154,7 +154,7 @@ pub struct Symbol { impl Symbol { fn new(name: &str) -> Self { - Symbol { + Self { name: name.to_owned(), // table, scope: SymbolScope::Unknown, @@ -293,7 +293,7 @@ impl SymbolTableAnalyzer { let mut info = (symbols, symbol_table.typ); self.tables.with_append(&mut info, |list| { - let inner_scope = unsafe { &mut *(list as *mut _ as *mut SymbolTableAnalyzer) }; + let inner_scope = unsafe { &mut *(list as *mut _ as *mut Self) }; // Analyze sub scopes: for sub_table in sub_tables.iter_mut() { inner_scope.analyze_symbol_table(sub_table)?; From b8957d236c54a8941a5a0455840b8ac9a5acc183 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:37:14 +0300 Subject: [PATCH 03/11] vm --- vm/src/buffer.rs | 22 ++-- vm/src/builtins/asyncgenerator.rs | 4 +- vm/src/builtins/bool.rs | 2 +- vm/src/builtins/builtin_func.rs | 2 +- vm/src/builtins/bytearray.rs | 20 ++-- vm/src/builtins/bytes.rs | 22 ++-- vm/src/builtins/classmethod.rs | 2 +- vm/src/builtins/code.rs | 8 +- vm/src/builtins/complex.rs | 8 +- vm/src/builtins/coroutine.rs | 2 +- vm/src/builtins/dict.rs | 16 +-- vm/src/builtins/enumerate.rs | 2 +- vm/src/builtins/float.rs | 6 +- vm/src/builtins/function.rs | 12 +-- vm/src/builtins/generator.rs | 2 +- vm/src/builtins/genericalias.rs | 6 +- vm/src/builtins/int.rs | 52 +++++----- vm/src/builtins/iter.rs | 4 +- vm/src/builtins/list.rs | 6 +- vm/src/builtins/map.rs | 2 +- vm/src/builtins/mappingproxy.rs | 4 +- vm/src/builtins/memory.rs | 6 +- vm/src/builtins/module.rs | 4 +- vm/src/builtins/object.rs | 2 +- vm/src/builtins/property.rs | 8 +- vm/src/builtins/range.rs | 16 +-- vm/src/builtins/set.rs | 26 ++--- vm/src/builtins/slice.rs | 6 +- vm/src/builtins/staticmethod.rs | 2 +- vm/src/builtins/str.rs | 62 +++++------ vm/src/builtins/super.rs | 4 +- vm/src/builtins/traceback.rs | 4 +- vm/src/builtins/tuple.rs | 2 +- vm/src/builtins/type.rs | 16 +-- vm/src/builtins/weakproxy.rs | 2 +- vm/src/builtins/zip.rs | 2 +- vm/src/bytes_inner.rs | 44 ++++---- vm/src/codecs.rs | 6 +- vm/src/convert/try_from.rs | 4 +- vm/src/coroutine.rs | 6 +- vm/src/dict_inner.rs | 10 +- vm/src/exceptions.rs | 8 +- vm/src/format.rs | 22 ++-- vm/src/frame.rs | 6 +- vm/src/function/argument.rs | 36 +++---- vm/src/function/arithmetic.rs | 4 +- vm/src/function/buffer.rs | 2 +- vm/src/function/either.rs | 2 +- vm/src/function/fspath.rs | 20 ++-- vm/src/function/number.rs | 4 +- vm/src/function/protocol.rs | 6 +- vm/src/intern.rs | 2 +- vm/src/object/core.rs | 24 ++--- vm/src/object/ext.rs | 2 +- vm/src/object/traverse.rs | 4 +- vm/src/object/traverse_object.rs | 4 +- vm/src/ospath.rs | 8 +- vm/src/protocol/buffer.rs | 2 +- vm/src/protocol/iter.rs | 10 +- vm/src/protocol/mapping.rs | 2 +- vm/src/protocol/number.rs | 4 +- vm/src/protocol/object.rs | 18 ++-- vm/src/protocol/sequence.rs | 2 +- vm/src/py_io.rs | 2 +- vm/src/scope.rs | 8 +- vm/src/sequence.rs | 2 +- vm/src/sliceable.rs | 2 +- vm/src/stdlib/ast/basic.rs | 2 +- vm/src/stdlib/ast/exception.rs | 6 +- vm/src/stdlib/ast/expression.rs | 8 +- vm/src/stdlib/ast/statement.rs | 150 +++++++++++++-------------- vm/src/stdlib/ast/string.rs | 4 +- vm/src/stdlib/ast/type_ignore.rs | 4 +- vm/src/stdlib/ast/type_parameters.rs | 6 +- vm/src/stdlib/collections.rs | 10 +- vm/src/stdlib/functools.rs | 6 +- vm/src/stdlib/io.rs | 14 +-- vm/src/stdlib/itertools.rs | 10 +- vm/src/stdlib/operator.rs | 6 +- vm/src/stdlib/os.rs | 4 +- vm/src/stdlib/posix.rs | 8 +- vm/src/stdlib/sre.rs | 24 ++--- vm/src/stdlib/sys.rs | 8 +- vm/src/stdlib/time.rs | 16 +-- vm/src/stdlib/typevar.rs | 10 +- vm/src/stdlib/typing.rs | 4 +- vm/src/vm/context.rs | 4 +- vm/src/vm/method.rs | 8 +- vm/src/vm/mod.rs | 4 +- vm/src/vm/setting.rs | 2 +- vm/src/warn.rs | 4 +- 91 files changed, 482 insertions(+), 482 deletions(-) diff --git a/vm/src/buffer.rs b/vm/src/buffer.rs index d6bff51372..eb8732e871 100644 --- a/vm/src/buffer.rs +++ b/vm/src/buffer.rs @@ -27,16 +27,16 @@ pub(crate) enum Endianness { impl Endianness { /// Parse endianness /// See also: https://docs.python.org/3/library/struct.html?highlight=struct#byte-order-size-and-alignment - fn parse(chars: &mut Peekable) -> Endianness + fn parse(chars: &mut Peekable) -> Self where I: Sized + Iterator, { let e = match chars.peek() { - Some(b'@') => Endianness::Native, - Some(b'=') => Endianness::Host, - Some(b'<') => Endianness::Little, - Some(b'>') | Some(b'!') => Endianness::Big, - _ => return Endianness::Native, + Some(b'@') => Self::Native, + Some(b'=') => Self::Host, + Some(b'<') => Self::Little, + Some(b'>') | Some(b'!') => Self::Big, + _ => return Self::Native, }; chars.next().unwrap(); e @@ -267,7 +267,7 @@ impl FormatCode { .and_then(|extra| offset.checked_add(extra)) .ok_or_else(|| OVERFLOW_MSG.to_owned())?; - let code = FormatCode { + let code = Self { repeat: repeat as usize, code, info, @@ -321,7 +321,7 @@ pub struct FormatSpec { } impl FormatSpec { - pub fn parse(fmt: &[u8], vm: &VirtualMachine) -> PyResult { + pub fn parse(fmt: &[u8], vm: &VirtualMachine) -> PyResult { let mut chars = fmt.iter().copied().peekable(); // First determine "@", "<", ">","!" or "=" @@ -331,7 +331,7 @@ impl FormatSpec { let (codes, size, arg_count) = FormatCode::parse(&mut chars, endianness).map_err(|err| new_struct_error(vm, err))?; - Ok(FormatSpec { + Ok(Self { endianness, codes, size, @@ -544,7 +544,7 @@ impl Packable for f16 { fn pack(vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8]) -> PyResult<()> { let f_64 = *ArgIntoFloat::try_from_object(vm, arg)?; // "from_f64 should be preferred in any non-`const` context" except it gives the wrong result :/ - let f_16 = f16::from_f64_const(f_64); + let f_16 = Self::from_f64_const(f_64); if f_16.is_infinite() != f_64.is_infinite() { return Err(vm.new_overflow_error("float too large to pack with e format")); } @@ -554,7 +554,7 @@ impl Packable for f16 { fn unpack(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef { let i = PackInt::unpack_int::(rdr); - f16::from_bits(i).to_f64().to_pyobject(vm) + Self::from_bits(i).to_f64().to_pyobject(vm) } } diff --git a/vm/src/builtins/asyncgenerator.rs b/vm/src/builtins/asyncgenerator.rs index a280495fda..c3c707a69c 100644 --- a/vm/src/builtins/asyncgenerator.rs +++ b/vm/src/builtins/asyncgenerator.rs @@ -34,7 +34,7 @@ impl PyAsyncGen { } pub fn new(frame: FrameRef, name: PyStrRef) -> Self { - PyAsyncGen { + Self { inner: Coro::new(frame, name), running_async: AtomicCell::new(false), } @@ -76,7 +76,7 @@ impl PyAsyncGen { #[pyclass] impl PyRef { #[pymethod] - fn __aiter__(self, _vm: &VirtualMachine) -> PyRef { + fn __aiter__(self, _vm: &VirtualMachine) -> Self { self } diff --git a/vm/src/builtins/bool.rs b/vm/src/builtins/bool.rs index fa07c4d409..c21db81d56 100644 --- a/vm/src/builtins/bool.rs +++ b/vm/src/builtins/bool.rs @@ -21,7 +21,7 @@ impl ToPyObject for bool { } impl<'a> TryFromBorrowedObject<'a> for bool { - fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { if obj.fast_isinstance(vm.ctx.types.int_type) { Ok(get_value(obj)) } else { diff --git a/vm/src/builtins/builtin_func.rs b/vm/src/builtins/builtin_func.rs index 5e276b8976..43bac5a884 100644 --- a/vm/src/builtins/builtin_func.rs +++ b/vm/src/builtins/builtin_func.rs @@ -264,7 +264,7 @@ impl TryFromObject for NativeFunctionOrMethod { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let class = vm.ctx.types.builtin_function_or_method_type; if obj.fast_isinstance(class) { - Ok(NativeFunctionOrMethod(unsafe { obj.downcast_unchecked() })) + Ok(Self(unsafe { obj.downcast_unchecked() })) } else { Err(vm.new_downcast_type_error(class, &obj)) } diff --git a/vm/src/builtins/bytearray.rs b/vm/src/builtins/bytearray.rs index f7f1d9da34..49d950c1e8 100644 --- a/vm/src/builtins/bytearray.rs +++ b/vm/src/builtins/bytearray.rs @@ -78,7 +78,7 @@ impl PyByteArray { } fn from_inner(inner: PyBytesInner) -> Self { - PyByteArray { + Self { inner: PyRwLock::new(inner), exports: AtomicUsize::new(0), } @@ -339,7 +339,7 @@ impl PyByteArray { &self, options: ByteInnerPaddingOptions, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { Ok(self.inner().center(options, vm)?.into()) } @@ -348,7 +348,7 @@ impl PyByteArray { &self, options: ByteInnerPaddingOptions, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { Ok(self.inner().ljust(options, vm)?.into()) } @@ -357,7 +357,7 @@ impl PyByteArray { &self, options: ByteInnerPaddingOptions, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { Ok(self.inner().rjust(options, vm)?.into()) } @@ -367,7 +367,7 @@ impl PyByteArray { } #[pymethod] - fn join(&self, iter: ArgIterable, vm: &VirtualMachine) -> PyResult { + fn join(&self, iter: ArgIterable, vm: &VirtualMachine) -> PyResult { Ok(self.inner().join(iter, vm)?.into()) } @@ -438,7 +438,7 @@ impl PyByteArray { &self, options: ByteInnerTranslateOptions, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { Ok(self.inner().translate(options, vm)?.into()) } @@ -526,7 +526,7 @@ impl PyByteArray { new: PyBytesInner, count: OptionalArg, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { Ok(self.inner().replace(old, new, count, vm)?.into()) } @@ -553,7 +553,7 @@ impl PyByteArray { } #[pymethod(name = "__mod__")] - fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult { let formatted = self.inner().cformat(values, vm)?; Ok(formatted.into()) } @@ -667,7 +667,7 @@ impl PyRef { self, chars: OptionalOption, vm: &VirtualMachine, - ) -> PyRef { + ) -> Self { let inner = self.inner(); let stripped = inner.lstrip(chars); let elements = &inner.elements; @@ -684,7 +684,7 @@ impl PyRef { self, chars: OptionalOption, vm: &VirtualMachine, - ) -> PyRef { + ) -> Self { let inner = self.inner(); let stripped = inner.rstrip(chars); let elements = &inner.elements; diff --git a/vm/src/builtins/bytes.rs b/vm/src/builtins/bytes.rs index 67f910bef7..050093fd83 100644 --- a/vm/src/builtins/bytes.rs +++ b/vm/src/builtins/bytes.rs @@ -116,7 +116,7 @@ impl PyBytes { } impl PyRef { - fn repeat(self, count: isize, vm: &VirtualMachine) -> PyResult> { + fn repeat(self, count: isize, vm: &VirtualMachine) -> PyResult { if count == 1 && self.class().is(vm.ctx.types.bytes_type) { // Special case: when some `bytes` is multiplied by `1`, // nothing really happens, we need to return an object itself @@ -270,17 +270,17 @@ impl PyBytes { } #[pymethod] - fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { + fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { Ok(self.inner.center(options, vm)?.into()) } #[pymethod] - fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { + fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { Ok(self.inner.ljust(options, vm)?.into()) } #[pymethod] - fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { + fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { Ok(self.inner.rjust(options, vm)?.into()) } @@ -290,7 +290,7 @@ impl PyBytes { } #[pymethod] - fn join(&self, iter: ArgIterable, vm: &VirtualMachine) -> PyResult { + fn join(&self, iter: ArgIterable, vm: &VirtualMachine) -> PyResult { Ok(self.inner.join(iter, vm)?.into()) } @@ -359,7 +359,7 @@ impl PyBytes { &self, options: ByteInnerTranslateOptions, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { Ok(self.inner.translate(options, vm)?.into()) } @@ -451,7 +451,7 @@ impl PyBytes { new: PyBytesInner, count: OptionalArg, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { Ok(self.inner.replace(old, new, count, vm)?.into()) } @@ -467,7 +467,7 @@ impl PyBytes { } #[pymethod(name = "__mod__")] - fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult { let formatted = self.inner.cformat(values, vm)?; Ok(formatted.into()) } @@ -515,7 +515,7 @@ impl Py { #[pyclass] impl PyRef { #[pymethod] - fn __bytes__(self, vm: &VirtualMachine) -> PyRef { + fn __bytes__(self, vm: &VirtualMachine) -> Self { if self.is(vm.ctx.types.bytes_type) { self } else { @@ -524,7 +524,7 @@ impl PyRef { } #[pymethod] - fn lstrip(self, chars: OptionalOption, vm: &VirtualMachine) -> PyRef { + fn lstrip(self, chars: OptionalOption, vm: &VirtualMachine) -> Self { let stripped = self.inner.lstrip(chars); if stripped == self.as_bytes() { self @@ -534,7 +534,7 @@ impl PyRef { } #[pymethod] - fn rstrip(self, chars: OptionalOption, vm: &VirtualMachine) -> PyRef { + fn rstrip(self, chars: OptionalOption, vm: &VirtualMachine) -> Self { let stripped = self.inner.rstrip(chars); if stripped == self.as_bytes() { self diff --git a/vm/src/builtins/classmethod.rs b/vm/src/builtins/classmethod.rs index f48152d503..03bdeb171d 100644 --- a/vm/src/builtins/classmethod.rs +++ b/vm/src/builtins/classmethod.rs @@ -92,7 +92,7 @@ impl Constructor for PyClassMethod { } // Create PyClassMethod instance with the pre-populated dict - let classmethod = PyClassMethod { + let classmethod = Self { callable: PyMutex::new(callable), }; diff --git a/vm/src/builtins/code.rs b/vm/src/builtins/code.rs index 659a1ce702..ada589adc5 100644 --- a/vm/src/builtins/code.rs +++ b/vm/src/builtins/code.rs @@ -202,8 +202,8 @@ impl Deref for PyCode { } impl PyCode { - pub fn new(code: CodeObject) -> PyCode { - PyCode { code } + pub fn new(code: CodeObject) -> Self { + Self { code } } } @@ -335,7 +335,7 @@ impl PyCode { } #[pymethod] - pub fn replace(&self, args: ReplaceArgs, vm: &VirtualMachine) -> PyResult { + pub fn replace(&self, args: ReplaceArgs, vm: &VirtualMachine) -> PyResult { let posonlyarg_count = match args.co_posonlyargcount { OptionalArg::Present(posonlyarg_count) => posonlyarg_count, OptionalArg::Missing => self.code.posonlyarg_count, @@ -392,7 +392,7 @@ impl PyCode { OptionalArg::Missing => self.code.varnames.iter().map(|s| s.to_object()).collect(), }; - Ok(PyCode { + Ok(Self { code: CodeObject { flags: CodeFlags::from_bits_truncate(flags), posonlyarg_count, diff --git a/vm/src/builtins/complex.rs b/vm/src/builtins/complex.rs index 752d941061..67e7edebe6 100644 --- a/vm/src/builtins/complex.rs +++ b/vm/src/builtins/complex.rs @@ -48,7 +48,7 @@ impl ToPyObject for Complex64 { impl From for PyComplex { fn from(value: Complex64) -> Self { - PyComplex { value } + Self { value } } } @@ -161,7 +161,7 @@ impl Constructor for PyComplex { OptionalArg::Missing => (Complex64::new(0.0, 0.0), false), OptionalArg::Present(val) => { let val = if cls.is(vm.ctx.types.complex_type) && imag_missing { - match val.downcast_exact::(vm) { + match val.downcast_exact::(vm) { Ok(c) => { return Ok(c.into_pyref().into()); } @@ -393,7 +393,7 @@ impl PyComplex { #[pyclass] impl PyRef { #[pymethod] - fn __complex__(self, vm: &VirtualMachine) -> PyRef { + fn __complex__(self, vm: &VirtualMachine) -> Self { if self.is(vm.ctx.types.complex_type) { self } else { @@ -410,7 +410,7 @@ impl Comparable for PyComplex { vm: &VirtualMachine, ) -> PyResult { op.eq_only(|| { - let result = if let Some(other) = other.payload_if_subclass::(vm) { + let result = if let Some(other) = other.payload_if_subclass::(vm) { if zelf.value.re.is_nan() && zelf.value.im.is_nan() && other.value.re.is_nan() diff --git a/vm/src/builtins/coroutine.rs b/vm/src/builtins/coroutine.rs index eea50a567b..dab6ef8793 100644 --- a/vm/src/builtins/coroutine.rs +++ b/vm/src/builtins/coroutine.rs @@ -30,7 +30,7 @@ impl PyCoroutine { } pub fn new(frame: FrameRef, name: PyStrRef) -> Self { - PyCoroutine { + Self { inner: Coro::new(frame, name), } } diff --git a/vm/src/builtins/dict.rs b/vm/src/builtins/dict.rs index f9610af5dc..d18f795403 100644 --- a/vm/src/builtins/dict.rs +++ b/vm/src/builtins/dict.rs @@ -63,7 +63,7 @@ impl PyDict { // Used in update and ior. pub(crate) fn merge_object(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let casted: Result, _> = other.downcast_exact(vm); + let casted: Result, _> = other.downcast_exact(vm); let other = match casted { Ok(dict_other) => return self.merge_dict(dict_other.into_pyref(), vm), Err(other) => other, @@ -187,7 +187,7 @@ impl PyDict { ) -> PyResult { let value = value.unwrap_or_none(vm); let d = PyType::call(&class, ().into(), vm)?; - match d.downcast_exact::(vm) { + match d.downcast_exact::(vm) { Ok(pydict) => { for key in iterable.iter(vm)? { pydict.__setitem__(key?, value.clone(), vm)?; @@ -263,8 +263,8 @@ impl PyDict { } #[pymethod] - pub fn copy(&self) -> PyDict { - PyDict { + pub fn copy(&self) -> Self { + Self { entries: self.entries.clone(), } } @@ -331,7 +331,7 @@ impl PyDict { impl Py { fn inner_cmp( &self, - other: &Py, + other: &Self, op: PyComparisonOp, item: bool, vm: &VirtualMachine, @@ -403,7 +403,7 @@ impl PyRef { #[pymethod] fn __ror__(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let other_dict: Result = other.downcast(); + let other_dict: Result = other.downcast(); if let Ok(other) = other_dict { let other_cp = other.copy(); other_cp.merge_dict(self, vm)?; @@ -692,8 +692,8 @@ pub struct DictIntoIter { } impl DictIntoIter { - pub const fn new(dict: PyDictRef) -> DictIntoIter { - DictIntoIter { dict, position: 0 } + pub const fn new(dict: PyDictRef) -> Self { + Self { dict, position: 0 } } } diff --git a/vm/src/builtins/enumerate.rs b/vm/src/builtins/enumerate.rs index f0287a6193..fd57532da9 100644 --- a/vm/src/builtins/enumerate.rs +++ b/vm/src/builtins/enumerate.rs @@ -44,7 +44,7 @@ impl Constructor for PyEnumerate { vm: &VirtualMachine, ) -> PyResult { let counter = start.map_or_else(BigInt::zero, |start| start.as_bigint().clone()); - PyEnumerate { + Self { counter: PyRwLock::new(counter), iterator, } diff --git a/vm/src/builtins/float.rs b/vm/src/builtins/float.rs index 6c0ba28e55..f01eceef0c 100644 --- a/vm/src/builtins/float.rs +++ b/vm/src/builtins/float.rs @@ -52,7 +52,7 @@ impl ToPyObject for f32 { impl From for PyFloat { fn from(value: f64) -> Self { - PyFloat { value } + Self { value } } } @@ -146,7 +146,7 @@ impl Constructor for PyFloat { } } }; - PyFloat::from(float_val) + Self::from(float_val) .into_ref_with_type(vm, cls) .map(Into::into) } @@ -523,7 +523,7 @@ impl Comparable for PyFloat { op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { - let ret = if let Some(other) = other.payload_if_subclass::(vm) { + let ret = if let Some(other) = other.payload_if_subclass::(vm) { zelf.value .partial_cmp(&other.value) .map_or_else(|| op == PyComparisonOp::Ne, |ord| op.eval_ord(ord)) diff --git a/vm/src/builtins/function.rs b/vm/src/builtins/function.rs index 7bcd6bd7b0..ee75f850d0 100644 --- a/vm/src/builtins/function.rs +++ b/vm/src/builtins/function.rs @@ -78,7 +78,7 @@ impl PyFunction { } }); - let func = PyFunction { + let func = Self { code, globals, builtins, @@ -449,7 +449,7 @@ impl PyFunction { #[pymember] fn __doc__(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { // When accessed from instance, obj is the PyFunction instance - if let Ok(func) = obj.downcast::() { + if let Ok(func) = obj.downcast::() { let doc = func.doc.lock(); Ok(doc.clone()) } else { @@ -460,7 +460,7 @@ impl PyFunction { #[pymember(setter)] fn set___doc__(vm: &VirtualMachine, zelf: PyObjectRef, value: PySetterValue) -> PyResult<()> { - let zelf: PyRef = zelf.downcast().unwrap_or_else(|_| unreachable!()); + let zelf: PyRef = zelf.downcast().unwrap_or_else(|_| unreachable!()); let value = value.unwrap_or_none(vm); *zelf.doc.lock() = value; Ok(()) @@ -637,7 +637,7 @@ impl Constructor for PyFunction { // Get doc from code object - for now just use None let doc = vm.ctx.none(); - let func = PyFunction::new( + let func = Self::new( args.code, args.globals, closure, @@ -715,7 +715,7 @@ impl Constructor for PyBoundMethod { Self::Args { function, object }: Self::Args, vm: &VirtualMachine, ) -> PyResult { - PyBoundMethod::new(object, function) + Self::new(object, function) .into_ref_with_type(vm, cls) .map(Into::into) } @@ -723,7 +723,7 @@ impl Constructor for PyBoundMethod { impl PyBoundMethod { pub fn new(object: PyObjectRef, function: PyObjectRef) -> Self { - PyBoundMethod { object, function } + Self { object, function } } pub fn new_ref(object: PyObjectRef, function: PyObjectRef, ctx: &Context) -> PyRef { diff --git a/vm/src/builtins/generator.rs b/vm/src/builtins/generator.rs index a7db393eab..44021c24ed 100644 --- a/vm/src/builtins/generator.rs +++ b/vm/src/builtins/generator.rs @@ -33,7 +33,7 @@ impl PyGenerator { } pub fn new(frame: FrameRef, name: PyStrRef) -> Self { - PyGenerator { + Self { inner: Coro::new(frame, name), } } diff --git a/vm/src/builtins/genericalias.rs b/vm/src/builtins/genericalias.rs index 84a820e064..d55967bd7e 100644 --- a/vm/src/builtins/genericalias.rs +++ b/vm/src/builtins/genericalias.rs @@ -68,7 +68,7 @@ impl Constructor for PyGenericAlias { } else { PyTuple::new_ref(vec![arguments], &vm.ctx) }; - PyGenericAlias::new(origin, args, false, vm) + Self::new(origin, args, false, vm) .into_ref_with_type(vm, cls) .map(Into::into) } @@ -201,7 +201,7 @@ impl PyGenericAlias { vm, )?; - Ok(PyGenericAlias::new(zelf.origin.clone(), new_args, false, vm).into_pyobject(vm)) + Ok(Self::new(zelf.origin.clone(), new_args, false, vm).into_pyobject(vm)) } #[pymethod] @@ -596,7 +596,7 @@ impl Iterable for PyGenericAlias { // CPython's ga_iter creates an iterator that yields one starred GenericAlias // we don't have gaiterobject yet - let starred_alias = PyGenericAlias::new( + let starred_alias = Self::new( zelf.origin.clone(), zelf.args.clone(), true, // starred diff --git a/vm/src/builtins/int.rs b/vm/src/builtins/int.rs index 30249fac88..8ae8f30881 100644 --- a/vm/src/builtins/int.rs +++ b/vm/src/builtins/int.rs @@ -223,7 +223,7 @@ impl Constructor for PyInt { try_int_radix(&val, base, vm) } else { let val = if cls.is(vm.ctx.types.int_type) { - match val.downcast_exact::(vm) { + match val.downcast_exact::(vm) { Ok(i) => { return Ok(i.into_pyref().into()); } @@ -255,7 +255,7 @@ impl PyInt { } else if cls.is(vm.ctx.types.bool_type) { Ok(vm.ctx.new_bool(!value.into().eq(&BigInt::zero()))) } else { - PyInt::from(value).into_ref_with_type(vm, cls) + Self::from(value).into_ref_with_type(vm, cls) } } @@ -298,7 +298,7 @@ impl PyInt { F: Fn(&BigInt, &BigInt) -> BigInt, { let r = other - .payload_if_subclass::(vm) + .payload_if_subclass::(vm) .map(|other| op(&self.value, &other.value)); PyArithmeticValue::from_option(r) } @@ -308,7 +308,7 @@ impl PyInt { where F: Fn(&BigInt, &BigInt) -> PyResult, { - if let Some(other) = other.payload_if_subclass::(vm) { + if let Some(other) = other.payload_if_subclass::(vm) { op(&self.value, &other.value) } else { Ok(vm.ctx.not_implemented()) @@ -402,7 +402,7 @@ impl PyInt { } fn modpow(&self, other: PyObjectRef, modulus: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let modulus = match modulus.payload_if_subclass::(vm) { + let modulus = match modulus.payload_if_subclass::(vm) { Some(val) => val.as_bigint(), None => return Ok(vm.ctx.not_implemented()), }; @@ -717,7 +717,7 @@ impl Comparable for PyInt { vm: &VirtualMachine, ) -> PyResult { let r = other - .payload_if_subclass::(vm) + .payload_if_subclass::(vm) .map(|other| op.eval_ord(zelf.value.cmp(&other.value))); Ok(PyComparisonValue::from_option(r)) } @@ -751,11 +751,11 @@ impl AsNumber for PyInt { impl PyInt { pub(super) const AS_NUMBER: PyNumberMethods = PyNumberMethods { - add: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a + b, vm)), - subtract: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a - b, vm)), - multiply: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a * b, vm)), - remainder: Some(|a, b, vm| PyInt::number_op(a, b, inner_mod, vm)), - divmod: Some(|a, b, vm| PyInt::number_op(a, b, inner_divmod, vm)), + add: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a + b, vm)), + subtract: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a - b, vm)), + multiply: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a * b, vm)), + remainder: Some(|a, b, vm| Self::number_op(a, b, inner_mod, vm)), + divmod: Some(|a, b, vm| Self::number_op(a, b, inner_divmod, vm)), power: Some(|a, b, c, vm| { if let (Some(a), Some(b)) = ( a.payload::(), @@ -774,24 +774,24 @@ impl PyInt { Ok(vm.ctx.not_implemented()) } }), - negative: Some(|num, vm| (&PyInt::number_downcast(num).value).neg().to_pyresult(vm)), - positive: Some(|num, vm| Ok(PyInt::number_downcast_exact(num, vm).into())), - absolute: Some(|num, vm| PyInt::number_downcast(num).value.abs().to_pyresult(vm)), - boolean: Some(|num, _vm| Ok(PyInt::number_downcast(num).value.is_zero())), - invert: Some(|num, vm| (&PyInt::number_downcast(num).value).not().to_pyresult(vm)), - lshift: Some(|a, b, vm| PyInt::number_op(a, b, inner_lshift, vm)), - rshift: Some(|a, b, vm| PyInt::number_op(a, b, inner_rshift, vm)), - and: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a & b, vm)), - xor: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a ^ b, vm)), - or: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a | b, vm)), - int: Some(|num, vm| Ok(PyInt::number_downcast_exact(num, vm).into())), + negative: Some(|num, vm| (&Self::number_downcast(num).value).neg().to_pyresult(vm)), + positive: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())), + absolute: Some(|num, vm| Self::number_downcast(num).value.abs().to_pyresult(vm)), + boolean: Some(|num, _vm| Ok(Self::number_downcast(num).value.is_zero())), + invert: Some(|num, vm| (&Self::number_downcast(num).value).not().to_pyresult(vm)), + lshift: Some(|a, b, vm| Self::number_op(a, b, inner_lshift, vm)), + rshift: Some(|a, b, vm| Self::number_op(a, b, inner_rshift, vm)), + and: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a & b, vm)), + xor: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a ^ b, vm)), + or: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a | b, vm)), + int: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())), float: Some(|num, vm| { - let zelf = PyInt::number_downcast(num); + let zelf = Self::number_downcast(num); try_to_float(&zelf.value, vm).map(|x| vm.ctx.new_float(x).into()) }), - floor_divide: Some(|a, b, vm| PyInt::number_op(a, b, inner_floordiv, vm)), - true_divide: Some(|a, b, vm| PyInt::number_op(a, b, inner_truediv, vm)), - index: Some(|num, vm| Ok(PyInt::number_downcast_exact(num, vm).into())), + floor_divide: Some(|a, b, vm| Self::number_op(a, b, inner_floordiv, vm)), + true_divide: Some(|a, b, vm| Self::number_op(a, b, inner_truediv, vm)), + index: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())), ..PyNumberMethods::NOT_IMPLEMENTED }; diff --git a/vm/src/builtins/iter.rs b/vm/src/builtins/iter.rs index 4250a86d71..52ee853549 100644 --- a/vm/src/builtins/iter.rs +++ b/vm/src/builtins/iter.rs @@ -28,8 +28,8 @@ pub enum IterStatus { unsafe impl Traverse for IterStatus { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { - IterStatus::Active(r) => r.traverse(tracer_fn), - IterStatus::Exhausted => (), + Self::Active(r) => r.traverse(tracer_fn), + Self::Exhausted => (), } } } diff --git a/vm/src/builtins/list.rs b/vm/src/builtins/list.rs index 9cd7ecbe47..838295b01b 100644 --- a/vm/src/builtins/list.rs +++ b/vm/src/builtins/list.rs @@ -37,7 +37,7 @@ impl fmt::Debug for PyList { impl From> for PyList { fn from(elements: Vec) -> Self { - PyList { + Self { elements: PyRwLock::new(elements), } } @@ -131,7 +131,7 @@ impl PyList { } fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult> { - let other = other.payload_if_subclass::(vm).ok_or_else(|| { + let other = other.payload_if_subclass::(vm).ok_or_else(|| { vm.new_type_error(format!( "Cannot add {} and {}", Self::class(&vm.ctx).name(), @@ -379,7 +379,7 @@ impl Constructor for PyList { type Args = FuncArgs; fn py_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { - PyList::default() + Self::default() .into_ref_with_type(vm, cls) .map(Into::into) } diff --git a/vm/src/builtins/map.rs b/vm/src/builtins/map.rs index 867f29a5cb..004028c2cb 100644 --- a/vm/src/builtins/map.rs +++ b/vm/src/builtins/map.rs @@ -27,7 +27,7 @@ impl Constructor for PyMap { fn py_new(cls: PyTypeRef, (mapper, iterators): Self::Args, vm: &VirtualMachine) -> PyResult { let iterators = iterators.into_vec(); - PyMap { mapper, iterators } + Self { mapper, iterators } .into_ref_with_type(vm, cls) .map(Into::into) } diff --git a/vm/src/builtins/mappingproxy.rs b/vm/src/builtins/mappingproxy.rs index 8942a0a22f..5ba6597e1f 100644 --- a/vm/src/builtins/mappingproxy.rs +++ b/vm/src/builtins/mappingproxy.rs @@ -29,8 +29,8 @@ enum MappingProxyInner { unsafe impl Traverse for MappingProxyInner { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { - MappingProxyInner::Class(r) => r.traverse(tracer_fn), - MappingProxyInner::Mapping(arg) => arg.traverse(tracer_fn), + Self::Class(r) => r.traverse(tracer_fn), + Self::Mapping(arg) => arg.traverse(tracer_fn), } } } diff --git a/vm/src/builtins/memory.rs b/vm/src/builtins/memory.rs index 9bf22c6b35..33fd19573b 100644 --- a/vm/src/builtins/memory.rs +++ b/vm/src/builtins/memory.rs @@ -79,7 +79,7 @@ impl PyMemoryView { Ok(other.new_view()) } else { let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?; - PyMemoryView::from_buffer(buffer, vm) + Self::from_buffer(buffer, vm) } } @@ -93,7 +93,7 @@ impl PyMemoryView { let format_spec = Self::parse_format(&buffer.desc.format, vm)?; let desc = buffer.desc.clone(); - Ok(PyMemoryView { + Ok(Self { buffer: ManuallyDrop::new(buffer), released: AtomicCell::new(false), start: 0, @@ -120,7 +120,7 @@ impl PyMemoryView { /// this should be the only way to create a memoryview from another memoryview pub fn new_view(&self) -> Self { - let zelf = PyMemoryView { + let zelf = Self { buffer: self.buffer.clone(), released: AtomicCell::new(false), start: self.start, diff --git a/vm/src/builtins/module.rs b/vm/src/builtins/module.rs index dac98f8d1b..f8e42b28e0 100644 --- a/vm/src/builtins/module.rs +++ b/vm/src/builtins/module.rs @@ -83,7 +83,7 @@ impl PyModule { } } - pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py) { + pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py) { let doc = module.def.unwrap().doc.map(|doc| doc.to_owned()); module.init_dict(module.name.unwrap(), doc, vm); } @@ -169,7 +169,7 @@ impl Py { impl PyModule { #[pyslot] fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { - PyModule::new().into_ref_with_type(vm, cls).map(Into::into) + Self::new().into_ref_with_type(vm, cls).map(Into::into) } #[pymethod] diff --git a/vm/src/builtins/object.rs b/vm/src/builtins/object.rs index b83d22b34c..fc39e2fb08 100644 --- a/vm/src/builtins/object.rs +++ b/vm/src/builtins/object.rs @@ -69,7 +69,7 @@ impl Constructor for PyBaseObject { } } - Ok(crate::PyRef::new_ref(PyBaseObject, cls, dict).into()) + Ok(crate::PyRef::new_ref(Self, cls, dict).into()) } } diff --git a/vm/src/builtins/property.rs b/vm/src/builtins/property.rs index d515f431e0..925ec35f49 100644 --- a/vm/src/builtins/property.rs +++ b/vm/src/builtins/property.rs @@ -199,9 +199,9 @@ impl PyProperty { }; // Create new property using py_new and init - let new_prop = PyProperty::py_new(zelf.class().to_owned(), FuncArgs::default(), vm)?; - let new_prop_ref = new_prop.downcast::().unwrap(); - PyProperty::init(new_prop_ref.clone(), args, vm)?; + let new_prop = Self::py_new(zelf.class().to_owned(), FuncArgs::default(), vm)?; + let new_prop_ref = new_prop.downcast::().unwrap(); + Self::init(new_prop_ref.clone(), args, vm)?; // Copy the name if it exists if let Some(name) = zelf.name.read().clone() { @@ -312,7 +312,7 @@ impl Constructor for PyProperty { type Args = FuncArgs; fn py_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { - PyProperty { + Self { getter: PyRwLock::new(None), setter: PyRwLock::new(None), deleter: PyRwLock::new(None), diff --git a/vm/src/builtins/range.rs b/vm/src/builtins/range.rs index ac9c35a081..2d6ea92b19 100644 --- a/vm/src/builtins/range.rs +++ b/vm/src/builtins/range.rs @@ -185,7 +185,7 @@ pub fn init(context: &Context) { ))] impl PyRange { fn new(cls: PyTypeRef, stop: ArgIndex, vm: &VirtualMachine) -> PyResult> { - PyRange { + Self { start: vm.ctx.new_pyref(0), stop: stop.into(), step: vm.ctx.new_pyref(1), @@ -204,7 +204,7 @@ impl PyRange { if step.as_bigint().is_zero() { return Err(vm.new_value_error("range() arg 3 must not be zero")); } - PyRange { + Self { start: start.try_index(vm)?, stop: stop.try_index(vm)?, step, @@ -296,7 +296,7 @@ impl PyRange { sub_start = (sub_start * range_step.as_bigint()) + range_start.as_bigint(); sub_stop = (sub_stop * range_step.as_bigint()) + range_start.as_bigint(); - Ok(PyRange { + Ok(Self { start: vm.ctx.new_pyref(sub_start), stop: vm.ctx.new_pyref(sub_stop), step: vm.ctx.new_pyref(sub_step), @@ -315,10 +315,10 @@ impl PyRange { fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let range = if args.args.len() <= 1 { let stop = args.bind(vm)?; - PyRange::new(cls, stop, vm) + Self::new(cls, stop, vm) } else { let (start, stop, step) = args.bind(vm)?; - PyRange::new_from(cls, start, stop, step, vm) + Self::new_from(cls, start, stop, step, vm) }?; Ok(range.into()) @@ -697,14 +697,14 @@ pub enum RangeIndex { impl TryFromObject for RangeIndex { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { match_class!(match obj { - i @ PyInt => Ok(RangeIndex::Int(i)), - s @ PySlice => Ok(RangeIndex::Slice(s)), + i @ PyInt => Ok(Self::Int(i)), + s @ PySlice => Ok(Self::Slice(s)), obj => { let val = obj.try_index(vm).map_err(|_| vm.new_type_error(format!( "sequence indices be integers or slices or classes that override __index__ operator, not '{}'", obj.class().name() )))?; - Ok(RangeIndex::Int(val)) + Ok(Self::Int(val)) } }) } diff --git a/vm/src/builtins/set.rs b/vm/src/builtins/set.rs index 4ff5bed7b0..ff97f0ae2d 100644 --- a/vm/src/builtins/set.rs +++ b/vm/src/builtins/set.rs @@ -82,7 +82,7 @@ pub struct PyFrozenSet { impl Default for PyFrozenSet { fn default() -> Self { - PyFrozenSet { + Self { inner: PySetInner::default(), hash: hash::SENTINEL.into(), } @@ -183,7 +183,7 @@ impl PySetInner { where T: IntoIterator>, { - let set = PySetInner::default(); + let set = Self::default(); for item in iter { set.add(item?, vm)?; } @@ -211,8 +211,8 @@ impl PySetInner { self.content.sizeof() } - fn copy(&self) -> PySetInner { - PySetInner { + fn copy(&self) -> Self { + Self { content: PyRc::new((*self.content).clone()), } } @@ -223,7 +223,7 @@ impl PySetInner { fn compare( &self, - other: &PySetInner, + other: &Self, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { @@ -247,7 +247,7 @@ impl PySetInner { Ok(true) } - pub(super) fn union(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + pub(super) fn union(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { let set = self.clone(); for item in other.iter(vm)? { set.add(item?, vm)?; @@ -260,8 +260,8 @@ impl PySetInner { &self, other: ArgIterable, vm: &VirtualMachine, - ) -> PyResult { - let set = PySetInner::default(); + ) -> PyResult { + let set = Self::default(); for item in other.iter(vm)? { let obj = item?; if self.contains(&obj, vm)? { @@ -275,7 +275,7 @@ impl PySetInner { &self, other: ArgIterable, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { let set = self.copy(); for item in other.iter(vm)? { set.content.delete_if_exists(vm, &*item?)?; @@ -287,7 +287,7 @@ impl PySetInner { &self, other: ArgIterable, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyResult { let new_inner = self.clone(); // We want to remove duplicates in other @@ -310,7 +310,7 @@ impl PySetInner { } fn issubset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - let other_set = PySetInner::from_iter(other.iter(vm)?, vm)?; + let other_set = Self::from_iter(other.iter(vm)?, vm)?; self.compare(&other_set, PyComparisonOp::Le, vm) } @@ -412,7 +412,7 @@ impl PySetInner { others: impl std::iter::Iterator, vm: &VirtualMachine, ) -> PyResult<()> { - let temp_inner = self.fold_op(others, PySetInner::intersection, vm)?; + let temp_inner = self.fold_op(others, Self::intersection, vm)?; self.clear(); for obj in temp_inner.elements() { self.add(obj, vm)?; @@ -1278,7 +1278,7 @@ impl TryFromObject for AnySet { if class.fast_issubclass(vm.ctx.types.set_type) || class.fast_issubclass(vm.ctx.types.frozenset_type) { - Ok(AnySet { object: obj }) + Ok(Self { object: obj }) } else { Err(vm.new_type_error(format!("{class} is not a subtype of set or frozenset"))) } diff --git a/vm/src/builtins/slice.rs b/vm/src/builtins/slice.rs index 42607f4bb2..f77c8cb8e8 100644 --- a/vm/src/builtins/slice.rs +++ b/vm/src/builtins/slice.rs @@ -65,13 +65,13 @@ impl PySlice { #[pyslot] fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let slice: PySlice = match args.args.len() { + let slice: Self = match args.args.len() { 0 => { return Err(vm.new_type_error("slice() must have at least one arguments.")); } 1 => { let stop = args.bind(vm)?; - PySlice { + Self { start: None, stop, step: None, @@ -80,7 +80,7 @@ impl PySlice { _ => { let (start, stop, step): (PyObjectRef, PyObjectRef, OptionalArg) = args.bind(vm)?; - PySlice { + Self { start: Some(start), stop, step: step.into_option(), diff --git a/vm/src/builtins/staticmethod.rs b/vm/src/builtins/staticmethod.rs index 6024835487..c357516abb 100644 --- a/vm/src/builtins/staticmethod.rs +++ b/vm/src/builtins/staticmethod.rs @@ -46,7 +46,7 @@ impl Constructor for PyStaticMethod { fn py_new(cls: PyTypeRef, callable: Self::Args, vm: &VirtualMachine) -> PyResult { let doc = callable.get_attr("__doc__", vm); - let result = PyStaticMethod { + let result = Self { callable: PyMutex::new(callable), } .into_ref_with_type(vm, cls)?; diff --git a/vm/src/builtins/str.rs b/vm/src/builtins/str.rs index feb2231e7d..a2ea87cd22 100644 --- a/vm/src/builtins/str.rs +++ b/vm/src/builtins/str.rs @@ -181,7 +181,7 @@ impl From for PyStr { impl From for PyStr { fn from(data: StrData) -> Self { - PyStr { + Self { data, hash: Radium::new(hash::SENTINEL), } @@ -364,13 +364,13 @@ impl Constructor for PyStr { } } OptionalArg::Missing => { - PyStr::from(String::new()).into_ref_with_type(vm, cls.clone())? + Self::from(String::new()).into_ref_with_type(vm, cls.clone())? } }; if string.class().is(&cls) { Ok(string.into()) } else { - PyStr::from(string.as_wtf8()) + Self::from(string.as_wtf8()) .into_ref_with_type(vm, cls) .map(Into::into) } @@ -517,7 +517,7 @@ impl PyStr { impl PyStr { #[pymethod] fn __add__(zelf: PyRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - if let Some(other) = other.payload::() { + if let Some(other) = other.payload::() { let bytes = zelf.as_wtf8().py_add(other.as_wtf8()); Ok(unsafe { // SAFETY: `kind` is safely decided @@ -626,7 +626,7 @@ impl PyStr { } #[pymethod] - fn lower(&self) -> PyStr { + fn lower(&self) -> Self { match self.as_str_kind() { PyKindStr::Ascii(s) => s.to_ascii_lowercase().into(), PyKindStr::Utf8(s) => s.to_lowercase().into(), @@ -648,7 +648,7 @@ impl PyStr { } #[pymethod] - fn upper(&self) -> PyStr { + fn upper(&self) -> Self { match self.as_str_kind() { PyKindStr::Ascii(s) => s.to_ascii_uppercase().into(), PyKindStr::Utf8(s) => s.to_uppercase().into(), @@ -765,7 +765,7 @@ impl PyStr { } #[pymethod] - fn strip(&self, chars: OptionalOption) -> PyStr { + fn strip(&self, chars: OptionalOption) -> Self { match self.as_str_kind() { PyKindStr::Ascii(s) => s .py_strip( @@ -845,7 +845,7 @@ impl PyStr { &affix, "endswith", "str", - |s, x: &Py| s.ends_with(x.as_wtf8()), + |s, x: &Py| s.ends_with(x.as_wtf8()), vm, ) } @@ -865,7 +865,7 @@ impl PyStr { &affix, "startswith", "str", - |s, x: &Py| s.starts_with(x.as_wtf8()), + |s, x: &Py| s.starts_with(x.as_wtf8()), vm, ) } @@ -1335,7 +1335,7 @@ impl PyStr { for c in self.as_str().chars() { match table.get_item(&*(c as u32).to_pyobject(vm), vm) { Ok(value) => { - if let Some(text) = value.payload::() { + if let Some(text) = value.payload::() { translated.push_str(text.as_str()); } else if let Some(bigint) = value.payload::() { let ch = bigint @@ -1367,7 +1367,7 @@ impl PyStr { ) -> PyResult { let new_dict = vm.ctx.new_dict(); if let OptionalArg::Present(to_str) = to_str { - match dict_or_str.downcast::() { + match dict_or_str.downcast::() { Ok(from_str) => { if to_str.len() == from_str.len() { for (c1, c2) in from_str.as_str().chars().zip(to_str.as_str().chars()) { @@ -1405,7 +1405,7 @@ impl PyStr { val, vm, )?; - } else if let Some(string) = key.payload::() { + } else if let Some(string) = key.payload::() { if string.len() == 1 { let num_value = string.as_str().chars().next().unwrap() as u32; new_dict.set_item(&*num_value.to_pyobject(vm), val, vm)?; @@ -1693,7 +1693,7 @@ pub fn init(ctx: &Context) { impl SliceableSequenceOp for PyStr { type Item = CodePoint; - type Sliced = PyStr; + type Sliced = Self; fn do_get(&self, index: usize) -> Self::Item { self.data.nth_char(index) @@ -1706,13 +1706,13 @@ impl SliceableSequenceOp for PyStr { let char_len = range.len(); let out = rustpython_common::str::get_chars(s, range); // SAFETY: char_len is accurate - unsafe { PyStr::new_with_char_len(out, char_len) } + unsafe { Self::new_with_char_len(out, char_len) } } PyKindStr::Wtf8(w) => { let char_len = range.len(); let out = rustpython_common::str::get_codepoints(w, range); // SAFETY: char_len is accurate - unsafe { PyStr::new_with_char_len(out, char_len) } + unsafe { Self::new_with_char_len(out, char_len) } } } } @@ -1734,7 +1734,7 @@ impl SliceableSequenceOp for PyStr { .take(range.len()), ); // SAFETY: char_len is accurate - unsafe { PyStr::new_with_char_len(out, range.len()) } + unsafe { Self::new_with_char_len(out, range.len()) } } PyKindStr::Wtf8(w) => { let char_len = range.len(); @@ -1746,7 +1746,7 @@ impl SliceableSequenceOp for PyStr { .take(range.len()), ); // SAFETY: char_len is accurate - unsafe { PyStr::new_with_char_len(out, char_len) } + unsafe { Self::new_with_char_len(out, char_len) } } } } @@ -1765,7 +1765,7 @@ impl SliceableSequenceOp for PyStr { let mut out = String::with_capacity(2 * char_len); out.extend(s.chars().skip(range.start).take(range.len()).step_by(step)); // SAFETY: char_len is accurate - unsafe { PyStr::new_with_char_len(out, char_len) } + unsafe { Self::new_with_char_len(out, char_len) } } PyKindStr::Wtf8(w) => { let char_len = (range.len() / step) + 1; @@ -1777,7 +1777,7 @@ impl SliceableSequenceOp for PyStr { .step_by(step), ); // SAFETY: char_len is accurate - unsafe { PyStr::new_with_char_len(out, char_len) } + unsafe { Self::new_with_char_len(out, char_len) } } } } @@ -1802,7 +1802,7 @@ impl SliceableSequenceOp for PyStr { .step_by(step), ); // SAFETY: char_len is accurate - unsafe { PyStr::new_with_char_len(out, char_len) } + unsafe { Self::new_with_char_len(out, char_len) } } PyKindStr::Wtf8(w) => { let char_len = (range.len() / step) + 1; @@ -1816,13 +1816,13 @@ impl SliceableSequenceOp for PyStr { .step_by(step), ); // SAFETY: char_len is accurate - unsafe { PyStr::new_with_char_len(out, char_len) } + unsafe { Self::new_with_char_len(out, char_len) } } } } fn empty() -> Self::Sliced { - PyStr::default() + Self::default() } fn len(&self) -> usize { @@ -1886,15 +1886,15 @@ impl AnyStrWrapper for PyStrRef { impl AnyStrContainer for String { fn new() -> Self { - String::new() + Self::new() } fn with_capacity(capacity: usize) -> Self { - String::with_capacity(capacity) + Self::with_capacity(capacity) } fn push_str(&mut self, other: &str) { - String::push_str(self, other) + Self::push_str(self, other) } } @@ -1925,7 +1925,7 @@ impl AnyStr for str { } fn elements(&self) -> impl Iterator { - str::chars(self) + Self::chars(self) } fn get_bytes(&self, range: std::ops::Range) -> &Self { @@ -1999,11 +1999,11 @@ impl AnyStr for str { impl AnyStrContainer for Wtf8Buf { fn new() -> Self { - Wtf8Buf::new() + Self::new() } fn with_capacity(capacity: usize) -> Self { - Wtf8Buf::with_capacity(capacity) + Self::with_capacity(capacity) } fn push_str(&mut self, other: &Wtf8) { @@ -2117,15 +2117,15 @@ impl AnyStr for Wtf8 { impl AnyStrContainer for AsciiString { fn new() -> Self { - AsciiString::new() + Self::new() } fn with_capacity(capacity: usize) -> Self { - AsciiString::with_capacity(capacity) + Self::with_capacity(capacity) } fn push_str(&mut self, other: &AsciiStr) { - AsciiString::push_str(self, other) + Self::push_str(self, other) } } diff --git a/vm/src/builtins/super.rs b/vm/src/builtins/super.rs index 6e3c7fde47..2d7e48447f 100644 --- a/vm/src/builtins/super.rs +++ b/vm/src/builtins/super.rs @@ -48,7 +48,7 @@ impl Constructor for PySuper { type Args = FuncArgs; fn py_new(cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult { - let obj = PySuper { + let obj = Self { inner: PyRwLock::new(PySuperInner::new( vm.ctx.types.object_type.to_owned(), // is this correct? vm.ctx.none(), @@ -205,7 +205,7 @@ impl GetDescriptor for PySuper { let zelf_class = zelf.as_object().class(); if zelf_class.is(vm.ctx.types.super_type) { let typ = zelf.inner.read().typ.clone(); - Ok(PySuper { + Ok(Self { inner: PyRwLock::new(PySuperInner::new(typ, obj, vm)?), } .into_ref(&vm.ctx) diff --git a/vm/src/builtins/traceback.rs b/vm/src/builtins/traceback.rs index b0b9555e6e..6caa1a1f07 100644 --- a/vm/src/builtins/traceback.rs +++ b/vm/src/builtins/traceback.rs @@ -28,7 +28,7 @@ impl PyPayload for PyTraceback { #[pyclass] impl PyTraceback { pub fn new(next: Option>, frame: FrameRef, lasti: u32, lineno: LineNumber) -> Self { - PyTraceback { + Self { next: PyMutex::new(next), frame, lasti, @@ -63,7 +63,7 @@ impl PyTraceback { } impl PyTracebackRef { - pub fn iter(&self) -> impl Iterator { + pub fn iter(&self) -> impl Iterator { std::iter::successors(Some(self.clone()), |tb| tb.next.lock().clone()) } } diff --git a/vm/src/builtins/tuple.rs b/vm/src/builtins/tuple.rs index 029417f439..2ee8497dda 100644 --- a/vm/src/builtins/tuple.rs +++ b/vm/src/builtins/tuple.rs @@ -336,7 +336,7 @@ impl PyTuple { let tup_arg = if zelf.class().is(vm.ctx.types.tuple_type) { zelf } else { - PyTuple::new_ref(zelf.elements.clone().into_vec(), &vm.ctx) + Self::new_ref(zelf.elements.clone().into_vec(), &vm.ctx) }; (tup_arg,) } diff --git a/vm/src/builtins/type.rs b/vm/src/builtins/type.rs index 558653366e..b18c16a83f 100644 --- a/vm/src/builtins/type.rs +++ b/vm/src/builtins/type.rs @@ -260,7 +260,7 @@ impl PyType { } let new_type = PyRef::new_ref( - PyType { + Self { base: Some(base), bases: PyRwLock::new(bases), mro: PyRwLock::new(mro), @@ -305,7 +305,7 @@ impl PyType { let mro = base.mro_map_collect(|x| x.to_owned()); let new_type = PyRef::new_ref( - PyType { + Self { base: Some(base), bases, mro: PyRwLock::new(mro), @@ -434,7 +434,7 @@ impl PyType { let mut attributes = PyAttributes::default(); for bc in std::iter::once(self) - .chain(self.mro.read().iter().map(|cls| -> &PyType { cls })) + .chain(self.mro.read().iter().map(|cls| -> &Self { cls })) .rev() { for (name, value) in bc.attributes.read().iter() { @@ -446,7 +446,7 @@ impl PyType { } // bound method for every type - pub(crate) fn __new__(zelf: PyRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn __new__(zelf: PyRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let (subtype, args): (PyRef, FuncArgs) = args.bind(vm)?; if !subtype.fast_issubclass(&zelf) { return Err(vm.new_type_error(format!( @@ -486,13 +486,13 @@ impl PyType { } impl Py { - pub(crate) fn is_subtype(&self, other: &Py) -> bool { + pub(crate) fn is_subtype(&self, other: &Self) -> bool { is_subtype_with_mro(&self.mro.read(), self, other) } /// Equivalent to CPython's PyType_CheckExact macro /// Checks if obj is exactly a type (not a subclass) - pub fn check_exact<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> Option<&'a Py> { + pub fn check_exact<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> Option<&'a Self> { obj.downcast_ref_if_exact::(vm) } @@ -533,7 +533,7 @@ impl Py { } } - pub fn iter_base_chain(&self) -> impl Iterator> { + pub fn iter_base_chain(&self) -> impl Iterator { std::iter::successors(Some(self), |cls| cls.base.as_deref()) } @@ -929,7 +929,7 @@ impl Constructor for PyType { let bases = bases .iter() .map(|obj| { - obj.clone().downcast::().or_else(|obj| { + obj.clone().downcast::().or_else(|obj| { if vm .get_attribute_opt(obj, identifier!(vm, __mro_entries__))? .is_some() diff --git a/vm/src/builtins/weakproxy.rs b/vm/src/builtins/weakproxy.rs index b631e27c34..6f01e5eb22 100644 --- a/vm/src/builtins/weakproxy.rs +++ b/vm/src/builtins/weakproxy.rs @@ -53,7 +53,7 @@ impl Constructor for PyWeakProxy { ) }); // TODO: PyWeakProxy should use the same payload as PyWeak - PyWeakProxy { + Self { weak: referent.downgrade_with_typ(callback.into_option(), weak_cls.clone(), vm)?, } .into_ref_with_type(vm, cls) diff --git a/vm/src/builtins/zip.rs b/vm/src/builtins/zip.rs index 94e0e40331..98371d2f6c 100644 --- a/vm/src/builtins/zip.rs +++ b/vm/src/builtins/zip.rs @@ -36,7 +36,7 @@ impl Constructor for PyZip { fn py_new(cls: PyTypeRef, (iterators, args): Self::Args, vm: &VirtualMachine) -> PyResult { let iterators = iterators.into_vec(); let strict = Radium::new(args.strict.unwrap_or(false)); - PyZip { iterators, strict } + Self { iterators, strict } .into_ref_with_type(vm, cls) .map(Into::into) } diff --git a/vm/src/bytes_inner.rs b/vm/src/bytes_inner.rs index 8f189ee35e..692e489b90 100644 --- a/vm/src/bytes_inner.rs +++ b/vm/src/bytes_inner.rs @@ -30,7 +30,7 @@ pub struct PyBytesInner { } impl From> for PyBytesInner { - fn from(elements: Vec) -> PyBytesInner { + fn from(elements: Vec) -> Self { Self { elements } } } @@ -344,7 +344,7 @@ impl PyBytesInner { pub fn contains( &self, - needle: Either, + needle: Either, vm: &VirtualMachine, ) -> PyResult { Ok(match needle { @@ -554,7 +554,7 @@ impl PyBytesInner { pub fn join( &self, - iterable: ArgIterable, + iterable: ArgIterable, vm: &VirtualMachine, ) -> PyResult> { let iter = iterable.iter(vm)?; @@ -576,8 +576,8 @@ impl PyBytesInner { } pub fn maketrans( - from: PyBytesInner, - to: PyBytesInner, + from: Self, + to: Self, vm: &VirtualMachine, ) -> PyResult> { if from.len() != to.len() { @@ -618,7 +618,7 @@ impl PyBytesInner { Ok(res) } - pub fn strip(&self, chars: OptionalOption) -> Vec { + pub fn strip(&self, chars: OptionalOption) -> Vec { self.elements .py_strip( chars, @@ -628,7 +628,7 @@ impl PyBytesInner { .to_vec() } - pub fn lstrip(&self, chars: OptionalOption) -> &[u8] { + pub fn lstrip(&self, chars: OptionalOption) -> &[u8] { self.elements.py_strip( chars, |s, chars| s.trim_start_with(|c| chars.contains(&(c as u8))), @@ -636,7 +636,7 @@ impl PyBytesInner { ) } - pub fn rstrip(&self, chars: OptionalOption) -> &[u8] { + pub fn rstrip(&self, chars: OptionalOption) -> &[u8] { self.elements.py_strip( chars, |s, chars| s.trim_end_with(|c| chars.contains(&(c as u8))), @@ -645,7 +645,7 @@ impl PyBytesInner { } // new in Python 3.9 - pub fn removeprefix(&self, prefix: PyBytesInner) -> Vec { + pub fn removeprefix(&self, prefix: Self) -> Vec { self.elements .py_removeprefix(&prefix.elements, prefix.elements.len(), |s, p| { s.starts_with(p) @@ -654,7 +654,7 @@ impl PyBytesInner { } // new in Python 3.9 - pub fn removesuffix(&self, suffix: PyBytesInner) -> Vec { + pub fn removesuffix(&self, suffix: Self) -> Vec { self.elements .py_removesuffix(&suffix.elements, suffix.elements.len(), |s, p| { s.ends_with(p) @@ -705,7 +705,7 @@ impl PyBytesInner { pub fn partition( &self, - sub: &PyBytesInner, + sub: &Self, vm: &VirtualMachine, ) -> PyResult<(Vec, bool, Vec)> { self.elements.py_partition( @@ -717,7 +717,7 @@ impl PyBytesInner { pub fn rpartition( &self, - sub: &PyBytesInner, + sub: &Self, vm: &VirtualMachine, ) -> PyResult<(Vec, bool, Vec)> { self.elements.py_partition( @@ -771,7 +771,7 @@ impl PyBytesInner { } // len(self)>=1, from="", len(to)>=1, max_count>=1 - fn replace_interleave(&self, to: PyBytesInner, max_count: Option) -> Vec { + fn replace_interleave(&self, to: Self, max_count: Option) -> Vec { let place_count = self.elements.len() + 1; let count = max_count.map_or(place_count, |v| std::cmp::min(v, place_count)) - 1; let capacity = self.elements.len() + count * to.len(); @@ -786,7 +786,7 @@ impl PyBytesInner { result } - fn replace_delete(&self, from: PyBytesInner, max_count: Option) -> Vec { + fn replace_delete(&self, from: Self, max_count: Option) -> Vec { let count = count_substring( self.elements.as_slice(), from.elements.as_slice(), @@ -817,8 +817,8 @@ impl PyBytesInner { pub fn replace_in_place( &self, - from: PyBytesInner, - to: PyBytesInner, + from: Self, + to: Self, max_count: Option, ) -> Vec { let len = from.len(); @@ -849,8 +849,8 @@ impl PyBytesInner { fn replace_general( &self, - from: PyBytesInner, - to: PyBytesInner, + from: Self, + to: Self, max_count: Option, vm: &VirtualMachine, ) -> PyResult> { @@ -894,8 +894,8 @@ impl PyBytesInner { pub fn replace( &self, - from: PyBytesInner, - to: PyBytesInner, + from: Self, + to: Self, max_count: OptionalArg, vm: &VirtualMachine, ) -> PyResult> { @@ -1040,11 +1040,11 @@ impl AnyStrWrapper<[u8]> for PyBytesInner { impl AnyStrContainer<[u8]> for Vec { fn new() -> Self { - Vec::new() + Self::new() } fn with_capacity(capacity: usize) -> Self { - Vec::with_capacity(capacity) + Self::with_capacity(capacity) } fn push_str(&mut self, other: &[u8]) { diff --git a/vm/src/codecs.rs b/vm/src/codecs.rs index 0f55c438d6..59c5d66fde 100644 --- a/vm/src/codecs.rs +++ b/vm/src/codecs.rs @@ -42,7 +42,7 @@ impl PyCodec { #[inline] pub fn from_tuple(tuple: PyTupleRef) -> Result { if tuple.len() == 4 { - Ok(PyCodec(tuple)) + Ok(Self(tuple)) } else { Err(tuple) } @@ -139,7 +139,7 @@ impl TryFromObject for PyCodec { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { obj.downcast::() .ok() - .and_then(|tuple| PyCodec::from_tuple(tuple).ok()) + .and_then(|tuple| Self::from_tuple(tuple).ok()) .ok_or_else(|| vm.new_type_error("codec search functions must return 4-tuples")) } } @@ -190,7 +190,7 @@ impl CodecsRegistry { search_cache: HashMap::new(), errors, }; - CodecsRegistry { + Self { inner: PyRwLock::new(inner), } } diff --git a/vm/src/convert/try_from.rs b/vm/src/convert/try_from.rs index 44d666c294..479ef69ffe 100644 --- a/vm/src/convert/try_from.rs +++ b/vm/src/convert/try_from.rs @@ -125,13 +125,13 @@ impl TryFromObject for std::time::Duration { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { use std::time::Duration; if let Some(float) = obj.payload::() { - Ok(Duration::from_secs_f64(float.to_f64())) + Ok(Self::from_secs_f64(float.to_f64())) } else if let Some(int) = obj.try_index_opt(vm) { let sec = int? .as_bigint() .to_u64() .ok_or_else(|| vm.new_value_error("value out of range"))?; - Ok(Duration::from_secs(sec)) + Ok(Self::from_secs(sec)) } else { Err(vm.new_type_error(format!( "expected an int or float for duration, got {}", diff --git a/vm/src/coroutine.rs b/vm/src/coroutine.rs index 82a31ef80c..5e0ca62cae 100644 --- a/vm/src/coroutine.rs +++ b/vm/src/coroutine.rs @@ -11,8 +11,8 @@ impl ExecutionResult { /// Turn an ExecutionResult into a PyResult that would be returned from a generator or coroutine fn into_iter_return(self, vm: &VirtualMachine) -> PyIterReturn { match self { - ExecutionResult::Yield(value) => PyIterReturn::Return(value), - ExecutionResult::Return(value) => { + Self::Yield(value) => PyIterReturn::Return(value), + Self::Return(value) => { let arg = if vm.is_none(&value) { None } else { @@ -49,7 +49,7 @@ fn gen_name(jen: &PyObject, vm: &VirtualMachine) -> &'static str { impl Coro { pub fn new(frame: FrameRef, name: PyStrRef) -> Self { - Coro { + Self { frame, closed: AtomicCell::new(false), running: AtomicCell::new(false), diff --git a/vm/src/dict_inner.rs b/vm/src/dict_inner.rs index 02d882106c..000a22b6e3 100644 --- a/vm/src/dict_inner.rs +++ b/vm/src/dict_inner.rs @@ -795,7 +795,7 @@ impl DictKey for PyStrInterned { #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { - let zelf: &'static PyStrInterned = unsafe { &*(self as *const _) }; + let zelf: &'static Self = unsafe { &*(self as *const _) }; zelf.to_exact() } @@ -890,7 +890,7 @@ impl DictKey for str { } impl DictKey for String { - type Owned = String; + type Owned = Self; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { @@ -951,7 +951,7 @@ impl DictKey for Wtf8 { } impl DictKey for Wtf8Buf { - type Owned = Wtf8Buf; + type Owned = Self; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { @@ -1012,7 +1012,7 @@ impl DictKey for [u8] { } impl DictKey for Vec { - type Owned = Vec; + type Owned = Self; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { @@ -1037,7 +1037,7 @@ impl DictKey for Vec { } impl DictKey for usize { - type Owned = usize; + type Owned = Self; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { diff --git a/vm/src/exceptions.rs b/vm/src/exceptions.rs index 7544bcc99f..1e816145dd 100644 --- a/vm/src/exceptions.rs +++ b/vm/src/exceptions.rs @@ -547,8 +547,8 @@ macro_rules! extend_exception { } impl PyBaseException { - pub(crate) fn new(args: Vec, vm: &VirtualMachine) -> PyBaseException { - PyBaseException { + pub(crate) fn new(args: Vec, vm: &VirtualMachine) -> Self { + Self { traceback: PyRwLock::new(None), cause: PyRwLock::new(None), context: PyRwLock::new(None), @@ -688,10 +688,10 @@ impl Constructor for PyBaseException { type Args = FuncArgs; fn py_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - if cls.is(PyBaseException::class(&vm.ctx)) && !args.kwargs.is_empty() { + if cls.is(Self::class(&vm.ctx)) && !args.kwargs.is_empty() { return Err(vm.new_type_error("BaseException() takes no keyword arguments")); } - PyBaseException::new(args.args, vm) + Self::new(args.args, vm) .into_ref_with_type(vm, cls) .map(Into::into) } diff --git a/vm/src/format.rs b/vm/src/format.rs index 0b01806e0b..0fea4dedf5 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -12,35 +12,35 @@ use crate::common::wtf8::{Wtf8, Wtf8Buf}; impl IntoPyException for FormatSpecError { fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { - FormatSpecError::DecimalDigitsTooMany => { + Self::DecimalDigitsTooMany => { vm.new_value_error("Too many decimal digits in format string") } - FormatSpecError::PrecisionTooBig => vm.new_value_error("Precision too big"), - FormatSpecError::InvalidFormatSpecifier => { + Self::PrecisionTooBig => vm.new_value_error("Precision too big"), + Self::InvalidFormatSpecifier => { vm.new_value_error("Invalid format specifier") } - FormatSpecError::UnspecifiedFormat(c1, c2) => { + Self::UnspecifiedFormat(c1, c2) => { let msg = format!("Cannot specify '{c1}' with '{c2}'."); vm.new_value_error(msg) } - FormatSpecError::UnknownFormatCode(c, s) => { + Self::UnknownFormatCode(c, s) => { let msg = format!("Unknown format code '{c}' for object of type '{s}'"); vm.new_value_error(msg) } - FormatSpecError::PrecisionNotAllowed => { + Self::PrecisionNotAllowed => { vm.new_value_error("Precision not allowed in integer format specifier") } - FormatSpecError::NotAllowed(s) => { + Self::NotAllowed(s) => { let msg = format!("{s} not allowed with integer format specifier 'c'"); vm.new_value_error(msg) } - FormatSpecError::UnableToConvert => { + Self::UnableToConvert => { vm.new_value_error("Unable to convert int to float") } - FormatSpecError::CodeNotInRange => { + Self::CodeNotInRange => { vm.new_overflow_error("%c arg not in range(0x110000)") } - FormatSpecError::NotImplemented(c, s) => { + Self::NotImplemented(c, s) => { let msg = format!("Format code '{c}' for object of type '{s}' not implemented yet"); vm.new_value_error(msg) } @@ -51,7 +51,7 @@ impl IntoPyException for FormatSpecError { impl ToPyException for FormatParseError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { - FormatParseError::UnmatchedBracket => { + Self::UnmatchedBracket => { vm.new_value_error("expected '}' before end of string") } _ => vm.new_value_error("Unexpected error parsing format string"), diff --git a/vm/src/frame.rs b/vm/src/frame.rs index 41d80b454f..50b73c8677 100644 --- a/vm/src/frame.rs +++ b/vm/src/frame.rs @@ -142,7 +142,7 @@ impl Frame { closure: &[PyCellRef], func_obj: Option, vm: &VirtualMachine, - ) -> Frame { + ) -> Self { let cells_frees = std::iter::repeat_with(|| PyCell::default().into_ref(&vm.ctx)) .take(code.cellvars.len()) .chain(closure.iter().cloned()) @@ -155,7 +155,7 @@ impl Frame { lasti: 0, }; - Frame { + Self { fastlocals: PyMutex::new(vec![None; code.varnames.len()].into_boxed_slice()), cells_frees, locals: scope.locals, @@ -2285,7 +2285,7 @@ impl fmt::Debug for Frame { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let state = self.state.lock(); let stack_str = state.stack.iter().fold(String::new(), |mut s, elem| { - if elem.payload_is::() { + if elem.payload_is::() { s.push_str("\n > {frame}"); } else { std::fmt::write(&mut s, format_args!("\n > {elem:?}")).unwrap(); diff --git a/vm/src/function/argument.rs b/vm/src/function/argument.rs index b4ba3bd578..aef5061ff2 100644 --- a/vm/src/function/argument.rs +++ b/vm/src/function/argument.rs @@ -78,7 +78,7 @@ where A: Into, { fn from(args: A) -> Self { - FuncArgs { + Self { args: args.into().into_vec(), kwargs: IndexMap::new(), } @@ -87,7 +87,7 @@ where impl From for FuncArgs { fn from(kwargs: KwArgs) -> Self { - FuncArgs { + Self { args: Vec::new(), kwargs: kwargs.0, } @@ -125,7 +125,7 @@ impl FuncArgs { let kwargs = kwarg_names.zip_eq(args).collect::>(); - FuncArgs { + Self { args: pos_args, kwargs, } @@ -250,7 +250,7 @@ pub enum ArgumentError { impl From for ArgumentError { fn from(ex: PyBaseExceptionRef) -> Self { - ArgumentError::Exception(ex) + Self::Exception(ex) } } @@ -262,23 +262,23 @@ impl ArgumentError { vm: &VirtualMachine, ) -> PyBaseExceptionRef { match self { - ArgumentError::TooFewArgs => vm.new_type_error(format!( + Self::TooFewArgs => vm.new_type_error(format!( "Expected at least {} arguments ({} given)", arity.start(), num_given )), - ArgumentError::TooManyArgs => vm.new_type_error(format!( + Self::TooManyArgs => vm.new_type_error(format!( "Expected at most {} arguments ({} given)", arity.end(), num_given )), - ArgumentError::InvalidKeywordArgument(name) => { + Self::InvalidKeywordArgument(name) => { vm.new_type_error(format!("{name} is an invalid keyword argument")) } - ArgumentError::RequiredKeywordArgument(name) => { + Self::RequiredKeywordArgument(name) => { vm.new_type_error(format!("Required keyword only argument {name}")) } - ArgumentError::Exception(ex) => ex, + Self::Exception(ex) => ex, } } } @@ -345,7 +345,7 @@ where impl KwArgs { pub const fn new(map: IndexMap) -> Self { - KwArgs(map) + Self(map) } pub fn pop_kwarg(&mut self, name: &str) -> Option { @@ -359,13 +359,13 @@ impl KwArgs { impl FromIterator<(String, T)> for KwArgs { fn from_iter>(iter: I) -> Self { - KwArgs(iter.into_iter().collect()) + Self(iter.into_iter().collect()) } } impl Default for KwArgs { fn default() -> Self { - KwArgs(IndexMap::new()) + Self(IndexMap::new()) } } @@ -378,7 +378,7 @@ where for (name, value) in args.remaining_keywords() { kwargs.insert(name, value.try_into_value(vm)?); } - Ok(KwArgs(kwargs)) + Ok(Self(kwargs)) } } @@ -459,7 +459,7 @@ where while let Some(value) = args.take_positional() { varargs.push(value.try_into_value(vm)?); } - Ok(PosArgs(varargs)) + Ok(Self(varargs)) } } @@ -501,8 +501,8 @@ where { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { - OptionalArg::Present(o) => o.traverse(tracer_fn), - OptionalArg::Missing => (), + Self::Present(o) => o.traverse(tracer_fn), + Self::Missing => (), } } } @@ -532,9 +532,9 @@ where fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { let r = if let Some(value) = args.take_positional() { - OptionalArg::Present(value.try_into_value(vm)?) + Self::Present(value.try_into_value(vm)?) } else { - OptionalArg::Missing + Self::Missing }; Ok(r) } diff --git a/vm/src/function/arithmetic.rs b/vm/src/function/arithmetic.rs index 9f40ca7fec..0ea15ba3ed 100644 --- a/vm/src/function/arithmetic.rs +++ b/vm/src/function/arithmetic.rs @@ -34,8 +34,8 @@ where { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { match self { - PyArithmeticValue::Implemented(v) => v.to_pyobject(vm), - PyArithmeticValue::NotImplemented => vm.ctx.not_implemented(), + Self::Implemented(v) => v.to_pyobject(vm), + Self::NotImplemented => vm.ctx.not_implemented(), } } } diff --git a/vm/src/function/buffer.rs b/vm/src/function/buffer.rs index d18f79cc56..8a2a471ac9 100644 --- a/vm/src/function/buffer.rs +++ b/vm/src/function/buffer.rs @@ -173,7 +173,7 @@ impl TryFromObject for ArgAsciiBuffer { match obj.downcast::() { Ok(string) => { if string.as_str().is_ascii() { - Ok(ArgAsciiBuffer::String(string)) + Ok(Self::String(string)) } else { Err(vm.new_value_error("string argument should contain only ASCII characters")) } diff --git a/vm/src/function/either.rs b/vm/src/function/either.rs index 08b96c7fe3..8700c6150d 100644 --- a/vm/src/function/either.rs +++ b/vm/src/function/either.rs @@ -28,7 +28,7 @@ impl, B: AsRef> AsRef for Either { } } -impl, B: Into> From> for PyObjectRef { +impl, B: Into> From> for PyObjectRef { #[inline(always)] fn from(value: Either) -> Self { match value { diff --git a/vm/src/function/fspath.rs b/vm/src/function/fspath.rs index c23111e76d..5e0108986d 100644 --- a/vm/src/function/fspath.rs +++ b/vm/src/function/fspath.rs @@ -27,11 +27,11 @@ impl FsPath { let pathlike = match_class!(match obj { s @ PyStr => { check_nul(s.as_bytes())?; - FsPath::Str(s) + Self::Str(s) } b @ PyBytes => { check_nul(&b)?; - FsPath::Bytes(b) + Self::Bytes(b) } obj => return Ok(Err(obj)), }); @@ -61,30 +61,30 @@ impl FsPath { pub fn as_os_str(&self, vm: &VirtualMachine) -> PyResult> { // TODO: FS encodings match self { - FsPath::Str(s) => vm.fsencode(s), - FsPath::Bytes(b) => Self::bytes_as_os_str(b.as_bytes(), vm).map(Cow::Borrowed), + Self::Str(s) => vm.fsencode(s), + Self::Bytes(b) => Self::bytes_as_os_str(b.as_bytes(), vm).map(Cow::Borrowed), } } pub fn as_bytes(&self) -> &[u8] { // TODO: FS encodings match self { - FsPath::Str(s) => s.as_bytes(), - FsPath::Bytes(b) => b.as_bytes(), + Self::Str(s) => s.as_bytes(), + Self::Bytes(b) => b.as_bytes(), } } pub fn to_string_lossy(&self) -> Cow<'_, str> { match self { - FsPath::Str(s) => s.to_string_lossy(), - FsPath::Bytes(s) => String::from_utf8_lossy(s), + Self::Str(s) => s.to_string_lossy(), + Self::Bytes(s) => String::from_utf8_lossy(s), } } pub fn to_path_buf(&self, vm: &VirtualMachine) -> PyResult { let path = match self { - FsPath::Str(s) => PathBuf::from(s.as_str()), - FsPath::Bytes(b) => PathBuf::from(Self::bytes_as_os_str(b, vm)?), + Self::Str(s) => PathBuf::from(s.as_str()), + Self::Bytes(b) => PathBuf::from(Self::bytes_as_os_str(b, vm)?), }; Ok(path) } diff --git a/vm/src/function/number.rs b/vm/src/function/number.rs index bead82123e..7bb37b8f54 100644 --- a/vm/src/function/number.rs +++ b/vm/src/function/number.rs @@ -41,7 +41,7 @@ impl TryFromObject for ArgIntoComplex { let (value, _) = obj.try_complex(vm)?.ok_or_else(|| { vm.new_type_error(format!("must be real number, not {}", obj.class().name())) })?; - Ok(ArgIntoComplex { value }) + Ok(Self { value }) } } @@ -86,7 +86,7 @@ impl TryFromObject for ArgIntoFloat { // Equivalent to PyFloat_AsDouble. fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let value = obj.try_float(vm)?.to_f64(); - Ok(ArgIntoFloat { value }) + Ok(Self { value }) } } diff --git a/vm/src/function/protocol.rs b/vm/src/function/protocol.rs index 0f146fed95..0601a9f968 100644 --- a/vm/src/function/protocol.rs +++ b/vm/src/function/protocol.rs @@ -50,7 +50,7 @@ impl AsRef for ArgCallable { impl From for PyObjectRef { #[inline(always)] - fn from(value: ArgCallable) -> PyObjectRef { + fn from(value: ArgCallable) -> Self { value.obj } } @@ -63,7 +63,7 @@ impl TryFromObject for ArgCallable { ); }; let call = callable.call; - Ok(ArgCallable { obj, call }) + Ok(Self { obj, call }) } } @@ -175,7 +175,7 @@ impl Deref for ArgMapping { impl From for PyObjectRef { #[inline(always)] - fn from(value: ArgMapping) -> PyObjectRef { + fn from(value: ArgMapping) -> Self { value.obj } } diff --git a/vm/src/intern.rs b/vm/src/intern.rs index 08e41bb5b5..92a02a2648 100644 --- a/vm/src/intern.rs +++ b/vm/src/intern.rs @@ -311,7 +311,7 @@ impl MaybeInternedString for Py { #[inline(always)] fn as_interned(&self) -> Option<&'static PyStrInterned> { if self.as_object().is_interned() { - Some(unsafe { std::mem::transmute::<&Py, &PyInterned>(self) }) + Some(unsafe { std::mem::transmute::<&Self, &PyInterned>(self) }) } else { None } diff --git a/vm/src/object/core.rs b/vm/src/object/core.rs index 253d8fda63..cfb290c73d 100644 --- a/vm/src/object/core.rs +++ b/vm/src/object/core.rs @@ -164,7 +164,7 @@ cfg_if::cfg_if! { impl WeakRefList { pub fn new() -> Self { - WeakRefList { + Self { inner: OncePtr::new(), } } @@ -268,7 +268,7 @@ impl WeakRefList { (inner.ref_count == 0).then_some(ptr) }; if let Some(ptr) = to_dealloc { - unsafe { WeakRefList::dealloc(ptr) } + unsafe { Self::dealloc(ptr) } } } @@ -369,7 +369,7 @@ impl PyWeak { fn drop_inner(&self) { let dealloc = { let mut guard = unsafe { self.parent.as_ref().lock() }; - let offset = std::mem::offset_of!(PyInner, payload); + let offset = std::mem::offset_of!(PyInner, payload); let py_inner = (self as *const Self) .cast::() .wrapping_sub(offset) @@ -446,7 +446,7 @@ impl InstanceDict { impl PyInner { fn new(payload: T, typ: PyTypeRef, dict: Option) -> Box { let member_count = typ.slots.member_count; - Box::new(PyInner { + Box::new(Self { ref_count: RefCount::new(), typeid: TypeId::of::(), vtable: PyObjVTable::of::(), @@ -546,7 +546,7 @@ impl PyObjectRef { if self.payload_is::() { // SAFETY: just checked that the payload is T, and PyRef is repr(transparent) over // PyObjectRef - Some(unsafe { &*(self as *const PyObjectRef as *const PyRef) }) + Some(unsafe { &*(self as *const Self as *const PyRef) }) } else { None } @@ -572,7 +572,7 @@ impl PyObjectRef { pub unsafe fn downcast_unchecked_ref(&self) -> &Py { debug_assert!(self.payload_is::()); // SAFETY: requirements forwarded from caller - unsafe { &*(self as *const PyObjectRef as *const PyRef) } + unsafe { &*(self as *const Self as *const PyRef) } } // ideally we'd be able to define these in pyobject.rs, but method visibility rules are weird @@ -758,7 +758,7 @@ impl PyObject { pub unsafe fn downcast_unchecked_ref(&self) -> &Py { debug_assert!(self.payload_is::()); // SAFETY: requirements forwarded from caller - unsafe { &*(self as *const PyObject as *const Py) } + unsafe { &*(self as *const Self as *const Py) } } #[inline(always)] @@ -772,7 +772,7 @@ impl PyObject { } #[inline(always)] - pub const fn as_raw(&self) -> *const PyObject { + pub const fn as_raw(&self) -> *const Self { self } @@ -819,7 +819,7 @@ impl PyObject { /// Can only be called when ref_count has dropped to zero. `ptr` must be valid #[inline(never)] - unsafe fn drop_slow(ptr: NonNull) { + unsafe fn drop_slow(ptr: NonNull) { if let Err(()) = unsafe { ptr.as_ref().drop_slow_inner() } { // abort drop for whatever reason return; @@ -862,9 +862,9 @@ impl AsRef for PyObjectRef { } } -impl AsRef for PyObject { +impl AsRef for PyObject { #[inline(always)] - fn as_ref(&self) -> &PyObject { + fn as_ref(&self) -> &Self { self } } @@ -1084,7 +1084,7 @@ where #[inline] fn from(value: PyRef) -> Self { let me = ManuallyDrop::new(value); - PyObjectRef { ptr: me.ptr.cast() } + Self { ptr: me.ptr.cast() } } } diff --git a/vm/src/object/ext.rs b/vm/src/object/ext.rs index 41443aa56f..a635d856c0 100644 --- a/vm/src/object/ext.rs +++ b/vm/src/object/ext.rs @@ -493,7 +493,7 @@ impl AsObject for T where T: Borrow {} impl PyObject { #[inline(always)] fn unique_id(&self) -> usize { - self as *const PyObject as usize + self as *const Self as usize } } diff --git a/vm/src/object/traverse.rs b/vm/src/object/traverse.rs index 3e2efefdff..31bee8bece 100644 --- a/vm/src/object/traverse.rs +++ b/vm/src/object/traverse.rs @@ -144,8 +144,8 @@ unsafe impl Traverse for Either { #[inline] fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { - Either::A(a) => a.traverse(tracer_fn), - Either::B(b) => b.traverse(tracer_fn), + Self::A(a) => a.traverse(tracer_fn), + Self::B(b) => b.traverse(tracer_fn), } } } diff --git a/vm/src/object/traverse_object.rs b/vm/src/object/traverse_object.rs index 55204080bc..ee32785950 100644 --- a/vm/src/object/traverse_object.rs +++ b/vm/src/object/traverse_object.rs @@ -17,7 +17,7 @@ pub(in crate::object) struct PyObjVTable { impl PyObjVTable { pub const fn of() -> &'static Self { - &PyObjVTable { + &Self { drop_dealloc: drop_dealloc_obj::, debug: debug_obj::, trace: const { @@ -49,7 +49,7 @@ unsafe impl Traverse for PyInner { if let Some(f) = self.vtable.trace { unsafe { - let zelf = &*(self as *const PyInner as *const PyObject); + let zelf = &*(self as *const Self as *const PyObject); f(zelf, tracer_fn) } }; diff --git a/vm/src/ospath.rs b/vm/src/ospath.rs index 3351d821ae..dde1f47af0 100644 --- a/vm/src/ospath.rs +++ b/vm/src/ospath.rs @@ -44,13 +44,13 @@ impl OsPath { } } - pub(crate) fn from_fspath(fspath: FsPath, vm: &VirtualMachine) -> PyResult { + pub(crate) fn from_fspath(fspath: FsPath, vm: &VirtualMachine) -> PyResult { let path = fspath.as_os_str(vm)?.into_owned(); let mode = match fspath { FsPath::Str(_) => OutputMode::String, FsPath::Bytes(_) => OutputMode::Bytes, }; - Ok(OsPath { path, mode }) + Ok(Self { path, mode }) } pub fn as_path(&self) -> &Path { @@ -119,8 +119,8 @@ impl From for OsPathOrFd { impl OsPathOrFd { pub fn filename(&self, vm: &VirtualMachine) -> PyObjectRef { match self { - OsPathOrFd::Path(path) => path.filename(vm), - OsPathOrFd::Fd(fd) => vm.ctx.new_int(*fd).into(), + Self::Path(path) => path.filename(vm), + Self::Fd(fd) => vm.ctx.new_int(*fd).into(), } } } diff --git a/vm/src/protocol/buffer.rs b/vm/src/protocol/buffer.rs index 0770cb5a83..1b1a4a14df 100644 --- a/vm/src/protocol/buffer.rs +++ b/vm/src/protocol/buffer.rs @@ -65,7 +65,7 @@ impl PyBuffer { pub fn from_byte_vector(bytes: Vec, vm: &VirtualMachine) -> Self { let bytes_len = bytes.len(); - PyBuffer::new( + Self::new( PyPayload::into_pyobject(VecBuffer::from(bytes), vm), BufferDescriptor::simple(bytes_len, true), &VEC_BUFFER_METHODS, diff --git a/vm/src/protocol/iter.rs b/vm/src/protocol/iter.rs index d05bd26a8a..da7ab17382 100644 --- a/vm/src/protocol/iter.rs +++ b/vm/src/protocol/iter.rs @@ -76,8 +76,8 @@ impl PyIter { } } -impl From> for PyObjectRef { - fn from(value: PyIter) -> PyObjectRef { +impl From> for PyObjectRef { + fn from(value: PyIter) -> Self { value.0 } } @@ -132,7 +132,7 @@ impl TryFromObject for PyIter { }; if let Some(get_iter) = get_iter { let iter = get_iter(iter_target, vm)?; - if PyIter::check(&iter) { + if Self::check(&iter) { Ok(Self(iter)) } else { Err(vm.new_type_error(format!( @@ -160,8 +160,8 @@ pub enum PyIterReturn { unsafe impl Traverse for PyIterReturn { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { - PyIterReturn::Return(r) => r.traverse(tracer_fn), - PyIterReturn::StopIteration(Some(obj)) => obj.traverse(tracer_fn), + Self::Return(r) => r.traverse(tracer_fn), + Self::StopIteration(Some(obj)) => obj.traverse(tracer_fn), _ => (), } } diff --git a/vm/src/protocol/mapping.rs b/vm/src/protocol/mapping.rs index 6b60ae6e05..f5da3f7de6 100644 --- a/vm/src/protocol/mapping.rs +++ b/vm/src/protocol/mapping.rs @@ -41,7 +41,7 @@ impl PyMappingMethods { } #[allow(clippy::declare_interior_mutable_const)] - pub const NOT_IMPLEMENTED: PyMappingMethods = PyMappingMethods { + pub const NOT_IMPLEMENTED: Self = Self { length: AtomicCell::new(None), subscript: AtomicCell::new(None), ass_subscript: AtomicCell::new(None), diff --git a/vm/src/protocol/number.rs b/vm/src/protocol/number.rs index 0a05cbfb8a..ec5f6d9795 100644 --- a/vm/src/protocol/number.rs +++ b/vm/src/protocol/number.rs @@ -159,7 +159,7 @@ pub struct PyNumberMethods { impl PyNumberMethods { /// this is NOT a global variable - pub const NOT_IMPLEMENTED: PyNumberMethods = PyNumberMethods { + pub const NOT_IMPLEMENTED: Self = Self { add: None, subtract: None, multiply: None, @@ -197,7 +197,7 @@ impl PyNumberMethods { inplace_matrix_multiply: None, }; - pub fn not_implemented() -> &'static PyNumberMethods { + pub fn not_implemented() -> &'static Self { static GLOBAL_NOT_IMPLEMENTED: PyNumberMethods = PyNumberMethods::NOT_IMPLEMENTED; &GLOBAL_NOT_IMPLEMENTED } diff --git a/vm/src/protocol/object.rs b/vm/src/protocol/object.rs index dc3bb3d7bd..498db0b26e 100644 --- a/vm/src/protocol/object.rs +++ b/vm/src/protocol/object.rs @@ -273,7 +273,7 @@ impl PyObject { vm: &VirtualMachine, ) -> PyResult> { let swapped = op.swapped(); - let call_cmp = |obj: &PyObject, other: &PyObject, op| { + let call_cmp = |obj: &Self, other: &Self, op| { let cmp = obj .class() .mro_find_map(|cls| cls.slots.richcompare.load()) @@ -409,7 +409,7 @@ impl PyObject { } } - fn abstract_issubclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { + fn abstract_issubclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult { // Store the current derived class to check let mut bases: PyTupleRef; let mut derived = self; @@ -457,7 +457,7 @@ impl PyObject { Ok(false) } - fn recursive_issubclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { + fn recursive_issubclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult { // Fast path for both being types (matches CPython's PyType_Check) if let Some(cls) = PyType::check(cls) && let Some(derived) = PyType::check(self) @@ -485,14 +485,14 @@ impl PyObject { /// Real issubclass check without going through __subclasscheck__ /// This is equivalent to CPython's _PyObject_RealIsSubclass which just calls recursive_issubclass - pub fn real_is_subclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { + pub fn real_is_subclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult { self.recursive_issubclass(cls, vm) } /// Determines if `self` is a subclass of `cls`, either directly, indirectly or virtually /// via the __subclasscheck__ magic method. /// PyObject_IsSubclass/object_issubclass - pub fn is_subclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { + pub fn is_subclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult { let derived = self; // PyType_CheckExact(cls) if cls.class().is(vm.ctx.types.type_type) { @@ -536,13 +536,13 @@ impl PyObject { } // _PyObject_RealIsInstance - pub(crate) fn real_is_instance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { + pub(crate) fn real_is_instance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult { self.object_isinstance(cls, vm) } /// Real isinstance check without going through __instancecheck__ /// This is equivalent to CPython's _PyObject_RealIsInstance/object_isinstance - fn object_isinstance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { + fn object_isinstance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult { if let Ok(cls) = cls.try_to_ref::(vm) { // PyType_Check(cls) - cls is a type object let mut retval = self.class().is_subtype(cls); @@ -581,12 +581,12 @@ impl PyObject { /// Determines if `self` is an instance of `cls`, either directly, indirectly or virtually via /// the __instancecheck__ magic method. - pub fn is_instance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { + pub fn is_instance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult { self.object_recursive_isinstance(cls, vm) } // This is object_recursive_isinstance from CPython's Objects/abstract.c - fn object_recursive_isinstance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult { + fn object_recursive_isinstance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult { // PyObject_TypeCheck(inst, (PyTypeObject *)cls) // This is an exact check of the type if self.class().is(cls) { diff --git a/vm/src/protocol/sequence.rs b/vm/src/protocol/sequence.rs index fbd8d63409..0bfbc0ffc5 100644 --- a/vm/src/protocol/sequence.rs +++ b/vm/src/protocol/sequence.rs @@ -50,7 +50,7 @@ impl Debug for PySequenceMethods { impl PySequenceMethods { #[allow(clippy::declare_interior_mutable_const)] - pub const NOT_IMPLEMENTED: PySequenceMethods = PySequenceMethods { + pub const NOT_IMPLEMENTED: Self = Self { length: AtomicCell::new(None), concat: AtomicCell::new(None), repeat: AtomicCell::new(None), diff --git a/vm/src/py_io.rs b/vm/src/py_io.rs index 87df9a73d8..6b82bbd478 100644 --- a/vm/src/py_io.rs +++ b/vm/src/py_io.rs @@ -45,7 +45,7 @@ where impl Write for String { type Error = fmt::Error; fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result { - ::write_fmt(self, args) + ::write_fmt(self, args) } } diff --git a/vm/src/scope.rs b/vm/src/scope.rs index 7515468d78..9311fa5c2d 100644 --- a/vm/src/scope.rs +++ b/vm/src/scope.rs @@ -16,22 +16,22 @@ impl fmt::Debug for Scope { impl Scope { #[inline] - pub fn new(locals: Option, globals: PyDictRef) -> Scope { + pub fn new(locals: Option, globals: PyDictRef) -> Self { let locals = locals.unwrap_or_else(|| ArgMapping::from_dict_exact(globals.clone())); - Scope { locals, globals } + Self { locals, globals } } pub fn with_builtins( locals: Option, globals: PyDictRef, vm: &VirtualMachine, - ) -> Scope { + ) -> Self { if !globals.contains_key("__builtins__", vm) { globals .set_item("__builtins__", vm.builtins.clone().into(), vm) .unwrap(); } - Scope::new(locals, globals) + Self::new(locals, globals) } // pub fn get_locals(&self) -> &PyDictRef { diff --git a/vm/src/sequence.rs b/vm/src/sequence.rs index 5d66822460..e75c0a6da5 100644 --- a/vm/src/sequence.rs +++ b/vm/src/sequence.rs @@ -139,7 +139,7 @@ where } impl SequenceMutExt for Vec { - fn as_vec_mut(&mut self) -> &mut Vec { + fn as_vec_mut(&mut self) -> &mut Self { self } } diff --git a/vm/src/sliceable.rs b/vm/src/sliceable.rs index 13035fadc2..b394e6f183 100644 --- a/vm/src/sliceable.rs +++ b/vm/src/sliceable.rs @@ -306,7 +306,7 @@ impl SequenceIndexOp for isize { let mut p = *self; if p < 0 { // casting to isize is ok because it is used by wrapping_add - p = p.wrapping_add(len as isize); + p = p.wrapping_add(len as Self); } if p < 0 || (p as usize) >= len { None diff --git a/vm/src/stdlib/ast/basic.rs b/vm/src/stdlib/ast/basic.rs index 4ed1e9e03d..c6ad8fa228 100644 --- a/vm/src/stdlib/ast/basic.rs +++ b/vm/src/stdlib/ast/basic.rs @@ -14,7 +14,7 @@ impl Node for ruff::Identifier { object: PyObjectRef, ) -> PyResult { let py_str = PyStrRef::try_from_object(vm, object)?; - Ok(ruff::Identifier::new(py_str.as_str(), TextRange::default())) + Ok(Self::new(py_str.as_str(), TextRange::default())) } } diff --git a/vm/src/stdlib/ast/exception.rs b/vm/src/stdlib/ast/exception.rs index 4f3b4de60d..c4ecf8831b 100644 --- a/vm/src/stdlib/ast/exception.rs +++ b/vm/src/stdlib/ast/exception.rs @@ -4,7 +4,7 @@ use super::*; impl Node for ruff::ExceptHandler { fn ast_to_object(self, vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { match self { - ruff::ExceptHandler::ExceptHandler(cons) => cons.ast_to_object(vm, source_code), + Self::ExceptHandler(cons) => cons.ast_to_object(vm, source_code), } } fn ast_from_object( @@ -15,7 +15,7 @@ impl Node for ruff::ExceptHandler { let _cls = _object.class(); Ok( if _cls.is(pyast::NodeExceptHandlerExceptHandler::static_type()) { - ruff::ExceptHandler::ExceptHandler( + Self::ExceptHandler( ruff::ExceptHandlerExceptHandler::ast_from_object(_vm, source_code, _object)?, ) } else { @@ -30,7 +30,7 @@ impl Node for ruff::ExceptHandler { // constructor impl Node for ruff::ExceptHandlerExceptHandler { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::ExceptHandlerExceptHandler { + let Self { type_, name, body, diff --git a/vm/src/stdlib/ast/expression.rs b/vm/src/stdlib/ast/expression.rs index 69cf534669..8999c2c92c 100644 --- a/vm/src/stdlib/ast/expression.rs +++ b/vm/src/stdlib/ast/expression.rs @@ -679,7 +679,7 @@ impl Node for ruff::ExprAwait { // constructor impl Node for ruff::ExprYield { fn ast_to_object(self, vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::ExprYield { value, range } = self; + let Self { value, range } = self; let node = NodeAst .into_ref_with_type(vm, pyast::NodeExprYield::static_type().to_owned()) .unwrap(); @@ -695,7 +695,7 @@ impl Node for ruff::ExprYield { source_code: &SourceCodeOwned, object: PyObjectRef, ) -> PyResult { - Ok(ruff::ExprYield { + Ok(Self { value: get_node_field_opt(vm, &object, "value")? .map(|obj| Node::ast_from_object(vm, source_code, obj)) .transpose()?, @@ -1020,7 +1020,7 @@ impl Node for ruff::ExprName { // constructor impl Node for ruff::ExprList { fn ast_to_object(self, vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::ExprList { elts, ctx, range } = self; + let Self { elts, ctx, range } = self; let node = NodeAst .into_ref_with_type(vm, pyast::NodeExprList::static_type().to_owned()) .unwrap(); @@ -1038,7 +1038,7 @@ impl Node for ruff::ExprList { source_code: &SourceCodeOwned, object: PyObjectRef, ) -> PyResult { - Ok(ruff::ExprList { + Ok(Self { elts: Node::ast_from_object( vm, source_code, diff --git a/vm/src/stdlib/ast/statement.rs b/vm/src/stdlib/ast/statement.rs index 61b6c0eaff..3636c4ab6d 100644 --- a/vm/src/stdlib/ast/statement.rs +++ b/vm/src/stdlib/ast/statement.rs @@ -4,31 +4,31 @@ use crate::stdlib::ast::argument::{merge_class_def_args, split_class_def_args}; impl Node for ruff::Stmt { fn ast_to_object(self, vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { match self { - ruff::Stmt::FunctionDef(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::ClassDef(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Return(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Delete(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Assign(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::TypeAlias(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::AugAssign(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::AnnAssign(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::For(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::While(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::If(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::With(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Match(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Raise(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Try(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Assert(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Import(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::ImportFrom(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Global(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Nonlocal(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Expr(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Pass(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Break(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::Continue(cons) => cons.ast_to_object(vm, source_code), - ruff::Stmt::IpyEscapeCommand(_) => { + Self::FunctionDef(cons) => cons.ast_to_object(vm, source_code), + Self::ClassDef(cons) => cons.ast_to_object(vm, source_code), + Self::Return(cons) => cons.ast_to_object(vm, source_code), + Self::Delete(cons) => cons.ast_to_object(vm, source_code), + Self::Assign(cons) => cons.ast_to_object(vm, source_code), + Self::TypeAlias(cons) => cons.ast_to_object(vm, source_code), + Self::AugAssign(cons) => cons.ast_to_object(vm, source_code), + Self::AnnAssign(cons) => cons.ast_to_object(vm, source_code), + Self::For(cons) => cons.ast_to_object(vm, source_code), + Self::While(cons) => cons.ast_to_object(vm, source_code), + Self::If(cons) => cons.ast_to_object(vm, source_code), + Self::With(cons) => cons.ast_to_object(vm, source_code), + Self::Match(cons) => cons.ast_to_object(vm, source_code), + Self::Raise(cons) => cons.ast_to_object(vm, source_code), + Self::Try(cons) => cons.ast_to_object(vm, source_code), + Self::Assert(cons) => cons.ast_to_object(vm, source_code), + Self::Import(cons) => cons.ast_to_object(vm, source_code), + Self::ImportFrom(cons) => cons.ast_to_object(vm, source_code), + Self::Global(cons) => cons.ast_to_object(vm, source_code), + Self::Nonlocal(cons) => cons.ast_to_object(vm, source_code), + Self::Expr(cons) => cons.ast_to_object(vm, source_code), + Self::Pass(cons) => cons.ast_to_object(vm, source_code), + Self::Break(cons) => cons.ast_to_object(vm, source_code), + Self::Continue(cons) => cons.ast_to_object(vm, source_code), + Self::IpyEscapeCommand(_) => { unimplemented!("IPython escape command is not allowed in Python AST") } } @@ -42,117 +42,117 @@ impl Node for ruff::Stmt { ) -> PyResult { let _cls = _object.class(); Ok(if _cls.is(pyast::NodeStmtFunctionDef::static_type()) { - ruff::Stmt::FunctionDef(ruff::StmtFunctionDef::ast_from_object( + Self::FunctionDef(ruff::StmtFunctionDef::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtAsyncFunctionDef::static_type()) { - ruff::Stmt::FunctionDef(ruff::StmtFunctionDef::ast_from_object( + Self::FunctionDef(ruff::StmtFunctionDef::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtClassDef::static_type()) { - ruff::Stmt::ClassDef(ruff::StmtClassDef::ast_from_object( + Self::ClassDef(ruff::StmtClassDef::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtReturn::static_type()) { - ruff::Stmt::Return(ruff::StmtReturn::ast_from_object( + Self::Return(ruff::StmtReturn::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtDelete::static_type()) { - ruff::Stmt::Delete(ruff::StmtDelete::ast_from_object( + Self::Delete(ruff::StmtDelete::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtAssign::static_type()) { - ruff::Stmt::Assign(ruff::StmtAssign::ast_from_object( + Self::Assign(ruff::StmtAssign::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtTypeAlias::static_type()) { - ruff::Stmt::TypeAlias(ruff::StmtTypeAlias::ast_from_object( + Self::TypeAlias(ruff::StmtTypeAlias::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtAugAssign::static_type()) { - ruff::Stmt::AugAssign(ruff::StmtAugAssign::ast_from_object( + Self::AugAssign(ruff::StmtAugAssign::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtAnnAssign::static_type()) { - ruff::Stmt::AnnAssign(ruff::StmtAnnAssign::ast_from_object( + Self::AnnAssign(ruff::StmtAnnAssign::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtFor::static_type()) { - ruff::Stmt::For(ruff::StmtFor::ast_from_object(_vm, source_code, _object)?) + Self::For(ruff::StmtFor::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtAsyncFor::static_type()) { - ruff::Stmt::For(ruff::StmtFor::ast_from_object(_vm, source_code, _object)?) + Self::For(ruff::StmtFor::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtWhile::static_type()) { - ruff::Stmt::While(ruff::StmtWhile::ast_from_object(_vm, source_code, _object)?) + Self::While(ruff::StmtWhile::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtIf::static_type()) { - ruff::Stmt::If(ruff::StmtIf::ast_from_object(_vm, source_code, _object)?) + Self::If(ruff::StmtIf::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtWith::static_type()) { - ruff::Stmt::With(ruff::StmtWith::ast_from_object(_vm, source_code, _object)?) + Self::With(ruff::StmtWith::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtAsyncWith::static_type()) { - ruff::Stmt::With(ruff::StmtWith::ast_from_object(_vm, source_code, _object)?) + Self::With(ruff::StmtWith::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtMatch::static_type()) { - ruff::Stmt::Match(ruff::StmtMatch::ast_from_object(_vm, source_code, _object)?) + Self::Match(ruff::StmtMatch::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtRaise::static_type()) { - ruff::Stmt::Raise(ruff::StmtRaise::ast_from_object(_vm, source_code, _object)?) + Self::Raise(ruff::StmtRaise::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtTry::static_type()) { - ruff::Stmt::Try(ruff::StmtTry::ast_from_object(_vm, source_code, _object)?) + Self::Try(ruff::StmtTry::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtTryStar::static_type()) { - ruff::Stmt::Try(ruff::StmtTry::ast_from_object(_vm, source_code, _object)?) + Self::Try(ruff::StmtTry::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtAssert::static_type()) { - ruff::Stmt::Assert(ruff::StmtAssert::ast_from_object( + Self::Assert(ruff::StmtAssert::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtImport::static_type()) { - ruff::Stmt::Import(ruff::StmtImport::ast_from_object( + Self::Import(ruff::StmtImport::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtImportFrom::static_type()) { - ruff::Stmt::ImportFrom(ruff::StmtImportFrom::ast_from_object( + Self::ImportFrom(ruff::StmtImportFrom::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtGlobal::static_type()) { - ruff::Stmt::Global(ruff::StmtGlobal::ast_from_object( + Self::Global(ruff::StmtGlobal::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtNonlocal::static_type()) { - ruff::Stmt::Nonlocal(ruff::StmtNonlocal::ast_from_object( + Self::Nonlocal(ruff::StmtNonlocal::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeStmtExpr::static_type()) { - ruff::Stmt::Expr(ruff::StmtExpr::ast_from_object(_vm, source_code, _object)?) + Self::Expr(ruff::StmtExpr::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtPass::static_type()) { - ruff::Stmt::Pass(ruff::StmtPass::ast_from_object(_vm, source_code, _object)?) + Self::Pass(ruff::StmtPass::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtBreak::static_type()) { - ruff::Stmt::Break(ruff::StmtBreak::ast_from_object(_vm, source_code, _object)?) + Self::Break(ruff::StmtBreak::ast_from_object(_vm, source_code, _object)?) } else if _cls.is(pyast::NodeStmtContinue::static_type()) { - ruff::Stmt::Continue(ruff::StmtContinue::ast_from_object( + Self::Continue(ruff::StmtContinue::ast_from_object( _vm, source_code, _object, @@ -342,7 +342,7 @@ impl Node for ruff::StmtClassDef { // constructor impl Node for ruff::StmtReturn { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtReturn { + let Self { value, range: _range, } = self; @@ -360,7 +360,7 @@ impl Node for ruff::StmtReturn { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtReturn { + Ok(Self { value: get_node_field_opt(_vm, &_object, "value")? .map(|obj| Node::ast_from_object(_vm, source_code, obj)) .transpose()?, @@ -371,7 +371,7 @@ impl Node for ruff::StmtReturn { // constructor impl Node for ruff::StmtDelete { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtDelete { + let Self { targets, range: _range, } = self; @@ -389,7 +389,7 @@ impl Node for ruff::StmtDelete { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtDelete { + Ok(Self { targets: Node::ast_from_object( _vm, source_code, @@ -447,7 +447,7 @@ impl Node for ruff::StmtAssign { // constructor impl Node for ruff::StmtTypeAlias { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtTypeAlias { + let Self { name, type_params, value, @@ -475,7 +475,7 @@ impl Node for ruff::StmtTypeAlias { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtTypeAlias { + Ok(Self { name: Node::ast_from_object( _vm, source_code, @@ -955,7 +955,7 @@ impl Node for ruff::StmtTry { // constructor impl Node for ruff::StmtAssert { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtAssert { + let Self { test, msg, range: _range, @@ -976,7 +976,7 @@ impl Node for ruff::StmtAssert { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtAssert { + Ok(Self { test: Node::ast_from_object( _vm, source_code, @@ -992,7 +992,7 @@ impl Node for ruff::StmtAssert { // constructor impl Node for ruff::StmtImport { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtImport { + let Self { names, range: _range, } = self; @@ -1010,7 +1010,7 @@ impl Node for ruff::StmtImport { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtImport { + Ok(Self { names: Node::ast_from_object( _vm, source_code, @@ -1067,7 +1067,7 @@ impl Node for ruff::StmtImportFrom { // constructor impl Node for ruff::StmtGlobal { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtGlobal { + let Self { names, range: _range, } = self; @@ -1085,7 +1085,7 @@ impl Node for ruff::StmtGlobal { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtGlobal { + Ok(Self { names: Node::ast_from_object( _vm, source_code, @@ -1098,7 +1098,7 @@ impl Node for ruff::StmtGlobal { // constructor impl Node for ruff::StmtNonlocal { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtNonlocal { + let Self { names, range: _range, } = self; @@ -1116,7 +1116,7 @@ impl Node for ruff::StmtNonlocal { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtNonlocal { + Ok(Self { names: Node::ast_from_object( _vm, source_code, @@ -1129,7 +1129,7 @@ impl Node for ruff::StmtNonlocal { // constructor impl Node for ruff::StmtExpr { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtExpr { + let Self { value, range: _range, } = self; @@ -1147,7 +1147,7 @@ impl Node for ruff::StmtExpr { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtExpr { + Ok(Self { value: Node::ast_from_object( _vm, source_code, @@ -1160,7 +1160,7 @@ impl Node for ruff::StmtExpr { // constructor impl Node for ruff::StmtPass { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtPass { range: _range } = self; + let Self { range: _range } = self; let node = NodeAst .into_ref_with_type(_vm, pyast::NodeStmtPass::static_type().to_owned()) .unwrap(); @@ -1173,7 +1173,7 @@ impl Node for ruff::StmtPass { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtPass { + Ok(Self { range: range_from_object(_vm, source_code, _object, "Pass")?, }) } @@ -1181,7 +1181,7 @@ impl Node for ruff::StmtPass { // constructor impl Node for ruff::StmtBreak { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtBreak { range: _range } = self; + let Self { range: _range } = self; let node = NodeAst .into_ref_with_type(_vm, pyast::NodeStmtBreak::static_type().to_owned()) .unwrap(); @@ -1194,7 +1194,7 @@ impl Node for ruff::StmtBreak { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtBreak { + Ok(Self { range: range_from_object(_vm, source_code, _object, "Break")?, }) } @@ -1202,7 +1202,7 @@ impl Node for ruff::StmtBreak { // constructor impl Node for ruff::StmtContinue { fn ast_to_object(self, _vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { - let ruff::StmtContinue { range: _range } = self; + let Self { range: _range } = self; let node = NodeAst .into_ref_with_type(_vm, pyast::NodeStmtContinue::static_type().to_owned()) .unwrap(); @@ -1215,7 +1215,7 @@ impl Node for ruff::StmtContinue { source_code: &SourceCodeOwned, _object: PyObjectRef, ) -> PyResult { - Ok(ruff::StmtContinue { + Ok(Self { range: range_from_object(_vm, source_code, _object, "Continue")?, }) } diff --git a/vm/src/stdlib/ast/string.rs b/vm/src/stdlib/ast/string.rs index 0d55d6f1e2..2c43dd7b86 100644 --- a/vm/src/stdlib/ast/string.rs +++ b/vm/src/stdlib/ast/string.rs @@ -255,8 +255,8 @@ pub(super) enum JoinedStrPart { impl Node for JoinedStrPart { fn ast_to_object(self, vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { match self { - JoinedStrPart::FormattedValue(value) => value.ast_to_object(vm, source_code), - JoinedStrPart::Constant(value) => value.ast_to_object(vm, source_code), + Self::FormattedValue(value) => value.ast_to_object(vm, source_code), + Self::Constant(value) => value.ast_to_object(vm, source_code), } } fn ast_from_object( diff --git a/vm/src/stdlib/ast/type_ignore.rs b/vm/src/stdlib/ast/type_ignore.rs index 7e318f6949..a247302fa6 100644 --- a/vm/src/stdlib/ast/type_ignore.rs +++ b/vm/src/stdlib/ast/type_ignore.rs @@ -8,7 +8,7 @@ pub(super) enum TypeIgnore { impl Node for TypeIgnore { fn ast_to_object(self, vm: &VirtualMachine, source_code: &SourceCodeOwned) -> PyObjectRef { match self { - TypeIgnore::TypeIgnore(cons) => cons.ast_to_object(vm, source_code), + Self::TypeIgnore(cons) => cons.ast_to_object(vm, source_code), } } fn ast_from_object( @@ -18,7 +18,7 @@ impl Node for TypeIgnore { ) -> PyResult { let _cls = _object.class(); Ok(if _cls.is(pyast::NodeTypeIgnoreTypeIgnore::static_type()) { - TypeIgnore::TypeIgnore(TypeIgnoreTypeIgnore::ast_from_object( + Self::TypeIgnore(TypeIgnoreTypeIgnore::ast_from_object( _vm, source_code, _object, diff --git a/vm/src/stdlib/ast/type_parameters.rs b/vm/src/stdlib/ast/type_parameters.rs index 686cee81f4..1856f2c5b8 100644 --- a/vm/src/stdlib/ast/type_parameters.rs +++ b/vm/src/stdlib/ast/type_parameters.rs @@ -38,19 +38,19 @@ impl Node for ruff::TypeParam { ) -> PyResult { let _cls = _object.class(); Ok(if _cls.is(pyast::NodeTypeParamTypeVar::static_type()) { - ruff::TypeParam::TypeVar(ruff::TypeParamTypeVar::ast_from_object( + Self::TypeVar(ruff::TypeParamTypeVar::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeTypeParamParamSpec::static_type()) { - ruff::TypeParam::ParamSpec(ruff::TypeParamParamSpec::ast_from_object( + Self::ParamSpec(ruff::TypeParamParamSpec::ast_from_object( _vm, source_code, _object, )?) } else if _cls.is(pyast::NodeTypeParamTypeVarTuple::static_type()) { - ruff::TypeParam::TypeVarTuple(ruff::TypeParamTypeVarTuple::ast_from_object( + Self::TypeVarTuple(ruff::TypeParamTypeVarTuple::ast_from_object( _vm, source_code, _object, diff --git a/vm/src/stdlib/collections.rs b/vm/src/stdlib/collections.rs index f24d3fb4e3..ab1fd7d4d0 100644 --- a/vm/src/stdlib/collections.rs +++ b/vm/src/stdlib/collections.rs @@ -335,7 +335,7 @@ mod _collections { #[pymethod(name = "__rmul__")] fn __mul__(&self, n: isize, vm: &VirtualMachine) -> PyResult { let deque = self._mul(n, vm)?; - Ok(PyDeque { + Ok(Self { deque: PyRwLock::new(deque), maxlen: self.maxlen, state: AtomicCell::new(0), @@ -365,7 +365,7 @@ mod _collections { } fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult { - if let Some(o) = other.payload_if_subclass::(vm) { + if let Some(o) = other.payload_if_subclass::(vm) { let mut deque = self.borrow_deque().clone(); let elements = o.borrow_deque().clone(); deque.extend(elements); @@ -376,7 +376,7 @@ mod _collections { .unwrap_or(0); deque.drain(..skipped); - Ok(PyDeque { + Ok(Self { deque: PyRwLock::new(deque), maxlen: self.maxlen, state: AtomicCell::new(0), @@ -610,7 +610,7 @@ mod _collections { (DequeIterArgs { deque, index }, _kwargs): Self::Args, vm: &VirtualMachine, ) -> PyResult { - let iter = PyDequeIterator::new(deque); + let iter = Self::new(deque); if let OptionalArg::Present(index) = index { let index = max(index, 0) as usize; iter.internal.lock().position = index; @@ -622,7 +622,7 @@ mod _collections { #[pyclass(with(IterNext, Iterable, Constructor))] impl PyDequeIterator { pub(crate) fn new(deque: PyDequeRef) -> Self { - PyDequeIterator { + Self { state: deque.state.load(), internal: PyMutex::new(PositionIterInternal::new(deque, 0)), } diff --git a/vm/src/stdlib/functools.rs b/vm/src/stdlib/functools.rs index 5449db3c39..21724db892 100644 --- a/vm/src/stdlib/functools.rs +++ b/vm/src/stdlib/functools.rs @@ -216,7 +216,7 @@ mod _functools { // Handle nested partial objects let (final_func, final_args, final_keywords) = - if let Some(partial) = func.downcast_ref::() { + if let Some(partial) = func.downcast_ref::() { let inner = partial.inner.read(); let mut combined_args = inner.args.as_slice().to_vec(); combined_args.extend_from_slice(args_slice); @@ -230,7 +230,7 @@ mod _functools { final_keywords.set_item(vm.ctx.intern_str(key.as_str()), value, vm)?; } - let partial = PyPartial { + let partial = Self { inner: PyRwLock::new(PyPartialInner { func: final_func, args: vm.ctx.new_tuple(final_args), @@ -304,7 +304,7 @@ mod _functools { let class_name = zelf.class().name(); let module = zelf.class().__module__(vm); - let qualified_name = if zelf.class().is(PyPartial::class(&vm.ctx)) { + let qualified_name = if zelf.class().is(Self::class(&vm.ctx)) { // For the base partial class, always use functools.partial "functools.partial".to_owned() } else { diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index bdce5ddcfc..9943f0da2a 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -93,7 +93,7 @@ impl TryFromObject for Fildes { "file descriptor cannot be a negative integer ({fd})" ))); } - Ok(Fildes(fd)) + Ok(Self(fd)) } } @@ -1967,10 +1967,10 @@ mod _io { fn find_newline(&self, s: &Wtf8) -> Result { let len = s.len(); match self { - Newlines::Universal | Newlines::Lf => { + Self::Universal | Self::Lf => { s.find("\n".as_ref()).map(|p| p + 1).ok_or(len) } - Newlines::Passthrough => { + Self::Passthrough => { let bytes = s.as_bytes(); memchr::memchr2(b'\n', b'\r', bytes) .map(|p| { @@ -1984,8 +1984,8 @@ mod _io { }) .ok_or(len) } - Newlines::Cr => s.find("\n".as_ref()).map(|p| p + 1).ok_or(len), - Newlines::Crlf => { + Self::Cr => s.find("\n".as_ref()).map(|p| p + 1).ok_or(len), + Self::Crlf => { // s[searched..] == remaining let mut searched = 0; let mut remaining = s.as_bytes(); @@ -2165,7 +2165,7 @@ mod _io { } } fn take(&mut self, vm: &VirtualMachine) -> PyBytesRef { - let PendingWrites { num_bytes, data } = std::mem::take(self); + let Self { num_bytes, data } = std::mem::take(self); if let PendingWritesData::One(PendingWrite::Bytes(b)) = data { return b; } @@ -3923,7 +3923,7 @@ mod _io { impl Default for OpenArgs { fn default() -> Self { - OpenArgs { + Self { buffering: -1, encoding: None, errors: None, diff --git a/vm/src/stdlib/itertools.rs b/vm/src/stdlib/itertools.rs index e8f5d21c54..a018fe382d 100644 --- a/vm/src/stdlib/itertools.rs +++ b/vm/src/stdlib/itertools.rs @@ -56,7 +56,7 @@ mod decl { source: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - PyItertoolsChain { + Self { source: PyRwLock::new(Some(source.get_iter(vm)?)), active: PyRwLock::new(None), } @@ -195,7 +195,7 @@ mod decl { Self::Args { data, selectors }: Self::Args, vm: &VirtualMachine, ) -> PyResult { - PyItertoolsCompress { data, selectors } + Self { data, selectors } .into_ref_with_type(vm, cls) .map(Into::into) } @@ -1235,7 +1235,7 @@ mod decl { let copyable = if iterable.class().has_attr(identifier!(vm, __copy__)) { vm.call_special_method(iterable.as_object(), identifier!(vm, __copy__), ())? } else { - PyItertoolsTee::from_iter(iterable, vm)? + Self::from_iter(iterable, vm)? }; let mut tee_vec: Vec = Vec::with_capacity(n); @@ -1250,8 +1250,8 @@ mod decl { #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsTee { fn from_iter(iterator: PyIter, vm: &VirtualMachine) -> PyResult { - let class = PyItertoolsTee::class(&vm.ctx); - if iterator.class().is(PyItertoolsTee::class(&vm.ctx)) { + let class = Self::class(&vm.ctx); + if iterator.class().is(Self::class(&vm.ctx)) { return vm.call_special_method(&iterator, identifier!(vm, __copy__), ()); } Ok(Self { diff --git a/vm/src/stdlib/operator.rs b/vm/src/stdlib/operator.rs index 5a2a50ff78..af7ffab7da 100644 --- a/vm/src/stdlib/operator.rs +++ b/vm/src/stdlib/operator.rs @@ -403,7 +403,7 @@ mod _operator { return Err(vm.new_type_error("attribute name must be a string")); } } - PyAttrGetter { attrs } + Self { attrs } .into_ref_with_type(vm, cls) .map(Into::into) } @@ -472,7 +472,7 @@ mod _operator { if args.args.is_empty() { return Err(vm.new_type_error("itemgetter expected 1 argument, got 0.")); } - PyItemGetter { items: args.args } + Self { items: args.args } .into_ref_with_type(vm, cls) .map(Into::into) } @@ -552,7 +552,7 @@ mod _operator { fn py_new(cls: PyTypeRef, (name, args): Self::Args, vm: &VirtualMachine) -> PyResult { if let Ok(name) = name.try_into_value(vm) { - PyMethodCaller { name, args } + Self { name, args } .into_ref_with_type(vm, cls) .map(Into::into) } else { diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index 0349307b27..f5863d8969 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -774,7 +774,7 @@ pub(super) mod _os { #[cfg(not(windows))] let st_reparse_tag = 0; - StatResult { + Self { st_mode: vm.ctx.new_pyref(stat.st_mode), st_ino: vm.ctx.new_pyref(stat.st_ino), st_dev: vm.ctx.new_pyref(stat.st_dev), @@ -817,7 +817,7 @@ pub(super) mod _os { let args: FuncArgs = flatten_args(&args.args).into(); - let stat: StatResult = args.bind(vm)?; + let stat: Self = args.bind(vm)?; Ok(stat.to_pyobject(vm)) } } diff --git a/vm/src/stdlib/posix.rs b/vm/src/stdlib/posix.rs index e7e6782b12..c58446dc96 100644 --- a/vm/src/stdlib/posix.rs +++ b/vm/src/stdlib/posix.rs @@ -184,7 +184,7 @@ pub mod module { } // SAFETY: none, really. but, python's os api of passing around file descriptors // everywhere isn't really io-safe anyway, so, this is passed to the user. - Ok(unsafe { OwnedFd::from_raw_fd(fd) }) + Ok(unsafe { Self::from_raw_fd(fd) }) } } @@ -1152,13 +1152,13 @@ pub mod module { impl TryFromObject for Uid { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, obj, "uid").map(Uid::from_raw) + try_from_id(vm, obj, "uid").map(Self::from_raw) } } impl TryFromObject for Gid { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, obj, "gid").map(Gid::from_raw) + try_from_id(vm, obj, "gid").map(Self::from_raw) } } @@ -2232,7 +2232,7 @@ pub mod module { } impl SysconfVar { - pub const SC_PAGESIZE: SysconfVar = Self::SC_PAGE_SIZE; + pub const SC_PAGESIZE: Self = Self::SC_PAGE_SIZE; } struct SysconfName(i32); diff --git a/vm/src/stdlib/sre.rs b/vm/src/stdlib/sre.rs index da72363e3a..2ee3a42573 100644 --- a/vm/src/stdlib/sre.rs +++ b/vm/src/stdlib/sre.rs @@ -233,7 +233,7 @@ mod _sre { #[pymethod(name = "match")] fn py_match( - zelf: PyRef, + zelf: PyRef, string_args: StringArgs, vm: &VirtualMachine, ) -> PyResult>> { @@ -253,7 +253,7 @@ mod _sre { #[pymethod] fn fullmatch( - zelf: PyRef, + zelf: PyRef, string_args: StringArgs, vm: &VirtualMachine, ) -> PyResult>> { @@ -269,7 +269,7 @@ mod _sre { #[pymethod] fn search( - zelf: PyRef, + zelf: PyRef, string_args: StringArgs, vm: &VirtualMachine, ) -> PyResult>> { @@ -284,7 +284,7 @@ mod _sre { #[pymethod] fn findall( - zelf: PyRef, + zelf: PyRef, string_args: StringArgs, vm: &VirtualMachine, ) -> PyResult> { @@ -314,7 +314,7 @@ mod _sre { #[pymethod] fn finditer( - zelf: PyRef, + zelf: PyRef, string_args: StringArgs, vm: &VirtualMachine, ) -> PyResult { @@ -334,7 +334,7 @@ mod _sre { #[pymethod] fn scanner( - zelf: PyRef, + zelf: PyRef, string_args: StringArgs, vm: &VirtualMachine, ) -> PyRef { @@ -349,18 +349,18 @@ mod _sre { } #[pymethod] - fn sub(zelf: PyRef, sub_args: SubArgs, vm: &VirtualMachine) -> PyResult { + fn sub(zelf: PyRef, sub_args: SubArgs, vm: &VirtualMachine) -> PyResult { Self::sub_impl(zelf, sub_args, false, vm) } #[pymethod] - fn subn(zelf: PyRef, sub_args: SubArgs, vm: &VirtualMachine) -> PyResult { + fn subn(zelf: PyRef, sub_args: SubArgs, vm: &VirtualMachine) -> PyResult { Self::sub_impl(zelf, sub_args, true, vm) } #[pymethod] fn split( - zelf: PyRef, + zelf: PyRef, split_args: SplitArgs, vm: &VirtualMachine, ) -> PyResult> { @@ -416,7 +416,7 @@ mod _sre { } fn sub_impl( - zelf: PyRef, + zelf: PyRef, sub_args: SubArgs, subn: bool, vm: &VirtualMachine, @@ -536,7 +536,7 @@ mod _sre { return Ok(res.into()); } op.eq_only(|| { - if let Some(other) = other.downcast_ref::() { + if let Some(other) = other.downcast_ref::() { Ok(PyComparisonValue::Implemented( zelf.flags == other.flags && zelf.isbytes == other.isbytes @@ -704,7 +704,7 @@ mod _sre { } #[pymethod] - fn expand(zelf: PyRef, template: PyStrRef, vm: &VirtualMachine) -> PyResult { + fn expand(zelf: PyRef, template: PyStrRef, vm: &VirtualMachine) -> PyResult { let re = vm.import("re", 0)?; let func = re.get_attr("_expand", vm)?; func.call((zelf.pattern.clone(), zelf, template), vm) diff --git a/vm/src/stdlib/sys.rs b/vm/src/stdlib/sys.rs index 3011c3b6c0..f7d83a3d71 100644 --- a/vm/src/stdlib/sys.rs +++ b/vm/src/stdlib/sys.rs @@ -1032,7 +1032,7 @@ mod sys { #[pyclass(with(PyStructSequence))] impl PyFloatInfo { - const INFO: Self = PyFloatInfo { + const INFO: Self = Self { max: f64::MAX, max_exp: f64::MAX_EXP, max_10_exp: f64::MAX_10_EXP, @@ -1065,7 +1065,7 @@ mod sys { impl PyHashInfo { const INFO: Self = { use rustpython_common::hash::*; - PyHashInfo { + Self { width: std::mem::size_of::() * 8, modulus: MODULUS, inf: INF, @@ -1090,7 +1090,7 @@ mod sys { #[pyclass(with(PyStructSequence))] impl PyIntInfo { - const INFO: Self = PyIntInfo { + const INFO: Self = Self { bits_per_digit: 30, //? sizeof_digit: std::mem::size_of::(), default_max_str_digits: 4300, @@ -1110,7 +1110,7 @@ mod sys { #[pyclass(with(PyStructSequence))] impl VersionInfo { - pub const VERSION: VersionInfo = VersionInfo { + pub const VERSION: Self = Self { major: version::MAJOR, minor: version::MINOR, micro: version::MICRO, diff --git a/vm/src/stdlib/time.rs b/vm/src/stdlib/time.rs index 562300f6e9..12a47fca87 100644 --- a/vm/src/stdlib/time.rs +++ b/vm/src/stdlib/time.rs @@ -255,15 +255,15 @@ mod decl { /// Construct a localtime from the optional seconds, or get the current local time. fn naive_or_local(self, vm: &VirtualMachine) -> PyResult { Ok(match self { - OptionalArg::Present(secs) => pyobj_to_date_time(secs, vm)?.naive_utc(), - OptionalArg::Missing => chrono::offset::Local::now().naive_local(), + Self::Present(secs) => pyobj_to_date_time(secs, vm)?.naive_utc(), + Self::Missing => chrono::offset::Local::now().naive_local(), }) } fn naive_or_utc(self, vm: &VirtualMachine) -> PyResult { Ok(match self { - OptionalArg::Present(secs) => pyobj_to_date_time(secs, vm)?.naive_utc(), - OptionalArg::Missing => chrono::offset::Utc::now().naive_utc(), + Self::Present(secs) => pyobj_to_date_time(secs, vm)?.naive_utc(), + Self::Missing => chrono::offset::Utc::now().naive_utc(), }) } } @@ -271,8 +271,8 @@ mod decl { impl OptionalArg { fn naive_or_local(self, vm: &VirtualMachine) -> PyResult { Ok(match self { - OptionalArg::Present(t) => t.to_date_time(vm)?, - OptionalArg::Missing => chrono::offset::Local::now().naive_local(), + Self::Present(t) => t.to_date_time(vm)?, + Self::Missing => chrono::offset::Local::now().naive_local(), }) } } @@ -473,7 +473,7 @@ mod decl { local_time.offset().local_minus_utc() + if isdst == 1 { 3600 } else { 0 }; let tz_abbr = local_time.format("%Z").to_string(); - PyStructTime { + Self { tm_year: vm.ctx.new_int(tm.year()).into(), tm_mon: vm.ctx.new_int(tm.month()).into(), tm_mday: vm.ctx.new_int(tm.day()).into(), @@ -563,7 +563,7 @@ mod platform { impl<'a> TryFromBorrowedObject<'a> for ClockId { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { - obj.try_to_value(vm).map(ClockId::from_raw) + obj.try_to_value(vm).map(Self::from_raw) } } diff --git a/vm/src/stdlib/typevar.rs b/vm/src/stdlib/typevar.rs index 9617439a0e..5b0158981d 100644 --- a/vm/src/stdlib/typevar.rs +++ b/vm/src/stdlib/typevar.rs @@ -351,7 +351,7 @@ impl Constructor for TypeVar { (vm.ctx.typing_no_default.clone().into(), vm.ctx.none()) }; - let typevar = TypeVar { + let typevar = Self { name, bound: parking_lot::Mutex::new(bound_obj), evaluate_bound, @@ -601,7 +601,7 @@ impl Constructor for ParamSpec { Some(vm.ctx.typing_no_default.clone().into()) }; - let paramspec = ParamSpec { + let paramspec = Self { name, bound, default_value, @@ -762,7 +762,7 @@ impl Constructor for TypeVarTuple { (vm.ctx.typing_no_default.clone().into(), vm.ctx.none()) }; - let typevartuple = TypeVarTuple { + let typevartuple = Self { name, default_value: parking_lot::Mutex::new(default_value), evaluate_default, @@ -817,7 +817,7 @@ impl Constructor for ParamSpecArgs { fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { let origin = args.0; - let psa = ParamSpecArgs { __origin__: origin }; + let psa = Self { __origin__: origin }; psa.into_ref_with_type(vm, cls).map(Into::into) } } @@ -895,7 +895,7 @@ impl Constructor for ParamSpecKwargs { fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { let origin = args.0; - let psa = ParamSpecKwargs { __origin__: origin }; + let psa = Self { __origin__: origin }; psa.into_ref_with_type(vm, cls).map(Into::into) } } diff --git a/vm/src/stdlib/typing.rs b/vm/src/stdlib/typing.rs index adf261cc65..e05029a8d6 100644 --- a/vm/src/stdlib/typing.rs +++ b/vm/src/stdlib/typing.rs @@ -109,8 +109,8 @@ pub(crate) mod decl { name: PyObjectRef, type_params: PyTupleRef, value: PyObjectRef, - ) -> TypeAliasType { - TypeAliasType { + ) -> Self { + Self { name, type_params, value, diff --git a/vm/src/vm/context.rs b/vm/src/vm/context.rs index 54f3dfabda..a5c0eba2b0 100644 --- a/vm/src/vm/context.rs +++ b/vm/src/vm/context.rs @@ -325,7 +325,7 @@ impl Context { let empty_str = unsafe { string_pool.intern("", types.str_type.to_owned()) }; let empty_bytes = create_object(PyBytes::from(Vec::new()), types.bytes_type); - Context { + Self { true_value, false_value, none, @@ -629,7 +629,7 @@ impl Context { } } -impl AsRef for Context { +impl AsRef for Context { fn as_ref(&self) -> &Self { self } diff --git a/vm/src/vm/method.rs b/vm/src/vm/method.rs index 099d5bb9fb..dc512c2576 100644 --- a/vm/src/vm/method.rs +++ b/vm/src/vm/method.rs @@ -122,8 +122,8 @@ impl PyMethod { pub fn invoke(self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { let (func, args) = match self { - PyMethod::Function { target, func } => (func, args.into_method_args(target, vm)), - PyMethod::Attribute(func) => (func, args.into_args(vm)), + Self::Function { target, func } => (func, args.into_method_args(target, vm)), + Self::Attribute(func) => (func, args.into_args(vm)), }; func.call(args, vm) } @@ -131,10 +131,10 @@ impl PyMethod { #[allow(dead_code)] pub fn invoke_ref(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { let (func, args) = match self { - PyMethod::Function { target, func } => { + Self::Function { target, func } => { (func, args.into_method_args(target.clone(), vm)) } - PyMethod::Attribute(func) => (func, args.into_args(vm)), + Self::Attribute(func) => (func, args.into_args(vm)), }; func.call(args, vm) } diff --git a/vm/src/vm/mod.rs b/vm/src/vm/mod.rs index e3409587a6..4a319c9635 100644 --- a/vm/src/vm/mod.rs +++ b/vm/src/vm/mod.rs @@ -118,7 +118,7 @@ pub fn process_hash_secret_seed() -> u32 { impl VirtualMachine { /// Create a new `VirtualMachine` structure. - fn new(settings: Settings, ctx: PyRc) -> VirtualMachine { + fn new(settings: Settings, ctx: PyRc) -> Self { flame_guard!("new VirtualMachine"); // make a new module without access to the vm; doesn't @@ -159,7 +159,7 @@ impl VirtualMachine { -1 => 4300, other => other, } as usize); - let mut vm = VirtualMachine { + let mut vm = Self { builtins, sys_module, ctx, diff --git a/vm/src/vm/setting.rs b/vm/src/vm/setting.rs index f6fa8ec4a8..caf8c9139d 100644 --- a/vm/src/vm/setting.rs +++ b/vm/src/vm/setting.rs @@ -135,7 +135,7 @@ impl Settings { /// Sensible default settings. impl Default for Settings { fn default() -> Self { - Settings { + Self { debug: 0, inspect: false, interactive: false, diff --git a/vm/src/warn.rs b/vm/src/warn.rs index 761cd69a0d..943fbcee23 100644 --- a/vm/src/warn.rs +++ b/vm/src/warn.rs @@ -28,8 +28,8 @@ impl WarningsState { ]) } - pub fn init_state(ctx: &Context) -> WarningsState { - WarningsState { + pub fn init_state(ctx: &Context) -> Self { + Self { filters: Self::create_filter(ctx), _once_registry: ctx.new_dict(), default_action: ctx.new_str("default"), From a9bbcf33dc04293ee0533b600b9cedae67450396 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:38:01 +0300 Subject: [PATCH 04/11] common --- common/src/atomic.rs | 2 +- common/src/boxvec.rs | 10 ++--- common/src/cformat.rs | 18 ++++----- common/src/format.rs | 70 ++++++++++++++++----------------- common/src/linked_list.rs | 8 ++-- common/src/lock/cell_lock.rs | 6 +-- common/src/lock/thread_mutex.rs | 4 +- common/src/refcount.rs | 2 +- common/src/str.rs | 6 +-- 9 files changed, 63 insertions(+), 63 deletions(-) diff --git a/common/src/atomic.rs b/common/src/atomic.rs index afe4afb444..ef7f41074e 100644 --- a/common/src/atomic.rs +++ b/common/src/atomic.rs @@ -65,7 +65,7 @@ impl Default for OncePtr { impl OncePtr { #[inline] pub fn new() -> Self { - OncePtr { + Self { inner: Radium::new(ptr::null_mut()), } } diff --git a/common/src/boxvec.rs b/common/src/boxvec.rs index 2b464509bd..4f3928e56b 100644 --- a/common/src/boxvec.rs +++ b/common/src/boxvec.rs @@ -38,8 +38,8 @@ macro_rules! panic_oob { } impl BoxVec { - pub fn new(n: usize) -> BoxVec { - BoxVec { + pub fn new(n: usize) -> Self { + Self { xs: Box::new_uninit_slice(n), len: 0, } @@ -593,7 +593,7 @@ where T: Clone, { fn clone(&self) -> Self { - let mut new = BoxVec::new(self.capacity()); + let mut new = Self::new(self.capacity()); new.extend(self.iter().cloned()); new } @@ -676,8 +676,8 @@ pub struct CapacityError { impl CapacityError { /// Create a new `CapacityError` from `element`. - pub const fn new(element: T) -> CapacityError { - CapacityError { element } + pub const fn new(element: T) -> Self { + Self { element } } /// Extract the overflowing element diff --git a/common/src/cformat.rs b/common/src/cformat.rs index 25d9aaca66..5065bd0a49 100644 --- a/common/src/cformat.rs +++ b/common/src/cformat.rs @@ -103,10 +103,10 @@ pub enum CFormatType { impl CFormatType { pub const fn to_char(self) -> char { match self { - CFormatType::Number(x) => x as u8 as char, - CFormatType::Float(x) => x as u8 as char, - CFormatType::Character(x) => x as u8 as char, - CFormatType::String(x) => x as u8 as char, + Self::Number(x) => x as u8 as char, + Self::Float(x) => x as u8 as char, + Self::Character(x) => x as u8 as char, + Self::String(x) => x as u8 as char, } } } @@ -119,7 +119,7 @@ pub enum CFormatPrecision { impl From for CFormatPrecision { fn from(quantity: CFormatQuantity) -> Self { - CFormatPrecision::Quantity(quantity) + Self::Quantity(quantity) } } @@ -338,7 +338,7 @@ impl CFormatSpec { _ => &num_chars, }; let fill_chars_needed = width.saturating_sub(num_chars); - let fill_string: T = CFormatSpec::compute_fill_string(fill_char, fill_chars_needed); + let fill_string: T = Self::compute_fill_string(fill_char, fill_chars_needed); if !fill_string.is_empty() { if self.flags.contains(CConversionFlags::LEFT_ADJUST) { @@ -361,7 +361,7 @@ impl CFormatSpec { _ => &num_chars, }; let fill_chars_needed = width.saturating_sub(num_chars); - let fill_string: T = CFormatSpec::compute_fill_string(fill_char, fill_chars_needed); + let fill_string: T = Self::compute_fill_string(fill_char, fill_chars_needed); if !fill_string.is_empty() { // Don't left-adjust if precision-filling: that will always be prepending 0s to %d @@ -721,13 +721,13 @@ pub enum CFormatPart { impl CFormatPart { #[inline] pub const fn is_specifier(&self) -> bool { - matches!(self, CFormatPart::Spec { .. }) + matches!(self, Self::Spec { .. }) } #[inline] pub const fn has_key(&self) -> bool { match self { - CFormatPart::Spec(s) => s.mapping_key.is_some(), + Self::Spec(s) => s.mapping_key.is_some(), _ => false, } } diff --git a/common/src/format.rs b/common/src/format.rs index 99e2e42d23..b9a780b146 100644 --- a/common/src/format.rs +++ b/common/src/format.rs @@ -38,23 +38,23 @@ impl FormatParse for FormatConversion { } impl FormatConversion { - pub fn from_char(c: CodePoint) -> Option { + pub fn from_char(c: CodePoint) -> Option { match c.to_char_lossy() { - 's' => Some(FormatConversion::Str), - 'r' => Some(FormatConversion::Repr), - 'a' => Some(FormatConversion::Ascii), - 'b' => Some(FormatConversion::Bytes), + 's' => Some(Self::Str), + 'r' => Some(Self::Repr), + 'a' => Some(Self::Ascii), + 'b' => Some(Self::Bytes), _ => None, } } - fn from_string(text: &Wtf8) -> Option { + fn from_string(text: &Wtf8) -> Option { let mut chars = text.code_points(); if chars.next()? != '!' { return None; } - FormatConversion::from_char(chars.next()?) + Self::from_char(chars.next()?) } } @@ -67,12 +67,12 @@ pub enum FormatAlign { } impl FormatAlign { - fn from_char(c: CodePoint) -> Option { + fn from_char(c: CodePoint) -> Option { match c.to_char_lossy() { - '<' => Some(FormatAlign::Left), - '>' => Some(FormatAlign::Right), - '=' => Some(FormatAlign::AfterSign), - '^' => Some(FormatAlign::Center), + '<' => Some(Self::Left), + '>' => Some(Self::Right), + '=' => Some(Self::AfterSign), + '^' => Some(Self::Center), _ => None, } } @@ -141,7 +141,7 @@ pub enum FormatType { } impl From<&FormatType> for char { - fn from(from: &FormatType) -> char { + fn from(from: &FormatType) -> Self { match from { FormatType::String => 's', FormatType::Binary => 'b', @@ -299,7 +299,7 @@ impl FormatSpec { align = align.or(Some(FormatAlign::AfterSign)); } - Ok(FormatSpec { + Ok(Self { conversion, fill, align, @@ -327,7 +327,7 @@ impl FormatSpec { let magnitude_int_str = parts.next().unwrap().to_string(); let dec_digit_cnt = magnitude_str.len() as i32 - magnitude_int_str.len() as i32; let int_digit_cnt = disp_digit_cnt - dec_digit_cnt; - let mut result = FormatSpec::separate_integer(magnitude_int_str, inter, sep, int_digit_cnt); + let mut result = Self::separate_integer(magnitude_int_str, inter, sep, int_digit_cnt); if let Some(part) = parts.next() { result.push_str(&format!(".{part}")) } @@ -350,11 +350,11 @@ impl FormatSpec { // separate with 0 padding let padding = "0".repeat(diff as usize); let padded_num = format!("{padding}{magnitude_str}"); - FormatSpec::insert_separator(padded_num, inter, sep, sep_cnt) + Self::insert_separator(padded_num, inter, sep, sep_cnt) } else { // separate without padding let sep_cnt = (magnitude_len - 1) / inter; - FormatSpec::insert_separator(magnitude_str, inter, sep, sep_cnt) + Self::insert_separator(magnitude_str, inter, sep, sep_cnt) } } @@ -412,7 +412,7 @@ impl FormatSpec { let magnitude_len = magnitude_str.len(); let width = self.width.unwrap_or(magnitude_len) as i32 - prefix.len() as i32; let disp_digit_cnt = cmp::max(width, magnitude_len as i32); - FormatSpec::add_magnitude_separators_for_char( + Self::add_magnitude_separators_for_char( magnitude_str, inter, sep, @@ -640,27 +640,27 @@ impl FormatSpec { "{}{}{}", sign_str, magnitude_str, - FormatSpec::compute_fill_string(fill_char, fill_chars_needed) + Self::compute_fill_string(fill_char, fill_chars_needed) ), FormatAlign::Right => format!( "{}{}{}", - FormatSpec::compute_fill_string(fill_char, fill_chars_needed), + Self::compute_fill_string(fill_char, fill_chars_needed), sign_str, magnitude_str ), FormatAlign::AfterSign => format!( "{}{}{}", sign_str, - FormatSpec::compute_fill_string(fill_char, fill_chars_needed), + Self::compute_fill_string(fill_char, fill_chars_needed), magnitude_str ), FormatAlign::Center => { let left_fill_chars_needed = fill_chars_needed / 2; let right_fill_chars_needed = fill_chars_needed - left_fill_chars_needed; let left_fill_string = - FormatSpec::compute_fill_string(fill_char, left_fill_chars_needed); + Self::compute_fill_string(fill_char, left_fill_chars_needed); let right_fill_string = - FormatSpec::compute_fill_string(fill_char, right_fill_chars_needed); + Self::compute_fill_string(fill_char, right_fill_chars_needed); format!("{left_fill_string}{sign_str}{magnitude_str}{right_fill_string}") } }) @@ -725,7 +725,7 @@ pub enum FormatParseError { impl FromStr for FormatSpec { type Err = FormatSpecError; fn from_str(s: &str) -> Result { - FormatSpec::parse(s) + Self::parse(s) } } @@ -739,7 +739,7 @@ pub enum FieldNamePart { impl FieldNamePart { fn parse_part( chars: &mut impl PeekingNext, - ) -> Result, FormatParseError> { + ) -> Result, FormatParseError> { chars .next() .map(|ch| match ch.to_char_lossy() { @@ -751,7 +751,7 @@ impl FieldNamePart { if attribute.is_empty() { Err(FormatParseError::EmptyAttribute) } else { - Ok(FieldNamePart::Attribute(attribute)) + Ok(Self::Attribute(attribute)) } } '[' => { @@ -761,9 +761,9 @@ impl FieldNamePart { return if index.is_empty() { Err(FormatParseError::EmptyAttribute) } else if let Some(index) = parse_usize(&index) { - Ok(FieldNamePart::Index(index)) + Ok(Self::Index(index)) } else { - Ok(FieldNamePart::StringIndex(index)) + Ok(Self::StringIndex(index)) }; } index.push(ch); @@ -794,7 +794,7 @@ fn parse_usize(s: &Wtf8) -> Option { } impl FieldName { - pub fn parse(text: &Wtf8) -> Result { + pub fn parse(text: &Wtf8) -> Result { let mut chars = text.code_points().peekable(); let first: Wtf8Buf = chars .peeking_take_while(|ch| *ch != '.' && *ch != '[') @@ -813,7 +813,7 @@ impl FieldName { parts.push(part) } - Ok(FieldName { field_type, parts }) + Ok(Self { field_type, parts }) } } @@ -854,7 +854,7 @@ impl FormatString { let mut cur_text = text; let mut result_string = Wtf8Buf::new(); while !cur_text.is_empty() { - match FormatString::parse_literal_single(cur_text) { + match Self::parse_literal_single(cur_text) { Ok((next_char, remaining)) => { result_string.push(next_char); cur_text = remaining; @@ -968,7 +968,7 @@ impl FormatString { } if let Some(pos) = end_bracket_pos { let right = &text[pos..]; - let format_part = FormatString::parse_part_in_brackets(&left)?; + let format_part = Self::parse_part_in_brackets(&left)?; Ok((format_part, &right[1..])) } else { Err(FormatParseError::UnmatchedBracket) @@ -990,14 +990,14 @@ impl<'a> FromTemplate<'a> for FormatString { while !cur_text.is_empty() { // Try to parse both literals and bracketed format parts until we // run out of text - cur_text = FormatString::parse_literal(cur_text) - .or_else(|_| FormatString::parse_spec(cur_text)) + cur_text = Self::parse_literal(cur_text) + .or_else(|_| Self::parse_spec(cur_text)) .map(|(part, new_text)| { parts.push(part); new_text })?; } - Ok(FormatString { + Ok(Self { format_parts: parts, }) } diff --git a/common/src/linked_list.rs b/common/src/linked_list.rs index d3f2ccaff5..29cdcaee9e 100644 --- a/common/src/linked_list.rs +++ b/common/src/linked_list.rs @@ -140,8 +140,8 @@ unsafe impl Sync for Pointers {} impl LinkedList { /// Creates an empty linked list. - pub const fn new() -> LinkedList { - LinkedList { + pub const fn new() -> Self { + Self { head: None, // tail: None, _marker: PhantomData, @@ -323,8 +323,8 @@ where impl Pointers { /// Create a new set of empty pointers - pub fn new() -> Pointers { - Pointers { + pub fn new() -> Self { + Self { inner: UnsafeCell::new(PointersInner { prev: None, next: None, diff --git a/common/src/lock/cell_lock.rs b/common/src/lock/cell_lock.rs index 3d2889d0a4..25a5cfedba 100644 --- a/common/src/lock/cell_lock.rs +++ b/common/src/lock/cell_lock.rs @@ -11,7 +11,7 @@ pub struct RawCellMutex { unsafe impl RawMutex for RawCellMutex { #[allow(clippy::declare_interior_mutable_const)] - const INIT: Self = RawCellMutex { + const INIT: Self = Self { locked: Cell::new(false), }; @@ -61,7 +61,7 @@ impl RawCellRwLock { unsafe impl RawRwLock for RawCellRwLock { #[allow(clippy::declare_interior_mutable_const)] - const INIT: Self = RawCellRwLock { + const INIT: Self = Self { state: Cell::new(0), }; @@ -203,7 +203,7 @@ fn deadlock(lock_kind: &str, ty: &str) -> ! { pub struct SingleThreadId(()); unsafe impl GetThreadId for SingleThreadId { - const INIT: Self = SingleThreadId(()); + const INIT: Self = Self(()); fn nonzero_thread_id(&self) -> NonZero { NonZero::new(1).unwrap() } diff --git a/common/src/lock/thread_mutex.rs b/common/src/lock/thread_mutex.rs index d730818d8f..14f4e68266 100644 --- a/common/src/lock/thread_mutex.rs +++ b/common/src/lock/thread_mutex.rs @@ -21,7 +21,7 @@ pub struct RawThreadMutex { impl RawThreadMutex { #[allow(clippy::declare_interior_mutable_const)] - pub const INIT: Self = RawThreadMutex { + pub const INIT: Self = Self { owner: AtomicUsize::new(0), mutex: R::INIT, get_thread_id: G::INIT, @@ -79,7 +79,7 @@ pub struct ThreadMutex { impl ThreadMutex { pub fn new(val: T) -> Self { - ThreadMutex { + Self { raw: RawThreadMutex::INIT, data: UnsafeCell::new(val), } diff --git a/common/src/refcount.rs b/common/src/refcount.rs index cfafa98a99..a5fbfa8fc3 100644 --- a/common/src/refcount.rs +++ b/common/src/refcount.rs @@ -21,7 +21,7 @@ impl RefCount { const MASK: usize = MAX_REFCOUNT; pub fn new() -> Self { - RefCount { + Self { strong: Radium::new(1), } } diff --git a/common/src/str.rs b/common/src/str.rs index d1222dfb4d..af30ed6dec 100644 --- a/common/src/str.rs +++ b/common/src/str.rs @@ -47,9 +47,9 @@ impl StrKind { #[inline(always)] pub fn can_encode(&self, code: CodePoint) -> bool { match self { - StrKind::Ascii => code.is_ascii(), - StrKind::Utf8 => code.to_char().is_some(), - StrKind::Wtf8 => true, + Self::Ascii => code.is_ascii(), + Self::Utf8 => code.to_char().is_some(), + Self::Wtf8 => true, } } } From 6ad5435c5959af6a1d4fa4b0e243bb78de1885e1 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:39:53 +0300 Subject: [PATCH 05/11] sre engine --- vm/sre_engine/src/engine.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vm/sre_engine/src/engine.rs b/vm/sre_engine/src/engine.rs index 1e0b15fd01..92b62e9f63 100644 --- a/vm/sre_engine/src/engine.rs +++ b/vm/sre_engine/src/engine.rs @@ -1170,7 +1170,7 @@ impl MatchContext { #[must_use] fn next_at(&mut self, code_position: usize, jump: Jump) -> Self { self.jump = jump; - MatchContext { + Self { code_position, jump: Jump::OpCode, count: -1, From c19a7366f36e27ae1e56f2590b6fc5735cab0aa9 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:40:31 +0300 Subject: [PATCH 06/11] compiler --- compiler/src/lib.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/compiler/src/lib.rs b/compiler/src/lib.rs index fde8e96e8a..9ae5297852 100644 --- a/compiler/src/lib.rs +++ b/compiler/src/lib.rs @@ -57,21 +57,21 @@ impl CompileError { pub fn location(&self) -> Option { match self { - CompileError::Codegen(codegen_error) => codegen_error.location.clone(), - CompileError::Parse(parse_error) => Some(parse_error.location.clone()), + Self::Codegen(codegen_error) => codegen_error.location.clone(), + Self::Parse(parse_error) => Some(parse_error.location.clone()), } } pub fn python_location(&self) -> (usize, usize) { match self { - CompileError::Codegen(codegen_error) => { + Self::Codegen(codegen_error) => { if let Some(location) = &codegen_error.location { (location.row.get(), location.column.get()) } else { (0, 0) } } - CompileError::Parse(parse_error) => ( + Self::Parse(parse_error) => ( parse_error.location.row.get(), parse_error.location.column.get(), ), @@ -80,8 +80,8 @@ impl CompileError { pub fn source_path(&self) -> &str { match self { - CompileError::Codegen(codegen_error) => &codegen_error.source_path, - CompileError::Parse(parse_error) => &parse_error.source_path, + Self::Codegen(codegen_error) => &codegen_error.source_path, + Self::Parse(parse_error) => &parse_error.source_path, } } } From dbdecccac351debcf4f45d562a8d3342db84d26a Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:41:24 +0300 Subject: [PATCH 07/11] compiler core --- compiler/core/src/bytecode.rs | 54 +++++++++++++++++------------------ compiler/core/src/frozen.rs | 8 +++--- compiler/core/src/mode.rs | 6 ++-- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/compiler/core/src/bytecode.rs b/compiler/core/src/bytecode.rs index 8100146cc3..2ad0e97969 100644 --- a/compiler/core/src/bytecode.rs +++ b/compiler/core/src/bytecode.rs @@ -36,16 +36,16 @@ impl Constant for ConstantData { fn borrow_constant(&self) -> BorrowedConstant<'_, Self> { use BorrowedConstant::*; match self { - ConstantData::Integer { value } => Integer { value }, - ConstantData::Float { value } => Float { value: *value }, - ConstantData::Complex { value } => Complex { value: *value }, - ConstantData::Boolean { value } => Boolean { value: *value }, - ConstantData::Str { value } => Str { value }, - ConstantData::Bytes { value } => Bytes { value }, - ConstantData::Code { code } => Code { code }, - ConstantData::Tuple { elements } => Tuple { elements }, - ConstantData::None => None, - ConstantData::Ellipsis => Ellipsis, + Self::Integer { value } => Integer { value }, + Self::Float { value } => Float { value: *value }, + Self::Complex { value } => Complex { value: *value }, + Self::Boolean { value } => Boolean { value: *value }, + Self::Str { value } => Str { value }, + Self::Bytes { value } => Bytes { value }, + Self::Code { code } => Code { code }, + Self::Tuple { elements } => Tuple { elements }, + Self::None => None, + Self::Ellipsis => Ellipsis, } } } @@ -136,15 +136,15 @@ bitflags! { } impl CodeFlags { - pub const NAME_MAPPING: &'static [(&'static str, CodeFlags)] = &[ - ("GENERATOR", CodeFlags::IS_GENERATOR), - ("COROUTINE", CodeFlags::IS_COROUTINE), + pub const NAME_MAPPING: &'static [(&'static str, Self)] = &[ + ("GENERATOR", Self::IS_GENERATOR), + ("COROUTINE", Self::IS_COROUTINE), ( "ASYNC_GENERATOR", Self::from_bits_truncate(Self::IS_GENERATOR.bits() | Self::IS_COROUTINE.bits()), ), - ("VARARGS", CodeFlags::HAS_VARARGS), - ("VARKEYWORDS", CodeFlags::HAS_VARKEYWORDS), + ("VARARGS", Self::HAS_VARARGS), + ("VARKEYWORDS", Self::HAS_VARKEYWORDS), ]; } @@ -154,7 +154,7 @@ impl CodeFlags { pub struct OpArgByte(pub u8); impl OpArgByte { pub const fn null() -> Self { - OpArgByte(0) + Self(0) } } impl fmt::Debug for OpArgByte { @@ -169,7 +169,7 @@ impl fmt::Debug for OpArgByte { pub struct OpArg(pub u32); impl OpArg { pub const fn null() -> Self { - OpArg(0) + Self(0) } /// Returns how many CodeUnits a instruction with this op_arg will be encoded as @@ -281,7 +281,7 @@ pub struct Arg(PhantomData); impl Arg { #[inline] pub fn marker() -> Self { - Arg(PhantomData) + Self(PhantomData) } #[inline] pub fn new(arg: T) -> (Self, OpArg) { @@ -333,7 +333,7 @@ pub struct Label(pub u32); impl OpArgType for Label { #[inline(always)] fn from_op_arg(x: u32) -> Option { - Some(Label(x)) + Some(Self(x)) } #[inline(always)] fn to_op_arg(self) -> u32 { @@ -351,10 +351,10 @@ impl OpArgType for ConversionFlag { #[inline] fn from_op_arg(x: u32) -> Option { match x as u8 { - b's' => Some(ConversionFlag::Str), - b'a' => Some(ConversionFlag::Ascii), - b'r' => Some(ConversionFlag::Repr), - std::u8::MAX => Some(ConversionFlag::None), + b's' => Some(Self::Str), + b'a' => Some(Self::Ascii), + b'r' => Some(Self::Repr), + std::u8::MAX => Some(Self::None), _ => None, } } @@ -631,9 +631,9 @@ const _: () = assert!(mem::size_of::() == 1); impl From for u8 { #[inline] - fn from(ins: Instruction) -> u8 { + fn from(ins: Instruction) -> Self { // SAFETY: there's no padding bits - unsafe { std::mem::transmute::(ins) } + unsafe { std::mem::transmute::(ins) } } } @@ -643,7 +643,7 @@ impl TryFrom for Instruction { #[inline] fn try_from(value: u8) -> Result { if value <= u8::from(LAST_INSTRUCTION) { - Ok(unsafe { std::mem::transmute::(value) }) + Ok(unsafe { std::mem::transmute::(value) }) } else { Err(crate::marshal::MarshalError::InvalidBytecode) } @@ -680,7 +680,7 @@ bitflags! { impl OpArgType for MakeFunctionFlags { #[inline(always)] fn from_op_arg(x: u32) -> Option { - MakeFunctionFlags::from_bits(x as u8) + Self::from_bits(x as u8) } #[inline(always)] fn to_op_arg(self) -> u32 { diff --git a/compiler/core/src/frozen.rs b/compiler/core/src/frozen.rs index 991898c1ea..466a914f04 100644 --- a/compiler/core/src/frozen.rs +++ b/compiler/core/src/frozen.rs @@ -32,7 +32,7 @@ impl FrozenCodeObject> { let mut data = Vec::new(); marshal::serialize_code(&mut data, code); let bytes = lz4_flex::compress_prepend_size(&data); - FrozenCodeObject { bytes } + Self { bytes } } } @@ -42,8 +42,8 @@ pub struct FrozenLib { } impl + ?Sized> FrozenLib { - pub const fn from_ref(b: &B) -> &FrozenLib { - unsafe { &*(b as *const B as *const FrozenLib) } + pub const fn from_ref(b: &B) -> &Self { + unsafe { &*(b as *const B as *const Self) } } /// Decode a library to a iterable of frozen modules @@ -100,7 +100,7 @@ fn read_entry<'a>( impl FrozenLib> { /// Encode the given iterator of frozen modules into a compressed vector of bytes - pub fn encode<'a, I, B: AsRef<[u8]>>(lib: I) -> FrozenLib> + pub fn encode<'a, I, B: AsRef<[u8]>>(lib: I) -> Self where I: IntoIterator), IntoIter: ExactSizeIterator + Clone>, { diff --git a/compiler/core/src/mode.rs b/compiler/core/src/mode.rs index 0c14c3c495..35e9e77f59 100644 --- a/compiler/core/src/mode.rs +++ b/compiler/core/src/mode.rs @@ -13,9 +13,9 @@ impl std::str::FromStr for Mode { // To support `builtins.compile()` `mode` argument fn from_str(s: &str) -> Result { match s { - "exec" => Ok(Mode::Exec), - "eval" => Ok(Mode::Eval), - "single" => Ok(Mode::Single), + "exec" => Ok(Self::Exec), + "eval" => Ok(Self::Eval), + "single" => Ok(Self::Single), _ => Err(ModeParseError), } } From 289256409654cc601dd39fabd358a9ae5818f891 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:43:37 +0300 Subject: [PATCH 08/11] stdlib --- stdlib/src/array.rs | 38 +++++++++++++++++------------------ stdlib/src/bz2.rs | 2 +- stdlib/src/contextvars.rs | 6 +++--- stdlib/src/csv.rs | 28 +++++++++++++------------- stdlib/src/hashlib.rs | 26 ++++++++++++------------ stdlib/src/posixsubprocess.rs | 8 ++++---- stdlib/src/pyexpat.rs | 2 +- stdlib/src/pystruct.rs | 8 ++++---- stdlib/src/resource.rs | 2 +- stdlib/src/select.rs | 10 ++++----- stdlib/src/socket.rs | 6 +++--- stdlib/src/syslog.rs | 4 ++-- stdlib/src/unicodedata.rs | 20 +++++++++--------- stdlib/src/zlib.rs | 18 ++++++++--------- 14 files changed, 89 insertions(+), 89 deletions(-) diff --git a/stdlib/src/array.rs b/stdlib/src/array.rs index b306c52185..6ed176f802 100644 --- a/stdlib/src/array.rs +++ b/stdlib/src/array.rs @@ -632,7 +632,7 @@ mod array { impl From for PyArray { fn from(array: ArrayContentType) -> Self { - PyArray { + Self { array: PyRwLock::new(array), exports: AtomicUsize::new(0), } @@ -659,7 +659,7 @@ mod array { vm.new_type_error("array() argument 1 must be a unicode character, not str") })?; - if cls.is(PyArray::class(&vm.ctx)) && !kwargs.is_empty() { + if cls.is(Self::class(&vm.ctx)) && !kwargs.is_empty() { return Err(vm.new_type_error("array.array() takes no keyword arguments")); } @@ -667,7 +667,7 @@ mod array { ArrayContentType::from_char(spec).map_err(|err| vm.new_value_error(err))?; if let OptionalArg::Present(init) = init { - if let Some(init) = init.payload::() { + if let Some(init) = init.payload::() { match (spec, init.read().typecode()) { (spec, ch) if spec == ch => array.frombytes(&init.get_bytes()), (spec, 'u') => { @@ -765,7 +765,7 @@ mod array { let mut w = zelf.try_resizable(vm)?; if zelf.is(&obj) { w.imul(2, vm) - } else if let Some(array) = obj.payload::() { + } else if let Some(array) = obj.payload::() { w.iadd(&array.read(), vm) } else { let iter = ArgIterable::try_from_object(vm, obj)?; @@ -977,12 +977,12 @@ mod array { } #[pymethod] - fn __copy__(&self) -> PyArray { + fn __copy__(&self) -> Self { self.array.read().clone().into() } #[pymethod] - fn __deepcopy__(&self, _memo: PyObjectRef) -> PyArray { + fn __deepcopy__(&self, _memo: PyObjectRef) -> Self { self.__copy__() } @@ -1013,7 +1013,7 @@ mod array { cloned = zelf.read().clone(); &cloned } else { - match value.payload::() { + match value.payload::() { Some(array) => { guard = array.read(); &*guard @@ -1059,10 +1059,10 @@ mod array { #[pymethod] fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { - if let Some(other) = other.payload::() { + if let Some(other) = other.payload::() { self.read() .add(&other.read(), vm) - .map(|array| PyArray::from(array).into_ref(&vm.ctx)) + .map(|array| Self::from(array).into_ref(&vm.ctx)) } else { Err(vm.new_type_error(format!( "can only append array (not \"{}\") to array", @@ -1079,7 +1079,7 @@ mod array { ) -> PyResult> { if zelf.is(&other) { zelf.try_resizable(vm)?.imul(2, vm)?; - } else if let Some(other) = other.payload::() { + } else if let Some(other) = other.payload::() { zelf.try_resizable(vm)?.iadd(&other.read(), vm)?; } else { return Err(vm.new_type_error(format!( @@ -1454,17 +1454,17 @@ mod array { } impl From for u8 { - fn from(code: MachineFormatCode) -> u8 { + fn from(code: MachineFormatCode) -> Self { use MachineFormatCode::*; match code { - Int8 { signed } => signed as u8, - Int16 { signed, big_endian } => 2 + signed as u8 * 2 + big_endian as u8, - Int32 { signed, big_endian } => 6 + signed as u8 * 2 + big_endian as u8, - Int64 { signed, big_endian } => 10 + signed as u8 * 2 + big_endian as u8, - Ieee754Float { big_endian } => 14 + big_endian as u8, - Ieee754Double { big_endian } => 16 + big_endian as u8, - Utf16 { big_endian } => 18 + big_endian as u8, - Utf32 { big_endian } => 20 + big_endian as u8, + Int8 { signed } => signed as Self, + Int16 { signed, big_endian } => 2 + signed as Self * 2 + big_endian as Self, + Int32 { signed, big_endian } => 6 + signed as Self * 2 + big_endian as Self, + Int64 { signed, big_endian } => 10 + signed as Self * 2 + big_endian as Self, + Ieee754Float { big_endian } => 14 + big_endian as Self, + Ieee754Double { big_endian } => 16 + big_endian as Self, + Utf16 { big_endian } => 18 + big_endian as Self, + Utf32 { big_endian } => 20 + big_endian as Self, } } } diff --git a/stdlib/src/bz2.rs b/stdlib/src/bz2.rs index c6e0a66a37..f4db2d9fa1 100644 --- a/stdlib/src/bz2.rs +++ b/stdlib/src/bz2.rs @@ -48,7 +48,7 @@ mod _bz2 { impl DecompressStatus for Status { fn is_stream_end(&self) -> bool { - *self == Status::StreamEnd + *self == Self::StreamEnd } } diff --git a/stdlib/src/contextvars.rs b/stdlib/src/contextvars.rs index b52310e625..72eba70389 100644 --- a/stdlib/src/contextvars.rs +++ b/stdlib/src/contextvars.rs @@ -150,7 +150,7 @@ mod _contextvars { if let Some(ctx) = ctxs.last() { ctx.clone() } else { - let ctx = PyContext::empty(vm); + let ctx = Self::empty(vm); ctx.inner.idx.set(0); ctx.inner.entered.set(true); let ctx = ctx.into_ref(&vm.ctx); @@ -253,7 +253,7 @@ mod _contextvars { impl Constructor for PyContext { type Args = (); fn py_new(_cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult { - Ok(PyContext::empty(vm).into_pyobject(vm)) + Ok(Self::empty(vm).into_pyobject(vm)) } } @@ -499,7 +499,7 @@ mod _contextvars { impl Constructor for ContextVar { type Args = ContextVarOptions; fn py_new(_cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let var = ContextVar { + let var = Self { name: args.name.to_string(), default: args.default.into_option(), cached_id: 0.into(), diff --git a/stdlib/src/csv.rs b/stdlib/src/csv.rs index 54d956234b..4e11fb1b2e 100644 --- a/stdlib/src/csv.rs +++ b/stdlib/src/csv.rs @@ -68,7 +68,7 @@ mod _csv { type Args = PyObjectRef; fn py_new(cls: PyTypeRef, ctx: Self::Args, vm: &VirtualMachine) -> PyResult { - PyDialect::try_from_object(vm, ctx)? + Self::try_from_object(vm, ctx)? .into_ref_with_type(vm, cls) .map(Into::into) } @@ -425,10 +425,10 @@ mod _csv { impl From for csv_core::QuoteStyle { fn from(val: QuoteStyle) -> Self { match val { - QuoteStyle::Minimal => csv_core::QuoteStyle::Always, - QuoteStyle::All => csv_core::QuoteStyle::Always, - QuoteStyle::Nonnumeric => csv_core::QuoteStyle::NonNumeric, - QuoteStyle::None => csv_core::QuoteStyle::Never, + QuoteStyle::Minimal => Self::Always, + QuoteStyle::All => Self::Always, + QuoteStyle::Nonnumeric => Self::NonNumeric, + QuoteStyle::None => Self::Never, QuoteStyle::Strings => todo!(), QuoteStyle::Notnull => todo!(), } @@ -444,14 +444,14 @@ mod _csv { } impl TryFrom for QuoteStyle { type Error = PyTypeError; - fn try_from(num: isize) -> Result { + fn try_from(num: isize) -> Result { match num { - 0 => Ok(QuoteStyle::Minimal), - 1 => Ok(QuoteStyle::All), - 2 => Ok(QuoteStyle::Nonnumeric), - 3 => Ok(QuoteStyle::None), - 4 => Ok(QuoteStyle::Strings), - 5 => Ok(QuoteStyle::Notnull), + 0 => Ok(Self::Minimal), + 1 => Ok(Self::All), + 2 => Ok(Self::Nonnumeric), + 3 => Ok(Self::None), + 4 => Ok(Self::Strings), + 5 => Ok(Self::Notnull), _ => Err(PyTypeError {}), } } @@ -488,7 +488,7 @@ mod _csv { } impl Default for FormatOptions { fn default() -> Self { - FormatOptions { + Self { dialect: DialectItem::None, delimiter: None, quotechar: None, @@ -557,7 +557,7 @@ mod _csv { impl FromArgs for FormatOptions { fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { - let mut res = FormatOptions::default(); + let mut res = Self::default(); if let Some(dialect) = args.kwargs.swap_remove("dialect") { res.dialect = prase_dialect_item_from_arg(vm, dialect)?; } else if let Some(dialect) = args.args.first() { diff --git a/stdlib/src/hashlib.rs b/stdlib/src/hashlib.rs index 296342f05b..49ef3bbb48 100644 --- a/stdlib/src/hashlib.rs +++ b/stdlib/src/hashlib.rs @@ -100,7 +100,7 @@ pub mod _hashlib { #[pyclass(with(Representable))] impl PyHasher { fn new(name: &str, d: HashWrapper) -> Self { - PyHasher { + Self { name: name.to_owned(), ctx: PyRwLock::new(d), } @@ -143,7 +143,7 @@ pub mod _hashlib { #[pymethod] fn copy(&self) -> Self { - PyHasher::new(&self.name, self.ctx.read().clone()) + Self::new(&self.name, self.ctx.read().clone()) } } @@ -173,7 +173,7 @@ pub mod _hashlib { #[pyclass] impl PyHasherXof { fn new(name: &str, d: HashXofWrapper) -> Self { - PyHasherXof { + Self { name: name.to_owned(), ctx: PyRwLock::new(d), } @@ -216,7 +216,7 @@ pub mod _hashlib { #[pymethod] fn copy(&self) -> Self { - PyHasherXof::new(&self.name, self.ctx.read().clone()) + Self::new(&self.name, self.ctx.read().clone()) } } @@ -367,7 +367,7 @@ pub mod _hashlib { where D: ThreadSafeDynDigest + BlockSizeUser + Default + 'static, { - let mut h = HashWrapper { + let mut h = Self { block_size: D::block_size(), inner: Box::::default(), }; @@ -403,7 +403,7 @@ pub mod _hashlib { impl HashXofWrapper { pub fn new_shake_128(data: OptionalArg) -> Self { - let mut h = HashXofWrapper::Shake128(Shake128::default()); + let mut h = Self::Shake128(Shake128::default()); if let OptionalArg::Present(d) = data { d.with_ref(|bytes| h.update(bytes)); } @@ -411,7 +411,7 @@ pub mod _hashlib { } pub fn new_shake_256(data: OptionalArg) -> Self { - let mut h = HashXofWrapper::Shake256(Shake256::default()); + let mut h = Self::Shake256(Shake256::default()); if let OptionalArg::Present(d) = data { d.with_ref(|bytes| h.update(bytes)); } @@ -420,22 +420,22 @@ pub mod _hashlib { fn update(&mut self, data: &[u8]) { match self { - HashXofWrapper::Shake128(h) => h.update(data), - HashXofWrapper::Shake256(h) => h.update(data), + Self::Shake128(h) => h.update(data), + Self::Shake256(h) => h.update(data), } } fn block_size(&self) -> usize { match self { - HashXofWrapper::Shake128(_) => Shake128::block_size(), - HashXofWrapper::Shake256(_) => Shake256::block_size(), + Self::Shake128(_) => Shake128::block_size(), + Self::Shake256(_) => Shake256::block_size(), } } fn finalize_xof(&self, length: usize) -> Vec { match self { - HashXofWrapper::Shake128(h) => h.clone().finalize_boxed(length).into_vec(), - HashXofWrapper::Shake256(h) => h.clone().finalize_boxed(length).into_vec(), + Self::Shake128(h) => h.clone().finalize_boxed(length).into_vec(), + Self::Shake256(h) => h.clone().finalize_boxed(length).into_vec(), } } } diff --git a/stdlib/src/posixsubprocess.rs b/stdlib/src/posixsubprocess.rs index bcf2e5ddc1..294aa0e462 100644 --- a/stdlib/src/posixsubprocess.rs +++ b/stdlib/src/posixsubprocess.rs @@ -71,7 +71,7 @@ struct CStrPathLike { impl TryFromObject for CStrPathLike { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let s = OsPath::try_from_object(vm, obj)?.into_cstring(vm)?; - Ok(CStrPathLike { s }) + Ok(Self { s }) } } impl AsRef for CStrPathLike { @@ -176,9 +176,9 @@ enum ExecErrorContext { impl ExecErrorContext { fn as_msg(&self) -> &'static str { match self { - ExecErrorContext::NoExec => "noexec", - ExecErrorContext::ChDir => "noexec:chdir", - ExecErrorContext::Exec => "", + Self::NoExec => "noexec", + Self::ChDir => "noexec:chdir", + Self::Exec => "", } } } diff --git a/stdlib/src/pyexpat.rs b/stdlib/src/pyexpat.rs index d74b54310c..033fa76c06 100644 --- a/stdlib/src/pyexpat.rs +++ b/stdlib/src/pyexpat.rs @@ -65,7 +65,7 @@ mod _pyexpat { #[pyclass] impl PyExpatLikeXmlParser { fn new(vm: &VirtualMachine) -> PyResult { - Ok(PyExpatLikeXmlParser { + Ok(Self { start_element: MutableObject::new(vm.ctx.none()), end_element: MutableObject::new(vm.ctx.none()), character_data: MutableObject::new(vm.ctx.none()), diff --git a/stdlib/src/pystruct.rs b/stdlib/src/pystruct.rs index 0fba16794a..39fdc70c7c 100644 --- a/stdlib/src/pystruct.rs +++ b/stdlib/src/pystruct.rs @@ -39,7 +39,7 @@ pub(crate) mod _struct { ))), }) .ok_or_else(|| vm.new_unicode_decode_error("Struct format must be a ascii string"))?; - Ok(IntoStructFormatBytes(fmt)) + Ok(Self(fmt)) } } @@ -165,7 +165,7 @@ pub(crate) mod _struct { vm: &VirtualMachine, format_spec: FormatSpec, buffer: ArgBytesLike, - ) -> PyResult { + ) -> PyResult { if format_spec.size == 0 { Err(new_struct_error( vm, @@ -180,7 +180,7 @@ pub(crate) mod _struct { ), )) } else { - Ok(UnpackIterator { + Ok(Self { format_spec, buffer, offset: AtomicCell::new(0), @@ -244,7 +244,7 @@ pub(crate) mod _struct { fn py_new(cls: PyTypeRef, fmt: Self::Args, vm: &VirtualMachine) -> PyResult { let spec = fmt.format_spec(vm)?; let format = fmt.0; - PyStruct { spec, format } + Self { spec, format } .into_ref_with_type(vm, cls) .map(Into::into) } diff --git a/stdlib/src/resource.rs b/stdlib/src/resource.rs index a45d024b6c..7f08b4441b 100644 --- a/stdlib/src/resource.rs +++ b/stdlib/src/resource.rs @@ -90,7 +90,7 @@ mod resource { impl From for Rusage { fn from(rusage: libc::rusage) -> Self { let tv = |tv: libc::timeval| tv.tv_sec as f64 + (tv.tv_usec as f64 / 1_000_000.0); - Rusage { + Self { ru_utime: tv(rusage.ru_utime), ru_stime: tv(rusage.ru_utime), ru_maxrss: rusage.ru_maxrss, diff --git a/stdlib/src/select.rs b/stdlib/src/select.rs index f9c86d7a92..17570b4e2e 100644 --- a/stdlib/src/select.rs +++ b/stdlib/src/select.rs @@ -146,7 +146,7 @@ impl TryFromObject for Selectable { )?; meth.call((), vm)?.try_into_value(vm) })?; - Ok(Selectable { obj, fno }) + Ok(Self { obj, fno }) } } @@ -155,12 +155,12 @@ impl TryFromObject for Selectable { pub struct FdSet(mem::MaybeUninit); impl FdSet { - pub fn new() -> FdSet { + pub fn new() -> Self { // it's just ints, and all the code that's actually // interacting with it is in C, so it's safe to zero let mut fdset = std::mem::MaybeUninit::zeroed(); unsafe { platform::FD_ZERO(fdset.as_mut_ptr()) }; - FdSet(fdset) + Self(fdset) } pub fn insert(&mut self, fd: RawFd) { @@ -440,7 +440,7 @@ mod decl { let mask = i16::try_from(val) .map_err(|_| vm.new_overflow_error("event mask value out of range"))?; - Ok(EventMask(mask)) + Ok(Self(mask)) } } @@ -602,7 +602,7 @@ mod decl { fn new() -> std::io::Result { let epoll_fd = epoll::create(epoll::CreateFlags::CLOEXEC)?; let epoll_fd = Some(epoll_fd).into(); - Ok(PyEpoll { epoll_fd }) + Ok(Self { epoll_fd }) } #[pymethod] diff --git a/stdlib/src/socket.rs b/stdlib/src/socket.rs index 38c1522d1b..50ee2b96fc 100644 --- a/stdlib/src/socket.rs +++ b/stdlib/src/socket.rs @@ -799,7 +799,7 @@ mod _socket { impl Default for PySocket { fn default() -> Self { - PySocket { + Self { kind: AtomicCell::default(), family: AtomicCell::default(), proto: AtomicCell::default(), @@ -1663,14 +1663,14 @@ mod _socket { let port = port .to_u16() .ok_or_else(|| vm.new_overflow_error("port must be 0-65535."))?; - Ok(Address { host, port }) + Ok(Self { host, port }) } fn from_tuple_ipv6( tuple: &[PyObjectRef], vm: &VirtualMachine, ) -> PyResult<(Self, u32, u32)> { - let addr = Address::from_tuple(tuple, vm)?; + let addr = Self::from_tuple(tuple, vm)?; let flowinfo = tuple .get(2) .map(|obj| u32::try_from_borrowed_object(vm, obj)) diff --git a/stdlib/src/syslog.rs b/stdlib/src/syslog.rs index dcdf317b02..b2936dee87 100644 --- a/stdlib/src/syslog.rs +++ b/stdlib/src/syslog.rs @@ -49,8 +49,8 @@ mod syslog { impl GlobalIdent { fn as_ptr(&self) -> *const c_char { match self { - GlobalIdent::Explicit(cstr) => cstr.as_ptr(), - GlobalIdent::Implicit => std::ptr::null(), + Self::Explicit(cstr) => cstr.as_ptr(), + Self::Implicit => std::ptr::null(), } } } diff --git a/stdlib/src/unicodedata.rs b/stdlib/src/unicodedata.rs index 8dbec1ffe8..b691c1f571 100644 --- a/stdlib/src/unicodedata.rs +++ b/stdlib/src/unicodedata.rs @@ -47,10 +47,10 @@ impl<'a> TryFromBorrowedObject<'a> for NormalizeForm { obj.try_value_with( |form: &PyStr| { Ok(match form.as_str() { - "NFC" => NormalizeForm::Nfc, - "NFKC" => NormalizeForm::Nfkc, - "NFD" => NormalizeForm::Nfd, - "NFKD" => NormalizeForm::Nfkd, + "NFC" => Self::Nfc, + "NFKC" => Self::Nfkc, + "NFD" => Self::Nfd, + "NFKD" => Self::Nfkd, _ => return Err(vm.new_value_error("invalid normalization form")), }) }, @@ -221,12 +221,12 @@ mod unicodedata { impl EastAsianWidthAbbrName for EastAsianWidth { fn abbr_name(&self) -> &'static str { match self { - EastAsianWidth::Narrow => "Na", - EastAsianWidth::Wide => "W", - EastAsianWidth::Neutral => "N", - EastAsianWidth::Ambiguous => "A", - EastAsianWidth::FullWidth => "F", - EastAsianWidth::HalfWidth => "H", + Self::Narrow => "Na", + Self::Wide => "W", + Self::Neutral => "N", + Self::Ambiguous => "A", + Self::FullWidth => "F", + Self::HalfWidth => "H", } } } diff --git a/stdlib/src/zlib.rs b/stdlib/src/zlib.rs index 1927d2a198..cf5669145b 100644 --- a/stdlib/src/zlib.rs +++ b/stdlib/src/zlib.rs @@ -118,7 +118,7 @@ mod zlib { } impl InitOptions { - fn new(wbits: i8, vm: &VirtualMachine) -> PyResult { + fn new(wbits: i8, vm: &VirtualMachine) -> PyResult { let header = wbits > 0; let wbits = wbits.unsigned_abs(); match wbits { @@ -127,8 +127,8 @@ mod zlib { // > the zlib header of the compressed stream. // but flate2 doesn't expose it // 0 => ... - 9..=15 => Ok(InitOptions::Standard { header, wbits }), - 25..=31 => Ok(InitOptions::Gzip { wbits: wbits - 16 }), + 9..=15 => Ok(Self::Standard { header, wbits }), + 25..=31 => Ok(Self::Gzip { wbits: wbits - 16 }), _ => Err(vm.new_value_error("Invalid initialization option")), } } @@ -422,8 +422,8 @@ mod zlib { } impl CompressStatusKind for Status { - const OK: Self = Status::Ok; - const EOF: Self = Status::StreamEnd; + const OK: Self = Self::Ok; + const EOF: Self = Self::StreamEnd; fn to_usize(self) -> usize { self as usize @@ -431,8 +431,8 @@ mod zlib { } impl CompressFlushKind for FlushCompress { - const NONE: Self = FlushCompress::None; - const FINISH: Self = FlushCompress::Finish; + const NONE: Self = Self::None; + const FINISH: Self = Self::Finish; fn to_usize(self) -> usize { self as usize @@ -514,12 +514,12 @@ mod zlib { impl DecompressStatus for Status { fn is_stream_end(&self) -> bool { - *self == Status::StreamEnd + *self == Self::StreamEnd } } impl DecompressFlushKind for FlushDecompress { - const SYNC: Self = FlushDecompress::Sync; + const SYNC: Self = Self::Sync; } impl Decompressor for Decompress { From 2b7cceddd717d78ea88c383f4b4865372f445a46 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:45:05 +0300 Subject: [PATCH 09/11] remove unused import --- vm/src/convert/try_from.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vm/src/convert/try_from.rs b/vm/src/convert/try_from.rs index 479ef69ffe..bcdcad9016 100644 --- a/vm/src/convert/try_from.rs +++ b/vm/src/convert/try_from.rs @@ -123,7 +123,7 @@ impl<'a, T: PyPayload> TryFromBorrowedObject<'a> for &'a Py { impl TryFromObject for std::time::Duration { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - use std::time::Duration; + if let Some(float) = obj.payload::() { Ok(Self::from_secs_f64(float.to_f64())) } else if let Some(int) = obj.try_index_opt(vm) { From 728401d66c7197290e09e51dd2c00e806ed2344a Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:49:09 +0300 Subject: [PATCH 10/11] More vm --- vm/src/stdlib/sys.rs | 2 +- vm/src/stdlib/thread.rs | 4 ++-- vm/src/vm/thread.rs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/vm/src/stdlib/sys.rs b/vm/src/stdlib/sys.rs index f7d83a3d71..a7310fc102 100644 --- a/vm/src/stdlib/sys.rs +++ b/vm/src/stdlib/sys.rs @@ -1005,7 +1005,7 @@ mod sys { #[cfg(feature = "threading")] #[pyclass(with(PyStructSequence))] impl PyThreadInfo { - const INFO: Self = PyThreadInfo { + const INFO: Self = Self { name: crate::stdlib::thread::_thread::PYTHREAD_NAME, // As I know, there's only way to use lock as "Mutex" in Rust // with satisfying python document spec. diff --git a/vm/src/stdlib/thread.rs b/vm/src/stdlib/thread.rs index cdcdee95a9..6b751f3074 100644 --- a/vm/src/stdlib/thread.rs +++ b/vm/src/stdlib/thread.rs @@ -201,7 +201,7 @@ pub(crate) mod _thread { impl RLock { #[pyslot] fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { - RLock { + Self { mu: RawRMutex::INIT, } .into_ref_with_type(vm, cls) @@ -393,7 +393,7 @@ pub(crate) mod _thread { #[pyslot] fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { - Local { + Self { data: ThreadLocal::new(), } .into_ref_with_type(vm, cls) diff --git a/vm/src/vm/thread.rs b/vm/src/vm/thread.rs index ea5a2d995a..a5a0a7b63b 100644 --- a/vm/src/vm/thread.rs +++ b/vm/src/vm/thread.rs @@ -114,7 +114,7 @@ impl VirtualMachine { #[cfg(feature = "threading")] pub fn start_thread(&self, f: F) -> std::thread::JoinHandle where - F: FnOnce(&VirtualMachine) -> R, + F: FnOnce(&Self) -> R, F: Send + 'static, R: Send + 'static, { @@ -146,7 +146,7 @@ impl VirtualMachine { /// specific guaranteed behavior. #[cfg(feature = "threading")] pub fn new_thread(&self) -> ThreadedVirtualMachine { - let vm = VirtualMachine { + let vm = Self { builtins: self.builtins.clone(), sys_module: self.sys_module.clone(), ctx: self.ctx.clone(), From fe13f807862fd06d77ab50253982dd019b08eaeb Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Thu, 3 Jul 2025 18:49:40 +0300 Subject: [PATCH 11/11] cargo fmt --- common/src/format.rs | 10 ++-------- vm/src/builtins/bytearray.rs | 36 ++++++---------------------------- vm/src/builtins/bytes.rs | 6 +----- vm/src/builtins/list.rs | 4 +--- vm/src/builtins/set.rs | 19 +++--------------- vm/src/bytes_inner.rs | 31 +++++------------------------ vm/src/convert/try_from.rs | 1 - vm/src/format.rs | 16 ++++----------- vm/src/stdlib/ast/exception.rs | 8 +++++--- vm/src/stdlib/io.rs | 4 +--- vm/src/stdlib/operator.rs | 4 +--- vm/src/stdlib/typing.rs | 6 +----- vm/src/vm/method.rs | 4 +--- 13 files changed, 31 insertions(+), 118 deletions(-) diff --git a/common/src/format.rs b/common/src/format.rs index b9a780b146..feebc3893c 100644 --- a/common/src/format.rs +++ b/common/src/format.rs @@ -412,12 +412,7 @@ impl FormatSpec { let magnitude_len = magnitude_str.len(); let width = self.width.unwrap_or(magnitude_len) as i32 - prefix.len() as i32; let disp_digit_cnt = cmp::max(width, magnitude_len as i32); - Self::add_magnitude_separators_for_char( - magnitude_str, - inter, - sep, - disp_digit_cnt, - ) + Self::add_magnitude_separators_for_char(magnitude_str, inter, sep, disp_digit_cnt) } None => magnitude_str, } @@ -657,8 +652,7 @@ impl FormatSpec { FormatAlign::Center => { let left_fill_chars_needed = fill_chars_needed / 2; let right_fill_chars_needed = fill_chars_needed - left_fill_chars_needed; - let left_fill_string = - Self::compute_fill_string(fill_char, left_fill_chars_needed); + let left_fill_string = Self::compute_fill_string(fill_char, left_fill_chars_needed); let right_fill_string = Self::compute_fill_string(fill_char, right_fill_chars_needed); format!("{left_fill_string}{sign_str}{magnitude_str}{right_fill_string}") diff --git a/vm/src/builtins/bytearray.rs b/vm/src/builtins/bytearray.rs index 49d950c1e8..aba1dc2db7 100644 --- a/vm/src/builtins/bytearray.rs +++ b/vm/src/builtins/bytearray.rs @@ -335,29 +335,17 @@ impl PyByteArray { } #[pymethod] - fn center( - &self, - options: ByteInnerPaddingOptions, - vm: &VirtualMachine, - ) -> PyResult { + fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { Ok(self.inner().center(options, vm)?.into()) } #[pymethod] - fn ljust( - &self, - options: ByteInnerPaddingOptions, - vm: &VirtualMachine, - ) -> PyResult { + fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { Ok(self.inner().ljust(options, vm)?.into()) } #[pymethod] - fn rjust( - &self, - options: ByteInnerPaddingOptions, - vm: &VirtualMachine, - ) -> PyResult { + fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult { Ok(self.inner().rjust(options, vm)?.into()) } @@ -434,11 +422,7 @@ impl PyByteArray { } #[pymethod] - fn translate( - &self, - options: ByteInnerTranslateOptions, - vm: &VirtualMachine, - ) -> PyResult { + fn translate(&self, options: ByteInnerTranslateOptions, vm: &VirtualMachine) -> PyResult { Ok(self.inner().translate(options, vm)?.into()) } @@ -663,11 +647,7 @@ impl Py { #[pyclass] impl PyRef { #[pymethod] - fn lstrip( - self, - chars: OptionalOption, - vm: &VirtualMachine, - ) -> Self { + fn lstrip(self, chars: OptionalOption, vm: &VirtualMachine) -> Self { let inner = self.inner(); let stripped = inner.lstrip(chars); let elements = &inner.elements; @@ -680,11 +660,7 @@ impl PyRef { } #[pymethod] - fn rstrip( - self, - chars: OptionalOption, - vm: &VirtualMachine, - ) -> Self { + fn rstrip(self, chars: OptionalOption, vm: &VirtualMachine) -> Self { let inner = self.inner(); let stripped = inner.rstrip(chars); let elements = &inner.elements; diff --git a/vm/src/builtins/bytes.rs b/vm/src/builtins/bytes.rs index 050093fd83..d103e7d466 100644 --- a/vm/src/builtins/bytes.rs +++ b/vm/src/builtins/bytes.rs @@ -355,11 +355,7 @@ impl PyBytes { } #[pymethod] - fn translate( - &self, - options: ByteInnerTranslateOptions, - vm: &VirtualMachine, - ) -> PyResult { + fn translate(&self, options: ByteInnerTranslateOptions, vm: &VirtualMachine) -> PyResult { Ok(self.inner.translate(options, vm)?.into()) } diff --git a/vm/src/builtins/list.rs b/vm/src/builtins/list.rs index 838295b01b..4f05390147 100644 --- a/vm/src/builtins/list.rs +++ b/vm/src/builtins/list.rs @@ -379,9 +379,7 @@ impl Constructor for PyList { type Args = FuncArgs; fn py_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { - Self::default() - .into_ref_with_type(vm, cls) - .map(Into::into) + Self::default().into_ref_with_type(vm, cls).map(Into::into) } } diff --git a/vm/src/builtins/set.rs b/vm/src/builtins/set.rs index ff97f0ae2d..77301bd384 100644 --- a/vm/src/builtins/set.rs +++ b/vm/src/builtins/set.rs @@ -221,12 +221,7 @@ impl PySetInner { self.retry_op_with_frozenset(needle, vm, |needle, vm| self.content.contains(vm, needle)) } - fn compare( - &self, - other: &Self, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { + fn compare(&self, other: &Self, op: PyComparisonOp, vm: &VirtualMachine) -> PyResult { if op == PyComparisonOp::Ne { return self.compare(other, PyComparisonOp::Eq, vm).map(|eq| !eq); } @@ -256,11 +251,7 @@ impl PySetInner { Ok(set) } - pub(super) fn intersection( - &self, - other: ArgIterable, - vm: &VirtualMachine, - ) -> PyResult { + pub(super) fn intersection(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { let set = Self::default(); for item in other.iter(vm)? { let obj = item?; @@ -271,11 +262,7 @@ impl PySetInner { Ok(set) } - pub(super) fn difference( - &self, - other: ArgIterable, - vm: &VirtualMachine, - ) -> PyResult { + pub(super) fn difference(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { let set = self.copy(); for item in other.iter(vm)? { set.content.delete_if_exists(vm, &*item?)?; diff --git a/vm/src/bytes_inner.rs b/vm/src/bytes_inner.rs index 692e489b90..db1e843091 100644 --- a/vm/src/bytes_inner.rs +++ b/vm/src/bytes_inner.rs @@ -342,11 +342,7 @@ impl PyBytesInner { self.elements.py_add(other) } - pub fn contains( - &self, - needle: Either, - vm: &VirtualMachine, - ) -> PyResult { + pub fn contains(&self, needle: Either, vm: &VirtualMachine) -> PyResult { Ok(match needle { Either::A(byte) => self.elements.contains_str(byte.elements.as_slice()), Either::B(int) => self.elements.contains(&int.as_bigint().byte_or(vm)?), @@ -552,11 +548,7 @@ impl PyBytesInner { .py_count(needle.as_slice(), range, |h, n| h.find_iter(n).count())) } - pub fn join( - &self, - iterable: ArgIterable, - vm: &VirtualMachine, - ) -> PyResult> { + pub fn join(&self, iterable: ArgIterable, vm: &VirtualMachine) -> PyResult> { let iter = iterable.iter(vm)?; self.elements.py_join(iter) } @@ -575,11 +567,7 @@ impl PyBytesInner { Ok(self.elements.py_find(&needle, range, find)) } - pub fn maketrans( - from: Self, - to: Self, - vm: &VirtualMachine, - ) -> PyResult> { + pub fn maketrans(from: Self, to: Self, vm: &VirtualMachine) -> PyResult> { if from.len() != to.len() { return Err(vm.new_value_error("the two maketrans arguments must have equal length")); } @@ -703,11 +691,7 @@ impl PyBytesInner { Ok(elements) } - pub fn partition( - &self, - sub: &Self, - vm: &VirtualMachine, - ) -> PyResult<(Vec, bool, Vec)> { + pub fn partition(&self, sub: &Self, vm: &VirtualMachine) -> PyResult<(Vec, bool, Vec)> { self.elements.py_partition( &sub.elements, || self.elements.splitn_str(2, &sub.elements), @@ -815,12 +799,7 @@ impl PyBytesInner { result } - pub fn replace_in_place( - &self, - from: Self, - to: Self, - max_count: Option, - ) -> Vec { + pub fn replace_in_place(&self, from: Self, to: Self, max_count: Option) -> Vec { let len = from.len(); let mut iter = self.elements.find_iter(&from.elements); diff --git a/vm/src/convert/try_from.rs b/vm/src/convert/try_from.rs index bcdcad9016..7eb1c9c00d 100644 --- a/vm/src/convert/try_from.rs +++ b/vm/src/convert/try_from.rs @@ -123,7 +123,6 @@ impl<'a, T: PyPayload> TryFromBorrowedObject<'a> for &'a Py { impl TryFromObject for std::time::Duration { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - if let Some(float) = obj.payload::() { Ok(Self::from_secs_f64(float.to_f64())) } else if let Some(int) = obj.try_index_opt(vm) { diff --git a/vm/src/format.rs b/vm/src/format.rs index 0fea4dedf5..3eca5ce1b8 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -16,9 +16,7 @@ impl IntoPyException for FormatSpecError { vm.new_value_error("Too many decimal digits in format string") } Self::PrecisionTooBig => vm.new_value_error("Precision too big"), - Self::InvalidFormatSpecifier => { - vm.new_value_error("Invalid format specifier") - } + Self::InvalidFormatSpecifier => vm.new_value_error("Invalid format specifier"), Self::UnspecifiedFormat(c1, c2) => { let msg = format!("Cannot specify '{c1}' with '{c2}'."); vm.new_value_error(msg) @@ -34,12 +32,8 @@ impl IntoPyException for FormatSpecError { let msg = format!("{s} not allowed with integer format specifier 'c'"); vm.new_value_error(msg) } - Self::UnableToConvert => { - vm.new_value_error("Unable to convert int to float") - } - Self::CodeNotInRange => { - vm.new_overflow_error("%c arg not in range(0x110000)") - } + Self::UnableToConvert => vm.new_value_error("Unable to convert int to float"), + Self::CodeNotInRange => vm.new_overflow_error("%c arg not in range(0x110000)"), Self::NotImplemented(c, s) => { let msg = format!("Format code '{c}' for object of type '{s}' not implemented yet"); vm.new_value_error(msg) @@ -51,9 +45,7 @@ impl IntoPyException for FormatSpecError { impl ToPyException for FormatParseError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { - Self::UnmatchedBracket => { - vm.new_value_error("expected '}' before end of string") - } + Self::UnmatchedBracket => vm.new_value_error("expected '}' before end of string"), _ => vm.new_value_error("Unexpected error parsing format string"), } } diff --git a/vm/src/stdlib/ast/exception.rs b/vm/src/stdlib/ast/exception.rs index c4ecf8831b..b8bf034a7b 100644 --- a/vm/src/stdlib/ast/exception.rs +++ b/vm/src/stdlib/ast/exception.rs @@ -15,9 +15,11 @@ impl Node for ruff::ExceptHandler { let _cls = _object.class(); Ok( if _cls.is(pyast::NodeExceptHandlerExceptHandler::static_type()) { - Self::ExceptHandler( - ruff::ExceptHandlerExceptHandler::ast_from_object(_vm, source_code, _object)?, - ) + Self::ExceptHandler(ruff::ExceptHandlerExceptHandler::ast_from_object( + _vm, + source_code, + _object, + )?) } else { return Err(_vm.new_type_error(format!( "expected some sort of excepthandler, but got {}", diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index 9943f0da2a..e6adf07fcd 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -1967,9 +1967,7 @@ mod _io { fn find_newline(&self, s: &Wtf8) -> Result { let len = s.len(); match self { - Self::Universal | Self::Lf => { - s.find("\n".as_ref()).map(|p| p + 1).ok_or(len) - } + Self::Universal | Self::Lf => s.find("\n".as_ref()).map(|p| p + 1).ok_or(len), Self::Passthrough => { let bytes = s.as_bytes(); memchr::memchr2(b'\n', b'\r', bytes) diff --git a/vm/src/stdlib/operator.rs b/vm/src/stdlib/operator.rs index af7ffab7da..c33b9a47b0 100644 --- a/vm/src/stdlib/operator.rs +++ b/vm/src/stdlib/operator.rs @@ -403,9 +403,7 @@ mod _operator { return Err(vm.new_type_error("attribute name must be a string")); } } - Self { attrs } - .into_ref_with_type(vm, cls) - .map(Into::into) + Self { attrs }.into_ref_with_type(vm, cls).map(Into::into) } } diff --git a/vm/src/stdlib/typing.rs b/vm/src/stdlib/typing.rs index e05029a8d6..ed3b3f0e97 100644 --- a/vm/src/stdlib/typing.rs +++ b/vm/src/stdlib/typing.rs @@ -105,11 +105,7 @@ pub(crate) mod decl { } #[pyclass(flags(BASETYPE))] impl TypeAliasType { - pub fn new( - name: PyObjectRef, - type_params: PyTupleRef, - value: PyObjectRef, - ) -> Self { + pub fn new(name: PyObjectRef, type_params: PyTupleRef, value: PyObjectRef) -> Self { Self { name, type_params, diff --git a/vm/src/vm/method.rs b/vm/src/vm/method.rs index dc512c2576..e10eb2db83 100644 --- a/vm/src/vm/method.rs +++ b/vm/src/vm/method.rs @@ -131,9 +131,7 @@ impl PyMethod { #[allow(dead_code)] pub fn invoke_ref(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { let (func, args) = match self { - Self::Function { target, func } => { - (func, args.into_method_args(target.clone(), vm)) - } + Self::Function { target, func } => (func, args.into_method_args(target.clone(), vm)), Self::Attribute(func) => (func, args.into_args(vm)), }; func.call(args, vm) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy