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