clean up imports and useless allow attributes

This commit is contained in:
Jeong Yunwon committed 2022-04-15 23:58:20 +09:00
1 parent 0fb5327271
commit 6357a1acbe
55 files changed
+185 -243

No files matched your search

+1 -2
View File
@@ -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;
+6 -4
View File
@@ -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,
+1 -2
View File
@@ -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)]
+9 -7
View File
@@ -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<T> {
xs: Box<[MaybeUninit<T>]>,
@@ -501,9 +505,7 @@ impl<T> 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 {
+4 -2
View File
@@ -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;
+1 -2
View File
@@ -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<bool>,
+1 -4
View File
@@ -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
+8 -7
View File
@@ -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
+5 -4
View File
@@ -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;
-1
View File
@@ -88,7 +88,6 @@ struct CompileContext {
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(clippy::enum_variant_names)]
enum FunctionContext {
NoFunction,
Function,
+1 -2
View File
@@ -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 {
+5 -4
View File
@@ -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<SymbolTable> {
let mut builder = SymbolTableBuilder::new();
+3 -9
View File
@@ -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 {}
+6 -8
View File
@@ -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<str::Chars<'a>>,
+1 -1
View File
@@ -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;
-1
View File
@@ -55,7 +55,6 @@ impl<'vm> ShellHelper<'vm> {
ShellHelper { vm, globals }
}
#[allow(clippy::type_complexity)]
fn get_available_completions<'w>(
&self,
words: &'w [String],
-1
View File
@@ -49,7 +49,6 @@ mod array {
$($n(Vec<$t>),)*
}
#[allow(clippy::naive_bytecount, clippy::float_cmp)]
impl ArrayContentType {
fn from_char(c: char) -> Result<Self, String> {
match c {
+1 -1
View File
@@ -111,7 +111,7 @@ mod decl {
#[pyfunction]
fn b2a_base64(data: ArgBytesLike, NewlineArg { newline }: NewlineArg) -> Vec<u8> {
#[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');
-2
View File
@@ -72,7 +72,6 @@ mod math {
abs_tol: OptionalArg<ArgIntoFloat>,
}
#[allow(clippy::float_cmp)]
#[pyfunction]
fn isclose(args: IsCloseArgs, vm: &VirtualMachine) -> PyResult<bool> {
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;
}
+3 -3
View File
@@ -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)]
+1 -4
View File
@@ -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());
+1 -2
View File
@@ -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)]
+1 -2
View File
@@ -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);
+1 -3
View File
@@ -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>() + self.entries.sizeof()
std::mem::size_of::<Self>() + self.entries.sizeof()
}
#[pymethod(magic)]
@@ -679,7 +678,6 @@ where
self.dict().len()
}
#[allow(clippy::redundant_closure_call)]
#[pymethod(magic)]
fn repr(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<String> {
let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
+1 -2
View File
@@ -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>() + (((self.value.bits() + 7) & !7) / 8) as usize
std::mem::size_of::<Self>() + (((self.value.bits() + 7) & !7) / 8) as usize
}
#[pymethod]
+3 -5
View File
@@ -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>() + self.elements.read().capacity() * size_of::<PyObjectRef>()
std::mem::size_of::<Self>()
+ self.elements.read().capacity() * std::mem::size_of::<PyObjectRef>()
}
#[pymethod]
+2 -5
View File
@@ -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>() + self.byte_len() * size_of::<u8>()
std::mem::size_of::<Self>() + self.byte_len() * std::mem::size_of::<u8>()
}
#[pymethod(name = "__rmul__")]
+1 -2
View File
@@ -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);
}
+2 -3
View File
@@ -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 {
+4 -7
View File
@@ -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
+4 -2
View File
@@ -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},
+6 -5
View File
@@ -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 {
+1 -10
View File
@@ -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<RegistryInner>,
@@ -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;
}
+12 -16
View File
@@ -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
+2 -4
View File
@@ -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 {
+1 -2
View File
@@ -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};
-4
View File
@@ -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)]
-1
View File
@@ -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]>,
+5 -5
View File
@@ -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
+1 -2
View File
@@ -1,5 +1,4 @@
use std::io;
use std::path::Path;
use std::{io, path::Path};
type OtherError = Box<dyn std::error::Error>;
type OtherResult<T> = Result<T, OtherError>;
+7 -3
View File
@@ -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);
+6 -13
View File
@@ -576,7 +576,6 @@ mod builtins {
modulus: Option<PyObjectRef>,
}
#[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<PyResult> {
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())) {
+1 -4
View File
@@ -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(
+6 -4
View File
@@ -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<usize> {
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,
-1
View File
@@ -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,
+2 -5
View File
@@ -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<py_dyn_fn!(dyn Fn(&VirtualMachine) -> PyObjectRef)>;
pub type StdlibMap = HashMap<Cow<'static, str>, StdlibInitFunc, ahash::RandomState>;
pub fn get_module_inits() -> StdlibMap {
+1 -2
View File
@@ -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")]
+18 -15
View File
@@ -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;
+10 -7
View File
@@ -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]
-2
View File
@@ -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<bool> {
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<bool> {
acquire_lock_impl!(&self.mu, args, vm)
}
+1 -2
View File
@@ -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
+3 -5
View File
@@ -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
+7 -7
View File
@@ -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<NonNull<VirtualMachine>>> = Vec::with_capacity(1).into();
+2 -6
View File
@@ -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) {
+16 -14
View File
@@ -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,