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