]> git.lizzy.rs Git - rust.git/blob - src/libcore/marker.rs
Rollup merge of #73169 - Amanieu:asm-warnings, r=petrochenkov
[rust.git] / src / libcore / marker.rs
1 //! Primitive traits and types representing basic properties of types.
2 //!
3 //! Rust types can be classified in various useful ways according to
4 //! their intrinsic properties. These classifications are represented
5 //! as traits.
6
7 #![stable(feature = "rust1", since = "1.0.0")]
8
9 use crate::cell::UnsafeCell;
10 use crate::cmp;
11 use crate::fmt::Debug;
12 use crate::hash::Hash;
13 use crate::hash::Hasher;
14
15 /// Types that can be transferred across thread boundaries.
16 ///
17 /// This trait is automatically implemented when the compiler determines it's
18 /// appropriate.
19 ///
20 /// An example of a non-`Send` type is the reference-counting pointer
21 /// [`rc::Rc`][`Rc`]. If two threads attempt to clone [`Rc`]s that point to the same
22 /// reference-counted value, they might try to update the reference count at the
23 /// same time, which is [undefined behavior][ub] because [`Rc`] doesn't use atomic
24 /// operations. Its cousin [`sync::Arc`][arc] does use atomic operations (incurring
25 /// some overhead) and thus is `Send`.
26 ///
27 /// See [the Nomicon](../../nomicon/send-and-sync.html) for more details.
28 ///
29 /// [`Rc`]: ../../std/rc/struct.Rc.html
30 /// [arc]: ../../std/sync/struct.Arc.html
31 /// [ub]: ../../reference/behavior-considered-undefined.html
32 #[stable(feature = "rust1", since = "1.0.0")]
33 #[cfg_attr(not(test), rustc_diagnostic_item = "send_trait")]
34 #[rustc_on_unimplemented(
35     message = "`{Self}` cannot be sent between threads safely",
36     label = "`{Self}` cannot be sent between threads safely"
37 )]
38 pub unsafe auto trait Send {
39     // empty.
40 }
41
42 #[stable(feature = "rust1", since = "1.0.0")]
43 impl<T: ?Sized> !Send for *const T {}
44 #[stable(feature = "rust1", since = "1.0.0")]
45 impl<T: ?Sized> !Send for *mut T {}
46
47 /// Types with a constant size known at compile time.
48 ///
49 /// All type parameters have an implicit bound of `Sized`. The special syntax
50 /// `?Sized` can be used to remove this bound if it's not appropriate.
51 ///
52 /// ```
53 /// # #![allow(dead_code)]
54 /// struct Foo<T>(T);
55 /// struct Bar<T: ?Sized>(T);
56 ///
57 /// // struct FooUse(Foo<[i32]>); // error: Sized is not implemented for [i32]
58 /// struct BarUse(Bar<[i32]>); // OK
59 /// ```
60 ///
61 /// The one exception is the implicit `Self` type of a trait. A trait does not
62 /// have an implicit `Sized` bound as this is incompatible with [trait object]s
63 /// where, by definition, the trait needs to work with all possible implementors,
64 /// and thus could be any size.
65 ///
66 /// Although Rust will let you bind `Sized` to a trait, you won't
67 /// be able to use it to form a trait object later:
68 ///
69 /// ```
70 /// # #![allow(unused_variables)]
71 /// trait Foo { }
72 /// trait Bar: Sized { }
73 ///
74 /// struct Impl;
75 /// impl Foo for Impl { }
76 /// impl Bar for Impl { }
77 ///
78 /// let x: &dyn Foo = &Impl;    // OK
79 /// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot
80 ///                             // be made into an object
81 /// ```
82 ///
83 /// [trait object]: ../../book/ch17-02-trait-objects.html
84 #[stable(feature = "rust1", since = "1.0.0")]
85 #[lang = "sized"]
86 #[rustc_on_unimplemented(
87     on(parent_trait = "std::path::Path", label = "borrow the `Path` instead"),
88     message = "the size for values of type `{Self}` cannot be known at compilation time",
89     label = "doesn't have a size known at compile-time",
90     note = "to learn more, visit <https://doc.rust-lang.org/book/\
91             ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>"
92 )]
93 #[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
94 #[rustc_specialization_trait]
95 pub trait Sized {
96     // Empty.
97 }
98
99 /// Types that can be "unsized" to a dynamically-sized type.
100 ///
101 /// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and
102 /// `Unsize<dyn fmt::Debug>`.
103 ///
104 /// All implementations of `Unsize` are provided automatically by the compiler.
105 ///
106 /// `Unsize` is implemented for:
107 ///
108 /// - `[T; N]` is `Unsize<[T]>`
109 /// - `T` is `Unsize<dyn Trait>` when `T: Trait`
110 /// - `Foo<..., T, ...>` is `Unsize<Foo<..., U, ...>>` if:
111 ///   - `T: Unsize<U>`
112 ///   - Foo is a struct
113 ///   - Only the last field of `Foo` has a type involving `T`
114 ///   - `T` is not part of the type of any other fields
115 ///   - `Bar<T>: Unsize<Bar<U>>`, if the last field of `Foo` has type `Bar<T>`
116 ///
117 /// `Unsize` is used along with [`ops::CoerceUnsized`][coerceunsized] to allow
118 /// "user-defined" containers such as [`rc::Rc`][rc] to contain dynamically-sized
119 /// types. See the [DST coercion RFC][RFC982] and [the nomicon entry on coercion][nomicon-coerce]
120 /// for more details.
121 ///
122 /// [coerceunsized]: ../ops/trait.CoerceUnsized.html
123 /// [rc]: ../../std/rc/struct.Rc.html
124 /// [RFC982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
125 /// [nomicon-coerce]: ../../nomicon/coercions.html
126 #[unstable(feature = "unsize", issue = "27732")]
127 #[lang = "unsize"]
128 pub trait Unsize<T: ?Sized> {
129     // Empty.
130 }
131
132 /// Required trait for constants used in pattern matches.
133 ///
134 /// Any type that derives `PartialEq` automatically implements this trait,
135 /// *regardless* of whether its type-parameters implement `Eq`.
136 ///
137 /// If a `const` item contains some type that does not implement this trait,
138 /// then that type either (1.) does not implement `PartialEq` (which means the
139 /// constant will not provide that comparison method, which code generation
140 /// assumes is available), or (2.) it implements *its own* version of
141 /// `PartialEq` (which we assume does not conform to a structural-equality
142 /// comparison).
143 ///
144 /// In either of the two scenarios above, we reject usage of such a constant in
145 /// a pattern match.
146 ///
147 /// See also the [structural match RFC][RFC1445], and [issue 63438] which
148 /// motivated migrating from attribute-based design to this trait.
149 ///
150 /// [RFC1445]: https://github.com/rust-lang/rfcs/blob/master/text/1445-restrict-constants-in-patterns.md
151 /// [issue 63438]: https://github.com/rust-lang/rust/issues/63438
152 #[unstable(feature = "structural_match", issue = "31434")]
153 #[rustc_on_unimplemented(message = "the type `{Self}` does not `#[derive(PartialEq)]`")]
154 #[lang = "structural_peq"]
155 pub trait StructuralPartialEq {
156     // Empty.
157 }
158
159 /// Required trait for constants used in pattern matches.
160 ///
161 /// Any type that derives `Eq` automatically implements this trait, *regardless*
162 /// of whether its type-parameters implement `Eq`.
163 ///
164 /// This is a hack to workaround a limitation in our type-system.
165 ///
166 /// Background:
167 ///
168 /// We want to require that types of consts used in pattern matches
169 /// have the attribute `#[derive(PartialEq, Eq)]`.
170 ///
171 /// In a more ideal world, we could check that requirement by just checking that
172 /// the given type implements both (1.) the `StructuralPartialEq` trait *and*
173 /// (2.) the `Eq` trait. However, you can have ADTs that *do* `derive(PartialEq, Eq)`,
174 /// and be a case that we want the compiler to accept, and yet the constant's
175 /// type fails to implement `Eq`.
176 ///
177 /// Namely, a case like this:
178 ///
179 /// ```rust
180 /// #[derive(PartialEq, Eq)]
181 /// struct Wrap<X>(X);
182 /// fn higher_order(_: &()) { }
183 /// const CFN: Wrap<fn(&())> = Wrap(higher_order);
184 /// fn main() {
185 ///     match CFN {
186 ///         CFN => {}
187 ///         _ => {}
188 ///     }
189 /// }
190 /// ```
191 ///
192 /// (The problem in the above code is that `Wrap<fn(&())>` does not implement
193 /// `PartialEq`, nor `Eq`, because `for<'a> fn(&'a _)` does not implement those
194 /// traits.)
195 ///
196 /// Therefore, we cannot rely on naive check for `StructuralPartialEq` and
197 /// mere `Eq`.
198 ///
199 /// As a hack to work around this, we use two separate traits injected by each
200 /// of the two derives (`#[derive(PartialEq)]` and `#[derive(Eq)]`) and check
201 /// that both of them are present as part of structural-match checking.
202 #[unstable(feature = "structural_match", issue = "31434")]
203 #[rustc_on_unimplemented(message = "the type `{Self}` does not `#[derive(Eq)]`")]
204 #[lang = "structural_teq"]
205 pub trait StructuralEq {
206     // Empty.
207 }
208
209 /// Types whose values can be duplicated simply by copying bits.
210 ///
211 /// By default, variable bindings have 'move semantics.' In other
212 /// words:
213 ///
214 /// ```
215 /// #[derive(Debug)]
216 /// struct Foo;
217 ///
218 /// let x = Foo;
219 ///
220 /// let y = x;
221 ///
222 /// // `x` has moved into `y`, and so cannot be used
223 ///
224 /// // println!("{:?}", x); // error: use of moved value
225 /// ```
226 ///
227 /// However, if a type implements `Copy`, it instead has 'copy semantics':
228 ///
229 /// ```
230 /// // We can derive a `Copy` implementation. `Clone` is also required, as it's
231 /// // a supertrait of `Copy`.
232 /// #[derive(Debug, Copy, Clone)]
233 /// struct Foo;
234 ///
235 /// let x = Foo;
236 ///
237 /// let y = x;
238 ///
239 /// // `y` is a copy of `x`
240 ///
241 /// println!("{:?}", x); // A-OK!
242 /// ```
243 ///
244 /// It's important to note that in these two examples, the only difference is whether you
245 /// are allowed to access `x` after the assignment. Under the hood, both a copy and a move
246 /// can result in bits being copied in memory, although this is sometimes optimized away.
247 ///
248 /// ## How can I implement `Copy`?
249 ///
250 /// There are two ways to implement `Copy` on your type. The simplest is to use `derive`:
251 ///
252 /// ```
253 /// #[derive(Copy, Clone)]
254 /// struct MyStruct;
255 /// ```
256 ///
257 /// You can also implement `Copy` and `Clone` manually:
258 ///
259 /// ```
260 /// struct MyStruct;
261 ///
262 /// impl Copy for MyStruct { }
263 ///
264 /// impl Clone for MyStruct {
265 ///     fn clone(&self) -> MyStruct {
266 ///         *self
267 ///     }
268 /// }
269 /// ```
270 ///
271 /// There is a small difference between the two: the `derive` strategy will also place a `Copy`
272 /// bound on type parameters, which isn't always desired.
273 ///
274 /// ## What's the difference between `Copy` and `Clone`?
275 ///
276 /// Copies happen implicitly, for example as part of an assignment `y = x`. The behavior of
277 /// `Copy` is not overloadable; it is always a simple bit-wise copy.
278 ///
279 /// Cloning is an explicit action, `x.clone()`. The implementation of [`Clone`] can
280 /// provide any type-specific behavior necessary to duplicate values safely. For example,
281 /// the implementation of [`Clone`] for [`String`] needs to copy the pointed-to string
282 /// buffer in the heap. A simple bitwise copy of [`String`] values would merely copy the
283 /// pointer, leading to a double free down the line. For this reason, [`String`] is [`Clone`]
284 /// but not `Copy`.
285 ///
286 /// [`Clone`] is a supertrait of `Copy`, so everything which is `Copy` must also implement
287 /// [`Clone`]. If a type is `Copy` then its [`Clone`] implementation only needs to return `*self`
288 /// (see the example above).
289 ///
290 /// ## When can my type be `Copy`?
291 ///
292 /// A type can implement `Copy` if all of its components implement `Copy`. For example, this
293 /// struct can be `Copy`:
294 ///
295 /// ```
296 /// # #[allow(dead_code)]
297 /// struct Point {
298 ///    x: i32,
299 ///    y: i32,
300 /// }
301 /// ```
302 ///
303 /// A struct can be `Copy`, and [`i32`] is `Copy`, therefore `Point` is eligible to be `Copy`.
304 /// By contrast, consider
305 ///
306 /// ```
307 /// # #![allow(dead_code)]
308 /// # struct Point;
309 /// struct PointList {
310 ///     points: Vec<Point>,
311 /// }
312 /// ```
313 ///
314 /// The struct `PointList` cannot implement `Copy`, because [`Vec<T>`] is not `Copy`. If we
315 /// attempt to derive a `Copy` implementation, we'll get an error:
316 ///
317 /// ```text
318 /// the trait `Copy` may not be implemented for this type; field `points` does not implement `Copy`
319 /// ```
320 ///
321 /// ## When *can't* my type be `Copy`?
322 ///
323 /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
324 /// mutable reference. Copying [`String`] would duplicate responsibility for managing the
325 /// [`String`]'s buffer, leading to a double free.
326 ///
327 /// Generalizing the latter case, any type implementing [`Drop`] can't be `Copy`, because it's
328 /// managing some resource besides its own [`size_of::<T>`] bytes.
329 ///
330 /// If you try to implement `Copy` on a struct or enum containing non-`Copy` data, you will get
331 /// the error [E0204].
332 ///
333 /// [E0204]: ../../error-index.html#E0204
334 ///
335 /// ## When *should* my type be `Copy`?
336 ///
337 /// Generally speaking, if your type _can_ implement `Copy`, it should. Keep in mind, though,
338 /// that implementing `Copy` is part of the public API of your type. If the type might become
339 /// non-`Copy` in the future, it could be prudent to omit the `Copy` implementation now, to
340 /// avoid a breaking API change.
341 ///
342 /// ## Additional implementors
343 ///
344 /// In addition to the [implementors listed below][impls],
345 /// the following types also implement `Copy`:
346 ///
347 /// * Function item types (i.e., the distinct types defined for each function)
348 /// * Function pointer types (e.g., `fn() -> i32`)
349 /// * Array types, for all sizes, if the item type also implements `Copy` (e.g., `[i32; 123456]`)
350 /// * Tuple types, if each component also implements `Copy` (e.g., `()`, `(i32, bool)`)
351 /// * Closure types, if they capture no value from the environment
352 ///   or if all such captured values implement `Copy` themselves.
353 ///   Note that variables captured by shared reference always implement `Copy`
354 ///   (even if the referent doesn't),
355 ///   while variables captured by mutable reference never implement `Copy`.
356 ///
357 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
358 /// [`String`]: ../../std/string/struct.String.html
359 /// [`Drop`]: ../../std/ops/trait.Drop.html
360 /// [`size_of::<T>`]: ../../std/mem/fn.size_of.html
361 /// [`Clone`]: ../clone/trait.Clone.html
362 /// [`String`]: ../../std/string/struct.String.html
363 /// [`i32`]: ../../std/primitive.i32.html
364 /// [impls]: #implementors
365 #[stable(feature = "rust1", since = "1.0.0")]
366 #[lang = "copy"]
367 // FIXME(matthewjasper) This allows copying a type that doesn't implement
368 // `Copy` because of unsatisfied lifetime bounds (copying `A<'_>` when only
369 // `A<'static>: Copy` and `A<'_>: Clone`).
370 // We have this attribute here for now only because there are quite a few
371 // existing specializations on `Copy` that already exist in the standard
372 // library, and there's no way to safely have this behavior right now.
373 #[rustc_unsafe_specialization_marker]
374 pub trait Copy: Clone {
375     // Empty.
376 }
377
378 /// Derive macro generating an impl of the trait `Copy`.
379 #[rustc_builtin_macro]
380 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
381 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
382 pub macro Copy($item:item) {
383     /* compiler built-in */
384 }
385
386 /// Types for which it is safe to share references between threads.
387 ///
388 /// This trait is automatically implemented when the compiler determines
389 /// it's appropriate.
390 ///
391 /// The precise definition is: a type `T` is `Sync` if and only if `&T` is
392 /// [`Send`][send]. In other words, if there is no possibility of
393 /// [undefined behavior][ub] (including data races) when passing
394 /// `&T` references between threads.
395 ///
396 /// As one would expect, primitive types like [`u8`][u8] and [`f64`][f64]
397 /// are all `Sync`, and so are simple aggregate types containing them,
398 /// like tuples, structs and enums. More examples of basic `Sync`
399 /// types include "immutable" types like `&T`, and those with simple
400 /// inherited mutability, such as [`Box<T>`][box], [`Vec<T>`][vec] and
401 /// most other collection types. (Generic parameters need to be `Sync`
402 /// for their container to be `Sync`.)
403 ///
404 /// A somewhat surprising consequence of the definition is that `&mut T`
405 /// is `Sync` (if `T` is `Sync`) even though it seems like that might
406 /// provide unsynchronized mutation. The trick is that a mutable
407 /// reference behind a shared reference (that is, `& &mut T`)
408 /// becomes read-only, as if it were a `& &T`. Hence there is no risk
409 /// of a data race.
410 ///
411 /// Types that are not `Sync` are those that have "interior
412 /// mutability" in a non-thread-safe form, such as [`cell::Cell`][cell]
413 /// and [`cell::RefCell`][refcell]. These types allow for mutation of
414 /// their contents even through an immutable, shared reference. For
415 /// example the `set` method on [`Cell<T>`][cell] takes `&self`, so it requires
416 /// only a shared reference [`&Cell<T>`][cell]. The method performs no
417 /// synchronization, thus [`Cell`][cell] cannot be `Sync`.
418 ///
419 /// Another example of a non-`Sync` type is the reference-counting
420 /// pointer [`rc::Rc`][rc]. Given any reference [`&Rc<T>`][rc], you can clone
421 /// a new [`Rc<T>`][rc], modifying the reference counts in a non-atomic way.
422 ///
423 /// For cases when one does need thread-safe interior mutability,
424 /// Rust provides [atomic data types], as well as explicit locking via
425 /// [`sync::Mutex`][mutex] and [`sync::RwLock`][rwlock]. These types
426 /// ensure that any mutation cannot cause data races, hence the types
427 /// are `Sync`. Likewise, [`sync::Arc`][arc] provides a thread-safe
428 /// analogue of [`Rc`][rc].
429 ///
430 /// Any types with interior mutability must also use the
431 /// [`cell::UnsafeCell`][unsafecell] wrapper around the value(s) which
432 /// can be mutated through a shared reference. Failing to doing this is
433 /// [undefined behavior][ub]. For example, [`transmute`][transmute]-ing
434 /// from `&T` to `&mut T` is invalid.
435 ///
436 /// See [the Nomicon](../../nomicon/send-and-sync.html) for more
437 /// details about `Sync`.
438 ///
439 /// [send]: trait.Send.html
440 /// [u8]: ../../std/primitive.u8.html
441 /// [f64]: ../../std/primitive.f64.html
442 /// [box]: ../../std/boxed/struct.Box.html
443 /// [vec]: ../../std/vec/struct.Vec.html
444 /// [cell]: ../cell/struct.Cell.html
445 /// [refcell]: ../cell/struct.RefCell.html
446 /// [rc]: ../../std/rc/struct.Rc.html
447 /// [arc]: ../../std/sync/struct.Arc.html
448 /// [atomic data types]: ../sync/atomic/index.html
449 /// [mutex]: ../../std/sync/struct.Mutex.html
450 /// [rwlock]: ../../std/sync/struct.RwLock.html
451 /// [unsafecell]: ../cell/struct.UnsafeCell.html
452 /// [ub]: ../../reference/behavior-considered-undefined.html
453 /// [transmute]: ../../std/mem/fn.transmute.html
454 #[stable(feature = "rust1", since = "1.0.0")]
455 #[cfg_attr(not(test), rustc_diagnostic_item = "sync_trait")]
456 #[lang = "sync"]
457 #[rustc_on_unimplemented(
458     message = "`{Self}` cannot be shared between threads safely",
459     label = "`{Self}` cannot be shared between threads safely"
460 )]
461 pub unsafe auto trait Sync {
462     // FIXME(estebank): once support to add notes in `rustc_on_unimplemented`
463     // lands in beta, and it has been extended to check whether a closure is
464     // anywhere in the requirement chain, extend it as such (#48534):
465     // ```
466     // on(
467     //     closure,
468     //     note="`{Self}` cannot be shared safely, consider marking the closure `move`"
469     // ),
470     // ```
471
472     // Empty
473 }
474
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl<T: ?Sized> !Sync for *const T {}
477 #[stable(feature = "rust1", since = "1.0.0")]
478 impl<T: ?Sized> !Sync for *mut T {}
479
480 macro_rules! impls {
481     ($t: ident) => {
482         #[stable(feature = "rust1", since = "1.0.0")]
483         impl<T: ?Sized> Hash for $t<T> {
484             #[inline]
485             fn hash<H: Hasher>(&self, _: &mut H) {}
486         }
487
488         #[stable(feature = "rust1", since = "1.0.0")]
489         impl<T: ?Sized> cmp::PartialEq for $t<T> {
490             fn eq(&self, _other: &$t<T>) -> bool {
491                 true
492             }
493         }
494
495         #[stable(feature = "rust1", since = "1.0.0")]
496         impl<T: ?Sized> cmp::Eq for $t<T> {}
497
498         #[stable(feature = "rust1", since = "1.0.0")]
499         impl<T: ?Sized> cmp::PartialOrd for $t<T> {
500             fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> {
501                 Option::Some(cmp::Ordering::Equal)
502             }
503         }
504
505         #[stable(feature = "rust1", since = "1.0.0")]
506         impl<T: ?Sized> cmp::Ord for $t<T> {
507             fn cmp(&self, _other: &$t<T>) -> cmp::Ordering {
508                 cmp::Ordering::Equal
509             }
510         }
511
512         #[stable(feature = "rust1", since = "1.0.0")]
513         impl<T: ?Sized> Copy for $t<T> {}
514
515         #[stable(feature = "rust1", since = "1.0.0")]
516         impl<T: ?Sized> Clone for $t<T> {
517             fn clone(&self) -> Self {
518                 Self
519             }
520         }
521
522         #[stable(feature = "rust1", since = "1.0.0")]
523         impl<T: ?Sized> Default for $t<T> {
524             fn default() -> Self {
525                 Self
526             }
527         }
528
529         #[unstable(feature = "structural_match", issue = "31434")]
530         impl<T: ?Sized> StructuralPartialEq for $t<T> {}
531
532         #[unstable(feature = "structural_match", issue = "31434")]
533         impl<T: ?Sized> StructuralEq for $t<T> {}
534     };
535 }
536
537 /// Zero-sized type used to mark things that "act like" they own a `T`.
538 ///
539 /// Adding a `PhantomData<T>` field to your type tells the compiler that your
540 /// type acts as though it stores a value of type `T`, even though it doesn't
541 /// really. This information is used when computing certain safety properties.
542 ///
543 /// For a more in-depth explanation of how to use `PhantomData<T>`, please see
544 /// [the Nomicon](../../nomicon/phantom-data.html).
545 ///
546 /// # A ghastly note ðŸ‘»ðŸ‘»ðŸ‘»
547 ///
548 /// Though they both have scary names, `PhantomData` and 'phantom types' are
549 /// related, but not identical. A phantom type parameter is simply a type
550 /// parameter which is never used. In Rust, this often causes the compiler to
551 /// complain, and the solution is to add a "dummy" use by way of `PhantomData`.
552 ///
553 /// # Examples
554 ///
555 /// ## Unused lifetime parameters
556 ///
557 /// Perhaps the most common use case for `PhantomData` is a struct that has an
558 /// unused lifetime parameter, typically as part of some unsafe code. For
559 /// example, here is a struct `Slice` that has two pointers of type `*const T`,
560 /// presumably pointing into an array somewhere:
561 ///
562 /// ```compile_fail,E0392
563 /// struct Slice<'a, T> {
564 ///     start: *const T,
565 ///     end: *const T,
566 /// }
567 /// ```
568 ///
569 /// The intention is that the underlying data is only valid for the
570 /// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
571 /// intent is not expressed in the code, since there are no uses of
572 /// the lifetime `'a` and hence it is not clear what data it applies
573 /// to. We can correct this by telling the compiler to act *as if* the
574 /// `Slice` struct contained a reference `&'a T`:
575 ///
576 /// ```
577 /// use std::marker::PhantomData;
578 ///
579 /// # #[allow(dead_code)]
580 /// struct Slice<'a, T: 'a> {
581 ///     start: *const T,
582 ///     end: *const T,
583 ///     phantom: PhantomData<&'a T>,
584 /// }
585 /// ```
586 ///
587 /// This also in turn requires the annotation `T: 'a`, indicating
588 /// that any references in `T` are valid over the lifetime `'a`.
589 ///
590 /// When initializing a `Slice` you simply provide the value
591 /// `PhantomData` for the field `phantom`:
592 ///
593 /// ```
594 /// # #![allow(dead_code)]
595 /// # use std::marker::PhantomData;
596 /// # struct Slice<'a, T: 'a> {
597 /// #     start: *const T,
598 /// #     end: *const T,
599 /// #     phantom: PhantomData<&'a T>,
600 /// # }
601 /// fn borrow_vec<T>(vec: &Vec<T>) -> Slice<'_, T> {
602 ///     let ptr = vec.as_ptr();
603 ///     Slice {
604 ///         start: ptr,
605 ///         end: unsafe { ptr.add(vec.len()) },
606 ///         phantom: PhantomData,
607 ///     }
608 /// }
609 /// ```
610 ///
611 /// ## Unused type parameters
612 ///
613 /// It sometimes happens that you have unused type parameters which
614 /// indicate what type of data a struct is "tied" to, even though that
615 /// data is not actually found in the struct itself. Here is an
616 /// example where this arises with [FFI]. The foreign interface uses
617 /// handles of type `*mut ()` to refer to Rust values of different
618 /// types. We track the Rust type using a phantom type parameter on
619 /// the struct `ExternalResource` which wraps a handle.
620 ///
621 /// [FFI]: ../../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
622 ///
623 /// ```
624 /// # #![allow(dead_code)]
625 /// # trait ResType { }
626 /// # struct ParamType;
627 /// # mod foreign_lib {
628 /// #     pub fn new(_: usize) -> *mut () { 42 as *mut () }
629 /// #     pub fn do_stuff(_: *mut (), _: usize) {}
630 /// # }
631 /// # fn convert_params(_: ParamType) -> usize { 42 }
632 /// use std::marker::PhantomData;
633 /// use std::mem;
634 ///
635 /// struct ExternalResource<R> {
636 ///    resource_handle: *mut (),
637 ///    resource_type: PhantomData<R>,
638 /// }
639 ///
640 /// impl<R: ResType> ExternalResource<R> {
641 ///     fn new() -> ExternalResource<R> {
642 ///         let size_of_res = mem::size_of::<R>();
643 ///         ExternalResource {
644 ///             resource_handle: foreign_lib::new(size_of_res),
645 ///             resource_type: PhantomData,
646 ///         }
647 ///     }
648 ///
649 ///     fn do_stuff(&self, param: ParamType) {
650 ///         let foreign_params = convert_params(param);
651 ///         foreign_lib::do_stuff(self.resource_handle, foreign_params);
652 ///     }
653 /// }
654 /// ```
655 ///
656 /// ## Ownership and the drop check
657 ///
658 /// Adding a field of type `PhantomData<T>` indicates that your
659 /// type owns data of type `T`. This in turn implies that when your
660 /// type is dropped, it may drop one or more instances of the type
661 /// `T`. This has bearing on the Rust compiler's [drop check]
662 /// analysis.
663 ///
664 /// If your struct does not in fact *own* the data of type `T`, it is
665 /// better to use a reference type, like `PhantomData<&'a T>`
666 /// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so
667 /// as not to indicate ownership.
668 ///
669 /// [drop check]: ../../nomicon/dropck.html
670 #[lang = "phantom_data"]
671 #[stable(feature = "rust1", since = "1.0.0")]
672 pub struct PhantomData<T: ?Sized>;
673
674 impls! { PhantomData }
675
676 mod impls {
677     #[stable(feature = "rust1", since = "1.0.0")]
678     unsafe impl<T: Sync + ?Sized> Send for &T {}
679     #[stable(feature = "rust1", since = "1.0.0")]
680     unsafe impl<T: Send + ?Sized> Send for &mut T {}
681 }
682
683 /// Compiler-internal trait used to indicate the type of enum discriminants.
684 ///
685 /// This trait is automatically implemented for every type and does not add any
686 /// guarantees to [`mem::Discriminant`]. It is **undefined behavior** to transmute
687 /// between `DiscriminantKind::Discriminant` and `mem::Discriminant`.
688 ///
689 /// [`mem::Discriminant`]: https://doc.rust-lang.org/stable/core/mem/struct.Discriminant.html
690 #[unstable(
691     feature = "discriminant_kind",
692     issue = "none",
693     reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead"
694 )]
695 #[lang = "discriminant_kind"]
696 pub trait DiscriminantKind {
697     /// The type of the dicriminant, which must satisfy the trait
698     /// bounds required by `mem::Discriminant`.
699     type Discriminant: Clone + Copy + Debug + Eq + PartialEq + Hash + Send + Sync + Unpin;
700 }
701
702 /// Compiler-internal trait used to determine whether a type contains
703 /// any `UnsafeCell` internally, but not through an indirection.
704 /// This affects, for example, whether a `static` of that type is
705 /// placed in read-only static memory or writable static memory.
706 #[lang = "freeze"]
707 pub(crate) unsafe auto trait Freeze {}
708
709 impl<T: ?Sized> !Freeze for UnsafeCell<T> {}
710 unsafe impl<T: ?Sized> Freeze for PhantomData<T> {}
711 unsafe impl<T: ?Sized> Freeze for *const T {}
712 unsafe impl<T: ?Sized> Freeze for *mut T {}
713 unsafe impl<T: ?Sized> Freeze for &T {}
714 unsafe impl<T: ?Sized> Freeze for &mut T {}
715
716 /// Types that can be safely moved after being pinned.
717 ///
718 /// Since Rust itself has no notion of immovable types, and considers moves
719 /// (e.g., through assignment or [`mem::replace`]) to always be safe,
720 /// this trait cannot prevent types from moving by itself.
721 ///
722 /// Instead it is used to prevent moves through the type system,
723 /// by controlling the behavior of pointers `P` wrapped in the [`Pin<P>`] wrapper,
724 /// which "pin" the type in place by not allowing it to be moved out of them.
725 /// See the [`pin module`] documentation for more information on pinning.
726 ///
727 /// Implementing this trait lifts the restrictions of pinning off a type,
728 /// which then allows it to move out with functions such as [`mem::replace`].
729 ///
730 /// `Unpin` has no consequence at all for non-pinned data. In particular,
731 /// [`mem::replace`] happily moves `!Unpin` data (it works for any `&mut T`, not
732 /// just when `T: Unpin`). However, you cannot use
733 /// [`mem::replace`] on data wrapped inside a [`Pin<P>`] because you cannot get the
734 /// `&mut T` you need for that, and *that* is what makes this system work.
735 ///
736 /// So this, for example, can only be done on types implementing `Unpin`:
737 ///
738 /// ```rust
739 /// # #![allow(unused_must_use)]
740 /// use std::mem;
741 /// use std::pin::Pin;
742 ///
743 /// let mut string = "this".to_string();
744 /// let mut pinned_string = Pin::new(&mut string);
745 ///
746 /// // We need a mutable reference to call `mem::replace`.
747 /// // We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`,
748 /// // but that is only possible because `String` implements `Unpin`.
749 /// mem::replace(&mut *pinned_string, "other".to_string());
750 /// ```
751 ///
752 /// This trait is automatically implemented for almost every type.
753 ///
754 /// [`mem::replace`]: ../../std/mem/fn.replace.html
755 /// [`Pin<P>`]: ../pin/struct.Pin.html
756 /// [`pin module`]: ../../std/pin/index.html
757 #[stable(feature = "pin", since = "1.33.0")]
758 #[rustc_on_unimplemented(
759     on(_Self = "std::future::Future", note = "consider using `Box::pin`",),
760     message = "`{Self}` cannot be unpinned"
761 )]
762 #[lang = "unpin"]
763 pub auto trait Unpin {}
764
765 /// A marker type which does not implement `Unpin`.
766 ///
767 /// If a type contains a `PhantomPinned`, it will not implement `Unpin` by default.
768 #[stable(feature = "pin", since = "1.33.0")]
769 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
770 pub struct PhantomPinned;
771
772 #[stable(feature = "pin", since = "1.33.0")]
773 impl !Unpin for PhantomPinned {}
774
775 #[stable(feature = "pin", since = "1.33.0")]
776 impl<'a, T: ?Sized + 'a> Unpin for &'a T {}
777
778 #[stable(feature = "pin", since = "1.33.0")]
779 impl<'a, T: ?Sized + 'a> Unpin for &'a mut T {}
780
781 #[stable(feature = "pin_raw", since = "1.38.0")]
782 impl<T: ?Sized> Unpin for *const T {}
783
784 #[stable(feature = "pin_raw", since = "1.38.0")]
785 impl<T: ?Sized> Unpin for *mut T {}
786
787 /// Implementations of `Copy` for primitive types.
788 ///
789 /// Implementations that cannot be described in Rust
790 /// are implemented in `traits::SelectionContext::copy_clone_conditions()`
791 /// in `rustc_trait_selection`.
792 mod copy_impls {
793
794     use super::Copy;
795
796     macro_rules! impl_copy {
797         ($($t:ty)*) => {
798             $(
799                 #[stable(feature = "rust1", since = "1.0.0")]
800                 impl Copy for $t {}
801             )*
802         }
803     }
804
805     impl_copy! {
806         usize u8 u16 u32 u64 u128
807         isize i8 i16 i32 i64 i128
808         f32 f64
809         bool char
810     }
811
812     #[unstable(feature = "never_type", issue = "35121")]
813     impl Copy for ! {}
814
815     #[stable(feature = "rust1", since = "1.0.0")]
816     impl<T: ?Sized> Copy for *const T {}
817
818     #[stable(feature = "rust1", since = "1.0.0")]
819     impl<T: ?Sized> Copy for *mut T {}
820
821     /// Shared references can be copied, but mutable references *cannot*!
822     #[stable(feature = "rust1", since = "1.0.0")]
823     impl<T: ?Sized> Copy for &T {}
824 }