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