From 081b1b5f1dba2ed1849abe4456a8ef403e2264a9 Mon Sep 17 00:00:00 2001 From: Mikhail Baykov Date: Sun, 23 Aug 2026 09:22:33 -0400 Subject: [PATCH] std: Make a lot of pub items crate private instead (ignore os/sys) Most of them don't need to be public, but there are scenarios where thing is private on one platform but public on the other, so having a lint on all the time gets complicated. I enabled the lint, made a lot of things private to the point that dealing with the rest required adding exceptions and disabled the lint back again. --- library/std/src/collections/hash/mod.rs | 4 ++-- library/std/src/fs/tests.rs | 2 +- library/std/src/io/stdio.rs | 2 +- library/std/src/lib.rs | 3 +++ library/std/src/panicking.rs | 10 +++++----- library/std/src/process/tests.rs | 4 ++-- library/std/src/sync/mpmc/context.rs | 14 +++++++------- library/std/src/sync/mpmc/select.rs | 8 ++++---- library/std/src/sync/mpmc/utils.rs | 12 ++++++------ library/std/src/sync/mpmc/waker.rs | 2 +- library/std/src/sync/poison.rs | 16 ++++++++-------- library/std/src/test_helpers.rs | 8 ++++---- library/std/src/thread/lifecycle.rs | 2 +- library/std/src/thread/thread.rs | 4 ++-- 14 files changed, 47 insertions(+), 44 deletions(-) diff --git a/library/std/src/collections/hash/mod.rs b/library/std/src/collections/hash/mod.rs index 348820af54bff..0476b0206f3d7 100644 --- a/library/std/src/collections/hash/mod.rs +++ b/library/std/src/collections/hash/mod.rs @@ -1,4 +1,4 @@ //! Unordered containers, implemented as hash-tables -pub mod map; -pub mod set; +pub(crate) mod map; +pub(crate) mod set; diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs index dab1df38aa1f5..148f1c32b08b9 100644 --- a/library/std/src/fs/tests.rs +++ b/library/std/src/fs/tests.rs @@ -45,7 +45,7 @@ macro_rules! error_contains { // have permission, and return otherwise. This way, we still don't run these // tests most of the time, but at least we do if the user has the right // permissions. -pub fn got_symlink_permission(tmpdir: &TempDir) -> bool { +pub(crate) fn got_symlink_permission(tmpdir: &TempDir) -> bool { if cfg!(not(windows)) || env::var_os("CI").is_some() { return true; } diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index b104ea69cd1fc..527671442fb72 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -726,7 +726,7 @@ pub fn stdout() -> Stdout { // Flush the data and disable buffering during shutdown // by replacing the line writer by one with zero // buffering capacity. -pub fn cleanup() { +pub(crate) fn cleanup() { let mut initialized = false; let stdout = STDOUT.get_or_init(|| { initialized = true; diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 817d208a8a620..28cb3dbfe3015 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -241,6 +241,7 @@ // Lints: #![warn(deprecated_in_future)] #![warn(missing_docs)] +#![warn(unreachable_pub)] #![warn(missing_debug_implementations)] #![allow(explicit_outlives_requirements)] #![allow(unused_lifetimes)] @@ -641,6 +642,7 @@ pub mod hash; pub mod io; pub mod net; pub mod num; +#[allow(unreachable_pub)] pub mod os; pub mod panic; #[unstable(feature = "pattern_type_macro", issue = "123646")] @@ -731,6 +733,7 @@ pub mod arch { #[stable(feature = "simd_x86", since = "1.27.0")] pub use std_detect::is_x86_feature_detected; +#[allow(unreachable_pub)] mod sys; pub mod alloc; diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 5a4684a973942..f69e0a749f579 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -41,7 +41,7 @@ use crate::{fmt, intrinsics, process, thread}; #[doc(hidden)] #[allow(dead_code)] #[used(compiler)] -pub static EMPTY_PANIC: fn(&'static str) -> ! = +pub(crate) static EMPTY_PANIC: fn(&'static str) -> ! = begin_panic::<&'static str> as fn(&'static str) -> !; // Binary interface to the panic runtime that the standard library depends on. @@ -495,7 +495,7 @@ pub unsafe fn catch_unwind R>(f: F) -> Result R>(f: F) -> Result> { +pub(crate) unsafe fn catch_unwind R>(f: F) -> Result> { union Data { f: ManuallyDrop, r: ManuallyDrop, @@ -599,14 +599,14 @@ pub unsafe fn catch_unwind R>(f: F) -> Result bool { +pub(crate) fn panicking() -> bool { !panic_count::count_is_zero() } /// Entry point of panics from the core crate (`panic_impl` lang item). #[cfg(not(any(test, doctest)))] #[panic_handler] -pub fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! { +pub(crate) fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! { struct FormatStringPayload<'a> { inner: &'a core::panic::PanicMessage<'a>, string: Option, @@ -839,7 +839,7 @@ fn panic_with_hook( /// This is the entry point for `resume_unwind`. /// It just forwards the payload to the panic runtime. #[cfg_attr(panic = "immediate-abort", inline)] -pub fn resume_unwind(payload: Box) -> ! { +pub(crate) fn resume_unwind(payload: Box) -> ! { if let Some(must_abort) = panic_count::increase(false) { match must_abort { panic_count::MustAbort::PanicInHook => { diff --git a/library/std/src/process/tests.rs b/library/std/src/process/tests.rs index 35ce30f1146e4..d5b01bcb3c29b 100644 --- a/library/std/src/process/tests.rs +++ b/library/std/src/process/tests.rs @@ -95,7 +95,7 @@ fn signal_reported_right() { } } -pub fn run_output(mut cmd: Command) -> String { +pub(crate) fn run_output(mut cmd: Command) -> String { let p = cmd.spawn(); assert!(p.is_ok()); let mut p = p.unwrap(); @@ -361,7 +361,7 @@ fn test_wait_with_output_once() { } #[cfg(all(unix, not(target_os = "android")))] -pub fn env_cmd() -> Command { +pub(crate) fn env_cmd() -> Command { Command::new("env") } #[cfg(target_os = "android")] diff --git a/library/std/src/sync/mpmc/context.rs b/library/std/src/sync/mpmc/context.rs index 6b2f4cb6ffd29..b4fee60a574ff 100644 --- a/library/std/src/sync/mpmc/context.rs +++ b/library/std/src/sync/mpmc/context.rs @@ -11,7 +11,7 @@ use crate::time::Instant; /// Thread-local context. #[derive(Debug, Clone)] -pub struct Context { +pub(crate) struct Context { inner: Arc, } @@ -34,7 +34,7 @@ struct Inner { impl Context { /// Creates a new context for the duration of the closure. #[inline] - pub fn with(f: F) -> R + pub(crate) fn with(f: F) -> R where F: FnOnce(&Context) -> R, { @@ -86,7 +86,7 @@ impl Context { /// /// On failure, the previously selected operation is returned. #[inline] - pub fn try_select(&self, select: Selected) -> Result<(), Selected> { + pub(crate) fn try_select(&self, select: Selected) -> Result<(), Selected> { self.inner .select .compare_exchange( @@ -103,7 +103,7 @@ impl Context { /// /// This method must be called after `try_select` succeeds and there is a packet to provide. #[inline] - pub fn store_packet(&self, packet: *mut ()) { + pub(crate) fn store_packet(&self, packet: *mut ()) { if !packet.is_null() { self.inner.packet.store(packet, Ordering::Release); } @@ -116,7 +116,7 @@ impl Context { /// # Safety /// This may only be called from the thread this `Context` belongs to. #[inline] - pub unsafe fn wait_until(&self, deadline: Option) -> Selected { + pub(crate) unsafe fn wait_until(&self, deadline: Option) -> Selected { loop { // Check whether an operation has been selected. let sel = Selected::from(self.inner.select.load(Ordering::Acquire)); @@ -147,13 +147,13 @@ impl Context { /// Unparks the thread this context belongs to. #[inline] - pub fn unpark(&self) { + pub(crate) fn unpark(&self) { self.inner.thread.unpark(); } /// Returns the id of the thread this context belongs to. #[inline] - pub fn thread_id(&self) -> usize { + pub(crate) fn thread_id(&self) -> usize { self.inner.thread_id } } diff --git a/library/std/src/sync/mpmc/select.rs b/library/std/src/sync/mpmc/select.rs index ff537aa686157..60f81d863ae4f 100644 --- a/library/std/src/sync/mpmc/select.rs +++ b/library/std/src/sync/mpmc/select.rs @@ -3,7 +3,7 @@ /// /// Each field contains data associated with a specific channel flavor. #[derive(Debug, Default)] -pub struct Token { +pub(crate) struct Token { pub(crate) array: super::array::ArrayToken, pub(crate) list: super::list::ListToken, #[allow(dead_code)] @@ -12,7 +12,7 @@ pub struct Token { /// Identifier associated with an operation by a specific thread on a specific channel. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Operation(usize); +pub(crate) struct Operation(usize); impl Operation { /// Creates an operation identifier from a mutable reference. @@ -21,7 +21,7 @@ impl Operation { /// reference should point to a variable that is specific to the thread and the operation, /// and is alive for the entire duration of a blocking operation. #[inline] - pub fn hook(r: &mut T) -> Operation { + pub(crate) fn hook(r: &mut T) -> Operation { let val = (r as *mut T).addr(); // Make sure that the pointer address doesn't equal the numerical representation of // `Selected::{Waiting, Aborted, Disconnected}`. @@ -32,7 +32,7 @@ impl Operation { /// Current state of a blocking operation. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Selected { +pub(crate) enum Selected { /// Still waiting for an operation. Waiting, diff --git a/library/std/src/sync/mpmc/utils.rs b/library/std/src/sync/mpmc/utils.rs index e3bcb149f648b..5a9bc7af6c36d 100644 --- a/library/std/src/sync/mpmc/utils.rs +++ b/library/std/src/sync/mpmc/utils.rs @@ -67,13 +67,13 @@ use crate::ops::{Deref, DerefMut}; )), repr(align(64)) )] -pub struct CachePadded { +pub(crate) struct CachePadded { value: T, } impl CachePadded { /// Pads and aligns a value to the length of a cache line. - pub fn new(value: T) -> CachePadded { + pub(crate) fn new(value: T) -> CachePadded { CachePadded:: { value } } } @@ -95,13 +95,13 @@ impl DerefMut for CachePadded { const SPIN_LIMIT: u32 = 6; /// Performs quadratic backoff in spin loops. -pub struct Backoff { +pub(crate) struct Backoff { step: Cell, } impl Backoff { /// Creates a new `Backoff`. - pub fn new() -> Self { + pub(crate) fn new() -> Self { Backoff { step: Cell::new(0) } } @@ -110,7 +110,7 @@ impl Backoff { /// This method should be used for retrying an operation because another thread made /// progress. i.e. on CAS failure. #[inline] - pub fn spin_light(&self) { + pub(crate) fn spin_light(&self) { let step = self.step.get().min(SPIN_LIMIT); for _ in 0..step.pow(2) { crate::hint::spin_loop(); @@ -123,7 +123,7 @@ impl Backoff { /// /// This method should be used in blocking loops where parking the thread is not an option. #[inline] - pub fn spin_heavy(&self) { + pub(crate) fn spin_heavy(&self) { if self.step.get() <= SPIN_LIMIT { for _ in 0..self.step.get().pow(2) { crate::hint::spin_loop() diff --git a/library/std/src/sync/mpmc/waker.rs b/library/std/src/sync/mpmc/waker.rs index 4216fb7ac5902..de913f0d421cc 100644 --- a/library/std/src/sync/mpmc/waker.rs +++ b/library/std/src/sync/mpmc/waker.rs @@ -201,7 +201,7 @@ impl Drop for SyncWaker { /// Returns a unique id for the current thread. #[inline] -pub fn current_thread_id() -> usize { +pub(crate) fn current_thread_id() -> usize { // `u8` is not drop so this variable will be available during thread destruction, // whereas `thread::current()` would not be thread_local! { static DUMMY: u8 = const { 0 } } diff --git a/library/std/src/sync/poison.rs b/library/std/src/sync/poison.rs index 3c32ec34dee5b..62d4c2754effe 100644 --- a/library/std/src/sync/poison.rs +++ b/library/std/src/sync/poison.rs @@ -97,7 +97,7 @@ pub(crate) struct Flag { impl Flag { #[inline] - pub const fn new() -> Flag { + pub(crate) const fn new() -> Flag { Flag { #[cfg(panic = "unwind")] failed: AtomicBool::new(false), @@ -106,13 +106,13 @@ impl Flag { /// Checks the flag for an unguarded borrow, where we only care about existing poison. #[inline] - pub fn borrow(&self) -> LockResult<()> { + pub(crate) fn borrow(&self) -> LockResult<()> { if self.get() { Err(PoisonError::new(())) } else { Ok(()) } } /// Checks the flag for a guarded borrow, where we may also set poison when `done`. #[inline] - pub fn guard(&self) -> LockResult { + pub(crate) fn guard(&self) -> LockResult { let ret = Guard { #[cfg(panic = "unwind")] panicking: thread::panicking(), @@ -122,7 +122,7 @@ impl Flag { #[inline] #[cfg(panic = "unwind")] - pub fn done(&self, guard: &Guard) { + pub(crate) fn done(&self, guard: &Guard) { if !guard.panicking && thread::panicking() { self.failed.store(true, Ordering::Relaxed); } @@ -130,22 +130,22 @@ impl Flag { #[inline] #[cfg(not(panic = "unwind"))] - pub fn done(&self, _guard: &Guard) {} + pub(crate) fn done(&self, _guard: &Guard) {} #[inline] #[cfg(panic = "unwind")] - pub fn get(&self) -> bool { + pub(crate) fn get(&self) -> bool { self.failed.load(Ordering::Relaxed) } #[inline(always)] #[cfg(not(panic = "unwind"))] - pub fn get(&self) -> bool { + pub(crate) fn get(&self) -> bool { false } #[inline] - pub fn clear(&self) { + pub(crate) fn clear(&self) { #[cfg(panic = "unwind")] self.failed.store(false, Ordering::Relaxed) } diff --git a/library/std/src/test_helpers.rs b/library/std/src/test_helpers.rs index 7c20f38c863b6..5690a40648ff2 100644 --- a/library/std/src/test_helpers.rs +++ b/library/std/src/test_helpers.rs @@ -27,15 +27,15 @@ pub(crate) fn test_rng() -> rand_xorshift::XorShiftRng { SeedableRng::from_seed(seed) } -pub struct TempDir(PathBuf); +pub(crate) struct TempDir(PathBuf); impl TempDir { - pub fn join(&self, path: &str) -> PathBuf { + pub(crate) fn join(&self, path: &str) -> PathBuf { let TempDir(ref p) = *self; p.join(path) } - pub fn path(&self) -> &Path { + pub(crate) fn path(&self) -> &Path { let TempDir(ref p) = *self; p } @@ -56,7 +56,7 @@ impl Drop for TempDir { } #[track_caller] // for `test_rng` -pub fn tmpdir() -> TempDir { +pub(crate) fn tmpdir() -> TempDir { let p = env::temp_dir(); let mut r = test_rng(); let ret = p.join(&format!("rust-{}", r.next_u32())); diff --git a/library/std/src/thread/lifecycle.rs b/library/std/src/thread/lifecycle.rs index 0dec359ccaec6..c22b97c39ecd5 100644 --- a/library/std/src/thread/lifecycle.rs +++ b/library/std/src/thread/lifecycle.rs @@ -125,7 +125,7 @@ pub(crate) struct ThreadInit { impl ThreadInit { /// Initialize the 'current thread' mechanism on this thread, returning the /// Rust entry point. - pub fn init(self: Box) -> Box { + pub(crate) fn init(self: Box) -> Box { // Set the current thread before any (de)allocations on the global allocator occur, // so that it may call std::thread::current() in its implementation. This is also // why we take Box, to ensure the Box is not destroyed until after this point. diff --git a/library/std/src/thread/thread.rs b/library/std/src/thread/thread.rs index d70c244c65d90..bfcf0fa4953d2 100644 --- a/library/std/src/thread/thread.rs +++ b/library/std/src/thread/thread.rs @@ -28,11 +28,11 @@ mod thread_name_string { } impl ThreadNameString { - pub fn as_cstr(&self) -> &CStr { + pub(crate) fn as_cstr(&self) -> &CStr { &self.inner } - pub fn as_str(&self) -> &str { + pub(crate) fn as_str(&self) -> &str { // SAFETY: `ThreadNameString` is guaranteed to be UTF-8. unsafe { str::from_utf8_unchecked(self.inner.to_bytes()) } }