core/
marker.rs

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

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy