]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/adjustment.rs
Auto merge of #58972 - QuietMisdreavus:intra-doc-link-imports, r=GuillaumeGomez
[rust.git] / src / librustc / ty / adjustment.rs
1 use crate::hir;
2 use crate::hir::def_id::DefId;
3 use crate::ty::{self, Ty, TyCtxt};
4 use crate::ty::subst::SubstsRef;
5 use rustc_macros::HashStable;
6
7
8 /// Represents coercing a value to a different type of value.
9 ///
10 /// We transform values by following a number of `Adjust` steps in order.
11 /// See the documentation on variants of `Adjust` for more details.
12 ///
13 /// Here are some common scenarios:
14 ///
15 /// 1. The simplest cases are where a pointer is not adjusted fat vs thin.
16 ///    Here the pointer will be dereferenced N times (where a dereference can
17 ///    happen to raw or borrowed pointers or any smart pointer which implements
18 ///    Deref, including Box<_>). The types of dereferences is given by
19 ///    `autoderefs`. It can then be auto-referenced zero or one times, indicated
20 ///    by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
21 ///    `false`.
22 ///
23 /// 2. A thin-to-fat coercion involves unsizing the underlying data. We start
24 ///    with a thin pointer, deref a number of times, unsize the underlying data,
25 ///    then autoref. The 'unsize' phase may change a fixed length array to a
26 ///    dynamically sized one, a concrete object to a trait object, or statically
27 ///    sized struct to a dynamically sized one. E.g., &[i32; 4] -> &[i32] is
28 ///    represented by:
29 ///
30 ///    ```
31 ///    Deref(None) -> [i32; 4],
32 ///    Borrow(AutoBorrow::Ref) -> &[i32; 4],
33 ///    Unsize -> &[i32],
34 ///    ```
35 ///
36 ///    Note that for a struct, the 'deep' unsizing of the struct is not recorded.
37 ///    E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
38 ///    The autoderef and -ref are the same as in the above example, but the type
39 ///    stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
40 ///    the underlying conversions from `[i32; 4]` to `[i32]`.
41 ///
42 /// 3. Coercing a `Box<T>` to `Box<dyn Trait>` is an interesting special case. In
43 ///    that case, we have the pointer we need coming in, so there are no
44 ///    autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
45 ///    At some point, of course, `Box` should move out of the compiler, in which
46 ///    case this is analogous to transforming a struct. E.g., Box<[i32; 4]> ->
47 ///    Box<[i32]> is an `Adjust::Unsize` with the target `Box<[i32]>`.
48 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
49 pub struct Adjustment<'tcx> {
50     pub kind: Adjust<'tcx>,
51     pub target: Ty<'tcx>,
52 }
53
54 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
55 pub enum Adjust<'tcx> {
56     /// Go from ! to any type.
57     NeverToAny,
58
59     /// Go from a fn-item type to a fn-pointer type.
60     ReifyFnPointer,
61
62     /// Go from a safe fn pointer to an unsafe fn pointer.
63     UnsafeFnPointer,
64
65     /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer.
66     /// It cannot convert a closure that requires unsafe.
67     ClosureFnPointer(hir::Unsafety),
68
69     /// Go from a mut raw pointer to a const raw pointer.
70     MutToConstPointer,
71
72     /// Dereference once, producing a place.
73     Deref(Option<OverloadedDeref<'tcx>>),
74
75     /// Take the address and produce either a `&` or `*` pointer.
76     Borrow(AutoBorrow<'tcx>),
77
78     /// Unsize a pointer/reference value, e.g., `&[T; n]` to
79     /// `&[T]`. Note that the source could be a thin or fat pointer.
80     /// This will do things like convert thin pointers to fat
81     /// pointers, or convert structs containing thin pointers to
82     /// structs containing fat pointers, or convert between fat
83     /// pointers. We don't store the details of how the transform is
84     /// done (in fact, we don't know that, because it might depend on
85     /// the precise type parameters). We just store the target
86     /// type. Codegen backends and miri figure out what has to be done
87     /// based on the precise source/target type at hand.
88     Unsize,
89 }
90
91 /// An overloaded autoderef step, representing a `Deref(Mut)::deref(_mut)`
92 /// call, with the signature `&'a T -> &'a U` or `&'a mut T -> &'a mut U`.
93 /// The target type is `U` in both cases, with the region and mutability
94 /// being those shared by both the receiver and the returned reference.
95 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
96 pub struct OverloadedDeref<'tcx> {
97     pub region: ty::Region<'tcx>,
98     pub mutbl: hir::Mutability,
99 }
100
101 impl<'a, 'gcx, 'tcx> OverloadedDeref<'tcx> {
102     pub fn method_call(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, source: Ty<'tcx>)
103                        -> (DefId, SubstsRef<'tcx>) {
104         let trait_def_id = match self.mutbl {
105             hir::MutImmutable => tcx.lang_items().deref_trait(),
106             hir::MutMutable => tcx.lang_items().deref_mut_trait()
107         };
108         let method_def_id = tcx.associated_items(trait_def_id.unwrap())
109             .find(|m| m.kind == ty::AssociatedKind::Method).unwrap().def_id;
110         (method_def_id, tcx.mk_substs_trait(source, &[]))
111     }
112 }
113
114 /// At least for initial deployment, we want to limit two-phase borrows to
115 /// only a few specific cases. Right now, those are mostly "things that desugar"
116 /// into method calls:
117 /// - using `x.some_method()` syntax, where some_method takes `&mut self`,
118 /// - using `Foo::some_method(&mut x, ...)` syntax,
119 /// - binary assignment operators (`+=`, `-=`, `*=`, etc.).
120 /// Anything else should be rejected until generalized two-phase borrow support
121 /// is implemented. Right now, dataflow can't handle the general case where there
122 /// is more than one use of a mutable borrow, and we don't want to accept too much
123 /// new code via two-phase borrows, so we try to limit where we create two-phase
124 /// capable mutable borrows.
125 /// See #49434 for tracking.
126 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
127 pub enum AllowTwoPhase {
128     Yes,
129     No
130 }
131
132 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
133 pub enum AutoBorrowMutability {
134     Mutable { allow_two_phase_borrow: AllowTwoPhase },
135     Immutable,
136 }
137
138 impl From<AutoBorrowMutability> for hir::Mutability {
139     fn from(m: AutoBorrowMutability) -> Self {
140         match m {
141             AutoBorrowMutability::Mutable { .. } => hir::MutMutable,
142             AutoBorrowMutability::Immutable => hir::MutImmutable,
143         }
144     }
145 }
146
147 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
148 pub enum AutoBorrow<'tcx> {
149     /// Converts from T to &T.
150     Ref(ty::Region<'tcx>, AutoBorrowMutability),
151
152     /// Converts from T to *T.
153     RawPtr(hir::Mutability),
154 }
155
156 /// Information for `CoerceUnsized` impls, storing information we
157 /// have computed about the coercion.
158 ///
159 /// This struct can be obtained via the `coerce_impl_info` query.
160 /// Demanding this struct also has the side-effect of reporting errors
161 /// for inappropriate impls.
162 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
163 pub struct CoerceUnsizedInfo {
164     /// If this is a "custom coerce" impl, then what kind of custom
165     /// coercion is it? This applies to impls of `CoerceUnsized` for
166     /// structs, primarily, where we store a bit of info about which
167     /// fields need to be coerced.
168     pub custom_kind: Option<CustomCoerceUnsized>
169 }
170
171 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
172 pub enum CustomCoerceUnsized {
173     /// Records the index of the field being coerced.
174     Struct(usize)
175 }