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
9use crate::cell::UnsafeCell;
10use crate::cmp;
11use crate::fmt::Debug;
12use crate::hash::Hash;
13use crate::hash::Hasher;
14
15/// Implements a given marker trait for multiple types at the same time.
16///
17/// The basic syntax looks like this:
18/// ```ignore private macro
19/// marker_impls! { MarkerTrait for u8, i8 }
20/// ```
21/// You can also implement `unsafe` traits
22/// ```ignore private macro
23/// marker_impls! { unsafe MarkerTrait for u8, i8 }
24/// ```
25/// Add attributes to all impls:
26/// ```ignore private macro
27/// marker_impls! {
28/// #[allow(lint)]
29/// #[unstable(feature = "marker_trait", issue = "none")]
30/// MarkerTrait for u8, i8
31/// }
32/// ```
33/// And use generics:
34/// ```ignore private macro
35/// marker_impls! {
36/// MarkerTrait for
37/// u8, i8,
38/// {T: ?Sized} *const T,
39/// {T: ?Sized} *mut T,
40/// {T: MarkerTrait} PhantomData<T>,
41/// u32,
42/// }
43/// ```
44#[unstable(feature = "internal_impls_macro", issue = "none")]
45macro marker_impls {
46 ( $(#[$($meta:tt)*])* $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => {
47 $(#[$($meta)*])* impl< $($($bounds)*)? > $Trait for $T {}
48 marker_impls! { $(#[$($meta)*])* $Trait for $($($rest)*)? }
49 },
50 ( $(#[$($meta:tt)*])* $Trait:ident for ) => {},
51
52 ( $(#[$($meta:tt)*])* unsafe $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => {
53 $(#[$($meta)*])* unsafe impl< $($($bounds)*)? > $Trait for $T {}
54 marker_impls! { $(#[$($meta)*])* unsafe $Trait for $($($rest)*)? }
55 },
56 ( $(#[$($meta:tt)*])* unsafe $Trait:ident for ) => {},
57}
58
59/// Types that can be transferred across thread boundaries.
60///
61/// This trait is automatically implemented when the compiler determines it's
62/// appropriate.
63///
64/// An example of a non-`Send` type is the reference-counting pointer
65/// [`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same
66/// reference-counted value, they might try to update the reference count at the
67/// same time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic
68/// operations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring
69/// some overhead) and thus is `Send`.
70///
71/// See [the Nomicon](../../nomicon/send-and-sync.html) and the [`Sync`] trait for more details.
72///
73/// [`Rc`]: ../../std/rc/struct.Rc.html
74/// [arc]: ../../std/sync/struct.Arc.html
75/// [ub]: ../../reference/behavior-considered-undefined.html
76#[stable(feature = "rust1", since = "1.0.0")]
77#[cfg_attr(not(test), rustc_diagnostic_item = "Send")]
78#[diagnostic::on_unimplemented(
79 message = "`{Self}` cannot be sent between threads safely",
80 label = "`{Self}` cannot be sent between threads safely"
81)]
82pub unsafe auto trait Send {
83 // empty.
84}
85
86#[stable(feature = "rust1", since = "1.0.0")]
87impl<T: ?Sized> !Send for *const T {}
88#[stable(feature = "rust1", since = "1.0.0")]
89impl<T: ?Sized> !Send for *mut T {}
90
91// Most instances arise automatically, but this instance is needed to link up `T: Sync` with
92// `&T: Send` (and it also removes the unsound default instance `T Send` -> `&T: Send` that would
93// otherwise exist).
94#[stable(feature = "rust1", since = "1.0.0")]
95unsafe impl<T: Sync + ?Sized> Send for &T {}
96
97/// Types with a constant size known at compile time.
98///
99/// All type parameters have an implicit bound of `Sized`. The special syntax
100/// `?Sized` can be used to remove this bound if it's not appropriate.
101///
102/// ```
103/// # #![allow(dead_code)]
104/// struct Foo<T>(T);
105/// struct Bar<T: ?Sized>(T);
106///
107/// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32]
108/// struct BarUse(Bar<[i32]>); // OK
109/// ```
110///
111/// The one exception is the implicit `Self` type of a trait. A trait does not
112/// have an implicit `Sized` bound as this is incompatible with [trait object]s
113/// where, by definition, the trait needs to work with all possible implementors,
114/// and thus could be any size.
115///
116/// Although Rust will let you bind `Sized` to a trait, you won't
117/// be able to use it to form a trait object later:
118///
119/// ```
120/// # #![allow(unused_variables)]
121/// trait Foo { }
122/// trait Bar: Sized { }
123///
124/// struct Impl;
125/// impl Foo for Impl { }
126/// impl Bar for Impl { }
127///
128/// let x: &dyn Foo = &Impl; // OK
129/// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot
130/// // be made into an object
131/// ```
132///
133/// [trait object]: ../../book/ch17-02-trait-objects.html
134#[doc(alias = "?", alias = "?Sized")]
135#[stable(feature = "rust1", since = "1.0.0")]
136#[lang = "sized"]
137#[diagnostic::on_unimplemented(
138 message = "the size for values of type `{Self}` cannot be known at compilation time",
139 label = "doesn't have a size known at compile-time"
140)]
141#[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
142#[rustc_specialization_trait]
143#[rustc_deny_explicit_impl(implement_via_object = false)]
144#[rustc_coinductive]
145pub trait Sized {
146 // Empty.
147}
148
149/// Types that can be "unsized" to a dynamically-sized type.
150///
151/// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and
152/// `Unsize<dyn fmt::Debug>`.
153///
154/// All implementations of `Unsize` are provided automatically by the compiler.
155/// Those implementations are:
156///
157/// - Arrays `[T; N]` implement `Unsize<[T]>`.
158/// - A type implements `Unsize<dyn Trait + 'a>` if all of these conditions are met:
159/// - The type implements `Trait`.
160/// - `Trait` is object safe.
161/// - The type is sized.
162/// - The type outlives `'a`.
163/// - Structs `Foo<..., T1, ..., Tn, ...>` implement `Unsize<Foo<..., U1, ..., Un, ...>>`
164/// where any number of (type and const) parameters may be changed if all of these conditions
165/// are met:
166/// - Only the last field of `Foo` has a type involving the parameters `T1`, ..., `Tn`.
167/// - All other parameters of the struct are equal.
168/// - `Field<T1, ..., Tn>: Unsize<Field<U1, ..., Un>>`, where `Field<...>` stands for the actual
169/// type of the struct's last field.
170///
171/// `Unsize` is used along with [`ops::CoerceUnsized`] to allow
172/// "user-defined" containers such as [`Rc`] to contain dynamically-sized
173/// types. See the [DST coercion RFC][RFC982] and [the nomicon entry on coercion][nomicon-coerce]
174/// for more details.
175///
176/// [`ops::CoerceUnsized`]: crate::ops::CoerceUnsized
177/// [`Rc`]: ../../std/rc/struct.Rc.html
178/// [RFC982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
179/// [nomicon-coerce]: ../../nomicon/coercions.html
180#[unstable(feature = "unsize", issue = "18598")]
181#[lang = "unsize"]
182#[rustc_deny_explicit_impl(implement_via_object = false)]
183pub trait Unsize<T: ?Sized> {
184 // Empty.
185}
186
187/// Required trait for constants used in pattern matches.
188///
189/// Any type that derives `PartialEq` automatically implements this trait,
190/// *regardless* of whether its type-parameters implement `PartialEq`.
191///
192/// If a `const` item contains some type that does not implement this trait,
193/// then that type either (1.) does not implement `PartialEq` (which means the
194/// constant will not provide that comparison method, which code generation
195/// assumes is available), or (2.) it implements *its own* version of
196/// `PartialEq` (which we assume does not conform to a structural-equality
197/// comparison).
198///
199/// In either of the two scenarios above, we reject usage of such a constant in
200/// a pattern match.
201///
202/// See also the [structural match RFC][RFC1445], and [issue 63438] which
203/// motivated migrating from an attribute-based design to this trait.
204///
205/// [RFC1445]: https://github.com/rust-lang/rfcs/blob/master/text/1445-restrict-constants-in-patterns.md
206/// [issue 63438]: https://github.com/rust-lang/rust/issues/63438
207#[unstable(feature = "structural_match", issue = "31434")]
208#[diagnostic::on_unimplemented(message = "the type `{Self}` does not `#[derive(PartialEq)]`")]
209#[lang = "structural_peq"]
210pub trait StructuralPartialEq {
211 // Empty.
212}
213
214marker_impls! {
215 #[unstable(feature = "structural_match", issue = "31434")]
216 StructuralPartialEq for
217 usize, u8, u16, u32, u64, u128,
218 isize, i8, i16, i32, i64, i128,
219 bool,
220 char,
221 str /* Technically requires `[u8]: StructuralPartialEq` */,
222 (),
223 {T, const N: usize} [T; N],
224 {T} [T],
225 {T: ?Sized} &T,
226}
227
228/// Required trait for constants used in pattern matches.
229///
230/// Any type that derives `Eq` automatically implements this trait, *regardless*
231/// of whether its type parameters implement `Eq`.
232///
233/// This is a hack to work around a limitation in our type system.
234///
235/// # Background
236///
237/// We want to require that types of consts used in pattern matches
238/// have the attribute `#[derive(PartialEq, Eq)]`.
239///
240/// In a more ideal world, we could check that requirement by just checking that
241/// the given type implements both the `StructuralPartialEq` trait *and*
242/// the `Eq` trait. However, you can have ADTs that *do* `derive(PartialEq, Eq)`,
243/// and be a case that we want the compiler to accept, and yet the constant's
244/// type fails to implement `Eq`.
245///
246/// Namely, a case like this:
247///
248/// ```rust
249/// #[derive(PartialEq, Eq)]
250/// struct Wrap<X>(X);
251///
252/// fn higher_order(_: &()) { }
253///
254/// const CFN: Wrap<fn(&())> = Wrap(higher_order);
255///
256/// #[allow(pointer_structural_match)]
257/// fn main() {
258/// match CFN {
259/// CFN => {}
260/// _ => {}
261/// }
262/// }
263/// ```
264///
265/// (The problem in the above code is that `Wrap<fn(&())>` does not implement
266/// `PartialEq`, nor `Eq`, because `for<'a> fn(&'a _)` does not implement those
267/// traits.)
268///
269/// Therefore, we cannot rely on naive check for `StructuralPartialEq` and
270/// mere `Eq`.
271///
272/// As a hack to work around this, we use two separate traits injected by each
273/// of the two derives (`#[derive(PartialEq)]` and `#[derive(Eq)]`) and check
274/// that both of them are present as part of structural-match checking.
275#[unstable(feature = "structural_match", issue = "31434")]
276#[diagnostic::on_unimplemented(message = "the type `{Self}` does not `#[derive(Eq)]`")]
277#[lang = "structural_teq"]
278#[cfg(bootstrap)]
279pub trait StructuralEq {
280 // Empty.
281}
282
283// FIXME: Remove special cases of these types from the compiler pattern checking code and always check `T: StructuralEq` instead
284marker_impls! {
285 #[unstable(feature = "structural_match", issue = "31434")]
286 #[cfg(bootstrap)]
287 StructuralEq for
288 usize, u8, u16, u32, u64, u128,
289 isize, i8, i16, i32, i64, i128,
290 bool,
291 char,
292 str /* Technically requires `[u8]: StructuralEq` */,
293 (),
294 {T, const N: usize} [T; N],
295 {T} [T],
296 {T: ?Sized} &T,
297}
298
299/// Types whose values can be duplicated simply by copying bits.
300///
301/// By default, variable bindings have 'move semantics.' In other
302/// words:
303///
304/// ```
305/// #[derive(Debug)]
306/// struct Foo;
307///
308/// let x = Foo;
309///
310/// let y = x;
311///
312/// // `x` has moved into `y`, and so cannot be used
313///
314/// // println!("{x:?}"); // error: use of moved value
315/// ```
316///
317/// However, if a type implements `Copy`, it instead has 'copy semantics':
318///
319/// ```
320/// // We can derive a `Copy` implementation. `Clone` is also required, as it's
321/// // a supertrait of `Copy`.
322/// #[derive(Debug, Copy, Clone)]
323/// struct Foo;
324///
325/// let x = Foo;
326///
327/// let y = x;
328///
329/// // `y` is a copy of `x`
330///
331/// println!("{x:?}"); // A-OK!
332/// ```
333///
334/// It's important to note that in these two examples, the only difference is whether you
335/// are allowed to access `x` after the assignment. Under the hood, both a copy and a move
336/// can result in bits being copied in memory, although this is sometimes optimized away.
337///
338/// ## How can I implement `Copy`?
339///
340/// There are two ways to implement `Copy` on your type. The simplest is to use `derive`:
341///
342/// ```
343/// #[derive(Copy, Clone)]
344/// struct MyStruct;
345/// ```
346///
347/// You can also implement `Copy` and `Clone` manually:
348///
349/// ```
350/// struct MyStruct;
351///
352/// impl Copy for MyStruct { }
353///
354/// impl Clone for MyStruct {
355/// fn clone(&self) -> MyStruct {
356/// *self
357/// }
358/// }
359/// ```
360///
361/// There is a small difference between the two: the `derive` strategy will also place a `Copy`
362/// bound on type parameters, which isn't always desired.
363///
364/// ## What's the difference between `Copy` and `Clone`?
365///
366/// Copies happen implicitly, for example as part of an assignment `y = x`. The behavior of
367/// `Copy` is not overloadable; it is always a simple bit-wise copy.
368///
369/// Cloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can
370/// provide any type-specific behavior necessary to duplicate values safely. For example,
371/// the implementation of [`Clone`] for [`String`] needs to copy the pointed-to string
372/// buffer in the heap. A simple bitwise copy of [`String`] values would merely copy the
373/// pointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`]
374/// but not `Copy`.
375///
376/// [`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement
377/// [`Clone`]. If a type is `Copy` then its [`Clone`] implementation only needs to return `*self`
378/// (see the example above).
379///
380/// ## When can my type be `Copy`?
381///
382/// A type can implement `Copy` if all of its components implement `Copy`. For example, this
383/// struct can be `Copy`:
384///
385/// ```
386/// # #[allow(dead_code)]
387/// #[derive(Copy, Clone)]
388/// struct Point {
389/// x: i32,
390/// y: i32,
391/// }
392/// ```
393///
394/// A struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`.
395/// By contrast, consider
396///
397/// ```
398/// # #![allow(dead_code)]
399/// # struct Point;
400/// struct PointList {
401/// points: Vec<Point>,
402/// }
403/// ```
404///
405/// The struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we
406/// attempt to derive a `Copy` implementation, we'll get an error:
407///
408/// ```text
409/// the trait `Copy` cannot be implemented for this type; field `points` does not implement `Copy`
410/// ```
411///
412/// Shared references (`&T`) are also `Copy`, so a type can be `Copy`, even when it holds
413/// shared references of types `T` that are *not* `Copy`. Consider the following struct,
414/// which can implement `Copy`, because it only holds a *shared reference* to our non-`Copy`
415/// type `PointList` from above:
416///
417/// ```
418/// # #![allow(dead_code)]
419/// # struct PointList;
420/// #[derive(Copy, Clone)]
421/// struct PointListWrapper<'a> {
422/// point_list_ref: &'a PointList,
423/// }
424/// ```
425///
426/// ## When *can't* my type be `Copy`?
427///
428/// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
429/// mutable reference. Copying [`String`] would duplicate responsibility for managing the
430/// [`String`]'s buffer, leading to a double free.
431///
432/// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's
433/// managing some resource besides its own [`size_of::<T>`] bytes.
434///
435/// If you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get
436/// the error [E0204].
437///
438/// [E0204]: ../../error_codes/E0204.html
439///
440/// ## When *should* my type be `Copy`?
441///
442/// Generally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though,
443/// that implementing `Copy` is part of the public API of your type. If the type might become
444/// non-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to
445/// avoid a breaking API change.
446///
447/// ## Additional implementors
448///
449/// In addition to the [implementors listed below][impls],
450/// the following types also implement `Copy`:
451///
452/// * Function item types (i.e., the distinct types defined for each function)
453/// * Function pointer types (e.g., `fn() -> i32`)
454/// * Closure types, if they capture no value from the environment
455/// or if all such captured values implement `Copy` themselves.
456/// Note that variables captured by shared reference always implement `Copy`
457/// (even if the referent doesn't),
458/// while variables captured by mutable reference never implement `Copy`.
459///
460/// [`Vec<T>`]: ../../std/vec/struct.Vec.html
461/// [`String`]: ../../std/string/struct.String.html
462/// [`size_of::<T>`]: crate::mem::size_of
463/// [impls]: #implementors
464#[stable(feature = "rust1", since = "1.0.0")]
465#[lang = "copy"]
466// FIXME(matthewjasper) This allows copying a type that doesn't implement
467// `Copy` because of unsatisfied lifetime bounds (copying `A<'_>` when only
468// `A<'static>: Copy` and `A<'_>: Clone`).
469// We have this attribute here for now only because there are quite a few
470// existing specializations on `Copy` that already exist in the standard
471// library, and there's no way to safely have this behavior right now.
472#[rustc_unsafe_specialization_marker]
473#[rustc_diagnostic_item = "Copy"]
474pub trait Copy: Clone {
475 // Empty.
476}
477
478/// Derive macro generating an impl of the trait `Copy`.
479#[rustc_builtin_macro]
480#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
481#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
482pub macro Copy($item:item) {
483 /* compiler built-in */
484}
485
486// Implementations of `Copy` for primitive types.
487//
488// Implementations that cannot be described in Rust
489// are implemented in `traits::SelectionContext::copy_clone_conditions()`
490// in `rustc_trait_selection`.
491marker_impls! {
492 #[stable(feature = "rust1", since = "1.0.0")]
493 Copy for
494 usize, u8, u16, u32, u64, u128,
495 isize, i8, i16, i32, i64, i128,
496 f32, f64,
497 bool, char,
498 {T: ?Sized} *const T,
499 {T: ?Sized} *mut T,
500
501}
502
503#[unstable(feature = "never_type", issue = "35121")]
504impl Copy for ! {}
505
506/// Shared references can be copied, but mutable references *cannot*!
507#[stable(feature = "rust1", since = "1.0.0")]
508impl<T: ?Sized> Copy for &T {}
509
510/// Types for which it is safe to share references between threads.
511///
512/// This trait is automatically implemented when the compiler determines
513/// it's appropriate.
514///
515/// The precise definition is: a type `T` is [`Sync`] if and only if `&T` is
516/// [`Send`]. In other words, if there is no possibility of
517/// [undefined behavior][ub] (including data races) when passing
518/// `&T` references between threads.
519///
520/// As one would expect, primitive types like [`u8`] and [`f64`]
521/// are all [`Sync`], and so are simple aggregate types containing them,
522/// like tuples, structs and enums. More examples of basic [`Sync`]
523/// types include "immutable" types like `&T`, and those with simple
524/// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and
525/// most other collection types. (Generic parameters need to be [`Sync`]
526/// for their container to be [`Sync`].)
527///
528/// A somewhat surprising consequence of the definition is that `&mut T`
529/// is `Sync` (if `T` is `Sync`) even though it seems like that might
530/// provide unsynchronized mutation. The trick is that a mutable
531/// reference behind a shared reference (that is, `& &mut T`)
532/// becomes read-only, as if it were a `& &T`. Hence there is no risk
533/// of a data race.
534///
535/// A shorter overview of how [`Sync`] and [`Send`] relate to referencing:
536/// * `&T` is [`Send`] if and only if `T` is [`Sync`]
537/// * `&mut T` is [`Send`] if and only if `T` is [`Send`]
538/// * `&T` and `&mut T` are [`Sync`] if and only if `T` is [`Sync`]
539///
540/// Types that are not `Sync` are those that have "interior
541/// mutability" in a non-thread-safe form, such as [`Cell`][cell]
542/// and [`RefCell`][refcell]. These types allow for mutation of
543/// their contents even through an immutable, shared reference. For
544/// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires
545/// only a shared reference [`&Cell<T>`][cell]. The method performs no
546/// synchronization, thus [`Cell`][cell] cannot be `Sync`.
547///
548/// Another example of a non-`Sync` type is the reference-counting
549/// pointer [`Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone
550/// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.
551///
552/// For cases when one does need thread-safe interior mutability,
553/// Rust provides [atomic data types], as well as explicit locking via
554/// [`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types
555/// ensure that any mutation cannot cause data races, hence the types
556/// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe
557/// analogue of [`Rc`][rc].
558///
559/// Any types with interior mutability must also use the
560/// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which
561/// can be mutated through a shared reference. Failing to doing this is
562/// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing
563/// from `&T` to `&mut T` is invalid.
564///
565/// See [the Nomicon][nomicon-send-and-sync] for more details about `Sync`.
566///
567/// [box]: ../../std/boxed/struct.Box.html
568/// [vec]: ../../std/vec/struct.Vec.html
569/// [cell]: crate::cell::Cell
570/// [refcell]: crate::cell::RefCell
571/// [rc]: ../../std/rc/struct.Rc.html
572/// [arc]: ../../std/sync/struct.Arc.html
573/// [atomic data types]: crate::sync::atomic
574/// [mutex]: ../../std/sync/struct.Mutex.html
575/// [rwlock]: ../../std/sync/struct.RwLock.html
576/// [unsafecell]: crate::cell::UnsafeCell
577/// [ub]: ../../reference/behavior-considered-undefined.html
578/// [transmute]: crate::mem::transmute
579/// [nomicon-send-and-sync]: ../../nomicon/send-and-sync.html
580#[stable(feature = "rust1", since = "1.0.0")]
581#[cfg_attr(not(test), rustc_diagnostic_item = "Sync")]
582#[lang = "sync"]
583#[rustc_on_unimplemented(
584 on(
585 _Self = "core::cell::once::OnceCell<T>",
586 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::OnceLock` instead"
587 ),
588 on(
589 _Self = "core::cell::Cell<u8>",
590 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU8` instead",
591 ),
592 on(
593 _Self = "core::cell::Cell<u16>",
594 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU16` instead",
595 ),
596 on(
597 _Self = "core::cell::Cell<u32>",
598 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU32` instead",
599 ),
600 on(
601 _Self = "core::cell::Cell<u64>",
602 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU64` instead",
603 ),
604 on(
605 _Self = "core::cell::Cell<usize>",
606 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicUsize` instead",
607 ),
608 on(
609 _Self = "core::cell::Cell<i8>",
610 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI8` instead",
611 ),
612 on(
613 _Self = "core::cell::Cell<i16>",
614 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI16` instead",
615 ),
616 on(
617 _Self = "core::cell::Cell<i32>",
618 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead",
619 ),
620 on(
621 _Self = "core::cell::Cell<i64>",
622 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicI64` instead",
623 ),
624 on(
625 _Self = "core::cell::Cell<isize>",
626 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicIsize` instead",
627 ),
628 on(
629 _Self = "core::cell::Cell<bool>",
630 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicBool` instead",
631 ),
632 on(
633 all(
634 _Self = "core::cell::Cell<T>",
635 not(_Self = "core::cell::Cell<u8>"),
636 not(_Self = "core::cell::Cell<u16>"),
637 not(_Self = "core::cell::Cell<u32>"),
638 not(_Self = "core::cell::Cell<u64>"),
639 not(_Self = "core::cell::Cell<usize>"),
640 not(_Self = "core::cell::Cell<i8>"),
641 not(_Self = "core::cell::Cell<i16>"),
642 not(_Self = "core::cell::Cell<i32>"),
643 not(_Self = "core::cell::Cell<i64>"),
644 not(_Self = "core::cell::Cell<isize>"),
645 not(_Self = "core::cell::Cell<bool>")
646 ),
647 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock`",
648 ),
649 on(
650 _Self = "core::cell::RefCell<T>",
651 note = "if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead",
652 ),
653 message = "`{Self}` cannot be shared between threads safely",
654 label = "`{Self}` cannot be shared between threads safely"
655)]
656pub unsafe auto trait Sync {
657 // FIXME(estebank): once support to add notes in `rustc_on_unimplemented`
658 // lands in beta, and it has been extended to check whether a closure is
659 // anywhere in the requirement chain, extend it as such (#48534):
660 // ```
661 // on(
662 // closure,
663 // note="`{Self}` cannot be shared safely, consider marking the closure `move`"
664 // ),
665 // ```
666
667 // Empty
668}
669
670#[stable(feature = "rust1", since = "1.0.0")]
671impl<T: ?Sized> !Sync for *const T {}
672#[stable(feature = "rust1", since = "1.0.0")]
673impl<T: ?Sized> !Sync for *mut T {}
674
675/// Zero-sized type used to mark things that "act like" they own a `T`.
676///
677/// Adding a `PhantomData<T>` field to your type tells the compiler that your
678/// type acts as though it stores a value of type `T`, even though it doesn't
679/// really. This information is used when computing certain safety properties.
680///
681/// For a more in-depth explanation of how to use `PhantomData<T>`, please see
682/// [the Nomicon](../../nomicon/phantom-data.html).
683///
684/// # A ghastly note 👻👻👻
685///
686/// Though they both have scary names, `PhantomData` and 'phantom types' are
687/// related, but not identical. A phantom type parameter is simply a type
688/// parameter which is never used. In Rust, this often causes the compiler to
689/// complain, and the solution is to add a "dummy" use by way of `PhantomData`.
690///
691/// # Examples
692///
693/// ## Unused lifetime parameters
694///
695/// Perhaps the most common use case for `PhantomData` is a struct that has an
696/// unused lifetime parameter, typically as part of some unsafe code. For
697/// example, here is a struct `Slice` that has two pointers of type `*const T`,
698/// presumably pointing into an array somewhere:
699///
700/// ```compile_fail,E0392
701/// struct Slice<'a, T> {
702/// start: *const T,
703/// end: *const T,
704/// }
705/// ```
706///
707/// The intention is that the underlying data is only valid for the
708/// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
709/// intent is not expressed in the code, since there are no uses of
710/// the lifetime `'a` and hence it is not clear what data it applies
711/// to. We can correct this by telling the compiler to act *as if* the
712/// `Slice` struct contained a reference `&'a T`:
713///
714/// ```
715/// use std::marker::PhantomData;
716///
717/// # #[allow(dead_code)]
718/// struct Slice<'a, T> {
719/// start: *const T,
720/// end: *const T,
721/// phantom: PhantomData<&'a T>,
722/// }
723/// ```
724///
725/// This also in turn infers the lifetime bound `T: 'a`, indicating
726/// that any references in `T` are valid over the lifetime `'a`.
727///
728/// When initializing a `Slice` you simply provide the value
729/// `PhantomData` for the field `phantom`:
730///
731/// ```
732/// # #![allow(dead_code)]
733/// # use std::marker::PhantomData;
734/// # struct Slice<'a, T> {
735/// # start: *const T,
736/// # end: *const T,
737/// # phantom: PhantomData<&'a T>,
738/// # }
739/// fn borrow_vec<T>(vec: &Vec<T>) -> Slice<'_, T> {
740/// let ptr = vec.as_ptr();
741/// Slice {
742/// start: ptr,
743/// end: unsafe { ptr.add(vec.len()) },
744/// phantom: PhantomData,
745/// }
746/// }
747/// ```
748///
749/// ## Unused type parameters
750///
751/// It sometimes happens that you have unused type parameters which
752/// indicate what type of data a struct is "tied" to, even though that
753/// data is not actually found in the struct itself. Here is an
754/// example where this arises with [FFI]. The foreign interface uses
755/// handles of type `*mut ()` to refer to Rust values of different
756/// types. We track the Rust type using a phantom type parameter on
757/// the struct `ExternalResource` which wraps a handle.
758///
759/// [FFI]: ../../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
760///
761/// ```
762/// # #![allow(dead_code)]
763/// # trait ResType { }
764/// # struct ParamType;
765/// # mod foreign_lib {
766/// # pub fn new(_: usize) -> *mut () { 42 as *mut () }
767/// # pub fn do_stuff(_: *mut (), _: usize) {}
768/// # }
769/// # fn convert_params(_: ParamType) -> usize { 42 }
770/// use std::marker::PhantomData;
771/// use std::mem;
772///
773/// struct ExternalResource<R> {
774/// resource_handle: *mut (),
775/// resource_type: PhantomData<R>,
776/// }
777///
778/// impl<R: ResType> ExternalResource<R> {
779/// fn new() -> Self {
780/// let size_of_res = mem::size_of::<R>();
781/// Self {
782/// resource_handle: foreign_lib::new(size_of_res),
783/// resource_type: PhantomData,
784/// }
785/// }
786///
787/// fn do_stuff(&self, param: ParamType) {
788/// let foreign_params = convert_params(param);
789/// foreign_lib::do_stuff(self.resource_handle, foreign_params);
790/// }
791/// }
792/// ```
793///
794/// ## Ownership and the drop check
795///
796/// The exact interaction of `PhantomData` with drop check **may change in the future**.
797///
798/// Currently, adding a field of type `PhantomData<T>` indicates that your type *owns* data of type
799/// `T` in very rare circumstances. This in turn has effects on the Rust compiler's [drop check]
800/// analysis. For the exact rules, see the [drop check] documentation.
801///
802/// ## Layout
803///
804/// For all `T`, the following are guaranteed:
805/// * `size_of::<PhantomData<T>>() == 0`
806/// * `align_of::<PhantomData<T>>() == 1`
807///
808/// [drop check]: Drop#drop-check
809#[lang = "phantom_data"]
810#[stable(feature = "rust1", since = "1.0.0")]
811pub struct PhantomData<T: ?Sized>;
812
813#[stable(feature = "rust1", since = "1.0.0")]
814impl<T: ?Sized> Hash for PhantomData<T> {
815 #[inline]
816 fn hash<H: Hasher>(&self, _: &mut H) {}
817}
818
819#[stable(feature = "rust1", since = "1.0.0")]
820impl<T: ?Sized> cmp::PartialEq for PhantomData<T> {
821 fn eq(&self, _other: &PhantomData<T>) -> bool {
822 true
823 }
824}
825
826#[stable(feature = "rust1", since = "1.0.0")]
827impl<T: ?Sized> cmp::Eq for PhantomData<T> {}
828
829#[stable(feature = "rust1", since = "1.0.0")]
830impl<T: ?Sized> cmp::PartialOrd for PhantomData<T> {
831 fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<cmp::Ordering> {
832 Option::Some(cmp::Ordering::Equal)
833 }
834}
835
836#[stable(feature = "rust1", since = "1.0.0")]
837impl<T: ?Sized> cmp::Ord for PhantomData<T> {
838 fn cmp(&self, _other: &PhantomData<T>) -> cmp::Ordering {
839 cmp::Ordering::Equal
840 }
841}
842
843#[stable(feature = "rust1", since = "1.0.0")]
844impl<T: ?Sized> Copy for PhantomData<T> {}
845
846#[stable(feature = "rust1", since = "1.0.0")]
847impl<T: ?Sized> Clone for PhantomData<T> {
848 fn clone(&self) -> Self {
849 Self
850 }
851}
852
853#[stable(feature = "rust1", since = "1.0.0")]
854impl<T: ?Sized> Default for PhantomData<T> {
855 fn default() -> Self {
856 Self
857 }
858}
859
860#[unstable(feature = "structural_match", issue = "31434")]
861impl<T: ?Sized> StructuralPartialEq for PhantomData<T> {}
862
863#[unstable(feature = "structural_match", issue = "31434")]
864#[cfg(bootstrap)]
865impl<T: ?Sized> StructuralEq for PhantomData<T> {}
866
867/// Compiler-internal trait used to indicate the type of enum discriminants.
868///
869/// This trait is automatically implemented for every type and does not add any
870/// guarantees to [`mem::Discriminant`]. It is **undefined behavior** to transmute
871/// between `DiscriminantKind::Discriminant` and `mem::Discriminant`.
872///
873/// [`mem::Discriminant`]: crate::mem::Discriminant
874#[unstable(
875 feature = "discriminant_kind",
876 issue = "none",
877 reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead"
878)]
879#[lang = "discriminant_kind"]
880#[rustc_deny_explicit_impl(implement_via_object = false)]
881pub trait DiscriminantKind {
882 /// The type of the discriminant, which must satisfy the trait
883 /// bounds required by `mem::Discriminant`.
884 #[lang = "discriminant_type"]
885 type Discriminant: Clone + Copy + Debug + Eq + PartialEq + Hash + Send + Sync + Unpin;
886}
887
888/// Compiler-internal trait used to determine whether a type contains
889/// any `UnsafeCell` internally, but not through an indirection.
890/// This affects, for example, whether a `static` of that type is
891/// placed in read-only static memory or writable static memory.
892#[lang = "freeze"]
893pub(crate) unsafe auto trait Freeze {}
894
895impl<T: ?Sized> !Freeze for UnsafeCell<T> {}
896marker_impls! {
897 unsafe Freeze for
898 {T: ?Sized} PhantomData<T>,
899 {T: ?Sized} *const T,
900 {T: ?Sized} *mut T,
901 {T: ?Sized} &T,
902 {T: ?Sized} &mut T,
903}
904
905/// Types that do not require any pinning guarantees.
906///
907/// For information on what "pinning" is, see the [`pin` module] documentation.
908///
909/// Implementing the `Unpin` trait for `T` expresses the fact that `T` is pinning-agnostic:
910/// it shall not expose nor rely on any pinning guarantees. This, in turn, means that a
911/// `Pin`-wrapped pointer to such a type can feature a *fully unrestricted* API.
912/// In other words, if `T: Unpin`, a value of type `T` will *not* be bound by the invariants
913/// which pinning otherwise offers, even when "pinned" by a [`Pin<Ptr>`] pointing at it.
914/// When a value of type `T` is pointed at by a [`Pin<Ptr>`], [`Pin`] will not restrict access
915/// to the pointee value like it normally would, thus allowing the user to do anything that they
916/// normally could with a non-[`Pin`]-wrapped `Ptr` to that value.
917///
918/// The idea of this trait is to alleviate the reduced ergonomics of APIs that require the use
919/// of [`Pin`] for soundness for some types, but which also want to be used by other types that
920/// don't care about pinning. The prime example of such an API is [`Future::poll`]. There are many
921/// [`Future`] types that don't care about pinning. These futures can implement `Unpin` and
922/// therefore get around the pinning related restrictions in the API, while still allowing the
923/// subset of [`Future`]s which *do* require pinning to be implemented soundly.
924///
925/// For more discussion on the consequences of [`Unpin`] within the wider scope of the pinning
926/// system, see the [section about `Unpin`] in the [`pin` module].
927///
928/// `Unpin` has no consequence at all for non-pinned data. In particular, [`mem::replace`] happily
929/// moves `!Unpin` data, which would be immovable when pinned ([`mem::replace`] works for any
930/// `&mut T`, not just when `T: Unpin`).
931///
932/// *However*, you cannot use [`mem::replace`] on `!Unpin` data which is *pinned* by being wrapped
933/// inside a [`Pin<Ptr>`] pointing at it. This is because you cannot (safely) use a
934/// [`Pin<Ptr>`] to get an `&mut T` to its pointee value, which you would need to call
935/// [`mem::replace`], and *that* is what makes this system work.
936///
937/// So this, for example, can only be done on types implementing `Unpin`:
938///
939/// ```rust
940/// # #![allow(unused_must_use)]
941/// use std::mem;
942/// use std::pin::Pin;
943///
944/// let mut string = "this".to_string();
945/// let mut pinned_string = Pin::new(&mut string);
946///
947/// // We need a mutable reference to call `mem::replace`.
948/// // We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`,
949/// // but that is only possible because `String` implements `Unpin`.
950/// mem::replace(&mut *pinned_string, "other".to_string());
951/// ```
952///
953/// This trait is automatically implemented for almost every type. The compiler is free
954/// to take the conservative stance of marking types as [`Unpin`] so long as all of the types that
955/// compose its fields are also [`Unpin`]. This is because if a type implements [`Unpin`], then it
956/// is unsound for that type's implementation to rely on pinning-related guarantees for soundness,
957/// *even* when viewed through a "pinning" pointer! It is the responsibility of the implementor of
958/// a type that relies upon pinning for soundness to ensure that type is *not* marked as [`Unpin`]
959/// by adding [`PhantomPinned`] field. For more details, see the [`pin` module] docs.
960///
961/// [`mem::replace`]: crate::mem::replace "mem replace"
962/// [`Future`]: crate::future::Future "Future"
963/// [`Future::poll`]: crate::future::Future::poll "Future poll"
964/// [`Pin`]: crate::pin::Pin "Pin"
965/// [`Pin<Ptr>`]: crate::pin::Pin "Pin"
966/// [`pin` module]: crate::pin "pin module"
967/// [section about `Unpin`]: crate::pin#unpin "pin module docs about unpin"
968/// [`unsafe`]: ../../std/keyword.unsafe.html "keyword unsafe"
969#[stable(feature = "pin", since = "1.33.0")]
970#[diagnostic::on_unimplemented(
971 note = "consider using the `pin!` macro\nconsider using `Box::pin` if you need to access the pinned value outside of the current scope",
972 message = "`{Self}` cannot be unpinned"
973)]
974#[lang = "unpin"]
975pub auto trait Unpin {}
976
977/// A marker type which does not implement `Unpin`.
978///
979/// If a type contains a `PhantomPinned`, it will not implement `Unpin` by default.
980#[stable(feature = "pin", since = "1.33.0")]
981#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
982pub struct PhantomPinned;
983
984#[stable(feature = "pin", since = "1.33.0")]
985impl !Unpin for PhantomPinned {}
986
987marker_impls! {
988 #[stable(feature = "pin", since = "1.33.0")]
989 Unpin for
990 {T: ?Sized} &T,
991 {T: ?Sized} &mut T,
992}
993
994marker_impls! {
995 #[stable(feature = "pin_raw", since = "1.38.0")]
996 Unpin for
997 {T: ?Sized} *const T,
998 {T: ?Sized} *mut T,
999}
1000
1001/// A marker for types that can be dropped.
1002///
1003/// This should be used for `~const` bounds,
1004/// as non-const bounds will always hold for every type.
1005#[unstable(feature = "const_trait_impl", issue = "67792")]
1006#[lang = "destruct"]
1007#[rustc_on_unimplemented(message = "can't drop `{Self}`", append_const_msg)]
1008#[rustc_deny_explicit_impl(implement_via_object = false)]
1009#[const_trait]
1010pub trait Destruct {}
1011
1012/// A marker for tuple types.
1013///
1014/// The implementation of this trait is built-in and cannot be implemented
1015/// for any user type.
1016#[unstable(feature = "tuple_trait", issue = "none")]
1017#[lang = "tuple_trait"]
1018#[diagnostic::on_unimplemented(message = "`{Self}` is not a tuple")]
1019#[rustc_deny_explicit_impl(implement_via_object = false)]
1020pub trait Tuple {}
1021
1022/// A marker for pointer-like types.
1023///
1024/// All types that have the same size and alignment as a `usize` or
1025/// `*const ()` automatically implement this trait.
1026#[unstable(feature = "pointer_like_trait", issue = "none")]
1027#[lang = "pointer_like"]
1028#[diagnostic::on_unimplemented(
1029 message = "`{Self}` needs to have the same ABI as a pointer",
1030 label = "`{Self}` needs to be a pointer-like type"
1031)]
1032pub trait PointerLike {}
1033
1034/// A marker for types which can be used as types of `const` generic parameters.
1035///
1036/// These types must have a proper equivalence relation (`Eq`) and it must be automatically
1037/// derived (`StructuralPartialEq`). There's a hard-coded check in the compiler ensuring
1038/// that all fields are also `ConstParamTy`, which implies that recursively, all fields
1039/// are `StructuralPartialEq`.
1040#[lang = "const_param_ty"]
1041#[unstable(feature = "adt_const_params", issue = "95174")]
1042#[diagnostic::on_unimplemented(message = "`{Self}` can't be used as a const parameter type")]
1043#[allow(multiple_supertrait_upcastable)]
1044#[cfg(not(bootstrap))]
1045pub trait ConstParamTy: StructuralPartialEq + Eq {}
1046
1047/// A marker for types which can be used as types of `const` generic parameters.
1048///
1049/// These types must have a proper equivalence relation (`Eq`) and it must be automatically
1050/// derived (`StructuralPartialEq`). There's a hard-coded check in the compiler ensuring
1051/// that all fields are also `ConstParamTy`, which implies that recursively, all fields
1052/// are `StructuralPartialEq`.
1053#[lang = "const_param_ty"]
1054#[unstable(feature = "adt_const_params", issue = "95174")]
1055#[rustc_on_unimplemented(message = "`{Self}` can't be used as a const parameter type")]
1056#[allow(multiple_supertrait_upcastable)]
1057#[cfg(bootstrap)]
1058pub trait ConstParamTy: StructuralEq + StructuralPartialEq + Eq {}
1059
1060/// Derive macro generating an impl of the trait `ConstParamTy`.
1061#[rustc_builtin_macro]
1062#[unstable(feature = "adt_const_params", issue = "95174")]
1063pub macro ConstParamTy($item:item) {
1064 /* compiler built-in */
1065}
1066
1067// FIXME(adt_const_params): handle `ty::FnDef`/`ty::Closure`
1068marker_impls! {
1069 #[unstable(feature = "adt_const_params", issue = "95174")]
1070 ConstParamTy for
1071 usize, u8, u16, u32, u64, u128,
1072 isize, i8, i16, i32, i64, i128,
1073 bool,
1074 char,
1075 str /* Technically requires `[u8]: ConstParamTy` */,
1076 {T: ConstParamTy, const N: usize} [T; N],
1077 {T: ConstParamTy} [T],
1078 {T: ?Sized + ConstParamTy} &T,
1079}
1080
1081// FIXME(adt_const_params): Add to marker_impls call above once not in bootstrap
1082#[unstable(feature = "adt_const_params", issue = "95174")]
1083impl ConstParamTy for () {}
1084
1085/// A common trait implemented by all function pointers.
1086#[unstable(
1087 feature = "fn_ptr_trait",
1088 issue = "none",
1089 reason = "internal trait for implementing various traits for all function pointers"
1090)]
1091#[lang = "fn_ptr_trait"]
1092#[rustc_deny_explicit_impl(implement_via_object = false)]
1093pub trait FnPtr: Copy + Clone {
1094 /// Returns the address of the function pointer.
1095 #[lang = "fn_ptr_addr"]
1096 fn addr(self) -> *const ();
1097}
1098