diff --git a/Cargo.toml b/Cargo.toml index 06734b47e18..12607cfa2cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,6 +232,9 @@ unsafe_op_in_unsafe_fn = "deny" elided_lifetimes_in_paths = "warn" [workspace.lints.clippy] +# alloc_instead_of_core = "warn" +# std_instead_of_alloc = "warn" +# std_instead_of_core = "warn" perf = "warn" style = "warn" complexity = "warn" diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 7909e924251..c44b2b00684 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -16,6 +16,7 @@ use crate::{ symboltable::{self, CompilerScope, SymbolFlags, SymbolScope, SymbolTable}, unparse::UnparseExpr, }; +use alloc::borrow::Cow; use itertools::Itertools; use malachite_bigint::BigInt; use num_complex::Complex; @@ -42,7 +43,7 @@ use rustpython_compiler_core::{ }, }; use rustpython_wtf8::Wtf8Buf; -use std::{borrow::Cow, collections::HashSet}; +use std::collections::HashSet; const MAXBLOCKS: usize = 20; @@ -293,7 +294,7 @@ fn compiler_unwrap_option(zelf: &Compiler, o: Option) -> T { o.unwrap() } -// fn compiler_result_unwrap(zelf: &Compiler, result: Result) -> T { +// fn compiler_result_unwrap(zelf: &Compiler, result: Result) -> T { // if result.is_err() { // eprintln!("=== CODEGEN PANIC INFO ==="); // eprintln!("This IS an internal error, an result was unwrapped during codegen"); @@ -1831,7 +1832,7 @@ impl Compiler { name.to_owned(), ); - let args_iter = std::iter::empty() + let args_iter = core::iter::empty() .chain(¶meters.posonlyargs) .chain(¶meters.args) .map(|arg| &arg.parameter) @@ -2438,7 +2439,7 @@ impl Compiler { let mut funcflags = bytecode::MakeFunctionFlags::empty(); // Handle positional defaults - let defaults: Vec<_> = std::iter::empty() + let defaults: Vec<_> = core::iter::empty() .chain(¶meters.posonlyargs) .chain(¶meters.args) .filter_map(|x| x.default.as_deref()) @@ -2566,7 +2567,7 @@ impl Compiler { let mut num_annotations = 0; // Handle parameter annotations - let parameters_iter = std::iter::empty() + let parameters_iter = core::iter::empty() .chain(¶meters.posonlyargs) .chain(¶meters.args) .chain(¶meters.kwonlyargs) @@ -4965,7 +4966,7 @@ impl Compiler { let name = "".to_owned(); // Prepare defaults before entering function - let defaults: Vec<_> = std::iter::empty() + let defaults: Vec<_> = core::iter::empty() .chain(¶ms.posonlyargs) .chain(¶ms.args) .filter_map(|x| x.default.as_deref()) diff --git a/crates/codegen/src/error.rs b/crates/codegen/src/error.rs index 70e2f13f253..459ba8e33b5 100644 --- a/crates/codegen/src/error.rs +++ b/crates/codegen/src/error.rs @@ -1,5 +1,6 @@ +use alloc::fmt; +use core::fmt::Display; use rustpython_compiler_core::SourceLocation; -use std::fmt::{self, Display}; use thiserror::Error; #[derive(Debug)] @@ -93,7 +94,7 @@ pub enum CodegenErrorType { NotImplementedYet, // RustPython marker for unimplemented features } -impl std::error::Error for CodegenErrorType {} +impl core::error::Error for CodegenErrorType {} impl fmt::Display for CodegenErrorType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index de0126f1122..670635fbd37 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -1,4 +1,4 @@ -use std::ops; +use core::ops; use crate::{IndexMap, IndexSet, error::InternalError}; use rustpython_compiler_core::{ @@ -198,7 +198,7 @@ impl CodeInfo { *arg = new_arg; } let (extras, lo_arg) = arg.split(); - locations.extend(std::iter::repeat_n(info.location, arg.instr_size())); + locations.extend(core::iter::repeat_n(info.location, arg.instr_size())); instructions.extend( extras .map(|byte| CodeUnit::new(Instruction::ExtendedArg, byte)) @@ -401,7 +401,7 @@ fn stackdepth_push( fn iter_blocks(blocks: &[Block]) -> impl Iterator + '_ { let mut next = BlockIdx(0); - std::iter::from_fn(move || { + core::iter::from_fn(move || { if next == BlockIdx::NULL { return None; } diff --git a/crates/codegen/src/lib.rs b/crates/codegen/src/lib.rs index 291b57d7f67..34d3870ae91 100644 --- a/crates/codegen/src/lib.rs +++ b/crates/codegen/src/lib.rs @@ -5,6 +5,8 @@ #[macro_use] extern crate log; +extern crate alloc; + type IndexMap = indexmap::IndexMap; type IndexSet = indexmap::IndexSet; diff --git a/crates/codegen/src/string_parser.rs b/crates/codegen/src/string_parser.rs index ede2f118c37..175e75c1a26 100644 --- a/crates/codegen/src/string_parser.rs +++ b/crates/codegen/src/string_parser.rs @@ -5,7 +5,7 @@ //! after ruff has already successfully parsed the string literal, meaning //! we don't need to do any validation or error handling. -use std::convert::Infallible; +use core::convert::Infallible; use ruff_python_ast::{AnyStringFlags, StringFlags}; use rustpython_wtf8::{CodePoint, Wtf8, Wtf8Buf}; @@ -96,7 +96,7 @@ impl StringParser { } // OK because radix_bytes is always going to be in the ASCII range. - let radix_str = std::str::from_utf8(&radix_bytes[..len]).expect("ASCII bytes"); + let radix_str = core::str::from_utf8(&radix_bytes[..len]).expect("ASCII bytes"); let value = u32::from_str_radix(radix_str, 8).unwrap(); char::from_u32(value).unwrap() } diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index 3c8454b9e22..1629e5fff38 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -11,6 +11,7 @@ use crate::{ IndexMap, error::{CodegenError, CodegenErrorType}, }; +use alloc::{borrow::Cow, fmt}; use bitflags::bitflags; use ruff_python_ast::{ self as ast, Comprehension, Decorator, Expr, Identifier, ModExpression, ModModule, Parameter, @@ -20,7 +21,6 @@ use ruff_python_ast::{ }; use ruff_text_size::{Ranged, TextRange}; use rustpython_compiler_core::{PositionEncoding, SourceFile, SourceLocation}; -use std::{borrow::Cow, fmt}; /// Captures all symbols in the current scope, and has a list of sub-scopes in this scope. #[derive(Clone)] @@ -215,8 +215,8 @@ impl SymbolTableError { type SymbolTableResult = Result; -impl std::fmt::Debug for SymbolTable { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for SymbolTable { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( f, "SymbolTable({:?} symbols, {:?} sub scopes)", @@ -261,8 +261,8 @@ fn drop_class_free(symbol_table: &mut SymbolTable) { type SymbolMap = IndexMap; mod stack { + use core::ptr::NonNull; use std::panic; - use std::ptr::NonNull; pub struct StackStack { v: Vec>, } @@ -325,7 +325,7 @@ struct SymbolTableAnalyzer { impl SymbolTableAnalyzer { fn analyze_symbol_table(&mut self, symbol_table: &mut SymbolTable) -> SymbolTableResult { - let symbols = std::mem::take(&mut symbol_table.symbols); + let symbols = core::mem::take(&mut symbol_table.symbols); let sub_tables = &mut *symbol_table.sub_tables; let mut info = (symbols, symbol_table.typ); @@ -689,7 +689,7 @@ impl SymbolTableBuilder { fn leave_scope(&mut self) { let mut table = self.tables.pop().unwrap(); // Save the collected varnames to the symbol table - table.varnames = std::mem::take(&mut self.current_varnames); + table.varnames = core::mem::take(&mut self.current_varnames); self.tables.last_mut().unwrap().sub_tables.push(table); } diff --git a/crates/codegen/src/unparse.rs b/crates/codegen/src/unparse.rs index 74e35fd5e2a..7b26d229187 100644 --- a/crates/codegen/src/unparse.rs +++ b/crates/codegen/src/unparse.rs @@ -1,3 +1,5 @@ +use alloc::fmt; +use core::fmt::Display as _; use ruff_python_ast::{ self as ruff, Arguments, BoolOp, Comprehension, ConversionFlag, Expr, Identifier, Operator, Parameter, ParameterWithDefault, Parameters, @@ -5,7 +7,6 @@ use ruff_python_ast::{ use ruff_text_size::Ranged; use rustpython_compiler_core::SourceFile; use rustpython_literal::escape::{AsciiEscape, UnicodeEscape}; -use std::fmt::{self, Display as _}; mod precedence { macro_rules! precedence { @@ -51,7 +52,7 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { } fn p_delim(&mut self, first: &mut bool, s: &str) -> fmt::Result { - self.p_if(!std::mem::take(first), s) + self.p_if(!core::mem::take(first), s) } fn write_fmt(&mut self, f: fmt::Arguments<'_>) -> fmt::Result { @@ -575,7 +576,7 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { if conversion != ConversionFlag::None { self.p("!")?; let buf = &[conversion as u8]; - let c = std::str::from_utf8(buf).unwrap(); + let c = core::str::from_utf8(buf).unwrap(); self.p(c)?; } @@ -650,7 +651,7 @@ impl fmt::Display for UnparseExpr<'_> { } fn to_string_fmt(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> String { - use std::cell::Cell; + use core::cell::Cell; struct Fmt(Cell>); impl) -> fmt::Result> fmt::Display for Fmt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/common/src/borrow.rs b/crates/common/src/borrow.rs index 610084006e1..d8389479b33 100644 --- a/crates/common/src/borrow.rs +++ b/crates/common/src/borrow.rs @@ -2,10 +2,8 @@ use crate::lock::{ MapImmutable, PyImmutableMappedMutexGuard, PyMappedMutexGuard, PyMappedRwLockReadGuard, PyMappedRwLockWriteGuard, PyMutexGuard, PyRwLockReadGuard, PyRwLockWriteGuard, }; -use std::{ - fmt, - ops::{Deref, DerefMut}, -}; +use alloc::fmt; +use core::ops::{Deref, DerefMut}; macro_rules! impl_from { ($lt:lifetime, $gen:ident, $t:ty, $($var:ident($from:ty),)*) => { diff --git a/crates/common/src/boxvec.rs b/crates/common/src/boxvec.rs index 8687ba7f7f5..3260e76ca87 100644 --- a/crates/common/src/boxvec.rs +++ b/crates/common/src/boxvec.rs @@ -2,13 +2,13 @@ //! An unresizable vector backed by a `Box<[T]>` #![allow(clippy::needless_lifetimes)] - -use std::{ +use alloc::{fmt, slice}; +use core::{ borrow::{Borrow, BorrowMut}, - cmp, fmt, + cmp, mem::{self, MaybeUninit}, ops::{Bound, Deref, DerefMut, RangeBounds}, - ptr, slice, + ptr, }; pub struct BoxVec { @@ -555,7 +555,7 @@ impl Extend for BoxVec { }; let mut iter = iter.into_iter(); loop { - if std::ptr::eq(ptr, end_ptr) { + if core::ptr::eq(ptr, end_ptr) { break; } if let Some(elt) = iter.next() { @@ -693,7 +693,7 @@ impl CapacityError { const CAPERROR: &str = "insufficient capacity"; -impl std::error::Error for CapacityError {} +impl core::error::Error for CapacityError {} impl fmt::Display for CapacityError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/common/src/cformat.rs b/crates/common/src/cformat.rs index b553f0b6b10..24332396fdb 100644 --- a/crates/common/src/cformat.rs +++ b/crates/common/src/cformat.rs @@ -1,15 +1,16 @@ //! Implementation of Printf-Style string formatting //! as per the [Python Docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting). +use alloc::fmt; use bitflags::bitflags; +use core::{ + cmp, + iter::{Enumerate, Peekable}, + str::FromStr, +}; use itertools::Itertools; use malachite_bigint::{BigInt, Sign}; use num_traits::Signed; use rustpython_literal::{float, format::Case}; -use std::{ - cmp, fmt, - iter::{Enumerate, Peekable}, - str::FromStr, -}; use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf}; @@ -785,7 +786,7 @@ impl CFormatStrOrBytes { if !literal.is_empty() { parts.push(( part_index, - CFormatPart::Literal(std::mem::take(&mut literal)), + CFormatPart::Literal(core::mem::take(&mut literal)), )); } let spec = CFormatSpecKeyed::parse(iter).map_err(|err| CFormatError { @@ -816,7 +817,7 @@ impl CFormatStrOrBytes { impl IntoIterator for CFormatStrOrBytes { type Item = (usize, CFormatPart); - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.parts.into_iter() diff --git a/crates/common/src/crt_fd.rs b/crates/common/src/crt_fd.rs index b873ef9c52c..1902a362e32 100644 --- a/crates/common/src/crt_fd.rs +++ b/crates/common/src/crt_fd.rs @@ -1,7 +1,9 @@ //! A module implementing an io type backed by the C runtime's file descriptors, i.e. what's //! returned from libc::open, even on windows. -use std::{cmp, ffi, fmt, io}; +use alloc::fmt; +use core::cmp; +use std::{ffi, io}; #[cfg(not(windows))] use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; diff --git a/crates/common/src/encodings.rs b/crates/common/src/encodings.rs index 39ca2661262..d54581eb9ea 100644 --- a/crates/common/src/encodings.rs +++ b/crates/common/src/encodings.rs @@ -1,4 +1,4 @@ -use std::ops::{self, Range}; +use core::ops::{self, Range}; use num_traits::ToPrimitive; @@ -260,7 +260,7 @@ pub mod errors { use crate::str::UnicodeEscapeCodepoint; use super::*; - use std::fmt::Write; + use core::fmt::Write; pub struct Strict; diff --git a/crates/common/src/fileutils.rs b/crates/common/src/fileutils.rs index a12c1cd82e5..9ed5e77afbb 100644 --- a/crates/common/src/fileutils.rs +++ b/crates/common/src/fileutils.rs @@ -9,7 +9,7 @@ pub use windows::{StatStruct, fstat}; #[cfg(not(windows))] pub fn fstat(fd: crate::crt_fd::Borrowed<'_>) -> std::io::Result { - let mut stat = std::mem::MaybeUninit::uninit(); + let mut stat = core::mem::MaybeUninit::uninit(); unsafe { let ret = libc::fstat(fd.as_raw(), stat.as_mut_ptr()); if ret == -1 { @@ -165,7 +165,7 @@ pub mod windows { } fn file_time_to_time_t_nsec(in_ptr: &FILETIME) -> (libc::time_t, libc::c_int) { - let in_val: i64 = unsafe { std::mem::transmute_copy(in_ptr) }; + let in_val: i64 = unsafe { core::mem::transmute_copy(in_ptr) }; let nsec_out = (in_val % 10_000_000) * 100; // FILETIME is in units of 100 nsec. let time_out = (in_val / 10_000_000) - SECS_BETWEEN_EPOCHS; (time_out, nsec_out as _) @@ -204,7 +204,7 @@ pub mod windows { let st_nlink = info.nNumberOfLinks as i32; let st_ino = if let Some(id_info) = id_info { - let file_id: [u64; 2] = unsafe { std::mem::transmute_copy(&id_info.FileId) }; + let file_id: [u64; 2] = unsafe { core::mem::transmute_copy(&id_info.FileId) }; file_id } else { let ino = ((info.nFileIndexHigh as u64) << 32) + info.nFileIndexLow as u64; @@ -313,7 +313,7 @@ pub mod windows { unsafe { GetProcAddress(module, name.as_bytes_with_nul().as_ptr()) } { Some(unsafe { - std::mem::transmute::< + core::mem::transmute::< unsafe extern "system" fn() -> isize, unsafe extern "system" fn( *const u16, @@ -441,7 +441,7 @@ pub mod windows { // Open a file using std::fs::File and convert to FILE* // Automatically handles path encoding and EINTR retries pub fn fopen(path: &std::path::Path, mode: &str) -> std::io::Result<*mut libc::FILE> { - use std::ffi::CString; + use alloc::ffi::CString; use std::fs::File; // Currently only supports read mode diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index 447ae575f48..1afee519aef 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -1,4 +1,6 @@ // spell-checker:ignore ddfe +use core::ops::Deref; +use core::{cmp, str::FromStr}; use itertools::{Itertools, PeekingNext}; use malachite_base::num::basic::floats::PrimitiveFloat; use malachite_bigint::{BigInt, Sign}; @@ -7,8 +9,6 @@ use num_traits::FromPrimitive; use num_traits::{Signed, cast::ToPrimitive}; use rustpython_literal::float; use rustpython_literal::format::Case; -use std::ops::Deref; -use std::{cmp, str::FromStr}; use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf}; @@ -598,7 +598,7 @@ impl FormatSpec { (Some(_), _) => Err(FormatSpecError::NotAllowed("Sign")), (_, true) => Err(FormatSpecError::NotAllowed("Alternate form (#)")), (_, _) => match num.to_u32() { - Some(n) if n <= 0x10ffff => Ok(std::char::from_u32(n).unwrap().to_string()), + Some(n) if n <= 0x10ffff => Ok(core::char::from_u32(n).unwrap().to_string()), Some(_) | None => Err(FormatSpecError::CodeNotInRange), }, }, diff --git a/crates/common/src/hash.rs b/crates/common/src/hash.rs index dcf424f7ba9..40c428d89e3 100644 --- a/crates/common/src/hash.rs +++ b/crates/common/src/hash.rs @@ -1,7 +1,7 @@ +use core::hash::{BuildHasher, Hash, Hasher}; use malachite_bigint::BigInt; use num_traits::ToPrimitive; use siphasher::sip::SipHasher24; -use std::hash::{BuildHasher, Hash, Hasher}; pub type PyHash = i64; pub type PyUHash = u64; @@ -19,9 +19,9 @@ pub const INF: PyHash = 314_159; pub const NAN: PyHash = 0; pub const IMAG: PyHash = MULTIPLIER; pub const ALGO: &str = "siphash24"; -pub const HASH_BITS: usize = std::mem::size_of::() * 8; +pub const HASH_BITS: usize = core::mem::size_of::() * 8; // SipHasher24 takes 2 u64s as a seed -pub const SEED_BITS: usize = std::mem::size_of::() * 2 * 8; +pub const SEED_BITS: usize = core::mem::size_of::() * 2 * 8; // pub const CUTOFF: usize = 7; @@ -134,7 +134,7 @@ pub fn hash_bigint(value: &BigInt) -> PyHash { Some(i) => mod_int(i), None => (value % MODULUS).to_i64().unwrap_or_else(|| unsafe { // SAFETY: MODULUS < i64::MAX, so value % MODULUS is guaranteed to be in the range of i64 - std::hint::unreachable_unchecked() + core::hint::unreachable_unchecked() }), }; fix_sentinel(ret) diff --git a/crates/common/src/int.rs b/crates/common/src/int.rs index ed09cc01a0a..57696e21fe7 100644 --- a/crates/common/src/int.rs +++ b/crates/common/src/int.rs @@ -7,18 +7,18 @@ pub fn true_div(numerator: &BigInt, denominator: &BigInt) -> f64 { let rational = Rational::from_integers_ref(numerator.into(), denominator.into()); match rational.rounding_into(RoundingMode::Nearest) { // returned value is $t::MAX but still less than the original - (val, std::cmp::Ordering::Less) if val == f64::MAX => f64::INFINITY, + (val, core::cmp::Ordering::Less) if val == f64::MAX => f64::INFINITY, // returned value is $t::MIN but still greater than the original - (val, std::cmp::Ordering::Greater) if val == f64::MIN => f64::NEG_INFINITY, + (val, core::cmp::Ordering::Greater) if val == f64::MIN => f64::NEG_INFINITY, (val, _) => val, } } pub fn float_to_ratio(value: f64) -> Option<(BigInt, BigInt)> { - let sign = match std::cmp::PartialOrd::partial_cmp(&value, &0.0)? { - std::cmp::Ordering::Less => Sign::Minus, - std::cmp::Ordering::Equal => return Some((BigInt::zero(), BigInt::one())), - std::cmp::Ordering::Greater => Sign::Plus, + let sign = match core::cmp::PartialOrd::partial_cmp(&value, &0.0)? { + core::cmp::Ordering::Less => Sign::Minus, + core::cmp::Ordering::Equal => return Some((BigInt::zero(), BigInt::one())), + core::cmp::Ordering::Greater => Sign::Plus, }; Rational::try_from(value).ok().map(|x| { let (numer, denom) = x.into_numerator_and_denominator(); diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index c99ba0286a4..0181562d043 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -2,6 +2,8 @@ #![cfg_attr(all(target_os = "wasi", target_env = "p2"), feature(wasip2))] +extern crate alloc; + #[macro_use] mod macros; pub use macros::*; diff --git a/crates/common/src/linked_list.rs b/crates/common/src/linked_list.rs index 8afc1478e6b..fb2b1260346 100644 --- a/crates/common/src/linked_list.rs +++ b/crates/common/src/linked_list.rs @@ -253,7 +253,7 @@ impl LinkedList { // === rustpython additions === pub fn iter(&self) -> impl Iterator { - std::iter::successors(self.head, |node| unsafe { + core::iter::successors(self.head, |node| unsafe { L::pointers(*node).as_ref().get_next() }) .map(|ptr| unsafe { ptr.as_ref() }) diff --git a/crates/common/src/lock/cell_lock.rs b/crates/common/src/lock/cell_lock.rs index 25a5cfedba1..73d722a8fdb 100644 --- a/crates/common/src/lock/cell_lock.rs +++ b/crates/common/src/lock/cell_lock.rs @@ -1,9 +1,9 @@ // spell-checker:ignore upgradably sharedly +use core::{cell::Cell, num::NonZero}; use lock_api::{ GetThreadId, RawMutex, RawRwLock, RawRwLockDowngrade, RawRwLockRecursive, RawRwLockUpgrade, RawRwLockUpgradeDowngrade, }; -use std::{cell::Cell, num::NonZero}; pub struct RawCellMutex { locked: Cell, diff --git a/crates/common/src/lock/immutable_mutex.rs b/crates/common/src/lock/immutable_mutex.rs index 81c5c93be71..2013cf1c60d 100644 --- a/crates/common/src/lock/immutable_mutex.rs +++ b/crates/common/src/lock/immutable_mutex.rs @@ -1,7 +1,8 @@ #![allow(clippy::needless_lifetimes)] +use alloc::fmt; +use core::{marker::PhantomData, 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 @@ -22,7 +23,7 @@ impl<'a, R: RawMutex, T: ?Sized> MapImmutable<'a, R, T> for MutexGuard<'a, R, T> { let raw = unsafe { MutexGuard::mutex(&s).raw() }; let data = f(&s) as *const U; - std::mem::forget(s); + core::mem::forget(s); ImmutableMappedMutexGuard { raw, data, @@ -38,7 +39,7 @@ impl<'a, R: RawMutex, T: ?Sized> ImmutableMappedMutexGuard<'a, R, T> { { let raw = s.raw; let data = f(&s) as *const U; - std::mem::forget(s); + core::mem::forget(s); ImmutableMappedMutexGuard { raw, data, diff --git a/crates/common/src/lock/thread_mutex.rs b/crates/common/src/lock/thread_mutex.rs index 2949a3c6c14..67ffc89245d 100644 --- a/crates/common/src/lock/thread_mutex.rs +++ b/crates/common/src/lock/thread_mutex.rs @@ -1,14 +1,14 @@ #![allow(clippy::needless_lifetimes)] -use lock_api::{GetThreadId, GuardNoSend, RawMutex}; -use std::{ +use alloc::fmt; +use core::{ cell::UnsafeCell, - fmt, marker::PhantomData, ops::{Deref, DerefMut}, ptr::NonNull, sync::atomic::{AtomicUsize, Ordering}, }; +use lock_api::{GetThreadId, GuardNoSend, RawMutex}; // based off ReentrantMutex from lock_api @@ -174,7 +174,7 @@ impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> ThreadMutexGuard<'a, R, G, T> { ) -> MappedThreadMutexGuard<'a, R, G, U> { let data = f(&mut s).into(); let mu = &s.mu.raw; - std::mem::forget(s); + core::mem::forget(s); MappedThreadMutexGuard { mu, data, @@ -188,7 +188,7 @@ impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> ThreadMutexGuard<'a, R, G, T> { if let Some(data) = f(&mut s) { let data = data.into(); let mu = &s.mu.raw; - std::mem::forget(s); + core::mem::forget(s); Ok(MappedThreadMutexGuard { mu, data, @@ -241,7 +241,7 @@ impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> MappedThreadMutexGuard<'a, R, G ) -> MappedThreadMutexGuard<'a, R, G, U> { let data = f(&mut s).into(); let mu = s.mu; - std::mem::forget(s); + core::mem::forget(s); MappedThreadMutexGuard { mu, data, @@ -255,7 +255,7 @@ impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> MappedThreadMutexGuard<'a, R, G if let Some(data) = f(&mut s) { let data = data.into(); let mu = s.mu; - std::mem::forget(s); + core::mem::forget(s); Ok(MappedThreadMutexGuard { mu, data, diff --git a/crates/common/src/os.rs b/crates/common/src/os.rs index e77a81fd94f..3e09a29210a 100644 --- a/crates/common/src/os.rs +++ b/crates/common/src/os.rs @@ -1,7 +1,8 @@ // spell-checker:disable // TODO: we can move more os-specific bindings/interfaces from stdlib::{os, posix, nt} to here -use std::{io, process::ExitCode, str::Utf8Error}; +use core::str::Utf8Error; +use std::{io, process::ExitCode}; /// Convert exit code to std::process::ExitCode /// diff --git a/crates/common/src/rc.rs b/crates/common/src/rc.rs index 40c7cf97a8d..9e4cca228fd 100644 --- a/crates/common/src/rc.rs +++ b/crates/common/src/rc.rs @@ -1,7 +1,7 @@ #[cfg(not(feature = "threading"))] -use std::rc::Rc; +use alloc::rc::Rc; #[cfg(feature = "threading")] -use std::sync::Arc; +use alloc::sync::Arc; // type aliases instead of new-types because you can't do `fn method(self: PyRc)` with a // newtype; requires the arbitrary_self_types unstable feature diff --git a/crates/common/src/str.rs b/crates/common/src/str.rs index 2d867130edd..155012ed21f 100644 --- a/crates/common/src/str.rs +++ b/crates/common/src/str.rs @@ -4,8 +4,8 @@ use crate::format::CharLen; use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf}; use ascii::{AsciiChar, AsciiStr, AsciiString}; use core::fmt; +use core::ops::{Bound, RangeBounds}; use core::sync::atomic::Ordering::Relaxed; -use std::ops::{Bound, RangeBounds}; #[cfg(not(target_arch = "wasm32"))] #[allow(non_camel_case_types)] @@ -22,7 +22,7 @@ pub enum StrKind { Wtf8, } -impl std::ops::BitOr for StrKind { +impl core::ops::BitOr for StrKind { type Output = Self; fn bitor(self, other: Self) -> Self { @@ -128,7 +128,7 @@ impl From for StrLen { } impl fmt::Debug for StrLen { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let len = self.0.load(Relaxed); if len == usize::MAX { f.write_str("") @@ -262,7 +262,7 @@ impl StrData { pub fn as_str(&self) -> Option<&str> { self.kind .is_utf8() - .then(|| unsafe { std::str::from_utf8_unchecked(self.data.as_bytes()) }) + .then(|| unsafe { core::str::from_utf8_unchecked(self.data.as_bytes()) }) } pub fn as_ascii(&self) -> Option<&AsciiStr> { @@ -282,7 +282,7 @@ impl StrData { PyKindStr::Ascii(unsafe { AsciiStr::from_ascii_unchecked(self.data.as_bytes()) }) } StrKind::Utf8 => { - PyKindStr::Utf8(unsafe { std::str::from_utf8_unchecked(self.data.as_bytes()) }) + PyKindStr::Utf8(unsafe { core::str::from_utf8_unchecked(self.data.as_bytes()) }) } StrKind::Wtf8 => PyKindStr::Wtf8(&self.data), } @@ -327,8 +327,8 @@ impl StrData { } } -impl std::fmt::Display for StrData { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for StrData { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.data.fmt(f) } } @@ -421,7 +421,7 @@ pub fn zfill(bytes: &[u8], width: usize) -> Vec { }; let mut filled = Vec::new(); filled.extend_from_slice(sign); - filled.extend(std::iter::repeat_n(b'0', width - bytes.len())); + filled.extend(core::iter::repeat_n(b'0', width - bytes.len())); filled.extend_from_slice(s); filled } @@ -465,7 +465,8 @@ impl fmt::Display for UnicodeEscapeCodepoint { } pub mod levenshtein { - use std::{cell::RefCell, thread_local}; + use core::cell::RefCell; + use std::thread_local; pub const MOVE_COST: usize = 2; const CASE_COST: usize = 1; @@ -524,9 +525,9 @@ pub mod levenshtein { } if b_end < a_end { - std::mem::swap(&mut a_bytes, &mut b_bytes); - std::mem::swap(&mut a_begin, &mut b_begin); - std::mem::swap(&mut a_end, &mut b_end); + core::mem::swap(&mut a_bytes, &mut b_bytes); + core::mem::swap(&mut a_begin, &mut b_begin); + core::mem::swap(&mut a_end, &mut b_end); } if (b_end - a_end) * MOVE_COST > max_cost { diff --git a/crates/compiler-core/src/bytecode.rs b/crates/compiler-core/src/bytecode.rs index 8df5d9caf6f..5569fa2012b 100644 --- a/crates/compiler-core/src/bytecode.rs +++ b/crates/compiler-core/src/bytecode.rs @@ -5,12 +5,13 @@ use crate::{ marshal::MarshalError, {OneIndexed, SourceLocation}, }; +use alloc::{collections::BTreeSet, fmt}; use bitflags::bitflags; +use core::{hash, marker::PhantomData, mem, num::NonZeroU8, ops::Deref}; use itertools::Itertools; use malachite_bigint::BigInt; use num_complex::Complex64; use rustpython_wtf8::{Wtf8, Wtf8Buf}; -use std::{collections::BTreeSet, fmt, hash, marker::PhantomData, mem, num::NonZeroU8, ops::Deref}; /// Oparg values for [`Instruction::ConvertValue`]. /// @@ -506,7 +507,7 @@ impl Eq for Arg {} impl fmt::Debug for Arg { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Arg<{}>", std::any::type_name::()) + write!(f, "Arg<{}>", core::any::type_name::()) } } @@ -880,7 +881,7 @@ impl From for u8 { #[inline] fn from(ins: Instruction) -> Self { // SAFETY: there's no padding bits - unsafe { std::mem::transmute::(ins) } + unsafe { core::mem::transmute::(ins) } } } @@ -890,7 +891,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 { core::mem::transmute::(value) }) } else { Err(MarshalError::InvalidBytecode) } @@ -1027,7 +1028,7 @@ impl PartialEq for ConstantData { (Boolean { value: a }, Boolean { value: b }) => a == b, (Str { value: a }, Str { value: b }) => a == b, (Bytes { value: a }, Bytes { value: b }) => a == b, - (Code { code: a }, Code { code: b }) => std::ptr::eq(a.as_ref(), b.as_ref()), + (Code { code: a }, Code { code: b }) => core::ptr::eq(a.as_ref(), b.as_ref()), (Tuple { elements: a }, Tuple { elements: b }) => a == b, (None, None) => true, (Ellipsis, Ellipsis) => true, @@ -1053,7 +1054,7 @@ impl hash::Hash for ConstantData { Boolean { value } => value.hash(state), Str { value } => value.hash(state), Bytes { value } => value.hash(state), - Code { code } => std::ptr::hash(code.as_ref(), state), + Code { code } => core::ptr::hash(code.as_ref(), state), Tuple { elements } => elements.hash(state), None => {} Ellipsis => {} diff --git a/crates/compiler-core/src/lib.rs b/crates/compiler-core/src/lib.rs index 08cdc0ec21f..11246f6f44c 100644 --- a/crates/compiler-core/src/lib.rs +++ b/crates/compiler-core/src/lib.rs @@ -1,6 +1,8 @@ #![doc(html_logo_url = "https://raw.githubusercontent.com/RustPython/RustPython/main/logo.png")] #![doc(html_root_url = "https://docs.rs/rustpython-compiler-core/")] +extern crate alloc; + pub mod bytecode; pub mod frozen; pub mod marshal; diff --git a/crates/compiler-core/src/marshal.rs b/crates/compiler-core/src/marshal.rs index 39e48071678..b30894ea065 100644 --- a/crates/compiler-core/src/marshal.rs +++ b/crates/compiler-core/src/marshal.rs @@ -1,8 +1,8 @@ use crate::{OneIndexed, SourceLocation, bytecode::*}; +use core::convert::Infallible; use malachite_bigint::{BigInt, Sign}; use num_complex::Complex64; use rustpython_wtf8::Wtf8; -use std::convert::Infallible; pub const FORMAT_VERSION: u32 = 4; @@ -20,8 +20,8 @@ pub enum MarshalError { BadType, } -impl std::fmt::Display for MarshalError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for MarshalError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::Eof => f.write_str("unexpected end of data"), Self::InvalidBytecode => f.write_str("invalid bytecode"), @@ -32,15 +32,15 @@ impl std::fmt::Display for MarshalError { } } -impl From for MarshalError { - fn from(_: std::str::Utf8Error) -> Self { +impl From for MarshalError { + fn from(_: core::str::Utf8Error) -> Self { Self::InvalidUtf8 } } -impl std::error::Error for MarshalError {} +impl core::error::Error for MarshalError {} -type Result = std::result::Result; +type Result = core::result::Result; #[repr(u8)] enum Type { @@ -119,7 +119,7 @@ pub trait Read { } fn read_str(&mut self, len: u32) -> Result<&str> { - Ok(std::str::from_utf8(self.read_slice(len)?)?) + Ok(core::str::from_utf8(self.read_slice(len)?)?) } fn read_wtf8(&mut self, len: u32) -> Result<&Wtf8> { @@ -147,7 +147,7 @@ pub(crate) trait ReadBorrowed<'a>: Read { fn read_slice_borrow(&mut self, n: u32) -> Result<&'a [u8]>; fn read_str_borrow(&mut self, len: u32) -> Result<&'a str> { - Ok(std::str::from_utf8(self.read_slice_borrow(len)?)?) + Ok(core::str::from_utf8(self.read_slice_borrow(len)?)?) } } diff --git a/crates/compiler-core/src/mode.rs b/crates/compiler-core/src/mode.rs index 35e9e77f590..f2b19d677be 100644 --- a/crates/compiler-core/src/mode.rs +++ b/crates/compiler-core/src/mode.rs @@ -7,7 +7,7 @@ pub enum Mode { BlockExpr, } -impl std::str::FromStr for Mode { +impl core::str::FromStr for Mode { type Err = ModeParseError; // To support `builtins.compile()` `mode` argument @@ -25,8 +25,8 @@ impl std::str::FromStr for Mode { #[derive(Debug)] pub struct ModeParseError; -impl std::fmt::Display for ModeParseError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for ModeParseError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, r#"mode must be "exec", "eval", or "single""#) } } diff --git a/crates/compiler/src/lib.rs b/crates/compiler/src/lib.rs index 84e64f3c27f..7fa695c0c71 100644 --- a/crates/compiler/src/lib.rs +++ b/crates/compiler/src/lib.rs @@ -28,8 +28,8 @@ pub struct ParseError { pub source_path: String, } -impl std::fmt::Display for ParseError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl ::core::fmt::Display for ParseError { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { self.error.fmt(f) } } diff --git a/crates/derive-impl/src/compile_bytecode.rs b/crates/derive-impl/src/compile_bytecode.rs index cdcc89b9984..23c90690dad 100644 --- a/crates/derive-impl/src/compile_bytecode.rs +++ b/crates/derive-impl/src/compile_bytecode.rs @@ -58,11 +58,11 @@ pub trait Compiler { source: &str, mode: Mode, module_name: String, - ) -> Result>; + ) -> Result>; } impl CompilationSource { - fn compile_string D>( + fn compile_string D>( &self, source: &str, mode: Mode, diff --git a/crates/derive-impl/src/from_args.rs b/crates/derive-impl/src/from_args.rs index 4633c9b3aac..667f887e81c 100644 --- a/crates/derive-impl/src/from_args.rs +++ b/crates/derive-impl/src/from_args.rs @@ -18,7 +18,7 @@ enum ParameterKind { impl TryFrom<&Ident> for ParameterKind { type Error = (); - fn try_from(ident: &Ident) -> std::result::Result { + fn try_from(ident: &Ident) -> core::result::Result { Ok(match ident.to_string().as_str() { "positional" => Self::PositionalOnly, "any" => Self::PositionalOrKeyword, @@ -105,12 +105,12 @@ impl ArgAttribute { impl TryFrom<&Field> for ArgAttribute { type Error = syn::Error; - fn try_from(field: &Field) -> std::result::Result { + fn try_from(field: &Field) -> core::result::Result { let mut pyarg_attrs = field .attrs .iter() .filter_map(Self::from_attribute) - .collect::, _>>()?; + .collect::, _>>()?; if pyarg_attrs.len() >= 2 { bail_span!(field, "Multiple pyarg attributes on field") @@ -234,7 +234,7 @@ pub fn impl_from_args(input: DeriveInput) -> Result { fn from_args( vm: &::rustpython_vm::VirtualMachine, args: &mut ::rustpython_vm::function::FuncArgs - ) -> ::std::result::Result { + ) -> ::core::result::Result { Ok(Self { #fields }) } } diff --git a/crates/derive-impl/src/pyclass.rs b/crates/derive-impl/src/pyclass.rs index 55f9c769940..06bbc06cfb2 100644 --- a/crates/derive-impl/src/pyclass.rs +++ b/crates/derive-impl/src/pyclass.rs @@ -4,11 +4,11 @@ use crate::util::{ ItemMeta, ItemMetaInner, ItemNursery, SimpleItemMeta, format_doc, pyclass_ident_and_attrs, pyexception_ident_and_attrs, text_signature, }; +use core::str::FromStr; use proc_macro2::{Delimiter, Group, Span, TokenStream, TokenTree}; use quote::{ToTokens, quote, quote_spanned}; use rustpython_doc::DB; use std::collections::{HashMap, HashSet}; -use std::str::FromStr; use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned}; use syn_ext::ext::*; use syn_ext::types::*; @@ -25,8 +25,8 @@ enum AttrName { Member, } -impl std::fmt::Display for AttrName { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for AttrName { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let s = match self { Self::Method => "pymethod", Self::ClassMethod => "pyclassmethod", @@ -44,7 +44,7 @@ impl std::fmt::Display for AttrName { impl FromStr for AttrName { type Err = String; - fn from_str(s: &str) -> std::result::Result { + fn from_str(s: &str) -> core::result::Result { Ok(match s { "pymethod" => Self::Method, "pyclassmethod" => Self::ClassMethod, @@ -1488,7 +1488,7 @@ impl ItemMeta for SlotItemMeta { fn from_nested(item_ident: Ident, meta_ident: Ident, mut nested: I) -> Result where - I: std::iter::Iterator, + I: core::iter::Iterator, { let meta_map = if let Some(nested_meta) = nested.next() { match nested_meta { diff --git a/crates/derive-impl/src/pymodule.rs b/crates/derive-impl/src/pymodule.rs index 2d5ff7cb0c2..3689ac97fd8 100644 --- a/crates/derive-impl/src/pymodule.rs +++ b/crates/derive-impl/src/pymodule.rs @@ -5,10 +5,11 @@ use crate::util::{ ErrorVec, ItemMeta, ItemNursery, ModuleItemMeta, SimpleItemMeta, format_doc, iter_use_idents, pyclass_ident_and_attrs, text_signature, }; +use core::str::FromStr; use proc_macro2::{Delimiter, Group, TokenStream, TokenTree}; use quote::{ToTokens, quote, quote_spanned}; use rustpython_doc::DB; -use std::{collections::HashSet, str::FromStr}; +use std::collections::HashSet; use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned}; use syn_ext::ext::*; use syn_ext::types::PunctuatedNestedMeta; @@ -22,8 +23,8 @@ enum AttrName { StructSequence, } -impl std::fmt::Display for AttrName { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for AttrName { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let s = match self { Self::Function => "pyfunction", Self::Attr => "pyattr", @@ -38,7 +39,7 @@ impl std::fmt::Display for AttrName { impl FromStr for AttrName { type Err = String; - fn from_str(s: &str) -> std::result::Result { + fn from_str(s: &str) -> core::result::Result { Ok(match s { "pyfunction" => Self::Function, "pyattr" => Self::Attr, diff --git a/crates/derive-impl/src/pytraverse.rs b/crates/derive-impl/src/pytraverse.rs index c5c4bbd2704..c4ec3823298 100644 --- a/crates/derive-impl/src/pytraverse.rs +++ b/crates/derive-impl/src/pytraverse.rs @@ -37,7 +37,7 @@ fn field_to_traverse_code(field: &Field) -> Result { .attrs .iter() .filter_map(pytraverse_arg) - .collect::, _>>()?; + .collect::, _>>()?; let do_trace = if pytraverse_attrs.len() > 1 { bail_span!( field, diff --git a/crates/derive-impl/src/util.rs b/crates/derive-impl/src/util.rs index 379adc65b57..6be1fcdf7ad 100644 --- a/crates/derive-impl/src/util.rs +++ b/crates/derive-impl/src/util.rs @@ -97,7 +97,7 @@ pub(crate) struct ContentItemInner { } pub(crate) trait ContentItem { - type AttrName: std::str::FromStr + std::fmt::Display; + type AttrName: core::str::FromStr + core::fmt::Display; fn inner(&self) -> &ContentItemInner; fn index(&self) -> usize { @@ -125,7 +125,7 @@ impl ItemMetaInner { allowed_names: &[&'static str], ) -> Result where - I: std::iter::Iterator, + I: core::iter::Iterator, { let (meta_map, lits) = nested.into_unique_map_and_lits(|path| { if let Some(ident) = path.get_ident() { @@ -243,7 +243,7 @@ impl ItemMetaInner { pub fn _optional_list( &self, key: &str, - ) -> Result>> { + ) -> Result>> { let value = if let Some((_, meta)) = self.meta_map.get(key) { let Meta::List(MetaList { path: _, nested, .. @@ -269,7 +269,7 @@ pub(crate) trait ItemMeta: Sized { fn from_nested(item_ident: Ident, meta_ident: Ident, nested: I) -> Result where - I: std::iter::Iterator, + I: core::iter::Iterator, { Ok(Self::from_inner(ItemMetaInner::from_nested( item_ident, @@ -529,7 +529,7 @@ impl ExceptionItemMeta { } } -impl std::ops::Deref for ExceptionItemMeta { +impl core::ops::Deref for ExceptionItemMeta { type Target = ClassItemMeta; fn deref(&self) -> &Self::Target { &self.0 diff --git a/crates/derive/src/lib.rs b/crates/derive/src/lib.rs index 655ad3b4c9e..5a3ff84c63a 100644 --- a/crates/derive/src/lib.rs +++ b/crates/derive/src/lib.rs @@ -274,7 +274,7 @@ impl derive_impl::Compiler for Compiler { source: &str, mode: rustpython_compiler::Mode, module_name: String, - ) -> Result> { + ) -> Result> { use rustpython_compiler::{CompileOpts, compile}; Ok(compile(source, mode, &module_name, CompileOpts::default())?) } diff --git a/crates/jit/src/lib.rs b/crates/jit/src/lib.rs index 65ef87a62f6..1e278617661 100644 --- a/crates/jit/src/lib.rs +++ b/crates/jit/src/lib.rs @@ -1,11 +1,14 @@ mod instructions; +extern crate alloc; + +use alloc::fmt; +use core::mem::ManuallyDrop; use cranelift::prelude::*; use cranelift_jit::{JITBuilder, JITModule}; use cranelift_module::{FuncId, Linkage, Module, ModuleError}; use instructions::FunctionCompiler; use rustpython_compiler_core::bytecode; -use std::{fmt, mem::ManuallyDrop}; #[derive(Debug, thiserror::Error)] #[non_exhaustive] diff --git a/crates/literal/src/escape.rs b/crates/literal/src/escape.rs index 6bdd94e9860..72ceaf60d5b 100644 --- a/crates/literal/src/escape.rs +++ b/crates/literal/src/escape.rs @@ -55,9 +55,9 @@ pub unsafe trait Escape { /// # Safety /// /// This string must only contain printable characters. - unsafe fn write_source(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result; - fn write_body_slow(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result; - fn write_body(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result { + unsafe fn write_source(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result; + fn write_body_slow(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result; + fn write_body(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result { if self.changed() { self.write_body_slow(formatter) } else { @@ -117,7 +117,7 @@ impl<'a> UnicodeEscape<'a> { pub struct StrRepr<'r, 'a>(&'r UnicodeEscape<'a>); impl StrRepr<'_, '_> { - pub fn write(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result { + pub fn write(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result { let quote = self.0.layout().quote.to_char(); formatter.write_char(quote)?; self.0.write_body(formatter)?; @@ -131,8 +131,8 @@ impl StrRepr<'_, '_> { } } -impl std::fmt::Display for StrRepr<'_, '_> { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for StrRepr<'_, '_> { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.write(formatter) } } @@ -217,7 +217,7 @@ impl UnicodeEscape<'_> { ch: CodePoint, quote: Quote, formatter: &mut impl std::fmt::Write, - ) -> std::fmt::Result { + ) -> core::fmt::Result { let Some(ch) = ch.to_char() else { return write!(formatter, "\\u{:04x}", ch.to_u32()); }; @@ -260,7 +260,7 @@ unsafe impl Escape for UnicodeEscape<'_> { &self.layout } - unsafe fn write_source(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result { + unsafe fn write_source(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result { formatter.write_str(unsafe { // SAFETY: this function must be called only when source is printable characters (i.e. no surrogates) std::str::from_utf8_unchecked(self.source.as_bytes()) @@ -268,7 +268,7 @@ unsafe impl Escape for UnicodeEscape<'_> { } #[cold] - fn write_body_slow(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result { + fn write_body_slow(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result { for ch in self.source.code_points() { Self::write_char(ch, self.layout().quote, formatter)?; } @@ -378,7 +378,7 @@ impl AsciiEscape<'_> { } } - fn write_char(ch: u8, quote: Quote, formatter: &mut impl std::fmt::Write) -> std::fmt::Result { + fn write_char(ch: u8, quote: Quote, formatter: &mut impl std::fmt::Write) -> core::fmt::Result { match ch { b'\t' => formatter.write_str("\\t"), b'\n' => formatter.write_str("\\n"), @@ -404,7 +404,7 @@ unsafe impl Escape for AsciiEscape<'_> { &self.layout } - unsafe fn write_source(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result { + unsafe fn write_source(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result { formatter.write_str(unsafe { // SAFETY: this function must be called only when source is printable ascii characters std::str::from_utf8_unchecked(self.source) @@ -412,7 +412,7 @@ unsafe impl Escape for AsciiEscape<'_> { } #[cold] - fn write_body_slow(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result { + fn write_body_slow(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result { for ch in self.source { Self::write_char(*ch, self.layout().quote, formatter)?; } @@ -423,7 +423,7 @@ unsafe impl Escape for AsciiEscape<'_> { pub struct BytesRepr<'r, 'a>(&'r AsciiEscape<'a>); impl BytesRepr<'_, '_> { - pub fn write(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result { + pub fn write(&self, formatter: &mut impl std::fmt::Write) -> core::fmt::Result { let quote = self.0.layout().quote.to_char(); formatter.write_char('b')?; formatter.write_char(quote)?; @@ -438,8 +438,8 @@ impl BytesRepr<'_, '_> { } } -impl std::fmt::Display for BytesRepr<'_, '_> { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for BytesRepr<'_, '_> { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.write(formatter) } } diff --git a/crates/literal/src/float.rs b/crates/literal/src/float.rs index e2bc54a8f1b..4d0d65cbb34 100644 --- a/crates/literal/src/float.rs +++ b/crates/literal/src/float.rs @@ -55,7 +55,7 @@ pub fn format_fixed(precision: usize, magnitude: f64, case: Case, alternate_form match magnitude { magnitude if magnitude.is_finite() => { let point = decimal_point_or_empty(precision, alternate_form); - let precision = std::cmp::min(precision, u16::MAX as usize); + let precision = core::cmp::min(precision, u16::MAX as usize); format!("{magnitude:.precision$}{point}") } magnitude if magnitude.is_nan() => format_nan(case), diff --git a/crates/sre_engine/src/engine.rs b/crates/sre_engine/src/engine.rs index 9cc2e4788a5..f1f25a2d920 100644 --- a/crates/sre_engine/src/engine.rs +++ b/crates/sre_engine/src/engine.rs @@ -6,8 +6,8 @@ use crate::string::{ }; use super::{MAXREPEAT, SreAtCode, SreCatCode, SreInfo, SreOpcode, StrDrive, StringCursor}; +use core::{convert::TryFrom, ptr::null}; use optional::Optioned; -use std::{convert::TryFrom, ptr::null}; #[derive(Debug, Clone, Copy)] pub struct Request<'a, S> { @@ -27,8 +27,8 @@ impl<'a, S: StrDrive> Request<'a, S> { pattern_codes: &'a [u32], match_all: bool, ) -> Self { - let end = std::cmp::min(end, string.count()); - let start = std::cmp::min(start, end); + let end = core::cmp::min(end, string.count()); + let start = core::cmp::min(start, end); Self { string, @@ -1332,7 +1332,7 @@ fn _count( ctx: &mut MatchContext, max_count: usize, ) -> usize { - let max_count = std::cmp::min(max_count, ctx.remaining_chars(req)); + let max_count = core::cmp::min(max_count, ctx.remaining_chars(req)); let end = ctx.cursor.position + max_count; let opcode = SreOpcode::try_from(ctx.peek_code(req, 0)).unwrap(); diff --git a/crates/sre_engine/src/string.rs b/crates/sre_engine/src/string.rs index 0d3325b6a1d..489819bfb3e 100644 --- a/crates/sre_engine/src/string.rs +++ b/crates/sre_engine/src/string.rs @@ -9,7 +9,7 @@ pub struct StringCursor { impl Default for StringCursor { fn default() -> Self { Self { - ptr: std::ptr::null(), + ptr: core::ptr::null(), position: 0, } } diff --git a/crates/stdlib/src/array.rs b/crates/stdlib/src/array.rs index b51bc02d3fb..b7a6fbd8b4f 100644 --- a/crates/stdlib/src/array.rs +++ b/crates/stdlib/src/array.rs @@ -68,11 +68,12 @@ mod array { }, }, }; + use alloc::fmt; + use core::cmp::Ordering; use itertools::Itertools; use num_traits::ToPrimitive; use rustpython_common::wtf8::{CodePoint, Wtf8, Wtf8Buf}; - use std::{cmp::Ordering, fmt, os::raw}; - + use std::os::raw; macro_rules! def_array_enum { ($(($n:ident, $t:ty, $c:literal, $scode:literal)),*$(,)?) => { #[derive(Debug, Clone)] @@ -104,14 +105,14 @@ mod array { const fn itemsize_of_typecode(c: char) -> Option { match c { - $($c => Some(std::mem::size_of::<$t>()),)* + $($c => Some(core::mem::size_of::<$t>()),)* _ => None, } } const fn itemsize(&self) -> usize { match self { - $(ArrayContentType::$n(_) => std::mem::size_of::<$t>(),)* + $(ArrayContentType::$n(_) => core::mem::size_of::<$t>(),)* } } @@ -201,10 +202,10 @@ mod array { if v.is_empty() { // safe because every configuration of bytes for the types we // support are valid - let b = std::mem::ManuallyDrop::new(b); + let b = core::mem::ManuallyDrop::new(b); let ptr = b.as_ptr() as *mut $t; - let len = b.len() / std::mem::size_of::<$t>(); - let capacity = b.capacity() / std::mem::size_of::<$t>(); + let len = b.len() / core::mem::size_of::<$t>(); + let capacity = b.capacity() / core::mem::size_of::<$t>(); *v = unsafe { Vec::from_raw_parts(ptr, len, capacity) }; } else { self.frombytes(&b); @@ -220,8 +221,8 @@ mod array { // support are valid if b.len() > 0 { let ptr = b.as_ptr() as *const $t; - let ptr_len = b.len() / std::mem::size_of::<$t>(); - let slice = unsafe { std::slice::from_raw_parts(ptr, ptr_len) }; + let ptr_len = b.len() / core::mem::size_of::<$t>(); + let slice = unsafe { core::slice::from_raw_parts(ptr, ptr_len) }; v.extend_from_slice(slice); } })* @@ -249,8 +250,8 @@ mod array { $(ArrayContentType::$n(v) => { // safe because we're just reading memory as bytes let ptr = v.as_ptr() as *const u8; - let ptr_len = v.len() * std::mem::size_of::<$t>(); - unsafe { std::slice::from_raw_parts(ptr, ptr_len) } + let ptr_len = v.len() * core::mem::size_of::<$t>(); + unsafe { core::slice::from_raw_parts(ptr, ptr_len) } })* } } @@ -260,8 +261,8 @@ mod array { $(ArrayContentType::$n(v) => { // safe because we're just reading memory as bytes let ptr = v.as_ptr() as *mut u8; - let ptr_len = v.len() * std::mem::size_of::<$t>(); - unsafe { std::slice::from_raw_parts_mut(ptr, ptr_len) } + let ptr_len = v.len() * core::mem::size_of::<$t>(); + unsafe { core::slice::from_raw_parts_mut(ptr, ptr_len) } })* } } @@ -785,18 +786,18 @@ mod array { if item_size == 2 { // safe because every configuration of bytes for the types we support are valid let utf16 = unsafe { - std::slice::from_raw_parts( + core::slice::from_raw_parts( bytes.as_ptr() as *const u16, - bytes.len() / std::mem::size_of::(), + bytes.len() / core::mem::size_of::(), ) }; Ok(Wtf8Buf::from_wide(utf16)) } else { // safe because every configuration of bytes for the types we support are valid let chars = unsafe { - std::slice::from_raw_parts( + core::slice::from_raw_parts( bytes.as_ptr() as *const u32, - bytes.len() / std::mem::size_of::(), + bytes.len() / core::mem::size_of::(), ) }; chars @@ -1516,7 +1517,7 @@ mod array { impl MachineFormatCode { fn from_typecode(code: char) -> Option { - use std::mem::size_of; + use core::mem::size_of; let signed = code.is_ascii_uppercase(); let big_endian = cfg!(target_endian = "big"); let int_size = match code { @@ -1590,7 +1591,7 @@ mod array { macro_rules! chunk_to_obj { ($BYTE:ident, $TY:ty, $BIG_ENDIAN:ident) => {{ - let b = <[u8; ::std::mem::size_of::<$TY>()]>::try_from($BYTE).unwrap(); + let b = <[u8; ::core::mem::size_of::<$TY>()]>::try_from($BYTE).unwrap(); if $BIG_ENDIAN { <$TY>::from_be_bytes(b) } else { @@ -1601,7 +1602,7 @@ mod array { chunk_to_obj!($BYTE, $TY, $BIG_ENDIAN).to_pyobject($VM) }; ($VM:ident, $BYTE:ident, $SIGNED_TY:ty, $UNSIGNED_TY:ty, $SIGNED:ident, $BIG_ENDIAN:ident) => {{ - let b = <[u8; ::std::mem::size_of::<$SIGNED_TY>()]>::try_from($BYTE).unwrap(); + let b = <[u8; ::core::mem::size_of::<$SIGNED_TY>()]>::try_from($BYTE).unwrap(); match ($SIGNED, $BIG_ENDIAN) { (false, false) => <$UNSIGNED_TY>::from_le_bytes(b).to_pyobject($VM), (false, true) => <$UNSIGNED_TY>::from_be_bytes(b).to_pyobject($VM), diff --git a/crates/stdlib/src/binascii.rs b/crates/stdlib/src/binascii.rs index a2316d3c204..671d1d9e253 100644 --- a/crates/stdlib/src/binascii.rs +++ b/crates/stdlib/src/binascii.rs @@ -359,7 +359,7 @@ mod decl { } _ => unsafe { // quad_pos is only assigned in this match statement to constants - std::hint::unreachable_unchecked() + core::hint::unreachable_unchecked() }, } } diff --git a/crates/stdlib/src/bz2.rs b/crates/stdlib/src/bz2.rs index a2a40953cff..93142e92a68 100644 --- a/crates/stdlib/src/bz2.rs +++ b/crates/stdlib/src/bz2.rs @@ -15,9 +15,10 @@ mod _bz2 { object::PyResult, types::Constructor, }; + use alloc::fmt; use bzip2::{Decompress, Status, write::BzEncoder}; use rustpython_vm::convert::ToPyException; - use std::{fmt, io::Write}; + use std::io::Write; const BUFSIZ: usize = 8192; diff --git a/crates/stdlib/src/cmath.rs b/crates/stdlib/src/cmath.rs index e5d1d55a578..7f975e41719 100644 --- a/crates/stdlib/src/cmath.rs +++ b/crates/stdlib/src/cmath.rs @@ -11,7 +11,7 @@ mod cmath { // Constants #[pyattr] - use std::f64::consts::{E as e, PI as pi, TAU as tau}; + use core::f64::consts::{E as e, PI as pi, TAU as tau}; #[pyattr(name = "inf")] const INF: f64 = f64::INFINITY; #[pyattr(name = "nan")] @@ -93,7 +93,7 @@ mod cmath { z.log( base.into_option() .map(|base| base.re) - .unwrap_or(std::f64::consts::E), + .unwrap_or(core::f64::consts::E), ) } diff --git a/crates/stdlib/src/compression.rs b/crates/stdlib/src/compression.rs index 7f4e3432eab..a857b4e53de 100644 --- a/crates/stdlib/src/compression.rs +++ b/crates/stdlib/src/compression.rs @@ -107,7 +107,7 @@ impl<'a> Chunker<'a> { pub fn advance(&mut self, consumed: usize) { self.data1 = &self.data1[consumed..]; if self.data1.is_empty() { - self.data1 = std::mem::take(&mut self.data2); + self.data1 = core::mem::take(&mut self.data2); } } } @@ -140,7 +140,7 @@ pub fn _decompress_chunks( let chunk = data.chunk(); let flush = calc_flush(chunk.len() == data.len()); loop { - let additional = std::cmp::min(bufsize, max_length - buf.capacity()); + let additional = core::cmp::min(bufsize, max_length - buf.capacity()); if additional == 0 { return Ok((buf, false)); } diff --git a/crates/stdlib/src/contextvars.rs b/crates/stdlib/src/contextvars.rs index f88ce398c1c..731f5d11e0b 100644 --- a/crates/stdlib/src/contextvars.rs +++ b/crates/stdlib/src/contextvars.rs @@ -1,6 +1,6 @@ use crate::vm::{PyRef, VirtualMachine, builtins::PyModule, class::StaticType}; use _contextvars::PyContext; -use std::cell::RefCell; +use core::cell::RefCell; pub(crate) fn make_module(vm: &VirtualMachine) -> PyRef { let module = _contextvars::make_module(vm); @@ -31,13 +31,13 @@ mod _contextvars { protocol::{PyMappingMethods, PySequenceMethods}, types::{AsMapping, AsSequence, Constructor, Hashable, Representable}, }; - use crossbeam_utils::atomic::AtomicCell; - use indexmap::IndexMap; - use std::sync::LazyLock; - use std::{ + use core::{ cell::{Cell, RefCell, UnsafeCell}, sync::atomic::Ordering, }; + use crossbeam_utils::atomic::AtomicCell; + use indexmap::IndexMap; + use std::sync::LazyLock; // TODO: Real hamt implementation type Hamt = IndexMap, PyObjectRef, ahash::RandomState>; @@ -90,11 +90,11 @@ mod _contextvars { } } - fn borrow_vars(&self) -> impl std::ops::Deref + '_ { + fn borrow_vars(&self) -> impl core::ops::Deref + '_ { self.inner.vars.hamt.borrow() } - fn borrow_vars_mut(&self) -> impl std::ops::DerefMut + '_ { + fn borrow_vars_mut(&self) -> impl core::ops::DerefMut + '_ { self.inner.vars.hamt.borrow_mut() } @@ -293,13 +293,13 @@ mod _contextvars { #[pytraverse(skip)] cached: AtomicCell>, #[pytraverse(skip)] - cached_id: std::sync::atomic::AtomicUsize, // cached_tsid in CPython + cached_id: core::sync::atomic::AtomicUsize, // cached_tsid in CPython #[pytraverse(skip)] hash: UnsafeCell, } - impl std::fmt::Debug for ContextVar { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for ContextVar { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("ContextVar").finish() } } @@ -308,7 +308,7 @@ mod _contextvars { impl PartialEq for ContextVar { fn eq(&self, other: &Self) -> bool { - std::ptr::eq(self, other) + core::ptr::eq(self, other) } } impl Eq for ContextVar {} @@ -512,9 +512,9 @@ mod _contextvars { } } - impl std::hash::Hash for ContextVar { + impl core::hash::Hash for ContextVar { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { unsafe { *self.hash.get() }.hash(state) } } diff --git a/crates/stdlib/src/csv.rs b/crates/stdlib/src/csv.rs index a62594a9f1b..4f6cbd76828 100644 --- a/crates/stdlib/src/csv.rs +++ b/crates/stdlib/src/csv.rs @@ -12,12 +12,13 @@ mod _csv { raise_if_stop, types::{Constructor, IterNext, Iterable, SelfIter}, }; + use alloc::fmt; use csv_core::Terminator; use itertools::{self, Itertools}; use parking_lot::Mutex; use rustpython_vm::match_class; + use std::collections::HashMap; use std::sync::LazyLock; - use std::{collections::HashMap, fmt}; #[pyattr] const QUOTE_MINIMAL: i32 = QuoteStyle::Minimal as i32; @@ -1006,7 +1007,7 @@ mod _csv { return Err(new_csv_error(vm, "filed too long to read".to_string())); } prev_end = end; - let s = std::str::from_utf8(&buffer[range.clone()]) + let s = core::str::from_utf8(&buffer[range.clone()]) // not sure if this is possible - the input was all strings .map_err(|_e| vm.new_unicode_decode_error("csv not utf8"))?; // Rustpython TODO! @@ -1116,7 +1117,7 @@ mod _csv { loop { handle_res!(writer.terminator(&mut buffer[buffer_offset..])); } - let s = std::str::from_utf8(&buffer[..buffer_offset]) + let s = core::str::from_utf8(&buffer[..buffer_offset]) .map_err(|_| vm.new_unicode_decode_error("csv not utf8"))?; self.write.call((s,), vm) diff --git a/crates/stdlib/src/faulthandler.rs b/crates/stdlib/src/faulthandler.rs index f45c9909c6f..eba5643b866 100644 --- a/crates/stdlib/src/faulthandler.rs +++ b/crates/stdlib/src/faulthandler.rs @@ -7,13 +7,13 @@ mod decl { PyObjectRef, PyResult, VirtualMachine, builtins::PyFloat, frame::Frame, function::OptionalArg, py_io::Write, }; + use alloc::sync::Arc; + use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; + use core::time::Duration; use parking_lot::{Condvar, Mutex}; #[cfg(any(unix, windows))] use rustpython_common::os::{get_errno, set_errno}; - use std::sync::Arc; - use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; use std::thread; - use std::time::Duration; /// fault_handler_t #[cfg(unix)] @@ -40,7 +40,7 @@ mod decl { enabled: false, name, // SAFETY: sigaction is a C struct that can be zero-initialized - previous: unsafe { std::mem::zeroed() }, + previous: unsafe { core::mem::zeroed() }, } } } @@ -144,7 +144,8 @@ mod decl { static mut FRAME_SNAPSHOTS: [FrameSnapshot; MAX_SNAPSHOT_FRAMES] = [FrameSnapshot::EMPTY; MAX_SNAPSHOT_FRAMES]; #[cfg(any(unix, windows))] - static SNAPSHOT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + static SNAPSHOT_COUNT: core::sync::atomic::AtomicUsize = + core::sync::atomic::AtomicUsize::new(0); // Signal-safe output functions @@ -240,7 +241,7 @@ mod decl { } let thread_id = current_thread_id(); // Use appropriate width based on platform pointer size - dump_hexadecimal(fd, thread_id, std::mem::size_of::() * 2); + dump_hexadecimal(fd, thread_id, core::mem::size_of::() * 2); puts(fd, " (most recent call first):\n"); } @@ -429,7 +430,7 @@ mod decl { } handler.enabled = false; unsafe { - libc::sigaction(handler.signum, &handler.previous, std::ptr::null_mut()); + libc::sigaction(handler.signum, &handler.previous, core::ptr::null_mut()); } } @@ -549,7 +550,7 @@ mod decl { continue; } - let mut action: libc::sigaction = std::mem::zeroed(); + let mut action: libc::sigaction = core::mem::zeroed(); action.sa_sigaction = faulthandler_fatal_error as libc::sighandler_t; // SA_NODEFER flag action.sa_flags = libc::SA_NODEFER; @@ -1051,8 +1052,8 @@ mod decl { #[cfg(not(target_arch = "wasm32"))] unsafe { suppress_crash_report(); - let ptr: *const i32 = std::ptr::null(); - std::ptr::read_volatile(ptr); + let ptr: *const i32 = core::ptr::null(); + core::ptr::read_volatile(ptr); } } @@ -1132,7 +1133,7 @@ mod decl { panic!("Fatal Python error: in new thread"); }); // Wait a bit for the thread to panic - std::thread::sleep(std::time::Duration::from_secs(1)); + std::thread::sleep(core::time::Duration::from_secs(1)); } } @@ -1203,7 +1204,7 @@ mod decl { suppress_crash_report(); unsafe { - RaiseException(args.code, args.flags, 0, std::ptr::null()); + RaiseException(args.code, args.flags, 0, core::ptr::null()); } } } diff --git a/crates/stdlib/src/fcntl.rs b/crates/stdlib/src/fcntl.rs index dc6a0b8171e..822faeeedaa 100644 --- a/crates/stdlib/src/fcntl.rs +++ b/crates/stdlib/src/fcntl.rs @@ -173,7 +173,7 @@ mod fcntl { }; } - let mut l: libc::flock = unsafe { std::mem::zeroed() }; + let mut l: libc::flock = unsafe { core::mem::zeroed() }; l.l_type = if cmd == libc::LOCK_UN { try_into_l_type!(libc::F_UNLCK) } else if (cmd & libc::LOCK_SH) != 0 { diff --git a/crates/stdlib/src/grp.rs b/crates/stdlib/src/grp.rs index 4664d5fc575..9f7e4195509 100644 --- a/crates/stdlib/src/grp.rs +++ b/crates/stdlib/src/grp.rs @@ -10,8 +10,8 @@ mod grp { exceptions, types::PyStructSequence, }; + use core::ptr::NonNull; use nix::unistd; - use std::ptr::NonNull; #[pystruct_sequence_data] struct GroupData { @@ -30,7 +30,7 @@ mod grp { impl GroupData { fn from_unistd_group(group: unistd::Group, vm: &VirtualMachine) -> Self { - let cstr_lossy = |s: std::ffi::CString| { + let cstr_lossy = |s: alloc::ffi::CString| { s.into_string() .unwrap_or_else(|e| e.into_cstring().to_string_lossy().into_owned()) }; diff --git a/crates/stdlib/src/hashlib.rs b/crates/stdlib/src/hashlib.rs index bfde58f43f7..2da47ceb740 100644 --- a/crates/stdlib/src/hashlib.rs +++ b/crates/stdlib/src/hashlib.rs @@ -97,8 +97,8 @@ pub mod _hashlib { pub ctx: PyRwLock, } - impl std::fmt::Debug for PyHasher { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for PyHasher { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "HASH {}", self.name) } } @@ -170,8 +170,8 @@ pub mod _hashlib { ctx: PyRwLock, } - impl std::fmt::Debug for PyHasherXof { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for PyHasherXof { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "HASHXOF {}", self.name) } } diff --git a/crates/stdlib/src/json.rs b/crates/stdlib/src/json.rs index eb6ed3a5f64..a3fd7972126 100644 --- a/crates/stdlib/src/json.rs +++ b/crates/stdlib/src/json.rs @@ -12,9 +12,9 @@ mod _json { protocol::PyIterReturn, types::{Callable, Constructor}, }; + use core::str::FromStr; use malachite_bigint::BigInt; use rustpython_common::wtf8::Wtf8Buf; - use std::str::FromStr; #[pyattr(name = "make_scanner")] #[pyclass(name = "Scanner", traverse)] @@ -216,7 +216,7 @@ mod _json { let mut buf = Vec::::with_capacity(s.len() + 2); machinery::write_json_string(s, ascii_only, &mut buf) // SAFETY: writing to a vec can't fail - .unwrap_or_else(|_| unsafe { std::hint::unreachable_unchecked() }); + .unwrap_or_else(|_| unsafe { core::hint::unreachable_unchecked() }); // SAFETY: we only output valid utf8 from write_json_string unsafe { String::from_utf8_unchecked(buf) } } diff --git a/crates/stdlib/src/lib.rs b/crates/stdlib/src/lib.rs index 4b463e09c73..6b7796c8bad 100644 --- a/crates/stdlib/src/lib.rs +++ b/crates/stdlib/src/lib.rs @@ -6,6 +6,7 @@ #[macro_use] extern crate rustpython_derive; +extern crate alloc; pub mod array; mod binascii; @@ -103,7 +104,7 @@ use rustpython_common as common; use rustpython_vm as vm; use crate::vm::{builtins, stdlib::StdlibInitFunc}; -use std::borrow::Cow; +use alloc::borrow::Cow; pub fn get_module_inits() -> impl Iterator, StdlibInitFunc)> { macro_rules! modules { diff --git a/crates/stdlib/src/locale.rs b/crates/stdlib/src/locale.rs index 6cca8b9123b..c65f861d208 100644 --- a/crates/stdlib/src/locale.rs +++ b/crates/stdlib/src/locale.rs @@ -41,16 +41,14 @@ use libc::localeconv; #[pymodule] mod _locale { + use alloc::ffi::CString; + use core::{ffi::CStr, ptr}; use rustpython_vm::{ PyObjectRef, PyResult, VirtualMachine, builtins::{PyDictRef, PyIntRef, PyListRef, PyStrRef, PyTypeRef}, convert::ToPyException, function::OptionalArg, }; - use std::{ - ffi::{CStr, CString}, - ptr, - }; #[cfg(all( unix, diff --git a/crates/stdlib/src/lzma.rs b/crates/stdlib/src/lzma.rs index 855a5eae562..b18ac3ee69a 100644 --- a/crates/stdlib/src/lzma.rs +++ b/crates/stdlib/src/lzma.rs @@ -8,6 +8,7 @@ mod _lzma { CompressFlushKind, CompressState, CompressStatusKind, Compressor, DecompressArgs, DecompressError, DecompressState, DecompressStatus, Decompressor, }; + use alloc::fmt; #[pyattr] use lzma_sys::{ LZMA_CHECK_CRC32 as CHECK_CRC32, LZMA_CHECK_CRC64 as CHECK_CRC64, @@ -38,7 +39,6 @@ mod _lzma { use rustpython_vm::function::ArgBytesLike; use rustpython_vm::types::Constructor; use rustpython_vm::{Py, PyObjectRef, PyPayload, PyResult, VirtualMachine}; - use std::fmt; use xz2::stream::{Action, Check, Error, Filters, LzmaOptions, Status, Stream}; #[cfg(windows)] diff --git a/crates/stdlib/src/math.rs b/crates/stdlib/src/math.rs index 62b0ef73ad3..6e139530804 100644 --- a/crates/stdlib/src/math.rs +++ b/crates/stdlib/src/math.rs @@ -10,15 +10,15 @@ mod math { function::{ArgIndex, ArgIntoFloat, ArgIterable, Either, OptionalArg, PosArgs}, identifier, }; + use core::cmp::Ordering; use itertools::Itertools; use malachite_bigint::BigInt; use num_traits::{One, Signed, ToPrimitive, Zero}; use rustpython_common::{float_ops, int::true_div}; - use std::cmp::Ordering; // Constants #[pyattr] - use std::f64::consts::{E as e, PI as pi, TAU as tau}; + use core::f64::consts::{E as e, PI as pi, TAU as tau}; use super::pymath_error_to_exception; #[pyattr(name = "inf")] @@ -136,7 +136,7 @@ mod math { #[pyfunction] fn log(x: PyObjectRef, base: OptionalArg, vm: &VirtualMachine) -> PyResult { - let base = base.map(|b| *b).unwrap_or(std::f64::consts::E); + let base = base.map(|b| *b).unwrap_or(core::f64::consts::E); if base.is_sign_negative() { return Err(vm.new_value_error("math domain error")); } @@ -359,9 +359,9 @@ mod math { .iter() .copied() .map(|x| (x / scale).powi(2)) - .chain(std::iter::once(-norm * norm)) + .chain(core::iter::once(-norm * norm)) // Pairwise summation of floats gives less rounding error than a naive sum. - .tree_reduce(std::ops::Add::add) + .tree_reduce(core::ops::Add::add) .expect("expected at least 1 element"); norm = norm + correction / (2.0 * norm); } @@ -424,12 +424,12 @@ mod math { #[pyfunction] fn degrees(x: ArgIntoFloat) -> f64 { - *x * (180.0 / std::f64::consts::PI) + *x * (180.0 / core::f64::consts::PI) } #[pyfunction] fn radians(x: ArgIntoFloat) -> f64 { - *x * (std::f64::consts::PI / 180.0) + *x * (core::f64::consts::PI / 180.0) } // Hyperbolic functions: @@ -684,7 +684,7 @@ mod math { for j in 0..partials.len() { let mut y: f64 = partials[j]; if x.abs() < y.abs() { - std::mem::swap(&mut x, &mut y); + core::mem::swap(&mut x, &mut y); } // Rounded `x+y` is stored in `hi` with round-off stored in // `lo`. Together `hi+lo` are exactly equal to `x+y`. diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index f1e2c2a039d..b520eb2a1a7 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -21,11 +21,11 @@ mod mmap { sliceable::{SaturatedSlice, SequenceIndex, SequenceIndexOp}, types::{AsBuffer, AsMapping, AsSequence, Constructor, Representable}, }; + use core::ops::{Deref, DerefMut}; use crossbeam_utils::atomic::AtomicCell; use memmap2::{Mmap, MmapMut, MmapOptions}; use num_traits::Signed; use std::io::{self, Write}; - use std::ops::{Deref, DerefMut}; #[cfg(unix)] use nix::{sys::stat::fstat, unistd}; @@ -1057,7 +1057,7 @@ mod mmap { // 3. Replace the old mmap let old_size = self.size.load(); - let copy_size = std::cmp::min(old_size, newsize); + let copy_size = core::cmp::min(old_size, newsize); // Create new anonymous mmap let mut new_mmap_opts = MmapOptions::new(); diff --git a/crates/stdlib/src/opcode.rs b/crates/stdlib/src/opcode.rs index c355b59df91..bd4b9aa750a 100644 --- a/crates/stdlib/src/opcode.rs +++ b/crates/stdlib/src/opcode.rs @@ -8,7 +8,7 @@ mod opcode { bytecode::Instruction, match_class, }; - use std::ops::Deref; + use core::ops::Deref; struct Opcode(Instruction); diff --git a/crates/stdlib/src/openssl.rs b/crates/stdlib/src/openssl.rs index d352d15a614..38103a9ab05 100644 --- a/crates/stdlib/src/openssl.rs +++ b/crates/stdlib/src/openssl.rs @@ -522,10 +522,10 @@ mod _ssl { // Thread-local storage for VirtualMachine pointer during handshake // SNI callback is only called during handshake which is synchronous thread_local! { - static HANDSHAKE_VM: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static HANDSHAKE_VM: core::cell::Cell> = const { core::cell::Cell::new(None) }; // SSL pointer during handshake - needed because connection lock is held during handshake // and callbacks may need to access SSL without acquiring the lock - static HANDSHAKE_SSL_PTR: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static HANDSHAKE_SSL_PTR: core::cell::Cell> = const { core::cell::Cell::new(None) }; } // RAII guard to set/clear thread-local handshake context @@ -1896,7 +1896,7 @@ mod _ssl { ))); return Err(openssl::error::ErrorStack::get()); } - let len = std::cmp::min(pw.len(), buf.len()); + let len = core::cmp::min(pw.len(), buf.len()); buf[..len].copy_from_slice(&pw[..len]); Ok(len) } @@ -2714,7 +2714,7 @@ mod _ssl { // Use thread-local SSL pointer during handshake to avoid deadlock let ssl_ptr = get_ssl_ptr_for_context_change(&self.connection); unsafe { - let mut out: *const libc::c_uchar = std::ptr::null(); + let mut out: *const libc::c_uchar = core::ptr::null(); let mut outlen: libc::c_uint = 0; sys::SSL_get0_alpn_selected(ssl_ptr, &mut out, &mut outlen); diff --git a/crates/stdlib/src/overlapped.rs b/crates/stdlib/src/overlapped.rs index d8f14baf35e..1c74ee271b9 100644 --- a/crates/stdlib/src/overlapped.rs +++ b/crates/stdlib/src/overlapped.rs @@ -35,7 +35,7 @@ mod _overlapped { #[pyattr] const INVALID_HANDLE_VALUE: isize = - unsafe { std::mem::transmute(windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE) }; + unsafe { core::mem::transmute(windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE) }; #[pyattr] const NULL: isize = 0; @@ -57,8 +57,8 @@ mod _overlapped { unsafe impl Sync for OverlappedInner {} unsafe impl Send for OverlappedInner {} - impl std::fmt::Debug for Overlapped { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for Overlapped { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let zelf = self.inner.lock(); f.debug_struct("Overlapped") // .field("overlapped", &(self.overlapped as *const _ as usize)) @@ -98,8 +98,8 @@ mod _overlapped { address_length: libc::c_int, } - impl std::fmt::Debug for OverlappedReadFrom { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for OverlappedReadFrom { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("OverlappedReadFrom") .field("result", &self.result) .field("allocated_buffer", &self.allocated_buffer) @@ -119,8 +119,8 @@ mod _overlapped { address_length: libc::c_int, } - impl std::fmt::Debug for OverlappedReadFromInto { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for OverlappedReadFromInto { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("OverlappedReadFromInto") .field("result", &self.result) .field("user_buffer", &self.user_buffer) @@ -226,7 +226,7 @@ mod _overlapped { } #[cfg(target_pointer_width = "32")] - let size = std::cmp::min(size, std::isize::MAX as _); + let size = core::cmp::min(size, std::isize::MAX as _); let buf = vec![0u8; std::cmp::max(size, 1) as usize]; let buf = vm.ctx.new_bytes(buf); @@ -272,10 +272,10 @@ mod _overlapped { if event == INVALID_HANDLE_VALUE { event = unsafe { windows_sys::Win32::System::Threading::CreateEventA( - std::ptr::null(), + core::ptr::null(), Foundation::TRUE, Foundation::FALSE, - std::ptr::null(), + core::ptr::null(), ) as isize }; if event == NULL { @@ -378,11 +378,11 @@ mod _overlapped { let name = widestring::WideCString::from_str(&name).unwrap(); name.as_ptr() } - None => std::ptr::null(), + None => core::ptr::null(), }; let event = unsafe { windows_sys::Win32::System::Threading::CreateEventW( - std::ptr::null(), + core::ptr::null(), manual_reset as _, initial_state as _, name, diff --git a/crates/stdlib/src/posixshmem.rs b/crates/stdlib/src/posixshmem.rs index 2957f16792c..53bf372532d 100644 --- a/crates/stdlib/src/posixshmem.rs +++ b/crates/stdlib/src/posixshmem.rs @@ -4,7 +4,7 @@ pub(crate) use _posixshmem::make_module; #[cfg(all(unix, not(target_os = "redox"), not(target_os = "android")))] #[pymodule] mod _posixshmem { - use std::ffi::CString; + use alloc::ffi::CString; use crate::{ common::os::errno_io_error, diff --git a/crates/stdlib/src/posixsubprocess.rs b/crates/stdlib/src/posixsubprocess.rs index d05b24fd6dd..5dd499abf40 100644 --- a/crates/stdlib/src/posixsubprocess.rs +++ b/crates/stdlib/src/posixsubprocess.rs @@ -13,15 +13,15 @@ use nix::{ unistd::{self, Pid}, }; use std::{ - convert::Infallible as Never, - ffi::{CStr, CString}, io::prelude::*, - marker::PhantomData, - ops::Deref, os::fd::{AsFd, AsRawFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd}, }; use unistd::{Gid, Uid}; +use alloc::ffi::CString; + +use core::{convert::Infallible as Never, ffi::CStr, marker::PhantomData, ops::Deref}; + pub(crate) use _posixsubprocess::make_module; #[pymodule] @@ -87,7 +87,7 @@ impl<'a, T: AsRef> FromIterator<&'a T> for CharPtrVec<'a> { let vec = iter .into_iter() .map(|x| x.as_ref().as_ptr()) - .chain(std::iter::once(std::ptr::null())) + .chain(core::iter::once(core::ptr::null())) .collect(); Self { vec, diff --git a/crates/stdlib/src/resource.rs b/crates/stdlib/src/resource.rs index 052f45e0cad..e6df75e4b01 100644 --- a/crates/stdlib/src/resource.rs +++ b/crates/stdlib/src/resource.rs @@ -9,7 +9,8 @@ mod resource { convert::{ToPyException, ToPyObject}, types::PyStructSequence, }; - use std::{io, mem}; + use core::mem; + use std::io; cfg_if::cfg_if! { if #[cfg(target_os = "android")] { diff --git a/crates/stdlib/src/scproxy.rs b/crates/stdlib/src/scproxy.rs index 1974e7814ae..40267579029 100644 --- a/crates/stdlib/src/scproxy.rs +++ b/crates/stdlib/src/scproxy.rs @@ -22,7 +22,7 @@ mod _scproxy { fn proxy_dict() -> Option> { // Py_BEGIN_ALLOW_THREADS - let proxy_dict = unsafe { SCDynamicStoreCopyProxies(std::ptr::null()) }; + let proxy_dict = unsafe { SCDynamicStoreCopyProxies(core::ptr::null()) }; // Py_END_ALLOW_THREADS if proxy_dict.is_null() { None diff --git a/crates/stdlib/src/select.rs b/crates/stdlib/src/select.rs index 5639a66d2cc..3c2f5e63c7c 100644 --- a/crates/stdlib/src/select.rs +++ b/crates/stdlib/src/select.rs @@ -4,7 +4,8 @@ use crate::vm::{ PyObject, PyObjectRef, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::PyListRef, builtins::PyModule, }; -use std::{io, mem}; +use core::mem; +use std::io; pub(crate) fn make_module(vm: &VirtualMachine) -> PyRef { #[cfg(windows)] @@ -158,7 +159,7 @@ impl 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(); + let mut fdset = core::mem::MaybeUninit::zeroed(); unsafe { platform::FD_ZERO(fdset.as_mut_ptr()) }; Self(fdset) } @@ -191,7 +192,7 @@ pub fn select( ) -> io::Result { let timeout = match timeout { Some(tv) => tv as *mut timeval, - None => std::ptr::null_mut(), + None => core::ptr::null_mut(), }; let ret = unsafe { platform::select( @@ -336,12 +337,10 @@ mod decl { function::OptionalArg, stdlib::io::Fildes, }; + use core::{convert::TryFrom, time::Duration}; use libc::pollfd; use num_traits::{Signed, ToPrimitive}; - use std::{ - convert::TryFrom, - time::{Duration, Instant}, - }; + use std::time::Instant; #[derive(Default)] pub(super) struct TimeoutArg(pub Option); @@ -554,8 +553,8 @@ mod decl { stdlib::io::Fildes, types::Constructor, }; + use core::ops::Deref; use rustix::event::epoll::{self, EventData, EventFlags}; - use std::ops::Deref; use std::os::fd::{AsRawFd, IntoRawFd, OwnedFd}; use std::time::Instant; diff --git a/crates/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index 91c7b1201f1..71bc8e9f170 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -22,15 +22,19 @@ mod _socket { types::{Constructor, DefaultConstructor, Initializer, Representable}, utils::ToCString, }; + use core::{ + mem::MaybeUninit, + net::{Ipv4Addr, Ipv6Addr, SocketAddr}, + time::Duration, + }; use crossbeam_utils::atomic::AtomicCell; use num_traits::ToPrimitive; use socket2::Socket; use std::{ ffi, io::{self, Read, Write}, - mem::MaybeUninit, - net::{self, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs}, - time::{Duration, Instant}, + net::{self, Shutdown, ToSocketAddrs}, + time::Instant, }; #[cfg(unix)] @@ -934,7 +938,7 @@ mod _socket { sock: PyRwLock>, } - const _: () = assert!(std::mem::size_of::>() == std::mem::size_of::()); + const _: () = assert!(core::mem::size_of::>() == core::mem::size_of::()); impl Default for PySocket { fn default() -> Self { @@ -1494,7 +1498,7 @@ mod _socket { Some(errcode!(ENOTSOCK)) | Some(errcode!(EBADF)) ) => { - std::mem::forget(sock); + core::mem::forget(sock); return Err(e.into()); } _ => {} @@ -2052,7 +2056,7 @@ mod _socket { cmsgs: &[(i32, i32, ArgBytesLike)], vm: &VirtualMachine, ) -> PyResult> { - use std::{mem, ptr}; + use core::{mem, ptr}; if cmsgs.is_empty() { return Ok(vec![]); @@ -2210,7 +2214,7 @@ mod _socket { let buflen = buflen.unwrap_or(0); if buflen == 0 { let mut flag: libc::c_int = 0; - let mut flagsize = std::mem::size_of::() as _; + let mut flagsize = core::mem::size_of::() as _; let ret = unsafe { c::getsockopt( fd as _, @@ -2270,11 +2274,11 @@ mod _socket { level, name, val as *const i32 as *const _, - std::mem::size_of::() as _, + core::mem::size_of::() as _, ) }, (None, OptionalArg::Present(optlen)) => unsafe { - c::setsockopt(fd as _, level, name, std::ptr::null(), optlen as _) + c::setsockopt(fd as _, level, name, core::ptr::null(), optlen as _) }, _ => { return Err(vm @@ -2456,7 +2460,7 @@ mod _socket { } impl ToSocketAddrs for Address { - type Iter = std::vec::IntoIter; + type Iter = alloc::vec::IntoIter; fn to_socket_addrs(&self) -> io::Result { (self.host.as_str(), self.port).to_socket_addrs() } @@ -2616,7 +2620,7 @@ mod _socket { } fn cstr_opt_as_ptr(x: &OptionalArg) -> *const libc::c_char { - x.as_ref().map_or_else(std::ptr::null, |s| s.as_ptr()) + x.as_ref().map_or_else(core::ptr::null, |s| s.as_ptr()) } #[pyfunction] @@ -2807,7 +2811,7 @@ mod _socket { vm.state .codec_registry .encode_text(s.to_owned(), "idna", None, vm)?; - let host_str = std::str::from_utf8(encoded.as_bytes()) + let host_str = core::str::from_utf8(encoded.as_bytes()) .map_err(|_| vm.new_runtime_error("idna output is not utf8".to_owned()))?; Some(host_str.to_owned()) } @@ -3183,7 +3187,7 @@ mod _socket { .state .codec_registry .encode_text(pyname, "idna", None, vm)?; - let name = std::str::from_utf8(name.as_bytes()) + let name = core::str::from_utf8(name.as_bytes()) .map_err(|_| vm.new_runtime_error("idna output is not utf8"))?; let mut res = dns_lookup::getaddrinfo(Some(name), None, Some(hints)) .map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?; @@ -3339,7 +3343,7 @@ mod _socket { #[pyfunction] fn dup(x: PyObjectRef, vm: &VirtualMachine) -> Result { let sock = get_raw_sock(x, vm)?; - let sock = std::mem::ManuallyDrop::new(sock_from_raw(sock, vm)?); + let sock = core::mem::ManuallyDrop::new(sock_from_raw(sock, vm)?); let newsock = sock.try_clone()?; let fd = into_sock_fileno(newsock); #[cfg(windows)] diff --git a/crates/stdlib/src/sqlite.rs b/crates/stdlib/src/sqlite.rs index 103a827e99a..3a82787cd8f 100644 --- a/crates/stdlib/src/sqlite.rs +++ b/crates/stdlib/src/sqlite.rs @@ -844,7 +844,7 @@ mod _sqlite { } impl Debug for Connection { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { write!(f, "Sqlite3 Connection") } } @@ -2583,7 +2583,7 @@ mod _sqlite { } impl Debug for Statement { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { write!( f, "{} Statement", diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index 16449e2d019..b90176a62fa 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -52,14 +52,12 @@ mod _ssl { use super::error::{ PySSLEOFError, PySSLError, create_ssl_want_read_error, create_ssl_want_write_error, }; - use std::{ - collections::HashMap, - sync::{ - Arc, - atomic::{AtomicUsize, Ordering}, - }, - time::{Duration, SystemTime}, + use alloc::sync::Arc; + use core::{ + sync::atomic::{AtomicUsize, Ordering}, + time::Duration, }; + use std::{collections::HashMap, time::SystemTime}; // Rustls imports use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock}; @@ -3124,7 +3122,7 @@ mod _ssl { // When server_hostname=None, use an IP address to suppress SNI // no hostname = no SNI extension ServerName::IpAddress( - std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1)).into(), + core::net::IpAddr::V4(core::net::Ipv4Addr::new(127, 0, 0, 1)).into(), ) }; @@ -3385,7 +3383,7 @@ mod _ssl { let mut written = 0; while written < data.len() { - let chunk_end = std::cmp::min(written + CHUNK_SIZE, data.len()); + let chunk_end = core::cmp::min(written + CHUNK_SIZE, data.len()); let chunk = &data[written..chunk_end]; // Write chunk to TLS layer @@ -4176,8 +4174,8 @@ mod _ssl { #[pygetset] fn id(&self, vm: &VirtualMachine) -> PyBytesRef { // Return session ID (hash of session data for uniqueness) + use core::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; let mut hasher = DefaultHasher::new(); self.session_data.hash(&mut hasher); @@ -4487,7 +4485,7 @@ mod _ssl { let mut result = Vec::new(); - let mut crl_context: *const CRL_CONTEXT = std::ptr::null(); + let mut crl_context: *const CRL_CONTEXT = core::ptr::null(); loop { crl_context = unsafe { CertEnumCRLsInStore(store, crl_context) }; if crl_context.is_null() { @@ -4587,8 +4585,8 @@ mod _ssl { // Implement Hashable trait for PySSLCertificate impl Hashable for PySSLCertificate { fn hash(zelf: &Py, _vm: &VirtualMachine) -> PyResult { + use core::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; let mut hasher = DefaultHasher::new(); zelf.der_bytes.hash(&mut hasher); diff --git a/crates/stdlib/src/ssl/cert.rs b/crates/stdlib/src/ssl/cert.rs index b3cb7d6c14e..cd39972cf41 100644 --- a/crates/stdlib/src/ssl/cert.rs +++ b/crates/stdlib/src/ssl/cert.rs @@ -9,6 +9,7 @@ //! - Building and verifying certificate chains //! - Loading certificates from files, directories, and bytes +use alloc::sync::Arc; use chrono::{DateTime, Utc}; use parking_lot::RwLock as ParkingRwLock; use rustls::{ @@ -19,7 +20,6 @@ use rustls::{ }; use rustpython_vm::{PyObjectRef, PyResult, VirtualMachine}; use std::collections::HashSet; -use std::sync::Arc; use x509_parser::prelude::*; use super::compat::{VERIFY_X509_PARTIAL_CHAIN, VERIFY_X509_STRICT}; @@ -51,8 +51,9 @@ const ALL_SIGNATURE_SCHEMES: &[SignatureScheme] = &[ /// operations, reducing code duplication and ensuring uniform error messages /// across the codebase. mod cert_error { + use alloc::sync::Arc; + use core::fmt::{Debug, Display}; use std::io; - use std::sync::Arc; /// Create InvalidData error with formatted message pub fn invalid_data(msg: impl Into) -> io::Error { @@ -67,11 +68,11 @@ mod cert_error { invalid_data(format!("no start line: {context}")) } - pub fn parse_failed(e: impl std::fmt::Display) -> io::Error { + pub fn parse_failed(e: impl Display) -> io::Error { invalid_data(format!("Failed to parse PEM certificate: {e}")) } - pub fn parse_failed_debug(e: impl std::fmt::Debug) -> io::Error { + pub fn parse_failed_debug(e: impl Debug) -> io::Error { invalid_data(format!("Failed to parse PEM certificate: {e:?}")) } @@ -88,7 +89,7 @@ mod cert_error { invalid_data(format!("not enough data: {context}")) } - pub fn parse_failed(e: impl std::fmt::Display) -> io::Error { + pub fn parse_failed(e: impl Display) -> io::Error { invalid_data(format!("Failed to parse DER certificate: {e}")) } } @@ -101,15 +102,15 @@ mod cert_error { invalid_data(format!("No private key found in {context}")) } - pub fn parse_failed(e: impl std::fmt::Display) -> io::Error { + pub fn parse_failed(e: impl Display) -> io::Error { invalid_data(format!("Failed to parse private key: {e}")) } - pub fn parse_encrypted_failed(e: impl std::fmt::Display) -> io::Error { + pub fn parse_encrypted_failed(e: impl Display) -> io::Error { invalid_data(format!("Failed to parse encrypted private key: {e}")) } - pub fn decrypt_failed(e: impl std::fmt::Display) -> io::Error { + pub fn decrypt_failed(e: impl Display) -> io::Error { io::Error::other(format!( "Failed to decrypt private key (wrong password?): {e}", )) @@ -383,7 +384,7 @@ pub fn cert_der_to_dict_helper(vm: &VirtualMachine, cert_der: &[u8]) -> PyResult s.to_string() } else { let value_bytes = attr.attr_value().data; - match std::str::from_utf8(value_bytes) { + match core::str::from_utf8(value_bytes) { Ok(s) => s.to_string(), Err(_) => String::from_utf8_lossy(value_bytes).into_owned(), } @@ -1126,7 +1127,7 @@ pub(super) fn load_cert_chain_from_file( cert_path: &str, key_path: &str, password: Option<&str>, -) -> Result<(Vec>, PrivateKeyDer<'static>), Box> { +) -> Result<(Vec>, PrivateKeyDer<'static>), Box> { // Load certificate file - preserve io::Error for errno let cert_contents = std::fs::read(cert_path)?; @@ -1727,13 +1728,13 @@ fn verify_ip_address( cert: &X509Certificate<'_>, expected_ip: &rustls::pki_types::IpAddr, ) -> Result<(), rustls::Error> { - use std::net::IpAddr; + use core::net::IpAddr; use x509_parser::extensions::GeneralName; // Convert rustls IpAddr to std::net::IpAddr for comparison let expected_std_ip: IpAddr = match expected_ip { - rustls::pki_types::IpAddr::V4(octets) => IpAddr::V4(std::net::Ipv4Addr::from(*octets)), - rustls::pki_types::IpAddr::V6(octets) => IpAddr::V6(std::net::Ipv6Addr::from(*octets)), + rustls::pki_types::IpAddr::V4(octets) => IpAddr::V4(core::net::Ipv4Addr::from(*octets)), + rustls::pki_types::IpAddr::V6(octets) => IpAddr::V6(core::net::Ipv6Addr::from(*octets)), }; // Check Subject Alternative Names for IP addresses @@ -1745,7 +1746,7 @@ fn verify_ip_address( 4 => { // IPv4 if let Ok(octets) = <[u8; 4]>::try_from(*cert_ip_bytes) { - IpAddr::V4(std::net::Ipv4Addr::from(octets)) + IpAddr::V4(core::net::Ipv4Addr::from(octets)) } else { continue; } @@ -1753,7 +1754,7 @@ fn verify_ip_address( 16 => { // IPv6 if let Ok(octets) = <[u8; 16]>::try_from(*cert_ip_bytes) { - IpAddr::V6(std::net::Ipv6Addr::from(octets)) + IpAddr::V6(core::net::Ipv6Addr::from(octets)) } else { continue; } diff --git a/crates/stdlib/src/ssl/compat.rs b/crates/stdlib/src/ssl/compat.rs index fa12855e242..2168fcfc91f 100644 --- a/crates/stdlib/src/ssl/compat.rs +++ b/crates/stdlib/src/ssl/compat.rs @@ -13,6 +13,7 @@ mod ssl_data; use crate::socket::{SelectKind, timeout_error_msg}; use crate::vm::VirtualMachine; +use alloc::sync::Arc; use parking_lot::RwLock as ParkingRwLock; use rustls::RootCertStore; use rustls::client::ClientConfig; @@ -28,7 +29,7 @@ use rustpython_vm::convert::IntoPyException; use rustpython_vm::function::ArgBytesLike; use rustpython_vm::{AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromObject}; use std::io::Read; -use std::sync::{Arc, Once}; +use std::sync::Once; // Import PySSLSocket from parent module use super::_ssl::PySSLSocket; diff --git a/crates/stdlib/src/syslog.rs b/crates/stdlib/src/syslog.rs index d0ed3f60949..b52d1415692 100644 --- a/crates/stdlib/src/syslog.rs +++ b/crates/stdlib/src/syslog.rs @@ -11,7 +11,8 @@ mod syslog { function::{OptionalArg, OptionalOption}, utils::ToCString, }; - use std::{ffi::CStr, os::raw::c_char}; + use core::ffi::CStr; + use std::os::raw::c_char; #[pyattr] use libc::{ @@ -50,7 +51,7 @@ mod syslog { fn as_ptr(&self) -> *const c_char { match self { Self::Explicit(cstr) => cstr.as_ptr(), - Self::Implicit => std::ptr::null(), + Self::Implicit => core::ptr::null(), } } } diff --git a/crates/stdlib/src/tkinter.rs b/crates/stdlib/src/tkinter.rs index 687458b193b..49dcdc5f84f 100644 --- a/crates/stdlib/src/tkinter.rs +++ b/crates/stdlib/src/tkinter.rs @@ -59,8 +59,8 @@ mod _tkinter { value: *mut tk_sys::Tcl_Obj, } - impl std::fmt::Debug for TclObject { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for TclObject { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "TclObject") } } @@ -107,8 +107,8 @@ mod _tkinter { unsafe impl Send for TkApp {} unsafe impl Sync for TkApp {} - impl std::fmt::Debug for TkApp { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for TkApp { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "TkApp") } } diff --git a/crates/stdlib/src/zlib.rs b/crates/stdlib/src/zlib.rs index 9ca94939f78..632543c5c64 100644 --- a/crates/stdlib/src/zlib.rs +++ b/crates/stdlib/src/zlib.rs @@ -39,7 +39,7 @@ mod zlib { #[pyattr(name = "ZLIB_RUNTIME_VERSION")] #[pyattr] const ZLIB_VERSION: &str = unsafe { - match std::ffi::CStr::from_ptr(libz_sys::zlibVersion()).to_str() { + match core::ffi::CStr::from_ptr(libz_sys::zlibVersion()).to_str() { Ok(s) => s, Err(_) => unreachable!(), } @@ -322,7 +322,7 @@ mod zlib { }; let inner = &mut *self.inner.lock(); - let data = std::mem::replace(&mut inner.unconsumed_tail, vm.ctx.empty_bytes.clone()); + let data = core::mem::replace(&mut inner.unconsumed_tail, vm.ctx.empty_bytes.clone()); let (ret, _) = Self::decompress_inner(inner, &data, length, None, true, vm)?; diff --git a/crates/venvlauncher/src/main.rs b/crates/venvlauncher/src/main.rs index aaf584dfa87..fe147ce7ff3 100644 --- a/crates/venvlauncher/src/main.rs +++ b/crates/venvlauncher/src/main.rs @@ -22,7 +22,7 @@ fn main() -> ExitCode { } } -fn run() -> Result> { +fn run() -> Result> { // 1. Get own executable path let exe_path = env::current_exe()?; let exe_name = exe_path @@ -72,7 +72,7 @@ fn run() -> Result> { } /// Parse the `home=` value from pyvenv.cfg -fn read_home(cfg_path: &Path) -> Result> { +fn read_home(cfg_path: &Path) -> Result> { let content = fs::read_to_string(cfg_path)?; for line in content.lines() { @@ -95,7 +95,7 @@ fn read_home(cfg_path: &Path) -> Result> { } /// Launch the Python process and wait for it to complete -fn launch_process(exe: &Path, args: &[String]) -> Result> { +fn launch_process(exe: &Path, args: &[String]) -> Result> { use std::process::Command; let status = Command::new(exe).args(args).status()?; diff --git a/crates/vm/src/anystr.rs b/crates/vm/src/anystr.rs index ef6d24c100e..79b62a58abf 100644 --- a/crates/vm/src/anystr.rs +++ b/crates/vm/src/anystr.rs @@ -6,6 +6,8 @@ use crate::{ }; use num_traits::{cast::ToPrimitive, sign::Signed}; +use core::ops::Range; + #[derive(FromArgs)] pub struct SplitArgs { #[pyarg(any, default)] @@ -43,7 +45,7 @@ pub struct StartsEndsWithArgs { } impl StartsEndsWithArgs { - pub fn get_value(self, len: usize) -> (PyObjectRef, Option>) { + pub fn get_value(self, len: usize) -> (PyObjectRef, Option>) { let range = if self.start.is_some() || self.end.is_some() { Some(adjust_indices(self.start, self.end, len)) } else { @@ -56,7 +58,7 @@ impl StartsEndsWithArgs { pub fn prepare(self, s: &S, len: usize, substr: F) -> Option<(PyObjectRef, &S)> where S: ?Sized + AnyStr, - F: Fn(&S, std::ops::Range) -> &S, + F: Fn(&S, Range) -> &S, { let (affix, range) = self.get_value(len); let substr = if let Some(range) = range { @@ -83,11 +85,7 @@ fn saturate_to_isize(py_int: PyIntRef) -> isize { } // help get optional string indices -pub fn adjust_indices( - start: Option, - end: Option, - len: usize, -) -> std::ops::Range { +pub fn adjust_indices(start: Option, end: Option, len: usize) -> Range { let mut start = start.map_or(0, saturate_to_isize); let mut end = end.map_or(len as isize, saturate_to_isize); if end > len as isize { @@ -111,7 +109,7 @@ pub trait StringRange { fn is_normal(&self) -> bool; } -impl StringRange for std::ops::Range { +impl StringRange for Range { fn is_normal(&self) -> bool { self.start <= self.end } @@ -144,9 +142,9 @@ pub trait AnyStr { fn to_container(&self) -> Self::Container; fn as_bytes(&self) -> &[u8]; fn elements(&self) -> impl Iterator; - fn get_bytes(&self, range: std::ops::Range) -> &Self; + fn get_bytes(&self, range: Range) -> &Self; // FIXME: get_chars is expensive for str - fn get_chars(&self, range: std::ops::Range) -> &Self; + fn get_chars(&self, range: Range) -> &Self; fn bytes_len(&self) -> usize; // NOTE: str::chars().count() consumes the O(n) time. But pystr::char_len does cache. // So using chars_len directly is too expensive and the below method shouldn't be implemented. @@ -254,7 +252,7 @@ pub trait AnyStr { } #[inline] - fn py_find(&self, needle: &Self, range: std::ops::Range, find: F) -> Option + fn py_find(&self, needle: &Self, range: Range, find: F) -> Option where F: Fn(&Self, &Self) -> Option, { @@ -268,7 +266,7 @@ pub trait AnyStr { } #[inline] - fn py_count(&self, needle: &Self, range: std::ops::Range, count: F) -> usize + fn py_count(&self, needle: &Self, range: Range, count: F) -> usize where F: Fn(&Self, &Self) -> usize, { @@ -283,9 +281,9 @@ pub trait AnyStr { let mut u = Self::Container::with_capacity( (left + right) * fillchar.bytes_len() + self.bytes_len(), ); - u.extend(std::iter::repeat_n(fillchar, left)); + u.extend(core::iter::repeat_n(fillchar, left)); u.push_str(self); - u.extend(std::iter::repeat_n(fillchar, right)); + u.extend(core::iter::repeat_n(fillchar, right)); u } @@ -305,7 +303,7 @@ pub trait AnyStr { fn py_join( &self, - mut iter: impl std::iter::Iterator + TryFromObject>>, + mut iter: impl core::iter::Iterator + TryFromObject>>, ) -> PyResult { let mut joined = if let Some(elem) = iter.next() { elem?.as_ref().unwrap().to_container() @@ -328,7 +326,7 @@ pub trait AnyStr { ) -> PyResult<(Self::Container, bool, Self::Container)> where F: Fn() -> S, - S: std::iter::Iterator, + S: core::iter::Iterator, { if sub.is_empty() { return Err(vm.new_value_error("empty separator")); diff --git a/crates/vm/src/buffer.rs b/crates/vm/src/buffer.rs index 5c67f87521d..3d5e48015ea 100644 --- a/crates/vm/src/buffer.rs +++ b/crates/vm/src/buffer.rs @@ -5,11 +5,13 @@ use crate::{ convert::ToPyObject, function::{ArgBytesLike, ArgIntoBool, ArgIntoFloat}, }; +use alloc::fmt; +use core::{iter::Peekable, mem}; use half::f16; use itertools::Itertools; use malachite_bigint::BigInt; use num_traits::{PrimInt, ToPrimitive}; -use std::{fmt, iter::Peekable, mem, os::raw}; +use std::os::raw; type PackFunc = fn(&VirtualMachine, PyObjectRef, &mut [u8]) -> PyResult<()>; type UnpackFunc = fn(&VirtualMachine, &[u8]) -> PyObjectRef; @@ -545,7 +547,7 @@ macro_rules! make_pack_prim_int { } #[inline] fn unpack_int(data: &[u8]) -> Self { - let mut x = [0; std::mem::size_of::<$T>()]; + let mut x = [0; core::mem::size_of::<$T>()]; x.copy_from_slice(data); E::convert(<$T>::from_ne_bytes(x)) } @@ -681,7 +683,7 @@ fn pack_pascal(vm: &VirtualMachine, arg: PyObjectRef, buf: &mut [u8]) -> PyResul } let b = ArgBytesLike::try_from_object(vm, arg)?; b.with_ref(|data| { - let string_length = std::cmp::min(std::cmp::min(data.len(), 255), buf.len() - 1); + let string_length = core::cmp::min(core::cmp::min(data.len(), 255), buf.len() - 1); buf[0] = string_length as u8; write_string(&mut buf[1..], data); }); @@ -689,7 +691,7 @@ fn pack_pascal(vm: &VirtualMachine, arg: PyObjectRef, buf: &mut [u8]) -> PyResul } fn write_string(buf: &mut [u8], data: &[u8]) { - let len_from_data = std::cmp::min(data.len(), buf.len()); + let len_from_data = core::cmp::min(data.len(), buf.len()); buf[..len_from_data].copy_from_slice(&data[..len_from_data]); for byte in &mut buf[len_from_data..] { *byte = 0 @@ -708,7 +710,7 @@ fn unpack_pascal(vm: &VirtualMachine, data: &[u8]) -> PyObjectRef { return vm.ctx.new_bytes(vec![]).into(); } }; - let len = std::cmp::min(len as usize, data.len()); + let len = core::cmp::min(len as usize, data.len()); vm.ctx.new_bytes(data[..len].to_vec()).into() } diff --git a/crates/vm/src/builtins/bool.rs b/crates/vm/src/builtins/bool.rs index cfd1f136d14..3dabdbae717 100644 --- a/crates/vm/src/builtins/bool.rs +++ b/crates/vm/src/builtins/bool.rs @@ -8,9 +8,9 @@ use crate::{ protocol::PyNumberMethods, types::{AsNumber, Constructor, Representable}, }; +use core::fmt::{Debug, Formatter}; use malachite_bigint::Sign; use num_traits::Zero; -use std::fmt::{Debug, Formatter}; impl ToPyObject for bool { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { @@ -90,7 +90,7 @@ impl PyObjectRef { pub struct PyBool(pub PyInt); impl Debug for PyBool { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let value = !self.0.as_bigint().is_zero(); write!(f, "PyBool({})", value) } diff --git a/crates/vm/src/builtins/builtin_func.rs b/crates/vm/src/builtins/builtin_func.rs index 2b569375b28..422f922df94 100644 --- a/crates/vm/src/builtins/builtin_func.rs +++ b/crates/vm/src/builtins/builtin_func.rs @@ -7,7 +7,7 @@ use crate::{ function::{FuncArgs, PyComparisonValue, PyMethodDef, PyMethodFlags, PyNativeFn}, types::{Callable, Comparable, PyComparisonOp, Representable}, }; -use std::fmt; +use alloc::fmt; // PyCFunctionObject in CPython #[pyclass(name = "builtin_function_or_method", module = false)] @@ -212,7 +212,7 @@ impl Comparable for PyNativeMethod { (None, None) => true, _ => false, }; - let eq = eq && std::ptr::eq(zelf.func.value, other.func.value); + let eq = eq && core::ptr::eq(zelf.func.value, other.func.value); Ok(eq.into()) } else { Ok(PyComparisonValue::NotImplemented) diff --git a/crates/vm/src/builtins/bytearray.rs b/crates/vm/src/builtins/bytearray.rs index c5861befb73..212e4604ec9 100644 --- a/crates/vm/src/builtins/bytearray.rs +++ b/crates/vm/src/builtins/bytearray.rs @@ -37,7 +37,7 @@ use crate::{ }, }; use bstr::ByteSlice; -use std::mem::size_of; +use core::mem::size_of; #[pyclass(module = false, name = "bytearray", unhashable = true)] #[derive(Debug, Default)] @@ -687,7 +687,7 @@ impl Initializer for PyByteArray { fn init(zelf: PyRef, options: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // First unpack bytearray and *then* get a lock to set it. let mut inner = options.get_bytearray_inner(vm)?; - std::mem::swap(&mut *zelf.inner_mut(), &mut inner); + core::mem::swap(&mut *zelf.inner_mut(), &mut inner); Ok(()) } } diff --git a/crates/vm/src/builtins/bytes.rs b/crates/vm/src/builtins/bytes.rs index 0c67cd7bf24..b3feac8ac97 100644 --- a/crates/vm/src/builtins/bytes.rs +++ b/crates/vm/src/builtins/bytes.rs @@ -29,8 +29,8 @@ use crate::{ }, }; use bstr::ByteSlice; +use core::{mem::size_of, ops::Deref}; use std::sync::LazyLock; -use std::{mem::size_of, ops::Deref}; #[pyclass(module = false, name = "bytes")] #[derive(Clone, Debug)] diff --git a/crates/vm/src/builtins/code.rs b/crates/vm/src/builtins/code.rs index e46cc711bb3..b897ef9d311 100644 --- a/crates/vm/src/builtins/code.rs +++ b/crates/vm/src/builtins/code.rs @@ -11,10 +11,11 @@ use crate::{ function::OptionalArg, types::{Constructor, Representable}, }; +use alloc::fmt; +use core::{borrow::Borrow, ops::Deref}; use malachite_bigint::BigInt; use num_traits::Zero; use rustpython_compiler_core::{OneIndexed, bytecode::CodeUnits, bytecode::PyCodeLocationInfoKind}; -use std::{borrow::Borrow, fmt, ops::Deref}; /// State for iterating through code address ranges struct PyCodeAddressRange<'a> { @@ -601,7 +602,7 @@ impl PyCode { pub fn co_code(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef { // SAFETY: CodeUnit is #[repr(C)] with size 2, so we can safely transmute to bytes let bytes = unsafe { - std::slice::from_raw_parts( + core::slice::from_raw_parts( self.code.instructions.as_ptr() as *const u8, self.code.instructions.len() * 2, ) diff --git a/crates/vm/src/builtins/complex.rs b/crates/vm/src/builtins/complex.rs index ba74d5e0367..78729b2f5c0 100644 --- a/crates/vm/src/builtins/complex.rs +++ b/crates/vm/src/builtins/complex.rs @@ -10,10 +10,10 @@ use crate::{ stdlib::warnings, types::{AsNumber, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; +use core::num::Wrapping; use num_complex::Complex64; use num_traits::Zero; use rustpython_common::hash; -use std::num::Wrapping; /// Create a complex number from a real part and an optional imaginary part. /// diff --git a/crates/vm/src/builtins/descriptor.rs b/crates/vm/src/builtins/descriptor.rs index 802b81f6d79..aa9da6e2d44 100644 --- a/crates/vm/src/builtins/descriptor.rs +++ b/crates/vm/src/builtins/descriptor.rs @@ -59,8 +59,8 @@ impl PyPayload for PyMethodDescriptor { } } -impl std::fmt::Debug for PyMethodDescriptor { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyMethodDescriptor { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "method descriptor for '{}'", self.common.name) } } @@ -218,8 +218,8 @@ impl PyMemberDef { } } -impl std::fmt::Debug for PyMemberDef { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyMemberDef { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyMemberDef") .field("name", &self.name) .field("kind", &self.kind) @@ -445,8 +445,8 @@ pub enum SlotFunc { NumTernaryRight(PyNumberTernaryFunc), // __rpow__ (swapped first two args) } -impl std::fmt::Debug for SlotFunc { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for SlotFunc { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { SlotFunc::Init(_) => write!(f, "SlotFunc::Init(...)"), SlotFunc::Hash(_) => write!(f, "SlotFunc::Hash(...)"), diff --git a/crates/vm/src/builtins/dict.rs b/crates/vm/src/builtins/dict.rs index 567e18d6419..358685fcdc4 100644 --- a/crates/vm/src/builtins/dict.rs +++ b/crates/vm/src/builtins/dict.rs @@ -23,8 +23,8 @@ use crate::{ }, vm::VirtualMachine, }; +use alloc::fmt; use rustpython_common::lock::PyMutex; -use std::fmt; use std::sync::LazyLock; pub type DictContentType = dict_inner::Dict; @@ -219,7 +219,7 @@ impl PyDict { #[pymethod] fn __sizeof__(&self) -> usize { - std::mem::size_of::() + self.entries.sizeof() + core::mem::size_of::() + self.entries.sizeof() } #[pymethod] @@ -759,7 +759,7 @@ impl ExactSizeIterator for DictIter<'_> { #[pyclass] trait DictView: PyPayload + PyClassDef + Iterable + Representable { - type ReverseIter: PyPayload + std::fmt::Debug; + type ReverseIter: PyPayload + core::fmt::Debug; fn dict(&self) -> &Py; fn item(vm: &VirtualMachine, key: PyObjectRef, value: PyObjectRef) -> PyObjectRef; diff --git a/crates/vm/src/builtins/function.rs b/crates/vm/src/builtins/function.rs index c29e45ddcf6..95d70afcbc7 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -149,7 +149,7 @@ impl PyFunction { None }; - let arg_pos = |range: std::ops::Range<_>, name: &str| { + let arg_pos = |range: core::ops::Range<_>, name: &str| { code.varnames .iter() .enumerate() @@ -255,7 +255,7 @@ impl PyFunction { } if let Some(defaults) = defaults { - let n = std::cmp::min(nargs, n_expected_args); + let n = core::cmp::min(nargs, n_expected_args); let i = n.saturating_sub(n_required); // We have sufficient defaults, so iterate over the corresponding names and use diff --git a/crates/vm/src/builtins/genericalias.rs b/crates/vm/src/builtins/genericalias.rs index 8a7288980fa..5596aca9da2 100644 --- a/crates/vm/src/builtins/genericalias.rs +++ b/crates/vm/src/builtins/genericalias.rs @@ -16,7 +16,7 @@ use crate::{ PyComparisonOp, Representable, }, }; -use std::fmt; +use alloc::fmt; // attr_exceptions static ATTR_EXCEPTIONS: [&str; 12] = [ diff --git a/crates/vm/src/builtins/getset.rs b/crates/vm/src/builtins/getset.rs index 3fa4667a997..a3f0605a473 100644 --- a/crates/vm/src/builtins/getset.rs +++ b/crates/vm/src/builtins/getset.rs @@ -19,8 +19,8 @@ pub struct PyGetSet { // doc: Option, } -impl std::fmt::Debug for PyGetSet { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyGetSet { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( f, "PyGetSet {{ name: {}, getter: {}, setter: {} }}", @@ -158,7 +158,7 @@ impl Representable for PyGetSet { fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { let class = unsafe { zelf.class.borrow_static() }; // Special case for object type - if std::ptr::eq(class, vm.ctx.types.object_type) { + if core::ptr::eq(class, vm.ctx.types.object_type) { Ok(format!("", zelf.name)) } else { Ok(format!( diff --git a/crates/vm/src/builtins/int.rs b/crates/vm/src/builtins/int.rs index 37b41e085ad..182333cea51 100644 --- a/crates/vm/src/builtins/int.rs +++ b/crates/vm/src/builtins/int.rs @@ -17,11 +17,11 @@ use crate::{ protocol::{PyNumberMethods, handle_bytes_to_int_err}, types::{AsNumber, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; +use alloc::fmt; +use core::ops::{Neg, Not}; use malachite_bigint::{BigInt, Sign}; use num_integer::Integer; use num_traits::{One, Pow, PrimInt, Signed, ToPrimitive, Zero}; -use std::fmt; -use std::ops::{Neg, Not}; #[pyclass(module = false, name = "int")] #[derive(Debug)] @@ -289,7 +289,7 @@ impl PyInt { I::try_from(self.as_bigint()).map_err(|_| { vm.new_overflow_error(format!( "Python int too large to convert to Rust {}", - std::any::type_name::() + core::any::type_name::() )) }) } @@ -444,7 +444,7 @@ impl PyInt { #[pymethod] fn __sizeof__(&self) -> usize { - std::mem::size_of::() + (((self.value.bits() + 7) & !7) / 8) as usize + core::mem::size_of::() + (((self.value.bits() + 7) & !7) / 8) as usize } #[pymethod] diff --git a/crates/vm/src/builtins/list.rs b/crates/vm/src/builtins/list.rs index 12cab27a750..46145b339cf 100644 --- a/crates/vm/src/builtins/list.rs +++ b/crates/vm/src/builtins/list.rs @@ -20,7 +20,8 @@ use crate::{ utils::collection_repr, vm::VirtualMachine, }; -use std::{fmt, ops::DerefMut}; +use alloc::fmt; +use core::ops::DerefMut; #[pyclass(module = false, name = "list", unhashable = true, traverse)] #[derive(Default)] @@ -172,7 +173,7 @@ impl PyList { #[pymethod] fn clear(&self) { - let _removed = std::mem::take(self.borrow_vec_mut().deref_mut()); + let _removed = core::mem::take(self.borrow_vec_mut().deref_mut()); } #[pymethod] @@ -188,8 +189,8 @@ impl PyList { #[pymethod] fn __sizeof__(&self) -> usize { - std::mem::size_of::() - + self.elements.read().capacity() * std::mem::size_of::() + core::mem::size_of::() + + self.elements.read().capacity() * core::mem::size_of::() } #[pymethod] @@ -324,9 +325,9 @@ impl PyList { // replace list contents with [] for duration of sort. // this prevents keyfunc from messing with the list and makes it easy to // check if it tries to append elements to it. - let mut elements = std::mem::take(self.borrow_vec_mut().deref_mut()); + let mut elements = core::mem::take(self.borrow_vec_mut().deref_mut()); let res = do_sort(vm, &mut elements, options.key, options.reverse); - std::mem::swap(self.borrow_vec_mut().deref_mut(), &mut elements); + core::mem::swap(self.borrow_vec_mut().deref_mut(), &mut elements); res?; if !elements.is_empty() { @@ -375,7 +376,7 @@ impl MutObjectSequenceOp for PyList { inner.get(index).map(|r| r.as_ref()) } - fn do_lock(&self) -> impl std::ops::Deref { + fn do_lock(&self) -> impl core::ops::Deref { self.borrow_vec() } } @@ -397,7 +398,7 @@ impl Initializer for PyList { } else { vec![] }; - std::mem::swap(zelf.borrow_vec_mut().deref_mut(), &mut elements); + core::mem::swap(zelf.borrow_vec_mut().deref_mut(), &mut elements); Ok(()) } } diff --git a/crates/vm/src/builtins/map.rs b/crates/vm/src/builtins/map.rs index f5cee945ece..f83030824f1 100644 --- a/crates/vm/src/builtins/map.rs +++ b/crates/vm/src/builtins/map.rs @@ -42,7 +42,7 @@ impl PyMap { fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult { self.iterators.iter().try_fold(0, |prev, cur| { let cur = cur.as_ref().to_owned().length_hint(0, vm)?; - let max = std::cmp::max(prev, cur); + let max = core::cmp::max(prev, cur); Ok(max) }) } diff --git a/crates/vm/src/builtins/memory.rs b/crates/vm/src/builtins/memory.rs index 4e895f92b7e..ff5df031c42 100644 --- a/crates/vm/src/builtins/memory.rs +++ b/crates/vm/src/builtins/memory.rs @@ -26,11 +26,11 @@ use crate::{ PyComparisonOp, Representable, SelfIter, }, }; +use core::{cmp::Ordering, fmt::Debug, mem::ManuallyDrop, ops::Range}; use crossbeam_utils::atomic::AtomicCell; use itertools::Itertools; use rustpython_common::lock::PyMutex; use std::sync::LazyLock; -use std::{cmp::Ordering, fmt::Debug, mem::ManuallyDrop, ops::Range}; #[derive(FromArgs)] pub struct PyMemoryViewNewArgs { diff --git a/crates/vm/src/builtins/module.rs b/crates/vm/src/builtins/module.rs index f8e42b28e0b..faa6e4813fd 100644 --- a/crates/vm/src/builtins/module.rs +++ b/crates/vm/src/builtins/module.rs @@ -32,8 +32,8 @@ pub struct PyModuleSlots { pub exec: Option, } -impl std::fmt::Debug for PyModuleSlots { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyModuleSlots { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyModuleSlots") .field("create", &self.create.is_some()) .field("exec", &self.exec.is_some()) diff --git a/crates/vm/src/builtins/object.rs b/crates/vm/src/builtins/object.rs index a61fb1e2971..e73f4b79ae0 100644 --- a/crates/vm/src/builtins/object.rs +++ b/crates/vm/src/builtins/object.rs @@ -218,7 +218,7 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine) // basicsize += std::mem::size_of::(); // } if let Some(ref slot_names) = slot_names { - basicsize += std::mem::size_of::() * slot_names.__len__(); + basicsize += core::mem::size_of::() * slot_names.__len__(); } if obj.class().slots.basicsize > basicsize { return Err( diff --git a/crates/vm/src/builtins/property.rs b/crates/vm/src/builtins/property.rs index 7ea36d39768..3a86867176a 100644 --- a/crates/vm/src/builtins/property.rs +++ b/crates/vm/src/builtins/property.rs @@ -10,7 +10,7 @@ use crate::{ function::{FuncArgs, PySetterValue}, types::{Constructor, GetDescriptor, Initializer}, }; -use std::sync::atomic::{AtomicBool, Ordering}; +use core::sync::atomic::{AtomicBool, Ordering}; #[pyclass(module = false, name = "property", traverse)] #[derive(Debug)] @@ -21,7 +21,7 @@ pub struct PyProperty { doc: PyRwLock>, name: PyRwLock>, #[pytraverse(skip)] - getter_doc: std::sync::atomic::AtomicBool, + getter_doc: core::sync::atomic::AtomicBool, } impl PyPayload for PyProperty { diff --git a/crates/vm/src/builtins/range.rs b/crates/vm/src/builtins/range.rs index 9f79f8efb2d..ab84c977ccd 100644 --- a/crates/vm/src/builtins/range.rs +++ b/crates/vm/src/builtins/range.rs @@ -14,11 +14,11 @@ use crate::{ Representable, SelfIter, }, }; +use core::cmp::max; use crossbeam_utils::atomic::AtomicCell; use malachite_bigint::{BigInt, Sign}; use num_integer::Integer; use num_traits::{One, Signed, ToPrimitive, Zero}; -use std::cmp::max; use std::sync::LazyLock; // Search flag passed to iter_search diff --git a/crates/vm/src/builtins/set.rs b/crates/vm/src/builtins/set.rs index 5582ff3323c..b1236e44e93 100644 --- a/crates/vm/src/builtins/set.rs +++ b/crates/vm/src/builtins/set.rs @@ -23,12 +23,13 @@ use crate::{ utils::collection_repr, vm::VirtualMachine, }; +use alloc::fmt; +use core::ops::Deref; use rustpython_common::{ atomic::{Ordering, PyAtomic, Radium}, hash, }; use std::sync::LazyLock; -use std::{fmt, ops::Deref}; pub type SetContentType = dict_inner::Dict<()>; @@ -50,7 +51,7 @@ impl PySet { fn fold_op( &self, - others: impl std::iter::Iterator, + others: impl core::iter::Iterator, op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult, vm: &VirtualMachine, ) -> PyResult { @@ -68,7 +69,7 @@ impl PySet { Ok(Self { inner: self .inner - .fold_op(std::iter::once(other.into_iterable(vm)?), op, vm)?, + .fold_op(core::iter::once(other.into_iterable(vm)?), op, vm)?, }) } } @@ -111,7 +112,7 @@ impl PyFrozenSet { fn fold_op( &self, - others: impl std::iter::Iterator, + others: impl core::iter::Iterator, op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult, vm: &VirtualMachine, ) -> PyResult { @@ -130,7 +131,7 @@ impl PyFrozenSet { Ok(Self { inner: self .inner - .fold_op(std::iter::once(other.into_iterable(vm)?), op, vm)?, + .fold_op(core::iter::once(other.into_iterable(vm)?), op, vm)?, ..Default::default() }) } @@ -191,7 +192,7 @@ impl PySetInner { fn fold_op( &self, - others: impl std::iter::Iterator, + others: impl core::iter::Iterator, op: fn(&Self, O, &VirtualMachine) -> PyResult, vm: &VirtualMachine, ) -> PyResult { @@ -352,7 +353,7 @@ impl PySetInner { fn update( &self, - others: impl std::iter::Iterator, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult<()> { for iterable in others { @@ -395,7 +396,7 @@ impl PySetInner { fn intersection_update( &self, - others: impl std::iter::Iterator, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult<()> { let temp_inner = self.fold_op(others, Self::intersection, vm)?; @@ -408,7 +409,7 @@ impl PySetInner { fn difference_update( &self, - others: impl std::iter::Iterator, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult<()> { for iterable in others { @@ -422,7 +423,7 @@ impl PySetInner { fn symmetric_difference_update( &self, - others: impl std::iter::Iterator, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult<()> { for iterable in others { @@ -539,7 +540,7 @@ impl PySet { #[pymethod] fn __sizeof__(&self) -> usize { - std::mem::size_of::() + self.inner.sizeof() + core::mem::size_of::() + self.inner.sizeof() } #[pymethod] @@ -731,7 +732,7 @@ impl PySet { #[pymethod] fn __iand__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { zelf.inner - .intersection_update(std::iter::once(set.into_iterable(vm)?), vm)?; + .intersection_update(core::iter::once(set.into_iterable(vm)?), vm)?; Ok(zelf) } @@ -978,7 +979,7 @@ impl PyFrozenSet { #[pymethod] fn __sizeof__(&self) -> usize { - std::mem::size_of::() + self.inner.sizeof() + core::mem::size_of::() + self.inner.sizeof() } #[pymethod] @@ -1258,8 +1259,8 @@ impl AnySet { fn into_iterable_iter( self, vm: &VirtualMachine, - ) -> PyResult> { - Ok(std::iter::once(self.into_iterable(vm)?)) + ) -> PyResult> { + Ok(core::iter::once(self.into_iterable(vm)?)) } fn as_inner(&self) -> &PySetInner { diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index fa35c1725d4..0357e81b365 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -24,8 +24,10 @@ use crate::{ PyComparisonOp, Representable, SelfIter, }, }; +use alloc::{borrow::Cow, fmt}; use ascii::{AsciiChar, AsciiStr, AsciiString}; use bstr::ByteSlice; +use core::{char, mem, ops::Range}; use itertools::Itertools; use num_traits::ToPrimitive; use rustpython_common::{ @@ -37,8 +39,7 @@ use rustpython_common::{ str::DeduceStrKind, wtf8::{CodePoint, Wtf8, Wtf8Buf, Wtf8Chunk}, }; -use std::{borrow::Cow, char, fmt, ops::Range}; -use std::{mem, sync::LazyLock}; +use std::sync::LazyLock; use unic_ucd_bidi::BidiClass; use unic_ucd_category::GeneralCategory; use unic_ucd_ident::{is_xid_continue, is_xid_start}; @@ -191,8 +192,8 @@ impl From for PyStr { } } -impl<'a> From> for PyStr { - fn from(s: std::borrow::Cow<'a, str>) -> Self { +impl<'a> From> for PyStr { + fn from(s: alloc::borrow::Cow<'a, str>) -> Self { s.into_owned().into() } } @@ -632,7 +633,7 @@ impl PyStr { #[pymethod] fn __sizeof__(&self) -> usize { - std::mem::size_of::() + self.byte_len() * std::mem::size_of::() + core::mem::size_of::() + self.byte_len() * core::mem::size_of::() } #[pymethod(name = "__rmul__")] @@ -1045,7 +1046,7 @@ impl PyStr { #[pymethod] fn replace(&self, args: ReplaceArgs) -> Wtf8Buf { - use std::cmp::Ordering; + use core::cmp::Ordering; let s = self.as_wtf8(); let ReplaceArgs { old, new, count } = args; @@ -1361,7 +1362,7 @@ impl PyStr { let ch = bigint .as_bigint() .to_u32() - .and_then(std::char::from_u32) + .and_then(core::char::from_u32) .ok_or_else(|| { vm.new_value_error("character mapping must be in range(0x110000)") })?; @@ -1494,7 +1495,7 @@ impl PyRef { } struct CharLenStr<'a>(&'a str, usize); -impl std::ops::Deref for CharLenStr<'_> { +impl core::ops::Deref for CharLenStr<'_> { type Target = str; fn deref(&self) -> &Self::Target { @@ -1705,7 +1706,7 @@ pub struct FindArgs { } impl FindArgs { - fn get_value(self, len: usize) -> (PyStrRef, std::ops::Range) { + fn get_value(self, len: usize) -> (PyStrRef, core::ops::Range) { let range = adjust_indices(self.start, self.end, len); (self.sub, range) } @@ -1945,8 +1946,8 @@ impl PyPayload for PyUtf8Str { ctx.types.str_type } - fn payload_type_id() -> std::any::TypeId { - std::any::TypeId::of::() + fn payload_type_id() -> core::any::TypeId { + core::any::TypeId::of::() } fn validate_downcastable_from(obj: &PyObject) -> bool { @@ -2005,8 +2006,8 @@ impl From for PyUtf8Str { } } -impl<'a> From> for PyUtf8Str { - fn from(s: std::borrow::Cow<'a, str>) -> Self { +impl<'a> From> for PyUtf8Str { + fn from(s: alloc::borrow::Cow<'a, str>) -> Self { s.into_owned().into() } } @@ -2128,11 +2129,11 @@ impl AnyStr for str { Self::chars(self) } - fn get_bytes(&self, range: std::ops::Range) -> &Self { + fn get_bytes(&self, range: core::ops::Range) -> &Self { &self[range] } - fn get_chars(&self, range: std::ops::Range) -> &Self { + fn get_chars(&self, range: core::ops::Range) -> &Self { rustpython_common::str::get_chars(self, range) } @@ -2239,11 +2240,11 @@ impl AnyStr for Wtf8 { self.code_points() } - fn get_bytes(&self, range: std::ops::Range) -> &Self { + fn get_bytes(&self, range: core::ops::Range) -> &Self { &self[range] } - fn get_chars(&self, range: std::ops::Range) -> &Self { + fn get_chars(&self, range: core::ops::Range) -> &Self { rustpython_common::str::get_codepoints(self, range) } @@ -2361,11 +2362,11 @@ impl AnyStr for AsciiStr { self.chars() } - fn get_bytes(&self, range: std::ops::Range) -> &Self { + fn get_bytes(&self, range: core::ops::Range) -> &Self { &self[range] } - fn get_chars(&self, range: std::ops::Range) -> &Self { + fn get_chars(&self, range: core::ops::Range) -> &Self { &self[range] } @@ -2436,8 +2437,8 @@ impl PyStrInterned { } } -impl std::fmt::Display for PyStrInterned { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for PyStrInterned { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.data.fmt(f) } } diff --git a/crates/vm/src/builtins/traceback.rs b/crates/vm/src/builtins/traceback.rs index 6bf4070c9b5..84493e7125f 100644 --- a/crates/vm/src/builtins/traceback.rs +++ b/crates/vm/src/builtins/traceback.rs @@ -81,7 +81,7 @@ impl Constructor for PyTraceback { impl PyTracebackRef { pub fn iter(&self) -> impl Iterator { - std::iter::successors(Some(self.clone()), |tb| tb.next.lock().clone()) + core::iter::successors(Some(self.clone()), |tb| tb.next.lock().clone()) } } diff --git a/crates/vm/src/builtins/tuple.rs b/crates/vm/src/builtins/tuple.rs index 13335428b35..70e4e20e405 100644 --- a/crates/vm/src/builtins/tuple.rs +++ b/crates/vm/src/builtins/tuple.rs @@ -21,7 +21,8 @@ use crate::{ utils::collection_repr, vm::VirtualMachine, }; -use std::{fmt, sync::LazyLock}; +use alloc::fmt; +use std::sync::LazyLock; #[pyclass(module = false, name = "tuple", traverse)] pub struct PyTuple { @@ -158,7 +159,7 @@ impl AsRef<[R]> for PyTuple { } } -impl std::ops::Deref for PyTuple { +impl core::ops::Deref for PyTuple { type Target = [R]; fn deref(&self) -> &[R] { @@ -166,18 +167,18 @@ impl std::ops::Deref for PyTuple { } } -impl<'a, R> std::iter::IntoIterator for &'a PyTuple { +impl<'a, R> core::iter::IntoIterator for &'a PyTuple { type Item = &'a R; - type IntoIter = std::slice::Iter<'a, R>; + type IntoIter = core::slice::Iter<'a, R>; fn into_iter(self) -> Self::IntoIter { self.iter() } } -impl<'a, R> std::iter::IntoIterator for &'a Py> { +impl<'a, R> core::iter::IntoIterator for &'a Py> { type Item = &'a R; - type IntoIter = std::slice::Iter<'a, R>; + type IntoIter = core::slice::Iter<'a, R>; fn into_iter(self) -> Self::IntoIter { self.iter() @@ -200,7 +201,7 @@ impl PyTuple { } #[inline] - pub fn iter(&self) -> std::slice::Iter<'_, R> { + pub fn iter(&self) -> core::slice::Iter<'_, R> { self.elements.iter() } } @@ -249,15 +250,15 @@ impl PyTuple> { // SAFETY: PyRef has the same layout as PyObjectRef unsafe { let elements: Vec = - std::mem::transmute::>, Vec>(elements); + core::mem::transmute::>, Vec>(elements); let tuple = PyTuple::::new_ref(elements, ctx); - std::mem::transmute::, PyRef>(tuple) + core::mem::transmute::, PyRef>(tuple) } } } #[pyclass( - itemsize = std::mem::size_of::(), + itemsize = core::mem::size_of::(), flags(BASETYPE, SEQUENCE, _MATCH_SELF), with(AsMapping, AsSequence, Hashable, Comparable, Iterable, Constructor, Representable) )] @@ -489,21 +490,21 @@ impl PyRef> { as TransmuteFromObject>::check(vm, elem)?; } // SAFETY: We just verified all elements are of type T - Ok(unsafe { std::mem::transmute::>>>(self) }) + Ok(unsafe { core::mem::transmute::>>>(self) }) } } impl PyRef>> { pub fn into_untyped(self) -> PyRef { // SAFETY: PyTuple> has the same layout as PyTuple - unsafe { std::mem::transmute::>(self) } + unsafe { core::mem::transmute::>(self) } } } impl Py>> { pub fn as_untyped(&self) -> &Py { // SAFETY: PyTuple> has the same layout as PyTuple - unsafe { std::mem::transmute::<&Self, &Py>(self) } + unsafe { core::mem::transmute::<&Self, &Py>(self) } } } diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index e807d3f4f8e..3eca5edc478 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -29,10 +29,11 @@ use crate::{ Representable, SLOT_DEFS, SetAttr, TypeDataRef, TypeDataRefMut, TypeDataSlot, }, }; +use core::{any::Any, borrow::Borrow, ops::Deref, pin::Pin, ptr::NonNull}; use indexmap::{IndexMap, map::Entry}; use itertools::Itertools; use num_traits::ToPrimitive; -use std::{any::Any, borrow::Borrow, collections::HashSet, ops::Deref, pin::Pin, ptr::NonNull}; +use std::collections::HashSet; #[pyclass(module = false, name = "type", traverse = "manual")] pub struct PyType { @@ -118,14 +119,14 @@ unsafe impl Traverse for PyAttributes { } } -impl std::fmt::Display for PyType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Display::fmt(&self.name(), f) +impl core::fmt::Display for PyType { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::Display::fmt(&self.name(), f) } } -impl std::fmt::Debug for PyType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyType { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "[PyType {}]", &self.name()) } } @@ -368,7 +369,7 @@ impl PyType { // Inherit SEQUENCE and MAPPING flags from base class // For static types, we only have a single base - Self::inherit_patma_flags(&mut slots, std::slice::from_ref(&base)); + Self::inherit_patma_flags(&mut slots, core::slice::from_ref(&base)); if slots.basicsize == 0 { slots.basicsize = base.slots.basicsize; @@ -549,7 +550,7 @@ impl PyType { // Gather all members here: let mut attributes = PyAttributes::default(); - for bc in std::iter::once(self) + for bc in core::iter::once(self) .chain(self.mro.read().iter().map(|cls| -> &Self { cls })) .rev() { @@ -667,21 +668,21 @@ impl Py { where F: Fn(&Self) -> R, { - std::iter::once(self) + core::iter::once(self) .chain(self.mro.read().iter().map(|x| x.deref())) .map(f) .collect() } pub fn mro_collect(&self) -> Vec> { - std::iter::once(self) + core::iter::once(self) .chain(self.mro.read().iter().map(|x| x.deref())) .map(|x| x.to_owned()) .collect() } pub fn iter_base_chain(&self) -> impl Iterator { - std::iter::successors(Some(self), |cls| cls.base.as_deref()) + core::iter::successors(Some(self), |cls| cls.base.as_deref()) } pub fn extend_methods(&'static self, method_defs: &'static [PyMethodDef], ctx: &Context) { @@ -846,7 +847,7 @@ impl PyType { // then drop the old value after releasing the lock let _old_qualname = { let mut qualname_guard = heap_type.qualname.write(); - std::mem::replace(&mut *qualname_guard, str_value) + core::mem::replace(&mut *qualname_guard, str_value) }; // old_qualname is dropped here, outside the lock scope @@ -1012,7 +1013,7 @@ impl PyType { // then drop the old value after releasing the lock (similar to CPython's Py_SETREF) let _old_name = { let mut name_guard = self.heaptype_ext.as_ref().unwrap().name.write(); - std::mem::replace(&mut *name_guard, name) + core::mem::replace(&mut *name_guard, name) }; // old_name is dropped here, outside the lock scope diff --git a/crates/vm/src/builtins/union.rs b/crates/vm/src/builtins/union.rs index 83e1316d027..0342442b83d 100644 --- a/crates/vm/src/builtins/union.rs +++ b/crates/vm/src/builtins/union.rs @@ -11,7 +11,7 @@ use crate::{ stdlib::typing::TypeAliasType, types::{AsMapping, AsNumber, Comparable, GetAttr, Hashable, PyComparisonOp, Representable}, }; -use std::fmt; +use alloc::fmt; use std::sync::LazyLock; const CLS_ATTRS: &[&str] = &["__module__"]; diff --git a/crates/vm/src/bytes_inner.rs b/crates/vm/src/bytes_inner.rs index 8593f16fcd9..bb5db442c35 100644 --- a/crates/vm/src/bytes_inner.rs +++ b/crates/vm/src/bytes_inner.rs @@ -151,7 +151,7 @@ impl ByteInnerFindOptions { self, len: usize, vm: &VirtualMachine, - ) -> PyResult<(Vec, std::ops::Range)> { + ) -> PyResult<(Vec, core::ops::Range)> { let sub = match self.sub { Either::A(v) => v.elements.to_vec(), Either::B(int) => vec![int.as_bigint().byte_or(vm)?], @@ -719,7 +719,7 @@ impl PyBytesInner { // len(self)>=1, from="", len(to)>=1, max_count>=1 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 count = max_count.map_or(place_count, |v| core::cmp::min(v, place_count)) - 1; let capacity = self.elements.len() + count * to.len(); let mut result = Vec::with_capacity(capacity); let to_slice = to.elements.as_slice(); @@ -952,7 +952,7 @@ where fn count_substring(haystack: &[u8], needle: &[u8], max_count: Option) -> usize { let substrings = haystack.find_iter(needle); if let Some(max_count) = max_count { - std::cmp::min(substrings.take(max_count).count(), max_count) + core::cmp::min(substrings.take(max_count).count(), max_count) } else { substrings.count() } @@ -1025,11 +1025,11 @@ impl AnyStr for [u8] { self.iter().copied() } - fn get_bytes(&self, range: std::ops::Range) -> &Self { + fn get_bytes(&self, range: core::ops::Range) -> &Self { &self[range] } - fn get_chars(&self, range: std::ops::Range) -> &Self { + fn get_chars(&self, range: core::ops::Range) -> &Self { &self[range] } @@ -1120,7 +1120,7 @@ fn hex_impl(bytes: &[u8], sep: u8, bytes_per_sep: isize) -> String { let len = bytes.len(); let buf = if bytes_per_sep < 0 { - let bytes_per_sep = std::cmp::min(len, (-bytes_per_sep) as usize); + let bytes_per_sep = core::cmp::min(len, (-bytes_per_sep) as usize); let chunks = (len - 1) / bytes_per_sep; let chunked = chunks * bytes_per_sep; let unchunked = len - chunked; @@ -1139,7 +1139,7 @@ fn hex_impl(bytes: &[u8], sep: u8, bytes_per_sep: isize) -> String { hex::encode_to_slice(&bytes[chunked..], &mut buf[j..j + unchunked * 2]).unwrap(); buf } else { - let bytes_per_sep = std::cmp::min(len, bytes_per_sep as usize); + let bytes_per_sep = core::cmp::min(len, bytes_per_sep as usize); let chunks = (len - 1) / bytes_per_sep; let chunked = chunks * bytes_per_sep; let unchunked = len - chunked; diff --git a/crates/vm/src/cformat.rs b/crates/vm/src/cformat.rs index efb3cb2acc9..939b1c7760f 100644 --- a/crates/vm/src/cformat.rs +++ b/crates/vm/src/cformat.rs @@ -342,7 +342,7 @@ pub(crate) fn cformat_bytes( let values = if let Some(tup) = values_obj.downcast_ref::() { tup.as_slice() } else { - std::slice::from_ref(&values_obj) + core::slice::from_ref(&values_obj) }; let mut value_iter = values.iter(); @@ -435,7 +435,7 @@ pub(crate) fn cformat_string( let values = if let Some(tup) = values_obj.downcast_ref::() { tup.as_slice() } else { - std::slice::from_ref(&values_obj) + core::slice::from_ref(&values_obj) }; let mut value_iter = values.iter(); diff --git a/crates/vm/src/class.rs b/crates/vm/src/class.rs index ce41abcc60b..98dc6fd2ed2 100644 --- a/crates/vm/src/class.rs +++ b/crates/vm/src/class.rs @@ -169,7 +169,7 @@ pub trait PyClassImpl: PyClassDef { // Exception: object itself should have __new__ in its dict if let Some(slot_new) = class.slots.new.load() { let object_new = ctx.types.object_type.slots.new.load(); - let is_object_itself = std::ptr::eq(class, ctx.types.object_type); + let is_object_itself = core::ptr::eq(class, ctx.types.object_type); let is_inherited_from_object = !is_object_itself && object_new.is_some_and(|obj_new| slot_new as usize == obj_new as usize); @@ -203,7 +203,7 @@ pub trait PyClassImpl: PyClassDef { Self::extend_class(ctx, unsafe { // typ will be saved in static_cell let r: &Py = &typ; - let r: &'static Py = std::mem::transmute(r); + let r: &'static Py = core::mem::transmute(r); r }); typ diff --git a/crates/vm/src/codecs.rs b/crates/vm/src/codecs.rs index 2edb67b497b..3241dee4981 100644 --- a/crates/vm/src/codecs.rs +++ b/crates/vm/src/codecs.rs @@ -16,12 +16,10 @@ use crate::{ convert::ToPyObject, function::{ArgBytesLike, PyMethodDef}, }; +use alloc::borrow::Cow; +use core::ops::{self, Range}; use once_cell::unsync::OnceCell; -use std::{ - borrow::Cow, - collections::HashMap, - ops::{self, Range}, -}; +use std::collections::HashMap; pub struct CodecsRegistry { inner: PyRwLock, diff --git a/crates/vm/src/convert/try_from.rs b/crates/vm/src/convert/try_from.rs index 4f921e9c5de..ceb7d003e9b 100644 --- a/crates/vm/src/convert/try_from.rs +++ b/crates/vm/src/convert/try_from.rs @@ -122,7 +122,7 @@ impl<'a, T: PyPayload> TryFromBorrowedObject<'a> for &'a Py { } } -impl TryFromObject for std::time::Duration { +impl TryFromObject for core::time::Duration { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { if let Some(float) = obj.downcast_ref::() { let f = float.to_f64(); diff --git a/crates/vm/src/dict_inner.rs b/crates/vm/src/dict_inner.rs index 02e237afb00..d57f8be0fe7 100644 --- a/crates/vm/src/dict_inner.rs +++ b/crates/vm/src/dict_inner.rs @@ -16,8 +16,9 @@ use crate::{ }, object::{Traverse, TraverseFn}, }; +use alloc::fmt; +use core::{mem::size_of, 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 @@ -281,7 +282,7 @@ impl Dict { continue; }; if entry.index == index_index { - let removed = std::mem::replace(&mut entry.value, value); + let removed = core::mem::replace(&mut entry.value, value); // defer dec RC break Some(removed); } else { @@ -357,7 +358,7 @@ impl Dict { inner.used = 0; inner.filled = 0; // defer dec rc - std::mem::take(&mut inner.entries) + core::mem::take(&mut inner.entries) }; } @@ -633,7 +634,7 @@ impl Dict { // returns Err(()) if changed since lookup fn pop_inner(&self, lookup: LookupResult) -> PopInnerResult { - self.pop_inner_if(lookup, |_| Ok::<_, std::convert::Infallible>(true)) + self.pop_inner_if(lookup, |_| Ok::<_, core::convert::Infallible>(true)) .unwrap_or_else(|x| match x {}) } diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index 4e8b572e457..b1a654d58c4 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -33,8 +33,8 @@ unsafe impl Traverse for PyBaseException { } } -impl std::fmt::Debug for PyBaseException { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyBaseException { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { // TODO: implement more detailed, non-recursive Debug formatter f.write_str("PyBaseException") } @@ -1173,7 +1173,7 @@ pub fn cstring_error(vm: &VirtualMachine) -> PyBaseExceptionRef { vm.new_value_error("embedded null character") } -impl ToPyException for std::ffi::NulError { +impl ToPyException for alloc::ffi::NulError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { cstring_error(vm) } @@ -1604,8 +1604,8 @@ pub(super) mod types { } } - impl std::fmt::Debug for PyOSError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for PyOSError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyOSError").finish_non_exhaustive() } } diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index 3f470e5453f..6acf0e84795 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -18,13 +18,14 @@ use crate::{ types::PyTypeFlags, vm::{Context, PyMethod}, }; +use alloc::fmt; +use core::iter::zip; +#[cfg(feature = "threading")] +use core::sync::atomic; use indexmap::IndexMap; use itertools::Itertools; use rustpython_common::{boxvec::BoxVec, lock::PyMutex, wtf8::Wtf8Buf}; use rustpython_compiler_core::SourceLocation; -#[cfg(feature = "threading")] -use std::sync::atomic; -use std::{fmt, iter::zip}; #[derive(Clone, Debug)] struct Block { @@ -91,7 +92,7 @@ struct FrameState { #[cfg(feature = "threading")] type Lasti = atomic::AtomicU32; #[cfg(not(feature = "threading"))] -type Lasti = std::cell::Cell; +type Lasti = core::cell::Cell; #[pyclass(module = false, name = "frame")] pub struct Frame { @@ -142,7 +143,7 @@ impl Frame { func_obj: Option, vm: &VirtualMachine, ) -> Self { - let cells_frees = std::iter::repeat_with(|| PyCell::default().into_ref(&vm.ctx)) + let cells_frees = core::iter::repeat_with(|| PyCell::default().into_ref(&vm.ctx)) .take(code.cellvars.len()) .chain(closure.iter().cloned()) .collect(); @@ -189,7 +190,7 @@ impl Frame { let locals = &self.locals; let code = &**self.code; let map = &code.varnames; - let j = std::cmp::min(map.len(), code.varnames.len()); + let j = core::cmp::min(map.len(), code.varnames.len()); if !code.varnames.is_empty() { let fastlocals = self.fastlocals.lock(); for (&k, v) in zip(&map[..j], &**fastlocals) { @@ -2243,14 +2244,14 @@ impl ExecutingFrame<'_> { } })?; let msg = match elements.len().cmp(&(size as usize)) { - std::cmp::Ordering::Equal => { + core::cmp::Ordering::Equal => { self.state.stack.extend(elements.into_iter().rev()); return Ok(None); } - std::cmp::Ordering::Greater => { + core::cmp::Ordering::Greater => { format!("too many values to unpack (expected {size})") } - std::cmp::Ordering::Less => format!( + core::cmp::Ordering::Less => format!( "not enough values to unpack (expected {}, got {})", size, elements.len() @@ -2525,7 +2526,7 @@ impl ExecutingFrame<'_> { #[inline] fn replace_top(&mut self, mut top: PyObjectRef) -> PyObjectRef { let last = self.state.stack.last_mut().unwrap(); - std::mem::swap(&mut top, last); + core::mem::swap(&mut top, last); top } @@ -2561,12 +2562,12 @@ impl fmt::Debug for Frame { if elem.downcastable::() { s.push_str("\n > {frame}"); } else { - std::fmt::write(&mut s, format_args!("\n > {elem:?}")).unwrap(); + core::fmt::write(&mut s, format_args!("\n > {elem:?}")).unwrap(); } s }); let block_str = state.blocks.iter().fold(String::new(), |mut s, elem| { - std::fmt::write(&mut s, format_args!("\n > {elem:?}")).unwrap(); + core::fmt::write(&mut s, format_args!("\n > {elem:?}")).unwrap(); s }); // TODO: fix this up diff --git a/crates/vm/src/function/argument.rs b/crates/vm/src/function/argument.rs index d657ff6be8f..a4877cf4042 100644 --- a/crates/vm/src/function/argument.rs +++ b/crates/vm/src/function/argument.rs @@ -4,9 +4,9 @@ use crate::{ convert::ToPyObject, object::{Traverse, TraverseFn}, }; +use core::ops::RangeInclusive; use indexmap::IndexMap; use itertools::Itertools; -use std::ops::RangeInclusive; pub trait IntoFuncArgs: Sized { fn into_args(self, vm: &VirtualMachine) -> FuncArgs; @@ -100,7 +100,7 @@ impl From for FuncArgs { impl FromArgs for FuncArgs { fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result { - Ok(std::mem::take(args)) + Ok(core::mem::take(args)) } } @@ -424,7 +424,7 @@ impl PosArgs { self.0 } - pub fn iter(&self) -> std::slice::Iter<'_, T> { + pub fn iter(&self) -> core::slice::Iter<'_, T> { self.0.iter() } } @@ -469,7 +469,7 @@ where impl IntoIterator for PosArgs { type Item = T; - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() diff --git a/crates/vm/src/function/builtin.rs b/crates/vm/src/function/builtin.rs index 1a91e4344ba..06fd6a44f54 100644 --- a/crates/vm/src/function/builtin.rs +++ b/crates/vm/src/function/builtin.rs @@ -3,7 +3,7 @@ use crate::{ Py, PyPayload, PyRef, PyResult, VirtualMachine, convert::ToPyResult, object::PyThreadingConstraint, }; -use std::marker::PhantomData; +use core::marker::PhantomData; /// A built-in Python function. // PyCFunction in CPython @@ -54,14 +54,14 @@ const fn zst_ref_out_of_thin_air(x: T) -> &'static T { // if T is zero-sized, there's no issue forgetting it - even if it does have a Drop impl, it // would never get called anyway if we consider this semantically a Box::leak(Box::new(x))-type // operation. if T isn't zero-sized, we don't have to worry about it because we'll fail to compile. - std::mem::forget(x); + core::mem::forget(x); const { - if std::mem::size_of::() != 0 { + if core::mem::size_of::() != 0 { panic!("can't use a non-zero-sized type here") } // SAFETY: we just confirmed that T is zero-sized, so we can // pull a value of it out of thin air. - unsafe { std::ptr::NonNull::::dangling().as_ref() } + unsafe { core::ptr::NonNull::::dangling().as_ref() } } } diff --git a/crates/vm/src/function/either.rs b/crates/vm/src/function/either.rs index 8700c6150db..9ee7f028bd2 100644 --- a/crates/vm/src/function/either.rs +++ b/crates/vm/src/function/either.rs @@ -1,7 +1,7 @@ use crate::{ AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, convert::ToPyObject, }; -use std::borrow::Borrow; +use core::borrow::Borrow; pub enum Either { A(A), diff --git a/crates/vm/src/function/fspath.rs b/crates/vm/src/function/fspath.rs index 44d41ab7632..7d3a0dcbbd5 100644 --- a/crates/vm/src/function/fspath.rs +++ b/crates/vm/src/function/fspath.rs @@ -5,7 +5,8 @@ use crate::{ function::PyStr, protocol::PyBuffer, }; -use std::{borrow::Cow, ffi::OsStr, path::PathBuf}; +use alloc::borrow::Cow; +use std::{ffi::OsStr, path::PathBuf}; /// Helper to implement os.fspath() #[derive(Clone)] @@ -111,8 +112,8 @@ impl FsPath { Ok(path) } - pub fn to_cstring(&self, vm: &VirtualMachine) -> PyResult { - std::ffi::CString::new(self.as_bytes()).map_err(|e| e.into_pyexception(vm)) + pub fn to_cstring(&self, vm: &VirtualMachine) -> PyResult { + alloc::ffi::CString::new(self.as_bytes()).map_err(|e| e.into_pyexception(vm)) } #[cfg(windows)] diff --git a/crates/vm/src/function/method.rs b/crates/vm/src/function/method.rs index 5e109176c5e..6440fd801fc 100644 --- a/crates/vm/src/function/method.rs +++ b/crates/vm/src/function/method.rs @@ -251,14 +251,14 @@ impl PyMethodDef { } } -impl std::fmt::Debug for PyMethodDef { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyMethodDef { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyMethodDef") .field("name", &self.name) .field( "func", &(unsafe { - std::mem::transmute::<&dyn PyNativeFn, [usize; 2]>(self.func)[1] as *const u8 + core::mem::transmute::<&dyn PyNativeFn, [usize; 2]>(self.func)[1] as *const u8 }), ) .field("flags", &self.flags) diff --git a/crates/vm/src/function/number.rs b/crates/vm/src/function/number.rs index 7bb37b8f549..fb872cc48fd 100644 --- a/crates/vm/src/function/number.rs +++ b/crates/vm/src/function/number.rs @@ -1,9 +1,9 @@ use super::argument::OptionalArg; use crate::{AsObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::PyIntRef}; +use core::ops::Deref; use malachite_bigint::BigInt; use num_complex::Complex64; use num_traits::PrimInt; -use std::ops::Deref; /// A Python complex-like object. /// @@ -62,7 +62,7 @@ pub struct ArgIntoFloat { impl ArgIntoFloat { pub fn vec_into_f64(v: Vec) -> Vec { // TODO: Vec::into_raw_parts once stabilized - let mut v = std::mem::ManuallyDrop::new(v); + let mut v = core::mem::ManuallyDrop::new(v); let (p, l, c) = (v.as_mut_ptr(), v.len(), v.capacity()); // SAFETY: IntoPyFloat is repr(transparent) over f64 unsafe { Vec::from_raw_parts(p.cast(), l, c) } diff --git a/crates/vm/src/function/protocol.rs b/crates/vm/src/function/protocol.rs index a87ef339edd..94bdd3027eb 100644 --- a/crates/vm/src/function/protocol.rs +++ b/crates/vm/src/function/protocol.rs @@ -7,7 +7,7 @@ use crate::{ protocol::{PyIter, PyIterIter, PyMapping}, types::GenericMethod, }; -use std::{borrow::Borrow, marker::PhantomData, ops::Deref}; +use core::{borrow::Borrow, marker::PhantomData, ops::Deref}; #[derive(Clone, Traverse)] pub struct ArgCallable { @@ -24,8 +24,8 @@ impl ArgCallable { } } -impl std::fmt::Debug for ArgCallable { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for ArgCallable { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("ArgCallable") .field("obj", &self.obj) .field("call", &format!("{:08x}", self.call as usize)) @@ -203,7 +203,7 @@ impl ArgSequence { } } -impl std::ops::Deref for ArgSequence { +impl core::ops::Deref for ArgSequence { type Target = [T]; #[inline(always)] fn deref(&self) -> &[T] { @@ -213,14 +213,14 @@ impl std::ops::Deref for ArgSequence { impl<'a, T> IntoIterator for &'a ArgSequence { type Item = &'a T; - type IntoIter = std::slice::Iter<'a, T>; + type IntoIter = core::slice::Iter<'a, T>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl IntoIterator for ArgSequence { type Item = T; - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } diff --git a/crates/vm/src/intern.rs b/crates/vm/src/intern.rs index a5b2a798d53..a50b8871cb9 100644 --- a/crates/vm/src/intern.rs +++ b/crates/vm/src/intern.rs @@ -6,10 +6,8 @@ use crate::{ common::lock::PyRwLock, convert::ToPyObject, }; -use std::{ - borrow::{Borrow, ToOwned}, - ops::Deref, -}; +use alloc::borrow::ToOwned; +use core::{borrow::Borrow, ops::Deref}; #[derive(Debug)] pub struct StringPool { @@ -86,8 +84,8 @@ pub struct CachedPyStrRef { inner: PyRefExact, } -impl std::hash::Hash for CachedPyStrRef { - fn hash(&self, state: &mut H) { +impl core::hash::Hash for CachedPyStrRef { + fn hash(&self, state: &mut H) { self.inner.as_wtf8().hash(state) } } @@ -100,7 +98,7 @@ impl PartialEq for CachedPyStrRef { impl Eq for CachedPyStrRef {} -impl std::borrow::Borrow for CachedPyStrRef { +impl core::borrow::Borrow for CachedPyStrRef { #[inline] fn borrow(&self) -> &Wtf8 { self.as_wtf8() @@ -119,7 +117,7 @@ impl CachedPyStrRef { /// the given cache must be alive while returned reference is alive #[inline] const unsafe fn as_interned_str(&self) -> &'static PyStrInterned { - unsafe { std::mem::transmute_copy(self) } + unsafe { core::mem::transmute_copy(self) } } #[inline] @@ -135,7 +133,7 @@ pub struct PyInterned { impl PyInterned { #[inline] pub fn leak(cache: PyRef) -> &'static Self { - unsafe { std::mem::transmute(cache) } + unsafe { core::mem::transmute(cache) } } #[inline] @@ -163,9 +161,9 @@ impl Borrow for PyInterned { // NOTE: std::hash::Hash of Self and Self::Borrowed *must* be the same // This is ok only because PyObject doesn't implement Hash -impl std::hash::Hash for PyInterned { +impl core::hash::Hash for PyInterned { #[inline(always)] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.get_id().hash(state) } } @@ -188,15 +186,15 @@ impl Deref for PyInterned { impl PartialEq for PyInterned { #[inline(always)] fn eq(&self, other: &Self) -> bool { - std::ptr::eq(self, other) + core::ptr::eq(self, other) } } impl Eq for PyInterned {} -impl std::fmt::Debug for PyInterned { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(&**self, f)?; +impl core::fmt::Debug for PyInterned { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::Debug::fmt(&**self, f)?; write!(f, "@{:p}", self.as_ptr()) } } @@ -308,7 +306,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::<&Self, &PyInterned>(self) }) + Some(unsafe { core::mem::transmute::<&Self, &PyInterned>(self) }) } else { None } diff --git a/crates/vm/src/lib.rs b/crates/vm/src/lib.rs index f461c612955..3f0eee278a2 100644 --- a/crates/vm/src/lib.rs +++ b/crates/vm/src/lib.rs @@ -24,6 +24,7 @@ extern crate bitflags; #[macro_use] extern crate log; // extern crate env_logger; +extern crate alloc; #[macro_use] extern crate rustpython_derive; diff --git a/crates/vm/src/macros.rs b/crates/vm/src/macros.rs index 1284c202782..f5c912d89cf 100644 --- a/crates/vm/src/macros.rs +++ b/crates/vm/src/macros.rs @@ -146,8 +146,8 @@ macro_rules! match_class { }; (match ($obj:expr) { ref $binding:ident @ $class:ty => $expr:expr, $($rest:tt)* }) => { match $obj.downcast_ref::<$class>() { - ::std::option::Option::Some($binding) => $expr, - ::std::option::Option::None => $crate::match_class!(match ($obj) { $($rest)* }), + core::option::Option::Some($binding) => $expr, + core::option::Option::None => $crate::match_class!(match ($obj) { $($rest)* }), } }; diff --git a/crates/vm/src/object/core.rs b/crates/vm/src/object/core.rs index d52a33884ce..cee3fac266e 100644 --- a/crates/vm/src/object/core.rs +++ b/crates/vm/src/object/core.rs @@ -31,11 +31,13 @@ use crate::{ object::traverse::{MaybeTraverse, Traverse, TraverseFn}, }; use itertools::Itertools; -use std::{ + +use alloc::fmt; + +use core::{ any::TypeId, borrow::Borrow, cell::UnsafeCell, - fmt, marker::PhantomData, mem::ManuallyDrop, ops::Deref, @@ -82,7 +84,7 @@ pub(super) struct Erased; pub(super) unsafe fn drop_dealloc_obj(x: *mut PyObject) { drop(unsafe { Box::from_raw(x as *mut PyInner) }); } -pub(super) unsafe fn debug_obj( +pub(super) unsafe fn debug_obj( x: &PyObject, f: &mut fmt::Formatter<'_>, ) -> fmt::Result { @@ -114,7 +116,7 @@ pub(super) struct PyInner { pub(super) payload: T, } -pub(crate) const SIZEOF_PYOBJECT_HEAD: usize = std::mem::size_of::>(); +pub(crate) const SIZEOF_PYOBJECT_HEAD: usize = core::mem::size_of::>(); impl fmt::Debug for PyInner { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -376,7 +378,7 @@ impl PyWeak { let node_ptr = unsafe { NonNull::new_unchecked(py_inner as *mut Py) }; // the list doesn't have ownership over its PyRef! we're being dropped // right now so that should be obvious!! - std::mem::forget(unsafe { guard.list.remove(node_ptr) }); + core::mem::forget(unsafe { guard.list.remove(node_ptr) }); guard.ref_count -= 1; if Some(node_ptr) == guard.generic_weakref { guard.generic_weakref = None; @@ -438,11 +440,11 @@ impl InstanceDict { #[inline] pub fn replace(&self, d: PyDictRef) -> PyDictRef { - std::mem::replace(&mut self.d.write(), d) + core::mem::replace(&mut self.d.write(), d) } } -impl PyInner { +impl PyInner { fn new(payload: T, typ: PyTypeRef, dict: Option) -> Box { let member_count = typ.slots.member_count; Box::new(Self { @@ -453,7 +455,7 @@ impl PyInner { dict: dict.map(InstanceDict::new), weak_list: WeakRefList::new(), payload, - slots: std::iter::repeat_with(|| PyRwLock::new(None)) + slots: core::iter::repeat_with(|| PyRwLock::new(None)) .take(member_count) .collect_vec() .into_boxed_slice(), @@ -513,7 +515,7 @@ impl PyObjectRef { #[inline(always)] pub const fn into_raw(self) -> NonNull { let ptr = self.ptr; - std::mem::forget(self); + core::mem::forget(self); ptr } @@ -946,12 +948,12 @@ impl Borrow for Py { } } -impl std::hash::Hash for Py +impl core::hash::Hash for Py where - T: std::hash::Hash + PyPayload, + T: core::hash::Hash + PyPayload, { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.deref().hash(state) } } @@ -978,7 +980,7 @@ where } } -impl fmt::Debug for Py { +impl fmt::Debug for Py { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (**self).fmt(f) } @@ -1059,12 +1061,12 @@ impl PyRef { pub const fn leak(pyref: Self) -> &'static Py { let ptr = pyref.ptr; - std::mem::forget(pyref); + core::mem::forget(pyref); unsafe { ptr.as_ref() } } } -impl PyRef { +impl PyRef { #[inline(always)] pub fn new_ref(payload: T, typ: crate::builtins::PyTypeRef, dict: Option) -> Self { let inner = Box::into_raw(PyInner::new(payload, typ, dict)); @@ -1074,9 +1076,9 @@ impl PyRef { } } -impl PyRef +impl PyRef where - T::Base: std::fmt::Debug, + T::Base: core::fmt::Debug, { /// Converts this reference to the base type (ownership transfer). /// # Safety @@ -1086,7 +1088,7 @@ where let obj: PyObjectRef = self.into(); match obj.downcast() { Ok(base_ref) => base_ref, - Err(_) => unsafe { std::hint::unreachable_unchecked() }, + Err(_) => unsafe { core::hint::unreachable_unchecked() }, } } #[inline] @@ -1098,7 +1100,7 @@ where let obj: PyObjectRef = self.into(); match obj.downcast::() { Ok(upcast_ref) => upcast_ref, - Err(_) => unsafe { std::hint::unreachable_unchecked() }, + Err(_) => unsafe { core::hint::unreachable_unchecked() }, } } } @@ -1176,12 +1178,12 @@ impl Deref for PyRef { } } -impl std::hash::Hash for PyRef +impl core::hash::Hash for PyRef where - T: std::hash::Hash + PyPayload, + T: core::hash::Hash + PyPayload, { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.deref().hash(state) } } @@ -1230,10 +1232,10 @@ macro_rules! partially_init { $($uninit_field: unreachable!(),)* }}; } - let mut m = ::std::mem::MaybeUninit::<$ty>::uninit(); + let mut m = ::core::mem::MaybeUninit::<$ty>::uninit(); #[allow(unused_unsafe)] unsafe { - $(::std::ptr::write(&mut (*m.as_mut_ptr()).$init_field, $init_value);)* + $(::core::ptr::write(&mut (*m.as_mut_ptr()).$init_field, $init_value);)* } m }}; @@ -1241,7 +1243,7 @@ macro_rules! partially_init { pub(crate) fn init_type_hierarchy() -> (PyTypeRef, PyTypeRef, PyTypeRef) { use crate::{builtins::object, class::PyClassImpl}; - use std::mem::MaybeUninit; + use core::mem::MaybeUninit; // `type` inherits from `object` // and both `type` and `object are instances of `type`. diff --git a/crates/vm/src/object/ext.rs b/crates/vm/src/object/ext.rs index 88f5fdc66d7..c1a5f63f85e 100644 --- a/crates/vm/src/object/ext.rs +++ b/crates/vm/src/object/ext.rs @@ -12,9 +12,10 @@ use crate::{ convert::{IntoPyException, ToPyObject, ToPyResult, TryFromObject}, vm::Context, }; -use std::{ +use alloc::fmt; + +use core::{ borrow::Borrow, - fmt, marker::PhantomData, ops::Deref, ptr::{NonNull, null_mut}, @@ -108,7 +109,7 @@ impl AsRef> for PyExact { } } -impl std::borrow::ToOwned for PyExact { +impl alloc::borrow::ToOwned for PyExact { type Owned = PyRefExact; fn to_owned(&self) -> Self::Owned { @@ -581,7 +582,7 @@ impl ToPyObject for &PyObject { // explicitly implementing `ToPyObject`. impl ToPyObject for T where - T: PyPayload + std::fmt::Debug + Sized, + T: PyPayload + core::fmt::Debug + Sized, { #[inline(always)] fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { diff --git a/crates/vm/src/object/payload.rs b/crates/vm/src/object/payload.rs index 4b900b7caa1..3a2f42675f7 100644 --- a/crates/vm/src/object/payload.rs +++ b/crates/vm/src/object/payload.rs @@ -27,8 +27,8 @@ pub(crate) fn cold_downcast_type_error( pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { #[inline] - fn payload_type_id() -> std::any::TypeId { - std::any::TypeId::of::() + fn payload_type_id() -> core::any::TypeId { + core::any::TypeId::of::() } /// # Safety: this function should only be called if `payload_type_id` matches the type of `obj`. @@ -56,7 +56,7 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { #[inline] fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef where - Self: std::fmt::Debug, + Self: core::fmt::Debug, { self.into_ref(&vm.ctx).into() } @@ -64,7 +64,7 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { #[inline] fn _into_ref(self, cls: PyTypeRef, ctx: &Context) -> PyRef where - Self: std::fmt::Debug, + Self: core::fmt::Debug, { let dict = if cls.slots.flags.has_feature(PyTypeFlags::HAS_DICT) { Some(ctx.new_dict()) @@ -77,7 +77,7 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { #[inline] fn into_exact_ref(self, ctx: &Context) -> PyRefExact where - Self: std::fmt::Debug, + Self: core::fmt::Debug, { unsafe { // Self::into_ref() always returns exact typed PyRef @@ -88,7 +88,7 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { #[inline] fn into_ref(self, ctx: &Context) -> PyRef where - Self: std::fmt::Debug, + Self: core::fmt::Debug, { let cls = Self::class(ctx); self._into_ref(cls.to_owned(), ctx) @@ -97,7 +97,7 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { #[inline] fn into_ref_with_type(self, vm: &VirtualMachine, cls: PyTypeRef) -> PyResult> where - Self: std::fmt::Debug, + Self: core::fmt::Debug, { let exact_class = Self::class(&vm.ctx); if cls.fast_issubclass(exact_class) { @@ -138,11 +138,11 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { } pub trait PyObjectPayload: - PyPayload + std::any::Any + std::fmt::Debug + MaybeTraverse + PyThreadingConstraint + 'static + PyPayload + core::any::Any + core::fmt::Debug + MaybeTraverse + PyThreadingConstraint + 'static { } -impl PyObjectPayload for T {} +impl PyObjectPayload for T {} pub trait SlotOffset { fn offset() -> usize; diff --git a/crates/vm/src/object/traverse.rs b/crates/vm/src/object/traverse.rs index 31bee8becea..2ce0db41a5e 100644 --- a/crates/vm/src/object/traverse.rs +++ b/crates/vm/src/object/traverse.rs @@ -1,4 +1,4 @@ -use std::ptr::NonNull; +use core::ptr::NonNull; use rustpython_common::lock::{PyMutex, PyRwLock}; diff --git a/crates/vm/src/object/traverse_object.rs b/crates/vm/src/object/traverse_object.rs index 281b0e56eb5..075ce5b9513 100644 --- a/crates/vm/src/object/traverse_object.rs +++ b/crates/vm/src/object/traverse_object.rs @@ -1,4 +1,4 @@ -use std::fmt; +use alloc::fmt; use crate::{ PyObject, diff --git a/crates/vm/src/ospath.rs b/crates/vm/src/ospath.rs index 77abbee2cd5..25fcafb74c5 100644 --- a/crates/vm/src/ospath.rs +++ b/crates/vm/src/ospath.rs @@ -230,12 +230,12 @@ impl OsPath { self.path.into_encoded_bytes() } - pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> { + pub fn to_string_lossy(&self) -> alloc::borrow::Cow<'_, str> { self.path.to_string_lossy() } - pub fn into_cstring(self, vm: &VirtualMachine) -> PyResult { - std::ffi::CString::new(self.into_bytes()).map_err(|err| err.to_pyexception(vm)) + pub fn into_cstring(self, vm: &VirtualMachine) -> PyResult { + alloc::ffi::CString::new(self.into_bytes()).map_err(|err| err.to_pyexception(vm)) } #[cfg(windows)] diff --git a/crates/vm/src/protocol/buffer.rs b/crates/vm/src/protocol/buffer.rs index 88524a9a9ee..0fe4d15458b 100644 --- a/crates/vm/src/protocol/buffer.rs +++ b/crates/vm/src/protocol/buffer.rs @@ -10,8 +10,9 @@ use crate::{ object::PyObjectPayload, sliceable::SequenceIndexOp, }; +use alloc::borrow::Cow; +use core::{fmt::Debug, ops::Range}; use itertools::Itertools; -use std::{borrow::Cow, fmt::Debug, ops::Range}; pub struct BufferMethods { pub obj_bytes: fn(&PyBuffer) -> BorrowedValue<'_, [u8]>, @@ -21,7 +22,7 @@ pub struct BufferMethods { } impl Debug for BufferMethods { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("BufferMethods") .field("obj_bytes", &(self.obj_bytes as usize)) .field("obj_bytes_mut", &(self.obj_bytes_mut as usize)) @@ -134,8 +135,8 @@ impl PyBuffer { pub(crate) unsafe fn drop_without_release(&mut self) { // SAFETY: requirements forwarded from caller unsafe { - std::ptr::drop_in_place(&mut self.obj); - std::ptr::drop_in_place(&mut self.desc); + core::ptr::drop_in_place(&mut self.obj); + core::ptr::drop_in_place(&mut self.desc); } } } @@ -414,7 +415,7 @@ pub struct VecBuffer { #[pyclass(flags(BASETYPE, DISALLOW_INSTANTIATION))] impl VecBuffer { pub fn take(&self) -> Vec { - std::mem::take(&mut self.data.lock()) + core::mem::take(&mut self.data.lock()) } } diff --git a/crates/vm/src/protocol/callable.rs b/crates/vm/src/protocol/callable.rs index 5280e04e928..fa5e48d58ba 100644 --- a/crates/vm/src/protocol/callable.rs +++ b/crates/vm/src/protocol/callable.rs @@ -61,8 +61,8 @@ enum TraceEvent { Return, } -impl std::fmt::Display for TraceEvent { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for TraceEvent { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { use TraceEvent::*; match self { Call => write!(f, "call"), diff --git a/crates/vm/src/protocol/iter.rs b/crates/vm/src/protocol/iter.rs index f6146543de9..aa6ab6769cd 100644 --- a/crates/vm/src/protocol/iter.rs +++ b/crates/vm/src/protocol/iter.rs @@ -4,8 +4,8 @@ use crate::{ convert::{ToPyObject, ToPyResult}, object::{Traverse, TraverseFn}, }; -use std::borrow::Borrow; -use std::ops::Deref; +use core::borrow::Borrow; +use core::ops::Deref; /// Iterator Protocol // https://docs.python.org/3/c-api/iter.html @@ -223,7 +223,7 @@ where vm: &'a VirtualMachine, obj: O, // creating PyIter is zero-cost length_hint: Option, - _phantom: std::marker::PhantomData, + _phantom: core::marker::PhantomData, } unsafe impl Traverse for PyIterIter<'_, T, O> @@ -244,7 +244,7 @@ where vm, obj, length_hint, - _phantom: std::marker::PhantomData, + _phantom: core::marker::PhantomData, } } } diff --git a/crates/vm/src/protocol/mapping.rs b/crates/vm/src/protocol/mapping.rs index 43dafeb9238..6c200043e35 100644 --- a/crates/vm/src/protocol/mapping.rs +++ b/crates/vm/src/protocol/mapping.rs @@ -22,8 +22,8 @@ pub struct PyMappingSlots { >, } -impl std::fmt::Debug for PyMappingSlots { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyMappingSlots { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("PyMappingSlots") } } @@ -56,8 +56,8 @@ pub struct PyMappingMethods { Option, &PyObject, Option, &VirtualMachine) -> PyResult<()>>, } -impl std::fmt::Debug for PyMappingMethods { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyMappingMethods { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("PyMappingMethods") } } diff --git a/crates/vm/src/protocol/number.rs b/crates/vm/src/protocol/number.rs index c208bf26de8..58891d1d710 100644 --- a/crates/vm/src/protocol/number.rs +++ b/crates/vm/src/protocol/number.rs @@ -1,4 +1,4 @@ -use std::ops::Deref; +use core::ops::Deref; use crossbeam_utils::atomic::AtomicCell; diff --git a/crates/vm/src/protocol/sequence.rs b/crates/vm/src/protocol/sequence.rs index 888ef91565f..cee46a29089 100644 --- a/crates/vm/src/protocol/sequence.rs +++ b/crates/vm/src/protocol/sequence.rs @@ -29,8 +29,8 @@ pub struct PySequenceSlots { pub inplace_repeat: AtomicCell, isize, &VirtualMachine) -> PyResult>>, } -impl std::fmt::Debug for PySequenceSlots { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PySequenceSlots { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("PySequenceSlots") } } @@ -83,8 +83,8 @@ pub struct PySequenceMethods { pub inplace_repeat: Option, isize, &VirtualMachine) -> PyResult>, } -impl std::fmt::Debug for PySequenceMethods { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PySequenceMethods { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("PySequenceMethods") } } diff --git a/crates/vm/src/py_io.rs b/crates/vm/src/py_io.rs index a8063673a70..5649463b30e 100644 --- a/crates/vm/src/py_io.rs +++ b/crates/vm/src/py_io.rs @@ -3,7 +3,9 @@ use crate::{ builtins::{PyBaseExceptionRef, PyBytes, PyStr}, common::ascii, }; -use std::{fmt, io, ops}; +use alloc::fmt; +use core::ops; +use std::io; pub trait Write { type Error; diff --git a/crates/vm/src/py_serde.rs b/crates/vm/src/py_serde.rs index f9a5f4bc060..945068113f1 100644 --- a/crates/vm/src/py_serde.rs +++ b/crates/vm/src/py_serde.rs @@ -130,7 +130,7 @@ impl<'de> DeserializeSeed<'de> for PyObjectDeserializer<'de> { impl<'de> Visitor<'de> for PyObjectDeserializer<'de> { type Value = PyObjectRef; - fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { formatter.write_str("a type that can deserialize in Python") } diff --git a/crates/vm/src/readline.rs b/crates/vm/src/readline.rs index 77402dc6839..d62d520ecbd 100644 --- a/crates/vm/src/readline.rs +++ b/crates/vm/src/readline.rs @@ -5,7 +5,7 @@ use std::{io, path::Path}; -type OtherError = Box; +type OtherError = Box; type OtherResult = Result; pub enum ReadlineResult { diff --git a/crates/vm/src/scope.rs b/crates/vm/src/scope.rs index 4f80e9999ec..74392dc9b73 100644 --- a/crates/vm/src/scope.rs +++ b/crates/vm/src/scope.rs @@ -1,5 +1,5 @@ use crate::{VirtualMachine, builtins::PyDictRef, function::ArgMapping}; -use std::fmt; +use alloc::fmt; #[derive(Clone)] pub struct Scope { diff --git a/crates/vm/src/sequence.rs b/crates/vm/src/sequence.rs index 6e03ad1697e..0bc12fd2631 100644 --- a/crates/vm/src/sequence.rs +++ b/crates/vm/src/sequence.rs @@ -6,8 +6,8 @@ use crate::{ types::PyComparisonOp, vm::{MAX_MEMORY_SIZE, VirtualMachine}, }; +use core::ops::{Deref, Range}; use optional::Optioned; -use std::ops::{Deref, Range}; pub trait MutObjectSequenceOp { type Inner: ?Sized; @@ -100,7 +100,7 @@ where fn mul(&self, vm: &VirtualMachine, n: isize) -> PyResult> { let n = vm.check_repeat_or_overflow_error(self.as_ref().len(), n)?; - if n > 1 && std::mem::size_of_val(self.as_ref()) >= MAX_MEMORY_SIZE / n { + if n > 1 && core::mem::size_of_val(self.as_ref()) >= MAX_MEMORY_SIZE / n { return Err(vm.new_memory_error("")); } diff --git a/crates/vm/src/signal.rs b/crates/vm/src/signal.rs index 1074c8e8f11..4a1b84a1521 100644 --- a/crates/vm/src/signal.rs +++ b/crates/vm/src/signal.rs @@ -1,12 +1,8 @@ #![cfg_attr(target_os = "wasi", allow(dead_code))] use crate::{PyResult, VirtualMachine}; -use std::{ - fmt, - sync::{ - atomic::{AtomicBool, Ordering}, - mpsc, - }, -}; +use alloc::fmt; +use core::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; pub(crate) const NSIG: usize = 64; static ANY_TRIGGERED: AtomicBool = AtomicBool::new(false); diff --git a/crates/vm/src/sliceable.rs b/crates/vm/src/sliceable.rs index 786b66fb36a..e416f5a1b49 100644 --- a/crates/vm/src/sliceable.rs +++ b/crates/vm/src/sliceable.rs @@ -3,9 +3,9 @@ use crate::{ PyObject, PyResult, VirtualMachine, builtins::{int::PyInt, slice::PySlice}, }; +use core::ops::Range; use malachite_bigint::BigInt; use num_traits::{Signed, ToPrimitive}; -use std::ops::Range; pub trait SliceableSequenceMutOp where diff --git a/crates/vm/src/stdlib/ast/elif_else_clause.rs b/crates/vm/src/stdlib/ast/elif_else_clause.rs index 581fc499b8a..e2a8789dd08 100644 --- a/crates/vm/src/stdlib/ast/elif_else_clause.rs +++ b/crates/vm/src/stdlib/ast/elif_else_clause.rs @@ -3,7 +3,7 @@ use rustpython_compiler_core::SourceFile; pub(super) fn ast_to_object( clause: ruff::ElifElseClause, - mut rest: std::vec::IntoIter, + mut rest: alloc::vec::IntoIter, vm: &VirtualMachine, source_file: &SourceFile, ) -> PyObjectRef { diff --git a/crates/vm/src/stdlib/ast/parameter.rs b/crates/vm/src/stdlib/ast/parameter.rs index 87fa736687b..44fcbb2b464 100644 --- a/crates/vm/src/stdlib/ast/parameter.rs +++ b/crates/vm/src/stdlib/ast/parameter.rs @@ -403,7 +403,7 @@ fn merge_keyword_parameter_defaults( kw_only_args: KeywordParameters, defaults: ParameterDefaults, ) -> Vec { - std::iter::zip(kw_only_args.keywords, defaults.defaults) + core::iter::zip(kw_only_args.keywords, defaults.defaults) .map(|(parameter, default)| ruff::ParameterWithDefault { node_index: Default::default(), parameter, diff --git a/crates/vm/src/stdlib/ast/string.rs b/crates/vm/src/stdlib/ast/string.rs index f3df8d99262..ffa5a3a958a 100644 --- a/crates/vm/src/stdlib/ast/string.rs +++ b/crates/vm/src/stdlib/ast/string.rs @@ -12,7 +12,7 @@ fn ruff_fstring_value_into_iter( }); (0..fstring_value.as_slice().len()).map(move |i| { let tmp = fstring_value.iter_mut().nth(i).unwrap(); - std::mem::replace(tmp, default.clone()) + core::mem::replace(tmp, default.clone()) }) } @@ -28,7 +28,7 @@ fn ruff_fstring_element_into_iter( (0..fstring_element.into_iter().len()).map(move |i| { let fstring_element = &mut fstring_element; let tmp = fstring_element.into_iter().nth(i).unwrap(); - std::mem::replace(tmp, default.clone()) + core::mem::replace(tmp, default.clone()) }) } diff --git a/crates/vm/src/stdlib/atexit.rs b/crates/vm/src/stdlib/atexit.rs index b1832b5481d..2286c36f1db 100644 --- a/crates/vm/src/stdlib/atexit.rs +++ b/crates/vm/src/stdlib/atexit.rs @@ -34,7 +34,7 @@ mod atexit { #[pyfunction] pub fn _run_exitfuncs(vm: &VirtualMachine) { - let funcs: Vec<_> = std::mem::take(&mut *vm.state.atexit_funcs.lock()); + let funcs: Vec<_> = core::mem::take(&mut *vm.state.atexit_funcs.lock()); for (func, args) in funcs.into_iter().rev() { if let Err(e) = func.call(args, vm) { let exit = e.fast_isinstance(vm.ctx.exceptions.system_exit); diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index 7cd91f8b4b7..c82161fc553 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -175,7 +175,7 @@ mod builtins { let source = source.borrow_bytes(); // TODO: compiler::compile should probably get bytes - let source = std::str::from_utf8(&source) + let source = core::str::from_utf8(&source) .map_err(|e| vm.new_unicode_decode_error(e.to_string()))?; let flags = args.flags.map_or(Ok(0), |v| v.try_to_primitive(vm))?; @@ -333,7 +333,7 @@ mod builtins { )); } - let source = std::str::from_utf8(source).map_err(|err| { + let source = core::str::from_utf8(source).map_err(|err| { let msg = format!( "(unicode error) 'utf-8' codec can't decode byte 0x{:x?} in position {}: invalid start byte", source[err.valid_up_to()], @@ -605,7 +605,7 @@ mod builtins { } let candidates = match args.args.len().cmp(&1) { - std::cmp::Ordering::Greater => { + core::cmp::Ordering::Greater => { if default.is_some() { return Err(vm.new_type_error(format!( "Cannot specify a default for {func_name}() with multiple positional arguments" @@ -613,8 +613,8 @@ mod builtins { } args.args } - std::cmp::Ordering::Equal => args.args[0].try_to_value(vm)?, - std::cmp::Ordering::Less => { + core::cmp::Ordering::Equal => args.args[0].try_to_value(vm)?, + core::cmp::Ordering::Less => { // zero arguments means type error: return Err( vm.new_type_error(format!("{func_name} expected at least 1 argument, got 0")) diff --git a/crates/vm/src/stdlib/codecs.rs b/crates/vm/src/stdlib/codecs.rs index 821b313090c..1661eef1750 100644 --- a/crates/vm/src/stdlib/codecs.rs +++ b/crates/vm/src/stdlib/codecs.rs @@ -270,7 +270,7 @@ mod _codecs { wide.len() as i32, std::ptr::null_mut(), 0, - std::ptr::null(), + core::ptr::null(), std::ptr::null_mut(), ) }; @@ -291,7 +291,7 @@ mod _codecs { wide.len() as i32, buffer.as_mut_ptr().cast(), size, - std::ptr::null(), + core::ptr::null(), if errors == "strict" { &mut used_default_char } else { @@ -472,7 +472,7 @@ mod _codecs { wide.len() as i32, std::ptr::null_mut(), 0, - std::ptr::null(), + core::ptr::null(), std::ptr::null_mut(), ) }; @@ -493,7 +493,7 @@ mod _codecs { wide.len() as i32, buffer.as_mut_ptr().cast(), size, - std::ptr::null(), + core::ptr::null(), if errors == "strict" { &mut used_default_char } else { diff --git a/crates/vm/src/stdlib/collections.rs b/crates/vm/src/stdlib/collections.rs index eae56968cba..1249fa9315d 100644 --- a/crates/vm/src/stdlib/collections.rs +++ b/crates/vm/src/stdlib/collections.rs @@ -22,9 +22,9 @@ mod _collections { }, utils::collection_repr, }; + use alloc::collections::VecDeque; + use core::cmp::max; use crossbeam_utils::atomic::AtomicCell; - use std::cmp::max; - use std::collections::VecDeque; #[pyattr] #[pyclass(module = "collections", name = "deque", unhashable = true)] @@ -157,7 +157,7 @@ mod _collections { let mut created = VecDeque::from(elements); let mut borrowed = self.borrow_deque_mut(); created.append(&mut borrowed); - std::mem::swap(&mut created, &mut borrowed); + core::mem::swap(&mut created, &mut borrowed); Ok(()) } @@ -426,7 +426,7 @@ mod _collections { inner.get(index).map(|r| r.as_ref()) } - fn do_lock(&self) -> impl std::ops::Deref { + fn do_lock(&self) -> impl core::ops::Deref { self.borrow_deque() } } @@ -484,7 +484,7 @@ mod _collections { // `maxlen` is better to be defined as UnsafeCell in common practice, // but then more type works without any safety benefits let unsafe_maxlen = - &zelf.maxlen as *const _ as *const std::cell::UnsafeCell>; + &zelf.maxlen as *const _ as *const core::cell::UnsafeCell>; *(*unsafe_maxlen).get() = maxlen; } if let Some(elements) = elements { diff --git a/crates/vm/src/stdlib/ctypes.rs b/crates/vm/src/stdlib/ctypes.rs index a9c0636bd12..f3b6dd25aca 100644 --- a/crates/vm/src/stdlib/ctypes.rs +++ b/crates/vm/src/stdlib/ctypes.rs @@ -15,11 +15,11 @@ use crate::{ class::PyClassImpl, types::TypeDataRef, }; -use std::ffi::{ +use core::ffi::{ c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, c_ulong, c_ulonglong, c_ushort, }; -use std::mem; +use core::mem; use widestring::WideChar; pub use array::PyCArray; @@ -387,7 +387,7 @@ pub(crate) mod _ctypes { const RTLD_GLOBAL: i32 = 0; #[pyattr] - const SIZEOF_TIME_T: usize = std::mem::size_of::(); + const SIZEOF_TIME_T: usize = core::mem::size_of::(); #[pyattr] const CTYPES_MAX_ARGCOUNT: usize = 1024; @@ -535,11 +535,11 @@ pub(crate) mod _ctypes { { return Ok(super::get_size(type_str.as_ref())); } - return Ok(std::mem::size_of::()); + return Ok(core::mem::size_of::()); } // Pointer types if type_obj.fast_issubclass(PyCPointer::static_type()) { - return Ok(std::mem::size_of::()); + return Ok(core::mem::size_of::()); } return Err(vm.new_type_error("this type has no size")); } @@ -550,7 +550,7 @@ pub(crate) mod _ctypes { return Ok(cdata.size()); } if obj.fast_isinstance(PyCPointer::static_type()) { - return Ok(std::mem::size_of::()); + return Ok(core::mem::size_of::()); } Err(vm.new_type_error("this type has no size")) @@ -596,13 +596,17 @@ pub(crate) mod _ctypes { } None => { // dlopen(NULL, mode) to get the current process handle (for pythonapi) - let handle = unsafe { libc::dlopen(std::ptr::null(), mode) }; + let handle = unsafe { libc::dlopen(core::ptr::null(), mode) }; if handle.is_null() { let err = unsafe { libc::dlerror() }; let msg = if err.is_null() { "dlopen() error".to_string() } else { - unsafe { std::ffi::CStr::from_ptr(err).to_string_lossy().into_owned() } + unsafe { + core::ffi::CStr::from_ptr(err) + .to_string_lossy() + .into_owned() + } }; return Err(vm.new_os_error(msg)); } @@ -641,7 +645,7 @@ pub(crate) mod _ctypes { name: crate::builtins::PyStrRef, vm: &VirtualMachine, ) -> PyResult { - let symbol_name = std::ffi::CString::new(name.as_str()) + let symbol_name = alloc::ffi::CString::new(name.as_str()) .map_err(|_| vm.new_value_error("symbol name contains null byte"))?; // Clear previous error @@ -652,7 +656,11 @@ pub(crate) mod _ctypes { // Check for error via dlerror first let err = unsafe { libc::dlerror() }; if !err.is_null() { - let msg = unsafe { std::ffi::CStr::from_ptr(err).to_string_lossy().into_owned() }; + let msg = unsafe { + core::ffi::CStr::from_ptr(err) + .to_string_lossy() + .into_owned() + }; return Err(vm.new_os_error(msg)); } @@ -851,7 +859,7 @@ pub(crate) mod _ctypes { } if obj.fast_isinstance(PyCPointer::static_type()) { // Pointer alignment is always pointer size - return Ok(std::mem::align_of::()); + return Ok(core::mem::align_of::()); } if obj.fast_isinstance(PyCUnion::static_type()) { // Calculate alignment from _fields_ @@ -914,7 +922,7 @@ pub(crate) mod _ctypes { #[pyfunction] fn resize(obj: PyObjectRef, size: isize, vm: &VirtualMachine) -> PyResult<()> { - use std::borrow::Cow; + use alloc::borrow::Cow; // 1. Get StgInfo from object's class (validates ctypes instance) let stg_info = obj @@ -1148,8 +1156,8 @@ pub(crate) mod _ctypes { } let raw_ptr = ptr as *mut crate::object::PyObject; unsafe { - let obj = crate::PyObjectRef::from_raw(std::ptr::NonNull::new_unchecked(raw_ptr)); - let obj = std::mem::ManuallyDrop::new(obj); + let obj = crate::PyObjectRef::from_raw(core::ptr::NonNull::new_unchecked(raw_ptr)); + let obj = core::mem::ManuallyDrop::new(obj); Ok((*obj).clone()) } } @@ -1208,12 +1216,12 @@ pub(crate) mod _ctypes { FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - std::ptr::null(), + core::ptr::null(), error_code, 0, &mut buffer as *mut *mut u16 as *mut u16, 0, - std::ptr::null(), + core::ptr::null(), ) }; @@ -1280,7 +1288,7 @@ pub(crate) mod _ctypes { let vtable = *iunknown; debug_assert!(!vtable.is_null(), "IUnknown vtable is null"); let addref_fn: extern "system" fn(*mut std::ffi::c_void) -> u32 = - std::mem::transmute(*vtable.add(1)); // AddRef is index 1 + core::mem::transmute(*vtable.add(1)); // AddRef is index 1 addref_fn(src_ptr as *mut std::ffi::c_void); } } diff --git a/crates/vm/src/stdlib/ctypes/array.rs b/crates/vm/src/stdlib/ctypes/array.rs index 25708b57f8e..168da2bcc01 100644 --- a/crates/vm/src/stdlib/ctypes/array.rs +++ b/crates/vm/src/stdlib/ctypes/array.rs @@ -631,7 +631,7 @@ impl PyCArray { let ptr_val = usize::from_ne_bytes( ptr_bytes .try_into() - .unwrap_or([0; std::mem::size_of::()]), + .unwrap_or([0; core::mem::size_of::()]), ); if ptr_val == 0 { return Ok(vm.ctx.none()); @@ -643,7 +643,7 @@ impl PyCArray { while *ptr.add(len) != 0 { len += 1; } - let bytes = std::slice::from_raw_parts(ptr, len); + let bytes = core::slice::from_raw_parts(ptr, len); Ok(vm.ctx.new_bytes(bytes.to_vec()).into()) } } @@ -656,7 +656,7 @@ impl PyCArray { let ptr_val = usize::from_ne_bytes( ptr_bytes .try_into() - .unwrap_or([0; std::mem::size_of::()]), + .unwrap_or([0; core::mem::size_of::()]), ); if ptr_val == 0 { return Ok(vm.ctx.none()); @@ -668,10 +668,10 @@ impl PyCArray { let mut pos = 0usize; loop { let code = if WCHAR_SIZE == 2 { - let bytes = std::slice::from_raw_parts(ptr.add(pos), 2); + let bytes = core::slice::from_raw_parts(ptr.add(pos), 2); u16::from_ne_bytes([bytes[0], bytes[1]]) as u32 } else { - let bytes = std::slice::from_raw_parts(ptr.add(pos), 4); + let bytes = core::slice::from_raw_parts(ptr.add(pos), 4); u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) }; if code == 0 { @@ -1136,7 +1136,7 @@ impl AsBuffer for PyCArray { len: buffer_len, readonly: false, itemsize, - format: std::borrow::Cow::Owned(fmt), + format: alloc::borrow::Cow::Owned(fmt), dim_desc, } } else { @@ -1291,7 +1291,7 @@ fn add_wchar_array_getsets(array_type: &Py, vm: &VirtualMachine) { // Linux/macOS: sizeof(wchar_t) == 4 (UTF-32) /// Size of wchar_t on this platform -pub(super) const WCHAR_SIZE: usize = std::mem::size_of::(); +pub(super) const WCHAR_SIZE: usize = core::mem::size_of::(); /// Read a single wchar_t from bytes (platform-endian) #[inline] diff --git a/crates/vm/src/stdlib/ctypes/base.rs b/crates/vm/src/stdlib/ctypes/base.rs index 0f859b3d10b..1f9eaeef56a 100644 --- a/crates/vm/src/stdlib/ctypes/base.rs +++ b/crates/vm/src/stdlib/ctypes/base.rs @@ -7,15 +7,15 @@ use crate::types::{GetDescriptor, Representable}; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, }; +use alloc::borrow::Cow; +use core::ffi::{ + c_double, c_float, c_int, c_long, c_longlong, c_short, c_uint, c_ulong, c_ulonglong, c_ushort, +}; +use core::fmt::Debug; +use core::mem; use crossbeam_utils::atomic::AtomicCell; use num_traits::{Signed, ToPrimitive}; use rustpython_common::lock::PyRwLock; -use std::borrow::Cow; -use std::ffi::{ - c_double, c_float, c_int, c_long, c_longlong, c_short, c_uint, c_ulong, c_ulonglong, c_ushort, -}; -use std::fmt::Debug; -use std::mem; use widestring::WideChar; // StgInfo - Storage information for ctypes types @@ -105,8 +105,8 @@ pub struct StgInfo { unsafe impl Send for StgInfo {} unsafe impl Sync for StgInfo {} -impl std::fmt::Debug for StgInfo { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for StgInfo { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("StgInfo") .field("initialized", &self.initialized) .field("size", &self.size) @@ -227,7 +227,7 @@ impl StgInfo { libffi::middle::Type::structure(self.ffi_field_types.iter().cloned()) } else if self.size <= MAX_FFI_STRUCT_SIZE { // Small struct without field types: use bytes array - libffi::middle::Type::structure(std::iter::repeat_n( + libffi::middle::Type::structure(core::iter::repeat_n( libffi::middle::Type::u8(), self.size, )) @@ -242,9 +242,9 @@ impl StgInfo { libffi::middle::Type::pointer() } else if let Some(ref fmt) = self.format { let elem_type = Self::format_to_ffi_type(fmt); - libffi::middle::Type::structure(std::iter::repeat_n(elem_type, self.length)) + libffi::middle::Type::structure(core::iter::repeat_n(elem_type, self.length)) } else { - libffi::middle::Type::structure(std::iter::repeat_n( + libffi::middle::Type::structure(core::iter::repeat_n( libffi::middle::Type::u8(), self.size, )) @@ -373,10 +373,10 @@ pub(super) static CDATA_BUFFER_METHODS: BufferMethods = BufferMethods { /// Convert Vec to Vec by reinterpreting the memory (same allocation). fn vec_to_bytes(vec: Vec) -> Vec { - let len = vec.len() * std::mem::size_of::(); - let cap = vec.capacity() * std::mem::size_of::(); + let len = vec.len() * core::mem::size_of::(); + let cap = vec.capacity() * core::mem::size_of::(); let ptr = vec.as_ptr() as *mut u8; - std::mem::forget(vec); + core::mem::forget(vec); unsafe { Vec::from_raw_parts(ptr, len, cap) } } @@ -406,7 +406,7 @@ pub(super) fn str_to_wchar_bytes(s: &str, vm: &VirtualMachine) -> (PyObjectRef, let wchars: Vec = s .chars() .map(|c| c as libc::wchar_t) - .chain(std::iter::once(0)) + .chain(core::iter::once(0)) .collect(); let ptr = wchars.as_ptr() as usize; let bytes = vec_to_bytes(wchars); @@ -486,7 +486,7 @@ impl PyCData { pub unsafe fn at_address(ptr: *const u8, size: usize) -> Self { // = PyCData_AtAddress // SAFETY: Caller must ensure ptr is valid for the lifetime of returned PyCData - let slice: &'static [u8] = unsafe { std::slice::from_raw_parts(ptr, size) }; + let slice: &'static [u8] = unsafe { core::slice::from_raw_parts(ptr, size) }; PyCData { buffer: PyRwLock::new(Cow::Borrowed(slice)), base: PyRwLock::new(None), @@ -534,7 +534,7 @@ impl PyCData { ) -> Self { // = PyCData_FromBaseObj // SAFETY: ptr points into base_obj's buffer, kept alive via base reference - let slice: &'static [u8] = unsafe { std::slice::from_raw_parts(ptr, size) }; + let slice: &'static [u8] = unsafe { core::slice::from_raw_parts(ptr, size) }; PyCData { buffer: PyRwLock::new(Cow::Borrowed(slice)), base: PyRwLock::new(Some(base_obj)), @@ -561,7 +561,7 @@ impl PyCData { vm: &VirtualMachine, ) -> Self { // SAFETY: Caller must ensure ptr is valid for the lifetime of source - let slice: &'static [u8] = unsafe { std::slice::from_raw_parts(ptr, size) }; + let slice: &'static [u8] = unsafe { core::slice::from_raw_parts(ptr, size) }; // Python stores the reference in a dict with key "-1" (unique_key pattern) let objects_dict = vm.ctx.new_dict(); @@ -707,7 +707,7 @@ impl PyCData { // (e.g., from from_address pointing to a ctypes buffer) unsafe { let ptr = slice.as_ptr() as *mut u8; - std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.add(offset), bytes.len()); + core::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.add(offset), bytes.len()); } } Cow::Owned(_) => { @@ -893,7 +893,7 @@ impl PyCData { if let Some(bytes_val) = value.downcast_ref::() { let src = bytes_val.as_bytes(); let to_copy = PyCField::bytes_for_char_array(src); - let copy_len = std::cmp::min(to_copy.len(), size); + let copy_len = core::cmp::min(to_copy.len(), size); self.write_bytes_at_offset(offset, &to_copy[..copy_len]); self.keep_ref(index, value, vm)?; return Ok(()); @@ -936,7 +936,7 @@ impl PyCData { array_buffer.as_ptr() as usize }; let addr_bytes = buffer_addr.to_ne_bytes(); - let len = std::cmp::min(addr_bytes.len(), size); + let len = core::cmp::min(addr_bytes.len(), size); self.write_bytes_at_offset(offset, &addr_bytes[..len]); self.keep_ref(index, value, vm)?; return Ok(()); @@ -1364,7 +1364,7 @@ impl PyCField { if let Some(bytes) = value.downcast_ref::() { let src = bytes.as_bytes(); let mut result = vec![0u8; size]; - let len = std::cmp::min(src.len(), size); + let len = core::cmp::min(src.len(), size); result[..len].copy_from_slice(&src[..len]); Ok(result) } @@ -1372,7 +1372,7 @@ impl PyCField { else if let Some(cdata) = value.downcast_ref::() { let buffer = cdata.buffer.read(); let mut result = vec![0u8; size]; - let len = std::cmp::min(buffer.len(), size); + let len = core::cmp::min(buffer.len(), size); result[..len].copy_from_slice(&buffer[..len]); Ok(result) } @@ -1473,7 +1473,7 @@ impl PyCField { let (converted, ptr) = ensure_z_null_terminated(bytes, vm); let mut result = vec![0u8; size]; let addr_bytes = ptr.to_ne_bytes(); - let len = std::cmp::min(addr_bytes.len(), size); + let len = core::cmp::min(addr_bytes.len(), size); result[..len].copy_from_slice(&addr_bytes[..len]); return Ok((result, Some(converted))); } @@ -1482,7 +1482,7 @@ impl PyCField { let v = int_val.as_bigint().to_usize().unwrap_or(0); let mut result = vec![0u8; size]; let bytes = v.to_ne_bytes(); - let len = std::cmp::min(bytes.len(), size); + let len = core::cmp::min(bytes.len(), size); result[..len].copy_from_slice(&bytes[..len]); return Ok((result, None)); } @@ -1498,7 +1498,7 @@ impl PyCField { let (holder, ptr) = str_to_wchar_bytes(s.as_str(), vm); let mut result = vec![0u8; size]; let addr_bytes = ptr.to_ne_bytes(); - let len = std::cmp::min(addr_bytes.len(), size); + let len = core::cmp::min(addr_bytes.len(), size); result[..len].copy_from_slice(&addr_bytes[..len]); return Ok((result, Some(holder))); } @@ -1507,7 +1507,7 @@ impl PyCField { let v = int_val.as_bigint().to_usize().unwrap_or(0); let mut result = vec![0u8; size]; let bytes = v.to_ne_bytes(); - let len = std::cmp::min(bytes.len(), size); + let len = core::cmp::min(bytes.len(), size); result[..len].copy_from_slice(&bytes[..len]); return Ok((result, None)); } @@ -1523,7 +1523,7 @@ impl PyCField { let v = int_val.as_bigint().to_usize().unwrap_or(0); let mut result = vec![0u8; size]; let bytes = v.to_ne_bytes(); - let len = std::cmp::min(bytes.len(), size); + let len = core::cmp::min(bytes.len(), size); result[..len].copy_from_slice(&bytes[..len]); return Ok((result, None)); } @@ -2078,7 +2078,7 @@ pub(super) fn bytes_to_pyobject( if ptr == 0 { return Ok(vm.ctx.none()); } - let c_str = unsafe { std::ffi::CStr::from_ptr(ptr as _) }; + let c_str = unsafe { core::ffi::CStr::from_ptr(ptr as _) }; Ok(vm.ctx.new_bytes(c_str.to_bytes().to_vec()).into()) } "Z" => { @@ -2089,7 +2089,7 @@ pub(super) fn bytes_to_pyobject( } let len = unsafe { libc::wcslen(ptr as *const libc::wchar_t) }; let wchars = - unsafe { std::slice::from_raw_parts(ptr as *const libc::wchar_t, len) }; + unsafe { core::slice::from_raw_parts(ptr as *const libc::wchar_t, len) }; let s: String = wchars .iter() .filter_map(|&c| char::from_u32(c as u32)) @@ -2149,7 +2149,7 @@ pub(super) fn get_usize_attr( /// Read a pointer value from buffer #[inline] pub(super) fn read_ptr_from_buffer(buffer: &[u8]) -> usize { - const PTR_SIZE: usize = std::mem::size_of::(); + const PTR_SIZE: usize = core::mem::size_of::(); if buffer.len() >= PTR_SIZE { usize::from_ne_bytes(buffer[..PTR_SIZE].try_into().unwrap()) } else { @@ -2242,7 +2242,7 @@ pub(super) fn get_field_size(field_type: &PyObject, vm: &VirtualMachine) -> PyRe return Ok(s); } - Ok(std::mem::size_of::()) + Ok(core::mem::size_of::()) } /// Get the alignment of a ctypes field type diff --git a/crates/vm/src/stdlib/ctypes/function.rs b/crates/vm/src/stdlib/ctypes/function.rs index 55a42f0ba15..5906bc91cd4 100644 --- a/crates/vm/src/stdlib/ctypes/function.rs +++ b/crates/vm/src/stdlib/ctypes/function.rs @@ -16,6 +16,9 @@ use crate::{ types::{AsBuffer, Callable, Constructor, Initializer, Representable}, vm::thread::with_current_vm, }; +use alloc::borrow::Cow; +use core::ffi::c_void; +use core::fmt::Debug; use libffi::{ low, middle::{Arg, Cif, Closure, CodePtr, Type}, @@ -23,9 +26,6 @@ use libffi::{ use libloading::Symbol; use num_traits::{Signed, ToPrimitive}; use rustpython_common::lock::PyRwLock; -use std::borrow::Cow; -use std::ffi::c_void; -use std::fmt::Debug; // Internal function addresses for special ctypes functions pub(super) const INTERNAL_CAST_ADDR: usize = 1; @@ -37,7 +37,7 @@ std::thread_local! { /// Thread-local storage for ctypes errno /// This is separate from the system errno - ctypes swaps them during FFI calls /// when use_errno=True is specified. - static CTYPES_LOCAL_ERRNO: std::cell::Cell = const { std::cell::Cell::new(0) }; + static CTYPES_LOCAL_ERRNO: core::cell::Cell = const { core::cell::Cell::new(0) }; } /// Get ctypes thread-local errno value @@ -79,7 +79,7 @@ where #[cfg(windows)] std::thread_local! { /// Thread-local storage for ctypes last_error (Windows only) - static CTYPES_LOCAL_LAST_ERROR: std::cell::Cell = const { std::cell::Cell::new(0) }; + static CTYPES_LOCAL_LAST_ERROR: core::cell::Cell = const { core::cell::Cell::new(0) }; } #[cfg(windows)] @@ -135,14 +135,14 @@ fn ffi_type_from_tag(tag: u8) -> Type { b'i' => Type::i32(), b'I' => Type::u32(), b'l' => { - if std::mem::size_of::() == 8 { + if core::mem::size_of::() == 8 { Type::i64() } else { Type::i32() } } b'L' => { - if std::mem::size_of::() == 8 { + if core::mem::size_of::() == 8 { Type::u64() } else { Type::u32() @@ -154,7 +154,7 @@ fn ffi_type_from_tag(tag: u8) -> Type { b'd' | b'g' => Type::f64(), b'?' => Type::u8(), b'u' => { - if std::mem::size_of::() == 2 { + if core::mem::size_of::() == 2 { Type::u16() } else { Type::u32() @@ -207,7 +207,7 @@ fn convert_to_pointer(value: &PyObject, vm: &VirtualMachine) -> PyResult value from buffer if let Some(simple) = value.downcast_ref::() { let buffer = simple.0.buffer.read(); - if buffer.len() >= std::mem::size_of::() { + if buffer.len() >= core::mem::size_of::() { let addr = super::base::read_ptr_from_buffer(&buffer); return Ok(FfiArgValue::Pointer(addr)); } @@ -283,7 +283,7 @@ fn conv_param(value: &PyObject, vm: &VirtualMachine) -> PyResult { let wide: Vec = s .as_str() .encode_utf16() - .chain(std::iter::once(0)) + .chain(core::iter::once(0)) .collect(); let wide_bytes: Vec = wide.iter().flat_map(|&x| x.to_ne_bytes()).collect(); let keep = vm.ctx.new_bytes(wide_bytes); @@ -499,7 +499,7 @@ impl Initializer for PyCFuncPtrType { new_type.check_not_initialized(vm)?; - let ptr_size = std::mem::size_of::(); + let ptr_size = core::mem::size_of::(); let mut stg_info = StgInfo::new(ptr_size, ptr_size); stg_info.format = Some("X{}".to_string()); stg_info.length = 1; @@ -552,7 +552,7 @@ pub(super) struct PyCFuncPtr { } impl Debug for PyCFuncPtr { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCFuncPtr") .field("func_ptr", &self.get_func_ptr()) .finish() @@ -567,9 +567,9 @@ fn extract_ptr_from_arg(arg: &PyObject, vm: &VirtualMachine) -> PyResult } if let Some(simple) = arg.downcast_ref::() { let buffer = simple.0.buffer.read(); - if buffer.len() >= std::mem::size_of::() { + if buffer.len() >= core::mem::size_of::() { return Ok(usize::from_ne_bytes( - buffer[..std::mem::size_of::()].try_into().unwrap(), + buffer[..core::mem::size_of::()].try_into().unwrap(), )); } } @@ -612,7 +612,7 @@ fn string_at_impl(ptr: usize, size: isize, vm: &VirtualMachine) -> PyResult { } size_usize }; - let bytes = unsafe { std::slice::from_raw_parts(ptr, len) }; + let bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; Ok(vm.ctx.new_bytes(bytes.to_vec()).into()) } @@ -627,12 +627,12 @@ fn wstring_at_impl(ptr: usize, size: isize, vm: &VirtualMachine) -> PyResult { } else { // Overflow check for huge size values let size_usize = size as usize; - if size_usize > isize::MAX as usize / std::mem::size_of::() { + if size_usize > isize::MAX as usize / core::mem::size_of::() { return Err(vm.new_overflow_error("string too long")); } size_usize }; - let wchars = unsafe { std::slice::from_raw_parts(w_ptr, len) }; + let wchars = unsafe { core::slice::from_raw_parts(w_ptr, len) }; // Windows: wchar_t = u16 (UTF-16) -> use Wtf8Buf::from_wide // macOS/Linux: wchar_t = i32 (UTF-32) -> convert via char::from_u32 @@ -815,7 +815,7 @@ impl Constructor for PyCFuncPtr { // 3. Tuple argument: (name, dll) form // 4. Callable: callback creation - let ptr_size = std::mem::size_of::(); + let ptr_size = core::mem::size_of::(); if args.args.is_empty() { return PyCFuncPtr { @@ -1513,11 +1513,11 @@ fn convert_raw_result( RawResult::Void => return None, RawResult::Pointer(ptr) => { let bytes = ptr.to_ne_bytes(); - (bytes.to_vec(), std::mem::size_of::()) + (bytes.to_vec(), core::mem::size_of::()) } RawResult::Value(val) => { let bytes = val.to_ne_bytes(); - (bytes.to_vec(), std::mem::size_of::()) + (bytes.to_vec(), core::mem::size_of::()) } }; @@ -1702,7 +1702,7 @@ impl Callable for PyCFuncPtr { None => { debug_assert!(false, "NULL function pointer"); // In release mode, this will crash - CodePtr(std::ptr::null_mut()) + CodePtr(core::ptr::null_mut()) } }; @@ -1758,7 +1758,7 @@ impl AsBuffer for PyCFuncPtr { stg_info.size, ) } else { - (Cow::Borrowed("X{}"), std::mem::size_of::()) + (Cow::Borrowed("X{}"), core::mem::size_of::()) }; let desc = BufferDescriptor { len: itemsize, @@ -1902,7 +1902,7 @@ fn ffi_to_python(ty: &Py, ptr: *const c_void, vm: &VirtualMachine) -> Py if cstr_ptr.is_null() { vm.ctx.none() } else { - let cstr = std::ffi::CStr::from_ptr(cstr_ptr); + let cstr = core::ffi::CStr::from_ptr(cstr_ptr); vm.ctx.new_bytes(cstr.to_bytes().to_vec()).into() } } @@ -1916,7 +1916,7 @@ fn ffi_to_python(ty: &Py, ptr: *const c_void, vm: &VirtualMachine) -> Py while *wstr_ptr.add(len) != 0 { len += 1; } - let slice = std::slice::from_raw_parts(wstr_ptr, len); + let slice = core::slice::from_raw_parts(wstr_ptr, len); // Windows: wchar_t = u16 (UTF-16) -> use Wtf8Buf::from_wide // Unix: wchar_t = i32 (UTF-32) -> convert via char::from_u32 #[cfg(windows)] @@ -2113,7 +2113,7 @@ pub(super) struct PyCThunk { } impl Debug for PyCThunk { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCThunk") .field("callable", &self.callable) .finish() diff --git a/crates/vm/src/stdlib/ctypes/library.rs b/crates/vm/src/stdlib/ctypes/library.rs index 7512ce29d8a..35ccb433845 100644 --- a/crates/vm/src/stdlib/ctypes/library.rs +++ b/crates/vm/src/stdlib/ctypes/library.rs @@ -1,9 +1,9 @@ use crate::VirtualMachine; +use alloc::fmt; use libloading::Library; use rustpython_common::lock::{PyMutex, PyRwLock}; use std::collections::HashMap; use std::ffi::OsStr; -use std::fmt; #[cfg(unix)] use libloading::os::unix::Library as UnixLibrary; @@ -54,7 +54,7 @@ impl SharedLibrary { // On Windows: HMODULE (*mut c_void) // On Unix: *mut c_void from dlopen // We use transmute_copy to read the handle without consuming the Library - unsafe { std::mem::transmute_copy::(l) } + unsafe { core::mem::transmute_copy::(l) } } else { 0 } diff --git a/crates/vm/src/stdlib/ctypes/pointer.rs b/crates/vm/src/stdlib/ctypes/pointer.rs index ae97b741b3c..f564fd1965c 100644 --- a/crates/vm/src/stdlib/ctypes/pointer.rs +++ b/crates/vm/src/stdlib/ctypes/pointer.rs @@ -8,8 +8,8 @@ use crate::{ class::StaticType, function::{FuncArgs, OptionalArg}, }; +use alloc::borrow::Cow; use num_traits::ToPrimitive; -use std::borrow::Cow; #[pyclass(name = "PyCPointerType", base = PyType, module = "_ctypes")] #[derive(Debug)] @@ -37,7 +37,7 @@ impl Initializer for PyCPointerType { .and_then(|obj| obj.downcast::().ok()); // Initialize StgInfo for pointer type - let pointer_size = std::mem::size_of::(); + let pointer_size = core::mem::size_of::(); let mut stg_info = StgInfo::new(pointer_size, pointer_size); stg_info.proto = proto; stg_info.paramfunc = super::base::ParamFunc::Pointer; @@ -232,7 +232,7 @@ impl Constructor for PyCPointer { // Create a new PyCPointer instance with NULL pointer (all zeros) // Initial contents is set via __init__ if provided - let cdata = PyCData::from_bytes(vec![0u8; std::mem::size_of::()], None); + let cdata = PyCData::from_bytes(vec![0u8; core::mem::size_of::()], None); // pointer instance has b_length set to 2 (for index 0 and 1) cdata.length.store(2); PyCPointer(cdata) @@ -299,7 +299,7 @@ impl PyCPointer { let proto_type = stg_info.proto(); let element_size = proto_type .stg_info_opt() - .map_or(std::mem::size_of::(), |info| info.size); + .map_or(core::mem::size_of::(), |info| info.size); // Create instance that references the memory directly // PyCData.into_ref_with_type works for all ctypes (simple, structure, union, array, pointer) @@ -383,7 +383,7 @@ impl PyCPointer { let proto_type = stg_info.proto(); let element_size = proto_type .stg_info_opt() - .map_or(std::mem::size_of::(), |info| info.size); + .map_or(core::mem::size_of::(), |info| info.size); // offset = index * iteminfo->size let offset = index * element_size as isize; @@ -468,7 +468,7 @@ impl PyCPointer { let element_size = if let Some(ref proto_type) = stg_info.proto { proto_type.stg_info_opt().expect("proto has StgInfo").size } else { - std::mem::size_of::() + core::mem::size_of::() }; let type_code = stg_info .proto @@ -489,7 +489,7 @@ impl PyCPointer { // Optimized contiguous copy let start_addr = (ptr_value as isize + start * element_size as isize) as *const u8; unsafe { - result.extend_from_slice(std::slice::from_raw_parts(start_addr, len)); + result.extend_from_slice(core::slice::from_raw_parts(start_addr, len)); } } else { let mut cur = start; @@ -510,7 +510,7 @@ impl PyCPointer { return Ok(vm.ctx.new_str("").into()); } let mut result = String::with_capacity(len); - let wchar_size = std::mem::size_of::(); + let wchar_size = core::mem::size_of::(); let mut cur = start; for _ in 0..len { let addr = (ptr_value as isize + cur * wchar_size as isize) as *const libc::wchar_t; @@ -578,7 +578,7 @@ impl PyCPointer { let element_size = proto_type .stg_info_opt() - .map_or(std::mem::size_of::(), |info| info.size); + .map_or(core::mem::size_of::(), |info| info.size); // Calculate address let offset = index * element_size as isize; @@ -595,7 +595,7 @@ impl PyCPointer { let copy_len = src_buffer.len().min(element_size); unsafe { let dest_ptr = addr as *mut u8; - std::ptr::copy_nonoverlapping(src_buffer.as_ptr(), dest_ptr, copy_len); + core::ptr::copy_nonoverlapping(src_buffer.as_ptr(), dest_ptr, copy_len); } } else { // Handle z/Z specially to store converted value @@ -641,43 +641,43 @@ impl PyCPointer { // Multi-byte types need read_unaligned for safety on strict-alignment architectures Some("h") => Ok(vm .ctx - .new_int(std::ptr::read_unaligned(ptr as *const i16) as i32) + .new_int(core::ptr::read_unaligned(ptr as *const i16) as i32) .into()), Some("H") => Ok(vm .ctx - .new_int(std::ptr::read_unaligned(ptr as *const u16) as i32) + .new_int(core::ptr::read_unaligned(ptr as *const u16) as i32) .into()), Some("i") | Some("l") => Ok(vm .ctx - .new_int(std::ptr::read_unaligned(ptr as *const i32)) + .new_int(core::ptr::read_unaligned(ptr as *const i32)) .into()), Some("I") | Some("L") => Ok(vm .ctx - .new_int(std::ptr::read_unaligned(ptr as *const u32)) + .new_int(core::ptr::read_unaligned(ptr as *const u32)) .into()), Some("q") => Ok(vm .ctx - .new_int(std::ptr::read_unaligned(ptr as *const i64)) + .new_int(core::ptr::read_unaligned(ptr as *const i64)) .into()), Some("Q") => Ok(vm .ctx - .new_int(std::ptr::read_unaligned(ptr as *const u64)) + .new_int(core::ptr::read_unaligned(ptr as *const u64)) .into()), Some("f") => Ok(vm .ctx - .new_float(std::ptr::read_unaligned(ptr as *const f32) as f64) + .new_float(core::ptr::read_unaligned(ptr as *const f32) as f64) .into()), Some("d") | Some("g") => Ok(vm .ctx - .new_float(std::ptr::read_unaligned(ptr as *const f64)) + .new_float(core::ptr::read_unaligned(ptr as *const f64)) .into()), Some("P") | Some("z") | Some("Z") => Ok(vm .ctx - .new_int(std::ptr::read_unaligned(ptr as *const usize)) + .new_int(core::ptr::read_unaligned(ptr as *const usize)) .into()), _ => { // Default: read as bytes - let bytes = std::slice::from_raw_parts(ptr, size).to_vec(); + let bytes = core::slice::from_raw_parts(ptr, size).to_vec(); Ok(vm.ctx.new_bytes(bytes).into()) } } @@ -708,7 +708,7 @@ impl PyCPointer { "bytes/string or integer address expected".to_owned(), )); }; - std::ptr::write_unaligned(ptr as *mut usize, ptr_val); + core::ptr::write_unaligned(ptr as *mut usize, ptr_val); return Ok(()); } _ => {} @@ -723,19 +723,19 @@ impl PyCPointer { *ptr = i.to_u8().expect("int too large"); } 2 => { - std::ptr::write_unaligned( + core::ptr::write_unaligned( ptr as *mut i16, i.to_i16().expect("int too large"), ); } 4 => { - std::ptr::write_unaligned( + core::ptr::write_unaligned( ptr as *mut i32, i.to_i32().expect("int too large"), ); } 8 => { - std::ptr::write_unaligned( + core::ptr::write_unaligned( ptr as *mut i64, i.to_i64().expect("int too large"), ); @@ -743,7 +743,7 @@ impl PyCPointer { _ => { let bytes = i.to_signed_bytes_le(); let copy_len = bytes.len().min(size); - std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, copy_len); + core::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, copy_len); } } return Ok(()); @@ -754,10 +754,10 @@ impl PyCPointer { let f = float_val.to_f64(); match size { 4 => { - std::ptr::write_unaligned(ptr as *mut f32, f as f32); + core::ptr::write_unaligned(ptr as *mut f32, f as f32); } 8 => { - std::ptr::write_unaligned(ptr as *mut f64, f); + core::ptr::write_unaligned(ptr as *mut f64, f); } _ => {} } @@ -767,7 +767,7 @@ impl PyCPointer { // Try bytes if let Ok(bytes) = value.try_bytes_like(vm, |b| b.to_vec()) { let copy_len = bytes.len().min(size); - std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, copy_len); + core::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, copy_len); return Ok(()); } diff --git a/crates/vm/src/stdlib/ctypes/simple.rs b/crates/vm/src/stdlib/ctypes/simple.rs index fbb17620fe4..9835953812f 100644 --- a/crates/vm/src/stdlib/ctypes/simple.rs +++ b/crates/vm/src/stdlib/ctypes/simple.rs @@ -13,9 +13,9 @@ use crate::function::{Either, FuncArgs, OptionalArg}; use crate::protocol::{BufferDescriptor, PyBuffer, PyNumberMethods}; use crate::types::{AsBuffer, AsNumber, Constructor, Initializer, Representable}; use crate::{AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine}; +use alloc::borrow::Cow; +use core::fmt::Debug; use num_traits::ToPrimitive; -use std::borrow::Cow; -use std::fmt::Debug; /// Valid type codes for ctypes simple types // spell-checker: disable-next-line @@ -27,22 +27,22 @@ pub(super) const SIMPLE_TYPE_CHARS: &str = "cbBhHiIlLdfuzZqQPXOv?g"; fn ctypes_code_to_pep3118(code: char) -> char { match code { // c_int: map based on sizeof(int) - 'i' if std::mem::size_of::() == 2 => 'h', - 'i' if std::mem::size_of::() == 4 => 'i', - 'i' if std::mem::size_of::() == 8 => 'q', - 'I' if std::mem::size_of::() == 2 => 'H', - 'I' if std::mem::size_of::() == 4 => 'I', - 'I' if std::mem::size_of::() == 8 => 'Q', + 'i' if core::mem::size_of::() == 2 => 'h', + 'i' if core::mem::size_of::() == 4 => 'i', + 'i' if core::mem::size_of::() == 8 => 'q', + 'I' if core::mem::size_of::() == 2 => 'H', + 'I' if core::mem::size_of::() == 4 => 'I', + 'I' if core::mem::size_of::() == 8 => 'Q', // c_long: map based on sizeof(long) - 'l' if std::mem::size_of::() == 4 => 'l', - 'l' if std::mem::size_of::() == 8 => 'q', - 'L' if std::mem::size_of::() == 4 => 'L', - 'L' if std::mem::size_of::() == 8 => 'Q', + 'l' if core::mem::size_of::() == 4 => 'l', + 'l' if core::mem::size_of::() == 8 => 'q', + 'L' if core::mem::size_of::() == 4 => 'L', + 'L' if core::mem::size_of::() == 8 => 'Q', // c_bool: map based on sizeof(bool) - typically 1 byte on all platforms - '?' if std::mem::size_of::() == 1 => '?', - '?' if std::mem::size_of::() == 2 => 'H', - '?' if std::mem::size_of::() == 4 => 'L', - '?' if std::mem::size_of::() == 8 => 'Q', + '?' if core::mem::size_of::() == 1 => '?', + '?' if core::mem::size_of::() == 2 => 'H', + '?' if core::mem::size_of::() == 4 => 'L', + '?' if core::mem::size_of::() == 8 => 'Q', // Default: use the same code _ => code, } @@ -268,7 +268,7 @@ impl PyCSimpleType { let create_simple_with_value = |type_str: &str, val: &PyObject| -> PyResult { let simple = new_simple_type(Either::B(&cls), vm)?; let buffer_bytes = value_to_bytes_endian(type_str, val, false, vm); - *simple.0.buffer.write() = std::borrow::Cow::Owned(buffer_bytes.clone()); + *simple.0.buffer.write() = alloc::borrow::Cow::Owned(buffer_bytes.clone()); let simple_obj: PyObjectRef = simple.into_ref_with_type(vm, cls.clone())?.into(); // from_param returns CArgObject, not the simple type itself let tag = type_str.as_bytes().first().copied().unwrap_or(b'?'); @@ -418,9 +418,9 @@ impl PyCSimpleType { if let Some(funcptr) = value.downcast_ref::() { let ptr_val = { let buffer = funcptr._base.buffer.read(); - if buffer.len() >= std::mem::size_of::() { + if buffer.len() >= core::mem::size_of::() { usize::from_ne_bytes( - buffer[..std::mem::size_of::()].try_into().unwrap(), + buffer[..core::mem::size_of::()].try_into().unwrap(), ) } else { 0 @@ -441,9 +441,9 @@ impl PyCSimpleType { if matches!(value_type_code.as_deref(), Some("z") | Some("Z")) { let ptr_val = { let buffer = simple.0.buffer.read(); - if buffer.len() >= std::mem::size_of::() { + if buffer.len() >= core::mem::size_of::() { usize::from_ne_bytes( - buffer[..std::mem::size_of::()].try_into().unwrap(), + buffer[..core::mem::size_of::()].try_into().unwrap(), ) } else { 0 @@ -712,7 +712,7 @@ fn create_swapped_types( pub struct PyCSimple(pub PyCData); impl Debug for PyCSimple { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCSimple") .field("size", &self.0.buffer.read().len()) .finish() @@ -833,7 +833,7 @@ fn value_to_bytes_endian( let v = int_val.as_bigint().to_i128().expect("int too large") as libc::c_long; return to_bytes!(v); } - const SIZE: usize = std::mem::size_of::(); + const SIZE: usize = core::mem::size_of::(); vec![0; SIZE] } "L" => { @@ -842,7 +842,7 @@ fn value_to_bytes_endian( let v = int_val.as_bigint().to_i128().expect("int too large") as libc::c_ulong; return to_bytes!(v); } - const SIZE: usize = std::mem::size_of::(); + const SIZE: usize = core::mem::size_of::(); vec![0; SIZE] } "q" => { @@ -938,7 +938,7 @@ fn value_to_bytes_endian( .expect("int too large for pointer"); return to_bytes!(v); } - vec![0; std::mem::size_of::()] + vec![0; core::mem::size_of::()] } "z" => { // c_char_p - pointer to char (stores pointer value from int) @@ -950,7 +950,7 @@ fn value_to_bytes_endian( .expect("int too large for pointer"); return to_bytes!(v); } - vec![0; std::mem::size_of::()] + vec![0; core::mem::size_of::()] } "Z" => { // c_wchar_p - pointer to wchar_t (stores pointer value from int) @@ -962,7 +962,7 @@ fn value_to_bytes_endian( .expect("int too large for pointer"); return to_bytes!(v); } - vec![0; std::mem::size_of::()] + vec![0; core::mem::size_of::()] } "O" => { // py_object - store object id as non-zero marker @@ -1166,7 +1166,7 @@ impl PyCSimple { } // Read null-terminated string at the address unsafe { - let cstr = std::ffi::CStr::from_ptr(ptr as _); + let cstr = core::ffi::CStr::from_ptr(ptr as _); return Ok(vm.ctx.new_bytes(cstr.to_bytes().to_vec()).into()); } } @@ -1183,7 +1183,7 @@ impl PyCSimple { unsafe { let w_ptr = ptr as *const libc::wchar_t; let len = libc::wcslen(w_ptr); - let wchars = std::slice::from_raw_parts(w_ptr, len); + let wchars = core::slice::from_raw_parts(w_ptr, len); #[cfg(windows)] { use rustpython_common::wtf8::Wtf8Buf; @@ -1221,13 +1221,13 @@ impl PyCSimple { // Read value from buffer, swap bytes if needed let buffer = zelf.0.buffer.read(); - let buffer_data: std::borrow::Cow<'_, [u8]> = if swapped { + let buffer_data: alloc::borrow::Cow<'_, [u8]> = if swapped { // Reverse bytes for swapped endian types let mut swapped_bytes = buffer.to_vec(); swapped_bytes.reverse(); - std::borrow::Cow::Owned(swapped_bytes) + alloc::borrow::Cow::Owned(swapped_bytes) } else { - std::borrow::Cow::Borrowed(&*buffer) + alloc::borrow::Cow::Borrowed(&*buffer) }; let cls_ref = cls.to_owned(); @@ -1269,7 +1269,7 @@ impl PyCSimple { if type_code == "z" { if let Some(bytes) = value.downcast_ref::() { let (converted, ptr) = super::base::ensure_z_null_terminated(bytes, vm); - *zelf.0.buffer.write() = std::borrow::Cow::Owned(ptr.to_ne_bytes().to_vec()); + *zelf.0.buffer.write() = alloc::borrow::Cow::Owned(ptr.to_ne_bytes().to_vec()); *zelf.0.objects.write() = Some(converted); return Ok(()); } @@ -1277,7 +1277,7 @@ impl PyCSimple { && let Some(s) = value.downcast_ref::() { let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_str(), vm); - *zelf.0.buffer.write() = std::borrow::Cow::Owned(ptr.to_ne_bytes().to_vec()); + *zelf.0.buffer.write() = alloc::borrow::Cow::Owned(ptr.to_ne_bytes().to_vec()); *zelf.0.objects.write() = Some(holder); return Ok(()); } @@ -1368,65 +1368,65 @@ impl PyCSimple { let buffer = self.0.buffer.read(); let bytes: &[u8] = &buffer; - if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::u8().as_raw_ptr()) { + if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::u8().as_raw_ptr()) { if !bytes.is_empty() { return Some(FfiArgValue::U8(bytes[0])); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::i8().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::i8().as_raw_ptr()) { if !bytes.is_empty() { return Some(FfiArgValue::I8(bytes[0] as i8)); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::u16().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::u16().as_raw_ptr()) { if bytes.len() >= 2 { return Some(FfiArgValue::U16(u16::from_ne_bytes([bytes[0], bytes[1]]))); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::i16().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::i16().as_raw_ptr()) { if bytes.len() >= 2 { return Some(FfiArgValue::I16(i16::from_ne_bytes([bytes[0], bytes[1]]))); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::u32().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::u32().as_raw_ptr()) { if bytes.len() >= 4 { return Some(FfiArgValue::U32(u32::from_ne_bytes([ bytes[0], bytes[1], bytes[2], bytes[3], ]))); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::i32().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::i32().as_raw_ptr()) { if bytes.len() >= 4 { return Some(FfiArgValue::I32(i32::from_ne_bytes([ bytes[0], bytes[1], bytes[2], bytes[3], ]))); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::u64().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::u64().as_raw_ptr()) { if bytes.len() >= 8 { return Some(FfiArgValue::U64(u64::from_ne_bytes([ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], ]))); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::i64().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::i64().as_raw_ptr()) { if bytes.len() >= 8 { return Some(FfiArgValue::I64(i64::from_ne_bytes([ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], ]))); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::f32().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::f32().as_raw_ptr()) { if bytes.len() >= 4 { return Some(FfiArgValue::F32(f32::from_ne_bytes([ bytes[0], bytes[1], bytes[2], bytes[3], ]))); } - } else if std::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::f64().as_raw_ptr()) { + } else if core::ptr::eq(ty.as_raw_ptr(), libffi::middle::Type::f64().as_raw_ptr()) { if bytes.len() >= 8 { return Some(FfiArgValue::F64(f64::from_ne_bytes([ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], ]))); } - } else if std::ptr::eq( + } else if core::ptr::eq( ty.as_raw_ptr(), libffi::middle::Type::pointer().as_raw_ptr(), - ) && bytes.len() >= std::mem::size_of::() + ) && bytes.len() >= core::mem::size_of::() { let val = - usize::from_ne_bytes(bytes[..std::mem::size_of::()].try_into().unwrap()); + usize::from_ne_bytes(bytes[..core::mem::size_of::()].try_into().unwrap()); return Some(FfiArgValue::Pointer(val)); } None diff --git a/crates/vm/src/stdlib/ctypes/structure.rs b/crates/vm/src/stdlib/ctypes/structure.rs index d5aca392c52..295ce0d87cf 100644 --- a/crates/vm/src/stdlib/ctypes/structure.rs +++ b/crates/vm/src/stdlib/ctypes/structure.rs @@ -6,9 +6,9 @@ use crate::function::PySetterValue; use crate::protocol::{BufferDescriptor, PyBuffer, PyNumberMethods}; use crate::types::{AsBuffer, AsNumber, Constructor, Initializer, SetAttr}; use crate::{AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine}; +use alloc::borrow::Cow; +use core::fmt::Debug; use num_traits::ToPrimitive; -use std::borrow::Cow; -use std::fmt::Debug; /// Calculate Structure type size from _fields_ (sum of field sizes) pub(super) fn calculate_struct_size(cls: &Py, vm: &VirtualMachine) -> PyResult { @@ -206,7 +206,7 @@ impl PyCStructType { { ( baseinfo.size, - std::cmp::max(baseinfo.align, forced_alignment), + core::cmp::max(baseinfo.align, forced_alignment), baseinfo.flags.contains(StgInfoFlags::TYPEFLAG_HASPOINTER), baseinfo.flags.contains(StgInfoFlags::TYPEFLAG_HASUNION), baseinfo.flags.contains(StgInfoFlags::TYPEFLAG_HASBITFIELD), @@ -252,7 +252,7 @@ impl PyCStructType { // Calculate effective alignment (PyCField_FromDesc) let effective_align = if pack > 0 { - std::cmp::min(pack, field_align) + core::cmp::min(pack, field_align) } else { field_align }; @@ -347,7 +347,7 @@ impl PyCStructType { } // Calculate total_align = max(max_align, forced_alignment) - let total_align = std::cmp::max(max_align, forced_alignment); + let total_align = core::cmp::max(max_align, forced_alignment); // Calculate aligned_size (PyCStructUnionType_update_stginfo) let aligned_size = if total_align > 0 { @@ -501,7 +501,7 @@ impl SetAttr for PyCStructType { pub struct PyCStructure(pub PyCData); impl Debug for PyCStructure { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCStructure") .field("size", &self.0.size()) .finish() diff --git a/crates/vm/src/stdlib/ctypes/union.rs b/crates/vm/src/stdlib/ctypes/union.rs index 41bc7492a25..0da1ffee3fd 100644 --- a/crates/vm/src/stdlib/ctypes/union.rs +++ b/crates/vm/src/stdlib/ctypes/union.rs @@ -7,7 +7,7 @@ use crate::function::PySetterValue; use crate::protocol::{BufferDescriptor, PyBuffer}; use crate::types::{AsBuffer, Constructor, Initializer, SetAttr}; use crate::{AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine}; -use std::borrow::Cow; +use alloc::borrow::Cow; /// Calculate Union type size from _fields_ (max field size) pub(super) fn calculate_union_size(cls: &Py, vm: &VirtualMachine) -> PyResult { @@ -175,7 +175,7 @@ impl PyCUnionType { { ( baseinfo.size, - std::cmp::max(baseinfo.align, forced_alignment), + core::cmp::max(baseinfo.align, forced_alignment), baseinfo.flags.contains(StgInfoFlags::TYPEFLAG_HASPOINTER), baseinfo.flags.contains(StgInfoFlags::TYPEFLAG_HASBITFIELD), baseinfo.ffi_field_types.clone(), @@ -215,7 +215,7 @@ impl PyCUnionType { // Calculate effective alignment let effective_align = if pack > 0 { - std::cmp::min(pack, field_align) + core::cmp::min(pack, field_align) } else { field_align }; @@ -264,7 +264,7 @@ impl PyCUnionType { } // Calculate total_align and aligned_size - let total_align = std::cmp::max(max_align, forced_alignment); + let total_align = core::cmp::max(max_align, forced_alignment); let aligned_size = if total_align > 0 { max_size.div_ceil(total_align) * total_align } else { @@ -418,8 +418,8 @@ impl SetAttr for PyCUnionType { #[repr(transparent)] pub struct PyCUnion(pub PyCData); -impl std::fmt::Debug for PyCUnion { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyCUnion { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCUnion") .field("size", &self.0.size()) .finish() diff --git a/crates/vm/src/stdlib/io.rs b/crates/vm/src/stdlib/io.rs index 89dc8bca925..bd451eff98e 100644 --- a/crates/vm/src/stdlib/io.rs +++ b/crates/vm/src/stdlib/io.rs @@ -53,7 +53,7 @@ impl ToOSErrorBuilder for std::io::Error { let msg = { let ptr = unsafe { libc::strerror(errno) }; if !ptr.is_null() { - unsafe { std::ffi::CStr::from_ptr(ptr) } + unsafe { core::ffi::CStr::from_ptr(ptr) } .to_string_lossy() .into_owned() } else { @@ -183,16 +183,16 @@ mod _io { }, vm::VirtualMachine, }; + use alloc::borrow::Cow; use bstr::ByteSlice; - use crossbeam_utils::atomic::AtomicCell; - use malachite_bigint::BigInt; - use num_traits::ToPrimitive; - use std::{ - borrow::Cow, - io::{self, Cursor, SeekFrom, prelude::*}, + use core::{ ops::Range, sync::atomic::{AtomicBool, Ordering}, }; + use crossbeam_utils::atomic::AtomicCell; + use malachite_bigint::BigInt; + use num_traits::ToPrimitive; + use std::io::{self, Cursor, SeekFrom, prelude::*}; #[allow(clippy::let_and_return)] fn validate_whence(whence: i32) -> bool { @@ -354,7 +354,7 @@ mod _io { // if we don't specify the number of bytes, or it's too big, give the whole rest of the slice let n = bytes.map_or_else( || avail_slice.len(), - |n| std::cmp::min(n, avail_slice.len()), + |n| core::cmp::min(n, avail_slice.len()), ); let b = avail_slice[..n].to_vec(); self.cursor.set_position((pos + n) as u64); @@ -1059,7 +1059,7 @@ mod _io { // TODO: loop if write() raises an interrupt vm.call_method(self.raw.as_ref().unwrap(), "write", (mem_obj,))? } else { - let v = std::mem::take(&mut self.buffer); + let v = core::mem::take(&mut self.buffer); let write_buf = VecBuffer::from(v).into_ref(&vm.ctx); let mem_obj = PyMemoryView::from_buffer_range( write_buf.clone().into_pybuffer(true), @@ -1330,7 +1330,7 @@ mod _io { let res = match v { Either::A(v) => { let v = v.unwrap_or(&mut self.buffer); - let read_buf = VecBuffer::from(std::mem::take(v)).into_ref(&vm.ctx); + let read_buf = VecBuffer::from(core::mem::take(v)).into_ref(&vm.ctx); let mem_obj = PyMemoryView::from_buffer_range( read_buf.clone().into_pybuffer(false), buf_range, @@ -1527,7 +1527,7 @@ mod _io { } else if !(readinto1 && written != 0) { let n = self.fill_buffer(vm)?; if let Some(n) = n.filter(|&n| n > 0) { - let n = std::cmp::min(n, remaining); + let n = core::cmp::min(n, remaining); buf.as_contiguous_mut().unwrap()[written..][..n] .copy_from_slice(&self.buffer[self.pos as usize..][..n]); self.pos += n as Offset; @@ -1881,7 +1881,7 @@ mod _io { } let have = data.readahead(); if have > 0 { - let n = std::cmp::min(have as usize, n); + let n = core::cmp::min(have as usize, n); return Ok(data.read_fast(n).unwrap()); } // Flush write buffer before reading @@ -2373,7 +2373,7 @@ mod _io { } } - impl std::ops::Add for Utf8size { + impl core::ops::Add for Utf8size { type Output = Self; #[inline] @@ -2383,7 +2383,7 @@ mod _io { } } - impl std::ops::AddAssign for Utf8size { + impl core::ops::AddAssign for Utf8size { #[inline] fn add_assign(&mut self, rhs: Self) { self.bytes += rhs.bytes; @@ -2391,7 +2391,7 @@ mod _io { } } - impl std::ops::Sub for Utf8size { + impl core::ops::Sub for Utf8size { type Output = Self; #[inline] @@ -2401,7 +2401,7 @@ mod _io { } } - impl std::ops::SubAssign for Utf8size { + impl core::ops::SubAssign for Utf8size { #[inline] fn sub_assign(&mut self, rhs: Self) { self.bytes -= rhs.bytes; @@ -2470,7 +2470,7 @@ mod _io { impl PendingWrites { fn push(&mut self, write: PendingWrite) { self.num_bytes += write.as_bytes().len(); - self.data = match std::mem::take(&mut self.data) { + self.data = match core::mem::take(&mut self.data) { PendingWritesData::None => PendingWritesData::One(write), PendingWritesData::One(write1) => PendingWritesData::Many(vec![write1, write]), PendingWritesData::Many(mut v) => { @@ -2480,13 +2480,13 @@ mod _io { } } fn take(&mut self, vm: &VirtualMachine) -> PyBytesRef { - let Self { num_bytes, data } = std::mem::take(self); + let Self { num_bytes, data } = core::mem::take(self); if let PendingWritesData::One(PendingWrite::Bytes(b)) = data { return b; } let writes_iter = match data { PendingWritesData::None => itertools::Either::Left(vec![].into_iter()), - PendingWritesData::One(write) => itertools::Either::Right(std::iter::once(write)), + PendingWritesData::One(write) => itertools::Either::Right(core::iter::once(write)), PendingWritesData::Many(writes) => itertools::Either::Left(writes.into_iter()), }; let mut buf = Vec::with_capacity(num_bytes); @@ -2508,7 +2508,7 @@ mod _io { impl TextIOCookie { const START_POS_OFF: usize = 0; - const DEC_FLAGS_OFF: usize = Self::START_POS_OFF + std::mem::size_of::(); + const DEC_FLAGS_OFF: usize = Self::START_POS_OFF + core::mem::size_of::(); const BYTES_TO_FEED_OFF: usize = Self::DEC_FLAGS_OFF + 4; const CHARS_TO_SKIP_OFF: usize = Self::BYTES_TO_FEED_OFF + 4; const NEED_EOF_OFF: usize = Self::CHARS_TO_SKIP_OFF + 4; @@ -2525,7 +2525,7 @@ mod _io { macro_rules! get_field { ($t:ty, $off:ident) => {{ <$t>::from_ne_bytes( - buf[Self::$off..][..std::mem::size_of::<$t>()] + buf[Self::$off..][..core::mem::size_of::<$t>()] .try_into() .unwrap(), ) @@ -2546,7 +2546,7 @@ mod _io { macro_rules! set_field { ($field:expr, $off:ident) => {{ let field = $field; - buf[Self::$off..][..std::mem::size_of_val(&field)] + buf[Self::$off..][..core::mem::size_of_val(&field)] .copy_from_slice(&field.to_ne_bytes()) }}; } @@ -3509,7 +3509,7 @@ mod _io { } else { size_hint }; - let chunk_size = std::cmp::max(self.chunk_size, size_hint); + let chunk_size = core::cmp::max(self.chunk_size, size_hint); let input_chunk = vm.call_method(&self.buffer, method, (chunk_size,))?; let buf = ArgBytesLike::try_from_borrowed_object(vm, &input_chunk).map_err(|_| { @@ -3591,8 +3591,8 @@ mod _io { vm: &VirtualMachine, ) -> PyStrRef { let empty_str = || vm.ctx.empty_str.to_owned(); - let chars_pos = std::mem::take(&mut self.decoded_chars_used).bytes; - let decoded_chars = match std::mem::take(&mut self.decoded_chars) { + let chars_pos = core::mem::take(&mut self.decoded_chars_used).bytes; + let decoded_chars = match core::mem::take(&mut self.decoded_chars) { None => return append.unwrap_or_else(empty_str), Some(s) if s.is_empty() => return append.unwrap_or_else(empty_str), Some(s) => s, @@ -4294,7 +4294,7 @@ mod _io { plus: bool, } - impl std::str::FromStr for Mode { + impl core::str::FromStr for Mode { type Err = ParseModeError; fn from_str(s: &str) -> Result { diff --git a/crates/vm/src/stdlib/itertools.rs b/crates/vm/src/stdlib/itertools.rs index 3fedd17f12b..3aad2f91931 100644 --- a/crates/vm/src/stdlib/itertools.rs +++ b/crates/vm/src/stdlib/itertools.rs @@ -25,8 +25,8 @@ mod decl { use malachite_bigint::BigInt; use num_traits::One; + use alloc::fmt; use num_traits::{Signed, ToPrimitive}; - use std::fmt; fn pickle_deprecation(vm: &VirtualMachine) -> PyResult<()> { warnings::warn( @@ -1320,7 +1320,7 @@ mod decl { for arg in iterables.iter() { pools.push(arg.try_to_value(vm)?); } - let pools = std::iter::repeat_n(pools, repeat) + let pools = core::iter::repeat_n(pools, repeat) .flatten() .collect::>>(); diff --git a/crates/vm/src/stdlib/mod.rs b/crates/vm/src/stdlib/mod.rs index 9fae516fe04..e46f333a28b 100644 --- a/crates/vm/src/stdlib/mod.rs +++ b/crates/vm/src/stdlib/mod.rs @@ -62,7 +62,8 @@ mod winapi; mod winreg; use crate::{PyRef, VirtualMachine, builtins::PyModule}; -use std::{borrow::Cow, collections::HashMap}; +use alloc::borrow::Cow; +use std::collections::HashMap; pub type StdlibInitFunc = Box PyRef)>; pub type StdlibMap = HashMap, StdlibInitFunc, ahash::RandomState>; diff --git a/crates/vm/src/stdlib/nt.rs b/crates/vm/src/stdlib/nt.rs index e056142658d..a32959808c0 100644 --- a/crates/vm/src/stdlib/nt.rs +++ b/crates/vm/src/stdlib/nt.rs @@ -497,7 +497,7 @@ pub(crate) mod module { wide_path.as_ptr(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - std::ptr::null(), + core::ptr::null(), OPEN_EXISTING, flags, std::ptr::null_mut(), @@ -517,7 +517,7 @@ pub(crate) mod module { wide_path.as_ptr(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - std::ptr::null(), + core::ptr::null(), OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, std::ptr::null_mut(), @@ -568,7 +568,7 @@ pub(crate) mod module { wide_path.as_ptr(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - std::ptr::null(), + core::ptr::null(), OPEN_EXISTING, flags, std::ptr::null_mut(), @@ -586,7 +586,7 @@ pub(crate) mod module { wide_path.as_ptr(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, - std::ptr::null(), + core::ptr::null(), OPEN_EXISTING, 0, std::ptr::null_mut(), @@ -733,7 +733,7 @@ pub(crate) mod module { volume.as_ptr(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, - std::ptr::null(), + core::ptr::null(), OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, std::ptr::null_mut(), @@ -862,7 +862,7 @@ pub(crate) mod module { conout.as_ptr(), Foundation::GENERIC_READ | Foundation::GENERIC_WRITE, FileSystem::FILE_SHARE_READ | FileSystem::FILE_SHARE_WRITE, - std::ptr::null(), + core::ptr::null(), FileSystem::OPEN_EXISTING, 0, std::ptr::null_mut(), @@ -933,7 +933,7 @@ pub(crate) mod module { let argv_spawn: Vec<*const u16> = argv .iter() .map(|v| v.as_ptr()) - .chain(once(std::ptr::null())) + .chain(once(core::ptr::null())) .collect(); let result = unsafe { suppress_iph!(_wspawnv(mode, path.as_ptr(), argv_spawn.as_ptr())) }; @@ -976,7 +976,7 @@ pub(crate) mod module { let argv_spawn: Vec<*const u16> = argv .iter() .map(|v| v.as_ptr()) - .chain(once(std::ptr::null())) + .chain(once(core::ptr::null())) .collect(); // Build environment strings as "KEY=VALUE\0" wide strings @@ -1004,7 +1004,7 @@ pub(crate) mod module { let envp: Vec<*const u16> = env_strings .iter() .map(|s| s.as_ptr()) - .chain(once(std::ptr::null())) + .chain(once(core::ptr::null())) .collect(); let result = unsafe { @@ -1052,7 +1052,7 @@ pub(crate) mod module { let argv_execv: Vec<*const u16> = argv .iter() .map(|v| v.as_ptr()) - .chain(once(std::ptr::null())) + .chain(once(core::ptr::null())) .collect(); if (unsafe { suppress_iph!(_wexecv(path.as_ptr(), argv_execv.as_ptr())) } == -1) { @@ -1093,7 +1093,7 @@ pub(crate) mod module { let argv_execve: Vec<*const u16> = argv .iter() .map(|v| v.as_ptr()) - .chain(once(std::ptr::null())) + .chain(once(core::ptr::null())) .collect(); // Build environment strings as "KEY=VALUE\0" wide strings @@ -1121,7 +1121,7 @@ pub(crate) mod module { let envp: Vec<*const u16> = env_strings .iter() .map(|s| s.as_ptr()) - .chain(once(std::ptr::null())) + .chain(once(core::ptr::null())) .collect(); if (unsafe { suppress_iph!(_wexecve(path.as_ptr(), argv_execve.as_ptr(), envp.as_ptr())) } @@ -1356,7 +1356,7 @@ pub(crate) mod module { .chain(std::iter::once(0)) // null-terminated .collect(); - let mut end: *const u16 = std::ptr::null(); + let mut end: *const u16 = core::ptr::null(); let hr = unsafe { windows_sys::Win32::UI::Shell::PathCchSkipRoot(backslashed.as_ptr(), &mut end) }; @@ -1667,7 +1667,7 @@ pub(crate) mod module { let res = CreatePipe( read.as_mut_ptr() as *mut _, write.as_mut_ptr() as *mut _, - std::ptr::null(), + core::ptr::null(), 0, ); if res == 0 { @@ -1723,7 +1723,7 @@ pub(crate) mod module { let Some(func) = func else { return 0; }; - let nt_query: NtQueryInformationProcessFn = unsafe { std::mem::transmute(func) }; + let nt_query: NtQueryInformationProcessFn = unsafe { core::mem::transmute(func) }; let mut info: PROCESS_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; @@ -1808,7 +1808,7 @@ pub(crate) mod module { wide_path.as_ptr(), 0, // No access needed, just reading reparse data FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - std::ptr::null(), + core::ptr::null(), OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, std::ptr::null_mut(), @@ -1832,7 +1832,7 @@ pub(crate) mod module { DeviceIoControl( handle, FSCTL_GET_REPARSE_POINT, - std::ptr::null(), + core::ptr::null(), 0, buffer.as_mut_ptr() as *mut _, BUFFER_SIZE as u32, diff --git a/crates/vm/src/stdlib/os.rs b/crates/vm/src/stdlib/os.rs index 6e2bb274fec..add8763f5e1 100644 --- a/crates/vm/src/stdlib/os.rs +++ b/crates/vm/src/stdlib/os.rs @@ -171,15 +171,10 @@ pub(super) mod _os { utils::ToCString, vm::VirtualMachine, }; + use core::time::Duration; use crossbeam_utils::atomic::AtomicCell; use itertools::Itertools; - use std::{ - env, fs, - fs::OpenOptions, - io, - path::PathBuf, - time::{Duration, SystemTime}, - }; + use std::{env, fs, fs::OpenOptions, io, path::PathBuf, time::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"))); @@ -518,7 +513,7 @@ pub(super) mod _os { 22, format!( "Invalid argument: {}", - std::str::from_utf8(key).unwrap_or("") + core::str::from_utf8(key).unwrap_or("") ), ); @@ -1051,12 +1046,12 @@ pub(super) mod _os { dir_fd: DirFd<'_, { STAT_DIR_FD as usize }>, follow_symlinks: FollowSymlinks, ) -> io::Result> { - let mut stat = std::mem::MaybeUninit::uninit(); + let mut stat = core::mem::MaybeUninit::uninit(); let ret = match file { OsPathOrFd::Path(path) => { use rustpython_common::os::ffi::OsStrExt; let path = path.as_ref().as_os_str().as_bytes(); - let path = match std::ffi::CString::new(path) { + let path = match alloc::ffi::CString::new(path) { Ok(x) => x, Err(_) => return Ok(None), }; @@ -1218,7 +1213,7 @@ pub(super) mod _os { use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Storage::FileSystem; let handle = crt_fd::as_handle(fd).map_err(|e| e.into_pyexception(vm))?; - let mut distance_to_move: [i32; 2] = std::mem::transmute(position); + let mut distance_to_move: [i32; 2] = core::mem::transmute(position); let ret = FileSystem::SetFilePointer( handle.as_raw_handle(), distance_to_move[0], @@ -1229,7 +1224,7 @@ pub(super) mod _os { -1 } else { distance_to_move[0] = ret as _; - std::mem::transmute::<[i32; 2], i64>(distance_to_move) + core::mem::transmute::<[i32; 2], i64>(distance_to_move) } }; if res < 0 { @@ -1411,7 +1406,7 @@ pub(super) mod _os { .map_err(|err| OSErrorBuilder::with_filename(&err, path.clone(), vm))?; let ret = unsafe { - FileSystem::SetFileTime(f.as_raw_handle() as _, std::ptr::null(), &acc, &modif) + FileSystem::SetFileTime(f.as_raw_handle() as _, core::ptr::null(), &acc, &modif) }; if ret == 0 { @@ -1532,9 +1527,9 @@ pub(super) mod _os { #[pyfunction] fn copy_file_range(args: CopyFileRangeArgs<'_>, vm: &VirtualMachine) -> PyResult { #[allow(clippy::unnecessary_option_map_or_else)] - let p_offset_src = args.offset_src.as_ref().map_or_else(std::ptr::null, |x| x); + let p_offset_src = args.offset_src.as_ref().map_or_else(core::ptr::null, |x| x); #[allow(clippy::unnecessary_option_map_or_else)] - let p_offset_dst = args.offset_dst.as_ref().map_or_else(std::ptr::null, |x| x); + let p_offset_dst = args.offset_dst.as_ref().map_or_else(core::ptr::null, |x| x); let count: usize = args .count .try_into() @@ -1566,7 +1561,7 @@ pub(super) mod _os { #[pyfunction] fn strerror(e: i32) -> String { - unsafe { std::ffi::CStr::from_ptr(libc::strerror(e)) } + unsafe { core::ffi::CStr::from_ptr(libc::strerror(e)) } .to_string_lossy() .into_owned() } @@ -1670,7 +1665,7 @@ pub(super) mod _os { if encoding.is_null() || encoding.read() == '\0' as libc::c_char { "UTF-8".to_owned() } else { - std::ffi::CStr::from_ptr(encoding).to_string_lossy().into_owned() + core::ffi::CStr::from_ptr(encoding).to_string_lossy().into_owned() } }; diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index efbd0cf9049..6414242ada9 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -33,15 +33,15 @@ pub mod module { types::{Constructor, Representable}, utils::ToCString, }; + use alloc::ffi::CString; use bitflags::bitflags; + use core::ffi::CStr; use nix::{ fcntl, unistd::{self, Gid, Pid, Uid}, }; use std::{ - env, - ffi::{CStr, CString}, - fs, io, + env, fs, io, os::fd::{AsFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}, }; use strum_macros::{EnumIter, EnumString}; @@ -917,7 +917,7 @@ pub mod module { #[pyfunction] fn sched_getparam(pid: libc::pid_t, vm: &VirtualMachine) -> PyResult { let param = unsafe { - let mut param = std::mem::MaybeUninit::uninit(); + let mut param = core::mem::MaybeUninit::uninit(); if -1 == libc::sched_getparam(pid, param.as_mut_ptr()) { return Err(vm.new_last_errno_error()); } @@ -1280,7 +1280,7 @@ pub mod module { } fn try_from_id(vm: &VirtualMachine, obj: PyObjectRef, typ_name: &str) -> PyResult { - use std::cmp::Ordering; + use core::cmp::Ordering; let i = obj .try_to_ref::(vm) .map_err(|_| { @@ -1838,9 +1838,9 @@ pub mod module { #[pyfunction] fn dup2(args: Dup2Args<'_>, vm: &VirtualMachine) -> PyResult { - let mut fd2 = std::mem::ManuallyDrop::new(args.fd2); + let mut fd2 = core::mem::ManuallyDrop::new(args.fd2); nix::unistd::dup2(args.fd, &mut fd2).map_err(|e| e.into_pyexception(vm))?; - let fd2 = std::mem::ManuallyDrop::into_inner(fd2); + let fd2 = core::mem::ManuallyDrop::into_inner(fd2); if !args.inheritable { super::set_inheritable(fd2.as_fd(), false).map_err(|e| e.into_pyexception(vm))? } diff --git a/crates/vm/src/stdlib/pwd.rs b/crates/vm/src/stdlib/pwd.rs index e4d7075dbc8..6405ed7be91 100644 --- a/crates/vm/src/stdlib/pwd.rs +++ b/crates/vm/src/stdlib/pwd.rs @@ -37,7 +37,7 @@ mod pwd { impl From for PasswdData { fn from(user: User) -> Self { // this is just a pain... - let cstr_lossy = |s: std::ffi::CString| { + let cstr_lossy = |s: alloc::ffi::CString| { s.into_string() .unwrap_or_else(|e| e.into_cstring().to_string_lossy().into_owned()) }; @@ -105,7 +105,7 @@ mod pwd { let mut list = Vec::new(); unsafe { libc::setpwent() }; - while let Some(ptr) = std::ptr::NonNull::new(unsafe { libc::getpwent() }) { + while let Some(ptr) = core::ptr::NonNull::new(unsafe { libc::getpwent() }) { let user = User::from(unsafe { ptr.as_ref() }); let passwd = PasswdData::from(user).to_pyobject(vm); list.push(passwd); diff --git a/crates/vm/src/stdlib/signal.rs b/crates/vm/src/stdlib/signal.rs index 810ffabefe6..dd0d9a7a96f 100644 --- a/crates/vm/src/stdlib/signal.rs +++ b/crates/vm/src/stdlib/signal.rs @@ -24,7 +24,7 @@ pub(crate) mod _signal { builtins::PyTypeRef, function::{ArgIntoFloat, OptionalArg}, }; - use std::sync::atomic::{self, Ordering}; + use core::sync::atomic::{self, Ordering}; #[cfg(any(unix, windows))] use libc::sighandler_t; @@ -301,7 +301,7 @@ pub(crate) mod _signal { it_value: double_to_timeval(seconds), it_interval: double_to_timeval(interval), }; - let mut old = std::mem::MaybeUninit::::uninit(); + let mut old = core::mem::MaybeUninit::::uninit(); #[cfg(any(target_os = "linux", target_os = "android"))] let ret = unsafe { ffi::setitimer(which, &new, old.as_mut_ptr()) }; #[cfg(not(any(target_os = "linux", target_os = "android")))] @@ -318,7 +318,7 @@ pub(crate) mod _signal { #[cfg(unix)] #[pyfunction] fn getitimer(which: i32, vm: &VirtualMachine) -> PyResult<(f64, f64)> { - let mut old = std::mem::MaybeUninit::::uninit(); + let mut old = core::mem::MaybeUninit::::uninit(); #[cfg(any(target_os = "linux", target_os = "android"))] let ret = unsafe { ffi::getitimer(which, old.as_mut_ptr()) }; #[cfg(not(any(target_os = "linux", target_os = "android")))] @@ -489,7 +489,7 @@ pub(crate) mod _signal { if s.is_null() { Ok(None) } else { - let cstr = unsafe { std::ffi::CStr::from_ptr(s) }; + let cstr = unsafe { core::ffi::CStr::from_ptr(s) }; Ok(Some(cstr.to_string_lossy().into_owned())) } } @@ -522,7 +522,7 @@ pub(crate) mod _signal { #[cfg(unix)] { // Use sigfillset to get all valid signals - let mut mask: libc::sigset_t = unsafe { std::mem::zeroed() }; + let mut mask: libc::sigset_t = unsafe { core::mem::zeroed() }; // SAFETY: mask is a valid pointer if unsafe { libc::sigfillset(&mut mask) } != 0 { return Err(vm.new_os_error("sigfillset failed".to_owned())); @@ -580,7 +580,7 @@ pub(crate) mod _signal { use crate::convert::IntoPyException; // Initialize sigset - let mut sigset: libc::sigset_t = unsafe { std::mem::zeroed() }; + let mut sigset: libc::sigset_t = unsafe { core::mem::zeroed() }; // SAFETY: sigset is a valid pointer if unsafe { libc::sigemptyset(&mut sigset) } != 0 { return Err(std::io::Error::last_os_error().into_pyexception(vm)); @@ -611,7 +611,7 @@ pub(crate) mod _signal { } // Call pthread_sigmask - let mut old_mask: libc::sigset_t = unsafe { std::mem::zeroed() }; + let mut old_mask: libc::sigset_t = unsafe { core::mem::zeroed() }; // SAFETY: all pointers are valid let err = unsafe { libc::pthread_sigmask(how, &sigset, &mut old_mask) }; if err != 0 { diff --git a/crates/vm/src/stdlib/string.rs b/crates/vm/src/stdlib/string.rs index 576cae62775..a9911f3d45f 100644 --- a/crates/vm/src/stdlib/string.rs +++ b/crates/vm/src/stdlib/string.rs @@ -16,7 +16,7 @@ mod _string { convert::ToPyException, convert::ToPyObject, }; - use std::mem; + use core::mem; fn create_format_part( literal: Wtf8Buf, diff --git a/crates/vm/src/stdlib/symtable.rs b/crates/vm/src/stdlib/symtable.rs index 8a142857787..51c5c8e47ea 100644 --- a/crates/vm/src/stdlib/symtable.rs +++ b/crates/vm/src/stdlib/symtable.rs @@ -7,10 +7,10 @@ mod symtable { builtins::{PyDictRef, PyStrRef}, compiler, }; + use alloc::fmt; use rustpython_codegen::symboltable::{ CompilerScope, Symbol, SymbolFlags, SymbolScope, SymbolTable, }; - use std::fmt; // Consts as defined at // https://github.com/python/cpython/blob/6cb20a219a860eaf687b2d968b41c480c7461909/Include/internal/pycore_symtable.h#L156 @@ -180,7 +180,7 @@ mod symtable { #[pygetset] fn id(&self) -> usize { - self as *const Self as *const std::ffi::c_void as usize + self as *const Self as *const core::ffi::c_void as usize } #[pygetset] diff --git a/crates/vm/src/stdlib/sys.rs b/crates/vm/src/stdlib/sys.rs index 92b15878b46..30f126b3742 100644 --- a/crates/vm/src/stdlib/sys.rs +++ b/crates/vm/src/stdlib/sys.rs @@ -24,11 +24,11 @@ mod sys { version, vm::{Settings, VirtualMachine}, }; + use core::sync::atomic::Ordering; use num_traits::ToPrimitive; use std::{ env::{self, VarError}, io::Read, - sync::atomic::Ordering, }; #[cfg(windows)] @@ -67,7 +67,7 @@ mod sys { #[pyattr(name = "maxsize")] pub(crate) const MAXSIZE: isize = isize::MAX; #[pyattr(name = "maxunicode")] - const MAXUNICODE: u32 = std::char::MAX as u32; + const MAXUNICODE: u32 = core::char::MAX as u32; #[pyattr(name = "platform")] pub(crate) const PLATFORM: &str = { cfg_if::cfg_if! { @@ -751,7 +751,7 @@ mod sys { let sizeof = || -> PyResult { let res = vm.call_special_method(&args.obj, identifier!(vm, __sizeof__), ())?; let res = res.try_index(vm)?.try_to_primitive::(vm)?; - Ok(res + std::mem::size_of::()) + Ok(res + core::mem::size_of::()) }; sizeof() .map(|x| vm.ctx.new_int(x).into()) @@ -1377,7 +1377,7 @@ mod sys { const INFO: Self = { use rustpython_common::hash::*; Self { - width: std::mem::size_of::() * 8, + width: core::mem::size_of::() * 8, modulus: MODULUS, inf: INF, nan: NAN, @@ -1407,7 +1407,7 @@ mod sys { impl IntInfoData { const INFO: Self = Self { bits_per_digit: 30, //? - sizeof_digit: std::mem::size_of::(), + sizeof_digit: core::mem::size_of::(), default_max_str_digits: 4300, str_digits_check_threshold: 640, }; @@ -1525,7 +1525,7 @@ pub(crate) fn init_module(vm: &VirtualMachine, module: &Py, builtins: pub struct PyStderr<'vm>(pub &'vm VirtualMachine); impl PyStderr<'_> { - pub fn write_fmt(&self, args: std::fmt::Arguments<'_>) { + pub fn write_fmt(&self, args: core::fmt::Arguments<'_>) { use crate::py_io::Write; let vm = self.0; diff --git a/crates/vm/src/stdlib/thread.rs b/crates/vm/src/stdlib/thread.rs index fd300ac2f74..6ab754be094 100644 --- a/crates/vm/src/stdlib/thread.rs +++ b/crates/vm/src/stdlib/thread.rs @@ -11,12 +11,14 @@ pub(crate) mod _thread { function::{ArgCallable, Either, FuncArgs, KwArgs, OptionalArg, PySetterValue}, types::{Constructor, GetAttr, Representable, SetAttr}, }; + use alloc::fmt; + use core::{cell::RefCell, time::Duration}; use crossbeam_utils::atomic::AtomicCell; use parking_lot::{ RawMutex, RawThreadId, lock_api::{RawMutex as RawMutexT, RawMutexTimed, RawReentrantMutex}, }; - use std::{cell::RefCell, fmt, thread, time::Duration}; + use std::thread; use thread_local::ThreadLocal; // PYTHREAD_NAME: show current thread name @@ -151,7 +153,7 @@ pub(crate) mod _thread { let new_mut = RawMutex::INIT; unsafe { - let old_mutex: &AtomicCell = std::mem::transmute(&self.mu); + let old_mutex: &AtomicCell = core::mem::transmute(&self.mu); old_mutex.swap(new_mut); } @@ -287,7 +289,7 @@ pub(crate) mod _thread { } fn thread_to_id(t: &thread::Thread) -> u64 { - use std::hash::{Hash, Hasher}; + use core::hash::{Hash, Hasher}; struct U64Hash { v: Option, } diff --git a/crates/vm/src/stdlib/time.rs b/crates/vm/src/stdlib/time.rs index b9b53cdc5c5..97d60ae98a1 100644 --- a/crates/vm/src/stdlib/time.rs +++ b/crates/vm/src/stdlib/time.rs @@ -21,12 +21,12 @@ pub(crate) fn make_module(vm: &VirtualMachine) -> PyRef { unsafe extern "C" { #[cfg(not(target_os = "freebsd"))] #[link_name = "daylight"] - static c_daylight: std::ffi::c_int; + static c_daylight: core::ffi::c_int; // pub static dstbias: std::ffi::c_int; #[link_name = "timezone"] - static c_timezone: std::ffi::c_long; + static c_timezone: core::ffi::c_long; #[link_name = "tzname"] - static c_tzname: [*const std::ffi::c_char; 2]; + static c_tzname: [*const core::ffi::c_char; 2]; #[link_name = "tzset"] fn c_tzset(); } @@ -43,7 +43,7 @@ mod decl { DateTime, Datelike, TimeZone, Timelike, naive::{NaiveDate, NaiveDateTime, NaiveTime}, }; - use std::time::Duration; + use core::time::Duration; #[cfg(target_env = "msvc")] #[cfg(not(target_arch = "wasm32"))] use windows_sys::Win32::System::Time::{GetTimeZoneInformation, TIME_ZONE_INFORMATION}; @@ -104,7 +104,7 @@ mod decl { { // this is basically std::thread::sleep, but that catches interrupts and we don't want to; let ts = nix::sys::time::TimeSpec::from(dur); - let res = unsafe { libc::nanosleep(ts.as_ref(), std::ptr::null_mut()) }; + let res = unsafe { libc::nanosleep(ts.as_ref(), core::ptr::null_mut()) }; let interrupted = res == -1 && nix::Error::last_raw() == libc::EINTR; if interrupted { @@ -200,7 +200,7 @@ mod decl { #[cfg(not(target_env = "msvc"))] #[cfg(not(target_arch = "wasm32"))] #[pyattr] - fn timezone(_vm: &VirtualMachine) -> std::ffi::c_long { + fn timezone(_vm: &VirtualMachine) -> core::ffi::c_long { unsafe { super::c_timezone } } @@ -217,7 +217,7 @@ mod decl { #[cfg(not(target_env = "msvc"))] #[cfg(not(target_arch = "wasm32"))] #[pyattr] - fn daylight(_vm: &VirtualMachine) -> std::ffi::c_int { + fn daylight(_vm: &VirtualMachine) -> core::ffi::c_int { unsafe { super::c_daylight } } @@ -236,8 +236,8 @@ mod decl { fn tzname(vm: &VirtualMachine) -> crate::builtins::PyTupleRef { use crate::builtins::tuple::IntoPyTuple; - unsafe fn to_str(s: *const std::ffi::c_char) -> String { - unsafe { std::ffi::CStr::from_ptr(s) } + unsafe fn to_str(s: *const core::ffi::c_char) -> String { + unsafe { core::ffi::CStr::from_ptr(s) } .to_string_lossy() .into_owned() } @@ -357,7 +357,7 @@ mod decl { t: OptionalArg, vm: &VirtualMachine, ) -> PyResult { - use std::fmt::Write; + use core::fmt::Write; let instant = t.naive_or_local(vm)?; @@ -500,8 +500,8 @@ mod decl { pub tm_zone: PyObjectRef, } - impl std::fmt::Debug for StructTimeData { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + impl core::fmt::Debug for StructTimeData { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "struct_time()") } } @@ -590,8 +590,8 @@ mod platform { builtins::{PyNamespace, PyStrRef}, convert::IntoPyException, }; + use core::time::Duration; use nix::{sys::time::TimeSpec, time::ClockId}; - use std::time::Duration; #[cfg(target_os = "solaris")] #[pyattr] @@ -818,7 +818,7 @@ mod platform { fn u64_from_filetime(time: FILETIME) -> u64 { let large: [u32; 2] = [time.dwLowDateTime, time.dwHighDateTime]; - unsafe { std::mem::transmute(large) } + unsafe { core::mem::transmute(large) } } fn win_perf_counter_frequency(vm: &VirtualMachine) -> PyResult { diff --git a/crates/vm/src/stdlib/winapi.rs b/crates/vm/src/stdlib/winapi.rs index 5cfb62fad6f..f01843f6f62 100644 --- a/crates/vm/src/stdlib/winapi.rs +++ b/crates/vm/src/stdlib/winapi.rs @@ -107,7 +107,7 @@ mod _winapi { WindowsSysResult(windows_sys::Win32::System::Pipes::CreatePipe( read.as_mut_ptr(), write.as_mut_ptr(), - std::ptr::null(), + core::ptr::null(), size, )) .to_pyresult(vm)?; @@ -278,8 +278,8 @@ mod _winapi { WindowsSysResult(windows_sys::Win32::System::Threading::CreateProcessW( app_name, command_line, - std::ptr::null(), - std::ptr::null(), + core::ptr::null(), + core::ptr::null(), args.inherit_handles, args.creation_flags | windows_sys::Win32::System::Threading::EXTENDED_STARTUPINFO_PRESENT @@ -454,7 +454,7 @@ mod _winapi { handlelist.as_mut_ptr() as _, (handlelist.len() * std::mem::size_of::()) as _, std::ptr::null_mut(), - std::ptr::null(), + core::ptr::null(), ) }) .into_pyresult(vm)?; @@ -873,7 +873,7 @@ mod _winapi { } let buf = buffer.borrow_buf(); - let len = std::cmp::min(buf.len(), u32::MAX as usize) as u32; + let len = core::cmp::min(buf.len(), u32::MAX as usize) as u32; let mut written: u32 = 0; let ret = unsafe { @@ -947,7 +947,7 @@ mod _winapi { let mut batches: Vec> = Vec::new(); let mut i = 0; while i < nhandles { - let end = std::cmp::min(i + batch_size, nhandles); + let end = core::cmp::min(i + batch_size, nhandles); batches.push(handles[i..end].to_vec()); i = end; } diff --git a/crates/vm/src/stdlib/winreg.rs b/crates/vm/src/stdlib/winreg.rs index b5e568fce6d..f3d8ca10768 100644 --- a/crates/vm/src/stdlib/winreg.rs +++ b/crates/vm/src/stdlib/winreg.rs @@ -367,10 +367,10 @@ mod winreg { key, wide_sub_key.as_ptr(), args.reserved, - std::ptr::null(), + core::ptr::null(), Registry::REG_OPTION_NON_VOLATILE, args.access, - std::ptr::null(), + core::ptr::null(), &mut res, std::ptr::null_mut(), ) @@ -404,7 +404,9 @@ mod winreg { #[pyfunction] fn DeleteValue(key: PyRef, value: Option, vm: &VirtualMachine) -> PyResult<()> { let wide_value = value.map(|v| v.to_wide_with_nul()); - let value_ptr = wide_value.as_ref().map_or(std::ptr::null(), |v| v.as_ptr()); + let value_ptr = wide_value + .as_ref() + .map_or(core::ptr::null(), |v| v.as_ptr()); let res = unsafe { Registry::RegDeleteValueW(key.hkey.load(), value_ptr) }; if res == 0 { Ok(()) @@ -713,7 +715,7 @@ mod winreg { let res = unsafe { Registry::RegQueryValueExW( target_key, - std::ptr::null(), // NULL value name for default value + core::ptr::null(), // NULL value name for default value std::ptr::null_mut(), &mut reg_type, buffer.as_mut_ptr(), @@ -871,10 +873,10 @@ mod winreg { hkey, wide_sub_key.as_ptr(), 0, - std::ptr::null(), + core::ptr::null(), 0, Registry::KEY_SET_VALUE, - std::ptr::null(), + core::ptr::null(), &mut out_key, std::ptr::null_mut(), ) @@ -893,7 +895,7 @@ mod winreg { let res = unsafe { Registry::RegSetValueExW( target_key, - std::ptr::null(), // value name is NULL + core::ptr::null(), // value name is NULL 0, typ, wide_value.as_ptr() as *const u8, @@ -1104,7 +1106,7 @@ mod winreg { } Ok(None) => { let len = 0; - let ptr = std::ptr::null(); + let ptr = core::ptr::null(); let wide_value_name = value_name.to_wide_with_nul(); let res = unsafe { Registry::RegSetValueExW( diff --git a/crates/vm/src/suggestion.rs b/crates/vm/src/suggestion.rs index 866deb668eb..55326d1d3f0 100644 --- a/crates/vm/src/suggestion.rs +++ b/crates/vm/src/suggestion.rs @@ -7,8 +7,8 @@ use crate::{ exceptions::types::PyBaseException, sliceable::SliceableSequenceOp, }; +use core::iter::ExactSizeIterator; use rustpython_common::str::levenshtein::{MOVE_COST, levenshtein_distance}; -use std::iter::ExactSizeIterator; const MAX_CANDIDATE_ITEMS: usize = 750; diff --git a/crates/vm/src/types/slot.rs b/crates/vm/src/types/slot.rs index 658e21cba8a..9d7d09f2d18 100644 --- a/crates/vm/src/types/slot.rs +++ b/crates/vm/src/types/slot.rs @@ -17,9 +17,9 @@ use crate::{ types::slot_defs::{SlotAccessor, find_slot_defs_by_name}, vm::Context, }; +use core::{any::Any, any::TypeId, borrow::Borrow, cmp::Ordering, ops::Deref}; use crossbeam_utils::atomic::AtomicCell; use num_traits::{Signed, ToPrimitive}; -use std::{any::Any, any::TypeId, borrow::Borrow, cmp::Ordering, ops::Deref}; /// Type-erased storage for extension module data attached to heap types. pub struct TypeDataSlot { @@ -71,7 +71,7 @@ impl<'a, T: Any + 'static> TypeDataRef<'a, T> { } } -impl std::ops::Deref for TypeDataRef<'_, T> { +impl core::ops::Deref for TypeDataRef<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -96,7 +96,7 @@ impl<'a, T: Any + 'static> TypeDataRefMut<'a, T> { } } -impl std::ops::Deref for TypeDataRefMut<'_, T> { +impl core::ops::Deref for TypeDataRefMut<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -104,7 +104,7 @@ impl std::ops::Deref for TypeDataRefMut<'_, T> { } } -impl std::ops::DerefMut for TypeDataRefMut<'_, T> { +impl core::ops::DerefMut for TypeDataRefMut<'_, T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.guard } @@ -203,8 +203,8 @@ impl PyTypeSlots { } } -impl std::fmt::Debug for PyTypeSlots { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for PyTypeSlots { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("PyTypeSlots") } } @@ -1310,7 +1310,7 @@ impl PyType { /// - Special class type handling (e.g., `PyType` and its metaclasses) /// - Post-creation mutations that require `PyRef` #[pyclass] -pub trait Constructor: PyPayload + std::fmt::Debug { +pub trait Constructor: PyPayload + core::fmt::Debug { type Args: FromArgs; /// The type slot for `__new__`. Override this only when you need special @@ -1328,7 +1328,7 @@ pub trait Constructor: PyPayload + std::fmt::Debug { fn py_new(cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult; } -pub trait DefaultConstructor: PyPayload + Default + std::fmt::Debug { +pub trait DefaultConstructor: PyPayload + Default + core::fmt::Debug { fn construct_and_init(args: Self::Args, vm: &VirtualMachine) -> PyResult> where Self: Initializer, @@ -1862,7 +1862,7 @@ pub trait Iterable: PyPayload { fn extend_slots(_slots: &mut PyTypeSlots) {} } -// `Iterator` fits better, but to avoid confusion with rust std::iter::Iterator +// `Iterator` fits better, but to avoid confusion with rust core::iter::Iterator #[pyclass(with(Iterable))] pub trait IterNext: PyPayload + Iterable { #[pyslot] diff --git a/crates/vm/src/utils.rs b/crates/vm/src/utils.rs index af34405c7be..db232e81949 100644 --- a/crates/vm/src/utils.rs +++ b/crates/vm/src/utils.rs @@ -14,15 +14,15 @@ pub fn hash_iter<'a, I: IntoIterator>( vm.state.hash_secret.hash_iter(iter, |obj| obj.hash(vm)) } -impl ToPyObject for std::convert::Infallible { +impl ToPyObject for core::convert::Infallible { fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { match self {} } } pub trait ToCString: AsRef { - fn to_cstring(&self, vm: &VirtualMachine) -> PyResult { - std::ffi::CString::new(self.as_ref().as_bytes()).map_err(|err| err.to_pyexception(vm)) + fn to_cstring(&self, vm: &VirtualMachine) -> PyResult { + alloc::ffi::CString::new(self.as_ref().as_bytes()).map_err(|err| err.to_pyexception(vm)) } fn ensure_no_nul(&self, vm: &VirtualMachine) -> PyResult<()> { if self.as_ref().as_bytes().contains(&b'\0') { @@ -45,7 +45,7 @@ pub(crate) fn collection_repr<'a, I>( vm: &VirtualMachine, ) -> PyResult where - I: std::iter::Iterator, + I: core::iter::Iterator, { let mut repr = String::new(); if let Some(name) = class_name { diff --git a/crates/vm/src/version.rs b/crates/vm/src/version.rs index 0a598842a56..cc118ee5b0e 100644 --- a/crates/vm/src/version.rs +++ b/crates/vm/src/version.rs @@ -1,7 +1,8 @@ //! Several function to retrieve version information. use chrono::{Local, prelude::DateTime}; -use std::time::{Duration, UNIX_EPOCH}; +use core::time::Duration; +use std::time::UNIX_EPOCH; // = 3.13.0alpha pub const MAJOR: usize = 3; diff --git a/crates/vm/src/vm/context.rs b/crates/vm/src/vm/context.rs index 486c1861fb1..b12352f6eee 100644 --- a/crates/vm/src/vm/context.rs +++ b/crates/vm/src/vm/context.rs @@ -264,7 +264,7 @@ declare_const_name! { // Basic objects: impl Context { - pub const INT_CACHE_POOL_RANGE: std::ops::RangeInclusive = (-5)..=256; + pub const INT_CACHE_POOL_RANGE: core::ops::RangeInclusive = (-5)..=256; const INT_CACHE_POOL_MIN: i32 = *Self::INT_CACHE_POOL_RANGE.start(); pub fn genesis() -> &'static PyRc { @@ -374,14 +374,14 @@ impl Context { #[inline] pub fn empty_tuple_typed(&self) -> &Py> { let py: &Py = &self.empty_tuple; - unsafe { std::mem::transmute(py) } + unsafe { core::mem::transmute(py) } } // universal pyref constructor pub fn new_pyref(&self, value: T) -> PyRef

where T: Into

, - P: PyPayload + std::fmt::Debug, + P: PyPayload + core::fmt::Debug, { value.into().into_ref(self) } diff --git a/crates/vm/src/vm/interpreter.rs b/crates/vm/src/vm/interpreter.rs index 503feb3dc7f..8d37ad6c840 100644 --- a/crates/vm/src/vm/interpreter.rs +++ b/crates/vm/src/vm/interpreter.rs @@ -1,6 +1,6 @@ use super::{Context, PyConfig, VirtualMachine, setting::Settings, thread}; use crate::{PyResult, getpath, stdlib::atexit, vm::PyBaseExceptionRef}; -use std::sync::atomic::Ordering; +use core::sync::atomic::Ordering; /// The general interface for the VM /// diff --git a/crates/vm/src/vm/mod.rs b/crates/vm/src/vm/mod.rs index 34092454059..7c527b3e0da 100644 --- a/crates/vm/src/vm/mod.rs +++ b/crates/vm/src/vm/mod.rs @@ -33,6 +33,11 @@ use crate::{ signal, stdlib, warn::WarningsState, }; +use alloc::borrow::Cow; +use core::{ + cell::{Cell, Ref, RefCell}, + sync::atomic::AtomicBool, +}; use crossbeam_utils::atomic::AtomicCell; #[cfg(unix)] use nix::{ @@ -40,11 +45,8 @@ use nix::{ unistd::getpid, }; use std::{ - borrow::Cow, - cell::{Cell, Ref, RefCell}, collections::{HashMap, HashSet}, ffi::{OsStr, OsString}, - sync::atomic::AtomicBool, }; pub use context::Context; @@ -789,14 +791,14 @@ impl VirtualMachine { pub(crate) fn push_exception(&self, exc: Option) { let mut excs = self.exceptions.borrow_mut(); - let prev = std::mem::take(&mut *excs); + let prev = core::mem::take(&mut *excs); excs.prev = Some(Box::new(prev)); excs.exc = exc } pub(crate) fn pop_exception(&self) -> Option { let mut excs = self.exceptions.borrow_mut(); - let cur = std::mem::take(&mut *excs); + let cur = core::mem::take(&mut *excs); *excs = *cur.prev.expect("pop_exception() without nested exc stack"); cur.exc } @@ -811,7 +813,7 @@ impl VirtualMachine { pub(crate) fn set_exception(&self, exc: Option) { // don't be holding the RefCell guard while __del__ is called - let prev = std::mem::replace(&mut self.exceptions.borrow_mut().exc, exc); + let prev = core::mem::replace(&mut self.exceptions.borrow_mut().exc, exc); drop(prev); } @@ -984,7 +986,7 @@ impl AsRef for VirtualMachine { } fn core_frozen_inits() -> impl Iterator { - let iter = std::iter::empty(); + let iter = core::iter::empty(); macro_rules! ext_modules { ($iter:ident, $($t:tt)*) => { let $iter = $iter.chain(py_freeze!($($t)*)); diff --git a/crates/vm/src/vm/thread.rs b/crates/vm/src/vm/thread.rs index 2e687d99820..7e8f0f87e56 100644 --- a/crates/vm/src/vm/thread.rs +++ b/crates/vm/src/vm/thread.rs @@ -1,10 +1,10 @@ use crate::{AsObject, PyObject, PyObjectRef, VirtualMachine}; -use itertools::Itertools; -use std::{ +use core::{ cell::{Cell, RefCell}, ptr::NonNull, - thread_local, }; +use itertools::Itertools; +use std::thread_local; thread_local! { pub(super) static VM_STACK: RefCell>> = Vec::with_capacity(1).into(); diff --git a/crates/vm/src/vm/vm_new.rs b/crates/vm/src/vm/vm_new.rs index 6d0e983c844..ba09c8ecf69 100644 --- a/crates/vm/src/vm/vm_new.rs +++ b/crates/vm/src/vm/vm_new.rs @@ -95,7 +95,7 @@ impl VirtualMachine { pub fn new_exception(&self, exc_type: PyTypeRef, args: Vec) -> PyBaseExceptionRef { debug_assert_eq!( exc_type.slots.basicsize, - std::mem::size_of::(), + core::mem::size_of::(), "vm.new_exception() is only for exception types without additional payload. The given type '{}' is not allowed.", exc_type.class().name() ); @@ -118,7 +118,7 @@ impl VirtualMachine { errno: Option, msg: impl ToPyObject, ) -> PyRef { - debug_assert_eq!(exc_type.slots.basicsize, std::mem::size_of::()); + debug_assert_eq!(exc_type.slots.basicsize, core::mem::size_of::()); OSErrorBuilder::with_subtype(exc_type, errno, msg, self).build(self) } diff --git a/crates/vm/src/vm/vm_ops.rs b/crates/vm/src/vm/vm_ops.rs index 635fa10e630..1d466984377 100644 --- a/crates/vm/src/vm/vm_ops.rs +++ b/crates/vm/src/vm/vm_ops.rs @@ -302,8 +302,8 @@ impl VirtualMachine { } if let Some(slot_c) = class_c.slots.as_number.left_ternary_op(op_slot) - && slot_a.is_some_and(|slot_a| !std::ptr::fn_addr_eq(slot_a, slot_c)) - && slot_b.is_some_and(|slot_b| !std::ptr::fn_addr_eq(slot_b, slot_c)) + && slot_a.is_some_and(|slot_a| !core::ptr::fn_addr_eq(slot_a, slot_c)) + && slot_b.is_some_and(|slot_b| !core::ptr::fn_addr_eq(slot_b, slot_c)) { let ret = slot_c(a, b, c, self)?; if !ret.is(&self.ctx.not_implemented) { diff --git a/crates/vm/src/warn.rs b/crates/vm/src/warn.rs index 3dbd43ab537..09d48078e56 100644 --- a/crates/vm/src/warn.rs +++ b/crates/vm/src/warn.rs @@ -60,7 +60,7 @@ fn get_warnings_attr( && !vm .state .finalizing - .load(std::sync::atomic::Ordering::SeqCst) + .load(core::sync::atomic::Ordering::SeqCst) { match vm.import("warnings", 0) { Ok(module) => module, diff --git a/crates/vm/src/windows.rs b/crates/vm/src/windows.rs index ccf940811b8..ff2b612c06d 100644 --- a/crates/vm/src/windows.rs +++ b/crates/vm/src/windows.rs @@ -301,7 +301,7 @@ fn win32_xstat_slow_impl(path: &OsStr, traverse: bool) -> std::io::Result std::io::Result std::io::Result PyResult<()> { } #[cfg(feature = "flame-it")] -fn write_profile(settings: &Settings) -> Result<(), Box> { +fn write_profile(settings: &Settings) -> Result<(), Box> { use std::{fs, io}; enum ProfileFormat {