diff --git a/benches/execution.rs b/benches/execution.rs index 9c00f8955..9c0bdb024 100644 --- a/benches/execution.rs +++ b/benches/execution.rs @@ -4,8 +4,7 @@ use criterion::{ }; use rustpython_compiler::Mode; use rustpython_parser::parser::parse_program; -use rustpython_vm::Interpreter; -use rustpython_vm::PyResult; +use rustpython_vm::{Interpreter, PyResult}; use std::collections::HashMap; use std::path::Path; diff --git a/benches/microbenchmarks.rs b/benches/microbenchmarks.rs index bbed9a890..6e6103ccf 100644 --- a/benches/microbenchmarks.rs +++ b/benches/microbenchmarks.rs @@ -1,13 +1,15 @@ -use criterion::measurement::WallTime; use criterion::{ - criterion_group, criterion_main, BatchSize, BenchmarkGroup, BenchmarkId, Criterion, Throughput, + criterion_group, criterion_main, measurement::WallTime, BatchSize, BenchmarkGroup, BenchmarkId, + Criterion, Throughput, }; use rustpython_compiler::Mode; use rustpython_vm::{ common::ascii, InitParameter, Interpreter, PyObjectWrap, PyResult, PySettings, }; -use std::path::{Path, PathBuf}; -use std::{ffi, fs, io}; +use std::{ + ffi, fs, io, + path::{Path, PathBuf}, +}; pub struct MicroBenchmark { name: String, diff --git a/bytecode/src/lib.rs b/bytecode/src/lib.rs index 9fd8b66fd..cdf348a07 100644 --- a/bytecode/src/lib.rs +++ b/bytecode/src/lib.rs @@ -10,8 +10,7 @@ use itertools::Itertools; use num_bigint::BigInt; use num_complex::Complex64; use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; -use std::{fmt, hash}; +use std::{collections::BTreeSet, fmt, hash}; /// Sourcecode location. #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] diff --git a/common/src/boxvec.rs b/common/src/boxvec.rs index 7d2e8a4c7..417013014 100644 --- a/common/src/boxvec.rs +++ b/common/src/boxvec.rs @@ -1,9 +1,13 @@ //! An unresizable vector backed by a `Box<[T]>` -use std::borrow::{Borrow, BorrowMut}; -use std::mem::{self, MaybeUninit}; -use std::ops::{Bound, Deref, DerefMut, RangeBounds}; -use std::{alloc, cmp, fmt, ptr, slice}; +use std::{ + alloc, + borrow::{Borrow, BorrowMut}, + cmp, fmt, + mem::{self, MaybeUninit}, + ops::{Bound, Deref, DerefMut, RangeBounds}, + ptr, slice, +}; pub struct BoxVec { xs: Box<[MaybeUninit]>, @@ -501,9 +505,7 @@ impl Drop for Drain<'_, T> { fn drop(&mut self) { // len is currently 0 so panicking while dropping will not cause a double drop. - // exhaust self first, clippy warning here is seemingly a fluke. - #[allow(clippy::while_let_on_iterator)] - while let Some(_) = self.next() {} + for _ in self.by_ref() {} if self.tail_len > 0 { unsafe { diff --git a/common/src/hash.rs b/common/src/hash.rs index e3ed7d1b8..c0b7945fa 100644 --- a/common/src/hash.rs +++ b/common/src/hash.rs @@ -2,8 +2,10 @@ use num_bigint::BigInt; use num_complex::Complex64; use num_traits::ToPrimitive; use siphasher::sip::SipHasher24; -use std::hash::{BuildHasher, Hash, Hasher}; -use std::num::Wrapping; +use std::{ + hash::{BuildHasher, Hash, Hasher}, + num::Wrapping, +}; pub type PyHash = i64; pub type PyUHash = u64; diff --git a/common/src/lock/cell_lock.rs b/common/src/lock/cell_lock.rs index edf968b3f..e40c854c5 100644 --- a/common/src/lock/cell_lock.rs +++ b/common/src/lock/cell_lock.rs @@ -2,8 +2,7 @@ use lock_api::{ GetThreadId, RawMutex, RawRwLock, RawRwLockDowngrade, RawRwLockRecursive, RawRwLockUpgrade, RawRwLockUpgradeDowngrade, }; -use std::cell::Cell; -use std::num::NonZeroUsize; +use std::{cell::Cell, num::NonZeroUsize}; pub struct RawCellMutex { locked: Cell, diff --git a/common/src/lock/immutable_mutex.rs b/common/src/lock/immutable_mutex.rs index d35ce55ae..3f5eba787 100644 --- a/common/src/lock/immutable_mutex.rs +++ b/common/src/lock/immutable_mutex.rs @@ -1,8 +1,5 @@ -use std::fmt; -use std::marker::PhantomData; -use std::ops::Deref; - use lock_api::{MutexGuard, RawMutex}; +use std::{fmt, marker::PhantomData, ops::Deref}; /// A mutex guard that has an exclusive lock, but only an immutable reference; useful if you /// need to map a mutex guard with a function that returns an `&T`. Construct using the diff --git a/common/src/lock/thread_mutex.rs b/common/src/lock/thread_mutex.rs index 98184d0b5..1a5054264 100644 --- a/common/src/lock/thread_mutex.rs +++ b/common/src/lock/thread_mutex.rs @@ -1,11 +1,12 @@ -use std::cell::UnsafeCell; -use std::fmt; -use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; -use std::ptr::NonNull; -use std::sync::atomic::{AtomicUsize, Ordering}; - use lock_api::{GetThreadId, GuardNoSend, RawMutex}; +use std::{ + cell::UnsafeCell, + fmt, + marker::PhantomData, + ops::{Deref, DerefMut}, + ptr::NonNull, + sync::atomic::{AtomicUsize, Ordering}, +}; // based off ReentrantMutex from lock_api diff --git a/common/src/str.rs b/common/src/str.rs index 5bba0a557..66dccf470 100644 --- a/common/src/str.rs +++ b/common/src/str.rs @@ -1,7 +1,9 @@ use ascii::AsciiString; use once_cell::unsync::OnceCell; -use std::fmt; -use std::ops::{Bound, RangeBounds}; +use std::{ + fmt, + ops::{Bound, RangeBounds}, +}; #[cfg(not(target_arch = "wasm32"))] #[allow(non_camel_case_types)] @@ -99,8 +101,7 @@ pub const fn bytes_is_ascii(x: &str) -> bool { } pub mod levenshtein { - use std::cell::RefCell; - use std::thread_local; + use std::{cell::RefCell, thread_local}; pub const MOVE_COST: usize = 2; const CASE_COST: usize = 1; diff --git a/compiler/src/compile.rs b/compiler/src/compile.rs index 56dd7d698..658e12b9d 100644 --- a/compiler/src/compile.rs +++ b/compiler/src/compile.rs @@ -88,7 +88,6 @@ struct CompileContext { } #[derive(Debug, Clone, Copy, PartialEq)] -#[allow(clippy::enum_variant_names)] enum FunctionContext { NoFunction, Function, diff --git a/compiler/src/error.rs b/compiler/src/error.rs index 6d4b3d98a..58b8c6dcb 100644 --- a/compiler/src/error.rs +++ b/compiler/src/error.rs @@ -1,7 +1,6 @@ use rustpython_ast::Location; -use std::error::Error; -use std::fmt; +use std::{error::Error, fmt}; #[derive(Debug)] pub struct CompileError { diff --git a/compiler/src/symboltable.rs b/compiler/src/symboltable.rs index 602861f9c..74305ea56 100644 --- a/compiler/src/symboltable.rs +++ b/compiler/src/symboltable.rs @@ -7,11 +7,12 @@ load and store instructions for names. Inspirational file: https://github.com/python/cpython/blob/main/Python/symtable.c */ -use crate::error::{CompileError, CompileErrorType}; -use crate::IndexMap; +use crate::{ + error::{CompileError, CompileErrorType}, + IndexMap, +}; use rustpython_ast::{self as ast, Location}; -use std::borrow::Cow; -use std::fmt; +use std::{borrow::Cow, fmt}; pub fn make_symbol_table(program: &[ast::Stmt]) -> SymbolTableResult { let mut builder = SymbolTableBuilder::new(); diff --git a/jit/src/lib.rs b/jit/src/lib.rs index 1b43de469..2c89bd5c2 100644 --- a/jit/src/lib.rs +++ b/jit/src/lib.rs @@ -1,16 +1,11 @@ -#![allow(clippy::unnecessary_wraps)] -use std::fmt; +mod instructions; use cranelift::prelude::*; use cranelift_jit::{JITBuilder, JITModule}; use cranelift_module::{FuncId, Linkage, Module, ModuleError}; - -use rustpython_bytecode as bytecode; - -mod instructions; - use instructions::FunctionCompiler; -use std::mem::ManuallyDrop; +use rustpython_bytecode as bytecode; +use std::{fmt, mem::ManuallyDrop}; #[derive(Debug, thiserror::Error)] #[non_exhaustive] @@ -292,7 +287,6 @@ impl UnTypedAbiValue { // we don't actually ever touch CompiledCode til we drop it, it should be safe. // TODO: confirm with wasmtime ppl that it's not unsound? -#[allow(clippy::non_send_fields_in_send_ty)] unsafe impl Send for CompiledCode {} unsafe impl Sync for CompiledCode {} diff --git a/parser/src/fstring.rs b/parser/src/fstring.rs index e78cf39cc..e7eb831f4 100644 --- a/parser/src/fstring.rs +++ b/parser/src/fstring.rs @@ -1,12 +1,10 @@ -use std::iter; -use std::mem; -use std::str; - -use crate::ast::{Constant, ConversionFlag, Expr, ExprKind, Location}; -use crate::error::{FStringError, FStringErrorType, ParseError}; -use crate::parser::parse_expression; - use self::FStringErrorType::*; +use crate::{ + ast::{Constant, ConversionFlag, Expr, ExprKind, Location}, + error::{FStringError, FStringErrorType, ParseError}, + parser::parse_expression, +}; +use std::{iter, mem, str}; struct FStringParser<'a> { chars: iter::Peekable>, diff --git a/src/lib.rs b/src/lib.rs index 406366d09..41c0be4c0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,7 +35,7 @@ //! //! The binary will have all the standard arguments of a python interpreter (including a REPL!) but //! it will have your modules loaded into the vm. -#![allow(clippy::needless_doctest_main, clippy::unnecessary_wraps)] +#![allow(clippy::needless_doctest_main)] #[macro_use] extern crate clap; diff --git a/src/shell/helper.rs b/src/shell/helper.rs index 03be107e9..171b7c274 100644 --- a/src/shell/helper.rs +++ b/src/shell/helper.rs @@ -55,7 +55,6 @@ impl<'vm> ShellHelper<'vm> { ShellHelper { vm, globals } } - #[allow(clippy::type_complexity)] fn get_available_completions<'w>( &self, words: &'w [String], diff --git a/stdlib/src/array.rs b/stdlib/src/array.rs index 6703a3c1e..fb74a442d 100644 --- a/stdlib/src/array.rs +++ b/stdlib/src/array.rs @@ -49,7 +49,6 @@ mod array { $($n(Vec<$t>),)* } - #[allow(clippy::naive_bytecount, clippy::float_cmp)] impl ArrayContentType { fn from_char(c: char) -> Result { match c { diff --git a/stdlib/src/binascii.rs b/stdlib/src/binascii.rs index 2130b5ddc..db59bc827 100644 --- a/stdlib/src/binascii.rs +++ b/stdlib/src/binascii.rs @@ -111,7 +111,7 @@ mod decl { #[pyfunction] fn b2a_base64(data: ArgBytesLike, NewlineArg { newline }: NewlineArg) -> Vec { - #[allow(clippy::redundant_closure)] // https://stackoverflow.com/questions/63916821 + // https://stackoverflow.com/questions/63916821 let mut encoded = data.with_ref(|b| base64::encode(b)).into_bytes(); if newline { encoded.push(b'\n'); diff --git a/stdlib/src/math.rs b/stdlib/src/math.rs index 29c8c6e6f..e74af7030 100644 --- a/stdlib/src/math.rs +++ b/stdlib/src/math.rs @@ -72,7 +72,6 @@ mod math { abs_tol: OptionalArg, } - #[allow(clippy::float_cmp)] #[pyfunction] fn isclose(args: IsCloseArgs, vm: &VirtualMachine) -> PyResult { let a = args.a.to_f64(); @@ -628,7 +627,6 @@ mod math { // digit to two instead of down to zero (the 1e-16 makes the 1 // slightly closer to two). With a potential 1 ULP rounding // error fixed-up, math.fsum() can guarantee commutativity. - #[allow(clippy::float_cmp)] if y == x - hi { hi = x; } diff --git a/stdlib/src/socket.rs b/stdlib/src/socket.rs index 4059cd395..378d3f7dc 100644 --- a/stdlib/src/socket.rs +++ b/stdlib/src/socket.rs @@ -24,12 +24,12 @@ mod _socket { use crossbeam_utils::atomic::AtomicCell; use num_traits::ToPrimitive; use socket2::{Domain, Protocol, Socket, Type as SocketType}; - use std::mem::MaybeUninit; - use std::net::{self, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs}; - use std::time::{Duration, Instant}; use std::{ ffi, io::{self, Read, Write}, + mem::MaybeUninit, + net::{self, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs}, + time::{Duration, Instant}, }; #[cfg(unix)] diff --git a/vm/build.rs b/vm/build.rs index 556682266..501f2bed5 100644 --- a/vm/build.rs +++ b/vm/build.rs @@ -1,8 +1,5 @@ use itertools::Itertools; -use std::env; -use std::io::prelude::*; -use std::path::PathBuf; -use std::process::Command; +use std::{env, io::prelude::*, path::PathBuf, process::Command}; fn main() { println!("cargo:rustc-env=RUSTPYTHON_GIT_HASH={}", git_hash()); diff --git a/vm/src/builtins/bytes.rs b/vm/src/builtins/bytes.rs index ed6f90938..720ae7998 100644 --- a/vm/src/builtins/bytes.rs +++ b/vm/src/builtins/bytes.rs @@ -25,8 +25,7 @@ use crate::{ VirtualMachine, }; use bstr::ByteSlice; -use std::ops::Deref; -use std::{borrow::Cow, mem::size_of}; +use std::{borrow::Cow, mem::size_of, ops::Deref}; #[pyclass(module = false, name = "bytes")] #[derive(Clone, Debug)] diff --git a/vm/src/builtins/code.rs b/vm/src/builtins/code.rs index 6dbc85005..62e208d91 100644 --- a/vm/src/builtins/code.rs +++ b/vm/src/builtins/code.rs @@ -10,8 +10,7 @@ use crate::{ StaticType, TypeProtocol, VirtualMachine, }; use num_traits::Zero; -use std::fmt; -use std::ops::Deref; +use std::{fmt, ops::Deref}; #[derive(Clone)] pub struct PyConstant(pub PyObjectRef); diff --git a/vm/src/builtins/dict.rs b/vm/src/builtins/dict.rs index f3b069b58..30914e51c 100644 --- a/vm/src/builtins/dict.rs +++ b/vm/src/builtins/dict.rs @@ -19,7 +19,6 @@ use crate::{ PyObjectView, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, }; use rustpython_common::lock::PyMutex; -use std::mem::size_of; use std::{borrow::Cow, fmt}; pub type DictContentType = dictdatatype::Dict; @@ -221,7 +220,7 @@ impl PyDict { #[pymethod(magic)] fn sizeof(&self) -> usize { - size_of::() + self.entries.sizeof() + std::mem::size_of::() + self.entries.sizeof() } #[pymethod(magic)] @@ -679,7 +678,6 @@ where self.dict().len() } - #[allow(clippy::redundant_closure_call)] #[pymethod(magic)] fn repr(zelf: PyRef, vm: &VirtualMachine) -> PyResult { let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { diff --git a/vm/src/builtins/int.rs b/vm/src/builtins/int.rs index 6b1e2ccc1..db75edec9 100644 --- a/vm/src/builtins/int.rs +++ b/vm/src/builtins/int.rs @@ -14,7 +14,6 @@ use num_bigint::{BigInt, BigUint, Sign}; use num_integer::Integer; use num_traits::{One, Pow, PrimInt, Signed, ToPrimitive, Zero}; use std::fmt; -use std::mem::size_of; /// int(x=0) -> integer /// int(x, base=10) -> integer @@ -583,7 +582,7 @@ impl PyInt { #[pymethod(magic)] fn sizeof(&self) -> usize { - size_of::() + (((self.value.bits() + 7) & !7) / 8) as usize + std::mem::size_of::() + (((self.value.bits() + 7) & !7) / 8) as usize } #[pymethod] diff --git a/vm/src/builtins/list.rs b/vm/src/builtins/list.rs index 94b0548da..69639589d 100644 --- a/vm/src/builtins/list.rs +++ b/vm/src/builtins/list.rs @@ -17,10 +17,7 @@ use crate::{ PyClassImpl, PyComparisonValue, PyContext, PyObject, PyObjectRef, PyObjectView, PyObjectWrap, PyRef, PyResult, PyValue, TypeProtocol, }; -use std::borrow::Cow; -use std::fmt; -use std::mem::size_of; -use std::ops::DerefMut; +use std::{borrow::Cow, fmt, ops::DerefMut}; /// Built-in mutable sequence. /// @@ -176,7 +173,8 @@ impl PyList { #[pymethod(magic)] fn sizeof(&self) -> usize { - size_of::() + self.elements.read().capacity() * size_of::() + std::mem::size_of::() + + self.elements.read().capacity() * std::mem::size_of::() } #[pymethod] diff --git a/vm/src/builtins/pystr.rs b/vm/src/builtins/pystr.rs index a01d715e3..e45eefd01 100644 --- a/vm/src/builtins/pystr.rs +++ b/vm/src/builtins/pystr.rs @@ -27,10 +27,7 @@ use rustpython_common::{ hash, lock::PyMutex, }; -use std::mem::size_of; -use std::ops::Range; -use std::string::ToString; -use std::{char, fmt}; +use std::{char, fmt, ops::Range, string::ToString}; use unic_ucd_bidi::BidiClass; use unic_ucd_category::GeneralCategory; use unic_ucd_ident::{is_xid_continue, is_xid_start}; @@ -495,7 +492,7 @@ impl PyStr { #[pymethod(magic)] fn sizeof(&self) -> usize { - size_of::() + self.byte_len() * size_of::() + std::mem::size_of::() + self.byte_len() * std::mem::size_of::() } #[pymethod(name = "__rmul__")] diff --git a/vm/src/builtins/pytype.rs b/vm/src/builtins/pytype.rs index 052826493..58e5216e0 100644 --- a/vm/src/builtins/pytype.rs +++ b/vm/src/builtins/pytype.rs @@ -446,8 +446,7 @@ impl PyType { // Search the bases for the proper metatype to deal with this: let winner = calculate_meta_class(metatype.clone(), &bases, vm)?; let metatype = if !winner.is(&metatype) { - #[allow(clippy::redundant_clone)] // false positive - if let Some(ref slot_new) = winner.clone().slots.new.load() { + if let Some(ref slot_new) = winner.slots.new.load() { // Pass it to the winner return slot_new(winner, args, vm); } diff --git a/vm/src/builtins/range.rs b/vm/src/builtins/range.rs index eff25edfe..075e997ef 100644 --- a/vm/src/builtins/range.rs +++ b/vm/src/builtins/range.rs @@ -1,7 +1,7 @@ use super::{PyInt, PyIntRef, PySlice, PyTupleRef, PyTypeRef}; -use crate::builtins::builtins_iter; use crate::common::hash::PyHash; use crate::{ + builtins::builtins_iter, function::{FuncArgs, OptionalArg}, protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods}, types::{ @@ -15,8 +15,7 @@ use crossbeam_utils::atomic::AtomicCell; use num_bigint::{BigInt, Sign}; use num_integer::Integer; use num_traits::{One, Signed, ToPrimitive, Zero}; -use std::borrow::Cow; -use std::cmp::max; +use std::{borrow::Cow, cmp::max}; // Search flag passed to iter_search enum SearchType { diff --git a/vm/src/builtins/tuple.rs b/vm/src/builtins/tuple.rs index c6bc0fca1..daff8e025 100644 --- a/vm/src/builtins/tuple.rs +++ b/vm/src/builtins/tuple.rs @@ -1,12 +1,10 @@ use super::{PositionIterInternal, PyGenericAlias, PyTypeRef}; use crate::common::{hash::PyHash, lock::PyMutex}; -use crate::sliceable::SequenceIndex; -use crate::TryFromBorrowedObject; use crate::{ function::{IntoPyObject, OptionalArg}, protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods}, sequence::{ObjectSequenceOp, SequenceOp}, - sliceable::SliceableSequenceOp, + sliceable::{SequenceIndex, SliceableSequenceOp}, stdlib::sys, types::{ AsMapping, AsSequence, Comparable, Constructor, Hashable, IterNext, IterNextIterable, @@ -15,11 +13,10 @@ use crate::{ utils::collection_repr, vm::{ReprGuard, VirtualMachine}, IdProtocol, PyArithmeticValue, PyClassImpl, PyComparisonValue, PyContext, PyObject, - PyObjectRef, PyRef, PyResult, PyValue, TransmuteFromObject, TryFromObject, TypeProtocol, + PyObjectRef, PyRef, PyResult, PyValue, TransmuteFromObject, TryFromBorrowedObject, + TryFromObject, TypeProtocol, }; -use std::borrow::Cow; -use std::fmt; -use std::marker::PhantomData; +use std::{borrow::Cow, fmt, marker::PhantomData}; /// tuple() -> empty tuple /// tuple(iterable) -> tuple initialized from iterable's items diff --git a/vm/src/builtins/weakref.rs b/vm/src/builtins/weakref.rs index 841681444..f9139f025 100644 --- a/vm/src/builtins/weakref.rs +++ b/vm/src/builtins/weakref.rs @@ -1,6 +1,8 @@ use super::{PyGenericAlias, PyTypeRef}; -use crate::common::atomic::{Ordering, Radium}; -use crate::common::hash::{self, PyHash}; +use crate::common::{ + atomic::{Ordering, Radium}, + hash::{self, PyHash}, +}; use crate::{ function::OptionalArg, types::{Callable, Comparable, Constructor, Hashable, PyComparisonOp}, diff --git a/vm/src/cformat.rs b/vm/src/cformat.rs index 09f7dd979..0184b00c8 100644 --- a/vm/src/cformat.rs +++ b/vm/src/cformat.rs @@ -11,11 +11,12 @@ use crate::{ }; use itertools::Itertools; use num_bigint::{BigInt, Sign}; -use num_traits::cast::ToPrimitive; -use num_traits::Signed; -use std::iter::{Enumerate, Peekable}; -use std::str::FromStr; -use std::{cmp, fmt}; +use num_traits::{cast::ToPrimitive, Signed}; +use std::{ + cmp, fmt, + iter::{Enumerate, Peekable}, + str::FromStr, +}; #[derive(Debug, PartialEq)] enum CFormatErrorType { diff --git a/vm/src/codecs.rs b/vm/src/codecs.rs index 9609e305e..af47a927d 100644 --- a/vm/src/codecs.rs +++ b/vm/src/codecs.rs @@ -5,9 +5,7 @@ use crate::{ IdProtocol, PyContext, PyObject, PyObjectRef, PyResult, PyValue, TryFromObject, TypeProtocol, VirtualMachine, }; -use std::borrow::Cow; -use std::collections::HashMap; -use std::ops::Range; +use std::{borrow::Cow, collections::HashMap, fmt::Write, ops::Range}; pub struct CodecsRegistry { inner: PyRwLock, @@ -422,7 +420,6 @@ fn xmlcharrefreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<( // capacity rough guess; assuming that the codepoints are 3 digits in decimal + the &#; let mut out = String::with_capacity(num_chars * 6); for c in s_after_start.chars().take(num_chars) { - use std::fmt::Write; write!(out, "&#{};", c as u32).unwrap() } Ok((out, range.end)) @@ -434,7 +431,6 @@ fn backslashreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(S let b = PyBytesRef::try_from_object(vm, err.get_attr("object", vm)?)?; let mut replace = String::with_capacity(4 * range.len()); for &c in &b[range.clone()] { - use std::fmt::Write; write!(replace, "\\x{:02x}", c).unwrap(); } return Ok((replace, range.end)); @@ -448,7 +444,6 @@ fn backslashreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(S // minimum 4 output bytes per char: \xNN let mut out = String::with_capacity(num_chars * 4); for c in s_after_start.chars().take(num_chars) { - use std::fmt::Write; let c = c as u32; if c >= 0x10000 { write!(out, "\\U{:08x}", c).unwrap(); @@ -470,7 +465,6 @@ fn namereplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String let num_chars = range.len(); let mut out = String::with_capacity(num_chars * 4); for c in s_after_start.chars().take(num_chars) { - use std::fmt::Write; let c_u32 = c as u32; if let Some(c_name) = unicode_names2::name(c) { write!(out, "\\N{{{c_name}}}").unwrap(); @@ -571,7 +565,6 @@ fn surrogatepass_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(Stri let num_chars = range.len(); let mut out = String::with_capacity(num_chars * 4); for c in s_after_start.chars().take(num_chars).map(|x| x as u32) { - use std::fmt::Write; if !(0xd800..=0xdfff).contains(&c) { // Not a surrogate, fail with original exception return Err(err.downcast().unwrap()); @@ -678,7 +671,6 @@ fn surrogateescape_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(St let num_chars = range.len(); let mut out = String::with_capacity(num_chars * 4); for c in s_after_start.chars().take(num_chars).map(|x| x as u32) { - use std::fmt::Write; if !(0xd800..=0xdfff).contains(&c) { // Not a UTF-8b surrogate, fail with original exception return Err(err.downcast().unwrap()); @@ -700,7 +692,6 @@ fn surrogateescape_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(St // Refuse to escape ASCII bytes break; } - use std::fmt::Write; write!(replace, "#{}", 0xdc00 + c).unwrap(); consumed += 1; } diff --git a/vm/src/dictdatatype.rs b/vm/src/dictdatatype.rs index bd57b0ddf..5503b13e1 100644 --- a/vm/src/dictdatatype.rs +++ b/vm/src/dictdatatype.rs @@ -1,24 +1,20 @@ -use num_traits::ToPrimitive; +//! Ordered dictionary implementation. +//! Inspired by: https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html +//! And: https://www.youtube.com/watch?v=p33CVV29OG8 +//! And: http://code.activestate.com/recipes/578375/ -/// Ordered dictionary implementation. -/// Inspired by: https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html -/// And: https://www.youtube.com/watch?v=p33CVV29OG8 -/// And: http://code.activestate.com/recipes/578375/ +use crate::common::{ + hash, + lock::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard}, +}; use crate::{ builtins::{PyInt, PyStr, PyStrRef}, function::IntoPyObject, - IdProtocol, PyObject, PyObjectRef, PyRefExact, PyResult, TypeProtocol, VirtualMachine, + IdProtocol, PyObject, PyObjectRef, PyObjectWrap, PyRefExact, PyResult, TypeProtocol, + VirtualMachine, }; -use crate::{ - common::{ - hash, - lock::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard}, - }, - PyObjectWrap, -}; -use std::fmt; -use std::mem::size_of; -use std::ops::ControlFlow; +use num_traits::ToPrimitive; +use std::{fmt, mem::size_of, ops::ControlFlow}; // HashIndex is intended to be same size with hash::PyHash // but it doesn't mean the values are compatible with actual pyhash value diff --git a/vm/src/format.rs b/vm/src/format.rs index 8affa8d2f..c4a762bfc 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -7,10 +7,8 @@ use crate::{ }; use itertools::{Itertools, PeekingNext}; use num_bigint::{BigInt, Sign}; -use num_traits::cast::ToPrimitive; -use num_traits::Signed; -use std::cmp; -use std::str::FromStr; +use num_traits::{cast::ToPrimitive, Signed}; +use std::{cmp, str::FromStr}; #[derive(Debug, Copy, Clone, PartialEq)] enum FormatPreconversor { diff --git a/vm/src/function.rs b/vm/src/function.rs index a4cec3085..c0957a1da 100644 --- a/vm/src/function.rs +++ b/vm/src/function.rs @@ -9,8 +9,7 @@ use crate::{ }; use indexmap::IndexMap; use itertools::Itertools; -use std::marker::PhantomData; -use std::ops::RangeInclusive; +use std::{marker::PhantomData, ops::RangeInclusive}; pub use argument::{ArgCallable, ArgIterable, ArgMapping, ArgSequence}; pub use buffer::{ArgAsciiBuffer, ArgBytesLike, ArgMemoryBuffer, ArgStrOrBytesLike}; diff --git a/vm/src/lib.rs b/vm/src/lib.rs index 3d897fe8b..af3a4b274 100644 --- a/vm/src/lib.rs +++ b/vm/src/lib.rs @@ -5,13 +5,9 @@ //! - Import mechanics //! - Base objects -// for methods like vm.to_str(), not the typical use of 'to' as a method prefix -#![allow(clippy::wrong_self_convention)] // to allow `mod foo {}` in foo.rs; clippy thinks this is a mistake/misunderstanding of // how `mod` works, but we want this sometimes for pymodule declarations #![allow(clippy::module_inception)] -// to encourage good API design, see https://github.com/rust-lang/rust-clippy/issues/6726 -#![allow(clippy::unnecessary_wraps)] // we want to mirror python naming conventions when defining python structs, so that does mean // uppercase acronyms, e.g. TextIOWrapper instead of TextIoWrapper #![allow(clippy::upper_case_acronyms)] diff --git a/vm/src/protocol/buffer.rs b/vm/src/protocol/buffer.rs index 39b1e23dc..8b4d84688 100644 --- a/vm/src/protocol/buffer.rs +++ b/vm/src/protocol/buffer.rs @@ -15,7 +15,6 @@ use crate::{ }; use std::{borrow::Cow, fmt::Debug, ops::Range}; -#[allow(clippy::type_complexity)] pub struct BufferMethods { pub obj_bytes: fn(&PyBuffer) -> BorrowedValue<[u8]>, pub obj_bytes_mut: fn(&PyBuffer) -> BorrowedValueMut<[u8]>, diff --git a/vm/src/protocol/sequence.rs b/vm/src/protocol/sequence.rs index 8d1c45d8c..bdea55d1f 100644 --- a/vm/src/protocol/sequence.rs +++ b/vm/src/protocol/sequence.rs @@ -1,8 +1,3 @@ -use std::borrow::{Borrow, Cow}; -use std::fmt::Debug; - -use itertools::Itertools; - use crate::{ builtins::{PyList, PyListRef, PySlice, PyTuple, PyTupleRef}, common::lock::OnceCell, @@ -11,6 +6,11 @@ use crate::{ IdProtocol, PyArithmeticValue, PyObject, PyObjectRef, PyResult, PyValue, TypeProtocol, VirtualMachine, }; +use itertools::Itertools; +use std::{ + borrow::{Borrow, Cow}, + fmt::Debug, +}; // Sequence Protocol // https://docs.python.org/3/c-api/sequence.html diff --git a/vm/src/readline.rs b/vm/src/readline.rs index 8844b3788..89ec88e92 100644 --- a/vm/src/readline.rs +++ b/vm/src/readline.rs @@ -1,5 +1,4 @@ -use std::io; -use std::path::Path; +use std::{io, path::Path}; type OtherError = Box; type OtherResult = Result; diff --git a/vm/src/signal.rs b/vm/src/signal.rs index 6f399642a..2d46c1849 100644 --- a/vm/src/signal.rs +++ b/vm/src/signal.rs @@ -1,8 +1,12 @@ #![cfg_attr(target_os = "wasi", allow(dead_code))] use crate::{PyResult, VirtualMachine}; -use std::fmt; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc; +use std::{ + fmt, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc, + }, +}; pub(crate) const NSIG: usize = 64; static ANY_TRIGGERED: AtomicBool = AtomicBool::new(false); diff --git a/vm/src/stdlib/builtins.rs b/vm/src/stdlib/builtins.rs index 959238616..c944dfce1 100644 --- a/vm/src/stdlib/builtins.rs +++ b/vm/src/stdlib/builtins.rs @@ -576,7 +576,6 @@ mod builtins { modulus: Option, } - #[allow(clippy::suspicious_else_formatting)] #[pyfunction] fn pow(args: PowArgs, vm: &VirtualMachine) -> PyResult { let PowArgs { @@ -592,18 +591,12 @@ mod builtins { let try_pow_value = |obj: &PyObject, args: (PyObjectRef, PyObjectRef, PyObjectRef)| -> Option { - if let Some(method) = obj.get_class_attr("__pow__") { - let result = match vm.invoke(&method, args) { - Ok(x) => x, - Err(e) => return Some(Err(e)), - }; - if let PyArithmeticValue::Implemented(x) = - PyArithmeticValue::from_object(vm, result) - { - return Some(Ok(x)); - } - } - None + let method = obj.get_class_attr("__pow__")?; + let result = match vm.invoke(&method, args) { + Ok(x) => x, + Err(e) => return Some(Err(e)), + }; + Some(Ok(PyArithmeticValue::from_object(vm, result).into_option()?)) }; if let Some(val) = try_pow_value(&x, (x.clone(), y.clone(), z.clone())) { diff --git a/vm/src/stdlib/functools.rs b/vm/src/stdlib/functools.rs index f6475dd8d..fc53c5aaa 100644 --- a/vm/src/stdlib/functools.rs +++ b/vm/src/stdlib/functools.rs @@ -2,10 +2,7 @@ pub(crate) use _functools::make_module; #[pymodule] mod _functools { - use crate::function::OptionalArg; - use crate::protocol::PyIter; - use crate::vm::VirtualMachine; - use crate::{PyObjectRef, PyResult}; + use crate::{function::OptionalArg, protocol::PyIter, PyObjectRef, PyResult, VirtualMachine}; #[pyfunction] fn reduce( diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index 0f6d99063..eca8f432a 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -93,8 +93,10 @@ mod _io { use bstr::ByteSlice; use crossbeam_utils::atomic::AtomicCell; use num_traits::ToPrimitive; - use std::io::{self, prelude::*, Cursor, SeekFrom}; - use std::ops::Range; + use std::{ + io::{self, prelude::*, Cursor, SeekFrom}, + ops::Range, + }; #[allow(clippy::let_and_return)] fn validate_whence(whence: i32) -> bool { @@ -136,6 +138,7 @@ mod _io { } impl OptionalSize { + #[allow(clippy::wrong_self_convention)] pub fn to_usize(self) -> Option { self.size.and_then(|v| v.to_usize()) } @@ -3649,8 +3652,7 @@ mod _io { #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] #[pymodule] mod fileio { - use super::Offset; - use super::_io::*; + use super::{Offset, _io::*}; use crate::{ builtins::{PyStr, PyStrRef, PyTypeRef}, crt_fd::Fd, diff --git a/vm/src/stdlib/itertools.rs b/vm/src/stdlib/itertools.rs index 51a32ffa5..b2d040f45 100644 --- a/vm/src/stdlib/itertools.rs +++ b/vm/src/stdlib/itertools.rs @@ -995,7 +995,6 @@ mod decl { // TODO: make tee() a function, rename this class to itertools._tee and make // teedata a python class - #[allow(clippy::new_ret_no_self)] fn py_new( _cls: PyTypeRef, Self::Args { iterable, n }: Self::Args, diff --git a/vm/src/stdlib/mod.rs b/vm/src/stdlib/mod.rs index 10861779e..3d091ad5d 100644 --- a/vm/src/stdlib/mod.rs +++ b/vm/src/stdlib/mod.rs @@ -49,13 +49,10 @@ mod winapi; #[cfg(windows)] mod winreg; -use crate::vm::VirtualMachine; -use crate::PyObjectRef; -use std::borrow::Cow; -use std::collections::HashMap; +use crate::{PyObjectRef, VirtualMachine}; +use std::{borrow::Cow, collections::HashMap}; pub type StdlibInitFunc = Box PyObjectRef)>; - pub type StdlibMap = HashMap, StdlibInitFunc, ahash::RandomState>; pub fn get_module_inits() -> StdlibMap { diff --git a/vm/src/stdlib/nt.rs b/vm/src/stdlib/nt.rs index 5a8d12ac3..77dcd855b 100644 --- a/vm/src/stdlib/nt.rs +++ b/vm/src/stdlib/nt.rs @@ -22,8 +22,7 @@ pub(crate) mod module { utils::Either, PyResult, TryFromObject, VirtualMachine, }; - use std::io; - use std::{env, fs}; + use std::{env, fs, io}; use crate::builtins::PyDictRef; #[cfg(target_env = "msvc")] diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index f138adf62..ce1f92802 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -1,15 +1,16 @@ -use crate::crt_fd::Fd; use crate::{ builtins::{PyBaseExceptionRef, PyBytes, PyBytesRef, PyInt, PySet, PyStr, PyStrRef}, + crt_fd::Fd, function::{ArgumentError, FromArgs, FuncArgs, IntoPyException, IntoPyObject}, protocol::PyBuffer, PyObject, PyObjectRef, PyResult, PyValue, TryFromBorrowedObject, TryFromObject, TypeProtocol, VirtualMachine, }; -use std::ffi; -use std::fs; -use std::io::{self, ErrorKind}; -use std::path::{Path, PathBuf}; +use std::{ + ffi, fs, + io::{self, ErrorKind}, + path::{Path, PathBuf}, +}; #[cfg(unix)] use std::os::unix::ffi as ffi_ext; @@ -444,12 +445,13 @@ pub(super) mod _os { }; use crossbeam_utils::atomic::AtomicCell; use itertools::Itertools; - use std::ffi; - use std::fs::OpenOptions; - use std::io::{self, Read, Write}; - use std::path::PathBuf; - use std::time::{Duration, SystemTime}; - use std::{env, fs}; + use std::{ + env, ffi, fs, + fs::OpenOptions, + io::{self, Read, Write}, + path::PathBuf, + time::{Duration, SystemTime}, + }; const OPEN_DIR_FD: bool = cfg!(not(any(windows, target_os = "redox"))); pub(crate) const MKDIR_DIR_FD: bool = cfg!(not(any(windows, target_os = "redox"))); @@ -1472,10 +1474,11 @@ pub(super) mod _os { } #[cfg(windows)] { - use std::fs::OpenOptions; - use std::os::windows::prelude::*; - use winapi::shared::minwindef::{DWORD, FILETIME}; - use winapi::um::fileapi::SetFileTime; + use std::{fs::OpenOptions, os::windows::prelude::*}; + use winapi::{ + shared::minwindef::{DWORD, FILETIME}, + um::fileapi::SetFileTime, + }; let [] = dir_fd.0; diff --git a/vm/src/stdlib/posix.rs b/vm/src/stdlib/posix.rs index 81fae3272..5beb08898 100644 --- a/vm/src/stdlib/posix.rs +++ b/vm/src/stdlib/posix.rs @@ -1,5 +1,4 @@ use crate::{PyObjectRef, PyResult, VirtualMachine}; -use nix; use std::os::unix::io::RawFd; pub fn raw_set_inheritable(fd: RawFd, inheritable: bool) -> nix::Result<()> { @@ -41,12 +40,16 @@ pub mod module { PyObjectRef, PyResult, PyValue, TryFromObject, TypeProtocol, VirtualMachine, }; use bitflags::bitflags; - use nix::fcntl; - use nix::unistd::{self, Gid, Pid, Uid}; - use std::ffi::{CStr, CString}; - use std::os::unix::ffi as ffi_ext; - use std::os::unix::io::RawFd; - use std::{env, fs, io}; + use nix::{ + fcntl, + unistd::{self, Gid, Pid, Uid}, + }; + use std::{ + env, + ffi::{CStr, CString}, + fs, io, + os::unix::{ffi as ffi_ext, io::RawFd}, + }; use strum_macros::EnumString; #[pyattr] diff --git a/vm/src/stdlib/thread.rs b/vm/src/stdlib/thread.rs index d8a91dc27..abb67fe22 100644 --- a/vm/src/stdlib/thread.rs +++ b/vm/src/stdlib/thread.rs @@ -110,7 +110,6 @@ pub(crate) mod _thread { #[pymethod] #[pymethod(name = "acquire_lock")] #[pymethod(name = "__enter__")] - #[allow(clippy::float_cmp, clippy::match_bool)] fn acquire(&self, args: AcquireArgs, vm: &VirtualMachine) -> PyResult { acquire_lock_impl!(&self.mu, args, vm) } @@ -174,7 +173,6 @@ pub(crate) mod _thread { #[pymethod] #[pymethod(name = "acquire_lock")] #[pymethod(name = "__enter__")] - #[allow(clippy::float_cmp, clippy::match_bool)] fn acquire(&self, args: AcquireArgs, vm: &VirtualMachine) -> PyResult { acquire_lock_impl!(&self.mu, args, vm) } diff --git a/vm/src/stdlib/winreg.rs b/vm/src/stdlib/winreg.rs index 3c6124958..a90d0707c 100644 --- a/vm/src/stdlib/winreg.rs +++ b/vm/src/stdlib/winreg.rs @@ -33,8 +33,7 @@ mod winreg { TryFromObject, VirtualMachine, }; use ::winreg::{enums::RegType, RegKey, RegValue}; - use std::ffi::OsStr; - use std::io; + use std::{ffi::OsStr, io}; use winapi::shared::winerror; // access rights diff --git a/vm/src/types/slot.rs b/vm/src/types/slot.rs index 00ca9b0ee..0392ace80 100644 --- a/vm/src/types/slot.rs +++ b/vm/src/types/slot.rs @@ -1,19 +1,17 @@ pub use crate::builtins::object::{generic_getattr, generic_setattr}; use crate::common::{hash::PyHash, lock::PyRwLock}; -use crate::function::IntoPyObject; -use crate::protocol::{PySequence, PySequenceMethods}; use crate::{ builtins::{PyInt, PyStrRef, PyType, PyTypeRef}, - function::{FromArgs, FuncArgs, IntoPyResult, OptionalArg}, + function::{FromArgs, FuncArgs, IntoPyObject, IntoPyResult, OptionalArg}, protocol::{PyBuffer, PyIterReturn, PyMapping, PyMappingMethods}, + protocol::{PySequence, PySequenceMethods}, utils::Either, IdProtocol, PyComparisonValue, PyObject, PyObjectRef, PyObjectView, PyRef, PyResult, PyValue, TypeProtocol, VirtualMachine, }; use crossbeam_utils::atomic::AtomicCell; use num_traits::{Signed, ToPrimitive}; -use std::borrow::Cow; -use std::cmp::Ordering; +use std::{borrow::Cow, cmp::Ordering}; // The corresponding field in CPython is `tp_` prefixed. // e.g. name -> tp_name diff --git a/vm/src/vm.rs b/vm/src/vm.rs index 3812cdede..03ac8e935 100644 --- a/vm/src/vm.rs +++ b/vm/src/vm.rs @@ -30,10 +30,12 @@ use crate::{ PyObjectWrap, PyRef, PyRefExact, PyResult, PyValue, TryFromObject, TypeProtocol, }; use crossbeam_utils::atomic::AtomicCell; -use std::borrow::Cow; -use std::cell::{Cell, Ref, RefCell}; -use std::collections::{HashMap, HashSet}; -use std::fmt; +use std::{ + borrow::Cow, + cell::{Cell, Ref, RefCell}, + collections::{HashMap, HashSet}, + fmt, +}; // use objects::ects; @@ -72,9 +74,7 @@ struct ExceptionStack { pub(crate) mod thread { use super::{PyObject, TypeProtocol, VirtualMachine}; use itertools::Itertools; - use std::cell::RefCell; - use std::ptr::NonNull; - use std::thread_local; + use std::{cell::RefCell, ptr::NonNull, thread_local}; thread_local! { pub(super) static VM_STACK: RefCell>> = Vec::with_capacity(1).into(); diff --git a/wasm/lib/src/lib.rs b/wasm/lib/src/lib.rs index d60f6c145..40b5808b3 100644 --- a/wasm/lib/src/lib.rs +++ b/wasm/lib/src/lib.rs @@ -1,5 +1,3 @@ -#![allow(clippy::upper_case_acronyms)] - pub mod browser_module; pub mod convert; pub mod js_module; @@ -9,13 +7,11 @@ pub mod wasm_builtins; #[macro_use] extern crate rustpython_vm; -pub(crate) use vm_class::weak_vm; - use js_sys::{Reflect, WebAssembly::RuntimeError}; use std::panic; -use wasm_bindgen::prelude::*; - pub use vm_class::add_init_func; +pub(crate) use vm_class::weak_vm; +use wasm_bindgen::prelude::*; /// Sets error info on the window object, and prints the backtrace to console pub fn panic_hook(info: &panic::PanicInfo) { diff --git a/wasm/lib/src/vm_class.rs b/wasm/lib/src/vm_class.rs index b50d255d9..731c0173c 100644 --- a/wasm/lib/src/vm_class.rs +++ b/wasm/lib/src/vm_class.rs @@ -1,20 +1,22 @@ -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::{Rc, Weak}; - +use crate::{ + browser_module::setup_browser_module, + convert::{self, PyResultExt}, + js_module, wasm_builtins, +}; use js_sys::{Object, TypeError}; +use rustpython_vm::{ + compile::{self, Mode}, + scope::Scope, + InitParameter, Interpreter, PyObjectRef, PyObjectWeak, PyResult, PySettings, PyValue, + VirtualMachine, +}; +use std::{ + cell::RefCell, + collections::HashMap, + rc::{Rc, Weak}, +}; use wasm_bindgen::prelude::*; -use rustpython_vm::compile::{self, Mode}; -use rustpython_vm::scope::Scope; -use rustpython_vm::{InitParameter, Interpreter, PySettings, VirtualMachine}; -use rustpython_vm::{PyObjectRef, PyObjectWeak, PyResult, PyValue}; - -use crate::browser_module::setup_browser_module; -use crate::convert::{self, PyResultExt}; -use crate::js_module; -use crate::wasm_builtins; - pub(crate) struct StoredVirtualMachine { pub interp: Interpreter, pub scope: Scope,