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