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