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