Skip to main content

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