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