rustc_data_structures/
marker.rs

1use std::alloc::Allocator;
2
3use rustc_serialize::PointeeSized;
4
5#[diagnostic::on_unimplemented(message = "`{Self}` doesn't implement `DynSend`. \
6            Add it to `rustc_data_structures::marker` or use `IntoDynSyncSend` if it's already `Send`")]
7// This is an auto trait for types which can be sent across threads if `sync::is_dyn_thread_safe()`
8// is true. These types can be wrapped in a `FromDyn` to get a `Send` type. Wrapping a
9// `Send` type in `IntoDynSyncSend` will create a `DynSend` type.
10pub unsafe auto trait DynSend {}
11
12#[diagnostic::on_unimplemented(message = "`{Self}` doesn't implement `DynSync`. \
13            Add it to `rustc_data_structures::marker` or use `IntoDynSyncSend` if it's already `Sync`")]
14// This is an auto trait for types which can be shared across threads if `sync::is_dyn_thread_safe()`
15// is true. These types can be wrapped in a `FromDyn` to get a `Sync` type. Wrapping a
16// `Sync` type in `IntoDynSyncSend` will create a `DynSync` type.
17pub unsafe auto trait DynSync {}
18
19// Same with `Sync` and `Send`.
20unsafe impl<T: DynSync + ?Sized + PointeeSized> DynSend for &T {}
21
22macro_rules! impls_dyn_send_neg {
23    ($([$t1: ty $(where $($generics1: tt)*)?])*) => {
24        $(impl$(<$($generics1)*>)? !DynSend for $t1 {})*
25    };
26}
27
28// Consistent with `std`
29impls_dyn_send_neg!(
30    [std::env::Args]
31    [std::env::ArgsOs]
32    [*const T where T: ?Sized + PointeeSized]
33    [*mut T where T: ?Sized + PointeeSized]
34    [std::ptr::NonNull<T> where T: ?Sized + PointeeSized]
35    [std::rc::Rc<T, A> where T: ?Sized, A: Allocator]
36    [std::rc::Weak<T, A> where T: ?Sized, A: Allocator]
37    [std::sync::MutexGuard<'_, T> where T: ?Sized]
38    [std::sync::RwLockReadGuard<'_, T> where T: ?Sized]
39    [std::sync::RwLockWriteGuard<'_, T> where T: ?Sized]
40    [std::io::StdoutLock<'_>]
41    [std::io::StderrLock<'_>]
42);
43
44#[cfg(any(
45    unix,
46    target_os = "hermit",
47    all(target_vendor = "fortanix", target_env = "sgx"),
48    target_os = "solid_asp3",
49    target_os = "wasi",
50    target_os = "xous"
51))]
52// Consistent with `std`, `env_imp::Env` is `!Sync` in these platforms
53impl !DynSend for std::env::VarsOs {}
54
55macro_rules! already_send {
56    ($([$ty: ty])*) => {
57        $(unsafe impl DynSend for $ty where $ty: Send {})*
58    };
59}
60
61// These structures are already `Send`.
62already_send!(
63    [std::backtrace::Backtrace][std::io::Stdout][std::io::Stderr][std::io::Error][std::fs::File]
64        [rustc_arena::DroplessArena][jobserver_crate::Client][jobserver_crate::HelperThread]
65        [crate::memmap::Mmap][crate::profiling::SelfProfiler][crate::owned_slice::OwnedSlice]
66);
67
68macro_rules! impl_dyn_send {
69    ($($($attr: meta)* [$ty: ty where $($generics2: tt)*])*) => {
70        $(unsafe impl<$($generics2)*> DynSend for $ty {})*
71    };
72}
73
74impl_dyn_send!(
75    [std::sync::atomic::AtomicPtr<T> where T]
76    [std::sync::Mutex<T> where T: ?Sized+ DynSend]
77    [std::sync::mpsc::Sender<T> where T: DynSend]
78    [std::sync::Arc<T> where T: ?Sized + DynSync + DynSend]
79    [std::sync::LazyLock<T, F> where T: DynSend, F: DynSend]
80    [std::collections::HashSet<K, S> where K: DynSend, S: DynSend]
81    [std::collections::HashMap<K, V, S> where K: DynSend, V: DynSend, S: DynSend]
82    [std::collections::BTreeMap<K, V, A> where K: DynSend, V: DynSend, A: std::alloc::Allocator + Clone + DynSend]
83    [Vec<T, A> where T: DynSend, A: std::alloc::Allocator + DynSend]
84    [Box<T, A> where T: ?Sized + DynSend, A: std::alloc::Allocator + DynSend]
85    [crate::sync::RwLock<T> where T: DynSend]
86    [crate::tagged_ptr::TaggedRef<'a, P, T> where 'a, P: Sync, T: Send + crate::tagged_ptr::Tag]
87    [rustc_arena::TypedArena<T> where T: DynSend]
88    [hashbrown::HashTable<T> where T: DynSend]
89    [indexmap::IndexSet<V, S> where V: DynSend, S: DynSend]
90    [indexmap::IndexMap<K, V, S> where K: DynSend, V: DynSend, S: DynSend]
91    [thin_vec::ThinVec<T> where T: DynSend]
92    [smallvec::SmallVec<A> where A: smallvec::Array + DynSend]
93);
94
95macro_rules! impls_dyn_sync_neg {
96    ($([$t1: ty $(where $($generics1: tt)*)?])*) => {
97        $(impl$(<$($generics1)*>)? !DynSync for $t1 {})*
98    };
99}
100
101// Consistent with `std`
102impls_dyn_sync_neg!(
103    [std::env::Args]
104    [std::env::ArgsOs]
105    [*const T where T: ?Sized + PointeeSized]
106    [*mut T where T: ?Sized + PointeeSized]
107    [std::cell::Cell<T> where T: ?Sized]
108    [std::cell::RefCell<T> where T: ?Sized]
109    [std::cell::UnsafeCell<T> where T: ?Sized]
110    [std::ptr::NonNull<T> where T: ?Sized + PointeeSized]
111    [std::rc::Rc<T, A> where T: ?Sized, A: Allocator]
112    [std::rc::Weak<T, A> where T: ?Sized, A: Allocator]
113    [std::cell::OnceCell<T> where T]
114    [std::sync::mpsc::Receiver<T> where T]
115    [std::sync::mpsc::Sender<T> where T]
116);
117
118#[cfg(any(
119    unix,
120    target_os = "hermit",
121    all(target_vendor = "fortanix", target_env = "sgx"),
122    target_os = "solid_asp3",
123    target_os = "wasi",
124    target_os = "xous"
125))]
126// Consistent with `std`, `env_imp::Env` is `!Sync` in these platforms
127impl !DynSync for std::env::VarsOs {}
128
129macro_rules! already_sync {
130    ($([$ty: ty])*) => {
131        $(unsafe impl DynSync for $ty where $ty: Sync {})*
132    };
133}
134
135// These structures are already `Sync`.
136already_sync!(
137    [std::sync::atomic::AtomicBool][std::sync::atomic::AtomicUsize][std::sync::atomic::AtomicU8]
138        [std::sync::atomic::AtomicU32][std::backtrace::Backtrace][std::io::Error][std::fs::File]
139        [jobserver_crate::Client][jobserver_crate::HelperThread][crate::memmap::Mmap]
140        [crate::profiling::SelfProfiler][crate::owned_slice::OwnedSlice]
141);
142
143// Use portable AtomicU64 for targets without native 64-bit atomics
144#[cfg(target_has_atomic = "64")]
145already_sync!([std::sync::atomic::AtomicU64]);
146
147#[cfg(not(target_has_atomic = "64"))]
148already_sync!([portable_atomic::AtomicU64]);
149
150macro_rules! impl_dyn_sync {
151    ($($($attr: meta)* [$ty: ty where $($generics2: tt)*])*) => {
152        $(unsafe impl<$($generics2)*> DynSync for $ty {})*
153    };
154}
155
156impl_dyn_sync!(
157    [std::sync::atomic::AtomicPtr<T> where T]
158    [std::sync::OnceLock<T> where T: DynSend + DynSync]
159    [std::sync::Mutex<T> where T: ?Sized + DynSend]
160    [std::sync::Arc<T> where T: ?Sized + DynSync + DynSend]
161    [std::sync::LazyLock<T, F> where T: DynSend + DynSync, F: DynSend]
162    [std::collections::HashSet<K, S> where K: DynSync, S: DynSync]
163    [std::collections::HashMap<K, V, S> where K: DynSync, V: DynSync, S: DynSync]
164    [std::collections::BTreeMap<K, V, A> where K: DynSync, V: DynSync, A: std::alloc::Allocator + Clone + DynSync]
165    [Vec<T, A> where T: DynSync, A: std::alloc::Allocator + DynSync]
166    [Box<T, A> where T: ?Sized + DynSync, A: std::alloc::Allocator + DynSync]
167    [crate::sync::RwLock<T> where T: DynSend + DynSync]
168    [crate::sync::WorkerLocal<T> where T: DynSend]
169    [crate::intern::Interned<'a, T> where 'a, T: DynSync]
170    [crate::tagged_ptr::TaggedRef<'a, P, T> where 'a, P: Sync, T: Sync + crate::tagged_ptr::Tag]
171    [parking_lot::lock_api::Mutex<R, T> where R: DynSync, T: ?Sized + DynSend]
172    [parking_lot::lock_api::RwLock<R, T> where R: DynSync, T: ?Sized + DynSend + DynSync]
173    [hashbrown::HashTable<T> where T: DynSync]
174    [indexmap::IndexSet<V, S> where V: DynSync, S: DynSync]
175    [indexmap::IndexMap<K, V, S> where K: DynSync, V: DynSync, S: DynSync]
176    [smallvec::SmallVec<A> where A: smallvec::Array + DynSync]
177    [thin_vec::ThinVec<T> where T: DynSync]
178);
179
180pub fn assert_dyn_sync<T: ?Sized + PointeeSized + DynSync>() {}
181pub fn assert_dyn_send<T: ?Sized + PointeeSized + DynSend>() {}
182pub fn assert_dyn_send_val<T: ?Sized + PointeeSized + DynSend>(_t: &T) {}
183pub fn assert_dyn_send_sync_val<T: ?Sized + PointeeSized + DynSync + DynSend>(_t: &T) {}
184
185#[derive(Copy, Clone)]
186pub struct FromDyn<T>(T);
187
188impl<T> FromDyn<T> {
189    #[inline(always)]
190    pub fn from(val: T) -> Self {
191        // Check that `sync::is_dyn_thread_safe()` is true on creation so we can
192        // implement `Send` and `Sync` for this structure when `T`
193        // implements `DynSend` and `DynSync` respectively.
194        assert!(crate::sync::is_dyn_thread_safe());
195        FromDyn(val)
196    }
197
198    #[inline(always)]
199    pub fn derive<O>(&self, val: O) -> FromDyn<O> {
200        // We already did the check for `sync::is_dyn_thread_safe()` when creating `Self`
201        FromDyn(val)
202    }
203
204    #[inline(always)]
205    pub fn into_inner(self) -> T {
206        self.0
207    }
208}
209
210// `FromDyn` is `Send` if `T` is `DynSend`, since it ensures that sync::is_dyn_thread_safe() is true.
211unsafe impl<T: DynSend> Send for FromDyn<T> {}
212
213// `FromDyn` is `Sync` if `T` is `DynSync`, since it ensures that sync::is_dyn_thread_safe() is true.
214unsafe impl<T: DynSync> Sync for FromDyn<T> {}
215
216impl<T> std::ops::Deref for FromDyn<T> {
217    type Target = T;
218
219    #[inline(always)]
220    fn deref(&self) -> &Self::Target {
221        &self.0
222    }
223}
224
225impl<T> std::ops::DerefMut for FromDyn<T> {
226    #[inline(always)]
227    fn deref_mut(&mut self) -> &mut Self::Target {
228        &mut self.0
229    }
230}
231
232// A wrapper to convert a struct that is already a `Send` or `Sync` into
233// an instance of `DynSend` and `DynSync`, since the compiler cannot infer
234// it automatically in some cases. (e.g. Box<dyn Send / Sync>)
235#[derive(Copy, Clone)]
236pub struct IntoDynSyncSend<T: ?Sized + PointeeSized>(pub T);
237
238unsafe impl<T: ?Sized + PointeeSized + Send> DynSend for IntoDynSyncSend<T> {}
239unsafe impl<T: ?Sized + PointeeSized + Sync> DynSync for IntoDynSyncSend<T> {}
240
241impl<T> std::ops::Deref for IntoDynSyncSend<T> {
242    type Target = T;
243
244    #[inline(always)]
245    fn deref(&self) -> &T {
246        &self.0
247    }
248}
249
250impl<T> std::ops::DerefMut for IntoDynSyncSend<T> {
251    #[inline(always)]
252    fn deref_mut(&mut self) -> &mut T {
253        &mut self.0
254    }
255}