marker.rs - source
Description: Source of the Rust file `library/core/src/marker.rs`.

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