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#[rustc_diagnostic_item = "Copy"]
459pub trait Copy: Clone {
460    // Empty.
461}
462
463/// Derive macro generating an impl of the trait `Copy`.
464#[rustc_builtin_macro]
465#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
466#[allow_internal_unstable(core_intrinsics, derive_clone_copy_internals)]
467pub macro Copy($item:item) {
468    /* compiler built-in */
469}
470
471// Implementations of `Copy` for primitive types.
472//
473// Implementations that cannot be described in Rust
474// are implemented in `traits::SelectionContext::copy_clone_conditions()`
475// in `rustc_trait_selection`.
476marker_impls! {
477    #[stable(feature = "rust1", since = "1.0.0")]
478    Copy for
479        usize, u8, u16, u32, u64, u128,
480        isize, i8, i16, i32, i64, i128,
481        f16, f32, f64, f128,
482        bool, char,
483        {T: PointeeSized} *const T,
484        {T: PointeeSized} *mut T,
485
486}
487
488#[unstable(feature = "never_type", issue = "35121")]
489impl Copy for ! {}
490
491/// Shared references can be copied, but mutable references *cannot*!
492#[stable(feature = "rust1", since = "1.0.0")]
493impl<T: PointeeSized> Copy for &T {}
494
495/// Marker trait for the types that are allowed in union fields and unsafe
496/// binder types.
497///
498/// Implemented for:
499/// * `&T`, `&mut T` for all `T`,
500/// * `ManuallyDrop<T>` for all `T`,
501/// * tuples and arrays whose elements implement `BikeshedGuaranteedNoDrop`,
502/// * or otherwise, all types that are `Copy`.
503///
504/// Notably, this doesn't include all trivially-destructible types for semver
505/// reasons.
506///
507/// Bikeshed name for now. This trait does not do anything other than reflect the
508/// set of types that are allowed within unions for field validity.
509#[unstable(feature = "bikeshed_guaranteed_no_drop", issue = "none")]
510#[lang = "bikeshed_guaranteed_no_drop"]
511#[rustc_deny_explicit_impl]
512#[rustc_do_not_implement_via_object]
513#[doc(hidden)]
514pub trait BikeshedGuaranteedNoDrop {}
515
516/// Types for which it is safe to share references between threads.
517///
518/// This trait is automatically implemented when the compiler determines
519/// it's appropriate.
520///
521/// The precise definition is: a type `T` is [`Sync`] if and only if `&T` is
522/// [`Send`]. In other words, if there is no possibility of
523/// [undefined behavior][ub] (including data races) when passing
524/// `&T` references between threads.
525///
526/// As one would expect, primitive types like [`u8`] and [`f64`]
527/// are all [`Sync`], and so are simple aggregate types containing them,
528/// like tuples, structs and enums. More examples of basic [`Sync`]
529/// types include "immutable" types like `&T`, and those with simple
530/// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and
531/// most other collection types. (Generic parameters need to be [`Sync`]
532/// for their container to be [`Sync`].)
533///
534/// A somewhat surprising consequence of the definition is that `&mut T`
535/// is `Sync` (if `T` is `Sync`) even though it seems like that might
536/// provide unsynchronized mutation. The trick is that a mutable
537/// reference behind a shared reference (that is, `& &mut T`)
538/// becomes read-only, as if it were a `& &T`. Hence there is no risk
539/// of a data race.
540///
541/// A shorter overview of how [`Sync`] and [`Send`] relate to referencing:
542/// * `&T` is [`Send`] if and only if `T` is [`Sync`]
543/// * `&mut T` is [`Send`] if and only if `T` is [`Send`]
544/// * `&T` and `&mut T` are [`Sync`] if and only if `T` is [`Sync`]
545///
546/// Types that are not `Sync` are those that have "interior
547/// mutability" in a non-thread-safe form, such as [`Cell`][cell]
548/// and [`RefCell`][refcell]. These types allow for mutation of
549/// their contents even through an immutable, shared reference. For
550/// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires
551/// only a shared reference [`&Cell<T>`][cell]. The method performs no
552/// synchronization, thus [`Cell`][cell] cannot be `Sync`.
553///
554/// Another example of a non-`Sync` type is the reference-counting
555/// pointer [`Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone
556/// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.
557///
558/// For cases when one does need thread-safe interior mutability,
559/// Rust provides [atomic data types], as well as explicit locking via
560/// [`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types
561/// ensure that any mutation cannot cause data races, hence the types
562/// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe
563/// analogue of [`Rc`][rc].
564///
565/// Any types with interior mutability must also use the
566/// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which
567/// can be mutated through a shared reference. Failing to doing this is
568/// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing
569/// from `&T` to `&mut T` is invalid.
570///
571/// See [the Nomicon][nomicon-send-and-sync] for more details about `Sync`.
572///
573/// [box]: ../../std/boxed/struct.Box.html
574/// [vec]: ../../std/vec/struct.Vec.html
575/// [cell]: crate::cell::Cell
576/// [refcell]: crate::cell::RefCell
577/// [rc]: ../../std/rc/struct.Rc.html
578/// [arc]: ../../std/sync/struct.Arc.html
579/// [atomic data types]: crate::sync::atomic
580/// [mutex]: ../../std/sync/struct.Mutex.html
581/// [rwlock]: ../../std/sync/struct.RwLock.html
582/// [unsafecell]: crate::cell::UnsafeCell
583/// [ub]: ../../reference/behavior-considered-undefined.html
584/// [transmute]: crate::mem::transmute
585/// [nomicon-send-and-sync]: ../../nomicon/send-and-sync.html
586#[stable(feature = "rust1", since = "1.0.0")]
587#[rustc_diagnostic_item = "Sync"]
588#[lang = "sync"]
589#[rustc_on_unimplemented(
590    on(
591        Self = "core::cell::once::OnceCell<T>",
592        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::OnceLock` instead"
593    ),
594    on(
595        Self = "core::cell::Cell<u8>",
596        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU8` instead",
597    ),
598    on(
599        Self = "core::cell::Cell<u16>",
600        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU16` instead",
601    ),
602    on(
603        Self = "core::cell::Cell<u32>",
604        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU32` instead",
605    ),
606    on(
607        Self = "core::cell::Cell<u64>",
608        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU64` instead",
609    ),
610    on(
611        Self = "core::cell::Cell<usize>",
612        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicUsize` instead",
613    ),
614    on(
615        Self = "core::cell::Cell<i8>",
616        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI8` instead",
617    ),
618    on(
619        Self = "core::cell::Cell<i16>",
620        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI16` instead",
621    ),
622    on(
623        Self = "core::cell::Cell<i32>",
624        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead",
625    ),
626    on(
627        Self = "core::cell::Cell<i64>",
628        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI64` instead",
629    ),
630    on(
631        Self = "core::cell::Cell<isize>",
632        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicIsize` instead",
633    ),
634    on(
635        Self = "core::cell::Cell<bool>",
636        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicBool` instead",
637    ),
638    on(
639        all(
640            Self = "core::cell::Cell<T>",
641            not(Self = "core::cell::Cell<u8>"),
642            not(Self = "core::cell::Cell<u16>"),
643            not(Self = "core::cell::Cell<u32>"),
644            not(Self = "core::cell::Cell<u64>"),
645            not(Self = "core::cell::Cell<usize>"),
646            not(Self = "core::cell::Cell<i8>"),
647            not(Self = "core::cell::Cell<i16>"),
648            not(Self = "core::cell::Cell<i32>"),
649            not(Self = "core::cell::Cell<i64>"),
650            not(Self = "core::cell::Cell<isize>"),
651            not(Self = "core::cell::Cell<bool>")
652        ),
653        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock`",
654    ),
655    on(
656        Self = "core::cell::RefCell<T>",
657        note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead",
658    ),
659    message = "`{Self}` cannot be shared between threads safely",
660    label = "`{Self}` cannot be shared between threads safely"
661)]
662pub unsafe auto trait Sync {
663    // FIXME(estebank): once support to add notes in `rustc_on_unimplemented`
664    // lands in beta, and it has been extended to check whether a closure is
665    // anywhere in the requirement chain, extend it as such (#48534):
666    // ```
667    // on(
668    //     closure,
669    //     note="`{Self}` cannot be shared safely, consider marking the closure `move`"
670    // ),
671    // ```
672
673    // Empty
674}
675
676#[stable(feature = "rust1", since = "1.0.0")]
677impl<T: PointeeSized> !Sync for *const T {}
678#[stable(feature = "rust1", since = "1.0.0")]
679impl<T: PointeeSized> !Sync for *mut T {}
680
681/// Zero-sized type used to mark things that "act like" they own a `T`.
682///
683/// Adding a `PhantomData<T>` field to your type tells the compiler that your
684/// type acts as though it stores a value of type `T`, even though it doesn't
685/// really. This information is used when computing certain safety properties.
686///
687/// For a more in-depth explanation of how to use `PhantomData<T>`, please see
688/// [the Nomicon](../../nomicon/phantom-data.html).
689///
690/// # A ghastly note 👻👻👻
691///
692/// Though they both have scary names, `PhantomData` and 'phantom types' are
693/// related, but not identical. A phantom type parameter is simply a type
694/// parameter which is never used. In Rust, this often causes the compiler to
695/// complain, and the solution is to add a "dummy" use by way of `PhantomData`.
696///
697/// # Examples
698///
699/// ## Unused lifetime parameters
700///
701/// Perhaps the most common use case for `PhantomData` is a struct that has an
702/// unused lifetime parameter, typically as part of some unsafe code. For
703/// example, here is a struct `Slice` that has two pointers of type `*const T`,
704/// presumably pointing into an array somewhere:
705///
706/// ```compile_fail,E0392
707/// struct Slice<'a, T> {
708///     start: *const T,
709///     end: *const T,
710/// }
711/// ```
712///
713/// The intention is that the underlying data is only valid for the
714/// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
715/// intent is not expressed in the code, since there are no uses of
716/// the lifetime `'a` and hence it is not clear what data it applies
717/// to. We can correct this by telling the compiler to act *as if* the
718/// `Slice` struct contained a reference `&'a T`:
719///
720/// ```
721/// use std::marker::PhantomData;
722///
723/// # #[allow(dead_code)]
724/// struct Slice<'a, T> {
725///     start: *const T,
726///     end: *const T,
727///     phantom: PhantomData<&'a T>,
728/// }
729/// ```
730///
731/// This also in turn infers the lifetime bound `T: 'a`, indicating
732/// that any references in `T` are valid over the lifetime `'a`.
733///
734/// When initializing a `Slice` you simply provide the value
735/// `PhantomData` for the field `phantom`:
736///
737/// ```
738/// # #![allow(dead_code)]
739/// # use std::marker::PhantomData;
740/// # struct Slice<'a, T> {
741/// #     start: *const T,
742/// #     end: *const T,
743/// #     phantom: PhantomData<&'a T>,
744/// # }
745/// fn borrow_vec<T>(vec: &Vec<T>) -> Slice<'_, T> {
746///     let ptr = vec.as_ptr();
747///     Slice {
748///         start: ptr,
749///         end: unsafe { ptr.add(vec.len()) },
750///         phantom: PhantomData,
751///     }
752/// }
753/// ```
754///
755/// ## Unused type parameters
756///
757/// It sometimes happens that you have unused type parameters which
758/// indicate what type of data a struct is "tied" to, even though that
759/// data is not actually found in the struct itself. Here is an
760/// example where this arises with [FFI]. The foreign interface uses
761/// handles of type `*mut ()` to refer to Rust values of different
762/// types. We track the Rust type using a phantom type parameter on
763/// the struct `ExternalResource` which wraps a handle.
764///
765/// [FFI]: ../../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
766///
767/// ```
768/// # #![allow(dead_code)]
769/// # trait ResType { }
770/// # struct ParamType;
771/// # mod foreign_lib {
772/// #     pub fn new(_: usize) -> *mut () { 42 as *mut () }
773/// #     pub fn do_stuff(_: *mut (), _: usize) {}
774/// # }
775/// # fn convert_params(_: ParamType) -> usize { 42 }
776/// use std::marker::PhantomData;
777///
778/// struct ExternalResource<R> {
779///    resource_handle: *mut (),
780///    resource_type: PhantomData<R>,
781/// }
782///
783/// impl<R: ResType> ExternalResource<R> {
784///     fn new() -> Self {
785///         let size_of_res = size_of::<R>();
786///         Self {
787///             resource_handle: foreign_lib::new(size_of_res),
788///             resource_type: PhantomData,
789///         }
790///     }
791///
792///     fn do_stuff(&self, param: ParamType) {
793///         let foreign_params = convert_params(param);
794///         foreign_lib::do_stuff(self.resource_handle, foreign_params);
795///     }
796/// }
797/// ```
798///
799/// ## Ownership and the drop check
800///
801/// The exact interaction of `PhantomData` with drop check **may change in the future**.
802///
803/// Currently, adding a field of type `PhantomData<T>` indicates that your type *owns* data of type
804/// `T` in very rare circumstances. This in turn has effects on the Rust compiler's [drop check]
805/// analysis. For the exact rules, see the [drop check] documentation.
806///
807/// ## Layout
808///
809/// For all `T`, the following are guaranteed:
810/// * `size_of::<PhantomData<T>>() == 0`
811/// * `align_of::<PhantomData<T>>() == 1`
812///
813/// [drop check]: Drop#drop-check
814#[lang = "phantom_data"]
815#[stable(feature = "rust1", since = "1.0.0")]
816pub struct PhantomData<T: PointeeSized>;
817
818#[stable(feature = "rust1", since = "1.0.0")]
819impl<T: PointeeSized> Hash for PhantomData<T> {
820    #[inline]
821    fn hash<H: Hasher>(&self, _: &mut H) {}
822}
823
824#[stable(feature = "rust1", since = "1.0.0")]
825impl<T: PointeeSized> cmp::PartialEq for PhantomData<T> {
826    fn eq(&self, _other: &PhantomData<T>) -> bool {
827        true
828    }
829}
830
831#[stable(feature = "rust1", since = "1.0.0")]
832impl<T: PointeeSized> cmp::Eq for PhantomData<T> {}
833
834#[stable(feature = "rust1", since = "1.0.0")]
835impl<T: PointeeSized> cmp::PartialOrd for PhantomData<T> {
836    fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<cmp::Ordering> {
837        Option::Some(cmp::Ordering::Equal)
838    }
839}
840
841#[stable(feature = "rust1", since = "1.0.0")]
842impl<T: PointeeSized> cmp::Ord for PhantomData<T> {
843    fn cmp(&self, _other: &PhantomData<T>) -> cmp::Ordering {
844        cmp::Ordering::Equal
845    }
846}
847
848#[stable(feature = "rust1", since = "1.0.0")]
849impl<T: PointeeSized> Copy for PhantomData<T> {}
850
851#[stable(feature = "rust1", since = "1.0.0")]
852impl<T: PointeeSized> Clone for PhantomData<T> {
853    fn clone(&self) -> Self {
854        Self
855    }
856}
857
858#[doc(hidden)]
859#[unstable(feature = "trivial_clone", issue = "none")]
860unsafe impl<T: PointeeSized> TrivialClone for PhantomData<T> {}
861
862#[stable(feature = "rust1", since = "1.0.0")]
863#[rustc_const_unstable(feature = "const_default", issue = "143894")]
864impl<T: PointeeSized> const Default for PhantomData<T> {
865    fn default() -> Self {
866        Self
867    }
868}
869
870#[unstable(feature = "structural_match", issue = "31434")]
871impl<T: PointeeSized> StructuralPartialEq for PhantomData<T> {}
872
873/// Compiler-internal trait used to indicate the type of enum discriminants.
874///
875/// This trait is automatically implemented for every type and does not add any
876/// guarantees to [`mem::Discriminant`]. It is **undefined behavior** to transmute
877/// between `DiscriminantKind::Discriminant` and `mem::Discriminant`.
878///
879/// [`mem::Discriminant`]: crate::mem::Discriminant
880#[unstable(
881    feature = "discriminant_kind",
882    issue = "none",
883    reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead"
884)]
885#[lang = "discriminant_kind"]
886#[rustc_deny_explicit_impl]
887#[rustc_do_not_implement_via_object]
888pub trait DiscriminantKind {
889    /// The type of the discriminant, which must satisfy the trait
890    /// bounds required by `mem::Discriminant`.
891    #[lang = "discriminant_type"]
892    type Discriminant: Clone + Copy + Debug + Eq + PartialEq + Hash + Send + Sync + Unpin;
893}
894
895/// Used to determine whether a type contains
896/// any `UnsafeCell` internally, but not through an indirection.
897/// This affects, for example, whether a `static` of that type is
898/// placed in read-only static memory or writable static memory.
899/// This can be used to declare that a constant with a generic type
900/// will not contain interior mutability, and subsequently allow
901/// placing the constant behind references.
902///
903/// # Safety
904///
905/// This trait is a core part of the language, it is just expressed as a trait in libcore for
906/// convenience. Do *not* implement it for other types.
907// FIXME: Eventually this trait should become `#[rustc_deny_explicit_impl]`.
908// That requires porting the impls below to native internal impls.
909#[lang = "freeze"]
910#[unstable(feature = "freeze", issue = "121675")]
911pub unsafe auto trait Freeze {}
912
913#[unstable(feature = "freeze", issue = "121675")]
914impl<T: PointeeSized> !Freeze for UnsafeCell<T> {}
915marker_impls! {
916    #[unstable(feature = "freeze", issue = "121675")]
917    unsafe Freeze for
918        {T: PointeeSized} PhantomData<T>,
919        {T: PointeeSized} *const T,
920        {T: PointeeSized} *mut T,
921        {T: PointeeSized} &T,
922        {T: PointeeSized} &mut T,
923}
924
925/// Used to determine whether a type contains any `UnsafePinned` (or `PhantomPinned`) internally,
926/// but not through an indirection. This affects, for example, whether we emit `noalias` metadata
927/// for `&mut T` or not.
928///
929/// This is part of [RFC 3467](https://rust-lang.github.io/rfcs/3467-unsafe-pinned.html), and is
930/// tracked by [#125735](https://github.com/rust-lang/rust/issues/125735).
931#[lang = "unsafe_unpin"]
932pub(crate) unsafe auto trait UnsafeUnpin {}
933
934impl<T: ?Sized> !UnsafeUnpin for UnsafePinned<T> {}
935unsafe impl<T: ?Sized> UnsafeUnpin for PhantomData<T> {}
936unsafe impl<T: ?Sized> UnsafeUnpin for *const T {}
937unsafe impl<T: ?Sized> UnsafeUnpin for *mut T {}
938unsafe impl<T: ?Sized> UnsafeUnpin for &T {}
939unsafe impl<T: ?Sized> UnsafeUnpin for &mut T {}
940
941/// Types that do not require any pinning guarantees.
942///
943/// For information on what "pinning" is, see the [`pin` module] documentation.
944///
945/// Implementing the `Unpin` trait for `T` expresses the fact that `T` is pinning-agnostic:
946/// it shall not expose nor rely on any pinning guarantees. This, in turn, means that a
947/// `Pin`-wrapped pointer to such a type can feature a *fully unrestricted* API.
948/// In other words, if `T: Unpin`, a value of type `T` will *not* be bound by the invariants
949/// which pinning otherwise offers, even when "pinned" by a [`Pin<Ptr>`] pointing at it.
950/// When a value of type `T` is pointed at by a [`Pin<Ptr>`], [`Pin`] will not restrict access
951/// to the pointee value like it normally would, thus allowing the user to do anything that they
952/// normally could with a non-[`Pin`]-wrapped `Ptr` to that value.
953///
954/// The idea of this trait is to alleviate the reduced ergonomics of APIs that require the use
955/// of [`Pin`] for soundness for some types, but which also want to be used by other types that
956/// don't care about pinning. The prime example of such an API is [`Future::poll`]. There are many
957/// [`Future`] types that don't care about pinning. These futures can implement `Unpin` and
958/// therefore get around the pinning related restrictions in the API, while still allowing the
959/// subset of [`Future`]s which *do* require pinning to be implemented soundly.
960///
961/// For more discussion on the consequences of [`Unpin`] within the wider scope of the pinning
962/// system, see the [section about `Unpin`] in the [`pin` module].
963///
964/// `Unpin` has no consequence at all for non-pinned data. In particular, [`mem::replace`] happily
965/// moves `!Unpin` data, which would be immovable when pinned ([`mem::replace`] works for any
966/// `&mut T`, not just when `T: Unpin`).
967///
968/// *However*, you cannot use [`mem::replace`] on `!Unpin` data which is *pinned* by being wrapped
969/// inside a [`Pin<Ptr>`] pointing at it. This is because you cannot (safely) use a
970/// [`Pin<Ptr>`] to get a `&mut T` to its pointee value, which you would need to call
971/// [`mem::replace`], and *that* is what makes this system work.
972///
973/// So this, for example, can only be done on types implementing `Unpin`:
974///
975/// ```rust
976/// # #![allow(unused_must_use)]
977/// use std::mem;
978/// use std::pin::Pin;
979///
980/// let mut string = "this".to_string();
981/// let mut pinned_string = Pin::new(&mut string);
982///
983/// // We need a mutable reference to call `mem::replace`.
984/// // We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`,
985/// // but that is only possible because `String` implements `Unpin`.
986/// mem::replace(&mut *pinned_string, "other".to_string());
987/// ```
988///
989/// This trait is automatically implemented for almost every type. The compiler is free
990/// to take the conservative stance of marking types as [`Unpin`] so long as all of the types that
991/// compose its fields are also [`Unpin`]. This is because if a type implements [`Unpin`], then it
992/// is unsound for that type's implementation to rely on pinning-related guarantees for soundness,
993/// *even* when viewed through a "pinning" pointer! It is the responsibility of the implementor of
994/// a type that relies upon pinning for soundness to ensure that type is *not* marked as [`Unpin`]
995/// by adding [`PhantomPinned`] field. For more details, see the [`pin` module] docs.
996///
997/// [`mem::replace`]: crate::mem::replace "mem replace"
998/// [`Future`]: crate::future::Future "Future"
999/// [`Future::poll`]: crate::future::Future::poll "Future poll"
1000/// [`Pin`]: crate::pin::Pin "Pin"
1001/// [`Pin<Ptr>`]: crate::pin::Pin "Pin"
1002/// [`pin` module]: crate::pin "pin module"
1003/// [section about `Unpin`]: crate::pin#unpin "pin module docs about unpin"
1004/// [`unsafe`]: ../../std/keyword.unsafe.html "keyword unsafe"
1005#[stable(feature = "pin", since = "1.33.0")]
1006#[diagnostic::on_unimplemented(
1007    note = "consider using the `pin!` macro\nconsider using `Box::pin` if you need to access the pinned value outside of the current scope",
1008    message = "`{Self}` cannot be unpinned"
1009)]
1010#[lang = "unpin"]
1011pub auto trait Unpin {}
1012
1013/// A marker type which does not implement `Unpin`.
1014///
1015/// If a type contains a `PhantomPinned`, it will not implement `Unpin` by default.
1016//
1017// FIXME(unsafe_pinned): This is *not* a stable guarantee we want to make, at least not yet.
1018// Note that for backwards compatibility with the new [`UnsafePinned`] wrapper type, placing this
1019// marker in your struct acts as if you wrapped the entire struct in an `UnsafePinned`. This type
1020// will likely eventually be deprecated, and all new code should be using `UnsafePinned` instead.
1021#[stable(feature = "pin", since = "1.33.0")]
1022#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1023pub struct PhantomPinned;
1024
1025#[stable(feature = "pin", since = "1.33.0")]
1026impl !Unpin for PhantomPinned {}
1027
1028// This is a small hack to allow existing code which uses PhantomPinned to opt-out of noalias to
1029// continue working. Ideally PhantomPinned could just wrap an `UnsafePinned<()>` to get the same
1030// effect, but we can't add a new field to an already stable unit struct -- that would be a breaking
1031// change.
1032impl !UnsafeUnpin for PhantomPinned {}
1033
1034marker_impls! {
1035    #[stable(feature = "pin", since = "1.33.0")]
1036    Unpin for
1037        {T: PointeeSized} &T,
1038        {T: PointeeSized} &mut T,
1039}
1040
1041marker_impls! {
1042    #[stable(feature = "pin_raw", since = "1.38.0")]
1043    Unpin for
1044        {T: PointeeSized} *const T,
1045        {T: PointeeSized} *mut T,
1046}
1047
1048/// A marker for types that can be dropped.
1049///
1050/// This should be used for `[const]` bounds,
1051/// as non-const bounds will always hold for every type.
1052#[unstable(feature = "const_destruct", issue = "133214")]
1053#[rustc_const_unstable(feature = "const_destruct", issue = "133214")]
1054#[lang = "destruct"]
1055#[rustc_on_unimplemented(message = "can't drop `{Self}`", append_const_msg)]
1056#[rustc_deny_explicit_impl]
1057#[rustc_do_not_implement_via_object]
1058pub const trait Destruct: PointeeSized {}
1059
1060/// A marker for tuple types.
1061///
1062/// The implementation of this trait is built-in and cannot be implemented
1063/// for any user type.
1064#[unstable(feature = "tuple_trait", issue = "none")]
1065#[lang = "tuple_trait"]
1066#[diagnostic::on_unimplemented(message = "`{Self}` is not a tuple")]
1067#[rustc_deny_explicit_impl]
1068#[rustc_do_not_implement_via_object]
1069pub trait Tuple {}
1070
1071/// A marker for types which can be used as types of `const` generic parameters.
1072///
1073/// These types must have a proper equivalence relation (`Eq`) and it must be automatically
1074/// derived (`StructuralPartialEq`). There's a hard-coded check in the compiler ensuring
1075/// that all fields are also `ConstParamTy`, which implies that recursively, all fields
1076/// are `StructuralPartialEq`.
1077#[lang = "const_param_ty"]
1078#[unstable(feature = "unsized_const_params", issue = "95174")]
1079#[diagnostic::on_unimplemented(message = "`{Self}` can't be used as a const parameter type")]
1080#[allow(multiple_supertrait_upcastable)]
1081// We name this differently than the derive macro so that the `adt_const_params` can
1082// be used independently of `unsized_const_params` without requiring a full path
1083// to the derive macro every time it is used. This should be renamed on stabilization.
1084pub trait ConstParamTy_: StructuralPartialEq + Eq {}
1085
1086/// Derive macro generating an impl of the trait `ConstParamTy`.
1087#[rustc_builtin_macro]
1088#[allow_internal_unstable(unsized_const_params)]
1089#[unstable(feature = "adt_const_params", issue = "95174")]
1090pub macro ConstParamTy($item:item) {
1091    /* compiler built-in */
1092}
1093
1094// FIXME(adt_const_params): handle `ty::FnDef`/`ty::Closure`
1095marker_impls! {
1096    #[unstable(feature = "adt_const_params", issue = "95174")]
1097    ConstParamTy_ for
1098        usize, u8, u16, u32, u64, u128,
1099        isize, i8, i16, i32, i64, i128,
1100        bool,
1101        char,
1102        (),
1103        {T: ConstParamTy_, const N: usize} [T; N],
1104}
1105
1106marker_impls! {
1107    #[unstable(feature = "unsized_const_params", issue = "95174")]
1108    #[unstable_feature_bound(unsized_const_params)]
1109    ConstParamTy_ for
1110        str,
1111        {T: ConstParamTy_} [T],
1112        {T: ConstParamTy_ + ?Sized} &T,
1113}
1114
1115/// A common trait implemented by all function pointers.
1116//
1117// Note that while the trait is internal and unstable it is nevertheless
1118// exposed as a public bound of the stable `core::ptr::fn_addr_eq` function.
1119#[unstable(
1120    feature = "fn_ptr_trait",
1121    issue = "none",
1122    reason = "internal trait for implementing various traits for all function pointers"
1123)]
1124#[lang = "fn_ptr_trait"]
1125#[rustc_deny_explicit_impl]
1126#[rustc_do_not_implement_via_object]
1127pub trait FnPtr: Copy + Clone {
1128    /// Returns the address of the function pointer.
1129    #[lang = "fn_ptr_addr"]
1130    fn addr(self) -> *const ();
1131}
1132
1133/// Derive macro that makes a smart pointer usable with trait objects.
1134///
1135/// # What this macro does
1136///
1137/// This macro is intended to be used with user-defined pointer types, and makes it possible to
1138/// perform coercions on the pointee of the user-defined pointer. There are two aspects to this:
1139///
1140/// ## Unsizing coercions of the pointee
1141///
1142/// By using the macro, the following example will compile:
1143/// ```
1144/// #![feature(derive_coerce_pointee)]
1145/// use std::marker::CoercePointee;
1146/// use std::ops::Deref;
1147///
1148/// #[derive(CoercePointee)]
1149/// #[repr(transparent)]
1150/// struct MySmartPointer<T: ?Sized>(Box<T>);
1151///
1152/// impl<T: ?Sized> Deref for MySmartPointer<T> {
1153///     type Target = T;
1154///     fn deref(&self) -> &T {
1155///         &self.0
1156///     }
1157/// }
1158///
1159/// trait MyTrait {}
1160///
1161/// impl MyTrait for i32 {}
1162///
1163/// fn main() {
1164///     let ptr: MySmartPointer<i32> = MySmartPointer(Box::new(4));
1165///
1166///     // This coercion would be an error without the derive.
1167///     let ptr: MySmartPointer<dyn MyTrait> = ptr;
1168/// }
1169/// ```
1170/// Without the `#[derive(CoercePointee)]` macro, this example would fail with the following error:
1171/// ```text
1172/// error[E0308]: mismatched types
1173///   --> src/main.rs:11:44
1174///    |
1175/// 11 |     let ptr: MySmartPointer<dyn MyTrait> = ptr;
1176///    |              ---------------------------   ^^^ expected `MySmartPointer<dyn MyTrait>`, found `MySmartPointer<i32>`
1177///    |              |
1178///    |              expected due to this
1179///    |
1180///    = note: expected struct `MySmartPointer<dyn MyTrait>`
1181///               found struct `MySmartPointer<i32>`
1182///    = 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
1183/// ```
1184///
1185/// ## Dyn compatibility
1186///
1187/// This macro allows you to dispatch on the user-defined pointer type. That is, traits using the
1188/// type as a receiver are dyn-compatible. For example, this compiles:
1189///
1190/// ```
1191/// #![feature(arbitrary_self_types, derive_coerce_pointee)]
1192/// use std::marker::CoercePointee;
1193/// use std::ops::Deref;
1194///
1195/// #[derive(CoercePointee)]
1196/// #[repr(transparent)]
1197/// struct MySmartPointer<T: ?Sized>(Box<T>);
1198///
1199/// impl<T: ?Sized> Deref for MySmartPointer<T> {
1200///     type Target = T;
1201///     fn deref(&self) -> &T {
1202///         &self.0
1203///     }
1204/// }
1205///
1206/// // You can always define this trait. (as long as you have #![feature(arbitrary_self_types)])
1207/// trait MyTrait {
1208///     fn func(self: MySmartPointer<Self>);
1209/// }
1210///
1211/// // But using `dyn MyTrait` requires #[derive(CoercePointee)].
1212/// fn call_func(value: MySmartPointer<dyn MyTrait>) {
1213///     value.func();
1214/// }
1215/// ```
1216/// If you remove the `#[derive(CoercePointee)]` annotation from the struct, then the above example
1217/// will fail with this error message:
1218/// ```text
1219/// error[E0038]: the trait `MyTrait` is not dyn compatible
1220///   --> src/lib.rs:21:36
1221///    |
1222/// 17 |     fn func(self: MySmartPointer<Self>);
1223///    |                   -------------------- help: consider changing method `func`'s `self` parameter to be `&self`: `&Self`
1224/// ...
1225/// 21 | fn call_func(value: MySmartPointer<dyn MyTrait>) {
1226///    |                                    ^^^^^^^^^^^ `MyTrait` is not dyn compatible
1227///    |
1228/// note: for a trait to be dyn compatible it needs to allow building a vtable
1229///       for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
1230///   --> src/lib.rs:17:19
1231///    |
1232/// 16 | trait MyTrait {
1233///    |       ------- this trait is not dyn compatible...
1234/// 17 |     fn func(self: MySmartPointer<Self>);
1235///    |                   ^^^^^^^^^^^^^^^^^^^^ ...because method `func`'s `self` parameter cannot be dispatched on
1236/// ```
1237///
1238/// # Requirements for using the macro
1239///
1240/// This macro can only be used if:
1241/// * The type is a `#[repr(transparent)]` struct.
1242/// * The type of its non-zero-sized field must either be a standard library pointer type
1243///   (reference, raw pointer, `NonNull`, `Box`, `Rc`, `Arc`, etc.) or another user-defined type
1244///   also using the `#[derive(CoercePointee)]` macro.
1245/// * Zero-sized fields must not mention any generic parameters unless the zero-sized field has
1246///   type [`PhantomData`].
1247///
1248/// ## Multiple type parameters
1249///
1250/// If the type has multiple type parameters, then you must explicitly specify which one should be
1251/// used for dynamic dispatch. For example:
1252/// ```
1253/// # #![feature(derive_coerce_pointee)]
1254/// # use std::marker::{CoercePointee, PhantomData};
1255/// #[derive(CoercePointee)]
1256/// #[repr(transparent)]
1257/// struct MySmartPointer<#[pointee] T: ?Sized, U> {
1258///     ptr: Box<T>,
1259///     _phantom: PhantomData<U>,
1260/// }
1261/// ```
1262/// Specifying `#[pointee]` when the struct has only one type parameter is allowed, but not required.
1263///
1264/// # Examples
1265///
1266/// A custom implementation of the `Rc` type:
1267/// ```
1268/// #![feature(derive_coerce_pointee)]
1269/// use std::marker::CoercePointee;
1270/// use std::ops::Deref;
1271/// use std::ptr::NonNull;
1272///
1273/// #[derive(CoercePointee)]
1274/// #[repr(transparent)]
1275/// pub struct Rc<T: ?Sized> {
1276///     inner: NonNull<RcInner<T>>,
1277/// }
1278///
1279/// struct RcInner<T: ?Sized> {
1280///     refcount: usize,
1281///     value: T,
1282/// }
1283///
1284/// impl<T: ?Sized> Deref for Rc<T> {
1285///     type Target = T;
1286///     fn deref(&self) -> &T {
1287///         let ptr = self.inner.as_ptr();
1288///         unsafe { &(*ptr).value }
1289///     }
1290/// }
1291///
1292/// impl<T> Rc<T> {
1293///     pub fn new(value: T) -> Self {
1294///         let inner = Box::new(RcInner {
1295///             refcount: 1,
1296///             value,
1297///         });
1298///         Self {
1299///             inner: NonNull::from(Box::leak(inner)),
1300///         }
1301///     }
1302/// }
1303///
1304/// impl<T: ?Sized> Clone for Rc<T> {
1305///     fn clone(&self) -> Self {
1306///         // A real implementation would handle overflow here.
1307///         unsafe { (*self.inner.as_ptr()).refcount += 1 };
1308///         Self { inner: self.inner }
1309///     }
1310/// }
1311///
1312/// impl<T: ?Sized> Drop for Rc<T> {
1313///     fn drop(&mut self) {
1314///         let ptr = self.inner.as_ptr();
1315///         unsafe { (*ptr).refcount -= 1 };
1316///         if unsafe { (*ptr).refcount } == 0 {
1317///             drop(unsafe { Box::from_raw(ptr) });
1318///         }
1319///     }
1320/// }
1321/// ```
1322#[rustc_builtin_macro(CoercePointee, attributes(pointee))]
1323#[allow_internal_unstable(dispatch_from_dyn, coerce_unsized, unsize, coerce_pointee_validated)]
1324#[rustc_diagnostic_item = "CoercePointee"]
1325#[unstable(feature = "derive_coerce_pointee", issue = "123430")]
1326pub macro CoercePointee($item:item) {
1327    /* compiler built-in */
1328}
1329
1330/// A trait that is implemented for ADTs with `derive(CoercePointee)` so that
1331/// the compiler can enforce the derive impls are valid post-expansion, since
1332/// the derive has stricter requirements than if the impls were written by hand.
1333///
1334/// This trait is not intended to be implemented by users or used other than
1335/// validation, so it should never be stabilized.
1336#[lang = "coerce_pointee_validated"]
1337#[unstable(feature = "coerce_pointee_validated", issue = "none")]
1338#[doc(hidden)]
1339pub trait CoercePointeeValidated {
1340    /* compiler built-in */
1341}