Skip to main content

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