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