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