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