diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 87c59734af4..9cc89ecd7c6 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -74,7 +74,7 @@ jobs: uses: ./.github/actions/install-macos-deps - name: run clippy - run: cargo clippy ${{ env.CARGO_ARGS }} --workspace --all-targets ${{ env.WORKSPACE_EXCLUDES }} -- -Dwarnings + run: cargo clippy --keep-going ${{ env.CARGO_ARGS }} --workspace --all-targets ${{ env.WORKSPACE_EXCLUDES }} -- -Dwarnings - name: run rust tests run: cargo test --workspace ${{ env.WORKSPACE_EXCLUDES }} --verbose --features threading ${{ env.CARGO_ARGS }} @@ -518,7 +518,7 @@ jobs: ${{ runner.os }}- - name: cargo clippy - run: cargo clippy --manifest-path=crates/wasm/Cargo.toml -- -Dwarnings + run: cargo clippy --keep-going --manifest-path=crates/wasm/Cargo.toml -- -Dwarnings - name: install wasm-pack run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh diff --git a/Cargo.toml b/Cargo.toml index 4e4092f3a5d..58606ed74a2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -247,6 +247,7 @@ wasm-bindgen = "0.2.106" unsafe_code = "allow" unsafe_op_in_unsafe_fn = "deny" elided_lifetimes_in_paths = "warn" +unreachable_pub = "warn" [workspace.lints.clippy] alloc_instead_of_core = "warn" diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index bafc7c81cf1..6d11df7bd08 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -391,7 +391,7 @@ type SymbolMap = IndexMap; mod stack { use alloc::vec::Vec; use core::ptr::NonNull; - pub struct StackStack { + pub(super) struct StackStack { v: Vec>, } impl Default for StackStack { @@ -403,7 +403,7 @@ mod stack { /// Appends a reference to this stack for the duration of the function `f`. When `f` /// returns, the reference will be popped off the stack. #[cfg(feature = "std")] - pub fn with_append(&mut self, x: &mut T, f: F) -> R + pub(super) fn with_append(&mut self, x: &mut T, f: F) -> R where F: FnOnce(&mut Self) -> R, { @@ -428,10 +428,10 @@ mod stack { result } - pub fn iter(&self) -> impl DoubleEndedIterator + '_ { + pub(super) fn iter(&self) -> impl DoubleEndedIterator + '_ { self.as_ref().iter().copied() } - pub fn iter_mut(&mut self) -> impl DoubleEndedIterator + '_ { + pub(super) fn iter_mut(&mut self) -> impl DoubleEndedIterator + '_ { self.as_mut().iter_mut().map(|x| &mut **x) } // pub fn top(&self) -> Option<&T> { @@ -440,18 +440,18 @@ mod stack { // pub fn top_mut(&mut self) -> Option<&mut T> { // self.as_mut().last_mut().map(|x| &mut **x) // } - pub fn len(&self) -> usize { + pub(super) fn len(&self) -> usize { self.v.len() } - pub fn is_empty(&self) -> bool { + pub(super) fn is_empty(&self) -> bool { self.len() == 0 } - pub fn as_ref(&self) -> &[&T] { + pub(super) fn as_ref(&self) -> &[&T] { unsafe { &*(self.v.as_slice() as *const [NonNull] as *const [&T]) } } - pub fn as_mut(&mut self) -> &mut [&mut T] { + pub(super) fn as_mut(&mut self) -> &mut [&mut T] { unsafe { &mut *(self.v.as_mut_slice() as *mut [NonNull] as *mut [&mut T]) } } } diff --git a/crates/codegen/src/unparse.rs b/crates/codegen/src/unparse.rs index a590323cb78..d7f754e2f9d 100644 --- a/crates/codegen/src/unparse.rs +++ b/crates/codegen/src/unparse.rs @@ -5,22 +5,24 @@ use ruff_text_size::Ranged; use rustpython_compiler_core::SourceFile; use rustpython_literal::escape::{AsciiEscape, UnicodeEscape}; -mod precedence { +pub(crate) mod precedence { macro_rules! precedence { ($($op:ident,)*) => { precedence!(@0, $($op,)*); }; (@$i:expr, $op1:ident, $($op:ident,)*) => { - pub const $op1: u8 = $i; + pub(crate) const $op1: u8 = $i; precedence!(@$i + 1, $($op,)*); }; (@$i:expr,) => {}; } + precedence!( TUPLE, TEST, OR, AND, NOT, CMP, // "EXPR" = BOR, BXOR, BAND, SHIFT, ARITH, TERM, FACTOR, POWER, AWAIT, ATOM, ); - pub const EXPR: u8 = BOR; + + pub(crate) const EXPR: u8 = BOR; } struct Unparser<'a, 'b, 'c> { @@ -653,13 +655,13 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { } } -pub struct UnparseExpr<'a> { +pub(crate) struct UnparseExpr<'a> { expr: &'a ast::Expr, source: &'a SourceFile, } impl<'a> UnparseExpr<'a> { - pub const fn new(expr: &'a ast::Expr, source: &'a SourceFile) -> Self { + pub(crate) const fn new(expr: &'a ast::Expr, source: &'a SourceFile) -> Self { Self { expr, source } } } diff --git a/crates/derive-impl/src/compile_bytecode.rs b/crates/derive-impl/src/compile_bytecode.rs index 16984139fcd..ffd3060e9d5 100644 --- a/crates/derive-impl/src/compile_bytecode.rs +++ b/crates/derive-impl/src/compile_bytecode.rs @@ -335,7 +335,7 @@ struct PyCompileArgs { crate_name: syn::Path, } -pub fn impl_py_compile( +pub(crate) fn impl_py_compile( input: TokenStream, compiler: &dyn Compiler, ) -> Result { @@ -356,7 +356,7 @@ pub fn impl_py_compile( Ok(output) } -pub fn impl_py_freeze( +pub(crate) fn impl_py_freeze( input: TokenStream, compiler: &dyn Compiler, ) -> Result { diff --git a/crates/derive-impl/src/error.rs b/crates/derive-impl/src/error.rs index 2fdf7a4b4a3..32afa4620ed 100644 --- a/crates/derive-impl/src/error.rs +++ b/crates/derive-impl/src/error.rs @@ -58,7 +58,7 @@ macro_rules! bail_span { // } #[derive(Debug)] -pub struct Diagnostic { +pub(crate) struct Diagnostic { inner: Repr, } @@ -75,7 +75,7 @@ enum Repr { } impl Diagnostic { - pub fn error>(text: T) -> Self { + pub(crate) fn error>(text: T) -> Self { Self { inner: Repr::Single { text: text.into(), @@ -93,7 +93,7 @@ impl Diagnostic { } } - pub fn from_vec(diagnostics: Vec) -> Result<(), Self> { + pub(crate) fn from_vec(diagnostics: Vec) -> Result<(), Self> { if diagnostics.is_empty() { Ok(()) } else { @@ -103,7 +103,7 @@ impl Diagnostic { } } - pub fn panic(&self) -> ! { + pub(crate) fn panic(&self) -> ! { match &self.inner { Repr::Single { text, .. } => panic!("{}", text), Repr::SynError(error) => panic!("{}", error), @@ -120,7 +120,7 @@ impl From for Diagnostic { } } -pub fn extract_spans(node: &dyn ToTokens) -> Option<(Span, Span)> { +pub(crate) fn extract_spans(node: &dyn ToTokens) -> Option<(Span, Span)> { let mut t = TokenStream::new(); node.to_tokens(&mut t); let mut tokens = t.into_iter(); diff --git a/crates/derive-impl/src/from_args.rs b/crates/derive-impl/src/from_args.rs index 9f2d0460fb0..8149a3aa65e 100644 --- a/crates/derive-impl/src/from_args.rs +++ b/crates/derive-impl/src/from_args.rs @@ -220,7 +220,7 @@ fn compute_arity_bounds(field_attrs: &[ArgAttribute]) -> (usize, usize) { (min_arity, max_arity) } -pub fn impl_from_args(input: DeriveInput) -> Result { +pub(crate) fn impl_from_args(input: DeriveInput) -> Result { let (fields, field_attrs) = match input.data { Data::Struct(syn::DataStruct { fields, .. }) => ( fields diff --git a/crates/derive-impl/src/pymodule.rs b/crates/derive-impl/src/pymodule.rs index b4b5535200c..d16ef79dbfd 100644 --- a/crates/derive-impl/src/pymodule.rs +++ b/crates/derive-impl/src/pymodule.rs @@ -147,7 +147,7 @@ struct ModuleContext { errors: Vec, } -pub fn impl_pymodule(args: PyModuleArgs, module_item: Item) -> Result { +pub(crate) fn impl_pymodule(args: PyModuleArgs, module_item: Item) -> Result { let PyModuleArgs { metas, with_items } = args; let (doc, mut module_item) = match module_item { Item::Mod(m) => (m.attrs.doc(), m), diff --git a/crates/derive-impl/src/pystructseq.rs b/crates/derive-impl/src/pystructseq.rs index 51628d438f1..ae2c4f76936 100644 --- a/crates/derive-impl/src/pystructseq.rs +++ b/crates/derive-impl/src/pystructseq.rs @@ -432,7 +432,7 @@ impl ItemMeta for PyStructSequenceMeta { } impl PyStructSequenceMeta { - pub fn class_name(&self) -> Result> { + pub(crate) fn class_name(&self) -> Result> { const KEY: &str = "name"; let inner = self.inner(); if let Some((_, meta)) = inner.meta_map.get(KEY) { @@ -456,7 +456,7 @@ impl PyStructSequenceMeta { } } - pub fn module(&self) -> Result> { + pub(crate) fn module(&self) -> Result> { const KEY: &str = "module"; let inner = self.inner(); if let Some((_, meta)) = inner.meta_map.get(KEY) { @@ -507,7 +507,7 @@ impl PyStructSequenceMeta { } } - pub fn no_attr(&self) -> Result { + pub(crate) fn no_attr(&self) -> Result { self.inner()._bool("no_attr") } } diff --git a/crates/derive-impl/src/util.rs b/crates/derive-impl/src/util.rs index 068bde9bccd..e1ad9ed2b89 100644 --- a/crates/derive-impl/src/util.rs +++ b/crates/derive-impl/src/util.rs @@ -38,7 +38,7 @@ pub(crate) struct ItemNursery(Vec); pub(crate) struct ValidatedItemNursery(ItemNursery); impl ItemNursery { - pub fn add_item( + pub(crate) fn add_item( &mut self, attr_name: Ident, py_names: Vec, @@ -56,7 +56,7 @@ impl ItemNursery { Ok(()) } - pub fn validate(self) -> Result { + pub(crate) fn validate(self) -> Result { let mut by_name: HashSet<(String, Vec)> = HashSet::new(); for item in &self.0 { for py_name in &item.py_names { @@ -118,7 +118,7 @@ pub(crate) struct ItemMetaInner { } impl ItemMetaInner { - pub fn from_nested( + pub(crate) fn from_nested( item_ident: Ident, meta_ident: Ident, nested: I, @@ -154,15 +154,15 @@ impl ItemMetaInner { }) } - pub fn item_name(&self) -> String { + pub(crate) fn item_name(&self) -> String { self.item_ident.to_string() } - pub fn meta_name(&self) -> String { + pub(crate) fn meta_name(&self) -> String { self.meta_ident.to_string() } - pub fn _optional_str(&self, key: &str) -> Result> { + pub(crate) fn _optional_str(&self, key: &str) -> Result> { let value = if let Some((_, meta)) = self.meta_map.get(key) { let Meta::NameValue(syn::MetaNameValue { value: @@ -187,7 +187,7 @@ impl ItemMetaInner { Ok(value) } - pub fn _optional_path(&self, key: &str) -> Result> { + pub(crate) fn _optional_path(&self, key: &str) -> Result> { let value = if let Some((_, meta)) = self.meta_map.get(key) { let Meta::NameValue(syn::MetaNameValue { value, .. }) = meta else { bail_span!( @@ -216,11 +216,11 @@ impl ItemMetaInner { Ok(value) } - pub fn _has_key(&self, key: &str) -> Result { + pub(crate) fn _has_key(&self, key: &str) -> Result { Ok(matches!(self.meta_map.get(key), Some((_, _)))) } - pub fn _bool(&self, key: &str) -> Result { + pub(crate) fn _bool(&self, key: &str) -> Result { let value = if let Some((_, meta)) = self.meta_map.get(key) { match meta { Meta::NameValue(syn::MetaNameValue { @@ -240,7 +240,7 @@ impl ItemMetaInner { Ok(value) } - pub fn _optional_list( + pub(crate) fn _optional_list( &self, key: &str, ) -> Result>> { @@ -327,7 +327,7 @@ impl ItemMeta for ModuleItemMeta { } impl ModuleItemMeta { - pub fn sub(&self) -> Result { + pub(crate) fn sub(&self) -> Result { self.inner()._bool("sub") } } @@ -371,7 +371,7 @@ impl ItemMeta for ClassItemMeta { } impl ClassItemMeta { - pub fn class_name(&self) -> Result { + pub(crate) fn class_name(&self) -> Result { const KEY: &str = "name"; let inner = self.inner(); if let Some((_, meta)) = inner.meta_map.get(KEY) { @@ -396,23 +396,23 @@ impl ClassItemMeta { ) } - pub fn ctx_name(&self) -> Result> { + pub(crate) fn ctx_name(&self) -> Result> { self.inner()._optional_str("ctx") } - pub fn base(&self) -> Result> { + pub(crate) fn base(&self) -> Result> { self.inner()._optional_path("base") } - pub fn unhashable(&self) -> Result { + pub(crate) fn unhashable(&self) -> Result { self.inner()._bool("unhashable") } - pub fn metaclass(&self) -> Result> { + pub(crate) fn metaclass(&self) -> Result> { self.inner()._optional_str("metaclass") } - pub fn module(&self) -> Result> { + pub(crate) fn module(&self) -> Result> { const KEY: &str = "module"; let inner = self.inner(); let value = if let Some((_, meta)) = inner.meta_map.get(KEY) { @@ -443,7 +443,7 @@ impl ClassItemMeta { Ok(value) } - pub fn impl_attrs(&self) -> Result> { + pub(crate) fn impl_attrs(&self) -> Result> { self.inner()._optional_str("impl") } @@ -475,7 +475,7 @@ impl ItemMeta for ExceptionItemMeta { } impl ExceptionItemMeta { - pub fn class_name(&self) -> Result { + pub(crate) fn class_name(&self) -> Result { const KEY: &str = "name"; let inner = self.inner(); if let Some((_, meta)) = inner.meta_map.get(KEY) { @@ -511,7 +511,7 @@ impl ExceptionItemMeta { ) } - pub fn has_impl(&self) -> Result { + pub(crate) fn has_impl(&self) -> Result { self.inner()._bool("impl") } } diff --git a/crates/host_env/src/crt_fd.rs b/crates/host_env/src/crt_fd.rs index ab7c94f8b3b..c6579106c7a 100644 --- a/crates/host_env/src/crt_fd.rs +++ b/crates/host_env/src/crt_fd.rs @@ -72,15 +72,17 @@ mod win { impl OwnedInner { #[inline] - pub unsafe fn from_raw_fd(fd: Raw) -> Self { + pub(super) unsafe fn from_raw_fd(fd: Raw) -> Self { Self(fd) } + #[inline] - pub fn as_raw_fd(&self) -> Raw { + pub(super) fn as_raw_fd(&self) -> Raw { self.0 } + #[inline] - pub fn into_raw_fd(self) -> Raw { + pub(super) fn into_raw_fd(self) -> Raw { let me = ManuallyDrop::new(self); me.0 } @@ -102,14 +104,15 @@ mod win { impl BorrowedInner<'_> { #[inline] - pub const unsafe fn borrow_raw(fd: Raw) -> Self { + pub(super) const unsafe fn borrow_raw(fd: Raw) -> Self { Self { fd, _marker: PhantomData, } } + #[inline] - pub fn as_raw_fd(&self) -> Raw { + pub(super) fn as_raw_fd(&self) -> Raw { self.fd } } diff --git a/crates/host_env/src/select.rs b/crates/host_env/src/select.rs index e5ddc4284f7..d3967ec17ad 100644 --- a/crates/host_env/src/select.rs +++ b/crates/host_env/src/select.rs @@ -2,7 +2,7 @@ use core::mem::MaybeUninit; use std::io; #[cfg(unix)] -mod platform { +pub mod platform { pub use libc::{FD_ISSET, FD_SET, FD_SETSIZE, FD_ZERO, fd_set, select, timeval}; pub use std::os::unix::io::RawFd; @@ -13,10 +13,13 @@ mod platform { #[allow(non_snake_case)] #[cfg(windows)] -mod platform { +pub mod platform { pub use WinSock::{FD_SET as fd_set, FD_SETSIZE, SOCKET as RawFd, TIMEVAL as timeval, select}; use windows_sys::Win32::Networking::WinSock; + /// # Safety + /// + /// Requirements forwarded from the caller. pub unsafe fn FD_SET(fd: RawFd, set: *mut fd_set) { let mut slot = unsafe { (&raw mut (*set).fd_array).cast::() }; let fd_count = unsafe { (*set).fd_count }; @@ -34,10 +37,16 @@ mod platform { } } + /// # Safety + /// + /// Requirements forwarded from the caller. pub unsafe fn FD_ZERO(set: *mut fd_set) { unsafe { (*set).fd_count = 0 }; } + /// # Safety + /// + /// Requirements forwarded from the caller. pub unsafe fn FD_ISSET(fd: RawFd, set: *mut fd_set) -> bool { use WinSock::__WSAFDIsSet; unsafe { __WSAFDIsSet(fd as _, set) != 0 } @@ -49,7 +58,7 @@ mod platform { } #[cfg(target_os = "wasi")] -mod platform { +pub mod platform { pub use libc::{FD_SETSIZE, timeval}; pub use std::os::fd::RawFd; diff --git a/crates/jit/src/instructions.rs b/crates/jit/src/instructions.rs index ec9501d1fa8..35ffdbe95aa 100644 --- a/crates/jit/src/instructions.rs +++ b/crates/jit/src/instructions.rs @@ -65,7 +65,7 @@ struct DDValue { lo: Value, } -pub struct FunctionCompiler<'a, 'b> { +pub(crate) struct FunctionCompiler<'a, 'b> { builder: &'a mut FunctionBuilder<'b>, stack: Vec, variables: Box<[Option]>, @@ -74,7 +74,7 @@ pub struct FunctionCompiler<'a, 'b> { } impl<'a, 'b> FunctionCompiler<'a, 'b> { - pub fn new( + pub(crate) fn new( builder: &'a mut FunctionBuilder<'b>, num_variables: usize, arg_types: &[JitType], @@ -204,7 +204,7 @@ impl<'a, 'b> FunctionCompiler<'a, 'b> { Ok(target) } - pub fn compile( + pub(crate) fn compile( &mut self, func_ref: FuncRef, bytecode: &CodeObject, @@ -350,7 +350,7 @@ impl<'a, 'b> FunctionCompiler<'a, 'b> { Ok(()) } - pub fn add_instruction( + pub(crate) fn add_instruction( &mut self, func_ref: FuncRef, bytecode: &CodeObject, diff --git a/crates/jit/tests/common.rs b/crates/jit/tests/common.rs index 349b3b6f39c..6066ebc4307 100644 --- a/crates/jit/tests/common.rs +++ b/crates/jit/tests/common.rs @@ -7,13 +7,13 @@ use rustpython_wtf8::{Wtf8, Wtf8Buf}; use std::collections::HashMap; #[derive(Debug, Clone)] -pub struct Function { +pub(crate) struct Function { code: Box, annotations: HashMap, } impl Function { - pub fn compile(self) -> CompiledCode { + pub(crate) fn compile(self) -> CompiledCode { let mut arg_types = Vec::new(); for arg in self.code.arg_names().args { let arg_type = match self.annotations.get(AsRef::::as_ref(arg.as_str())) { @@ -171,20 +171,20 @@ fn extract_annotations_from_annotate_code(code: &CodeObject) -> HashMap, locals: HashMap, } impl StackMachine { - pub fn new() -> StackMachine { + pub(crate) fn new() -> StackMachine { StackMachine { stack: Vec::new(), locals: HashMap::new(), } } - pub fn run(&mut self, code: CodeObject) { + pub(crate) fn run(&mut self, code: CodeObject) { let mut op_arg_state = OpArgState::default(); let _ = code.instructions.iter().try_for_each(|&word| { let (instruction, arg) = op_arg_state.get(word); @@ -299,7 +299,7 @@ impl StackMachine { ControlFlow::Continue(()) } - pub fn get_function(&self, name: &str) -> Function { + pub(crate) fn get_function(&self, name: &str) -> Function { if let Some(StackValue::Function(function)) = self.locals.get(name) { function.clone() } else { diff --git a/crates/stdlib/src/_tokenize.rs b/crates/stdlib/src/_tokenize.rs index 13bd1661305..7106c527096 100644 --- a/crates/stdlib/src/_tokenize.rs +++ b/crates/stdlib/src/_tokenize.rs @@ -31,7 +31,7 @@ mod _tokenize { #[pyattr] #[pyclass(name = "TokenizerIter")] #[derive(PyPayload)] - pub struct PyTokenizerIter { + pub(super) struct PyTokenizerIter { readline: ArgCallable, extra_tokens: bool, encoding: Option, @@ -611,7 +611,7 @@ mod _tokenize { } #[derive(FromArgs)] - pub struct PyTokenizerIterArgs { + pub(super) struct PyTokenizerIterArgs { #[pyarg(positional)] readline: ArgCallable, #[pyarg(named)] diff --git a/crates/stdlib/src/array.rs b/crates/stdlib/src/array.rs index 15a64c6d99c..f3cd601c771 100644 --- a/crates/stdlib/src/array.rs +++ b/crates/stdlib/src/array.rs @@ -3,7 +3,7 @@ pub(crate) use array::module_def; #[pymodule(name = "array")] -mod array { +pub mod array { use crate::{ common::{ atomic::{self, AtomicUsize}, diff --git a/crates/stdlib/src/compression.rs b/crates/stdlib/src/compression.rs index ae47ebbff70..e07d6d09b6d 100644 --- a/crates/stdlib/src/compression.rs +++ b/crates/stdlib/src/compression.rs @@ -9,12 +9,12 @@ use crate::vm::{ convert::ToPyException, }; -pub const USE_AFTER_FINISH_ERR: &str = "Error -2: inconsistent stream state"; +pub(crate) const USE_AFTER_FINISH_ERR: &str = "Error -2: inconsistent stream state"; // TODO: don't hardcode const CHUNKSIZE: usize = u32::MAX as usize; #[derive(FromArgs)] -pub struct DecompressArgs { +pub(crate) struct DecompressArgs { #[pyarg(positional)] data: ArgBytesLike, #[pyarg(any, optional)] @@ -22,22 +22,22 @@ pub struct DecompressArgs { } impl DecompressArgs { - pub fn data(&self) -> crate::common::borrow::BorrowedValue<'_, [u8]> { + pub(crate) fn data(&self) -> crate::common::borrow::BorrowedValue<'_, [u8]> { self.data.borrow_buf() } - pub fn raw_max_length(&self) -> Option { + pub(crate) fn raw_max_length(&self) -> Option { self.max_length.into_option().map(|ArgSize { value }| value) } // negative is None - pub fn max_length(&self) -> Option { + pub(crate) fn max_length(&self) -> Option { self.max_length .into_option() .and_then(|ArgSize { value }| usize::try_from(value).ok()) } } -pub trait Decompressor { +pub(crate) trait Decompressor { type Flush: DecompressFlushKind; type Status: DecompressStatus; type Error; @@ -54,11 +54,11 @@ pub trait Decompressor { } } -pub trait DecompressStatus { +pub(crate) trait DecompressStatus { fn is_stream_end(&self) -> bool; } -pub trait DecompressFlushKind: Copy { +pub(crate) trait DecompressFlushKind: Copy { const SYNC: Self; } @@ -66,23 +66,23 @@ impl DecompressFlushKind for () { const SYNC: Self = (); } -pub const fn flush_sync(_final_chunk: bool) -> T { +pub(crate) const fn flush_sync(_final_chunk: bool) -> T { T::SYNC } #[derive(Clone)] -pub struct Chunker<'a> { +pub(crate) struct Chunker<'a> { data1: &'a [u8], data2: &'a [u8], } impl<'a> Chunker<'a> { - pub const fn new(data: &'a [u8]) -> Self { + pub(crate) const fn new(data: &'a [u8]) -> Self { Self { data1: data, data2: &[], } } - pub const fn chain(data1: &'a [u8], data2: &'a [u8]) -> Self { + pub(crate) const fn chain(data1: &'a [u8], data2: &'a [u8]) -> Self { if data1.is_empty() { Self { data1: data2, @@ -92,19 +92,19 @@ impl<'a> Chunker<'a> { Self { data1, data2 } } } - pub const fn len(&self) -> usize { + pub(crate) const fn len(&self) -> usize { self.data1.len() + self.data2.len() } - pub const fn is_empty(&self) -> bool { + pub(crate) const fn is_empty(&self) -> bool { self.data1.is_empty() } - pub fn to_vec(&self) -> Vec { + pub(crate) fn to_vec(&self) -> Vec { [self.data1, self.data2].concat() } - pub fn chunk(&self) -> &'a [u8] { + pub(crate) fn chunk(&self) -> &'a [u8] { self.data1.get(..CHUNKSIZE).unwrap_or(self.data1) } - pub fn advance(&mut self, consumed: usize) { + pub(crate) fn advance(&mut self, consumed: usize) { self.data1 = &self.data1[consumed..]; if self.data1.is_empty() { self.data1 = core::mem::take(&mut self.data2); @@ -112,7 +112,7 @@ impl<'a> Chunker<'a> { } } -pub fn _decompress( +pub(crate) fn _decompress( data: &[u8], d: &mut D, bufsize: usize, @@ -123,7 +123,7 @@ pub fn _decompress( _decompress_chunks(&mut data, d, bufsize, max_length, calc_flush) } -pub fn _decompress_chunks( +pub(crate) fn _decompress_chunks( data: &mut Chunker<'_>, d: &mut D, bufsize: usize, @@ -177,7 +177,7 @@ pub fn _decompress_chunks( } } -pub trait Compressor { +pub(crate) trait Compressor { type Status: CompressStatusKind; type Flush: CompressFlushKind; const CHUNKSIZE: usize; @@ -196,26 +196,26 @@ pub trait Compressor { fn new_error(message: impl Into, vm: &VirtualMachine) -> PyBaseExceptionRef; } -pub trait CompressFlushKind: Copy { +pub(crate) trait CompressFlushKind: Copy { const NONE: Self; const FINISH: Self; fn to_usize(self) -> usize; } -pub trait CompressStatusKind: Copy { +pub(crate) trait CompressStatusKind: Copy { const EOF: Self; fn to_usize(self) -> usize; } #[derive(Debug)] -pub struct CompressState { +pub(crate) struct CompressState { compressor: Option, } impl CompressState { - pub const fn new(compressor: C) -> Self { + pub(crate) const fn new(compressor: C) -> Self { Self { compressor: Some(compressor), } @@ -227,7 +227,7 @@ impl CompressState { .ok_or_else(|| C::new_error(USE_AFTER_FINISH_ERR, vm)) } - pub fn compress(&mut self, data: &[u8], vm: &VirtualMachine) -> PyResult> { + pub(crate) fn compress(&mut self, data: &[u8], vm: &VirtualMachine) -> PyResult> { let mut buf = Vec::new(); let compressor = self.get_compressor(vm)?; @@ -245,7 +245,7 @@ impl CompressState { Ok(buf) } - pub fn flush(&mut self, mode: C::Flush, vm: &VirtualMachine) -> PyResult> { + pub(crate) fn flush(&mut self, mode: C::Flush, vm: &VirtualMachine) -> PyResult> { let mut buf = Vec::new(); let compressor = self.get_compressor(vm)?; @@ -273,7 +273,7 @@ impl CompressState { } #[derive(Debug)] -pub struct DecompressState { +pub(crate) struct DecompressState { decompress: D, unused_data: PyBytesRef, input_buffer: Vec, @@ -282,7 +282,7 @@ pub struct DecompressState { } impl DecompressState { - pub fn new(decompress: D, vm: &VirtualMachine) -> Self { + pub(crate) fn new(decompress: D, vm: &VirtualMachine) -> Self { Self { decompress, unused_data: vm.ctx.empty_bytes.clone(), @@ -292,24 +292,24 @@ impl DecompressState { } } - pub const fn eof(&self) -> bool { + pub(crate) const fn eof(&self) -> bool { self.eof } #[cfg_attr(target_os = "android", allow(dead_code))] - pub const fn decompressor(&self) -> &D { + pub(crate) const fn decompressor(&self) -> &D { &self.decompress } - pub fn unused_data(&self) -> PyBytesRef { + pub(crate) fn unused_data(&self) -> PyBytesRef { self.unused_data.clone() } - pub const fn needs_input(&self) -> bool { + pub(crate) const fn needs_input(&self) -> bool { self.needs_input } - pub fn decompress( + pub(crate) fn decompress( &mut self, data: &[u8], max_length: Option, @@ -358,7 +358,7 @@ impl DecompressState { } } -pub enum DecompressError { +pub(crate) enum DecompressError { Decompress(E), Eof(EofError), } @@ -369,7 +369,7 @@ impl From for DecompressError { } } -pub struct EofError; +pub(crate) struct EofError; impl ToPyException for EofError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { diff --git a/crates/stdlib/src/faulthandler.rs b/crates/stdlib/src/faulthandler.rs index e562a382345..28febe7b5dd 100644 --- a/crates/stdlib/src/faulthandler.rs +++ b/crates/stdlib/src/faulthandler.rs @@ -987,7 +987,7 @@ mod decl { const NSIG: usize = 64; #[derive(Clone, Copy)] - pub struct UserSignal { + pub(super) struct UserSignal { pub enabled: bool, pub fd: i32, pub all_threads: bool, @@ -1010,12 +1010,12 @@ mod decl { static USER_SIGNALS: Mutex>> = Mutex::new(None); - pub fn get_user_signal(signum: usize) -> Option { + pub(super) fn get_user_signal(signum: usize) -> Option { let guard = USER_SIGNALS.lock(); guard.as_ref().and_then(|v| v.get(signum).cloned()) } - pub fn set_user_signal(signum: usize, signal: UserSignal) { + pub(super) fn set_user_signal(signum: usize, signal: UserSignal) { let mut guard = USER_SIGNALS.lock(); if guard.is_none() { *guard = Some(vec![UserSignal::default(); NSIG]); @@ -1027,7 +1027,7 @@ mod decl { } } - pub fn clear_user_signal(signum: usize) -> Option { + pub(super) fn clear_user_signal(signum: usize) -> Option { let mut guard = USER_SIGNALS.lock(); if let Some(ref mut v) = *guard && signum < v.len() @@ -1040,7 +1040,7 @@ mod decl { None } - pub fn is_enabled(signum: usize) -> bool { + pub(super) fn is_enabled(signum: usize) -> bool { let guard = USER_SIGNALS.lock(); guard .as_ref() diff --git a/crates/stdlib/src/hashlib.rs b/crates/stdlib/src/hashlib.rs index 584ed1714d5..8f37407c35d 100644 --- a/crates/stdlib/src/hashlib.rs +++ b/crates/stdlib/src/hashlib.rs @@ -6,7 +6,7 @@ pub(crate) use _hashlib::module_def; #[pymodule] -pub mod _hashlib { +pub(crate) mod _hashlib { use crate::common::lock::PyRwLock; use crate::vm::{ Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, @@ -51,7 +51,7 @@ pub mod _hashlib { #[pyexception(name = "UnsupportedDigestmodError", base = PyValueError, impl)] #[derive(Debug)] #[repr(transparent)] - pub struct UnsupportedDigestmodError(PyValueError); + pub(crate) struct UnsupportedDigestmodError(PyValueError); #[pyattr] fn openssl_md_meth_names(vm: &VirtualMachine) -> PyObjectRef { @@ -89,7 +89,7 @@ pub mod _hashlib { #[derive(FromArgs)] #[allow(unused)] - pub struct BlakeHashArgs { + pub(crate) struct BlakeHashArgs { #[pyarg(any, optional)] pub data: OptionalArg, #[pyarg(named, default = true)] @@ -110,7 +110,7 @@ pub mod _hashlib { #[derive(FromArgs, Debug)] #[allow(unused)] - pub struct HashArgs { + pub(crate) struct HashArgs { #[pyarg(any, optional)] pub data: OptionalArg, #[pyarg(named, default = true)] @@ -288,7 +288,7 @@ pub mod _hashlib { #[pyattr] #[pyclass(module = "_hashlib", name = "HMAC")] #[derive(PyPayload)] - pub struct PyHmac { + pub(crate) struct PyHmac { algo_name: String, digest_size: usize, block_size: usize, @@ -361,7 +361,7 @@ pub mod _hashlib { #[pyattr] #[pyclass(module = "_hashlib", name = "HASH")] #[derive(PyPayload)] - pub struct PyHasher { + pub(crate) struct PyHasher { pub name: String, pub ctx: PyRwLock, } @@ -460,7 +460,7 @@ pub mod _hashlib { #[pyattr] #[pyclass(module = "_hashlib", name = "HASHXOF")] #[derive(PyPayload)] - pub struct PyHasherXof { + pub(crate) struct PyHasherXof { name: String, ctx: PyRwLock, } @@ -605,43 +605,43 @@ pub mod _hashlib { } #[pyfunction(name = "openssl_md5")] - pub fn local_md5(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_md5(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new("md5", HashWrapper::new::(data))) } #[pyfunction(name = "openssl_sha1")] - pub fn local_sha1(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha1(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new("sha1", HashWrapper::new::(data))) } #[pyfunction(name = "openssl_sha224")] - pub fn local_sha224(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha224(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new("sha224", HashWrapper::new::(data))) } #[pyfunction(name = "openssl_sha256")] - pub fn local_sha256(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha256(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new("sha256", HashWrapper::new::(data))) } #[pyfunction(name = "openssl_sha384")] - pub fn local_sha384(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha384(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new("sha384", HashWrapper::new::(data))) } #[pyfunction(name = "openssl_sha512")] - pub fn local_sha512(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha512(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new("sha512", HashWrapper::new::(data))) } #[pyfunction(name = "openssl_sha3_224")] - pub fn local_sha3_224(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha3_224(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new( "sha3_224", @@ -650,7 +650,7 @@ pub mod _hashlib { } #[pyfunction(name = "openssl_sha3_256")] - pub fn local_sha3_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha3_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new( "sha3_256", @@ -659,7 +659,7 @@ pub mod _hashlib { } #[pyfunction(name = "openssl_sha3_384")] - pub fn local_sha3_384(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha3_384(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new( "sha3_384", @@ -668,7 +668,7 @@ pub mod _hashlib { } #[pyfunction(name = "openssl_sha3_512")] - pub fn local_sha3_512(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_sha3_512(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new( "sha3_512", @@ -677,7 +677,7 @@ pub mod _hashlib { } #[pyfunction(name = "openssl_shake_128")] - pub fn local_shake_128(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_shake_128(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasherXof::new( "shake_128", @@ -686,7 +686,7 @@ pub mod _hashlib { } #[pyfunction(name = "openssl_shake_256")] - pub fn local_shake_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_shake_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasherXof::new( "shake_256", @@ -695,7 +695,7 @@ pub mod _hashlib { } #[pyfunction(name = "openssl_blake2b")] - pub fn local_blake2b(args: BlakeHashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_blake2b(args: BlakeHashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new( "blake2b", @@ -704,7 +704,7 @@ pub mod _hashlib { } #[pyfunction(name = "openssl_blake2s")] - pub fn local_blake2s(args: BlakeHashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_blake2s(args: BlakeHashArgs, vm: &VirtualMachine) -> PyResult { let data = resolve_data(args.data, args.string, vm)?; Ok(PyHasher::new( "blake2s", @@ -746,7 +746,7 @@ pub mod _hashlib { #[derive(FromArgs, Debug)] #[allow(unused)] - pub struct NewHMACHashArgs { + pub(crate) struct NewHMACHashArgs { #[pyarg(positional)] key: ArgBytesLike, #[pyarg(any, optional)] @@ -885,13 +885,13 @@ pub mod _hashlib { clone_trait_object!(ThreadSafeDynDigest); #[derive(Clone)] - pub struct HashWrapper { + pub(crate) struct HashWrapper { block_size: usize, inner: Box, } impl HashWrapper { - pub fn new(data: OptionalArg) -> Self + pub(crate) fn new(data: OptionalArg) -> Self where D: ThreadSafeDynDigest + BlockSizeUser + Default + 'static, { @@ -924,13 +924,13 @@ pub mod _hashlib { } #[derive(Clone)] - pub enum HashXofWrapper { + pub(crate) enum HashXofWrapper { Shake128(Shake128), Shake256(Shake256), } impl HashXofWrapper { - pub fn new_shake_128(data: OptionalArg) -> Self { + pub(crate) fn new_shake_128(data: OptionalArg) -> Self { let mut h = Self::Shake128(Shake128::default()); if let OptionalArg::Present(d) = data { d.with_ref(|bytes| h.update(bytes)); @@ -938,7 +938,7 @@ pub mod _hashlib { h } - pub fn new_shake_256(data: OptionalArg) -> Self { + pub(crate) fn new_shake_256(data: OptionalArg) -> Self { let mut h = Self::Shake256(Shake256::default()); if let OptionalArg::Present(d) = data { d.with_ref(|bytes| h.update(bytes)); diff --git a/crates/stdlib/src/json/machinery.rs b/crates/stdlib/src/json/machinery.rs index 6106acc8406..30882588e34 100644 --- a/crates/stdlib/src/json/machinery.rs +++ b/crates/stdlib/src/json/machinery.rs @@ -72,7 +72,11 @@ fn json_escaped_char(c: u8) -> Option<&'static str> { } } -pub fn write_json_string(wtf8: &Wtf8, ascii_only: bool, w: &mut W) -> io::Result<()> { +pub(super) fn write_json_string( + wtf8: &Wtf8, + ascii_only: bool, + w: &mut W, +) -> io::Result<()> { w.write_all(b"\"")?; let mut write_start_idx = 0; let bytes = wtf8.as_bytes(); @@ -128,12 +132,12 @@ pub fn write_json_string(wtf8: &Wtf8, ascii_only: bool, w: &mut W) } #[derive(Debug)] -pub struct DecodeError { +pub(super) struct DecodeError { pub msg: String, pub pos: usize, } impl DecodeError { - pub fn new(msg: impl Into, pos: usize) -> Self { + pub(super) fn new(msg: impl Into, pos: usize) -> Self { let msg = msg.into(); Self { msg, pos } } @@ -161,7 +165,7 @@ impl StrOrChar<'_> { /// # Returns /// * `Ok((result, chars_consumed, bytes_consumed))` - The decoded string and how much was consumed /// * `Err(DecodeError)` - If the string is malformed -pub fn scanstring<'a>( +pub(super) fn scanstring<'a>( s: &'a Wtf8, char_offset: usize, strict: bool, diff --git a/crates/stdlib/src/lzma.rs b/crates/stdlib/src/lzma.rs index b98cfb1bf94..7ff8a952037 100644 --- a/crates/stdlib/src/lzma.rs +++ b/crates/stdlib/src/lzma.rs @@ -566,7 +566,7 @@ mod _lzma { } #[derive(FromArgs)] - pub struct LZMADecompressorConstructorArgs { + pub(super) struct LZMADecompressorConstructorArgs { #[pyarg(any, default = FORMAT_AUTO)] format: i32, #[pyarg(any, optional)] @@ -782,7 +782,7 @@ mod _lzma { } #[derive(FromArgs)] - pub struct LZMACompressorConstructorArgs { + pub(super) struct LZMACompressorConstructorArgs { #[pyarg(any, default = FORMAT_XZ)] format: i32, #[pyarg(any, default = -1)] diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index ca666418a2d..d360a2c2ada 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -352,7 +352,7 @@ mod mmap { } #[derive(FromArgs)] - pub struct FlushOptions { + pub(super) struct FlushOptions { #[pyarg(positional, default)] offset: Option, #[pyarg(positional, default)] @@ -382,7 +382,7 @@ mod mmap { } #[derive(FromArgs, Clone)] - pub struct FindOptions { + pub(super) struct FindOptions { #[pyarg(positional)] sub: Vec, #[pyarg(positional, default)] @@ -393,7 +393,7 @@ mod mmap { #[cfg(all(unix, not(target_os = "redox")))] #[derive(FromArgs)] - pub struct AdviseOptions { + pub(super) struct AdviseOptions { #[pyarg(positional)] option: libc::c_int, #[pyarg(positional, default)] diff --git a/crates/stdlib/src/openssl/ssl_data_31.rs b/crates/stdlib/src/openssl/ssl_data_31.rs index 4b80de539ec..c2bf6699131 100644 --- a/crates/stdlib/src/openssl/ssl_data_31.rs +++ b/crates/stdlib/src/openssl/ssl_data_31.rs @@ -7,7 +7,7 @@ use phf::phf_map; // Maps lib_code -> library name // Example: 20 -> "SSL" -pub static LIBRARY_CODES: phf::Map = phf_map! { +pub(super) static LIBRARY_CODES: phf::Map = phf_map! { 0u32 => "MASK", 1u32 => "NONE", 2u32 => "SYS", @@ -67,7 +67,7 @@ pub static LIBRARY_CODES: phf::Map = phf_map! { // Maps encoded (lib, reason) -> error mnemonic // Example: encode_error_key(20, 134) -> "CERTIFICATE_VERIFY_FAILED" // Key encoding: (lib << 32) | reason -pub static ERROR_CODES: phf::Map = phf_map! { +pub(super) static ERROR_CODES: phf::Map = phf_map! { 55834575019u64 => "ADDING_OBJECT", 55834575051u64 => "ASN1_PARSE_ERROR", 55834575052u64 => "ASN1_SIG_PARSE_ERROR", @@ -1765,6 +1765,6 @@ pub static ERROR_CODES: phf::Map = phf_map! { /// Helper function to create encoded key from (lib, reason) pair #[inline] -pub fn encode_error_key(lib: i32, reason: i32) -> u64 { +pub(super) fn encode_error_key(lib: i32, reason: i32) -> u64 { ((lib as u64) << 32) | (reason as u64 & 0xFFFFFFFF) } diff --git a/crates/stdlib/src/pyexpat.rs b/crates/stdlib/src/pyexpat.rs index 2e0730e6f93..5dae80c304d 100644 --- a/crates/stdlib/src/pyexpat.rs +++ b/crates/stdlib/src/pyexpat.rs @@ -68,13 +68,13 @@ mod _pyexpat { type MutableObject = PyRwLock; #[pyattr(name = "version_info")] - pub const VERSION_INFO: (u32, u32, u32) = (2, 7, 1); + pub(super) const VERSION_INFO: (u32, u32, u32) = (2, 7, 1); #[pyattr] #[pyattr(name = "XMLParserType")] #[pyclass(name = "xmlparser", module = false, traverse)] #[derive(Debug, PyPayload)] - pub struct PyExpatLikeXmlParser { + pub(super) struct PyExpatLikeXmlParser { #[pytraverse(skip)] namespace_separator: Option, start_element: MutableObject, @@ -426,7 +426,7 @@ mod _pyexpat { #[pyexception(name = "ExpatError", base = PyException)] #[derive(Debug)] #[repr(transparent)] - pub struct PyExpatError(PyException); + pub(super) struct PyExpatError(PyException); #[pyexception] impl PyExpatError {} diff --git a/crates/stdlib/src/select.rs b/crates/stdlib/src/select.rs index 1cfe22e7c61..8f6e5fafb42 100644 --- a/crates/stdlib/src/select.rs +++ b/crates/stdlib/src/select.rs @@ -213,7 +213,7 @@ mod decl { #[pyclass(module = "select", name = "poll")] #[derive(Default, Debug, PyPayload)] - pub struct PyPoll { + pub(crate) struct PyPoll { // keep sorted fds: PyMutex>, } @@ -248,7 +248,7 @@ mod decl { // new EventMask type #[derive(Copy, Clone)] #[repr(transparent)] - pub struct EventMask(pub i16); + pub(crate) struct EventMask(pub i16); impl TryFromObject for EventMask { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { @@ -389,12 +389,12 @@ mod decl { #[pyclass(module = "select", name = "epoll")] #[derive(Debug, rustpython_vm::PyPayload)] - pub struct PyEpoll { + pub(crate) struct PyEpoll { epoll_fd: PyRwLock>, } #[derive(FromArgs)] - pub struct EpollNewArgs { + pub(crate) struct EpollNewArgs { #[pyarg(any, default = -1)] sizehint: i32, #[pyarg(any, default = 0)] diff --git a/crates/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index baffbcaff7e..5e7286559f5 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -48,14 +48,18 @@ mod _socket { #[cfg(unix)] use libc as c; + #[cfg(windows)] mod c { - pub use windows_sys::Win32::NetworkManagement::IpHelper::{if_indextoname, if_nametoindex}; - pub use windows_sys::Win32::Networking::WinSock::{ + pub(super) use windows_sys::Win32::NetworkManagement::IpHelper::{ + if_indextoname, if_nametoindex, + }; + + pub(super) use windows_sys::Win32::Networking::WinSock::{ INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE, }; - pub use windows_sys::Win32::Networking::WinSock::{ + pub(super) use windows_sys::Win32::Networking::WinSock::{ AF_APPLETALK, AF_DECnet, AF_IPX, AF_LINK, AI_ADDRCONFIG, AI_ALL, AI_CANONNAME, AI_NUMERICSERV, AI_V4MAPPED, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_HDRINCL, IP_MULTICAST_IF, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_OPTIONS, IP_RECVDSTADDR, @@ -76,34 +80,40 @@ mod _socket { SOCK_SEQPACKET, SOCK_STREAM, SOL_SOCKET, SOMAXCONN, TCP_NODELAY, WSAEBADF, WSAECONNRESET, WSAENOTSOCK, WSAEWOULDBLOCK, }; - pub use windows_sys::Win32::Networking::WinSock::{ + + pub(super) use windows_sys::Win32::Networking::WinSock::{ INVALID_SOCKET, SOCKET_ERROR, WSA_FLAG_OVERLAPPED, WSADuplicateSocketW, WSAGetLastError, WSAIoctl, WSAPROTOCOL_INFOW, WSASocketW, }; - pub use windows_sys::Win32::Networking::WinSock::{ + + pub(super) use windows_sys::Win32::Networking::WinSock::{ SO_REUSEADDR as SO_EXCLUSIVEADDRUSE, getprotobyname, getservbyname, getservbyport, getsockopt, setsockopt, }; - pub use windows_sys::Win32::Networking::WinSock::{ + + pub(super) use windows_sys::Win32::Networking::WinSock::{ WSA_NOT_ENOUGH_MEMORY as EAI_MEMORY, WSAEAFNOSUPPORT as EAI_FAMILY, WSAEINVAL as EAI_BADFLAGS, WSAESOCKTNOSUPPORT as EAI_SOCKTYPE, WSAHOST_NOT_FOUND as EAI_NODATA, WSAHOST_NOT_FOUND as EAI_NONAME, WSANO_RECOVERY as EAI_FAIL, WSATRY_AGAIN as EAI_AGAIN, WSATYPE_NOT_FOUND as EAI_SERVICE, }; - pub const IF_NAMESIZE: usize = + + pub(super) const IF_NAMESIZE: usize = windows_sys::Win32::NetworkManagement::Ndis::IF_MAX_STRING_SIZE as _; - pub const AF_UNSPEC: i32 = windows_sys::Win32::Networking::WinSock::AF_UNSPEC as _; - pub const AF_INET: i32 = windows_sys::Win32::Networking::WinSock::AF_INET as _; - pub const AF_INET6: i32 = windows_sys::Win32::Networking::WinSock::AF_INET6 as _; - pub const AI_PASSIVE: i32 = windows_sys::Win32::Networking::WinSock::AI_PASSIVE as _; - pub const AI_NUMERICHOST: i32 = + pub(super) const AF_UNSPEC: i32 = windows_sys::Win32::Networking::WinSock::AF_UNSPEC as _; + pub(super) const AF_INET: i32 = windows_sys::Win32::Networking::WinSock::AF_INET as _; + pub(super) const AF_INET6: i32 = windows_sys::Win32::Networking::WinSock::AF_INET6 as _; + pub(super) const AI_PASSIVE: i32 = windows_sys::Win32::Networking::WinSock::AI_PASSIVE as _; + pub(super) const AI_NUMERICHOST: i32 = windows_sys::Win32::Networking::WinSock::AI_NUMERICHOST as _; - pub const FROM_PROTOCOL_INFO: i32 = -1; + pub(super) const FROM_PROTOCOL_INFO: i32 = -1; } + // constants #[pyattr(name = "has_ipv6")] const HAS_IPV6: bool = true; + #[pyattr] // put IPPROTO_MAX later use c::{ diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index cbc842538a9..9534cac0534 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -5079,7 +5079,7 @@ mod _ssl { #[pyattr] #[pyclass(module = "_ssl", name = "Certificate")] #[derive(Debug, PyPayload)] - pub struct PySSLCertificate { + pub(super) struct PySSLCertificate { // Store the raw DER bytes der_bytes: Vec, } diff --git a/crates/stdlib/src/ssl/cert.rs b/crates/stdlib/src/ssl/cert.rs index f838733c03d..8ce2e4c1b38 100644 --- a/crates/stdlib/src/ssl/cert.rs +++ b/crates/stdlib/src/ssl/cert.rs @@ -56,61 +56,61 @@ mod cert_error { use std::io; /// Create InvalidData error with formatted message - pub fn invalid_data(msg: impl Into) -> io::Error { + pub(super) fn invalid_data(msg: impl Into) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, msg.into()) } /// PEM parsing error variants - pub mod pem { + pub(super) mod pem { use super::*; - pub fn no_start_line(context: &str) -> io::Error { + pub(crate) fn no_start_line(context: &str) -> io::Error { invalid_data(format!("no start line: {context}")) } - pub fn parse_failed(e: impl Display) -> io::Error { + pub(crate) fn parse_failed(e: impl Display) -> io::Error { invalid_data(format!("Failed to parse PEM certificate: {e}")) } - pub fn parse_failed_debug(e: impl Debug) -> io::Error { + pub(crate) fn parse_failed_debug(e: impl Debug) -> io::Error { invalid_data(format!("Failed to parse PEM certificate: {e:?}")) } - pub fn invalid_cert() -> io::Error { + pub(crate) fn invalid_cert() -> io::Error { invalid_data("No certificates found in certificate file") } } /// DER parsing error variants - pub mod der { + pub(super) mod der { use super::*; - pub fn not_enough_data(context: &str) -> io::Error { + pub(crate) fn not_enough_data(context: &str) -> io::Error { invalid_data(format!("not enough data: {context}")) } - pub fn parse_failed(e: impl Display) -> io::Error { + pub(crate) fn parse_failed(e: impl Display) -> io::Error { invalid_data(format!("Failed to parse DER certificate: {e}")) } } /// Private key error variants - pub mod key { + pub(super) mod key { use super::*; - pub fn not_found(context: &str) -> io::Error { + pub(crate) fn not_found(context: &str) -> io::Error { invalid_data(format!("No private key found in {context}")) } - pub fn parse_failed(e: impl Display) -> io::Error { + pub(crate) fn parse_failed(e: impl Display) -> io::Error { invalid_data(format!("Failed to parse private key: {e}")) } - pub fn parse_encrypted_failed(e: impl Display) -> io::Error { + pub(crate) 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 Display) -> io::Error { + pub(crate) fn decrypt_failed(e: impl Display) -> io::Error { io::Error::other(format!( "Failed to decrypt private key (wrong password?): {e}", )) @@ -118,14 +118,17 @@ mod cert_error { } /// Convert error message to rustls::Error with InvalidCertificate wrapper - pub fn to_rustls_invalid_cert(msg: impl Into) -> rustls::Error { + pub(super) fn to_rustls_invalid_cert(msg: impl Into) -> rustls::Error { rustls::Error::InvalidCertificate(rustls::CertificateError::Other(rustls::OtherError( Arc::new(invalid_data(msg)), ))) } /// Convert error message to rustls::Error with InvalidCertificate wrapper and custom ErrorKind - pub fn to_rustls_cert_error(kind: io::ErrorKind, msg: impl Into) -> rustls::Error { + pub(super) fn to_rustls_cert_error( + kind: io::ErrorKind, + msg: impl Into, + ) -> rustls::Error { rustls::Error::InvalidCertificate(rustls::CertificateError::Other(rustls::OtherError( Arc::new(io::Error::new(kind, msg.into())), ))) @@ -268,7 +271,7 @@ fn process_san_general_names( /// Returns `true` if the certificate has Basic Constraints with CA=true, /// `false` otherwise (including parse errors or missing extension). /// This matches OpenSSL's X509_check_ca() behavior. -pub fn is_ca_certificate(cert_der: &[u8]) -> bool { +pub(super) fn is_ca_certificate(cert_der: &[u8]) -> bool { // Parse the certificate let Ok((_, cert)) = X509Certificate::from_der(cert_der) else { return false; @@ -314,7 +317,7 @@ fn name_to_py(vm: &VirtualMachine, name: &x509_parser::x509::X509Name<'_>) -> Py /// /// Returns a dict with fields: subject, issuer, version, serialNumber, /// notBefore, notAfter, subjectAltName (if present) -pub fn cert_to_dict( +pub(super) fn cert_to_dict( vm: &VirtualMachine, cert: &x509_parser::certificate::X509Certificate<'_>, ) -> PyResult { @@ -367,7 +370,10 @@ pub fn cert_to_dict( /// /// Similar to cert_to_dict but includes additional fields like crlDistributionPoints /// and uses CPython's specific ordering: issuer, notAfter, notBefore, serialNumber, subject, version -pub fn cert_der_to_dict_helper(vm: &VirtualMachine, cert_der: &[u8]) -> PyResult { +pub(super) fn cert_der_to_dict_helper( + vm: &VirtualMachine, + cert_der: &[u8], +) -> PyResult { // Parse the certificate using x509-parser let (_, cert) = x509_parser::parse_x509_certificate(cert_der) .map_err(|e| vm.new_value_error(format!("Failed to parse certificate: {e}")))?; @@ -546,7 +552,7 @@ pub fn cert_der_to_dict_helper(vm: &VirtualMachine, cert_der: &[u8]) -> PyResult /// issuer certificates from the trust store until reaching a root certificate. /// /// Returns the complete chain as DER-encoded bytes. -pub fn build_verified_chain( +pub(super) fn build_verified_chain( peer_certs: &[CertificateDer<'static>], ca_certs_der: &[Vec], ) -> Vec> { @@ -605,7 +611,7 @@ pub fn build_verified_chain( /// Statistics from certificate loading operations #[derive(Debug, Clone, Default)] -pub struct CertStats { +pub(super) struct CertStats { pub total_certs: usize, pub ca_certs: usize, } @@ -617,7 +623,7 @@ pub struct CertStats { /// a RootCertStore while tracking statistics. /// /// Duplicate certificates are detected and only counted once. -pub struct CertLoader<'a> { +pub(super) struct CertLoader<'a> { store: &'a mut RootCertStore, ca_certs_der: &'a mut Vec>, seen_certs: HashSet>, @@ -625,7 +631,7 @@ pub struct CertLoader<'a> { impl<'a> CertLoader<'a> { /// Create a new CertLoader with references to the store and DER cache - pub fn new(store: &'a mut RootCertStore, ca_certs_der: &'a mut Vec>) -> Self { + pub(super) fn new(store: &'a mut RootCertStore, ca_certs_der: &'a mut Vec>) -> Self { // Initialize seen_certs with existing certificates let seen_certs = ca_certs_der.iter().cloned().collect(); Self { @@ -638,7 +644,7 @@ impl<'a> CertLoader<'a> { /// Load certificates from a file (supports both PEM and DER formats) /// /// Returns statistics about loaded certificates - pub fn load_from_file(&mut self, path: &str) -> Result { + pub(super) fn load_from_file(&mut self, path: &str) -> Result { let contents = rustpython_host_env::fs::read(path)?; self.load_from_bytes(&contents) } @@ -647,7 +653,7 @@ impl<'a> CertLoader<'a> { /// /// Reads all files in the directory and attempts to parse them as certificates. /// Invalid files are silently skipped (matches OpenSSL capath behavior). - pub fn load_from_dir(&mut self, dir_path: &str) -> Result { + pub(super) fn load_from_dir(&mut self, dir_path: &str) -> Result { let entries = rustpython_host_env::fs::read_dir(dir_path)?; let mut stats = CertStats::default(); @@ -718,7 +724,7 @@ impl<'a> CertLoader<'a> { /// load_verify_locations with cadata parameter). /// /// If `pem_only` is true, only PEM parsing is attempted (for string input) - pub fn load_from_bytes_ex( + pub(super) fn load_from_bytes_ex( &mut self, data: &[u8], treat_all_as_ca: bool, @@ -835,14 +841,14 @@ impl<'a> CertLoader<'a> { /// /// This is a convenience wrapper that calls load_from_bytes_ex with treat_all_as_ca=false /// and pem_only=false. - pub fn load_from_bytes(&mut self, data: &[u8]) -> Result { + pub(super) fn load_from_bytes(&mut self, data: &[u8]) -> Result { self.load_from_bytes_ex(data, false, false) } } // NoVerifier: disables certificate verification (for CERT_NONE mode) #[derive(Debug)] -pub struct NoVerifier; +pub(super) struct NoVerifier; impl ServerCertVerifier for NoVerifier { fn verify_server_cert( @@ -889,14 +895,14 @@ impl ServerCertVerifier for NoVerifier { // this version uses webpki directly to verify only the certificate chain, // completely bypassing hostname verification. #[derive(Debug)] -pub struct HostnameIgnoringVerifier { +pub(super) struct HostnameIgnoringVerifier { inner: Arc, } impl HostnameIgnoringVerifier { /// Create a new HostnameIgnoringVerifier with a pre-built verifier /// This is useful when you need to configure the verifier with CRLs or other options - pub fn new_with_verifier(inner: Arc) -> Self { + pub(super) fn new_with_verifier(inner: Arc) -> Self { Self { inner } } } @@ -1021,7 +1027,7 @@ fn extract_first_dns_name(cert_der: &CertificateDer<'_>) -> Option, // Shared storage for deferred error message @@ -1029,7 +1035,7 @@ pub struct DeferredClientCertVerifier { } impl DeferredClientCertVerifier { - pub fn new( + pub(super) fn new( inner: Arc, deferred_error: Arc>>, ) -> Self { @@ -1253,7 +1259,7 @@ pub(super) fn load_cert_chain_from_file( /// /// Note: This is a simplified validation. Full validation would require /// signing and verifying a test message, which is complex with rustls. -pub fn validate_cert_key_match( +pub(super) fn validate_cert_key_match( certs: &[CertificateDer<'_>], private_key: &PrivateKeyDer<'_>, ) -> Result<(), String> { @@ -1283,7 +1289,7 @@ pub fn validate_cert_key_match( /// /// This matches X509_V_FLAG_X509_STRICT behavior in OpenSSL. #[derive(Debug)] -pub struct StrictCertVerifier { +pub(super) struct StrictCertVerifier { inner: Arc, verify_flags: i32, } @@ -1294,7 +1300,7 @@ impl StrictCertVerifier { /// # Arguments /// * `inner` - The underlying verifier to wrap /// * `verify_flags` - SSL verification flags (e.g., VERIFY_X509_STRICT) - pub fn new(inner: Arc, verify_flags: i32) -> Self { + pub(super) fn new(inner: Arc, verify_flags: i32) -> Self { Self { inner, verify_flags, @@ -1394,7 +1400,7 @@ impl ServerCertVerifier for StrictCertVerifier { /// This allows the SSL context to be created successfully, but handshake will fail /// with a proper SSLCertVerificationError (verify_code=20, UNABLE_TO_GET_ISSUER_CERT_LOCALLY). #[derive(Debug)] -pub struct EmptyRootStoreVerifier; +pub(super) struct EmptyRootStoreVerifier; impl ServerCertVerifier for EmptyRootStoreVerifier { fn verify_server_cert( @@ -1444,14 +1450,14 @@ impl ServerCertVerifier for EmptyRootStoreVerifier { /// This matches X509_V_FLAG_CRL_CHECK without loaded CRLs /// causes "unable to get CRL" error. #[derive(Debug)] -pub struct CRLCheckVerifier { +pub(super) struct CRLCheckVerifier { inner: Arc, has_crls: bool, crl_check_enabled: bool, } impl CRLCheckVerifier { - pub fn new( + pub(super) fn new( inner: Arc, has_crls: bool, crl_check_enabled: bool, @@ -1527,14 +1533,14 @@ impl ServerCertVerifier for CRLCheckVerifier { /// This matches accepting self-signed certificates that /// are explicitly loaded via load_verify_locations(). #[derive(Debug)] -pub struct PartialChainVerifier { +pub(super) struct PartialChainVerifier { inner: Arc, ca_certs_der: Vec>, verify_flags: i32, } impl PartialChainVerifier { - pub fn new( + pub(super) fn new( inner: Arc, ca_certs_der: Vec>, verify_flags: i32, diff --git a/crates/stdlib/src/ssl/compat.rs b/crates/stdlib/src/ssl/compat.rs index a703ab4d8b0..6ea264806d4 100644 --- a/crates/stdlib/src/ssl/compat.rs +++ b/crates/stdlib/src/ssl/compat.rs @@ -43,12 +43,12 @@ use super::error::{ // SSL Verification Flags /// VERIFY_X509_STRICT flag for RFC 5280 strict compliance /// When set, performs additional validation including AKI extension checks -pub const VERIFY_X509_STRICT: i32 = 0x20; +pub(super) const VERIFY_X509_STRICT: i32 = 0x20; /// VERIFY_X509_PARTIAL_CHAIN flag for partial chain validation /// When set, accept certificates if any certificate in the chain is in the trust store /// (not just root CAs). This matches OpenSSL's X509_V_FLAG_PARTIAL_CHAIN behavior. -pub const VERIFY_X509_PARTIAL_CHAIN: i32 = 0x80000; +pub(super) const VERIFY_X509_PARTIAL_CHAIN: i32 = 0x80000; // CryptoProvider Initialization: @@ -91,7 +91,7 @@ const X509_V_FLAG_CRL_CHECK: i32 = 4; // verification. They are used to map rustls certificate errors to OpenSSL // error codes for compatibility. -pub use x509::{ +pub(super) use x509::{ X509_V_ERR_CERT_HAS_EXPIRED, X509_V_ERR_CERT_NOT_YET_VALID, X509_V_ERR_CERT_REVOKED, X509_V_ERR_HOSTNAME_MISMATCH, X509_V_ERR_INVALID_PURPOSE, X509_V_ERR_IP_ADDRESS_MISMATCH, X509_V_ERR_UNABLE_TO_GET_CRL, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, @@ -100,64 +100,64 @@ pub use x509::{ #[allow(dead_code)] mod x509 { - pub const X509_V_OK: i32 = 0; - pub const X509_V_ERR_UNSPECIFIED: i32 = 1; - pub const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: i32 = 2; - pub const X509_V_ERR_UNABLE_TO_GET_CRL: i32 = 3; - pub const X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: i32 = 4; - pub const X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: i32 = 5; - pub const X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: i32 = 6; - pub const X509_V_ERR_CERT_SIGNATURE_FAILURE: i32 = 7; - pub const X509_V_ERR_CRL_SIGNATURE_FAILURE: i32 = 8; - pub const X509_V_ERR_CERT_NOT_YET_VALID: i32 = 9; - pub const X509_V_ERR_CERT_HAS_EXPIRED: i32 = 10; - pub const X509_V_ERR_CRL_NOT_YET_VALID: i32 = 11; - pub const X509_V_ERR_CRL_HAS_EXPIRED: i32 = 12; - pub const X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: i32 = 13; - pub const X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: i32 = 14; - pub const X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: i32 = 15; - pub const X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: i32 = 16; - pub const X509_V_ERR_OUT_OF_MEM: i32 = 17; - pub const X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: i32 = 18; - pub const X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: i32 = 19; - pub const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: i32 = 20; - pub const X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: i32 = 21; - pub const X509_V_ERR_CERT_CHAIN_TOO_LONG: i32 = 22; - pub const X509_V_ERR_CERT_REVOKED: i32 = 23; - pub const X509_V_ERR_INVALID_CA: i32 = 24; - pub const X509_V_ERR_PATH_LENGTH_EXCEEDED: i32 = 25; - pub const X509_V_ERR_INVALID_PURPOSE: i32 = 26; - pub const X509_V_ERR_CERT_UNTRUSTED: i32 = 27; - pub const X509_V_ERR_CERT_REJECTED: i32 = 28; - pub const X509_V_ERR_SUBJECT_ISSUER_MISMATCH: i32 = 29; - pub const X509_V_ERR_AKID_SKID_MISMATCH: i32 = 30; - pub const X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: i32 = 31; - pub const X509_V_ERR_KEYUSAGE_NO_CERTSIGN: i32 = 32; - pub const X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: i32 = 33; - pub const X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: i32 = 34; - pub const X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: i32 = 35; - pub const X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: i32 = 36; - pub const X509_V_ERR_INVALID_NON_CA: i32 = 37; - pub const X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED: i32 = 38; - pub const X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: i32 = 39; - pub const X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED: i32 = 40; - pub const X509_V_ERR_INVALID_EXTENSION: i32 = 41; - pub const X509_V_ERR_INVALID_POLICY_EXTENSION: i32 = 42; - pub const X509_V_ERR_NO_EXPLICIT_POLICY: i32 = 43; - pub const X509_V_ERR_DIFFERENT_CRL_SCOPE: i32 = 44; - pub const X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE: i32 = 45; - pub const X509_V_ERR_UNNESTED_RESOURCE: i32 = 46; - pub const X509_V_ERR_PERMITTED_VIOLATION: i32 = 47; - pub const X509_V_ERR_EXCLUDED_VIOLATION: i32 = 48; - pub const X509_V_ERR_SUBTREE_MINMAX: i32 = 49; - pub const X509_V_ERR_APPLICATION_VERIFICATION: i32 = 50; - pub const X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: i32 = 51; - pub const X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: i32 = 52; - pub const X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: i32 = 53; - pub const X509_V_ERR_CRL_PATH_VALIDATION_ERROR: i32 = 54; - pub const X509_V_ERR_HOSTNAME_MISMATCH: i32 = 62; - pub const X509_V_ERR_EMAIL_MISMATCH: i32 = 63; - pub const X509_V_ERR_IP_ADDRESS_MISMATCH: i32 = 64; + pub(super) const X509_V_OK: i32 = 0; + pub(crate) const X509_V_ERR_UNSPECIFIED: i32 = 1; + pub(super) const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: i32 = 2; + pub(crate) const X509_V_ERR_UNABLE_TO_GET_CRL: i32 = 3; + pub(super) const X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: i32 = 4; + pub(super) const X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: i32 = 5; + pub(super) const X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: i32 = 6; + pub(super) const X509_V_ERR_CERT_SIGNATURE_FAILURE: i32 = 7; + pub(super) const X509_V_ERR_CRL_SIGNATURE_FAILURE: i32 = 8; + pub(crate) const X509_V_ERR_CERT_NOT_YET_VALID: i32 = 9; + pub(crate) const X509_V_ERR_CERT_HAS_EXPIRED: i32 = 10; + pub(super) const X509_V_ERR_CRL_NOT_YET_VALID: i32 = 11; + pub(super) const X509_V_ERR_CRL_HAS_EXPIRED: i32 = 12; + pub(super) const X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: i32 = 13; + pub(super) const X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: i32 = 14; + pub(super) const X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: i32 = 15; + pub(super) const X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: i32 = 16; + pub(super) const X509_V_ERR_OUT_OF_MEM: i32 = 17; + pub(super) const X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: i32 = 18; + pub(super) const X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: i32 = 19; + pub(crate) const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: i32 = 20; + pub(super) const X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: i32 = 21; + pub(super) const X509_V_ERR_CERT_CHAIN_TOO_LONG: i32 = 22; + pub(crate) const X509_V_ERR_CERT_REVOKED: i32 = 23; + pub(super) const X509_V_ERR_INVALID_CA: i32 = 24; + pub(super) const X509_V_ERR_PATH_LENGTH_EXCEEDED: i32 = 25; + pub(crate) const X509_V_ERR_INVALID_PURPOSE: i32 = 26; + pub(super) const X509_V_ERR_CERT_UNTRUSTED: i32 = 27; + pub(super) const X509_V_ERR_CERT_REJECTED: i32 = 28; + pub(super) const X509_V_ERR_SUBJECT_ISSUER_MISMATCH: i32 = 29; + pub(super) const X509_V_ERR_AKID_SKID_MISMATCH: i32 = 30; + pub(super) const X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: i32 = 31; + pub(super) const X509_V_ERR_KEYUSAGE_NO_CERTSIGN: i32 = 32; + pub(super) const X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: i32 = 33; + pub(super) const X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: i32 = 34; + pub(super) const X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: i32 = 35; + pub(super) const X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: i32 = 36; + pub(super) const X509_V_ERR_INVALID_NON_CA: i32 = 37; + pub(super) const X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED: i32 = 38; + pub(super) const X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: i32 = 39; + pub(super) const X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED: i32 = 40; + pub(super) const X509_V_ERR_INVALID_EXTENSION: i32 = 41; + pub(super) const X509_V_ERR_INVALID_POLICY_EXTENSION: i32 = 42; + pub(super) const X509_V_ERR_NO_EXPLICIT_POLICY: i32 = 43; + pub(super) const X509_V_ERR_DIFFERENT_CRL_SCOPE: i32 = 44; + pub(super) const X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE: i32 = 45; + pub(super) const X509_V_ERR_UNNESTED_RESOURCE: i32 = 46; + pub(super) const X509_V_ERR_PERMITTED_VIOLATION: i32 = 47; + pub(super) const X509_V_ERR_EXCLUDED_VIOLATION: i32 = 48; + pub(super) const X509_V_ERR_SUBTREE_MINMAX: i32 = 49; + pub(super) const X509_V_ERR_APPLICATION_VERIFICATION: i32 = 50; + pub(super) const X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: i32 = 51; + pub(super) const X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: i32 = 52; + pub(super) const X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: i32 = 53; + pub(super) const X509_V_ERR_CRL_PATH_VALIDATION_ERROR: i32 = 54; + pub(crate) const X509_V_ERR_HOSTNAME_MISMATCH: i32 = 62; + pub(super) const X509_V_ERR_EMAIL_MISMATCH: i32 = 63; + pub(crate) const X509_V_ERR_IP_ADDRESS_MISMATCH: i32 = 64; } // Certificate Error Conversion Functions: @@ -268,7 +268,7 @@ pub(super) enum TlsConnection { impl TlsConnection { /// Check if handshake is in progress - pub fn is_handshaking(&self) -> bool { + pub(super) fn is_handshaking(&self) -> bool { match self { TlsConnection::Client(conn) => conn.is_handshaking(), TlsConnection::Server(conn) => conn.is_handshaking(), @@ -276,7 +276,7 @@ impl TlsConnection { } /// Check if connection wants to read data - pub fn wants_read(&self) -> bool { + pub(super) fn wants_read(&self) -> bool { match self { TlsConnection::Client(conn) => conn.wants_read(), TlsConnection::Server(conn) => conn.wants_read(), @@ -284,7 +284,7 @@ impl TlsConnection { } /// Check if connection wants to write data - pub fn wants_write(&self) -> bool { + pub(super) fn wants_write(&self) -> bool { match self { TlsConnection::Client(conn) => conn.wants_write(), TlsConnection::Server(conn) => conn.wants_write(), @@ -292,7 +292,7 @@ impl TlsConnection { } /// Read TLS data from socket - pub fn read_tls(&mut self, reader: &mut dyn std::io::Read) -> std::io::Result { + pub(super) fn read_tls(&mut self, reader: &mut dyn std::io::Read) -> std::io::Result { match self { TlsConnection::Client(conn) => conn.read_tls(reader), TlsConnection::Server(conn) => conn.read_tls(reader), @@ -300,7 +300,7 @@ impl TlsConnection { } /// Write TLS data to socket - pub fn write_tls(&mut self, writer: &mut dyn std::io::Write) -> std::io::Result { + pub(super) fn write_tls(&mut self, writer: &mut dyn std::io::Write) -> std::io::Result { match self { TlsConnection::Client(conn) => conn.write_tls(writer), TlsConnection::Server(conn) => conn.write_tls(writer), @@ -308,7 +308,7 @@ impl TlsConnection { } /// Process new TLS packets - pub fn process_new_packets(&mut self) -> Result { + pub(super) fn process_new_packets(&mut self) -> Result { match self { TlsConnection::Client(conn) => conn.process_new_packets(), TlsConnection::Server(conn) => conn.process_new_packets(), @@ -316,7 +316,7 @@ impl TlsConnection { } /// Get reader for plaintext data (rustls native type) - pub fn reader(&mut self) -> rustls::Reader<'_> { + pub(super) fn reader(&mut self) -> rustls::Reader<'_> { match self { TlsConnection::Client(conn) => conn.reader(), TlsConnection::Server(conn) => conn.reader(), @@ -324,7 +324,7 @@ impl TlsConnection { } /// Get writer for plaintext data (rustls native type) - pub fn writer(&mut self) -> rustls::Writer<'_> { + pub(super) fn writer(&mut self) -> rustls::Writer<'_> { match self { TlsConnection::Client(conn) => conn.writer(), TlsConnection::Server(conn) => conn.writer(), @@ -332,7 +332,7 @@ impl TlsConnection { } /// Check if session was resumed - pub fn is_session_resumed(&self) -> bool { + pub(super) fn is_session_resumed(&self) -> bool { use rustls::HandshakeKind; match self { TlsConnection::Client(conn) => { @@ -345,7 +345,7 @@ impl TlsConnection { } /// Send close_notify alert - pub fn send_close_notify(&mut self) { + pub(super) fn send_close_notify(&mut self) { match self { TlsConnection::Client(conn) => conn.send_close_notify(), TlsConnection::Server(conn) => conn.send_close_notify(), @@ -353,7 +353,7 @@ impl TlsConnection { } /// Get negotiated ALPN protocol - pub fn alpn_protocol(&self) -> Option<&[u8]> { + pub(super) fn alpn_protocol(&self) -> Option<&[u8]> { match self { TlsConnection::Client(conn) => conn.alpn_protocol(), TlsConnection::Server(conn) => conn.alpn_protocol(), @@ -361,7 +361,7 @@ impl TlsConnection { } /// Get negotiated cipher suite - pub fn negotiated_cipher_suite(&self) -> Option { + pub(super) fn negotiated_cipher_suite(&self) -> Option { match self { TlsConnection::Client(conn) => conn.negotiated_cipher_suite(), TlsConnection::Server(conn) => conn.negotiated_cipher_suite(), @@ -369,7 +369,9 @@ impl TlsConnection { } /// Get peer certificates - pub fn peer_certificates(&self) -> Option<&[rustls::pki_types::CertificateDer<'static>]> { + pub(super) fn peer_certificates( + &self, + ) -> Option<&[rustls::pki_types::CertificateDer<'static>]> { match self { TlsConnection::Client(conn) => conn.peer_certificates(), TlsConnection::Server(conn) => conn.peer_certificates(), @@ -419,7 +421,7 @@ impl SslError { } /// Convert rustls error to SslError - pub fn from_rustls(err: rustls::Error) -> Self { + pub(super) fn from_rustls(err: rustls::Error) -> Self { match err { rustls::Error::InvalidCertificate(cert_err) => SslError::CertVerification(cert_err), rustls::Error::AlertReceived(alert_desc) => { @@ -547,7 +549,7 @@ impl SslError { } /// Convert to Python exception - pub fn into_py_err(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + pub(super) fn into_py_err(self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { SslError::WantRead => create_ssl_want_read_error(vm).upcast(), SslError::WantWrite => create_ssl_want_write_error(vm).upcast(), @@ -595,10 +597,10 @@ impl SslError { } } -pub type SslResult = Result; +pub(super) type SslResult = Result; /// Common protocol settings shared between client and server connections #[derive(Debug)] -pub struct ProtocolSettings { +pub(super) struct ProtocolSettings { pub versions: &'static [&'static rustls::SupportedProtocolVersion], pub kx_groups: Option>, pub cipher_suites: Option>, @@ -607,7 +609,7 @@ pub struct ProtocolSettings { /// Options for creating a server TLS configuration #[derive(Debug)] -pub struct ServerConfigOptions { +pub(super) struct ServerConfigOptions { /// Common protocol settings (versions, ALPN, KX groups, cipher suites) pub protocol_settings: ProtocolSettings, /// Server certificate chain @@ -632,7 +634,7 @@ pub struct ServerConfigOptions { /// Options for creating a client TLS configuration #[derive(Debug)] -pub struct ClientConfigOptions { +pub(super) struct ClientConfigOptions { /// Common protocol settings (versions, ALPN, KX groups, cipher suites) pub protocol_settings: ProtocolSettings, /// Root certificates for server verification @@ -2230,7 +2232,7 @@ pub(super) struct MultiCertResolver { impl MultiCertResolver { /// Create a new multi-certificate resolver - pub fn new(cert_keys: Vec>) -> Self { + pub(super) fn new(cert_keys: Vec>) -> Self { Self { cert_keys } } } diff --git a/crates/stdlib/src/ssl/error.rs b/crates/stdlib/src/ssl/error.rs index cbc59e0e8f6..07ff4488698 100644 --- a/crates/stdlib/src/ssl/error.rs +++ b/crates/stdlib/src/ssl/error.rs @@ -36,7 +36,7 @@ pub(crate) mod ssl_error { #[pyexception(name = "SSLError", base = PyOSError)] #[derive(Debug)] #[repr(transparent)] - pub struct PySSLError(PyOSError); + pub(crate) struct PySSLError(PyOSError); #[pyexception] impl PySSLError { @@ -65,7 +65,7 @@ pub(crate) mod ssl_error { #[pyexception(name = "SSLZeroReturnError", base = PySSLError)] #[derive(Debug)] #[repr(transparent)] - pub struct PySSLZeroReturnError(PySSLError); + pub(crate) struct PySSLZeroReturnError(PySSLError); #[pyexception] impl PySSLZeroReturnError {} @@ -74,34 +74,34 @@ pub(crate) mod ssl_error { #[pyexception(name = "SSLWantReadError", base = PySSLError, impl)] #[derive(Debug)] #[repr(transparent)] - pub struct PySSLWantReadError(PySSLError); + pub(crate) struct PySSLWantReadError(PySSLError); #[pyattr] #[pyexception(name = "SSLWantWriteError", base = PySSLError, impl)] #[derive(Debug)] #[repr(transparent)] - pub struct PySSLWantWriteError(PySSLError); + pub(crate) struct PySSLWantWriteError(PySSLError); #[pyattr] #[pyexception(name = "SSLSyscallError", base = PySSLError, impl)] #[derive(Debug)] #[repr(transparent)] - pub struct PySSLSyscallError(PySSLError); + pub(crate) struct PySSLSyscallError(PySSLError); #[pyattr] #[pyexception(name = "SSLEOFError", base = PySSLError, impl)] #[derive(Debug)] #[repr(transparent)] - pub struct PySSLEOFError(PySSLError); + pub(crate) struct PySSLEOFError(PySSLError); #[pyattr] #[pyexception(name = "SSLCertVerificationError", base = PySSLError, impl)] #[derive(Debug)] #[repr(transparent)] - pub struct PySSLCertVerificationError(PySSLError); + pub(crate) struct PySSLCertVerificationError(PySSLError); // Helper functions to create SSL exceptions with proper errno attribute - pub fn create_ssl_want_read_error(vm: &VirtualMachine) -> PyRef { + pub(crate) fn create_ssl_want_read_error(vm: &VirtualMachine) -> PyRef { vm.new_os_subtype_error( PySSLWantReadError::class(&vm.ctx).to_owned(), Some(SSL_ERROR_WANT_READ), @@ -109,7 +109,7 @@ pub(crate) mod ssl_error { ) } - pub fn create_ssl_want_write_error(vm: &VirtualMachine) -> PyRef { + pub(crate) fn create_ssl_want_write_error(vm: &VirtualMachine) -> PyRef { vm.new_os_subtype_error( PySSLWantWriteError::class(&vm.ctx).to_owned(), Some(SSL_ERROR_WANT_WRITE), @@ -117,7 +117,7 @@ pub(crate) mod ssl_error { ) } - pub fn create_ssl_eof_error(vm: &VirtualMachine) -> PyRef { + pub(crate) fn create_ssl_eof_error(vm: &VirtualMachine) -> PyRef { vm.new_os_subtype_error( PySSLEOFError::class(&vm.ctx).to_owned(), Some(SSL_ERROR_EOF), @@ -125,7 +125,7 @@ pub(crate) mod ssl_error { ) } - pub fn create_ssl_zero_return_error(vm: &VirtualMachine) -> PyRef { + pub(crate) fn create_ssl_zero_return_error(vm: &VirtualMachine) -> PyRef { vm.new_os_subtype_error( PySSLZeroReturnError::class(&vm.ctx).to_owned(), Some(SSL_ERROR_ZERO_RETURN), @@ -133,7 +133,7 @@ pub(crate) mod ssl_error { ) } - pub fn create_ssl_syscall_error( + pub(crate) fn create_ssl_syscall_error( vm: &VirtualMachine, msg: impl Into, ) -> PyRef { diff --git a/crates/stdlib/src/ssl/oid.rs b/crates/stdlib/src/ssl/oid.rs index d85898c0f79..175951628d1 100644 --- a/crates/stdlib/src/ssl/oid.rs +++ b/crates/stdlib/src/ssl/oid.rs @@ -11,7 +11,7 @@ use std::collections::HashMap; /// OID entry with openssl-compatible metadata #[derive(Debug, Clone)] -pub struct OidEntry { +pub(super) struct OidEntry { /// NID (OpenSSL Numerical Identifier) - must match CPython/OpenSSL values pub nid: i32, /// Short name (e.g., "CN", "serverAuth") @@ -24,7 +24,7 @@ pub struct OidEntry { /// OID reference - either from oid-registry or runtime-created #[derive(Debug, Clone)] -pub enum OidRef { +pub(super) enum OidRef { /// Static OID from oid-registry crate (stored as value) Static(Oid<'static>), /// OID string (for OIDs not in oid-registry) - parsed on demand @@ -33,7 +33,7 @@ pub enum OidRef { impl OidEntry { /// Create entry from oid-registry static constant - pub fn from_static( + pub(super) fn from_static( nid: i32, short_name: &'static str, long_name: &'static str, @@ -48,7 +48,7 @@ impl OidEntry { } /// Create entry from OID string (for OIDs not in oid-registry) - pub const fn from_string( + pub(super) const fn from_string( nid: i32, short_name: &'static str, long_name: &'static str, @@ -63,7 +63,7 @@ impl OidEntry { } /// Get OID as string (e.g., "2.5.4.3") - pub fn oid_string(&self) -> String { + pub(super) fn oid_string(&self) -> String { match &self.oid { OidRef::Static(oid) => oid.to_id_string(), OidRef::String(s) => s.to_string(), @@ -72,7 +72,7 @@ impl OidEntry { } /// OID table with multiple indices for fast lookup -pub struct OidTable { +pub(super) struct OidTable { /// All entries entries: Vec, /// NID -> index mapping @@ -109,17 +109,17 @@ impl OidTable { } } - pub fn find_by_nid(&self, nid: i32) -> Option<&OidEntry> { + pub(super) fn find_by_nid(&self, nid: i32) -> Option<&OidEntry> { self.nid_to_idx.get(&nid).map(|&idx| &self.entries[idx]) } - pub fn find_by_oid_string(&self, oid_str: &str) -> Option<&OidEntry> { + pub(super) fn find_by_oid_string(&self, oid_str: &str) -> Option<&OidEntry> { self.oid_str_to_idx .get(oid_str) .map(|&idx| &self.entries[idx]) } - pub fn find_by_name(&self, name: &str) -> Option<&OidEntry> { + pub(super) fn find_by_name(&self, name: &str) -> Option<&OidEntry> { // Try short name first (exact match) self.short_name_to_idx .get(name) @@ -375,17 +375,17 @@ fn build_oid_entries() -> Vec { // Public API Functions /// Find OID entry by NID -pub fn find_by_nid(nid: i32) -> Option<&'static OidEntry> { +pub(super) fn find_by_nid(nid: i32) -> Option<&'static OidEntry> { OID_TABLE.find_by_nid(nid) } /// Find OID entry by OID string (e.g., "2.5.4.3") -pub fn find_by_oid_string(oid_str: &str) -> Option<&'static OidEntry> { +pub(super) fn find_by_oid_string(oid_str: &str) -> Option<&'static OidEntry> { OID_TABLE.find_by_oid_string(oid_str) } /// Find OID entry by name (short or long name) -pub fn find_by_name(name: &str) -> Option<&'static OidEntry> { +pub(super) fn find_by_name(name: &str) -> Option<&'static OidEntry> { OID_TABLE.find_by_name(name) } diff --git a/crates/stdlib/src/unicodedata.rs b/crates/stdlib/src/unicodedata.rs index afbdbe43881..9a666ee9107 100644 --- a/crates/stdlib/src/unicodedata.rs +++ b/crates/stdlib/src/unicodedata.rs @@ -89,7 +89,7 @@ mod unicodedata { } impl Ucd { - pub const fn new(unic_version: UnicodeVersion) -> Self { + pub(super) const fn new(unic_version: UnicodeVersion) -> Self { Self { unic_version } } diff --git a/crates/vm/src/anystr.rs b/crates/vm/src/anystr.rs index ed32605e587..f1c35ecd65f 100644 --- a/crates/vm/src/anystr.rs +++ b/crates/vm/src/anystr.rs @@ -38,7 +38,7 @@ impl ExpandTabsArgs { } #[derive(FromArgs)] -pub struct StartsEndsWithArgs { +pub(crate) struct StartsEndsWithArgs { #[pyarg(positional)] affix: PyObjectRef, #[pyarg(positional, default)] @@ -48,7 +48,7 @@ pub struct StartsEndsWithArgs { } impl StartsEndsWithArgs { - pub fn get_value(self, len: usize) -> (PyObjectRef, Option>) { + pub(crate) 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 { @@ -58,7 +58,7 @@ impl StartsEndsWithArgs { } #[inline] - pub fn prepare(self, s: &S, len: usize, substr: F) -> Option<(PyObjectRef, &S)> + pub(crate) fn prepare(self, s: &S, len: usize, substr: F) -> Option<(PyObjectRef, &S)> where S: ?Sized + AnyStr, F: Fn(&S, Range) -> &S, @@ -88,7 +88,11 @@ fn saturate_to_isize(py_int: PyIntRef) -> isize { } // help get optional string indices -pub fn adjust_indices(start: Option, end: Option, len: usize) -> Range { +pub(crate) 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 { @@ -108,7 +112,7 @@ pub fn adjust_indices(start: Option, end: Option, len: usize start as usize..end as usize } -pub trait StringRange { +pub(crate) trait StringRange { fn is_normal(&self) -> bool; } @@ -118,12 +122,12 @@ impl StringRange for Range { } } -pub trait AnyStrWrapper { +pub(crate) trait AnyStrWrapper { fn as_ref(&self) -> Option<&S>; fn is_empty(&self) -> bool; } -pub trait AnyStrContainer +pub(crate) trait AnyStrContainer where S: ?Sized, { @@ -132,11 +136,11 @@ where fn push_str(&mut self, s: &S); } -pub trait AnyChar: Copy { +pub(crate) trait AnyChar: Copy { fn bytes_len(self) -> usize; } -pub trait AnyStr { +pub(crate) trait AnyStr { type Char: AnyChar; type Container: AnyStrContainer + Extend; @@ -469,7 +473,7 @@ pub trait AnyStr { /// test that any of the values contained within the tuples satisfies the predicate. Type parameter /// T specifies the type that is expected, if the input value is not of that type or a tuple of /// values of that type, then a TypeError is raised. -pub fn single_or_tuple_any<'a, T, F, M>( +pub(crate) fn single_or_tuple_any<'a, T, F, M>( obj: &'a PyObject, predicate: &F, message: &M, diff --git a/crates/vm/src/buffer.rs b/crates/vm/src/buffer.rs index 9a47dd35858..9b18839149d 100644 --- a/crates/vm/src/buffer.rs +++ b/crates/vm/src/buffer.rs @@ -209,7 +209,7 @@ pub(crate) struct FormatCode { } impl FormatCode { - pub const fn arg_count(&self) -> usize { + pub(crate) const fn arg_count(&self) -> usize { match self.code { FormatType::Pad => 0, FormatType::Str | FormatType::Pascal => 1, @@ -217,7 +217,7 @@ impl FormatCode { } } - pub fn parse( + pub(crate) fn parse( chars: &mut Peekable, endianness: Endianness, ) -> Result<(Vec, usize, usize), String> diff --git a/crates/vm/src/builtins/asyncgenerator.rs b/crates/vm/src/builtins/asyncgenerator.rs index dcb1c6d6f81..224262c3192 100644 --- a/crates/vm/src/builtins/asyncgenerator.rs +++ b/crates/vm/src/builtins/asyncgenerator.rs @@ -620,7 +620,7 @@ impl IterNext for PyAsyncGenAThrow { /// When StopAsyncIteration is raised, it converts it to StopIteration(default). #[pyclass(module = false, name = "anext_awaitable", traverse = "manual")] #[derive(Debug)] -pub struct PyAnextAwaitable { +pub(crate) struct PyAnextAwaitable { wrapped: PyObjectRef, default_value: PyObjectRef, state: AtomicCell, @@ -642,7 +642,7 @@ impl PyPayload for PyAnextAwaitable { #[pyclass(with(IterNext, Iterable))] impl PyAnextAwaitable { - pub fn new(wrapped: PyObjectRef, default_value: PyObjectRef) -> Self { + pub(crate) fn new(wrapped: PyObjectRef, default_value: PyObjectRef) -> Self { Self { wrapped, default_value, @@ -813,7 +813,7 @@ impl Drop for PyAsyncGen { } } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { PyAsyncGen::extend_class(ctx, ctx.types.async_generator); PyAsyncGenASend::extend_class(ctx, ctx.types.async_generator_asend); PyAsyncGenAThrow::extend_class(ctx, ctx.types.async_generator_athrow); diff --git a/crates/vm/src/builtins/builtin_func.rs b/crates/vm/src/builtins/builtin_func.rs index 95c743b16ba..d3195aa0eab 100644 --- a/crates/vm/src/builtins/builtin_func.rs +++ b/crates/vm/src/builtins/builtin_func.rs @@ -255,7 +255,7 @@ fn vectorcall_native_function( (zelf.value.func)(vm, func_args) } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyNativeFunction::extend_class(context, context.types.builtin_function_or_method_type); context .types diff --git a/crates/vm/src/builtins/bytearray.rs b/crates/vm/src/builtins/bytearray.rs index 0285526692c..5a1b8565a9e 100644 --- a/crates/vm/src/builtins/bytearray.rs +++ b/crates/vm/src/builtins/bytearray.rs @@ -46,7 +46,7 @@ pub struct PyByteArray { exports: AtomicUsize, } -pub type PyByteArrayRef = PyRef; +pub(crate) type PyByteArrayRef = PyRef; impl From for PyByteArray { fn from(inner: PyBytesInner) -> Self { @@ -856,7 +856,7 @@ impl Representable for PyByteArray { #[pyclass(module = false, name = "bytearray_iterator")] #[derive(Debug)] -pub struct PyByteArrayIterator { +pub(crate) struct PyByteArrayIterator { internal: PyMutex>, } diff --git a/crates/vm/src/builtins/bytes.rs b/crates/vm/src/builtins/bytes.rs index 00cf3d2d113..6bc546523cc 100644 --- a/crates/vm/src/builtins/bytes.rs +++ b/crates/vm/src/builtins/bytes.rs @@ -734,7 +734,7 @@ impl Representable for PyBytes { #[pyclass(module = false, name = "bytes_iterator")] #[derive(Debug)] -pub struct PyBytesIterator { +pub(crate) struct PyBytesIterator { internal: PyMutex>, } diff --git a/crates/vm/src/builtins/capsule.rs b/crates/vm/src/builtins/capsule.rs index 9be57c09fed..33680fb1973 100644 --- a/crates/vm/src/builtins/capsule.rs +++ b/crates/vm/src/builtins/capsule.rs @@ -60,6 +60,6 @@ impl Destructor for PyCapsule { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyCapsule::extend_class(context, context.types.capsule_type); } diff --git a/crates/vm/src/builtins/code.rs b/crates/vm/src/builtins/code.rs index d2da5fc5a70..456be793f59 100644 --- a/crates/vm/src/builtins/code.rs +++ b/crates/vm/src/builtins/code.rs @@ -344,7 +344,7 @@ impl ConstantBag for PyObjBag<'_> { } #[derive(Clone, Copy)] -pub struct PyVmBag<'a>(pub &'a VirtualMachine); +pub(crate) struct PyVmBag<'a>(pub &'a VirtualMachine); impl ConstantBag for PyVmBag<'_> { type Constant = Literal; @@ -424,7 +424,7 @@ impl ConstantBag for PyVmBag<'_> { } } -pub type CodeObject = bytecode::CodeObject; +pub(crate) type CodeObject = bytecode::CodeObject; pub trait IntoCodeObject { fn into_code_object(self, ctx: &Context) -> CodeObject; @@ -1543,6 +1543,6 @@ impl<'a> LineTableReader<'a> { } } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { PyCode::extend_class(ctx, ctx.types.code_type); } diff --git a/crates/vm/src/builtins/complex.rs b/crates/vm/src/builtins/complex.rs index 9034c5f3fb3..f121d6c1b5f 100644 --- a/crates/vm/src/builtins/complex.rs +++ b/crates/vm/src/builtins/complex.rs @@ -129,7 +129,7 @@ impl PyObjectRef { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyComplex::extend_class(context, context.types.complex_type); } diff --git a/crates/vm/src/builtins/coroutine.rs b/crates/vm/src/builtins/coroutine.rs index 9746dddda87..c705dd5e248 100644 --- a/crates/vm/src/builtins/coroutine.rs +++ b/crates/vm/src/builtins/coroutine.rs @@ -171,7 +171,7 @@ impl Destructor for PyCoroutine { #[pyclass(module = false, name = "coroutine_wrapper", traverse = "manual")] #[derive(Debug)] // PyCoroWrapper_Type in CPython -pub struct PyCoroutineWrapper { +pub(crate) struct PyCoroutineWrapper { coro: PyRef, closed: AtomicCell, } @@ -247,7 +247,7 @@ impl Drop for PyCoroutine { } } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { PyCoroutine::extend_class(ctx, ctx.types.coroutine_type); PyCoroutineWrapper::extend_class(ctx, ctx.types.coroutine_wrapper_type); } diff --git a/crates/vm/src/builtins/descriptor.rs b/crates/vm/src/builtins/descriptor.rs index acfe58d723b..c8825572212 100644 --- a/crates/vm/src/builtins/descriptor.rs +++ b/crates/vm/src/builtins/descriptor.rs @@ -177,7 +177,8 @@ pub enum MemberKind { ObjectEx = 16, } -pub type MemberSetterFunc = Option PyResult<()>>; +pub(crate) type MemberSetterFunc = + Option PyResult<()>>; pub enum MemberGetter { Getter(fn(&VirtualMachine, PyObjectRef) -> PyResult), @@ -471,7 +472,7 @@ fn vectorcall_wrapper( zelf.wrapped.call(obj, rest, vm) } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { PyMemberDescriptor::extend_class(ctx, ctx.types.member_descriptor_type); PyMethodDescriptor::extend_class(ctx, ctx.types.method_descriptor_type); ctx.types @@ -762,7 +763,7 @@ impl SlotFunc { // = PyWrapperDescrObject #[pyclass(name = "wrapper_descriptor", module = false)] #[derive(Debug)] -pub struct PyWrapper { +pub(crate) struct PyWrapper { pub typ: &'static Py, pub name: &'static PyStrInterned, pub wrapped: SlotFunc, @@ -855,7 +856,7 @@ impl Representable for PyWrapper { /// Returned when accessing l.__init__ on an instance #[pyclass(name = "method-wrapper", module = false, traverse)] #[derive(Debug)] -pub struct PyMethodWrapper { +pub(crate) struct PyMethodWrapper { pub wrapper: PyRef, #[pytraverse(skip)] pub obj: PyObjectRef, diff --git a/crates/vm/src/builtins/dict.rs b/crates/vm/src/builtins/dict.rs index 9791435a23a..1593c250f86 100644 --- a/crates/vm/src/builtins/dict.rs +++ b/crates/vm/src/builtins/dict.rs @@ -33,7 +33,7 @@ use core::ptr::NonNull; use rustpython_common::lock::PyMutex; use rustpython_common::wtf8::Wtf8Buf; -pub type DictContentType = dict_inner::Dict; +pub(crate) type DictContentType = dict_inner::Dict; #[pyclass(module = false, name = "dict", unhashable = true, traverse = "manual")] #[derive(Default)] @@ -897,18 +897,26 @@ trait DictView: PyPayload + PyClassDef + Iterable + Representable { } macro_rules! dict_view { - ( $name: ident, $iter_name: ident, $reverse_iter_name: ident, - $class: ident, $iter_class: ident, $reverse_iter_class: ident, - $class_name: literal, $iter_class_name: literal, $reverse_iter_class_name: literal, - $result_fn: expr) => { + ( + $name: ident, + $iter_name: ident, + $reverse_iter_name: ident, + $class: ident, + $iter_class: ident, + $reverse_iter_class: ident, + $class_name: literal, + $iter_class_name: literal, + $reverse_iter_class_name: literal, + $result_fn: expr + ) => { #[pyclass(module = false, name = $class_name)] #[derive(Debug)] pub(crate) struct $name { - pub dict: PyDictRef, + pub(crate) dict: PyDictRef, } impl $name { - pub const fn new(dict: PyDictRef) -> Self { + pub(crate) const fn new(dict: PyDictRef) -> Self { $name { dict } } } @@ -972,8 +980,8 @@ macro_rules! dict_view { #[pyclass(module = false, name = $iter_class_name)] #[derive(Debug)] pub(crate) struct $iter_name { - pub size: dict_inner::DictSize, - pub internal: PyMutex>, + pub(crate) size: dict_inner::DictSize, + pub(crate) internal: PyMutex>, } impl PyPayload for $iter_name { @@ -1014,6 +1022,7 @@ macro_rules! dict_view { } impl SelfIter for $iter_name {} + impl IterNext for $iter_name { #[allow(clippy::redundant_closure_call)] fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { @@ -1045,7 +1054,7 @@ macro_rules! dict_view { #[pyclass(module = false, name = $reverse_iter_class_name)] #[derive(Debug)] pub(crate) struct $reverse_iter_name { - pub size: dict_inner::DictSize, + pub(crate) size: dict_inner::DictSize, internal: PyMutex>, } @@ -1090,7 +1099,9 @@ macro_rules! dict_view { .rev_length_hint(|_| self.size.entries_size) } } + impl SelfIter for $reverse_iter_name {} + impl IterNext for $reverse_iter_name { #[allow(clippy::redundant_closure_call)] fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { diff --git a/crates/vm/src/builtins/enumerate.rs b/crates/vm/src/builtins/enumerate.rs index 3cca47ce2d3..96073ba7667 100644 --- a/crates/vm/src/builtins/enumerate.rs +++ b/crates/vm/src/builtins/enumerate.rs @@ -87,7 +87,7 @@ impl IterNext for PyEnumerate { #[pyclass(module = false, name = "reversed", traverse)] #[derive(Debug)] -pub struct PyReverseSequenceIterator { +pub(crate) struct PyReverseSequenceIterator { internal: PyMutex>, } @@ -100,7 +100,7 @@ impl PyPayload for PyReverseSequenceIterator { #[pyclass(with(IterNext, Iterable))] impl PyReverseSequenceIterator { - pub const fn new(obj: PyObjectRef, len: usize) -> Self { + pub(crate) const fn new(obj: PyObjectRef, len: usize) -> Self { let position = len.saturating_sub(1); Self { internal: PyMutex::new(PositionIterInternal::new(obj, position)), @@ -144,7 +144,7 @@ impl IterNext for PyReverseSequenceIterator { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyEnumerate::extend_class(context, context.types.enumerate_type); PyReverseSequenceIterator::extend_class(context, context.types.reverse_iter_type); } diff --git a/crates/vm/src/builtins/filter.rs b/crates/vm/src/builtins/filter.rs index 56d951f8a79..2bce5c7822a 100644 --- a/crates/vm/src/builtins/filter.rs +++ b/crates/vm/src/builtins/filter.rs @@ -71,6 +71,6 @@ impl IterNext for PyFilter { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyFilter::extend_class(context, context.types.filter_type); } diff --git a/crates/vm/src/builtins/float.rs b/crates/vm/src/builtins/float.rs index 4adec5e2a07..ddce34a8820 100644 --- a/crates/vm/src/builtins/float.rs +++ b/crates/vm/src/builtins/float.rs @@ -154,7 +154,7 @@ fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> { float_ops::divmod(v1, v2).ok_or_else(|| vm.new_zero_division_error("division by zero")) } -pub fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { +pub(crate) fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { if v1.is_zero() && v2.is_sign_negative() { let msg = "zero to a negative power"; Err(vm.new_zero_division_error(msg.to_owned())) @@ -543,7 +543,7 @@ fn vectorcall_float( } #[rustfmt::skip] // to avoid line splitting -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyFloat::extend_class(context, context.types.float_type); context.types.float_type.slots.vectorcall.store(Some(vectorcall_float)); } diff --git a/crates/vm/src/builtins/frame.rs b/crates/vm/src/builtins/frame.rs index 42615e81a7a..e79df2db7f2 100644 --- a/crates/vm/src/builtins/frame.rs +++ b/crates/vm/src/builtins/frame.rs @@ -29,14 +29,14 @@ pub(crate) mod stack_analysis { const MAX_STACK_ENTRIES: u32 = 63 / BITS_PER_BLOCK; // 21 const WILL_OVERFLOW: u64 = 1u64 << ((MAX_STACK_ENTRIES - 1) * BITS_PER_BLOCK); - pub const EMPTY_STACK: i64 = 0; - pub const UNINITIALIZED: i64 = -2; - pub const OVERFLOWED: i64 = -1; + pub(crate) const EMPTY_STACK: i64 = 0; + pub(crate) const UNINITIALIZED: i64 = -2; + pub(crate) const OVERFLOWED: i64 = -1; /// Kind of a stack entry. #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[repr(i64)] - pub enum Kind { + pub(crate) enum Kind { Iterator = 1, Except = 2, Object = 3, @@ -57,7 +57,7 @@ pub(crate) mod stack_analysis { } } - pub fn push_value(stack: i64, kind: i64) -> i64 { + pub(crate) fn push_value(stack: i64, kind: i64) -> i64 { if (stack as u64) >= WILL_OVERFLOW { OVERFLOWED } else { @@ -65,11 +65,11 @@ pub(crate) mod stack_analysis { } } - pub fn pop_value(stack: i64) -> i64 { + pub(crate) fn pop_value(stack: i64) -> i64 { stack >> BITS_PER_BLOCK } - pub fn top_of_stack(stack: i64) -> i64 { + pub(crate) fn top_of_stack(stack: i64) -> i64 { stack & MASK } @@ -112,7 +112,7 @@ pub(crate) mod stack_analysis { from == to } - pub fn compatible_stack(from_stack: i64, to_stack: i64) -> bool { + pub(crate) fn compatible_stack(from_stack: i64, to_stack: i64) -> bool { if from_stack < 0 || to_stack < 0 { return false; } @@ -133,7 +133,7 @@ pub(crate) mod stack_analysis { to == 0 } - pub fn explain_incompatible_stack(to_stack: i64) -> &'static str { + pub(crate) fn explain_incompatible_stack(to_stack: i64) -> &'static str { debug_assert!(to_stack != 0); if to_stack == OVERFLOWED { return "stack is too deep to analyze"; @@ -150,7 +150,7 @@ pub(crate) mod stack_analysis { } /// Analyze bytecode and compute the stack state at each instruction index. - pub fn mark_stacks(code: &bytecode::CodeObject) -> Vec { + pub(crate) fn mark_stacks(code: &bytecode::CodeObject) -> Vec { let instructions = &*code.instructions; let len = instructions.len(); @@ -393,7 +393,7 @@ pub(crate) mod stack_analysis { /// Build a mapping from instruction index to line number. /// Returns -1 for indices with no line start. - pub fn mark_lines(code: &bytecode::CodeObject) -> Vec { + pub(crate) fn mark_lines(code: &bytecode::CodeObject) -> Vec { let len = code.instructions.len(); let mut line_starts = vec![-1i32; len]; let mut last_line: i32 = -1; @@ -412,7 +412,7 @@ pub(crate) mod stack_analysis { } /// Find the first line number >= `line` that has code. - pub fn first_line_not_before(lines: &[i32], line: i32) -> i32 { + pub(crate) fn first_line_not_before(lines: &[i32], line: i32) -> i32 { let mut result = i32::MAX; for &l in lines { if l >= line && l < result { @@ -423,7 +423,7 @@ pub(crate) mod stack_analysis { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { Frame::extend_class(context, context.types.frame_type); } diff --git a/crates/vm/src/builtins/function.rs b/crates/vm/src/builtins/function.rs index 93ba3693b93..a81c3908b5a 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -1415,16 +1415,16 @@ impl Constructor for PyCell { #[pyclass(with(Constructor))] impl PyCell { - pub const fn new(contents: Option) -> Self { + pub(crate) const fn new(contents: Option) -> Self { Self { contents: PyMutex::new(contents), } } - pub fn get(&self) -> Option { + pub(crate) fn get(&self) -> Option { self.contents.lock().clone() } - pub fn set(&self, x: Option) { + pub(crate) fn set(&self, x: Option) { *self.contents.lock() = x; } @@ -1506,7 +1506,7 @@ fn vectorcall_bound_method( zelf.function.vectorcall(args, new_nargs, kwnames, vm) } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyFunction::extend_class(context, context.types.function_type); context .types diff --git a/crates/vm/src/builtins/generator.rs b/crates/vm/src/builtins/generator.rs index 2eee2fecd0d..e4e11f05e83 100644 --- a/crates/vm/src/builtins/generator.rs +++ b/crates/vm/src/builtins/generator.rs @@ -173,6 +173,6 @@ impl Drop for PyGenerator { } } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { PyGenerator::extend_class(ctx, ctx.types.generator_type); } diff --git a/crates/vm/src/builtins/genericalias.rs b/crates/vm/src/builtins/genericalias.rs index 1564229d186..0f22241c0f7 100644 --- a/crates/vm/src/builtins/genericalias.rs +++ b/crates/vm/src/builtins/genericalias.rs @@ -446,7 +446,7 @@ fn unpack_args(item: PyObjectRef, vm: &VirtualMachine) -> PyResult { } // _Py_subs_parameters -pub fn subs_parameters( +pub(crate) fn subs_parameters( alias: PyObjectRef, // = self args: PyTupleRef, parameters: PyTupleRef, @@ -670,7 +670,7 @@ impl Iterable for PyGenericAlias { // gaiterobject - yields one starred GenericAlias then exhausts #[pyclass(module = "types", name = "generic_alias_iterator")] #[derive(Debug, PyPayload)] -pub struct PyGenericAliasIterator { +pub(crate) struct PyGenericAliasIterator { obj: crate::common::lock::PyMutex>, } @@ -724,7 +724,7 @@ impl crate::types::IterNext for PyGenericAliasIterator { /// Creates a GenericAlias from type parameters, equivalent to _Py_subscript_generic. /// This is used for PEP 695 classes to create Generic[T] from type parameters. // _Py_subscript_generic -pub fn subscript_generic(type_params: PyObjectRef, vm: &VirtualMachine) -> PyResult { +pub(crate) fn subscript_generic(type_params: PyObjectRef, vm: &VirtualMachine) -> PyResult { let typing_module = vm.import("typing", 0)?; let generic_type = typing_module.get_attr("Generic", vm)?; let generic_alias_class = typing_module.get_attr("_GenericAlias", vm)?; @@ -740,7 +740,7 @@ pub fn subscript_generic(type_params: PyObjectRef, vm: &VirtualMachine) -> PyRes generic_alias_class.call((generic_type, args.to_pyobject(vm)), vm) } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyGenericAlias::extend_class(context, context.types.generic_alias_type); PyGenericAliasIterator::extend_class(context, context.types.generic_alias_iterator_type); } diff --git a/crates/vm/src/builtins/int.rs b/crates/vm/src/builtins/int.rs index a586a881711..e8cd5ca5016 100644 --- a/crates/vm/src/builtins/int.rs +++ b/crates/vm/src/builtins/int.rs @@ -765,7 +765,7 @@ impl PyInt { } #[derive(FromArgs)] -pub struct IntOptions { +pub(crate) struct IntOptions { #[pyarg(positional, optional)] val_options: OptionalArg, #[pyarg(any, optional)] diff --git a/crates/vm/src/builtins/interpolation.rs b/crates/vm/src/builtins/interpolation.rs index 327565263cf..25c5e034cd4 100644 --- a/crates/vm/src/builtins/interpolation.rs +++ b/crates/vm/src/builtins/interpolation.rs @@ -224,6 +224,6 @@ impl Representable for PyInterpolation { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyInterpolation::extend_class(context, context.types.interpolation_type); } diff --git a/crates/vm/src/builtins/list.rs b/crates/vm/src/builtins/list.rs index f3ea11b595b..a59d9367f03 100644 --- a/crates/vm/src/builtins/list.rs +++ b/crates/vm/src/builtins/list.rs @@ -669,7 +669,7 @@ fn do_sort( #[pyclass(module = false, name = "list_iterator", traverse)] #[derive(Debug)] -pub struct PyListIterator { +pub(crate) struct PyListIterator { internal: PyMutex>, } @@ -735,7 +735,7 @@ impl IterNext for PyListIterator { #[pyclass(module = false, name = "list_reverseiterator", traverse)] #[derive(Debug)] -pub struct PyListReverseIterator { +pub(crate) struct PyListReverseIterator { internal: PyMutex>, } @@ -796,7 +796,7 @@ fn vectorcall_list( Ok(obj.into()) } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { let list_type = &context.types.list_type; PyList::extend_class(context, list_type); list_type.slots.vectorcall.store(Some(vectorcall_list)); diff --git a/crates/vm/src/builtins/map.rs b/crates/vm/src/builtins/map.rs index 663c1bc94e0..eff2ed72ff5 100644 --- a/crates/vm/src/builtins/map.rs +++ b/crates/vm/src/builtins/map.rs @@ -124,6 +124,6 @@ impl IterNext for PyMap { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyMap::extend_class(context, context.types.map_type); } diff --git a/crates/vm/src/builtins/mappingproxy.rs b/crates/vm/src/builtins/mappingproxy.rs index 3f9a2538d57..9603a77f730 100644 --- a/crates/vm/src/builtins/mappingproxy.rs +++ b/crates/vm/src/builtins/mappingproxy.rs @@ -304,6 +304,6 @@ impl Representable for PyMappingProxy { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyMappingProxy::extend_class(context, context.types.mappingproxy_type) } diff --git a/crates/vm/src/builtins/memory.rs b/crates/vm/src/builtins/memory.rs index 73eb1f1780b..d063bf0144f 100644 --- a/crates/vm/src/builtins/memory.rs +++ b/crates/vm/src/builtins/memory.rs @@ -1185,7 +1185,7 @@ impl Iterable for PyMemoryView { #[pyclass(module = false, name = "memory_iterator")] #[derive(Debug, Traverse)] -pub struct PyMemoryViewIterator { +pub(crate) struct PyMemoryViewIterator { internal: PyMutex>>, } diff --git a/crates/vm/src/builtins/module.rs b/crates/vm/src/builtins/module.rs index cabaf1d63cb..07142fe0cea 100644 --- a/crates/vm/src/builtins/module.rs +++ b/crates/vm/src/builtins/module.rs @@ -23,9 +23,9 @@ pub struct PyModuleDef { // free: free_func } -pub type ModuleCreate = +pub(crate) type ModuleCreate = fn(&VirtualMachine, &PyObject, &'static PyModuleDef) -> PyResult>; -pub type ModuleExec = fn(&VirtualMachine, &Py) -> PyResult<()>; +pub(crate) type ModuleExec = fn(&VirtualMachine, &Py) -> PyResult<()>; #[derive(Default)] pub struct PyModuleSlots { diff --git a/crates/vm/src/builtins/namespace.rs b/crates/vm/src/builtins/namespace.rs index 4e872a172a4..1ec73e0f732 100644 --- a/crates/vm/src/builtins/namespace.rs +++ b/crates/vm/src/builtins/namespace.rs @@ -175,6 +175,6 @@ impl Representable for PyNamespace { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyNamespace::extend_class(context, context.types.namespace_type); } diff --git a/crates/vm/src/builtins/object.rs b/crates/vm/src/builtins/object.rs index f600e36beea..6670d64d588 100644 --- a/crates/vm/src/builtins/object.rs +++ b/crates/vm/src/builtins/object.rs @@ -553,7 +553,7 @@ impl PyBaseObject { } } -pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { +pub(crate) fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { if let Some(dict) = obj.dict() { Ok(dict) } else { @@ -563,7 +563,7 @@ pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult, vm: &VirtualMachine, @@ -576,7 +576,7 @@ pub fn object_set_dict( .map_err(|_| vm.new_attribute_error("This object has no __dict__")) } -pub fn object_generic_set_dict( +pub(crate) fn object_generic_set_dict( obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine, @@ -596,7 +596,7 @@ pub fn object_generic_set_dict( object_set_dict(obj, dict, vm) } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { // Manually set alloc/init slots - derive macro doesn't generate extend_slots // for trait impl that overrides #[pyslot] method ctx.types.object_type.slots.alloc.store(Some(generic_alloc)); diff --git a/crates/vm/src/builtins/range.rs b/crates/vm/src/builtins/range.rs index 6e03ea8b482..48bc660ea6f 100644 --- a/crates/vm/src/builtins/range.rs +++ b/crates/vm/src/builtins/range.rs @@ -207,7 +207,7 @@ impl PyRange { // obj.downcast_ref::().unwrap().clone() // } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyRange::extend_class(context, context.types.range_type); PyLongRangeIterator::extend_class(context, context.types.long_range_iterator_type); PyRangeIterator::extend_class(context, context.types.range_iterator_type); @@ -581,7 +581,7 @@ impl Representable for PyRange { // can be BigInts, we can store any arbitrary range of values. #[pyclass(module = false, name = "longrange_iterator")] #[derive(Debug)] -pub struct PyLongRangeIterator { +pub(crate) struct PyLongRangeIterator { index: AtomicCell, start: BigInt, step: BigInt, @@ -646,7 +646,7 @@ impl IterNext for PyLongRangeIterator { // that only operates using isize to track values. #[pyclass(module = false, name = "range_iterator")] #[derive(Debug)] -pub struct PyRangeIterator { +pub(crate) struct PyRangeIterator { index: AtomicCell, start: isize, step: isize, @@ -742,7 +742,7 @@ fn range_state(length: &BigInt, state: PyObjectRef, vm: &VirtualMachine) -> PyRe } } -pub enum RangeIndex { +pub(crate) enum RangeIndex { Int(PyIntRef), Slice(PyRef), } diff --git a/crates/vm/src/builtins/set.rs b/crates/vm/src/builtins/set.rs index fe1da1174d7..e738b80e81f 100644 --- a/crates/vm/src/builtins/set.rs +++ b/crates/vm/src/builtins/set.rs @@ -32,7 +32,7 @@ use rustpython_common::{ hash, }; -pub type SetContentType = dict_inner::Dict<()>; +pub(crate) type SetContentType = dict_inner::Dict<()>; #[pyclass(module = false, name = "set", unhashable = true, traverse)] #[derive(Default)] @@ -1432,7 +1432,7 @@ fn vectorcall_frozenset( (zelf.slots.new.load().unwrap())(zelf.to_owned(), func_args, vm) } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PySet::extend_class(context, context.types.set_type); context .types diff --git a/crates/vm/src/builtins/singletons.rs b/crates/vm/src/builtins/singletons.rs index 00d84dfabb6..31dbf1666f1 100644 --- a/crates/vm/src/builtins/singletons.rs +++ b/crates/vm/src/builtins/singletons.rs @@ -151,7 +151,7 @@ impl Representable for PyNotImplemented { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyNone::extend_class(context, context.types.none_type); PyNotImplemented::extend_class(context, context.types.not_implemented_type); } diff --git a/crates/vm/src/builtins/slice.rs b/crates/vm/src/builtins/slice.rs index 9c6fa5b59fe..96fb3fb5a5e 100644 --- a/crates/vm/src/builtins/slice.rs +++ b/crates/vm/src/builtins/slice.rs @@ -413,7 +413,7 @@ impl Representable for PyEllipsis { } } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { PySlice::extend_class(ctx, ctx.types.slice_type); PyEllipsis::extend_class(ctx, ctx.types.ellipsis_type); } diff --git a/crates/vm/src/builtins/staticmethod.rs b/crates/vm/src/builtins/staticmethod.rs index 551e1cb4b88..d11ba5b3b84 100644 --- a/crates/vm/src/builtins/staticmethod.rs +++ b/crates/vm/src/builtins/staticmethod.rs @@ -196,6 +196,6 @@ impl Representable for PyStaticMethod { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyStaticMethod::extend_class(context, context.types.staticmethod_type); } diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index 8a50c4a5268..1a91d918c58 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -309,7 +309,7 @@ impl<'a> AsPyStr<'a> for &'a PyUtf8StrInterned { #[pyclass(module = false, name = "str_iterator", traverse = "manual")] #[derive(Debug)] -pub struct PyStrIterator { +pub(crate) struct PyStrIterator { internal: PyMutex<(PositionIterInternal, usize)>, } @@ -1792,7 +1792,7 @@ impl ToPyObject for AsciiChar { type SplitArgs = anystr::SplitArgs; #[derive(FromArgs)] -pub struct FindArgs { +pub(crate) struct FindArgs { #[pyarg(positional)] sub: PyStrRef, #[pyarg(positional, default)] @@ -1832,7 +1832,7 @@ fn vectorcall_str( (zelf.slots.new.load().unwrap())(zelf.to_owned(), func_args, vm) } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { PyStr::extend_class(ctx, ctx.types.str_type); ctx.types .str_type diff --git a/crates/vm/src/builtins/super.rs b/crates/vm/src/builtins/super.rs index 88998dc8c8a..f75b9b36327 100644 --- a/crates/vm/src/builtins/super.rs +++ b/crates/vm/src/builtins/super.rs @@ -276,7 +276,7 @@ fn super_check(ty: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult ))) } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { let super_type = &context.types.super_type; PySuper::extend_class(context, super_type); diff --git a/crates/vm/src/builtins/template.rs b/crates/vm/src/builtins/template.rs index 3f03f9a227a..03814343511 100644 --- a/crates/vm/src/builtins/template.rs +++ b/crates/vm/src/builtins/template.rs @@ -329,7 +329,7 @@ impl IterNext for PyTemplateIter { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyTemplate::extend_class(context, context.types.template_type); PyTemplateIter::extend_class(context, context.types.template_iter_type); } diff --git a/crates/vm/src/builtins/traceback.rs b/crates/vm/src/builtins/traceback.rs index c6eac4e87e7..c4dc6a6cfe2 100644 --- a/crates/vm/src/builtins/traceback.rs +++ b/crates/vm/src/builtins/traceback.rs @@ -17,7 +17,7 @@ pub struct PyTraceback { pub lineno: OneIndexed, } -pub type PyTracebackRef = PyRef; +pub(crate) type PyTracebackRef = PyRef; impl PyPayload for PyTraceback { #[inline] @@ -119,7 +119,7 @@ impl PyTracebackRef { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyTraceback::extend_class(context, context.types.traceback_type); } diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index 5c834919c01..6208bc5ebfe 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -205,7 +205,7 @@ fn type_cache_clear_version(version: u32) { /// Sets TYPE_CACHE_CLEARING to suppress cache re-population during the /// entire operation, preventing concurrent lookups from repopulating /// entries while we're clearing them. -pub fn type_cache_clear() { +pub(crate) fn type_cache_clear() { TYPE_CACHE_CLEARING.store(true, Ordering::Release); for entry in TYPE_CACHE.iter() { entry.begin_write(); @@ -364,13 +364,13 @@ impl TypeSpecializationCache { } } -pub struct PointerSlot(NonNull); +pub(crate) struct PointerSlot(NonNull); unsafe impl Sync for PointerSlot {} unsafe impl Send for PointerSlot {} impl PointerSlot { - pub const unsafe fn borrow_static(&self) -> &'static T { + pub(crate) const unsafe fn borrow_static(&self) -> &'static T { unsafe { self.0.as_ref() } } } @@ -408,7 +408,7 @@ cfg_select! { /// For attributes we do not use a dict, but an IndexMap, which is an Hash Table /// that maintains order and is compatible with the standard HashMap This is probably /// faster and only supports strings as keys. -pub type PyAttributes = IndexMap<&'static PyStrInterned, PyObjectRef, ahash::RandomState>; +pub(crate) type PyAttributes = IndexMap<&'static PyStrInterned, PyObjectRef, ahash::RandomState>; unsafe impl Traverse for PyAttributes { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { diff --git a/crates/vm/src/builtins/union.rs b/crates/vm/src/builtins/union.rs index c3a7e42c7ab..fa653427884 100644 --- a/crates/vm/src/builtins/union.rs +++ b/crates/vm/src/builtins/union.rs @@ -219,7 +219,7 @@ fn has_union_operands(a: PyObjectRef, b: PyObjectRef, vm: &VirtualMachine) -> bo a.class().is(union_type) || b.class().is(union_type) } -pub fn or_op(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { +pub(crate) fn or_op(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if !has_union_operands(zelf.clone(), other.clone(), vm) && (!is_unionable(zelf.clone(), vm) || !is_unionable(other.clone(), vm)) { @@ -540,7 +540,7 @@ impl Representable for PyUnion { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { let union_type = &context.types.union_type; PyUnion::extend_class(context, union_type); } diff --git a/crates/vm/src/builtins/weakproxy.rs b/crates/vm/src/builtins/weakproxy.rs index 44579afcc76..8cdc206db88 100644 --- a/crates/vm/src/builtins/weakproxy.rs +++ b/crates/vm/src/builtins/weakproxy.rs @@ -355,7 +355,7 @@ impl Representable for PyWeakProxy { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyWeakProxy::extend_class(context, context.types.weakproxy_type); } diff --git a/crates/vm/src/builtins/weakref.rs b/crates/vm/src/builtins/weakref.rs index 43d4af38221..c7c4466a1d2 100644 --- a/crates/vm/src/builtins/weakref.rs +++ b/crates/vm/src/builtins/weakref.rs @@ -165,6 +165,6 @@ impl Representable for PyWeak { } } -pub fn init(context: &'static Context) { +pub(crate) fn init(context: &'static Context) { PyWeak::extend_class(context, context.types.weakref_type); } diff --git a/crates/vm/src/builtins/zip.rs b/crates/vm/src/builtins/zip.rs index 19c036e7951..b090cd424d6 100644 --- a/crates/vm/src/builtins/zip.rs +++ b/crates/vm/src/builtins/zip.rs @@ -113,6 +113,6 @@ impl IterNext for PyZip { } } -pub fn init(ctx: &'static Context) { +pub(crate) fn init(ctx: &'static Context) { PyZip::extend_class(ctx, ctx.types.zip_type); } diff --git a/crates/vm/src/bytes_inner.rs b/crates/vm/src/bytes_inner.rs index 52fda9e7f2b..c8645245611 100644 --- a/crates/vm/src/bytes_inner.rs +++ b/crates/vm/src/bytes_inner.rs @@ -225,7 +225,7 @@ impl ByteInnerTranslateOptions { } } -pub type ByteInnerSplitOptions = anystr::SplitArgs; +pub(crate) type ByteInnerSplitOptions = anystr::SplitArgs; impl PyBytesInner { #[inline] @@ -972,7 +972,7 @@ impl PyBytesInner { } } -pub fn try_as_bytes(obj: PyObjectRef, f: F) -> Option +pub(crate) fn try_as_bytes(obj: PyObjectRef, f: F) -> Option where F: Fn(&[u8]) -> R, { @@ -993,7 +993,7 @@ fn count_substring(haystack: &[u8], needle: &[u8], max_count: Option) -> } } -pub trait ByteOr: ToPrimitive { +pub(crate) trait ByteOr: ToPrimitive { fn byte_or(&self, vm: &VirtualMachine) -> PyResult { match self.to_u8() { Some(value) => Ok(value), @@ -1116,14 +1116,14 @@ impl AnyStr for [u8] { } #[derive(FromArgs)] -pub struct DecodeArgs { +pub(crate) struct DecodeArgs { #[pyarg(any, default)] encoding: Option, #[pyarg(any, default)] errors: Option, } -pub fn bytes_decode( +pub(crate) fn bytes_decode( zelf: PyObjectRef, args: DecodeArgs, vm: &VirtualMachine, @@ -1190,7 +1190,7 @@ fn hex_impl(bytes: &[u8], sep: u8, bytes_per_sep: isize) -> String { unsafe { String::from_utf8_unchecked(buf) } } -pub fn bytes_to_hex( +pub(crate) fn bytes_to_hex( bytes: &[u8], sep: OptionalArg>, bytes_per_sep: OptionalArg, @@ -1233,6 +1233,6 @@ pub fn bytes_to_hex( } } -pub const fn is_py_ascii_whitespace(b: u8) -> bool { +pub(crate) const fn is_py_ascii_whitespace(b: u8) -> bool { matches!(b, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' | b'\x0B') } diff --git a/crates/vm/src/codecs.rs b/crates/vm/src/codecs.rs index 8e393ee7dc2..8a49694ac69 100644 --- a/crates/vm/src/codecs.rs +++ b/crates/vm/src/codecs.rs @@ -34,7 +34,7 @@ struct RegistryInner { errors: HashMap, } -pub const DEFAULT_ENCODING: &str = "utf-8"; +pub(crate) const DEFAULT_ENCODING: &str = "utf-8"; #[derive(Clone)] #[repr(transparent)] @@ -580,7 +580,7 @@ impl<'a> DecodeErrorHandler> for SurrogatePass { } } -pub struct PyEncodeContext<'a> { +pub(crate) struct PyEncodeContext<'a> { vm: &'a VirtualMachine, encoding: &'a str, data: &'a Py, @@ -589,7 +589,7 @@ pub struct PyEncodeContext<'a> { } impl<'a> PyEncodeContext<'a> { - pub fn new(encoding: &'a str, data: &'a Py, vm: &'a VirtualMachine) -> Self { + pub(crate) fn new(encoding: &'a str, data: &'a Py, vm: &'a VirtualMachine) -> Self { Self { vm, encoding, @@ -683,7 +683,7 @@ impl EncodeContext for PyEncodeContext<'_> { } } -pub struct PyDecodeContext<'a> { +pub(crate) struct PyDecodeContext<'a> { vm: &'a VirtualMachine, encoding: &'a str, data: PyDecodeData<'a>, @@ -706,7 +706,7 @@ impl ops::Deref for PyDecodeData<'_> { } impl<'a> PyDecodeContext<'a> { - pub fn new(encoding: &'a str, data: &'a ArgBytesLike, vm: &'a VirtualMachine) -> Self { + pub(crate) fn new(encoding: &'a str, data: &'a ArgBytesLike, vm: &'a VirtualMachine) -> Self { Self { vm, encoding, @@ -855,7 +855,7 @@ impl<'a> DecodeErrorHandler> for StandardError { } } -pub struct ErrorsHandler<'a> { +pub(crate) struct ErrorsHandler<'a> { errors: &'a Py, resolved: OnceCell, } @@ -866,7 +866,7 @@ enum ResolvedError { impl<'a> ErrorsHandler<'a> { #[inline] - pub fn new(errors: Option<&'a Py>, vm: &VirtualMachine) -> Self { + pub(crate) fn new(errors: Option<&'a Py>, vm: &VirtualMachine) -> Self { match errors { Some(errors) => Self { errors, diff --git a/crates/vm/src/coroutine.rs b/crates/vm/src/coroutine.rs index e77bcec61a3..34d280acdca 100644 --- a/crates/vm/src/coroutine.rs +++ b/crates/vm/src/coroutine.rs @@ -313,7 +313,7 @@ impl Coro { } } -pub fn is_gen_exit(exc: &Py, vm: &VirtualMachine) -> bool { +pub(crate) fn is_gen_exit(exc: &Py, vm: &VirtualMachine) -> bool { exc.fast_isinstance(vm.ctx.exceptions.generator_exit) } @@ -321,7 +321,7 @@ pub fn is_gen_exit(exc: &Py, vm: &VirtualMachine) -> bool { /// /// Returns the object itself if it's a coroutine or iterable coroutine (generator with /// CO_ITERABLE_COROUTINE flag). Otherwise calls `__await__()` and validates the result. -pub fn get_awaitable_iter(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { +pub(crate) fn get_awaitable_iter(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { use crate::builtins::{PyCoroutine, PyGenerator}; use crate::protocol::PyIter; @@ -364,7 +364,7 @@ pub fn get_awaitable_iter(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { } /// Emit DeprecationWarning for the deprecated 3-argument throw() signature. -pub fn warn_deprecated_throw_signature( +pub(crate) fn warn_deprecated_throw_signature( exc_val: &OptionalArg, exc_tb: &OptionalArg, vm: &VirtualMachine, diff --git a/crates/vm/src/dict_inner.rs b/crates/vm/src/dict_inner.rs index 763fa856319..b21ba9882dd 100644 --- a/crates/vm/src/dict_inner.rs +++ b/crates/vm/src/dict_inner.rs @@ -37,7 +37,7 @@ type IndexIndex = usize; /// index into dict.entries type EntryIndex = usize; -pub struct Dict { +pub(crate) struct Dict { inner: PyRwLock>, version: AtomicU64, } @@ -263,7 +263,7 @@ type PopInnerResult = ControlFlow>>; impl Dict { /// Monotonically increasing version counter for mutation tracking. - pub fn version(&self) -> u64 { + pub(crate) fn version(&self) -> u64 { self.version.load(Acquire) } @@ -281,7 +281,7 @@ impl Dict { } /// Store a key - pub fn insert(&self, vm: &VirtualMachine, key: &K, value: T) -> PyResult<()> + pub(crate) fn insert(&self, vm: &VirtualMachine, key: &K, value: T) -> PyResult<()> where K: DictKey + ?Sized, { @@ -324,7 +324,11 @@ impl Dict { Ok(()) } - pub fn contains(&self, vm: &VirtualMachine, key: &K) -> PyResult { + pub(crate) fn contains( + &self, + vm: &VirtualMachine, + key: &K, + ) -> PyResult { let key_hash = key.key_hash(vm)?; let (entry, _) = self.lookup(vm, key, key_hash, None)?; Ok(entry.index().is_some()) @@ -332,7 +336,11 @@ impl Dict { /// Retrieve a key #[cfg_attr(feature = "flame-it", flame("Dict"))] - pub fn get(&self, vm: &VirtualMachine, key: &K) -> PyResult> { + pub(crate) fn get( + &self, + vm: &VirtualMachine, + key: &K, + ) -> PyResult> { let hash = key.key_hash(vm)?; self._get_inner(vm, key, hash) } @@ -341,7 +349,7 @@ impl Dict { /// /// The hint is the internal entry index and can be used with /// [`Self::get_hint`]. It is invalidated by dict mutations. - pub fn hint_for_key( + pub(crate) fn hint_for_key( &self, vm: &VirtualMachine, key: &K, @@ -357,7 +365,7 @@ impl Dict { /// Fast path lookup using a cached entry index (`hint`). /// /// Returns `None` if the hint is stale or the key no longer matches. - pub fn get_hint( + pub(crate) fn get_hint( &self, vm: &VirtualMachine, key: &K, @@ -404,7 +412,7 @@ impl Dict { Ok(ret) } - pub fn get_chain( + pub(crate) fn get_chain( &self, other: &Self, vm: &VirtualMachine, @@ -418,7 +426,7 @@ impl Dict { } } - pub fn clear(&self) { + pub(crate) fn clear(&self) { let _removed = { let mut inner = self.write(); inner.indices.clear(); @@ -432,7 +440,7 @@ impl Dict { } /// Delete a key - pub fn delete(&self, vm: &VirtualMachine, key: &K) -> PyResult<()> + pub(crate) fn delete(&self, vm: &VirtualMachine, key: &K) -> PyResult<()> where K: DictKey + ?Sized, { @@ -443,14 +451,14 @@ impl Dict { } } - pub fn delete_if_exists(&self, vm: &VirtualMachine, key: &K) -> PyResult + pub(crate) fn delete_if_exists(&self, vm: &VirtualMachine, key: &K) -> PyResult where K: DictKey + ?Sized, { self.remove_if_exists(vm, key).map(|opt| opt.is_some()) } - pub fn delete_if(&self, vm: &VirtualMachine, key: &K, pred: F) -> PyResult + pub(crate) fn delete_if(&self, vm: &VirtualMachine, key: &K, pred: F) -> PyResult where K: DictKey + ?Sized, F: Fn(&T) -> PyResult, @@ -458,7 +466,7 @@ impl Dict { self.remove_if(vm, key, pred).map(|opt| opt.is_some()) } - pub fn remove_if_exists(&self, vm: &VirtualMachine, key: &K) -> PyResult> + pub(crate) fn remove_if_exists(&self, vm: &VirtualMachine, key: &K) -> PyResult> where K: DictKey + ?Sized, { @@ -488,7 +496,12 @@ impl Dict { Ok(removed.map(|entry| entry.value)) } - pub fn delete_or_insert(&self, vm: &VirtualMachine, key: &PyObject, value: T) -> PyResult<()> { + pub(crate) fn delete_or_insert( + &self, + vm: &VirtualMachine, + key: &PyObject, + value: T, + ) -> PyResult<()> { let hash = key.key_hash(vm)?; let _removed = loop { let lookup = self.lookup(vm, key, hash, None)?; @@ -511,7 +524,7 @@ impl Dict { Ok(()) } - pub fn setdefault(&self, vm: &VirtualMachine, key: &K, default: F) -> PyResult + pub(crate) fn setdefault(&self, vm: &VirtualMachine, key: &K, default: F) -> PyResult where K: DictKey + ?Sized, F: FnOnce() -> T, @@ -547,7 +560,7 @@ impl Dict { } #[allow(dead_code)] - pub fn setdefault_entry( + pub(crate) fn setdefault_entry( &self, vm: &VirtualMachine, key: &K, @@ -583,15 +596,15 @@ impl Dict { } } - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { self.read().used } - pub fn size(&self) -> DictSize { + pub(crate) fn size(&self) -> DictSize { self.read().size() } - pub fn next_entry(&self, mut position: EntryIndex) -> Option<(usize, PyObjectRef, T)> { + pub(crate) fn next_entry(&self, mut position: EntryIndex) -> Option<(usize, PyObjectRef, T)> { let inner = self.read(); loop { let entry = inner.entries.get(position)?; @@ -602,7 +615,7 @@ impl Dict { } } - pub fn prev_entry(&self, mut position: EntryIndex) -> Option<(usize, PyObjectRef, T)> { + pub(crate) fn prev_entry(&self, mut position: EntryIndex) -> Option<(usize, PyObjectRef, T)> { let inner = self.read(); loop { let entry = inner.entries.get(position)?; @@ -613,16 +626,16 @@ impl Dict { } } - pub fn len_from_entry_index(&self, position: EntryIndex) -> usize { + pub(crate) fn len_from_entry_index(&self, position: EntryIndex) -> usize { self.read().entries.len().saturating_sub(position) } - pub fn has_changed_size(&self, old: &DictSize) -> bool { + pub(crate) fn has_changed_size(&self, old: &DictSize) -> bool { let current = self.read().size(); current != *old } - pub fn keys(&self) -> Vec { + pub(crate) fn keys(&self) -> Vec { self.read() .entries .iter() @@ -630,7 +643,7 @@ impl Dict { .collect() } - pub fn values(&self) -> Vec { + pub(crate) fn values(&self) -> Vec { self.read() .entries .iter() @@ -638,7 +651,7 @@ impl Dict { .collect() } - pub fn items(&self) -> Vec<(PyObjectRef, T)> { + pub(crate) fn items(&self) -> Vec<(PyObjectRef, T)> { self.read() .entries .iter() @@ -646,7 +659,7 @@ impl Dict { .collect() } - pub fn try_fold_keys(&self, init: Acc, f: Fold) -> PyResult + pub(crate) fn try_fold_keys(&self, init: Acc, f: Fold) -> PyResult where Fold: FnMut(Acc, &PyObject) -> PyResult, { @@ -771,7 +784,11 @@ impl Dict { } /// Retrieve and delete a key - pub fn pop(&self, vm: &VirtualMachine, key: &K) -> PyResult> { + pub(crate) fn pop( + &self, + vm: &VirtualMachine, + key: &K, + ) -> PyResult> { let hash_value = key.key_hash(vm)?; let removed = loop { let lookup = self.lookup(vm, key, hash_value, None)?; @@ -783,7 +800,7 @@ impl Dict { Ok(removed) } - pub fn pop_back(&self) -> Option<(PyObjectRef, T)> { + pub(crate) fn pop_back(&self) -> Option<(PyObjectRef, T)> { let inner = &mut *self.write(); let entry = loop { let entry = inner.entries.pop()?; @@ -800,7 +817,7 @@ impl Dict { Some((entry.key, entry.value)) } - pub fn sizeof(&self) -> usize { + pub(crate) fn sizeof(&self) -> usize { let inner = self.read(); size_of::() + size_of::>() @@ -811,7 +828,7 @@ impl Dict { /// Pop all entries from the dict, returning (key, value) pairs. /// This is used for circular reference resolution in GC. /// Requires &mut self to avoid lock contention. - pub fn drain_entries(&mut self) -> impl Iterator + '_ { + pub(crate) fn drain_entries(&mut self) -> impl Iterator + '_ { let inner = self.inner.get_mut(); inner.used = 0; inner.filled = 0; diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index aa6f552e426..e50d3fb7a7f 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -1283,7 +1283,7 @@ pub(crate) struct OSErrorBuilder { impl OSErrorBuilder { #[must_use] - pub fn with_subtype( + pub(crate) fn with_subtype( exc_type: PyTypeRef, errno: Option, strerror: impl ToPyObject, @@ -1302,7 +1302,7 @@ impl OSErrorBuilder { } #[must_use] - pub fn with_errno(errno: i32, strerror: impl ToPyObject, vm: &VirtualMachine) -> Self { + pub(crate) fn with_errno(errno: i32, strerror: impl ToPyObject, vm: &VirtualMachine) -> Self { let exc_type = errno_to_exc_type(errno, vm) .unwrap_or(vm.ctx.exceptions.os_error) .to_owned(); @@ -1340,7 +1340,7 @@ impl OSErrorBuilder { self } - pub fn build(self, vm: &VirtualMachine) -> PyRef { + pub(crate) fn build(self, vm: &VirtualMachine) -> PyRef { use types::PyOSError; let OSErrorBuilder { diff --git a/crates/vm/src/function/getset.rs b/crates/vm/src/function/getset.rs index e7a6ae5bdec..bcd745f561b 100644 --- a/crates/vm/src/function/getset.rs +++ b/crates/vm/src/function/getset.rs @@ -51,8 +51,8 @@ where } } -pub type PyGetterFunc = Box PyResult)>; -pub type PySetterFunc = +pub(crate) type PyGetterFunc = Box PyResult)>; +pub(crate) type PySetterFunc = Box PyResult<()>)>; pub trait IntoPyGetterFunc: PyThreadingConstraint + Sized + 'static { diff --git a/crates/vm/src/getpath.rs b/crates/vm/src/getpath.rs index 75b7c45a66e..13e3841c0fa 100644 --- a/crates/vm/src/getpath.rs +++ b/crates/vm/src/getpath.rs @@ -15,21 +15,21 @@ use std::path::{Path, PathBuf}; mod platform { use crate::version; - pub const BUILDDIR_TXT: &str = "pybuilddir.txt"; - pub const BUILD_LANDMARK: &str = "Modules/Setup.local"; - pub const VENV_LANDMARK: &str = "pyvenv.cfg"; - pub const BUILDSTDLIB_LANDMARK: &str = "Lib/os.py"; + pub(super) const BUILDDIR_TXT: &str = "pybuilddir.txt"; + pub(super) const BUILD_LANDMARK: &str = "Modules/Setup.local"; + pub(super) const VENV_LANDMARK: &str = "pyvenv.cfg"; + pub(super) const BUILDSTDLIB_LANDMARK: &str = "Lib/os.py"; - pub fn stdlib_subdir() -> String { + pub(super) fn stdlib_subdir() -> String { format!("lib/python{}.{}", version::MAJOR, version::MINOR) } - pub fn stdlib_landmarks() -> [String; 2] { + pub(super) fn stdlib_landmarks() -> [String; 2] { let subdir = stdlib_subdir(); [format!("{}/os.py", subdir), format!("{}/os.pyc", subdir)] } - pub fn platstdlib_landmark() -> String { + pub(super) fn platstdlib_landmark() -> String { format!( "lib/python{}.{}/lib-dynload", version::MAJOR, @@ -37,7 +37,7 @@ mod platform { ) } - pub fn zip_landmark() -> String { + pub(super) fn zip_landmark() -> String { format!("lib/python{}{}.zip", version::MAJOR, version::MINOR) } } @@ -46,21 +46,21 @@ mod platform { mod platform { use crate::version; - pub const BUILDDIR_TXT: &str = "pybuilddir.txt"; - pub const BUILD_LANDMARK: &str = "Modules\\Setup.local"; - pub const VENV_LANDMARK: &str = "pyvenv.cfg"; - pub const BUILDSTDLIB_LANDMARK: &str = "Lib\\os.py"; - pub const STDLIB_SUBDIR: &str = "Lib"; + pub(super) const BUILDDIR_TXT: &str = "pybuilddir.txt"; + pub(super) const BUILD_LANDMARK: &str = "Modules\\Setup.local"; + pub(super) const VENV_LANDMARK: &str = "pyvenv.cfg"; + pub(super) const BUILDSTDLIB_LANDMARK: &str = "Lib\\os.py"; + pub(super) const STDLIB_SUBDIR: &str = "Lib"; - pub fn stdlib_landmarks() -> [String; 2] { + pub(super) fn stdlib_landmarks() -> [String; 2] { ["Lib\\os.py".into(), "Lib\\os.pyc".into()] } - pub fn platstdlib_landmark() -> String { + pub(super) fn platstdlib_landmark() -> String { "DLLs".into() } - pub fn zip_landmark() -> String { + pub(super) fn zip_landmark() -> String { format!("python{}{}.zip", version::MAJOR, version::MINOR) } } diff --git a/crates/vm/src/intern.rs b/crates/vm/src/intern.rs index 37b971b8dca..3082d655454 100644 --- a/crates/vm/src/intern.rs +++ b/crates/vm/src/intern.rs @@ -10,7 +10,7 @@ use alloc::borrow::ToOwned; use core::{borrow::Borrow, ops::Deref}; #[derive(Debug)] -pub struct StringPool { +pub(crate) struct StringPool { inner: PyRwLock>, } @@ -42,7 +42,7 @@ impl StringPool { } #[inline] - pub unsafe fn intern( + pub(crate) unsafe fn intern( &self, s: S, typ: PyTypeRef, @@ -74,7 +74,7 @@ impl StringPool { } #[inline] - pub fn interned( + pub(crate) fn interned( &self, s: &S, ) -> Option<&'static PyStrInterned> { @@ -90,7 +90,7 @@ impl StringPool { #[derive(Debug, Clone)] #[repr(transparent)] -pub struct CachedPyStrRef { +pub(crate) struct CachedPyStrRef { inner: PyRefExact, } diff --git a/crates/vm/src/object/core.rs b/crates/vm/src/object/core.rs index 39ef93de5fb..d09ce069331 100644 --- a/crates/vm/src/object/core.rs +++ b/crates/vm/src/object/core.rs @@ -548,7 +548,7 @@ unsafe fn unlink_weakref(wrl: &WeakRefList, node: NonNull>) { } impl WeakRefList { - pub fn new() -> Self { + pub(super) fn new() -> Self { Self { head: Radium::new(ptr::null_mut()), generic: Radium::new(ptr::null_mut()), @@ -950,31 +950,31 @@ impl From for InstanceDict { impl InstanceDict { #[inline] - pub const fn new(d: PyDictRef) -> Self { + pub(crate) const fn new(d: PyDictRef) -> Self { Self { d: PyRwLock::new(Some(d)), } } #[inline] - pub const fn from_opt(d: Option) -> Self { + pub(crate) const fn from_opt(d: Option) -> Self { Self { d: PyRwLock::new(d), } } #[inline] - pub fn get(&self) -> Option { + pub(crate) fn get(&self) -> Option { self.d.read().clone() } #[inline] - pub fn set(&self, d: Option) { + pub(crate) fn set(&self, d: Option) { self.replace(d); } #[inline] - pub fn replace(&self, d: Option) -> Option { + pub(crate) fn replace(&self, d: Option) -> Option { core::mem::replace(&mut self.d.write(), d) } diff --git a/crates/vm/src/object/traverse_object.rs b/crates/vm/src/object/traverse_object.rs index f5614b3502a..57542637788 100644 --- a/crates/vm/src/object/traverse_object.rs +++ b/crates/vm/src/object/traverse_object.rs @@ -23,7 +23,7 @@ pub(in crate::object) struct PyObjVTable { } impl PyObjVTable { - pub const fn of() -> &'static Self { + pub(super) const fn of() -> &'static Self { &Self { typeid: T::PAYLOAD_TYPE_ID, dealloc: default_dealloc::, diff --git a/crates/vm/src/ospath.rs b/crates/vm/src/ospath.rs index c90d4789db3..71950729847 100644 --- a/crates/vm/src/ospath.rs +++ b/crates/vm/src/ospath.rs @@ -306,7 +306,7 @@ impl From for OsPathOrFd<'_> { } impl OsPathOrFd<'_> { - pub fn filename(&self, vm: &VirtualMachine) -> PyObjectRef { + pub(crate) fn filename(&self, vm: &VirtualMachine) -> PyObjectRef { match self { Self::Path(path) => path.filename(vm), Self::Fd(fd) => fd.to_pyobject(vm), diff --git a/crates/vm/src/readline.rs b/crates/vm/src/readline.rs index cf82c3ba1ff..b154bd1365c 100644 --- a/crates/vm/src/readline.rs +++ b/crates/vm/src/readline.rs @@ -19,10 +19,11 @@ pub enum ReadlineResult { } #[allow(unused)] -mod basic_readline { +pub mod basic_readline { use super::*; pub trait Helper {} + impl Helper for T {} pub struct Readline { @@ -65,7 +66,7 @@ mod basic_readline { } #[cfg(not(target_arch = "wasm32"))] -mod rustyline_readline { +pub mod rustyline_readline { use super::*; pub trait Helper: rustyline::Helper {} diff --git a/crates/vm/src/stdlib/_ast.rs b/crates/vm/src/stdlib/_ast.rs index 104ad39ee12..8307d0bae6d 100644 --- a/crates/vm/src/stdlib/_ast.rs +++ b/crates/vm/src/stdlib/_ast.rs @@ -126,7 +126,7 @@ struct PySourceRange { end: PySourceLocation, } -pub struct PySourceLocation { +pub(crate) struct PySourceLocation { row: Row, column: Column, } @@ -815,18 +815,18 @@ pub(crate) fn validate_ast_object(vm: &VirtualMachine, object: PyObjectRef) -> P } // Used by builtins::compile() -pub const PY_CF_ONLY_AST: i32 = 0x0400; +pub(crate) const PY_CF_ONLY_AST: i32 = 0x0400; // The following flags match the values from Include/cpython/compile.h // Caveat emptor: These flags are undocumented on purpose and depending // on their effect outside the standard library is **unsupported**. -pub const PY_CF_SOURCE_IS_UTF8: i32 = 0x0100; -pub const PY_CF_DONT_IMPLY_DEDENT: i32 = 0x200; -pub const PY_CF_IGNORE_COOKIE: i32 = 0x0800; -pub const PY_CF_ALLOW_INCOMPLETE_INPUT: i32 = 0x4000; -pub const PY_CF_OPTIMIZED_AST: i32 = 0x8000 | PY_CF_ONLY_AST; -pub const PY_CF_TYPE_COMMENTS: i32 = 0x1000; -pub const PY_CF_ALLOW_TOP_LEVEL_AWAIT: i32 = 0x2000; +pub(crate) const PY_CF_SOURCE_IS_UTF8: i32 = 0x0100; +pub(crate) const PY_CF_DONT_IMPLY_DEDENT: i32 = 0x200; +pub(crate) const PY_CF_IGNORE_COOKIE: i32 = 0x0800; +pub(crate) const PY_CF_ALLOW_INCOMPLETE_INPUT: i32 = 0x4000; +pub(crate) const PY_CF_OPTIMIZED_AST: i32 = 0x8000 | PY_CF_ONLY_AST; +pub(crate) const PY_CF_TYPE_COMMENTS: i32 = 0x1000; +pub(crate) const PY_CF_ALLOW_TOP_LEVEL_AWAIT: i32 = 0x2000; // __future__ flags - sync with Lib/__future__.py // TODO: These flags aren't being used in rust code @@ -845,7 +845,7 @@ const CO_FUTURE_GENERATOR_STOP: i32 = 0x800000; const CO_FUTURE_ANNOTATIONS: i32 = 0x1000000; // Used by builtins::compile() - the summary of all flags -pub const PY_COMPILE_FLAGS_MASK: i32 = PY_CF_ONLY_AST +pub(crate) const PY_COMPILE_FLAGS_MASK: i32 = PY_CF_ONLY_AST | PY_CF_SOURCE_IS_UTF8 | PY_CF_DONT_IMPLY_DEDENT | PY_CF_IGNORE_COOKIE diff --git a/crates/vm/src/stdlib/_ast/pyast.rs b/crates/vm/src/stdlib/_ast/pyast.rs index 4b6e97e13fc..c9017006f1d 100644 --- a/crates/vm/src/stdlib/_ast/pyast.rs +++ b/crates/vm/src/stdlib/_ast/pyast.rs @@ -1521,7 +1521,7 @@ const FIELD_TYPES: &[(&str, &[(&str, FieldType)])] = &[ ), ]; -pub fn extend_module_nodes(vm: &VirtualMachine, module: &Py) { +pub(super) fn extend_module_nodes(vm: &VirtualMachine, module: &Py) { extend_module!(vm, module, { "AST" => NodeAst::make_static_type(), "mod" => NodeMod::make_static_type(), diff --git a/crates/vm/src/stdlib/_ctypes.rs b/crates/vm/src/stdlib/_ctypes.rs index 0ffcb1e01ab..527188c01a2 100644 --- a/crates/vm/src/stdlib/_ctypes.rs +++ b/crates/vm/src/stdlib/_ctypes.rs @@ -22,12 +22,12 @@ use core::ffi::{ use core::mem; use widestring::WideChar; -pub use array::PyCArray; -pub use base::{FfiArgValue, PyCData, PyCField, StgInfo, StgInfoFlags}; -pub use pointer::PyCPointer; -pub use simple::{PyCSimple, PyCSimpleType}; -pub use structure::PyCStructure; -pub use union::PyCUnion; +pub(super) use array::PyCArray; +pub(super) use base::{FfiArgValue, PyCData, PyCField, StgInfo, StgInfoFlags}; +pub(super) use pointer::PyCPointer; +pub(super) use simple::{PyCSimple, PyCSimpleType}; +pub(super) use structure::PyCStructure; +pub(super) use union::PyCUnion; /// Extension for PyType to get StgInfo /// PyStgInfo_FromType @@ -249,7 +249,7 @@ pub(crate) mod _ctypes { /// tagPyCArgObject #[pyclass(name = "CArgObject", module = "_ctypes", no_attr)] #[derive(Debug, PyPayload)] - pub struct CArgObject { + pub(crate) struct CArgObject { /// Type tag ('P', 'V', 'i', 'd', etc.) pub tag: u8, /// The actual FFI value (mirrors union value) @@ -480,7 +480,7 @@ pub(crate) mod _ctypes { /// Get the size of a ctypes type or instance #[pyfunction] - pub fn sizeof(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + pub(crate) fn sizeof(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { use super::structure::PyCStructType; use super::union::PyCUnionType; @@ -768,7 +768,11 @@ pub(crate) mod _ctypes { } #[pyfunction] - pub fn byref(obj: PyObjectRef, offset: OptionalArg, vm: &VirtualMachine) -> PyResult { + pub(crate) fn byref( + obj: PyObjectRef, + offset: OptionalArg, + vm: &VirtualMachine, + ) -> PyResult { use super::FfiArgValue; // Check if obj is a ctypes instance diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index d236f80f9cf..c04e342547a 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -392,7 +392,7 @@ impl AsNumber for PyCArrayType { )] #[derive(Debug)] #[repr(transparent)] -pub struct PyCArray(pub PyCData); +pub(crate) struct PyCArray(pub PyCData); impl PyCArray { /// Get the type code of array element type (e.g., "c" for c_char, "u" for c_wchar) diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index 8558e614474..7d611c27b0f 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -77,7 +77,7 @@ pub(super) enum ParamFunc { } #[derive(Clone)] -pub struct StgInfo { +pub(crate) struct StgInfo { pub initialized: bool, pub size: usize, // number of bytes pub align: usize, // alignment requirements @@ -154,7 +154,7 @@ impl Default for StgInfo { } impl StgInfo { - pub fn new(size: usize, align: usize) -> Self { + pub(crate) fn new(size: usize, align: usize) -> Self { StgInfo { initialized: true, size, @@ -178,7 +178,7 @@ impl StgInfo { /// item_shape: the element's shape (will be prepended with length) /// item_flags: the element type's flags (for HASPOINTER inheritance) #[allow(clippy::too_many_arguments)] - pub fn new_array( + pub(crate) fn new_array( size: usize, align: usize, length: usize, @@ -227,7 +227,7 @@ impl StgInfo { /// Get libffi type for this StgInfo /// Note: For very large types, returns pointer type to avoid overflow - pub fn to_ffi_type(&self) -> libffi::middle::Type { + pub(crate) fn to_ffi_type(&self) -> libffi::middle::Type { // Limit to avoid overflow in libffi (MAX_STRUCT_SIZE is platform-dependent) const MAX_FFI_STRUCT_SIZE: usize = 1024 * 1024; // 1MB limit for safety @@ -293,12 +293,12 @@ impl StgInfo { } /// Check if this type is finalized (cannot set _fields_ again) - pub fn is_final(&self) -> bool { + pub(crate) fn is_final(&self) -> bool { self.flags.contains(StgInfoFlags::DICTFLAG_FINAL) } /// Get proto type reference (for Pointer/Array types) - pub fn proto(&self) -> &Py { + pub(crate) fn proto(&self) -> &Py { self.proto.as_deref().expect("type has proto") } } @@ -449,7 +449,7 @@ pub(super) fn str_to_wchar_bytes(s: &Wtf8, vm: &VirtualMachine) -> (PyObjectRef, /// PyCData - base type for all ctypes data types #[pyclass(name = "_CData", module = "_ctypes")] #[derive(Debug, PyPayload)] -pub struct PyCData { +pub(crate) struct PyCData { /// Memory buffer - Owned (self-owned) or Borrowed (external reference) /// /// SAFETY: Borrowed variant's 'static lifetime is not actually static. @@ -475,7 +475,7 @@ pub struct PyCData { impl PyCData { /// Create from StgInfo (PyCData_MallocBuffer pattern) - pub fn from_stg_info(stg_info: &StgInfo) -> Self { + pub(crate) fn from_stg_info(stg_info: &StgInfo) -> Self { PyCData { buffer: PyRwLock::new(Cow::Owned(vec![0u8; stg_info.size])), base: PyRwLock::new(None), @@ -488,7 +488,7 @@ impl PyCData { } /// Create from existing bytes (copies data) - pub fn from_bytes(data: Vec, objects: Option) -> Self { + pub(crate) fn from_bytes(data: Vec, objects: Option) -> Self { PyCData { buffer: PyRwLock::new(Cow::Owned(data)), base: PyRwLock::new(None), @@ -501,7 +501,7 @@ impl PyCData { } /// Create from bytes with specified length (for arrays) - pub fn from_bytes_with_length( + pub(crate) fn from_bytes_with_length( data: Vec, objects: Option, length: usize, @@ -523,7 +523,7 @@ impl PyCData { /// The returned slice's 'static lifetime is a lie. /// Actually only valid for the lifetime of the memory pointed to by ptr. /// PyCData_AtAddress - pub unsafe fn at_address(ptr: *const u8, size: usize) -> Self { + pub(crate) 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 { core::slice::from_raw_parts(ptr, size) }; @@ -543,7 +543,7 @@ impl PyCData { /// Similar to from_base_with_offset, but also stores a copy of the data. /// This is used for arrays where we need our own buffer for the buffer protocol, /// but still maintain the base reference for KeepRef and tracking. - pub fn from_base_with_data( + pub(crate) fn from_base_with_data( base_obj: PyObjectRef, offset: usize, idx: usize, @@ -568,7 +568,7 @@ impl PyCData { /// /// # Safety /// ptr must point into base_obj's buffer and remain valid as long as base_obj is alive. - pub unsafe fn from_base_obj( + pub(crate) unsafe fn from_base_obj( ptr: *mut u8, size: usize, base_obj: PyObjectRef, @@ -596,7 +596,7 @@ impl PyCData { /// /// # Safety /// ptr must point to valid memory that remains valid as long as source is alive. - pub unsafe fn from_buffer_shared( + pub(crate) unsafe fn from_buffer_shared( ptr: *const u8, size: usize, length: usize, @@ -627,7 +627,7 @@ impl PyCData { /// Validates buffer, creates memoryview, and returns PyCData sharing memory with source. /// /// CDataType_from_buffer_impl - pub fn from_buffer_impl( + pub(crate) fn from_buffer_impl( cls: &Py, source: PyObjectRef, offset: isize, @@ -687,7 +687,7 @@ impl PyCData { /// Copies data from buffer and creates new independent instance. /// /// CDataType_from_buffer_copy_impl - pub fn from_buffer_copy_impl( + pub(crate) fn from_buffer_copy_impl( cls: &Py, source: &[u8], offset: isize, @@ -721,13 +721,13 @@ impl PyCData { } #[inline] - pub fn size(&self) -> usize { + pub(crate) fn size(&self) -> usize { self.buffer.read().len() } /// Check if this buffer is borrowed (external memory reference) #[inline] - pub fn is_borrowed(&self) -> bool { + pub(crate) fn is_borrowed(&self) -> bool { matches!(&*self.buffer.read(), Cow::Borrowed(_)) } @@ -738,7 +738,7 @@ impl PyCData { /// /// # Safety /// For borrowed buffers, caller must ensure the memory is writable. - pub fn write_bytes_at_offset(&self, offset: usize, bytes: &[u8]) { + pub(crate) fn write_bytes_at_offset(&self, offset: usize, bytes: &[u8]) { let buffer = self.buffer.read(); if offset + bytes.len() > buffer.len() { return; // Out of bounds @@ -766,7 +766,7 @@ impl PyCData { /// Generate unique key for nested references (unique_key) /// Creates a hierarchical key by walking up the b_base chain. /// Format: "index:parent_index:grandparent_index:..." - pub fn unique_key(&self, index: usize) -> String { + pub(crate) fn unique_key(&self, index: usize) -> String { let mut key = format!("{index:x}"); // Walk up the base chain to build hierarchical key if self.base.read().is_some() { @@ -785,7 +785,12 @@ impl PyCData { /// /// If this object has a base (is embedded in another structure/union/array), /// the reference is stored in the root object's b_objects with a hierarchical key. - pub fn keep_ref(&self, index: usize, keep: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + pub(crate) fn keep_ref( + &self, + index: usize, + keep: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { // Optimization: no need to store None if vm.is_none(&keep) { return Ok(()); @@ -845,7 +850,7 @@ impl PyCData { /// Walks up to root object (same as keep_ref) so the reference /// lives as long as the owning ctypes object. /// Uses unique_key (hierarchical) so nested fields don't collide. - pub fn keep_alive(&self, index: usize, obj: PyObjectRef) { + pub(crate) fn keep_alive(&self, index: usize, obj: PyObjectRef) { let key = self.unique_key(index); if let Some(base_obj) = self.base.read().clone() { let root = Self::find_root_object(&base_obj); @@ -918,7 +923,7 @@ impl PyCData { /// Get kept objects from a CData instance /// Returns the _objects of the CData, or an empty dict if None. - pub fn get_kept_objects(value: &PyObject, vm: &VirtualMachine) -> PyObjectRef { + pub(crate) fn get_kept_objects(value: &PyObject, vm: &VirtualMachine) -> PyObjectRef { value .downcast_ref::() .and_then(|cdata| cdata.objects.read().clone()) @@ -927,14 +932,14 @@ impl PyCData { /// Check if a value should be stored in _objects /// Returns true for ctypes objects and bytes (for c_char_p) - pub fn should_keep_ref(value: &PyObject) -> bool { + pub(crate) fn should_keep_ref(value: &PyObject) -> bool { value.downcast_ref::().is_some() || value.downcast_ref::().is_some() } /// PyCData_set /// Sets a field value at the given offset, handling type conversion and KeepRef #[allow(clippy::too_many_arguments)] - pub fn set_field( + pub(crate) fn set_field( &self, proto: &PyObject, value: PyObjectRef, @@ -1090,7 +1095,7 @@ impl PyCData { /// PyCData_get /// Gets a field value at the given offset - pub fn get_field( + pub(crate) fn get_field( &self, proto: &PyObject, index: usize, @@ -1332,7 +1337,7 @@ impl PyCData { /// CField descriptor for Structure/Union field access #[pyclass(name = "CField", module = "_ctypes")] #[derive(Debug, PyPayload)] -pub struct PyCField { +pub(crate) struct PyCField { /// Field name pub(crate) name: String, /// Byte offset of the field within the structure/union @@ -1353,7 +1358,7 @@ pub struct PyCField { impl PyCField { /// Create a new CField descriptor (non-bitfield) - pub fn new( + pub(crate) fn new( name: String, proto: PyTypeRef, offset: isize, @@ -1373,7 +1378,7 @@ impl PyCField { } /// Create a new CField descriptor for a bitfield - pub fn new_bitfield( + pub(crate) fn new_bitfield( name: String, proto: PyTypeRef, offset: isize, @@ -1395,13 +1400,17 @@ impl PyCField { } /// Get the byte size of the field's underlying type - pub fn get_byte_size(&self) -> usize { + pub(crate) fn get_byte_size(&self) -> usize { self.byte_size_val as usize } /// Create a new CField from an existing field with adjusted offset and index /// Used by MakeFields to promote anonymous fields - pub fn new_from_field(fdescr: &PyCField, index_offset: usize, offset_delta: isize) -> Self { + pub(crate) fn new_from_field( + fdescr: &PyCField, + index_offset: usize, + offset_delta: isize, + ) -> Self { Self { name: fdescr.name.clone(), offset: fdescr.offset + offset_delta, @@ -1415,7 +1424,7 @@ impl PyCField { } /// Set anonymous flag - pub fn set_anonymous(&mut self, anonymous: bool) { + pub(crate) fn set_anonymous(&mut self, anonymous: bool) { self.anonymous = anonymous; } } @@ -2049,7 +2058,7 @@ fn struct_union_paramfunc( /// Owned FFI argument value. Keeps the value alive for the duration of the FFI call. #[derive(Debug, Clone)] -pub enum FfiArgValue { +pub(crate) enum FfiArgValue { U8(u8), I8(i8), U16(u16), @@ -2067,7 +2076,7 @@ pub enum FfiArgValue { impl FfiArgValue { /// Create an Arg reference to this owned value - pub fn as_arg(&self) -> libffi::middle::Arg<'_> { + pub(crate) fn as_arg(&self) -> libffi::middle::Arg<'_> { match self { FfiArgValue::U8(v) => libffi::middle::Arg::new(v), FfiArgValue::I8(v) => libffi::middle::Arg::new(v), diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 1e8e6309368..f126bb1f09f 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -2233,7 +2233,7 @@ impl Debug for PyCThunk { } impl PyCThunk { - pub fn new( + pub(super) fn new( callable: PyObjectRef, arg_types: Option, res_type: Option, @@ -2302,7 +2302,7 @@ impl PyCThunk { }) } - pub fn code_ptr(&self) -> CodePtr { + pub(super) fn code_ptr(&self) -> CodePtr { self.code_ptr } } diff --git a/crates/vm/src/stdlib/_ctypes/library.rs b/crates/vm/src/stdlib/_ctypes/library.rs index 35ccb433845..c662d32e1df 100644 --- a/crates/vm/src/stdlib/_ctypes/library.rs +++ b/crates/vm/src/stdlib/_ctypes/library.rs @@ -8,7 +8,7 @@ use std::ffi::OsStr; #[cfg(unix)] use libloading::os::unix::Library as UnixLibrary; -pub struct SharedLibrary { +pub(super) struct SharedLibrary { pub(crate) lib: PyMutex>, } @@ -20,18 +20,18 @@ impl fmt::Debug for SharedLibrary { impl SharedLibrary { #[cfg(windows)] - pub fn new(name: impl AsRef) -> Result { - Ok(SharedLibrary { + pub(super) fn new(name: impl AsRef) -> Result { + Ok(Self { lib: PyMutex::new(unsafe { Some(Library::new(name.as_ref())?) }), }) } #[cfg(unix)] - pub fn new_with_mode( + pub(super) fn new_with_mode( name: impl AsRef, mode: i32, - ) -> Result { - Ok(SharedLibrary { + ) -> Result { + Ok(Self { lib: PyMutex::new(Some(unsafe { UnixLibrary::open(Some(name.as_ref()), mode)?.into() })), @@ -40,14 +40,14 @@ impl SharedLibrary { /// Create a SharedLibrary from a raw dlopen handle (for pythonapi / dlopen(NULL)) #[cfg(unix)] - pub fn from_raw_handle(handle: *mut libc::c_void) -> SharedLibrary { + pub(super) fn from_raw_handle(handle: *mut libc::c_void) -> Self { SharedLibrary { lib: PyMutex::new(Some(unsafe { UnixLibrary::from_raw(handle).into() })), } } /// Get the underlying OS handle (HMODULE on Windows, dlopen handle on Unix) - pub fn get_pointer(&self) -> usize { + pub(super) fn get_pointer(&self) -> usize { let lib_lock = self.lib.lock(); if let Some(l) = &*lib_lock { // libloading::Library internally stores the OS handle directly @@ -77,12 +77,12 @@ impl ExternalLibs { } } - pub fn get_lib(&self, key: usize) -> Option<&SharedLibrary> { + pub(super) fn get_lib(&self, key: usize) -> Option<&SharedLibrary> { self.libraries.get(&key) } #[cfg(windows)] - pub fn get_or_insert_lib( + pub(super) fn get_or_insert_lib( &mut self, library_path: impl AsRef, _vm: &VirtualMachine, @@ -105,7 +105,7 @@ impl ExternalLibs { } #[cfg(unix)] - pub fn get_or_insert_lib_with_mode( + pub(super) fn get_or_insert_lib_with_mode( &mut self, library_path: impl AsRef, mode: i32, @@ -130,14 +130,14 @@ impl ExternalLibs { /// Insert a raw dlopen handle into the cache (for pythonapi / dlopen(NULL)) #[cfg(unix)] - pub fn insert_raw_handle(&mut self, handle: *mut libc::c_void) -> usize { + pub(super) fn insert_raw_handle(&mut self, handle: *mut libc::c_void) -> usize { let shared_lib = SharedLibrary::from_raw_handle(handle); let key = handle as usize; self.libraries.insert(key, shared_lib); key } - pub fn drop_lib(&mut self, key: usize) { + pub(super) fn drop_lib(&mut self, key: usize) { self.libraries.remove(&key); } } diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index bc71bd2caf0..1e704a1e4ad 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -249,7 +249,7 @@ impl AsNumber for PyCPointerType { )] #[derive(Debug)] #[repr(transparent)] -pub struct PyCPointer(pub PyCData); +pub(crate) struct PyCPointer(pub PyCData); impl Constructor for PyCPointer { type Args = FuncArgs; @@ -296,13 +296,13 @@ impl Initializer for PyCPointer { )] impl PyCPointer { /// Get the pointer value stored in buffer as usize - pub fn get_ptr_value(&self) -> usize { + pub(crate) fn get_ptr_value(&self) -> usize { let buffer = self.0.buffer.read(); super::base::read_ptr_from_buffer(&buffer) } /// Set the pointer value in buffer - pub fn set_ptr_value(&self, value: usize) { + pub(crate) fn set_ptr_value(&self, value: usize) { let mut buffer = self.0.buffer.write(); let bytes = value.to_ne_bytes(); if buffer.len() >= bytes.len() { diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index 6d78a1704a1..93c29da55df 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -235,7 +235,7 @@ fn set_primitive(_type_: &str, value: &PyObject, vm: &VirtualMachine) -> PyResul #[pyclass(module = "_ctypes", name = "PyCSimpleType", base = PyType)] #[derive(Debug)] #[repr(transparent)] -pub struct PyCSimpleType(PyType); +pub(crate) struct PyCSimpleType(PyType); #[pyclass(flags(BASETYPE), with(AsNumber, Initializer))] impl PyCSimpleType { @@ -713,7 +713,7 @@ fn create_swapped_types( metaclass = "PyCSimpleType" )] #[repr(transparent)] -pub struct PyCSimple(pub PyCData); +pub(crate) struct PyCSimple(pub PyCData); impl Debug for PyCSimple { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { @@ -1140,7 +1140,7 @@ impl PyCSimple { } #[pygetset] - pub fn value(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult { + pub(crate) fn value(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult { let zelf: &Py = instance .downcast_ref() .ok_or_else(|| vm.new_type_error("cannot get value of instance"))?; @@ -1363,7 +1363,7 @@ impl PyCSimple { impl PyCSimple { /// Extract the value from this ctypes object as an owned FfiArgValue. /// The value must be kept alive until after the FFI call completes. - pub fn to_ffi_value( + pub(crate) fn to_ffi_value( &self, ty: libffi::middle::Type, _vm: &VirtualMachine, diff --git a/crates/vm/src/stdlib/_ctypes/structure.rs b/crates/vm/src/stdlib/_ctypes/structure.rs index 059b7a6b523..a12edf52524 100644 --- a/crates/vm/src/stdlib/_ctypes/structure.rs +++ b/crates/vm/src/stdlib/_ctypes/structure.rs @@ -667,7 +667,7 @@ impl SetAttr for PyCStructType { metaclass = "PyCStructType" )] #[repr(transparent)] -pub struct PyCStructure(pub PyCData); +pub(crate) struct PyCStructure(pub PyCData); impl Debug for PyCStructure { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { diff --git a/crates/vm/src/stdlib/_ctypes/union.rs b/crates/vm/src/stdlib/_ctypes/union.rs index 0ac5f64bd21..1eb8403f24f 100644 --- a/crates/vm/src/stdlib/_ctypes/union.rs +++ b/crates/vm/src/stdlib/_ctypes/union.rs @@ -536,7 +536,7 @@ impl SetAttr for PyCUnionType { /// PyCUnion - base class for Union #[pyclass(module = "_ctypes", name = "Union", base = PyCData, metaclass = "PyCUnionType")] #[repr(transparent)] -pub struct PyCUnion(pub PyCData); +pub(crate) struct PyCUnion(pub PyCData); impl core::fmt::Debug for PyCUnion { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { diff --git a/crates/vm/src/stdlib/_functools.rs b/crates/vm/src/stdlib/_functools.rs index 110fca67590..7e648bae259 100644 --- a/crates/vm/src/stdlib/_functools.rs +++ b/crates/vm/src/stdlib/_functools.rs @@ -74,7 +74,7 @@ mod _functools { #[pyattr] #[pyclass(name = "_PlaceholderType", module = "functools")] #[derive(Debug, PyPayload)] - pub struct PyPlaceholderType; + pub(super) struct PyPlaceholderType; impl Constructor for PyPlaceholderType { type Args = FuncArgs; @@ -128,7 +128,7 @@ mod _functools { #[pyattr] #[pyclass(name = "partial", module = "functools")] #[derive(Debug, PyPayload)] - pub struct PyPartial { + pub(super) struct PyPartial { inner: PyRwLock, } diff --git a/crates/vm/src/stdlib/_imp.rs b/crates/vm/src/stdlib/_imp.rs index 71a8c091e5e..23a68572cb4 100644 --- a/crates/vm/src/stdlib/_imp.rs +++ b/crates/vm/src/stdlib/_imp.rs @@ -5,7 +5,7 @@ use core::borrow::Borrow; pub(crate) use _imp::module_def; -pub use crate::vm::resolve_frozen_alias; +pub(super) use crate::vm::resolve_frozen_alias; #[cfg(feature = "threading")] #[pymodule(sub)] diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index 96095f565f5..a97929ef973 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -193,7 +193,10 @@ mod _io { result.map(Some) } - pub fn new_unsupported_operation(vm: &VirtualMachine, msg: String) -> PyBaseExceptionRef { + pub(super) fn new_unsupported_operation( + vm: &VirtualMachine, + msg: String, + ) -> PyBaseExceptionRef { vm.new_os_subtype_error(unsupported_operation().to_owned(), None, msg) .upcast() } @@ -215,11 +218,11 @@ mod _io { impl OptionalSize { #[allow(clippy::wrong_self_convention)] - pub fn to_usize(self) -> Option { + pub(super) fn to_usize(self) -> Option { self.size?.to_usize() } - pub fn try_usize(self, vm: &VirtualMachine) -> PyResult> { + pub(super) fn try_usize(self, vm: &VirtualMachine) -> PyResult> { self.size .map(|v| { let v = *v; @@ -406,7 +409,7 @@ mod _io { #[pyattr] #[pyclass(name = "_IOBase")] #[derive(Debug, Default, PyPayload)] - pub struct _IOBase; + pub(super) struct _IOBase; #[pyclass( with(IterNext, Iterable, Destructor), @@ -1526,7 +1529,7 @@ mod _io { } } - pub fn get_offset(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + pub(super) fn get_offset(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let int = obj.try_index(vm)?; int.as_bigint().try_into().map_err(|_| { vm.new_value_error(format!( @@ -1536,7 +1539,10 @@ mod _io { }) } - pub fn repr_file_obj_name(obj: &PyObject, vm: &VirtualMachine) -> PyResult> { + pub(super) fn repr_file_obj_name( + obj: &PyObject, + vm: &VirtualMachine, + ) -> PyResult> { let name = match obj.get_attr("name", vm) { Ok(name) => Some(name), Err(e) @@ -4998,7 +5004,7 @@ mod _io { /// Must only be called from the single-threaded child process immediately /// after `fork()`, before any other thread is created. #[cfg(all(unix, feature = "threading"))] - pub unsafe fn reinit_std_streams_after_fork(vm: &VirtualMachine) { + pub(crate) unsafe fn reinit_std_streams_after_fork(vm: &VirtualMachine) { for name in ["stdin", "stdout", "stderr"] { let Ok(stream) = vm.sys_module.get_attr(name, vm) else { continue; @@ -5222,7 +5228,7 @@ mod _io { .unwrap() } - pub fn unsupported_operation() -> &'static Py { + pub(super) fn unsupported_operation() -> &'static Py { rustpython_common::static_cell! { static CELL: PyTypeRef; } @@ -5459,7 +5465,7 @@ mod fileio { } #[derive(FromArgs)] - pub struct FileIOArgs { + pub(super) struct FileIOArgs { #[pyarg(positional)] name: PyObjectRef, #[pyarg(any, default)] @@ -6175,7 +6181,7 @@ mod winconsoleio { impl DefaultConstructor for WindowsConsoleIO {} #[derive(FromArgs)] - pub struct WindowsConsoleIOArgs { + pub(super) struct WindowsConsoleIOArgs { #[pyarg(positional)] name: PyObjectRef, #[pyarg(any, default)] diff --git a/crates/vm/src/stdlib/_signal.rs b/crates/vm/src/stdlib/_signal.rs index e80386a670a..dedbb9ee0fa 100644 --- a/crates/vm/src/stdlib/_signal.rs +++ b/crates/vm/src/stdlib/_signal.rs @@ -57,13 +57,14 @@ pub(crate) mod _signal { } #[cfg(unix)] - pub use libc::SIG_ERR; + pub(crate) use libc::SIG_ERR; + #[cfg(unix)] - pub use nix::unistd::alarm as sig_alarm; + pub(crate) use nix::unistd::alarm as sig_alarm; #[cfg(unix)] #[pyattr] - pub use libc::{SIG_DFL, SIG_IGN}; + pub(crate) use libc::{SIG_DFL, SIG_IGN}; // pthread_sigmask 'how' constants #[cfg(unix)] @@ -72,13 +73,15 @@ pub(crate) mod _signal { #[cfg(not(unix))] #[pyattr] - pub const SIG_DFL: sighandler_t = 0; + pub(crate) const SIG_DFL: sighandler_t = 0; + #[cfg(not(unix))] #[pyattr] - pub const SIG_IGN: sighandler_t = 1; + pub(crate) const SIG_IGN: sighandler_t = 1; + #[cfg(not(unix))] #[allow(dead_code)] - pub const SIG_ERR: sighandler_t = -1 as _; + pub(crate) const SIG_ERR: sighandler_t = -1 as _; #[cfg(all(unix, not(target_os = "redox")))] unsafe extern "C" { @@ -88,8 +91,11 @@ pub(crate) mod _signal { #[cfg(any(target_os = "linux", target_os = "android"))] mod ffi { unsafe extern "C" { - pub fn getitimer(which: libc::c_int, curr_value: *mut libc::itimerval) -> libc::c_int; - pub fn setitimer( + pub(super) fn getitimer( + which: libc::c_int, + curr_value: *mut libc::itimerval, + ) -> libc::c_int; + pub(super) fn setitimer( which: libc::c_int, new_value: *const libc::itimerval, old_value: *mut libc::itimerval, @@ -102,7 +108,7 @@ pub(crate) mod _signal { #[cfg(any(unix, windows))] #[pyattr] - pub use libc::{SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM}; + pub(crate) use libc::{SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM}; #[cfg(windows)] #[pyattr] @@ -204,7 +210,7 @@ pub(crate) mod _signal { #[cfg(any(unix, windows))] #[pyfunction] - pub fn signal( + pub(crate) fn signal( signalnum: i32, handler: PyObjectRef, vm: &VirtualMachine, @@ -660,7 +666,7 @@ pub(crate) mod _signal { } #[cfg(any(unix, windows))] - pub extern "C" fn run_signal(signum: i32) { + pub(crate) extern "C" fn run_signal(signum: i32) { signal::TRIGGERS[signum as usize].store(true, Ordering::Relaxed); signal::set_triggered(); #[cfg(windows)] diff --git a/crates/vm/src/stdlib/_sre.rs b/crates/vm/src/stdlib/_sre.rs index 2aac4bd92cc..64cf8fe23a0 100644 --- a/crates/vm/src/stdlib/_sre.rs +++ b/crates/vm/src/stdlib/_sre.rs @@ -27,7 +27,7 @@ mod _sre { }; #[pyattr] - pub use rustpython_sre_engine::{CODESIZE, MAXGROUPS, MAXREPEAT, SRE_MAGIC as MAGIC}; + pub(super) use rustpython_sre_engine::{CODESIZE, MAXGROUPS, MAXREPEAT, SRE_MAGIC as MAGIC}; #[pyfunction] const fn getcodesize() -> usize { diff --git a/crates/vm/src/stdlib/_stat.rs b/crates/vm/src/stdlib/_stat.rs index 44b55628d6f..8809c1d0bf8 100644 --- a/crates/vm/src/stdlib/_stat.rs +++ b/crates/vm/src/stdlib/_stat.rs @@ -25,65 +25,65 @@ mod _stat { } #[pyattr] - pub const S_IFDIR: Mode = libc_const!( + pub(super) const S_IFDIR: Mode = libc_const!( #[cfg(unix)] S_IFDIR, 0o040000 ); #[pyattr] - pub const S_IFCHR: Mode = libc_const!( + pub(super) const S_IFCHR: Mode = libc_const!( #[cfg(unix)] S_IFCHR, 0o020000 ); #[pyattr] - pub const S_IFBLK: Mode = libc_const!( + pub(super) const S_IFBLK: Mode = libc_const!( #[cfg(unix)] S_IFBLK, 0o060000 ); #[pyattr] - pub const S_IFREG: Mode = libc_const!( + pub(super) const S_IFREG: Mode = libc_const!( #[cfg(unix)] S_IFREG, 0o100000 ); #[pyattr] - pub const S_IFIFO: Mode = libc_const!( + pub(super) const S_IFIFO: Mode = libc_const!( #[cfg(unix)] S_IFIFO, 0o010000 ); #[pyattr] - pub const S_IFLNK: Mode = libc_const!( + pub(super) const S_IFLNK: Mode = libc_const!( #[cfg(unix)] S_IFLNK, 0o120000 ); #[pyattr] - pub const S_IFSOCK: Mode = libc_const!( + pub(super) const S_IFSOCK: Mode = libc_const!( #[cfg(unix)] S_IFSOCK, 0o140000 ); #[pyattr] - pub const S_IFDOOR: Mode = 0; // TODO: RUSTPYTHON Support Solaris + pub(super) const S_IFDOOR: Mode = 0; // TODO: RUSTPYTHON Support Solaris #[pyattr] - pub const S_IFPORT: Mode = 0; // TODO: RUSTPYTHON Support Solaris + pub(super) const S_IFPORT: Mode = 0; // TODO: RUSTPYTHON Support Solaris // TODO: RUSTPYTHON Support BSD // https://man.freebsd.org/cgi/man.cgi?stat(2) #[pyattr] - pub const S_IFWHT: Mode = if cfg!(target_os = "macos") { + pub(super) const S_IFWHT: Mode = if cfg!(target_os = "macos") { 0o160000 } else { 0 @@ -92,133 +92,133 @@ mod _stat { // Permission bits #[pyattr] - pub const S_ISUID: Mode = libc_const!( + pub(super) const S_ISUID: Mode = libc_const!( #[cfg(unix)] S_ISUID, 0o4000 ); #[pyattr] - pub const S_ISGID: Mode = libc_const!( + pub(super) const S_ISGID: Mode = libc_const!( #[cfg(unix)] S_ISGID, 0o2000 ); #[pyattr] - pub const S_ENFMT: Mode = libc_const!( + pub(super) const S_ENFMT: Mode = libc_const!( #[cfg(unix)] S_ISGID, 0o2000 ); #[pyattr] - pub const S_ISVTX: Mode = libc_const!( + pub(super) const S_ISVTX: Mode = libc_const!( #[cfg(unix)] S_ISVTX, 0o1000 ); #[pyattr] - pub const S_IRWXU: Mode = libc_const!( + pub(super) const S_IRWXU: Mode = libc_const!( #[cfg(unix)] S_IRWXU, 0o0700 ); #[pyattr] - pub const S_IRUSR: Mode = libc_const!( + pub(super) const S_IRUSR: Mode = libc_const!( #[cfg(unix)] S_IRUSR, 0o0400 ); #[pyattr] - pub const S_IREAD: Mode = libc_const!( + pub(super) const S_IREAD: Mode = libc_const!( #[cfg(unix)] S_IRUSR, 0o0400 ); #[pyattr] - pub const S_IWUSR: Mode = libc_const!( + pub(super) const S_IWUSR: Mode = libc_const!( #[cfg(unix)] S_IWUSR, 0o0200 ); #[pyattr] - pub const S_IXUSR: Mode = libc_const!( + pub(super) const S_IXUSR: Mode = libc_const!( #[cfg(unix)] S_IXUSR, 0o0100 ); #[pyattr] - pub const S_IRWXG: Mode = libc_const!( + pub(super) const S_IRWXG: Mode = libc_const!( #[cfg(unix)] S_IRWXG, 0o0070 ); #[pyattr] - pub const S_IRGRP: Mode = libc_const!( + pub(super) const S_IRGRP: Mode = libc_const!( #[cfg(unix)] S_IRGRP, 0o0040 ); #[pyattr] - pub const S_IWGRP: Mode = libc_const!( + pub(super) const S_IWGRP: Mode = libc_const!( #[cfg(unix)] S_IWGRP, 0o0020 ); #[pyattr] - pub const S_IXGRP: Mode = libc_const!( + pub(super) const S_IXGRP: Mode = libc_const!( #[cfg(unix)] S_IXGRP, 0o0010 ); #[pyattr] - pub const S_IRWXO: Mode = libc_const!( + pub(super) const S_IRWXO: Mode = libc_const!( #[cfg(unix)] S_IRWXO, 0o0007 ); #[pyattr] - pub const S_IROTH: Mode = libc_const!( + pub(super) const S_IROTH: Mode = libc_const!( #[cfg(unix)] S_IROTH, 0o0004 ); #[pyattr] - pub const S_IWOTH: Mode = libc_const!( + pub(super) const S_IWOTH: Mode = libc_const!( #[cfg(unix)] S_IWOTH, 0o0002 ); #[pyattr] - pub const S_IXOTH: Mode = libc_const!( + pub(super) const S_IXOTH: Mode = libc_const!( #[cfg(unix)] S_IXOTH, 0o0001 ); #[pyattr] - pub const S_IWRITE: Mode = libc_const!( + pub(super) const S_IWRITE: Mode = libc_const!( #[cfg(all(unix, not(target_os = "android"), not(target_os = "redox")))] S_IWRITE, 0o0200 ); #[pyattr] - pub const S_IEXEC: Mode = libc_const!( + pub(super) const S_IEXEC: Mode = libc_const!( #[cfg(all(unix, not(target_os = "android"), not(target_os = "redox")))] S_IEXEC, 0o0100 @@ -228,7 +228,7 @@ mod _stat { #[cfg(windows)] #[pyattr] - pub use windows_sys::Win32::Storage::FileSystem::{ + pub(super) use windows_sys::Win32::Storage::FileSystem::{ FILE_ATTRIBUTE_ARCHIVE, FILE_ATTRIBUTE_COMPRESSED, FILE_ATTRIBUTE_DEVICE, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_ENCRYPTED, FILE_ATTRIBUTE_HIDDEN, FILE_ATTRIBUTE_INTEGRITY_STREAM, FILE_ATTRIBUTE_NO_SCRUB_DATA, FILE_ATTRIBUTE_NORMAL, @@ -240,142 +240,144 @@ mod _stat { // Windows reparse point tags #[cfg(windows)] #[pyattr] - pub const IO_REPARSE_TAG_SYMLINK: u32 = 0xA000000C; + pub(super) const IO_REPARSE_TAG_SYMLINK: u32 = 0xA000000C; + #[cfg(windows)] #[pyattr] - pub const IO_REPARSE_TAG_MOUNT_POINT: u32 = 0xA0000003; + pub(super) const IO_REPARSE_TAG_MOUNT_POINT: u32 = 0xA0000003; + #[cfg(windows)] #[pyattr] - pub const IO_REPARSE_TAG_APPEXECLINK: u32 = 0x8000001B; + pub(super) const IO_REPARSE_TAG_APPEXECLINK: u32 = 0x8000001B; // Unix file flags (if on Unix) #[pyattr] - pub const UF_NODUMP: u32 = libc_const!( + pub(super) const UF_NODUMP: u32 = libc_const!( #[cfg(target_os = "macos")] UF_NODUMP, 0x00000001 ); #[pyattr] - pub const UF_IMMUTABLE: u32 = libc_const!( + pub(super) const UF_IMMUTABLE: u32 = libc_const!( #[cfg(target_os = "macos")] UF_IMMUTABLE, 0x00000002 ); #[pyattr] - pub const UF_APPEND: u32 = libc_const!( + pub(super) const UF_APPEND: u32 = libc_const!( #[cfg(target_os = "macos")] UF_APPEND, 0x00000004 ); #[pyattr] - pub const UF_OPAQUE: u32 = libc_const!( + pub(super) const UF_OPAQUE: u32 = libc_const!( #[cfg(target_os = "macos")] UF_OPAQUE, 0x00000008 ); #[pyattr] - pub const UF_COMPRESSED: u32 = libc_const!( + pub(super) const UF_COMPRESSED: u32 = libc_const!( #[cfg(target_os = "macos")] UF_COMPRESSED, 0x00000020 ); #[pyattr] - pub const UF_HIDDEN: u32 = libc_const!( + pub(super) const UF_HIDDEN: u32 = libc_const!( #[cfg(target_os = "macos")] UF_HIDDEN, 0x00008000 ); #[pyattr] - pub const SF_ARCHIVED: u32 = libc_const!( + pub(super) const SF_ARCHIVED: u32 = libc_const!( #[cfg(target_os = "macos")] SF_ARCHIVED, 0x00010000 ); #[pyattr] - pub const SF_IMMUTABLE: u32 = libc_const!( + pub(super) const SF_IMMUTABLE: u32 = libc_const!( #[cfg(target_os = "macos")] SF_IMMUTABLE, 0x00020000 ); #[pyattr] - pub const SF_APPEND: u32 = libc_const!( + pub(super) const SF_APPEND: u32 = libc_const!( #[cfg(target_os = "macos")] SF_APPEND, 0x00040000 ); #[pyattr] - pub const SF_SETTABLE: u32 = if cfg!(target_os = "macos") { + pub(super) const SF_SETTABLE: u32 = if cfg!(target_os = "macos") { 0x3fff0000 } else { 0xffff0000 }; #[pyattr] - pub const UF_NOUNLINK: u32 = 0x00000010; + pub(super) const UF_NOUNLINK: u32 = 0x00000010; #[pyattr] - pub const SF_NOUNLINK: u32 = 0x00100000; + pub(super) const SF_NOUNLINK: u32 = 0x00100000; #[pyattr] - pub const SF_SNAPSHOT: u32 = 0x00200000; + pub(super) const SF_SNAPSHOT: u32 = 0x00200000; #[pyattr] - pub const SF_FIRMLINK: u32 = 0x00800000; + pub(super) const SF_FIRMLINK: u32 = 0x00800000; #[pyattr] - pub const SF_DATALESS: u32 = 0x40000000; + pub(super) const SF_DATALESS: u32 = 0x40000000; // MacOS specific #[cfg(target_os = "macos")] #[pyattr] - pub const SF_SUPPORTED: u32 = 0x009f0000; + pub(super) const SF_SUPPORTED: u32 = 0x009f0000; #[cfg(target_os = "macos")] #[pyattr] - pub const SF_SYNTHETIC: u32 = 0xc0000000; + pub(super) const SF_SYNTHETIC: u32 = 0xc0000000; // Stat result indices #[pyattr] - pub const ST_MODE: u32 = 0; + pub(super) const ST_MODE: u32 = 0; #[pyattr] - pub const ST_INO: u32 = 1; + pub(super) const ST_INO: u32 = 1; #[pyattr] - pub const ST_DEV: u32 = 2; + pub(super) const ST_DEV: u32 = 2; #[pyattr] - pub const ST_NLINK: u32 = 3; + pub(super) const ST_NLINK: u32 = 3; #[pyattr] - pub const ST_UID: u32 = 4; + pub(super) const ST_UID: u32 = 4; #[pyattr] - pub const ST_GID: u32 = 5; + pub(super) const ST_GID: u32 = 5; #[pyattr] - pub const ST_SIZE: u32 = 6; + pub(super) const ST_SIZE: u32 = 6; #[pyattr] - pub const ST_ATIME: u32 = 7; + pub(super) const ST_ATIME: u32 = 7; #[pyattr] - pub const ST_MTIME: u32 = 8; + pub(super) const ST_MTIME: u32 = 8; #[pyattr] - pub const ST_CTIME: u32 = 9; + pub(super) const ST_CTIME: u32 = 9; const S_IFMT: Mode = 0o170000; diff --git a/crates/vm/src/stdlib/_symtable.rs b/crates/vm/src/stdlib/_symtable.rs index f1d571a8318..9b3c38c93e8 100644 --- a/crates/vm/src/stdlib/_symtable.rs +++ b/crates/vm/src/stdlib/_symtable.rs @@ -17,97 +17,97 @@ mod _symtable { // https://github.com/python/cpython/blob/6cb20a219a860eaf687b2d968b41c480c7461909/Include/internal/pycore_symtable.h#L156 #[pyattr] - pub const DEF_GLOBAL: i32 = 1; + pub(super) const DEF_GLOBAL: i32 = 1; #[pyattr] - pub const DEF_LOCAL: i32 = 2; + pub(super) const DEF_LOCAL: i32 = 2; #[pyattr] - pub const DEF_PARAM: i32 = 2 << 1; + pub(super) const DEF_PARAM: i32 = 2 << 1; #[pyattr] - pub const DEF_NONLOCAL: i32 = 2 << 2; + pub(super) const DEF_NONLOCAL: i32 = 2 << 2; #[pyattr] - pub const USE: i32 = 2 << 3; + pub(super) const USE: i32 = 2 << 3; #[pyattr] - pub const DEF_FREE: i32 = 2 << 4; + pub(super) const DEF_FREE: i32 = 2 << 4; #[pyattr] - pub const DEF_FREE_CLASS: i32 = 2 << 5; + pub(super) const DEF_FREE_CLASS: i32 = 2 << 5; #[pyattr] - pub const DEF_IMPORT: i32 = 2 << 6; + pub(super) const DEF_IMPORT: i32 = 2 << 6; #[pyattr] - pub const DEF_ANNOT: i32 = 2 << 7; + pub(super) const DEF_ANNOT: i32 = 2 << 7; #[pyattr] - pub const DEF_COMP_ITER: i32 = 2 << 8; + pub(super) const DEF_COMP_ITER: i32 = 2 << 8; #[pyattr] - pub const DEF_TYPE_PARAM: i32 = 2 << 9; + pub(super) const DEF_TYPE_PARAM: i32 = 2 << 9; #[pyattr] - pub const DEF_COMP_CELL: i32 = 2 << 10; + pub(super) const DEF_COMP_CELL: i32 = 2 << 10; #[pyattr] - pub const DEF_BOUND: i32 = DEF_LOCAL | DEF_PARAM | DEF_IMPORT; + pub(super) const DEF_BOUND: i32 = DEF_LOCAL | DEF_PARAM | DEF_IMPORT; #[pyattr] - pub const SCOPE_OFFSET: i32 = 12; + pub(super) const SCOPE_OFFSET: i32 = 12; #[pyattr] - pub const SCOPE_MASK: i32 = DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL; + pub(super) const SCOPE_MASK: i32 = DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL; #[pyattr] - pub const LOCAL: i32 = 1; + pub(super) const LOCAL: i32 = 1; #[pyattr] - pub const GLOBAL_EXPLICIT: i32 = 2; + pub(super) const GLOBAL_EXPLICIT: i32 = 2; #[pyattr] - pub const GLOBAL_IMPLICIT: i32 = 3; + pub(super) const GLOBAL_IMPLICIT: i32 = 3; #[pyattr] - pub const FREE: i32 = 4; + pub(super) const FREE: i32 = 4; #[pyattr] - pub const CELL: i32 = 5; + pub(super) const CELL: i32 = 5; #[pyattr] - pub const GENERATOR: i32 = 1; + pub(super) const GENERATOR: i32 = 1; #[pyattr] - pub const GENERATOR_EXPRESSION: i32 = 2; + pub(super) const GENERATOR_EXPRESSION: i32 = 2; #[pyattr] - pub const SCOPE_OFF: i32 = SCOPE_OFFSET; + pub(super) const SCOPE_OFF: i32 = SCOPE_OFFSET; #[pyattr] - pub const TYPE_FUNCTION: i32 = 0; + pub(super) const TYPE_FUNCTION: i32 = 0; #[pyattr] - pub const TYPE_CLASS: i32 = 1; + pub(super) const TYPE_CLASS: i32 = 1; #[pyattr] - pub const TYPE_MODULE: i32 = 2; + pub(super) const TYPE_MODULE: i32 = 2; #[pyattr] - pub const TYPE_ANNOTATION: i32 = 3; + pub(super) const TYPE_ANNOTATION: i32 = 3; #[pyattr] - pub const TYPE_TYPE_VAR_BOUND: i32 = 4; + pub(super) const TYPE_TYPE_VAR_BOUND: i32 = 4; #[pyattr] - pub const TYPE_TYPE_ALIAS: i32 = 5; + pub(super) const TYPE_TYPE_ALIAS: i32 = 5; #[pyattr] - pub const TYPE_TYPE_PARAMETERS: i32 = 6; + pub(super) const TYPE_TYPE_PARAMETERS: i32 = 6; #[pyattr] - pub const TYPE_TYPE_VARIABLE: i32 = 7; + pub(super) const TYPE_TYPE_VARIABLE: i32 = 7; #[pyfunction] fn symtable( diff --git a/crates/vm/src/stdlib/_thread.rs b/crates/vm/src/stdlib/_thread.rs index 48e5a4a0823..eccb9ad1bde 100644 --- a/crates/vm/src/stdlib/_thread.rs +++ b/crates/vm/src/stdlib/_thread.rs @@ -31,7 +31,7 @@ pub(crate) mod _thread { use std::thread; // PYTHREAD_NAME: show current thread name - pub const PYTHREAD_NAME: Option<&str> = cfg_select! { + pub(crate) const PYTHREAD_NAME: Option<&str> = cfg_select! { windows => Some("nt"), unix => Some("pthread"), any(target_os = "solaris", target_os = "illumos") => Some("solaris"), @@ -170,7 +170,7 @@ pub(crate) mod _thread { } } - pub type RawRMutex = RawReentrantMutex; + pub(crate) type RawRMutex = RawReentrantMutex; #[pyattr] #[pyclass(module = "_thread", name = "RLock")] #[derive(PyPayload)] @@ -642,7 +642,7 @@ pub(crate) mod _thread { } // Registry for non-daemon threads that need to be joined at shutdown - pub type ShutdownEntry = ( + pub(crate) type ShutdownEntry = ( Weak>, Weak<(parking_lot::Mutex, parking_lot::Condvar)>, ); @@ -749,7 +749,7 @@ pub(crate) mod _thread { } /// Initialize the main thread ident. Should be called once at interpreter startup. - pub fn init_main_thread_ident(vm: &VirtualMachine) { + pub(crate) fn init_main_thread_ident(vm: &VirtualMachine) { let ident = get_ident(); vm.state.main_thread_ident.store(ident); } @@ -1026,16 +1026,16 @@ pub(crate) mod _thread { // Registry of all ThreadHandles for fork cleanup // Stores weak references so handles can be garbage collected normally - pub type HandleEntry = ( + pub(crate) type HandleEntry = ( Weak>, Weak<(parking_lot::Mutex, parking_lot::Condvar)>, ); // Re-export type from vm::thread for PyGlobalState - pub use crate::vm::thread::CurrentFrameSlot; + pub(crate) use crate::vm::thread::CurrentFrameSlot; /// Get all threads' current (top) frames. Used by sys._current_frames(). - pub fn get_all_current_frames(vm: &VirtualMachine) -> Vec<(u64, FrameRef)> { + pub(crate) fn get_all_current_frames(vm: &VirtualMachine) -> Vec<(u64, FrameRef)> { let registry = vm.state.thread_frames.lock(); registry .iter() @@ -1056,7 +1056,7 @@ pub(crate) mod _thread { /// Precondition: `reinit_locks_after_fork()` has already been called, so all /// parking_lot-based locks in VmState are in unlocked state. #[cfg(unix)] - pub fn after_fork_child(vm: &VirtualMachine) { + pub(crate) fn after_fork_child(vm: &VirtualMachine) { let current_ident = get_ident(); // Update main thread ident - after fork, the current thread becomes the main thread diff --git a/crates/vm/src/stdlib/_typing.rs b/crates/vm/src/stdlib/_typing.rs index 7467a7f2574..70554037d46 100644 --- a/crates/vm/src/stdlib/_typing.rs +++ b/crates/vm/src/stdlib/_typing.rs @@ -206,7 +206,11 @@ pub(crate) mod decl { )] impl TypeAliasType { /// Create from intrinsic: compute_value is a callable that returns the value - pub fn new(name: PyStrRef, type_params: PyTupleRef, compute_value: PyObjectRef) -> Self { + pub(crate) fn new( + name: PyStrRef, + type_params: PyTupleRef, + compute_value: PyObjectRef, + ) -> Self { Self { name, type_params, diff --git a/crates/vm/src/stdlib/_wmi.rs b/crates/vm/src/stdlib/_wmi.rs index 96275e5ac4b..927e68ce0c1 100644 --- a/crates/vm/src/stdlib/_wmi.rs +++ b/crates/vm/src/stdlib/_wmi.rs @@ -8,28 +8,28 @@ mod wmi_ffi { #![allow(unsafe_op_in_unsafe_fn)] use core::ffi::c_void; - pub type HRESULT = i32; + pub(super) type HRESULT = i32; #[repr(C)] - pub struct GUID { - pub data1: u32, - pub data2: u16, - pub data3: u16, - pub data4: [u8; 8], + pub(super) struct GUID { + pub(super) data1: u32, + pub(super) data2: u16, + pub(super) data3: u16, + pub(super) data4: [u8; 8], } // Opaque VARIANT type (24 bytes covers both 32-bit and 64-bit) #[repr(C, align(8))] - pub struct VARIANT([u64; 3]); + pub(super) struct VARIANT([u64; 3]); impl VARIANT { - pub fn zeroed() -> Self { + pub(super) fn zeroed() -> Self { VARIANT([0u64; 3]) } } // CLSID_WbemLocator = {4590F811-1D3A-11D0-891F-00AA004B2E24} - pub const CLSID_WBEM_LOCATOR: GUID = GUID { + pub(super) const CLSID_WBEM_LOCATOR: GUID = GUID { data1: 0x4590F811, data2: 0x1D3A, data3: 0x11D0, @@ -37,7 +37,7 @@ mod wmi_ffi { }; // IID_IWbemLocator = {DC12A687-737F-11CF-884D-00AA004B2E24} - pub const IID_IWBEM_LOCATOR: GUID = GUID { + pub(super) const IID_IWBEM_LOCATOR: GUID = GUID { data1: 0xDC12A687, data2: 0x737F, data3: 0x11CF, @@ -45,30 +45,32 @@ mod wmi_ffi { }; // COM constants - pub const COINIT_APARTMENTTHREADED: u32 = 0x2; - pub const CLSCTX_INPROC_SERVER: u32 = 0x1; - pub const RPC_C_AUTHN_LEVEL_DEFAULT: u32 = 0; - pub const RPC_C_IMP_LEVEL_IMPERSONATE: u32 = 3; - pub const RPC_C_AUTHN_LEVEL_CALL: u32 = 3; - pub const RPC_C_AUTHN_WINNT: u32 = 10; - pub const RPC_C_AUTHZ_NONE: u32 = 0; - pub const EOAC_NONE: u32 = 0; - pub const RPC_E_TOO_LATE: HRESULT = 0x80010119_u32 as i32; + pub(super) const COINIT_APARTMENTTHREADED: u32 = 0x2; + pub(super) const CLSCTX_INPROC_SERVER: u32 = 0x1; + pub(super) const RPC_C_AUTHN_LEVEL_DEFAULT: u32 = 0; + pub(super) const RPC_C_IMP_LEVEL_IMPERSONATE: u32 = 3; + pub(super) const RPC_C_AUTHN_LEVEL_CALL: u32 = 3; + pub(super) const RPC_C_AUTHN_WINNT: u32 = 10; + pub(super) const RPC_C_AUTHZ_NONE: u32 = 0; + pub(super) const EOAC_NONE: u32 = 0; + pub(super) const RPC_E_TOO_LATE: HRESULT = 0x80010119_u32 as i32; // WMI constants - pub const WBEM_FLAG_FORWARD_ONLY: i32 = 0x20; - pub const WBEM_FLAG_RETURN_IMMEDIATELY: i32 = 0x10; - pub const WBEM_S_FALSE: HRESULT = 1; - pub const WBEM_S_NO_MORE_DATA: HRESULT = 0x40005; - pub const WBEM_INFINITE: i32 = -1; - pub const WBEM_FLAVOR_MASK_ORIGIN: i32 = 0x60; - pub const WBEM_FLAVOR_ORIGIN_SYSTEM: i32 = 0x40; + pub(super) const WBEM_FLAG_FORWARD_ONLY: i32 = 0x20; + pub(super) const WBEM_FLAG_RETURN_IMMEDIATELY: i32 = 0x10; + pub(super) const WBEM_S_FALSE: HRESULT = 1; + pub(super) const WBEM_S_NO_MORE_DATA: HRESULT = 0x40005; + pub(super) const WBEM_INFINITE: i32 = -1; + pub(super) const WBEM_FLAVOR_MASK_ORIGIN: i32 = 0x60; + pub(super) const WBEM_FLAVOR_ORIGIN_SYSTEM: i32 = 0x40; #[link(name = "ole32")] unsafe extern "system" { - pub fn CoInitializeEx(pvReserved: *mut c_void, dwCoInit: u32) -> HRESULT; - pub fn CoUninitialize(); - pub fn CoInitializeSecurity( + pub(super) fn CoInitializeEx(pvReserved: *mut c_void, dwCoInit: u32) -> HRESULT; + + pub(super) fn CoUninitialize(); + + pub(super) fn CoInitializeSecurity( pSecDesc: *const c_void, cAuthSvc: i32, asAuthSvc: *const c_void, @@ -79,14 +81,16 @@ mod wmi_ffi { dwCapabilities: u32, pReserved3: *const c_void, ) -> HRESULT; - pub fn CoCreateInstance( + + pub(super) fn CoCreateInstance( rclsid: *const GUID, pUnkOuter: *mut c_void, dwClsContext: u32, riid: *const GUID, ppv: *mut *mut c_void, ) -> HRESULT; - pub fn CoSetProxyBlanket( + + pub(super) fn CoSetProxyBlanket( pProxy: *mut c_void, dwAuthnSvc: u32, dwAuthzSvc: u32, @@ -100,18 +104,22 @@ mod wmi_ffi { #[link(name = "oleaut32")] unsafe extern "system" { - pub fn SysAllocString(psz: *const u16) -> *mut u16; - pub fn SysFreeString(bstrString: *mut u16); - pub fn VariantClear(pvarg: *mut VARIANT) -> HRESULT; + pub(super) fn SysAllocString(psz: *const u16) -> *mut u16; + pub(super) fn SysFreeString(bstrString: *mut u16); + pub(super) fn VariantClear(pvarg: *mut VARIANT) -> HRESULT; } #[link(name = "propsys")] unsafe extern "system" { - pub fn VariantToString(varIn: *const VARIANT, pszBuf: *mut u16, cchBuf: u32) -> HRESULT; + pub(super) fn VariantToString( + varIn: *const VARIANT, + pszBuf: *mut u16, + cchBuf: u32, + ) -> HRESULT; } /// Release a COM object (IUnknown::Release, vtable index 2) - pub unsafe fn com_release(this: *mut c_void) { + pub(super) unsafe fn com_release(this: *mut c_void) { if !this.is_null() { let vtable = *(this as *const *const usize); let release: unsafe extern "system" fn(*mut c_void) -> u32 = @@ -122,7 +130,7 @@ mod wmi_ffi { /// IWbemLocator::ConnectServer (vtable index 3) #[allow(clippy::too_many_arguments)] - pub unsafe fn locator_connect_server( + pub(super) unsafe fn locator_connect_server( this: *mut c_void, network_resource: *const u16, user: *const u16, @@ -159,7 +167,7 @@ mod wmi_ffi { } /// IWbemServices::ExecQuery (vtable index 20) - pub unsafe fn services_exec_query( + pub(super) unsafe fn services_exec_query( this: *mut c_void, query_language: *const u16, query: *const u16, @@ -180,7 +188,7 @@ mod wmi_ffi { } /// IEnumWbemClassObject::Next (vtable index 4) - pub unsafe fn enum_next( + pub(super) unsafe fn enum_next( this: *mut c_void, timeout: i32, count: u32, @@ -199,7 +207,7 @@ mod wmi_ffi { } /// IWbemClassObject::BeginEnumeration (vtable index 8) - pub unsafe fn object_begin_enumeration(this: *mut c_void, enum_flags: i32) -> HRESULT { + pub(super) unsafe fn object_begin_enumeration(this: *mut c_void, enum_flags: i32) -> HRESULT { let vtable = *(this as *const *const usize); let method: unsafe extern "system" fn(*mut c_void, i32) -> HRESULT = core::mem::transmute(*vtable.add(8)); @@ -207,7 +215,7 @@ mod wmi_ffi { } /// IWbemClassObject::Next (vtable index 9) - pub unsafe fn object_next( + pub(super) unsafe fn object_next( this: *mut c_void, flags: i32, name: *mut *mut u16, @@ -228,7 +236,7 @@ mod wmi_ffi { } /// IWbemClassObject::EndEnumeration (vtable index 10) - pub unsafe fn object_end_enumeration(this: *mut c_void) -> HRESULT { + pub(super) unsafe fn object_end_enumeration(this: *mut c_void) -> HRESULT { let vtable = *(this as *const *const usize); let method: unsafe extern "system" fn(*mut c_void) -> HRESULT = core::mem::transmute(*vtable.add(10)); diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index fd35b287211..4f6de558dd4 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -980,7 +980,7 @@ mod builtins { } #[pyfunction] - pub fn exit(exit_code_arg: OptionalArg, vm: &VirtualMachine) -> PyResult { + pub(super) fn exit(exit_code_arg: OptionalArg, vm: &VirtualMachine) -> PyResult { let code = exit_code_arg.unwrap_or_else(|| vm.ctx.new_int(0).into()); Err(vm.new_exception(vm.ctx.exceptions.system_exit.to_owned(), vec![code])) } @@ -1048,7 +1048,7 @@ mod builtins { } #[derive(FromArgs)] - pub struct RoundArgs { + pub(super) struct RoundArgs { number: PyObjectRef, #[pyarg(any, optional)] ndigits: OptionalOption, @@ -1104,7 +1104,7 @@ mod builtins { } #[derive(FromArgs)] - pub struct SumArgs { + pub(super) struct SumArgs { #[pyarg(positional)] iterable: ArgIterable, #[pyarg(any, optional)] @@ -1171,7 +1171,7 @@ mod builtins { } #[pyfunction] - pub fn __build_class__( + pub(super) fn __build_class__( function: PyRef, name: PyStrRef, bases: PosArgs, diff --git a/crates/vm/src/stdlib/msvcrt.rs b/crates/vm/src/stdlib/msvcrt.rs index f10de1238d5..e3aa7432b71 100644 --- a/crates/vm/src/stdlib/msvcrt.rs +++ b/crates/vm/src/stdlib/msvcrt.rs @@ -1,6 +1,6 @@ // spell-checker:disable -pub use msvcrt::*; +pub(crate) use msvcrt::*; #[pymodule] mod msvcrt { @@ -21,19 +21,23 @@ mod msvcrt { SEM_NOOPENFILEERRORBOX, }; - pub fn setmode_binary(fd: crt_fd::Borrowed<'_>) { + pub(crate) fn setmode_binary(fd: crt_fd::Borrowed<'_>) { host_msvcrt::setmode_binary(fd); } // Locking mode constants #[pyattr] const LK_UNLCK: i32 = host_msvcrt::LK_UNLCK; // Unlock + #[pyattr] const LK_LOCK: i32 = host_msvcrt::LK_LOCK; // Lock (blocking) + #[pyattr] const LK_NBLCK: i32 = host_msvcrt::LK_NBLCK; // Non-blocking lock + #[pyattr] const LK_RLCK: i32 = host_msvcrt::LK_RLCK; // Lock for reading (same as LK_LOCK) + #[pyattr] const LK_NBRLCK: i32 = host_msvcrt::LK_NBRLCK; // Non-blocking lock for reading (same as LK_NBLCK) @@ -41,18 +45,22 @@ mod msvcrt { fn getch() -> Vec { host_msvcrt::getch() } + #[pyfunction] fn getwch() -> String { host_msvcrt::getwch() } + #[pyfunction] fn getche() -> Vec { host_msvcrt::getche() } + #[pyfunction] fn getwche() -> String { host_msvcrt::getwche() } + #[pyfunction] fn putch(b: PyRef, vm: &VirtualMachine) -> PyResult<()> { let &c = @@ -62,6 +70,7 @@ mod msvcrt { host_msvcrt::putch(c); Ok(()) } + #[pyfunction] fn putwch(s: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { let c = s diff --git a/crates/vm/src/stdlib/os.rs b/crates/vm/src/stdlib/os.rs index da646c95411..c3ef5668ea9 100644 --- a/crates/vm/src/stdlib/os.rs +++ b/crates/vm/src/stdlib/os.rs @@ -1595,12 +1595,12 @@ pub(super) mod _os { } #[pyfunction] - pub fn isatty(fd: i32) -> bool { + pub(crate) fn isatty(fd: i32) -> bool { unsafe { suppress_iph!(libc::isatty(fd)) != 0 } } #[pyfunction] - pub fn lseek( + pub(crate) fn lseek( fd: crt_fd::Borrowed<'_>, position: crt_fd::Offset, how: i32, @@ -2030,7 +2030,7 @@ pub(super) mod _os { } #[pyfunction] - pub fn ftruncate(fd: crt_fd::Borrowed<'_>, length: crt_fd::Offset) -> io::Result<()> { + pub(crate) fn ftruncate(fd: crt_fd::Borrowed<'_>, length: crt_fd::Offset) -> io::Result<()> { crt_fd::ftruncate(fd, length) } diff --git a/crates/vm/src/stdlib/sys.rs b/crates/vm/src/stdlib/sys.rs index b385e244203..59972bfc3f3 100644 --- a/crates/vm/src/stdlib/sys.rs +++ b/crates/vm/src/stdlib/sys.rs @@ -31,7 +31,7 @@ mod sys_jit { } #[pymodule] -mod sys { +pub mod sys { use crate::{ AsObject, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, builtins::{ diff --git a/crates/vm/src/stdlib/sys/monitoring.rs b/crates/vm/src/stdlib/sys/monitoring.rs index f802cd94f07..bf113c7937f 100644 --- a/crates/vm/src/stdlib/sys/monitoring.rs +++ b/crates/vm/src/stdlib/sys/monitoring.rs @@ -7,7 +7,7 @@ use core::sync::atomic::Ordering; use crossbeam_utils::atomic::AtomicCell; use std::collections::{HashMap, HashSet}; -pub const TOOL_LIMIT: usize = 6; +pub(crate) const TOOL_LIMIT: usize = 6; const EVENTS_COUNT: usize = 19; const LOCAL_EVENTS_COUNT: usize = 11; const UNGROUPED_EVENTS_COUNT: usize = 18; @@ -39,25 +39,25 @@ bitflags::bitflags! { } // Re-export as plain u32 constants for use in frame.rs hot-path checks -pub const EVENT_PY_START: u32 = MonitoringEvents::PY_START.bits(); -pub const EVENT_PY_RESUME: u32 = MonitoringEvents::PY_RESUME.bits(); -pub const EVENT_PY_RETURN: u32 = MonitoringEvents::PY_RETURN.bits(); -pub const EVENT_PY_YIELD: u32 = MonitoringEvents::PY_YIELD.bits(); -pub const EVENT_CALL: u32 = MonitoringEvents::CALL.bits(); -pub const EVENT_LINE: u32 = MonitoringEvents::LINE.bits(); -pub const EVENT_INSTRUCTION: u32 = MonitoringEvents::INSTRUCTION.bits(); -pub const EVENT_JUMP: u32 = MonitoringEvents::JUMP.bits(); -pub const EVENT_BRANCH_LEFT: u32 = MonitoringEvents::BRANCH_LEFT.bits(); -pub const EVENT_BRANCH_RIGHT: u32 = MonitoringEvents::BRANCH_RIGHT.bits(); -pub const EVENT_RAISE: u32 = MonitoringEvents::RAISE.bits(); -pub const EVENT_EXCEPTION_HANDLED: u32 = MonitoringEvents::EXCEPTION_HANDLED.bits(); -pub const EVENT_PY_UNWIND: u32 = MonitoringEvents::PY_UNWIND.bits(); -pub const EVENT_C_RETURN: u32 = MonitoringEvents::C_RETURN.bits(); +pub(crate) const EVENT_PY_START: u32 = MonitoringEvents::PY_START.bits(); +pub(crate) const EVENT_PY_RESUME: u32 = MonitoringEvents::PY_RESUME.bits(); +pub(crate) const EVENT_PY_RETURN: u32 = MonitoringEvents::PY_RETURN.bits(); +pub(crate) const EVENT_PY_YIELD: u32 = MonitoringEvents::PY_YIELD.bits(); +pub(crate) const EVENT_CALL: u32 = MonitoringEvents::CALL.bits(); +pub(crate) const EVENT_LINE: u32 = MonitoringEvents::LINE.bits(); +pub(crate) const EVENT_INSTRUCTION: u32 = MonitoringEvents::INSTRUCTION.bits(); +pub(crate) const EVENT_JUMP: u32 = MonitoringEvents::JUMP.bits(); +pub(crate) const EVENT_BRANCH_LEFT: u32 = MonitoringEvents::BRANCH_LEFT.bits(); +pub(crate) const EVENT_BRANCH_RIGHT: u32 = MonitoringEvents::BRANCH_RIGHT.bits(); +pub(crate) const EVENT_RAISE: u32 = MonitoringEvents::RAISE.bits(); +pub(crate) const EVENT_EXCEPTION_HANDLED: u32 = MonitoringEvents::EXCEPTION_HANDLED.bits(); +pub(crate) const EVENT_PY_UNWIND: u32 = MonitoringEvents::PY_UNWIND.bits(); +pub(crate) const EVENT_C_RETURN: u32 = MonitoringEvents::C_RETURN.bits(); const EVENT_C_RAISE: u32 = MonitoringEvents::C_RAISE.bits(); -pub const EVENT_STOP_ITERATION: u32 = MonitoringEvents::STOP_ITERATION.bits(); -pub const EVENT_PY_THROW: u32 = MonitoringEvents::PY_THROW.bits(); +pub(crate) const EVENT_STOP_ITERATION: u32 = MonitoringEvents::STOP_ITERATION.bits(); +pub(crate) const EVENT_PY_THROW: u32 = MonitoringEvents::PY_THROW.bits(); const EVENT_BRANCH: u32 = MonitoringEvents::BRANCH.bits(); -pub const EVENT_RERAISE: u32 = MonitoringEvents::RERAISE.bits(); +pub(crate) const EVENT_RERAISE: u32 = MonitoringEvents::RERAISE.bits(); const EVENT_C_RETURN_MASK: u32 = EVENT_C_RETURN | EVENT_C_RAISE; const EVENT_NAMES: [&str; EVENTS_COUNT] = [ @@ -138,10 +138,10 @@ impl MonitoringState { /// Global atomic mask: OR of all tools' events. Checked in the hot path /// to skip monitoring overhead when no events are registered. /// Lives in PyGlobalState alongside the PyMutex. -pub type MonitoringEventsMask = AtomicCell; +pub(crate) type MonitoringEventsMask = AtomicCell; /// Get the MISSING sentinel, creating it if necessary. -pub fn get_missing(vm: &VirtualMachine) -> PyObjectRef { +pub(crate) fn get_missing(vm: &VirtualMachine) -> PyObjectRef { let mut state = vm.state.monitoring.lock(); if let Some(ref m) = state.missing { m.clone() @@ -153,7 +153,7 @@ pub fn get_missing(vm: &VirtualMachine) -> PyObjectRef { } /// Get the DISABLE sentinel, creating it if necessary. -pub fn get_disable(vm: &VirtualMachine) -> PyObjectRef { +pub(crate) fn get_disable(vm: &VirtualMachine) -> PyObjectRef { let mut state = vm.state.monitoring.lock(); if let Some(ref d) = state.disable { d.clone() @@ -234,7 +234,7 @@ fn normalize_event_set(event_set: i32, local: bool, vm: &VirtualMachine) -> PyRe /// 3. Regular INSTRUMENTED_* — direct 1:1 opcode swap (no side-table needed) /// /// De-instrumentation peels layers in reverse order. -pub fn instrument_code(code: &PyCode, events: u32) { +pub(crate) fn instrument_code(code: &PyCode, events: u32) { use rustpython_compiler_core::bytecode::{self, Instruction}; let len = code.code.instructions.len(); @@ -813,7 +813,11 @@ fn fire( // Public dispatch functions (called from frame.rs) -pub fn fire_py_start(vm: &VirtualMachine, code: &PyRef, offset: u32) -> PyResult<()> { +pub(crate) fn fire_py_start( + vm: &VirtualMachine, + code: &PyRef, + offset: u32, +) -> PyResult<()> { fire( vm, EVENT_PY_START, @@ -823,7 +827,11 @@ pub fn fire_py_start(vm: &VirtualMachine, code: &PyRef, offset: u32) -> ) } -pub fn fire_py_resume(vm: &VirtualMachine, code: &PyRef, offset: u32) -> PyResult<()> { +pub(crate) fn fire_py_resume( + vm: &VirtualMachine, + code: &PyRef, + offset: u32, +) -> PyResult<()> { fire( vm, EVENT_PY_RESUME, @@ -833,7 +841,7 @@ pub fn fire_py_resume(vm: &VirtualMachine, code: &PyRef, offset: u32) -> ) } -pub fn fire_py_return( +pub(crate) fn fire_py_return( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -848,7 +856,7 @@ pub fn fire_py_return( ) } -pub fn fire_py_yield( +pub(crate) fn fire_py_yield( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -863,7 +871,7 @@ pub fn fire_py_yield( ) } -pub fn fire_call( +pub(crate) fn fire_call( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -879,7 +887,7 @@ pub fn fire_call( ) } -pub fn fire_c_return( +pub(crate) fn fire_c_return( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -895,7 +903,7 @@ pub fn fire_c_return( ) } -pub fn fire_c_raise( +pub(crate) fn fire_c_raise( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -911,7 +919,7 @@ pub fn fire_c_raise( ) } -pub fn fire_line( +pub(crate) fn fire_line( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -920,7 +928,11 @@ pub fn fire_line( fire(vm, EVENT_LINE, code, offset, &[vm.ctx.new_int(line).into()]) } -pub fn fire_instruction(vm: &VirtualMachine, code: &PyRef, offset: u32) -> PyResult<()> { +pub(crate) fn fire_instruction( + vm: &VirtualMachine, + code: &PyRef, + offset: u32, +) -> PyResult<()> { fire( vm, EVENT_INSTRUCTION, @@ -930,7 +942,7 @@ pub fn fire_instruction(vm: &VirtualMachine, code: &PyRef, offset: u32) ) } -pub fn fire_raise( +pub(crate) fn fire_raise( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -947,7 +959,7 @@ pub fn fire_raise( /// Only fires if no RERAISE has been fired since the last EXCEPTION_HANDLED, /// preventing duplicate events from chained cleanup handlers. -pub fn fire_reraise( +pub(crate) fn fire_reraise( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -970,7 +982,7 @@ pub fn fire_reraise( result } -pub fn fire_exception_handled( +pub(crate) fn fire_exception_handled( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -986,7 +998,7 @@ pub fn fire_exception_handled( ) } -pub fn fire_py_unwind( +pub(crate) fn fire_py_unwind( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -1002,7 +1014,7 @@ pub fn fire_py_unwind( ) } -pub fn fire_py_throw( +pub(crate) fn fire_py_throw( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -1017,7 +1029,7 @@ pub fn fire_py_throw( ) } -pub fn fire_stop_iteration( +pub(crate) fn fire_stop_iteration( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -1032,7 +1044,7 @@ pub fn fire_stop_iteration( ) } -pub fn fire_jump( +pub(crate) fn fire_jump( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -1050,7 +1062,7 @@ pub fn fire_jump( ) } -pub fn fire_branch_left( +pub(crate) fn fire_branch_left( vm: &VirtualMachine, code: &PyRef, offset: u32, @@ -1068,7 +1080,7 @@ pub fn fire_branch_left( ) } -pub fn fire_branch_right( +pub(crate) fn fire_branch_right( vm: &VirtualMachine, code: &PyRef, offset: u32, diff --git a/crates/vm/src/stdlib/time.rs b/crates/vm/src/stdlib/time.rs index 5e3cfb36fca..c10958be6b8 100644 --- a/crates/vm/src/stdlib/time.rs +++ b/crates/vm/src/stdlib/time.rs @@ -24,7 +24,7 @@ unsafe extern "C" { } #[pymodule(name = "time", with(#[cfg(any(unix, windows))] platform))] -mod decl { +pub mod decl { use crate::{ AsObject, Py, PyObjectRef, PyResult, VirtualMachine, builtins::{PyBaseExceptionRef, PyStrRef, PyTypeRef}, diff --git a/crates/vm/src/stdlib/winreg.rs b/crates/vm/src/stdlib/winreg.rs index 89e4cb8e8aa..24099459527 100644 --- a/crates/vm/src/stdlib/winreg.rs +++ b/crates/vm/src/stdlib/winreg.rs @@ -62,14 +62,15 @@ mod winreg { // access rights #[pyattr] - pub use windows_sys::Win32::System::Registry::{ + pub(super) use windows_sys::Win32::System::Registry::{ KEY_ALL_ACCESS, KEY_CREATE_LINK, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_EXECUTE, KEY_NOTIFY, KEY_QUERY_VALUE, KEY_READ, KEY_SET_VALUE, KEY_WOW64_32KEY, KEY_WOW64_64KEY, KEY_WRITE, }; + // value types #[pyattr] - pub use windows_sys::Win32::System::Registry::{ + pub(super) use windows_sys::Win32::System::Registry::{ REG_BINARY, REG_CREATED_NEW_KEY, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_DWORD_LITTLE_ENDIAN, REG_EXPAND_SZ, REG_FULL_RESOURCE_DESCRIPTOR, REG_LINK, REG_MULTI_SZ, REG_NONE, REG_NOTIFY_CHANGE_ATTRIBUTES, REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_NAME, @@ -236,7 +237,7 @@ mod winreg { } } - pub const HKEY_ERR_MSG: &str = "bad operand type"; + pub(super) const HKEY_ERR_MSG: &str = "bad operand type"; impl AsNumber for PyHkey { fn as_number() -> &'static PyNumberMethods { diff --git a/crates/vm/src/stdlib/winsound.rs b/crates/vm/src/stdlib/winsound.rs index fea00d10c63..359d3967a99 100644 --- a/crates/vm/src/stdlib/winsound.rs +++ b/crates/vm/src/stdlib/winsound.rs @@ -6,12 +6,12 @@ pub(crate) use winsound::module_def; mod win32 { #[link(name = "winmm")] unsafe extern "system" { - pub fn PlaySoundW(pszSound: *const u16, hmod: isize, fdwSound: u32) -> i32; + pub(super) fn PlaySoundW(pszSound: *const u16, hmod: isize, fdwSound: u32) -> i32; } unsafe extern "system" { - pub fn Beep(dwFreq: u32, dwDuration: u32) -> i32; - pub fn MessageBeep(uType: u32) -> i32; + pub(super) fn Beep(dwFreq: u32, dwDuration: u32) -> i32; + pub(super) fn MessageBeep(uType: u32) -> i32; } } diff --git a/crates/vm/src/vm/method.rs b/crates/vm/src/vm/method.rs index 5f47c8b8c5b..9e4f7185552 100644 --- a/crates/vm/src/vm/method.rs +++ b/crates/vm/src/vm/method.rs @@ -10,7 +10,7 @@ use crate::{ }; #[derive(Debug)] -pub enum PyMethod { +pub(crate) enum PyMethod { Function { target: PyObjectRef, func: PyObjectRef, @@ -19,7 +19,7 @@ pub enum PyMethod { } impl PyMethod { - pub fn get(obj: PyObjectRef, name: &Py, vm: &VirtualMachine) -> PyResult { + pub(crate) fn get(obj: PyObjectRef, name: &Py, vm: &VirtualMachine) -> PyResult { let cls = obj.class(); let getattro = cls.slots.getattro.load().unwrap(); if getattro as usize != PyBaseObject::getattro as *const () as usize { @@ -124,7 +124,7 @@ impl PyMethod { Ok(Some(meth)) } - pub fn invoke(self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn invoke(self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { let (func, args) = match self { Self::Function { target, func } => (func, args.into_method_args(target, vm)), Self::Attribute(func) => (func, args.into_args(vm)), @@ -133,7 +133,7 @@ impl PyMethod { } #[allow(dead_code)] - pub fn invoke_ref(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn invoke_ref(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { let (func, args) = match self { Self::Function { target, func } => (func, args.into_method_args(target.clone(), vm)), Self::Attribute(func) => (func, args.into_args(vm)), diff --git a/crates/vm/src/windows.rs b/crates/vm/src/windows.rs index fe109c95ee5..30686412612 100644 --- a/crates/vm/src/windows.rs +++ b/crates/vm/src/windows.rs @@ -16,15 +16,19 @@ pub struct WinHandle(pub HANDLE); pub(crate) trait WindowsSysResultValue { type Ok: ToPyObject; + fn is_err(&self) -> bool; + fn into_ok(self) -> Self::Ok; } impl WindowsSysResultValue for HANDLE { type Ok = WinHandle; + fn is_err(&self) -> bool { *self == INVALID_HANDLE_VALUE } + fn into_ok(self) -> Self::Ok { WinHandle(self) } @@ -33,19 +37,22 @@ impl WindowsSysResultValue for HANDLE { // BOOL is i32 in windows-sys 0.61+ impl WindowsSysResultValue for i32 { type Ok = (); + fn is_err(&self) -> bool { *self == 0 } + fn into_ok(self) -> Self::Ok {} } pub(crate) struct WindowsSysResult(pub T); impl WindowsSysResult { - pub fn is_err(&self) -> bool { + pub(crate) fn is_err(&self) -> bool { self.0.is_err() } - pub fn into_pyresult(self, vm: &VirtualMachine) -> PyResult { + + pub(crate) fn into_pyresult(self, vm: &VirtualMachine) -> PyResult { if !self.is_err() { Ok(self.0.into_ok()) } else { diff --git a/crates/wasm/src/js_module.rs b/crates/wasm/src/js_module.rs index 314e2adbee0..7d531252043 100644 --- a/crates/wasm/src/js_module.rs +++ b/crates/wasm/src/js_module.rs @@ -56,9 +56,10 @@ mod _js { #[pyattr] #[pyclass(module = "_js", name = "JSValue")] #[derive(Debug, PyPayload)] - pub struct PyJsValue { + pub(crate) struct PyJsValue { pub(crate) value: JsValue, } + type PyJsValueRef = PyRef; impl AsRef for PyJsValue { @@ -92,7 +93,7 @@ mod _js { #[pyclass(with(Representable))] impl PyJsValue { #[inline] - pub fn new(value: impl Into) -> PyJsValue { + pub(crate) fn new(value: impl Into) -> PyJsValue { let value = value.into(); PyJsValue { value } } @@ -378,7 +379,7 @@ mod _js { #[pyattr] #[pyclass(module = "_js", name = "Promise")] #[derive(Debug, Clone, PyPayload)] - pub struct PyPromise { + pub(crate) struct PyPromise { value: PromiseKind, } @@ -392,18 +393,20 @@ mod _js { #[pyclass] impl PyPromise { - pub fn new(value: Promise) -> PyPromise { + pub(crate) fn new(value: Promise) -> PyPromise { PyPromise { value: PromiseKind::Js(value), } } - pub fn from_future(future: F) -> PyPromise + + pub(crate) fn from_future(future: F) -> PyPromise where F: future::Future> + 'static, { PyPromise::new(future_to_promise(future)) } - pub fn as_js(&self, vm: &VirtualMachine) -> Promise { + + pub(crate) fn as_js(&self, vm: &VirtualMachine) -> Promise { match &self.value { PromiseKind::Js(prom) => prom.clone(), PromiseKind::PyProm { then } => Promise::new(&mut |js_resolve, js_reject| { @@ -594,6 +597,7 @@ mod _js { } impl SelfIter for AwaitPromise {} + impl IterNext for AwaitPromise { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { zelf.send(None, vm)