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