core/marker.rs
1//! Primitive traits and types representing basic properties of types.
2//!
3//! Rust types can be classified in various useful ways according to
4//! their intrinsic properties. These classifications are represented
5//! as traits.
6
7#![stable(feature = "rust1", since = "1.0.0")]
8
9#[cfg(not(feature = "ferrocene_certified"))]
10mod variance;
11
12#[unstable(feature = "phantom_variance_markers", issue = "135806")]
13#[cfg(not(feature = "ferrocene_certified"))]
14pub use self::variance::{
15 PhantomContravariant, PhantomContravariantLifetime, PhantomCovariant, PhantomCovariantLifetime,
16 PhantomInvariant, PhantomInvariantLifetime, Variance, variance,
17};
18#[cfg(not(feature = "ferrocene_certified"))]
19use crate::cell::UnsafeCell;
20#[cfg(not(feature = "ferrocene_certified"))]
21use crate::clone::TrivialClone;
22#[cfg(not(feature = "ferrocene_certified"))]
23use crate::cmp;
24#[cfg(not(feature = "ferrocene_certified"))]
25use crate::fmt::Debug;
26#[cfg(not(feature = "ferrocene_certified"))]
27use crate::hash::{Hash, Hasher};
28#[cfg(not(feature = "ferrocene_certified"))]
29use crate::pin::UnsafePinned;
30
31// NOTE: for consistent error messages between `core` and `minicore`, all `diagnostic` attributes
32// should be replicated exactly in `minicore` (if `minicore` defines the item).
33
34/// Implements a given marker trait for multiple types at the same time.
35///
36/// The basic syntax looks like this:
37/// ```ignore private macro
38/// marker_impls! { MarkerTrait for u8, i8 }
39/// ```
40/// You can also implement `unsafe` traits
41/// ```ignore private macro
42/// marker_impls! { unsafe MarkerTrait for u8, i8 }
43/// ```
44/// Add attributes to all impls:
45/// ```ignore private macro
46/// marker_impls! {
47/// #[allow(lint)]
48/// #[unstable(feature = "marker_trait", issue = "none")]
49/// MarkerTrait for u8, i8
50/// }
51/// ```
52/// And use generics:
53/// ```ignore private macro
54/// marker_impls! {
55/// MarkerTrait for
56/// u8, i8,
57/// {T: ?Sized} *const T,
58/// {T: ?Sized} *mut T,
59/// {T: MarkerTrait} PhantomData<T>,
60/// u32,
61/// }
62/// ```
63#[unstable(feature = "internal_impls_macro", issue = "none")]
64// Allow implementations of `UnsizedConstParamTy` even though std cannot use that feature.
65#[allow_internal_unstable(unsized_const_params)]
66macro marker_impls {
67 ( $(#[$($meta:tt)*])* $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => {
68 $(#[$($meta)*])* impl< $($($bounds)*)? > $Trait for $T {}
69 marker_impls! { $(#[$($meta)*])* $Trait for $($($rest)*)? }
70 },
71 ( $(#[$($meta:tt)*])* $Trait:ident for ) => {},
72
73 ( $(#[$($meta:tt)*])* unsafe $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => {
74 $(#[$($meta)*])* unsafe impl< $($($bounds)*)? > $Trait for $T {}
75 marker_impls! { $(#[$($meta)*])* unsafe $Trait for $($($rest)*)? }
76 },
77 ( $(#[$($meta:tt)*])* unsafe $Trait:ident for ) => {},
78}
79
80/// Types that can be transferred across thread boundaries.
81///
82/// This trait is automatically implemented when the compiler determines it's
83/// appropriate.
84///
85/// An example of a non-`Send` type is the reference-counting pointer
86/// [`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same
87/// reference-counted value, they might try to update the reference count at the
88/// same time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic
89/// operations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring
90/// some overhead) and thus is `Send`.
91///
92/// See [the Nomicon](../../nomicon/send-and-sync.html) and the [`Sync`] trait for more details.
93///
94/// [`Rc`]: ../../std/rc/struct.Rc.html
95/// [arc]: ../../std/sync/struct.Arc.html
96/// [ub]: ../../reference/behavior-considered-undefined.html
97#[stable(feature = "rust1", since = "1.0.0")]
98#[rustc_diagnostic_item = "Send"]
99#[diagnostic::on_unimplemented(
100 message = "`{Self}` cannot be sent between threads safely",
101 label = "`{Self}` cannot be sent between threads safely"
102)]
103pub unsafe auto trait Send {
104 // empty.
105}
106
107#[stable(feature = "rust1", since = "1.0.0")]
108impl<T: PointeeSized> !Send for *const T {}
109#[stable(feature = "rust1", since = "1.0.0")]
110impl<T: PointeeSized> !Send for *mut T {}
111
112// Most instances arise automatically, but this instance is needed to link up `T: Sync` with
113// `&T: Send` (and it also removes the unsound default instance `T Send` -> `&T: Send` that would
114// otherwise exist).
115#[stable(feature = "rust1", since = "1.0.0")]
116unsafe impl<T: Sync + PointeeSized> Send for &T {}
117
118/// Types with a constant size known at compile time.
119///
120/// All type parameters have an implicit bound of `Sized`. The special syntax
121/// `?Sized` can be used to remove this bound if it's not appropriate.
122///
123/// ```
124/// # #![allow(dead_code)]
125/// struct Foo<T>(T);
126/// struct Bar<T: ?Sized>(T);
127///
128/// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32]
129/// struct BarUse(Bar<[i32]>); // OK
130/// ```
131///
132/// The one exception is the implicit `Self` type of a trait. A trait does not
133/// have an implicit `Sized` bound as this is incompatible with [trait object]s
134/// where, by definition, the trait needs to work with all possible implementors,
135/// and thus could be any size.
136///
137/// Although Rust will let you bind `Sized` to a trait, you won't
138/// be able to use it to form a trait object later:
139///
140/// ```
141/// # #![allow(unused_variables)]
142/// trait Foo { }
143/// trait Bar: Sized { }
144///
145/// struct Impl;
146/// impl Foo for Impl { }
147/// impl Bar for Impl { }
148///
149/// let x: &dyn Foo = &Impl; // OK
150/// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot be made into an object
151/// ```
152///
153/// [trait object]: ../../book/ch17-02-trait-objects.html
154#[doc(alias = "?", alias = "?Sized")]
155#[stable(feature = "rust1", since = "1.0.0")]
156#[lang = "sized"]
157#[diagnostic::on_unimplemented(
158 message = "the size for values of type `{Self}` cannot be known at compilation time",
159 label = "doesn't have a size known at compile-time"
160)]
161#[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
162#[rustc_specialization_trait]
163#[rustc_deny_explicit_impl]
164#[rustc_do_not_implement_via_object]
165// `Sized` being coinductive, despite having supertraits, is okay as there are no user-written impls,
166// and we know that the supertraits are always implemented if the subtrait is just by looking at
167// the builtin impls.
168#[rustc_coinductive]
169pub trait Sized: MetaSized {
170 // Empty.
171}
172
173/// Types with a size that can be determined from pointer metadata.
174#[unstable(feature = "sized_hierarchy", issue = "none")]
175#[lang = "meta_sized"]
176#[diagnostic::on_unimplemented(
177 message = "the size for values of type `{Self}` cannot be known",
178 label = "doesn't have a known size"
179)]
180#[fundamental]
181#[rustc_specialization_trait]
182#[rustc_deny_explicit_impl]
183#[rustc_do_not_implement_via_object]
184// `MetaSized` being coinductive, despite having supertraits, is okay for the same reasons as
185// `Sized` above.
186#[rustc_coinductive]
187pub trait MetaSized: PointeeSized {
188 // Empty
189}
190
191/// Types that may or may not have a size.
192#[unstable(feature = "sized_hierarchy", issue = "none")]
193#[lang = "pointee_sized"]
194#[diagnostic::on_unimplemented(
195 message = "values of type `{Self}` may or may not have a size",
196 label = "may or may not have a known size"
197)]
198#[fundamental]
199#[rustc_specialization_trait]
200#[rustc_deny_explicit_impl]
201#[rustc_do_not_implement_via_object]
202#[rustc_coinductive]
203pub trait PointeeSized {
204 // Empty
205}
206
207/// Types that can be "unsized" to a dynamically-sized type.
208///
209/// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and
210/// `Unsize<dyn fmt::Debug>`.
211///
212/// All implementations of `Unsize` are provided automatically by the compiler.
213/// Those implementations are:
214///
215/// - Arrays `[T; N]` implement `Unsize<[T]>`.
216/// - A type implements `Unsize<dyn Trait + 'a>` if all of these conditions are met:
217/// - The type implements `Trait`.
218/// - `Trait` is dyn-compatible[^1].
219/// - The type is sized.
220/// - The type outlives `'a`.
221/// - Trait objects `dyn TraitA + AutoA... + 'a` implement `Unsize<dyn TraitB + AutoB... + 'b>`
222/// if all of these conditions are met:
223/// - `TraitB` is a supertrait of `TraitA`.
224/// - `AutoB...` is a subset of `AutoA...`.
225/// - `'a` outlives `'b`.
226/// - Structs `Foo<..., T1, ..., Tn, ...>` implement `Unsize<Foo<..., U1, ..., Un, ...>>`
227/// where any number of (type and const) parameters may be changed if all of these conditions
228/// are met:
229/// - Only the last field of `Foo` has a type involving the parameters `T1`, ..., `Tn`.
230/// - All other parameters of the struct are equal.
231/// - `Field<T1, ..., Tn>: Unsize<Field<U1, ..., Un>>`, where `Field<...>` stands for the actual
232/// type of the struct's last field.
233///
234/// `Unsize` is used along with [`ops::CoerceUnsized`] to allow
235/// "user-defined" containers such as [`Rc`] to contain dynamically-sized
236/// types. See the [DST coercion RFC][RFC982] and [the nomicon entry on coercion][nomicon-coerce]
237/// for more details.
238///
239/// [`ops::CoerceUnsized`]: crate::ops::CoerceUnsized
240/// [`Rc`]: ../../std/rc/struct.Rc.html
241/// [RFC982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
242/// [nomicon-coerce]: ../../nomicon/coercions.html
243/// [^1]: Formerly known as *object safe*.
244#[unstable(feature = "unsize", issue = "18598")]
245#[lang = "unsize"]
246#[rustc_deny_explicit_impl]
247#[rustc_do_not_implement_via_object]
248pub trait Unsize<T: PointeeSized>: PointeeSized {
249 // Empty.
250}
251
252/// Required trait for constants used in pattern matches.
253///
254/// Constants are only allowed as patterns if (a) their type implements
255/// `PartialEq`, and (b) interpreting the value of the constant as a pattern
256/// is equivalent to calling `PartialEq`. This ensures that constants used as
257/// patterns cannot expose implementation details in an unexpected way or
258/// cause semver hazards.
259///
260/// This trait ensures point (b).
261/// Any type that derives `PartialEq` automatically implements this trait.
262///
263/// Implementing this trait (which is unstable) is a way for type authors to explicitly allow
264/// comparing const values of this type; that operation will recursively compare all fields
265/// (including private fields), even if that behavior differs from `PartialEq`. This can make it
266/// semver-breaking to add further private fields to a type.
267#[unstable(feature = "structural_match", issue = "31434")]
268#[diagnostic::on_unimplemented(message = "the type `{Self}` does not `#[derive(PartialEq)]`")]
269#[lang = "structural_peq"]
270pub trait StructuralPartialEq {
271 // Empty.
272}
273
274marker_impls! {
275 #[unstable(feature = "structural_match", issue = "31434")]
276 StructuralPartialEq for
277 usize, u8, u16, u32, u64, u128,
278 isize, i8, i16, i32, i64, i128,
279 bool,
280 char,
281 str /* Technically requires `[u8]: StructuralPartialEq` */,
282 (),
283 {T, const N: usize} [T; N],
284 {T} [T],
285 {T: PointeeSized} &T,
286}
287
288/// Types whose values can be duplicated simply by copying bits.
289///
290/// By default, variable bindings have 'move semantics.' In other
291/// words:
292///
293/// ```
294/// #[derive(Debug)]
295/// struct Foo;
296///
297/// let x = Foo;
298///
299/// let y = x;
300///
301/// // `x` has moved into `y`, and so cannot be used
302///
303/// // println!("{x:?}"); // error: use of moved value
304/// ```
305///
306/// However, if a type implements `Copy`, it instead has 'copy semantics':
307///
308/// ```
309/// // We can derive a `Copy` implementation. `Clone` is also required, as it's
310/// // a supertrait of `Copy`.
311/// #[derive(Debug, Copy, Clone)]
312/// struct Foo;
313///
314/// let x = Foo;
315///
316/// let y = x;
317///
318/// // `y` is a copy of `x`
319///
320/// println!("{x:?}"); // A-OK!
321/// ```
322///
323/// It's important to note that in these two examples, the only difference is whether you
324/// are allowed to access `x` after the assignment. Under the hood, both a copy and a move
325/// can result in bits being copied in memory, although this is sometimes optimized away.
326///
327/// ## How can I implement `Copy`?
328///
329/// There are two ways to implement `Copy` on your type. The simplest is to use `derive`:
330///
331/// ```
332/// #[derive(Copy, Clone)]
333/// struct MyStruct;
334/// ```
335///
336/// You can also implement `Copy` and `Clone` manually:
337///
338/// ```
339/// struct MyStruct;
340///
341/// impl Copy for MyStruct { }
342///
343/// impl Clone for MyStruct {
344/// fn clone(&self) -> MyStruct {
345/// *self
346/// }
347/// }
348/// ```
349///
350/// There is a small difference between the two. The `derive` strategy will also place a `Copy`
351/// bound on type parameters:
352///
353/// ```
354/// #[derive(Clone)]
355/// struct MyStruct<T>(T);
356///
357/// impl<T: Copy> Copy for MyStruct<T> { }
358/// ```
359///
360/// This isn't always desired. For example, shared references (`&T`) can be copied regardless of
361/// whether `T` is `Copy`. Likewise, a generic struct containing markers such as [`PhantomData`]
362/// could potentially be duplicated with a bit-wise copy.
363///
364/// ## What's the difference between `Copy` and `Clone`?
365///
366/// Copies happen implicitly, for example as part of an assignment `y = x`. The behavior of
367/// `Copy` is not overloadable; it is always a simple bit-wise copy.
368///
369/// Cloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can
370/// provide any type-specific behavior necessary to duplicate values safely. For example,
371/// the implementation of [`Clone`] for [`String`] needs to copy the pointed-to string
372/// buffer in the heap. A simple bitwise copy of [`String`] values would merely copy the
373/// pointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`]
374/// but not `Copy`.
375///
376/// [`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement
377/// [`Clone`]. If a type is `Copy` then its [`Clone`] implementation only needs to return `*self`
378/// (see the example above).
379///
380/// ## When can my type be `Copy`?
381///
382/// A type can implement `Copy` if all of its components implement `Copy`. For example, this
383/// struct can be `Copy`:
384///
385/// ```
386/// # #[allow(dead_code)]
387/// #[derive(Copy, Clone)]
388/// struct Point {
389/// x: i32,
390/// y: i32,
391/// }
392/// ```
393///
394/// A struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`.
395/// By contrast, consider
396///
397/// ```
398/// # #![allow(dead_code)]
399/// # struct Point;
400/// struct PointList {
401/// points: Vec<Point>,
402/// }
403/// ```
404///
405/// The struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we
406/// attempt to derive a `Copy` implementation, we'll get an error:
407///
408/// ```text
409/// the trait `Copy` cannot be implemented for this type; field `points` does not implement `Copy`
410/// ```
411///
412/// Shared references (`&T`) are also `Copy`, so a type can be `Copy`, even when it holds
413/// shared references of types `T` that are *not* `Copy`. Consider the following struct,
414/// which can implement `Copy`, because it only holds a *shared reference* to our non-`Copy`
415/// type `PointList` from above:
416///
417/// ```
418/// # #![allow(dead_code)]
419/// # struct PointList;
420/// #[derive(Copy, Clone)]
421/// struct PointListWrapper<'a> {
422/// point_list_ref: &'a PointList,
423/// }
424/// ```
425///
426/// ## When *can't* my type be `Copy`?
427///
428/// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
429/// mutable reference. Copying [`String`] would duplicate responsibility for managing the
430/// [`String`]'s buffer, leading to a double free.
431///
432/// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's
433/// managing some resource besides its own [`size_of::<T>`] bytes.
434///
435/// If you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get
436/// the error [E0204].
437///
438/// [E0204]: ../../error_codes/E0204.html
439///
440/// ## When *should* my type be `Copy`?
441///
442/// Generally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though,
443/// that implementing `Copy` is part of the public API of your type. If the type might become
444/// non-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to
445/// avoid a breaking API change.
446///
447/// ## Additional implementors
448///
449/// In addition to the [implementors listed below][impls],
450/// the following types also implement `Copy`:
451///
452/// * Function item types (i.e., the distinct types defined for each function)
453/// * Function pointer types (e.g., `fn() -> i32`)
454/// * Closure types, if they capture no value from the environment
455/// or if all such captured values implement `Copy` themselves.
456/// Note that variables captured by shared reference always implement `Copy`
457/// (even if the referent doesn't),
458/// while variables captured by mutable reference never implement `Copy`.
459///
460/// [`Vec<T>`]: ../../std/vec/struct.Vec.html
461/// [`String`]: ../../std/string/struct.String.html
462/// [`size_of::<T>`]: size_of
463/// [impls]: #implementors
464#[stable(feature = "rust1", since = "1.0.0")]
465#[lang = "copy"]
466// This is unsound, but required by `hashbrown`
467// FIXME(joboet): change `hashbrown` to use `TrivialClone`
468#[rustc_unsafe_specialization_marker]
469#[rustc_diagnostic_item = "Copy"]
470pub trait Copy: Clone {
471 // Empty.
472}
473
474/// Derive macro generating an impl of the trait `Copy`.
475#[rustc_builtin_macro]
476#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
477#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
478pub macro Copy($item:item) {
479 /* compiler built-in */
480}
481
482// Implementations of `Copy` for primitive types.
483//
484// Implementations that cannot be described in Rust
485// are implemented in `traits::SelectionContext::copy_clone_conditions()`
486// in `rustc_trait_selection`.
487marker_impls! {
488 #[stable(feature = "rust1", since = "1.0.0")]
489 Copy for
490 usize, u8, u16, u32, u64, u128,
491 isize, i8, i16, i32, i64, i128,
492 f16, f32, f64, f128,
493 bool, char,
494 {T: PointeeSized} *const T,
495 {T: PointeeSized} *mut T,
496
497}
498
499#[unstable(feature = "never_type", issue = "35121")]
500impl Copy for ! {}
501
502/// Shared references can be copied, but mutable references *cannot*!
503#[stable(feature = "rust1", since = "1.0.0")]
504impl<T: PointeeSized> Copy for &T {}
505
506/// Marker trait for the types that are allowed in union fields and unsafe
507/// binder types.
508///
509/// Implemented for:
510/// * `&T`, `&mut T` for all `T`,
511/// * `ManuallyDrop<T>` for all `T`,
512/// * tuples and arrays whose elements implement `BikeshedGuaranteedNoDrop`,
513/// * or otherwise, all types that are `Copy`.
514///
515/// Notably, this doesn't include all trivially-destructible types for semver
516/// reasons.
517///
518/// Bikeshed name for now. This trait does not do anything other than reflect the
519/// set of types that are allowed within unions for field validity.
520#[unstable(feature = "bikeshed_guaranteed_no_drop", issue = "none")]
521#[lang = "bikeshed_guaranteed_no_drop"]
522#[rustc_deny_explicit_impl]
523#[rustc_do_not_implement_via_object]
524#[doc(hidden)]
525pub trait BikeshedGuaranteedNoDrop {}
526
527/// Types for which it is safe to share references between threads.
528///
529/// This trait is automatically implemented when the compiler determines
530/// it's appropriate.
531///
532/// The precise definition is: a type `T` is [`Sync`] if and only if `&T` is
533/// [`Send`]. In other words, if there is no possibility of
534/// [undefined behavior][ub] (including data races) when passing
535/// `&T` references between threads.
536///
537/// As one would expect, primitive types like [`u8`] and [`f64`]
538/// are all [`Sync`], and so are simple aggregate types containing them,
539/// like tuples, structs and enums. More examples of basic [`Sync`]
540/// types include "immutable" types like `&T`, and those with simple
541/// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and
542/// most other collection types. (Generic parameters need to be [`Sync`]
543/// for their container to be [`Sync`].)
544///
545/// A somewhat surprising consequence of the definition is that `&mut T`
546/// is `Sync` (if `T` is `Sync`) even though it seems like that might
547/// provide unsynchronized mutation. The trick is that a mutable
548/// reference behind a shared reference (that is, `& &mut T`)
549/// becomes read-only, as if it were a `& &T`. Hence there is no risk
550/// of a data race.
551///
552/// A shorter overview of how [`Sync`] and [`Send`] relate to referencing:
553/// * `&T` is [`Send`] if and only if `T` is [`Sync`]
554/// * `&mut T` is [`Send`] if and only if `T` is [`Send`]
555/// * `&T` and `&mut T` are [`Sync`] if and only if `T` is [`Sync`]
556///
557/// Types that are not `Sync` are those that have "interior
558/// mutability" in a non-thread-safe form, such as [`Cell`][cell]
559/// and [`RefCell`][refcell]. These types allow for mutation of
560/// their contents even through an immutable, shared reference. For
561/// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires
562/// only a shared reference [`&Cell<T>`][cell]. The method performs no
563/// synchronization, thus [`Cell`][cell] cannot be `Sync`.
564///
565/// Another example of a non-`Sync` type is the reference-counting
566/// pointer [`Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone
567/// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.
568///
569/// For cases when one does need thread-safe interior mutability,
570/// Rust provides [atomic data types], as well as explicit locking via
571/// [`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types
572/// ensure that any mutation cannot cause data races, hence the types
573/// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe
574/// analogue of [`Rc`][rc].
575///
576/// Any types with interior mutability must also use the
577/// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which
578/// can be mutated through a shared reference. Failing to doing this is
579/// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing
580/// from `&T` to `&mut T` is invalid.
581///
582/// See [the Nomicon][nomicon-send-and-sync] for more details about `Sync`.
583///
584/// [box]: ../../std/boxed/struct.Box.html
585/// [vec]: ../../std/vec/struct.Vec.html
586/// [cell]: crate::cell::Cell
587/// [refcell]: crate::cell::RefCell
588/// [rc]: ../../std/rc/struct.Rc.html
589/// [arc]: ../../std/sync/struct.Arc.html
590/// [atomic data types]: crate::sync::atomic
591/// [mutex]: ../../std/sync/struct.Mutex.html
592/// [rwlock]: ../../std/sync/struct.RwLock.html
593/// [unsafecell]: crate::cell::UnsafeCell
594/// [ub]: ../../reference/behavior-considered-undefined.html
595/// [transmute]: crate::mem::transmute
596/// [nomicon-send-and-sync]: ../../nomicon/send-and-sync.html
597#[stable(feature = "rust1", since = "1.0.0")]
598#[rustc_diagnostic_item = "Sync"]
599#[lang = "sync"]
600#[rustc_on_unimplemented(
601 on(
602 Self = "core::cell::once::OnceCell<T>",
603 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::OnceLock` instead"
604 ),
605 on(
606 Self = "core::cell::Cell<u8>",
607 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU8` instead",
608 ),
609 on(
610 Self = "core::cell::Cell<u16>",
611 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU16` instead",
612 ),
613 on(
614 Self = "core::cell::Cell<u32>",
615 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU32` instead",
616 ),
617 on(
618 Self = "core::cell::Cell<u64>",
619 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU64` instead",
620 ),
621 on(
622 Self = "core::cell::Cell<usize>",
623 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicUsize` instead",
624 ),
625 on(
626 Self = "core::cell::Cell<i8>",
627 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI8` instead",
628 ),
629 on(
630 Self = "core::cell::Cell<i16>",
631 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI16` instead",
632 ),
633 on(
634 Self = "core::cell::Cell<i32>",
635 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead",
636 ),
637 on(
638 Self = "core::cell::Cell<i64>",
639 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI64` instead",
640 ),
641 on(
642 Self = "core::cell::Cell<isize>",
643 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicIsize` instead",
644 ),
645 on(
646 Self = "core::cell::Cell<bool>",
647 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicBool` instead",
648 ),
649 on(
650 all(
651 Self = "core::cell::Cell<T>",
652 not(Self = "core::cell::Cell<u8>"),
653 not(Self = "core::cell::Cell<u16>"),
654 not(Self = "core::cell::Cell<u32>"),
655 not(Self = "core::cell::Cell<u64>"),
656 not(Self = "core::cell::Cell<usize>"),
657 not(Self = "core::cell::Cell<i8>"),
658 not(Self = "core::cell::Cell<i16>"),
659 not(Self = "core::cell::Cell<i32>"),
660 not(Self = "core::cell::Cell<i64>"),
661 not(Self = "core::cell::Cell<isize>"),
662 not(Self = "core::cell::Cell<bool>")
663 ),
664 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock`",
665 ),
666 on(
667 Self = "core::cell::RefCell<T>",
668 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead",
669 ),
670 message = "`{Self}` cannot be shared between threads safely",
671 label = "`{Self}` cannot be shared between threads safely"
672)]
673pub unsafe auto trait Sync {
674 // FIXME(estebank): once support to add notes in `rustc_on_unimplemented`
675 // lands in beta, and it has been extended to check whether a closure is
676 // anywhere in the requirement chain, extend it as such (#48534):
677 // ```
678 // on(
679 // closure,
680 // note="`{Self}` cannot be shared safely, consider marking the closure `move`"
681 // ),
682 // ```
683
684 // Empty
685}
686
687#[stable(feature = "rust1", since = "1.0.0")]
688#[cfg(not(feature = "ferrocene_certified"))]
689impl<T: PointeeSized> !Sync for *const T {}
690#[stable(feature = "rust1", since = "1.0.0")]
691#[cfg(not(feature = "ferrocene_certified"))]
692impl<T: PointeeSized> !Sync for *mut T {}
693
694/// Zero-sized type used to mark things that "act like" they own a `T`.
695///
696/// Adding a `PhantomData<T>` field to your type tells the compiler that your
697/// type acts as though it stores a value of type `T`, even though it doesn't
698/// really. This information is used when computing certain safety properties.
699///
700/// For a more in-depth explanation of how to use `PhantomData<T>`, please see
701/// [the Nomicon](../../nomicon/phantom-data.html).
702///
703/// # A ghastly note 👻👻👻
704///
705/// Though they both have scary names, `PhantomData` and 'phantom types' are
706/// related, but not identical. A phantom type parameter is simply a type
707/// parameter which is never used. In Rust, this often causes the compiler to
708/// complain, and the solution is to add a "dummy" use by way of `PhantomData`.
709///
710/// # Examples
711///
712/// ## Unused lifetime parameters
713///
714/// Perhaps the most common use case for `PhantomData` is a struct that has an
715/// unused lifetime parameter, typically as part of some unsafe code. For
716/// example, here is a struct `Slice` that has two pointers of type `*const T`,
717/// presumably pointing into an array somewhere:
718///
719/// ```compile_fail,E0392
720/// struct Slice<'a, T> {
721/// start: *const T,
722/// end: *const T,
723/// }
724/// ```
725///
726/// The intention is that the underlying data is only valid for the
727/// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
728/// intent is not expressed in the code, since there are no uses of
729/// the lifetime `'a` and hence it is not clear what data it applies
730/// to. We can correct this by telling the compiler to act *as if* the
731/// `Slice` struct contained a reference `&'a T`:
732///
733/// ```
734/// use std::marker::PhantomData;
735///
736/// # #[allow(dead_code)]
737/// struct Slice<'a, T> {
738/// start: *const T,
739/// end: *const T,
740/// phantom: PhantomData<&'a T>,
741/// }
742/// ```
743///
744/// This also in turn infers the lifetime bound `T: 'a`, indicating
745/// that any references in `T` are valid over the lifetime `'a`.
746///
747/// When initializing a `Slice` you simply provide the value
748/// `PhantomData` for the field `phantom`:
749///
750/// ```
751/// # #![allow(dead_code)]
752/// # use std::marker::PhantomData;
753/// # struct Slice<'a, T> {
754/// # start: *const T,
755/// # end: *const T,
756/// # phantom: PhantomData<&'a T>,
757/// # }
758/// fn borrow_vec<T>(vec: &Vec<T>) -> Slice<'_, T> {
759/// let ptr = vec.as_ptr();
760/// Slice {
761/// start: ptr,
762/// end: unsafe { ptr.add(vec.len()) },
763/// phantom: PhantomData,
764/// }
765/// }
766/// ```
767///
768/// ## Unused type parameters
769///
770/// It sometimes happens that you have unused type parameters which
771/// indicate what type of data a struct is "tied" to, even though that
772/// data is not actually found in the struct itself. Here is an
773/// example where this arises with [FFI]. The foreign interface uses
774/// handles of type `*mut ()` to refer to Rust values of different
775/// types. We track the Rust type using a phantom type parameter on
776/// the struct `ExternalResource` which wraps a handle.
777///
778/// [FFI]: ../../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
779///
780/// ```
781/// # #![allow(dead_code)]
782/// # trait ResType { }
783/// # struct ParamType;
784/// # mod foreign_lib {
785/// # pub fn new(_: usize) -> *mut () { 42 as *mut () }
786/// # pub fn do_stuff(_: *mut (), _: usize) {}
787/// # }
788/// # fn convert_params(_: ParamType) -> usize { 42 }
789/// use std::marker::PhantomData;
790///
791/// struct ExternalResource<R> {
792/// resource_handle: *mut (),
793/// resource_type: PhantomData<R>,
794/// }
795///
796/// impl<R: ResType> ExternalResource<R> {
797/// fn new() -> Self {
798/// let size_of_res = size_of::<R>();
799/// Self {
800/// resource_handle: foreign_lib::new(size_of_res),
801/// resource_type: PhantomData,
802/// }
803/// }
804///
805/// fn do_stuff(&self, param: ParamType) {
806/// let foreign_params = convert_params(param);
807/// foreign_lib::do_stuff(self.resource_handle, foreign_params);
808/// }
809/// }
810/// ```
811///
812/// ## Ownership and the drop check
813///
814/// The exact interaction of `PhantomData` with drop check **may change in the future**.
815///
816/// Currently, adding a field of type `PhantomData<T>` indicates that your type *owns* data of type
817/// `T` in very rare circumstances. This in turn has effects on the Rust compiler's [drop check]
818/// analysis. For the exact rules, see the [drop check] documentation.
819///
820/// ## Layout
821///
822/// For all `T`, the following are guaranteed:
823/// * `size_of::<PhantomData<T>>() == 0`
824/// * `align_of::<PhantomData<T>>() == 1`
825///
826/// [drop check]: Drop#drop-check
827#[lang = "phantom_data"]
828#[stable(feature = "rust1", since = "1.0.0")]
829pub struct PhantomData<T: PointeeSized>;
830
831#[stable(feature = "rust1", since = "1.0.0")]
832#[cfg(not(feature = "ferrocene_certified"))]
833impl<T: PointeeSized> Hash for PhantomData<T> {
834 #[inline]
835 fn hash<H: Hasher>(&self, _: &mut H) {}
836}
837
838#[stable(feature = "rust1", since = "1.0.0")]
839#[cfg(not(feature = "ferrocene_certified"))]
840impl<T: PointeeSized> cmp::PartialEq for PhantomData<T> {
841 fn eq(&self, _other: &PhantomData<T>) -> bool {
842 true
843 }
844}
845
846#[stable(feature = "rust1", since = "1.0.0")]
847#[cfg(not(feature = "ferrocene_certified"))]
848impl<T: PointeeSized> cmp::Eq for PhantomData<T> {}
849
850#[stable(feature = "rust1", since = "1.0.0")]
851#[cfg(not(feature = "ferrocene_certified"))]
852impl<T: PointeeSized> cmp::PartialOrd for PhantomData<T> {
853 fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<cmp::Ordering> {
854 Option::Some(cmp::Ordering::Equal)
855 }
856}
857
858#[stable(feature = "rust1", since = "1.0.0")]
859#[cfg(not(feature = "ferrocene_certified"))]
860impl<T: PointeeSized> cmp::Ord for PhantomData<T> {
861 fn cmp(&self, _other: &PhantomData<T>) -> cmp::Ordering {
862 cmp::Ordering::Equal
863 }
864}
865
866#[stable(feature = "rust1", since = "1.0.0")]
867#[cfg(not(feature = "ferrocene_certified"))]
868impl<T: PointeeSized> Copy for PhantomData<T> {}
869
870#[stable(feature = "rust1", since = "1.0.0")]
871#[cfg(not(feature = "ferrocene_certified"))]
872impl<T: PointeeSized> Clone for PhantomData<T> {
873 fn clone(&self) -> Self {
874 Self
875 }
876}
877
878#[cfg(not(feature = "ferrocene_certified"))]
879#[doc(hidden)]
880#[unstable(feature = "trivial_clone", issue = "none")]
881unsafe impl<T: ?Sized> TrivialClone for PhantomData<T> {}
882
883#[stable(feature = "rust1", since = "1.0.0")]
884#[rustc_const_unstable(feature = "const_default", issue = "143894")]
885#[cfg(not(feature = "ferrocene_certified"))]
886impl<T: PointeeSized> const Default for PhantomData<T> {
887 fn default() -> Self {
888 Self
889 }
890}
891
892#[unstable(feature = "structural_match", issue = "31434")]
893#[cfg(not(feature = "ferrocene_certified"))]
894impl<T: PointeeSized> StructuralPartialEq for PhantomData<T> {}
895
896/// Compiler-internal trait used to indicate the type of enum discriminants.
897///
898/// This trait is automatically implemented for every type and does not add any
899/// guarantees to [`mem::Discriminant`]. It is **undefined behavior** to transmute
900/// between `DiscriminantKind::Discriminant` and `mem::Discriminant`.
901///
902/// [`mem::Discriminant`]: crate::mem::Discriminant
903#[unstable(
904 feature = "discriminant_kind",
905 issue = "none",
906 reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead"
907)]
908#[lang = "discriminant_kind"]
909#[rustc_deny_explicit_impl]
910#[rustc_do_not_implement_via_object]
911pub trait DiscriminantKind {
912 /// The type of the discriminant, which must satisfy the trait
913 /// bounds required by `mem::Discriminant`.
914 #[lang = "discriminant_type"]
915 #[cfg(not(feature = "ferrocene_certified"))]
916 type Discriminant: Clone + Copy + Debug + Eq + PartialEq + Hash + Send + Sync + Unpin;
917 /// The type of the discriminant, which must satisfy the trait
918 /// bounds required by `mem::Discriminant`.
919 #[lang = "discriminant_type"]
920 #[cfg(feature = "ferrocene_certified")]
921 type Discriminant: Clone + Copy + /* Debug */ Eq + PartialEq + /* Hash */ Send + Sync + Unpin;
922}
923
924/// Used to determine whether a type contains
925/// any `UnsafeCell` internally, but not through an indirection.
926/// This affects, for example, whether a `static` of that type is
927/// placed in read-only static memory or writable static memory.
928/// This can be used to declare that a constant with a generic type
929/// will not contain interior mutability, and subsequently allow
930/// placing the constant behind references.
931///
932/// # Safety
933///
934/// This trait is a core part of the language, it is just expressed as a trait in libcore for
935/// convenience. Do *not* implement it for other types.
936// FIXME: Eventually this trait should become `#[rustc_deny_explicit_impl]`.
937// That requires porting the impls below to native internal impls.
938#[lang = "freeze"]
939#[unstable(feature = "freeze", issue = "121675")]
940pub unsafe auto trait Freeze {}
941
942#[unstable(feature = "freeze", issue = "121675")]
943#[cfg(not(feature = "ferrocene_certified"))]
944impl<T: PointeeSized> !Freeze for UnsafeCell<T> {}
945marker_impls! {
946 #[unstable(feature = "freeze", issue = "121675")]
947 unsafe Freeze for
948 {T: PointeeSized} PhantomData<T>,
949 {T: PointeeSized} *const T,
950 {T: PointeeSized} *mut T,
951 {T: PointeeSized} &T,
952 {T: PointeeSized} &mut T,
953}
954
955/// Used to determine whether a type contains any `UnsafePinned` (or `PhantomPinned`) internally,
956/// but not through an indirection. This affects, for example, whether we emit `noalias` metadata
957/// for `&mut T` or not.
958///
959/// This is part of [RFC 3467](https://rust-lang.github.io/rfcs/3467-unsafe-pinned.html), and is
960/// tracked by [#125735](https://github.com/rust-lang/rust/issues/125735).
961#[lang = "unsafe_unpin"]
962#[cfg(not(feature = "ferrocene_certified"))]
963pub(crate) unsafe auto trait UnsafeUnpin {}
964
965#[cfg(not(feature = "ferrocene_certified"))]
966impl<T: ?Sized> !UnsafeUnpin for UnsafePinned<T> {}
967#[cfg(not(feature = "ferrocene_certified"))]
968unsafe impl<T: ?Sized> UnsafeUnpin for PhantomData<T> {}
969#[cfg(not(feature = "ferrocene_certified"))]
970unsafe impl<T: ?Sized> UnsafeUnpin for *const T {}
971#[cfg(not(feature = "ferrocene_certified"))]
972unsafe impl<T: ?Sized> UnsafeUnpin for *mut T {}
973#[cfg(not(feature = "ferrocene_certified"))]
974unsafe impl<T: ?Sized> UnsafeUnpin for &T {}
975#[cfg(not(feature = "ferrocene_certified"))]
976unsafe impl<T: ?Sized> UnsafeUnpin for &mut T {}
977
978/// Types that do not require any pinning guarantees.
979///
980/// For information on what "pinning" is, see the [`pin` module] documentation.
981///
982/// Implementing the `Unpin` trait for `T` expresses the fact that `T` is pinning-agnostic:
983/// it shall not expose nor rely on any pinning guarantees. This, in turn, means that a
984/// `Pin`-wrapped pointer to such a type can feature a *fully unrestricted* API.
985/// In other words, if `T: Unpin`, a value of type `T` will *not* be bound by the invariants
986/// which pinning otherwise offers, even when "pinned" by a [`Pin<Ptr>`] pointing at it.
987/// When a value of type `T` is pointed at by a [`Pin<Ptr>`], [`Pin`] will not restrict access
988/// to the pointee value like it normally would, thus allowing the user to do anything that they
989/// normally could with a non-[`Pin`]-wrapped `Ptr` to that value.
990///
991/// The idea of this trait is to alleviate the reduced ergonomics of APIs that require the use
992/// of [`Pin`] for soundness for some types, but which also want to be used by other types that
993/// don't care about pinning. The prime example of such an API is [`Future::poll`]. There are many
994/// [`Future`] types that don't care about pinning. These futures can implement `Unpin` and
995/// therefore get around the pinning related restrictions in the API, while still allowing the
996/// subset of [`Future`]s which *do* require pinning to be implemented soundly.
997///
998/// For more discussion on the consequences of [`Unpin`] within the wider scope of the pinning
999/// system, see the [section about `Unpin`] in the [`pin` module].
1000///
1001/// `Unpin` has no consequence at all for non-pinned data. In particular, [`mem::replace`] happily
1002/// moves `!Unpin` data, which would be immovable when pinned ([`mem::replace`] works for any
1003/// `&mut T`, not just when `T: Unpin`).
1004///
1005/// *However*, you cannot use [`mem::replace`] on `!Unpin` data which is *pinned* by being wrapped
1006/// inside a [`Pin<Ptr>`] pointing at it. This is because you cannot (safely) use a
1007/// [`Pin<Ptr>`] to get a `&mut T` to its pointee value, which you would need to call
1008/// [`mem::replace`], and *that* is what makes this system work.
1009///
1010/// So this, for example, can only be done on types implementing `Unpin`:
1011///
1012/// ```rust
1013/// # #![allow(unused_must_use)]
1014/// use std::mem;
1015/// use std::pin::Pin;
1016///
1017/// let mut string = "this".to_string();
1018/// let mut pinned_string = Pin::new(&mut string);
1019///
1020/// // We need a mutable reference to call `mem::replace`.
1021/// // We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`,
1022/// // but that is only possible because `String` implements `Unpin`.
1023/// mem::replace(&mut *pinned_string, "other".to_string());
1024/// ```
1025///
1026/// This trait is automatically implemented for almost every type. The compiler is free
1027/// to take the conservative stance of marking types as [`Unpin`] so long as all of the types that
1028/// compose its fields are also [`Unpin`]. This is because if a type implements [`Unpin`], then it
1029/// is unsound for that type's implementation to rely on pinning-related guarantees for soundness,
1030/// *even* when viewed through a "pinning" pointer! It is the responsibility of the implementor of
1031/// a type that relies upon pinning for soundness to ensure that type is *not* marked as [`Unpin`]
1032/// by adding [`PhantomPinned`] field. For more details, see the [`pin` module] docs.
1033///
1034/// [`mem::replace`]: crate::mem::replace "mem replace"
1035/// [`Future`]: crate::future::Future "Future"
1036/// [`Future::poll`]: crate::future::Future::poll "Future poll"
1037/// [`Pin`]: crate::pin::Pin "Pin"
1038/// [`Pin<Ptr>`]: crate::pin::Pin "Pin"
1039/// [`pin` module]: crate::pin "pin module"
1040/// [section about `Unpin`]: crate::pin#unpin "pin module docs about unpin"
1041/// [`unsafe`]: ../../std/keyword.unsafe.html "keyword unsafe"
1042#[stable(feature = "pin", since = "1.33.0")]
1043#[diagnostic::on_unimplemented(
1044 note = "consider using the `pin!` macro\nconsider using `Box::pin` if you need to access the pinned value outside of the current scope",
1045 message = "`{Self}` cannot be unpinned"
1046)]
1047#[lang = "unpin"]
1048pub auto trait Unpin {}
1049
1050/// A marker type which does not implement `Unpin`.
1051///
1052/// If a type contains a `PhantomPinned`, it will not implement `Unpin` by default.
1053//
1054// FIXME(unsafe_pinned): This is *not* a stable guarantee we want to make, at least not yet.
1055// Note that for backwards compatibility with the new [`UnsafePinned`] wrapper type, placing this
1056// marker in your struct acts as if you wrapped the entire struct in an `UnsafePinned`. This type
1057// will likely eventually be deprecated, and all new code should be using `UnsafePinned` instead.
1058#[stable(feature = "pin", since = "1.33.0")]
1059#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1060#[cfg(not(feature = "ferrocene_certified"))]
1061pub struct PhantomPinned;
1062
1063#[stable(feature = "pin", since = "1.33.0")]
1064#[cfg(not(feature = "ferrocene_certified"))]
1065impl !Unpin for PhantomPinned {}
1066
1067// This is a small hack to allow existing code which uses PhantomPinned to opt-out of noalias to
1068// continue working. Ideally PhantomPinned could just wrap an `UnsafePinned<()>` to get the same
1069// effect, but we can't add a new field to an already stable unit struct -- that would be a breaking
1070// change.
1071#[cfg(not(feature = "ferrocene_certified"))]
1072impl !UnsafeUnpin for PhantomPinned {}
1073
1074#[cfg(not(feature = "ferrocene_certified"))]
1075marker_impls! {
1076 #[stable(feature = "pin", since = "1.33.0")]
1077 Unpin for
1078 {T: PointeeSized} &T,
1079 {T: PointeeSized} &mut T,
1080}
1081
1082#[cfg(not(feature = "ferrocene_certified"))]
1083marker_impls! {
1084 #[stable(feature = "pin_raw", since = "1.38.0")]
1085 Unpin for
1086 {T: PointeeSized} *const T,
1087 {T: PointeeSized} *mut T,
1088}
1089
1090/// A marker for types that can be dropped.
1091///
1092/// This should be used for `[const]` bounds,
1093/// as non-const bounds will always hold for every type.
1094#[unstable(feature = "const_destruct", issue = "133214")]
1095#[rustc_const_unstable(feature = "const_destruct", issue = "133214")]
1096#[lang = "destruct"]
1097#[rustc_on_unimplemented(message = "can't drop `{Self}`", append_const_msg)]
1098#[rustc_deny_explicit_impl]
1099#[rustc_do_not_implement_via_object]
1100pub const trait Destruct: PointeeSized {}
1101
1102/// A marker for tuple types.
1103///
1104/// The implementation of this trait is built-in and cannot be implemented
1105/// for any user type.
1106#[unstable(feature = "tuple_trait", issue = "none")]
1107#[lang = "tuple_trait"]
1108#[diagnostic::on_unimplemented(message = "`{Self}` is not a tuple")]
1109#[rustc_deny_explicit_impl]
1110#[rustc_do_not_implement_via_object]
1111pub trait Tuple {}
1112
1113/// A marker for types which can be used as types of `const` generic parameters.
1114///
1115/// These types must have a proper equivalence relation (`Eq`) and it must be automatically
1116/// derived (`StructuralPartialEq`). There's a hard-coded check in the compiler ensuring
1117/// that all fields are also `ConstParamTy`, which implies that recursively, all fields
1118/// are `StructuralPartialEq`.
1119#[lang = "const_param_ty"]
1120#[unstable(feature = "unsized_const_params", issue = "95174")]
1121#[diagnostic::on_unimplemented(message = "`{Self}` can't be used as a const parameter type")]
1122#[allow(multiple_supertrait_upcastable)]
1123// We name this differently than the derive macro so that the `adt_const_params` can
1124// be used independently of `unsized_const_params` without requiring a full path
1125// to the derive macro every time it is used. This should be renamed on stabilization.
1126pub trait ConstParamTy_: StructuralPartialEq + Eq {}
1127
1128/// Derive macro generating an impl of the trait `ConstParamTy`.
1129#[rustc_builtin_macro]
1130#[allow_internal_unstable(unsized_const_params)]
1131#[unstable(feature = "adt_const_params", issue = "95174")]
1132pub macro ConstParamTy($item:item) {
1133 /* compiler built-in */
1134}
1135
1136// FIXME(adt_const_params): handle `ty::FnDef`/`ty::Closure`
1137marker_impls! {
1138 #[unstable(feature = "adt_const_params", issue = "95174")]
1139 ConstParamTy_ for
1140 usize, u8, u16, u32, u64, u128,
1141 isize, i8, i16, i32, i64, i128,
1142 bool,
1143 char,
1144 (),
1145 {T: ConstParamTy_, const N: usize} [T; N],
1146}
1147
1148#[cfg(not(feature = "ferrocene_certified"))]
1149marker_impls! {
1150 #[unstable(feature = "unsized_const_params", issue = "95174")]
1151 #[unstable_feature_bound(unsized_const_params)]
1152 ConstParamTy_ for
1153 str,
1154 {T: ConstParamTy_} [T],
1155 {T: ConstParamTy_ + ?Sized} &T,
1156}
1157
1158/// A common trait implemented by all function pointers.
1159//
1160// Note that while the trait is internal and unstable it is nevertheless
1161// exposed as a public bound of the stable `core::ptr::fn_addr_eq` function.
1162#[unstable(
1163 feature = "fn_ptr_trait",
1164 issue = "none",
1165 reason = "internal trait for implementing various traits for all function pointers"
1166)]
1167#[lang = "fn_ptr_trait"]
1168#[rustc_deny_explicit_impl]
1169#[rustc_do_not_implement_via_object]
1170#[cfg(not(feature = "ferrocene_certified"))]
1171pub trait FnPtr: Copy + Clone {
1172 /// Returns the address of the function pointer.
1173 #[lang = "fn_ptr_addr"]
1174 fn addr(self) -> *const ();
1175}
1176
1177/// Derive macro that makes a smart pointer usable with trait objects.
1178///
1179/// # What this macro does
1180///
1181/// This macro is intended to be used with user-defined pointer types, and makes it possible to
1182/// perform coercions on the pointee of the user-defined pointer. There are two aspects to this:
1183///
1184/// ## Unsizing coercions of the pointee
1185///
1186/// By using the macro, the following example will compile:
1187/// ```
1188/// #![feature(derive_coerce_pointee)]
1189/// use std::marker::CoercePointee;
1190/// use std::ops::Deref;
1191///
1192/// #[derive(CoercePointee)]
1193/// #[repr(transparent)]
1194/// struct MySmartPointer<T: ?Sized>(Box<T>);
1195///
1196/// impl<T: ?Sized> Deref for MySmartPointer<T> {
1197/// type Target = T;
1198/// fn deref(&self) -> &T {
1199/// &self.0
1200/// }
1201/// }
1202///
1203/// trait MyTrait {}
1204///
1205/// impl MyTrait for i32 {}
1206///
1207/// fn main() {
1208/// let ptr: MySmartPointer<i32> = MySmartPointer(Box::new(4));
1209///
1210/// // This coercion would be an error without the derive.
1211/// let ptr: MySmartPointer<dyn MyTrait> = ptr;
1212/// }
1213/// ```
1214/// Without the `#[derive(CoercePointee)]` macro, this example would fail with the following error:
1215/// ```text
1216/// error[E0308]: mismatched types
1217/// --> src/main.rs:11:44
1218/// |
1219/// 11 | let ptr: MySmartPointer<dyn MyTrait> = ptr;
1220/// | --------------------------- ^^^ expected `MySmartPointer<dyn MyTrait>`, found `MySmartPointer<i32>`
1221/// | |
1222/// | expected due to this
1223/// |
1224/// = note: expected struct `MySmartPointer<dyn MyTrait>`
1225/// found struct `MySmartPointer<i32>`
1226/// = help: `i32` implements `MyTrait` so you could box the found value and coerce it to the trait object `Box<dyn MyTrait>`, you will have to change the expected type as well
1227/// ```
1228///
1229/// ## Dyn compatibility
1230///
1231/// This macro allows you to dispatch on the user-defined pointer type. That is, traits using the
1232/// type as a receiver are dyn-compatible. For example, this compiles:
1233///
1234/// ```
1235/// #![feature(arbitrary_self_types, derive_coerce_pointee)]
1236/// use std::marker::CoercePointee;
1237/// use std::ops::Deref;
1238///
1239/// #[derive(CoercePointee)]
1240/// #[repr(transparent)]
1241/// struct MySmartPointer<T: ?Sized>(Box<T>);
1242///
1243/// impl<T: ?Sized> Deref for MySmartPointer<T> {
1244/// type Target = T;
1245/// fn deref(&self) -> &T {
1246/// &self.0
1247/// }
1248/// }
1249///
1250/// // You can always define this trait. (as long as you have #![feature(arbitrary_self_types)])
1251/// trait MyTrait {
1252/// fn func(self: MySmartPointer<Self>);
1253/// }
1254///
1255/// // But using `dyn MyTrait` requires #[derive(CoercePointee)].
1256/// fn call_func(value: MySmartPointer<dyn MyTrait>) {
1257/// value.func();
1258/// }
1259/// ```
1260/// If you remove the `#[derive(CoercePointee)]` annotation from the struct, then the above example
1261/// will fail with this error message:
1262/// ```text
1263/// error[E0038]: the trait `MyTrait` is not dyn compatible
1264/// --> src/lib.rs:21:36
1265/// |
1266/// 17 | fn func(self: MySmartPointer<Self>);
1267/// | -------------------- help: consider changing method `func`'s `self` parameter to be `&self`: `&Self`
1268/// ...
1269/// 21 | fn call_func(value: MySmartPointer<dyn MyTrait>) {
1270/// | ^^^^^^^^^^^ `MyTrait` is not dyn compatible
1271/// |
1272/// note: for a trait to be dyn compatible it needs to allow building a vtable
1273/// for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
1274/// --> src/lib.rs:17:19
1275/// |
1276/// 16 | trait MyTrait {
1277/// | ------- this trait is not dyn compatible...
1278/// 17 | fn func(self: MySmartPointer<Self>);
1279/// | ^^^^^^^^^^^^^^^^^^^^ ...because method `func`'s `self` parameter cannot be dispatched on
1280/// ```
1281///
1282/// # Requirements for using the macro
1283///
1284/// This macro can only be used if:
1285/// * The type is a `#[repr(transparent)]` struct.
1286/// * The type of its non-zero-sized field must either be a standard library pointer type
1287/// (reference, raw pointer, `NonNull`, `Box`, `Rc`, `Arc`, etc.) or another user-defined type
1288/// also using the `#[derive(CoercePointee)]` macro.
1289/// * Zero-sized fields must not mention any generic parameters unless the zero-sized field has
1290/// type [`PhantomData`].
1291///
1292/// ## Multiple type parameters
1293///
1294/// If the type has multiple type parameters, then you must explicitly specify which one should be
1295/// used for dynamic dispatch. For example:
1296/// ```
1297/// # #![feature(derive_coerce_pointee)]
1298/// # use std::marker::{CoercePointee, PhantomData};
1299/// #[derive(CoercePointee)]
1300/// #[repr(transparent)]
1301/// struct MySmartPointer<#[pointee] T: ?Sized, U> {
1302/// ptr: Box<T>,
1303/// _phantom: PhantomData<U>,
1304/// }
1305/// ```
1306/// Specifying `#[pointee]` when the struct has only one type parameter is allowed, but not required.
1307///
1308/// # Examples
1309///
1310/// A custom implementation of the `Rc` type:
1311/// ```
1312/// #![feature(derive_coerce_pointee)]
1313/// use std::marker::CoercePointee;
1314/// use std::ops::Deref;
1315/// use std::ptr::NonNull;
1316///
1317/// #[derive(CoercePointee)]
1318/// #[repr(transparent)]
1319/// pub struct Rc<T: ?Sized> {
1320/// inner: NonNull<RcInner<T>>,
1321/// }
1322///
1323/// struct RcInner<T: ?Sized> {
1324/// refcount: usize,
1325/// value: T,
1326/// }
1327///
1328/// impl<T: ?Sized> Deref for Rc<T> {
1329/// type Target = T;
1330/// fn deref(&self) -> &T {
1331/// let ptr = self.inner.as_ptr();
1332/// unsafe { &(*ptr).value }
1333/// }
1334/// }
1335///
1336/// impl<T> Rc<T> {
1337/// pub fn new(value: T) -> Self {
1338/// let inner = Box::new(RcInner {
1339/// refcount: 1,
1340/// value,
1341/// });
1342/// Self {
1343/// inner: NonNull::from(Box::leak(inner)),
1344/// }
1345/// }
1346/// }
1347///
1348/// impl<T: ?Sized> Clone for Rc<T> {
1349/// fn clone(&self) -> Self {
1350/// // A real implementation would handle overflow here.
1351/// unsafe { (*self.inner.as_ptr()).refcount += 1 };
1352/// Self { inner: self.inner }
1353/// }
1354/// }
1355///
1356/// impl<T: ?Sized> Drop for Rc<T> {
1357/// fn drop(&mut self) {
1358/// let ptr = self.inner.as_ptr();
1359/// unsafe { (*ptr).refcount -= 1 };
1360/// if unsafe { (*ptr).refcount } == 0 {
1361/// drop(unsafe { Box::from_raw(ptr) });
1362/// }
1363/// }
1364/// }
1365/// ```
1366#[rustc_builtin_macro(CoercePointee, attributes(pointee))]
1367#[allow_internal_unstable(dispatch_from_dyn, coerce_unsized, unsize, coerce_pointee_validated)]
1368#[rustc_diagnostic_item = "CoercePointee"]
1369#[unstable(feature = "derive_coerce_pointee", issue = "123430")]
1370#[cfg(not(feature = "ferrocene_certified"))]
1371pub macro CoercePointee($item:item) {
1372 /* compiler built-in */
1373}
1374
1375/// A trait that is implemented for ADTs with `derive(CoercePointee)` so that
1376/// the compiler can enforce the derive impls are valid post-expansion, since
1377/// the derive has stricter requirements than if the impls were written by hand.
1378///
1379/// This trait is not intended to be implemented by users or used other than
1380/// validation, so it should never be stabilized.
1381#[lang = "coerce_pointee_validated"]
1382#[unstable(feature = "coerce_pointee_validated", issue = "none")]
1383#[doc(hidden)]
1384#[cfg(not(feature = "ferrocene_certified"))]
1385pub trait CoercePointeeValidated {
1386 /* compiler built-in */
1387}