]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/tcx.rs
Remove leftover AwaitOrigin
[rust.git] / src / librustc / mir / tcx.rs
1 /*!
2  * Methods for the various MIR types. These are intended for use after
3  * building is complete.
4  */
5
6 use crate::mir::*;
7 use crate::ty::subst::Subst;
8 use crate::ty::{self, Ty, TyCtxt};
9 use crate::ty::layout::VariantIdx;
10 use crate::hir;
11 use crate::ty::util::IntTypeExt;
12
13 #[derive(Copy, Clone, Debug)]
14 pub struct PlaceTy<'tcx> {
15     pub ty: Ty<'tcx>,
16     /// Downcast to a particular variant of an enum, if included.
17     pub variant_index: Option<VariantIdx>,
18 }
19
20 // At least on 64 bit systems, `PlaceTy` should not be larger than two or three pointers.
21 #[cfg(target_arch = "x86_64")]
22 static_assert_size!(PlaceTy<'_>, 16);
23
24 impl<'tcx> PlaceTy<'tcx> {
25     pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
26         PlaceTy { ty, variant_index: None }
27     }
28
29     /// `place_ty.field_ty(tcx, f)` computes the type at a given field
30     /// of a record or enum-variant. (Most clients of `PlaceTy` can
31     /// instead just extract the relevant type directly from their
32     /// `PlaceElem`, but some instances of `ProjectionElem<V, T>` do
33     /// not carry a `Ty` for `T`.)
34     ///
35     /// Note that the resulting type has not been normalized.
36     pub fn field_ty(self, tcx: TyCtxt<'tcx>, f: &Field) -> Ty<'tcx> {
37         let answer = match self.ty.sty {
38             ty::Adt(adt_def, substs) => {
39                 let variant_def = match self.variant_index {
40                     None => adt_def.non_enum_variant(),
41                     Some(variant_index) => {
42                         assert!(adt_def.is_enum());
43                         &adt_def.variants[variant_index]
44                     }
45                 };
46                 let field_def = &variant_def.fields[f.index()];
47                 field_def.ty(tcx, substs)
48             }
49             ty::Tuple(ref tys) => tys[f.index()].expect_ty(),
50             _ => bug!("extracting field of non-tuple non-adt: {:?}", self),
51         };
52         debug!("field_ty self: {:?} f: {:?} yields: {:?}", self, f, answer);
53         answer
54     }
55
56     /// Convenience wrapper around `projection_ty_core` for
57     /// `PlaceElem`, where we can just use the `Ty` that is already
58     /// stored inline on field projection elems.
59     pub fn projection_ty(self, tcx: TyCtxt<'tcx>, elem: &PlaceElem<'tcx>) -> PlaceTy<'tcx> {
60         self.projection_ty_core(tcx, elem, |_, _, ty| ty)
61     }
62
63     /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
64     /// projects `place_ty` onto `elem`, returning the appropriate
65     /// `Ty` or downcast variant corresponding to that projection.
66     /// The `handle_field` callback must map a `Field` to its `Ty`,
67     /// (which should be trivial when `T` = `Ty`).
68     pub fn projection_ty_core<V, T>(
69         self,
70         tcx: TyCtxt<'tcx>,
71         elem: &ProjectionElem<V, T>,
72         mut handle_field: impl FnMut(&Self, &Field, &T) -> Ty<'tcx>,
73     ) -> PlaceTy<'tcx>
74     where
75         V: ::std::fmt::Debug,
76         T: ::std::fmt::Debug,
77     {
78         let answer = match *elem {
79             ProjectionElem::Deref => {
80                 let ty = self.ty
81                              .builtin_deref(true)
82                              .unwrap_or_else(|| {
83                                  bug!("deref projection of non-dereferencable ty {:?}", self)
84                              })
85                              .ty;
86                 PlaceTy::from_ty(ty)
87             }
88             ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } =>
89                 PlaceTy::from_ty(self.ty.builtin_index().unwrap()),
90             ProjectionElem::Subslice { from, to } => {
91                 PlaceTy::from_ty(match self.ty.sty {
92                     ty::Array(inner, size) => {
93                         let size = size.unwrap_usize(tcx);
94                         let len = size - (from as u64) - (to as u64);
95                         tcx.mk_array(inner, len)
96                     }
97                     ty::Slice(..) => self.ty,
98                     _ => {
99                         bug!("cannot subslice non-array type: `{:?}`", self)
100                     }
101                 })
102             }
103             ProjectionElem::Downcast(_name, index) =>
104                 PlaceTy { ty: self.ty, variant_index: Some(index) },
105             ProjectionElem::Field(ref f, ref fty) =>
106                 PlaceTy::from_ty(handle_field(&self, f, fty)),
107         };
108         debug!("projection_ty self: {:?} elem: {:?} yields: {:?}", self, elem, answer);
109         answer
110     }
111 }
112
113 BraceStructTypeFoldableImpl! {
114     impl<'tcx> TypeFoldable<'tcx> for PlaceTy<'tcx> {
115         ty,
116         variant_index,
117     }
118 }
119
120 impl<'tcx> Place<'tcx> {
121     pub fn ty_from<D>(
122         base: &PlaceBase<'tcx>,
123         projection: &Option<Box<Projection<'tcx>>>,
124         local_decls: &D,
125         tcx: TyCtxt<'tcx>
126     ) -> PlaceTy<'tcx>
127         where D: HasLocalDecls<'tcx>
128     {
129         Place::iterate_over(base, projection, |place_base, place_projections| {
130             let mut place_ty = place_base.ty(local_decls);
131
132             for proj in place_projections {
133                 place_ty = place_ty.projection_ty(tcx, &proj.elem);
134             }
135
136             place_ty
137         })
138     }
139
140     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
141     where
142         D: HasLocalDecls<'tcx>,
143     {
144         Place::ty_from(&self.base, &self.projection, local_decls, tcx)
145     }
146 }
147
148 impl<'tcx> PlaceBase<'tcx> {
149     pub fn ty<D>(&self, local_decls: &D) -> PlaceTy<'tcx>
150         where D: HasLocalDecls<'tcx>
151     {
152         match self {
153             PlaceBase::Local(index) => PlaceTy::from_ty(local_decls.local_decls()[*index].ty),
154             PlaceBase::Static(data) => PlaceTy::from_ty(data.ty),
155         }
156     }
157 }
158
159 pub enum RvalueInitializationState {
160     Shallow,
161     Deep
162 }
163
164 impl<'tcx> Rvalue<'tcx> {
165     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
166     where
167         D: HasLocalDecls<'tcx>,
168     {
169         match *self {
170             Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
171             Rvalue::Repeat(ref operand, count) => {
172                 tcx.mk_array(operand.ty(local_decls, tcx), count)
173             }
174             Rvalue::Ref(reg, bk, ref place) => {
175                 let place_ty = place.ty(local_decls, tcx).ty;
176                 tcx.mk_ref(reg,
177                     ty::TypeAndMut {
178                         ty: place_ty,
179                         mutbl: bk.to_mutbl_lossy()
180                     }
181                 )
182             }
183             Rvalue::Len(..) => tcx.types.usize,
184             Rvalue::Cast(.., ty) => ty,
185             Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
186                 let lhs_ty = lhs.ty(local_decls, tcx);
187                 let rhs_ty = rhs.ty(local_decls, tcx);
188                 op.ty(tcx, lhs_ty, rhs_ty)
189             }
190             Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
191                 let lhs_ty = lhs.ty(local_decls, tcx);
192                 let rhs_ty = rhs.ty(local_decls, tcx);
193                 let ty = op.ty(tcx, lhs_ty, rhs_ty);
194                 tcx.intern_tup(&[ty, tcx.types.bool])
195             }
196             Rvalue::UnaryOp(UnOp::Not, ref operand) |
197             Rvalue::UnaryOp(UnOp::Neg, ref operand) => {
198                 operand.ty(local_decls, tcx)
199             }
200             Rvalue::Discriminant(ref place) => {
201                 let ty = place.ty(local_decls, tcx).ty;
202                 match ty.sty {
203                     ty::Adt(adt_def, _) => adt_def.repr.discr_type().to_ty(tcx),
204                     ty::Generator(_, substs, _) => substs.discr_ty(tcx),
205                     _ => {
206                         // This can only be `0`, for now, so `u8` will suffice.
207                         tcx.types.u8
208                     }
209                 }
210             }
211             Rvalue::NullaryOp(NullOp::Box, t) => tcx.mk_box(t),
212             Rvalue::NullaryOp(NullOp::SizeOf, _) => tcx.types.usize,
213             Rvalue::Aggregate(ref ak, ref ops) => {
214                 match **ak {
215                     AggregateKind::Array(ty) => {
216                         tcx.mk_array(ty, ops.len() as u64)
217                     }
218                     AggregateKind::Tuple => {
219                         tcx.mk_tup(ops.iter().map(|op| op.ty(local_decls, tcx)))
220                     }
221                     AggregateKind::Adt(def, _, substs, _, _) => {
222                         tcx.type_of(def.did).subst(tcx, substs)
223                     }
224                     AggregateKind::Closure(did, substs) => {
225                         tcx.mk_closure(did, substs)
226                     }
227                     AggregateKind::Generator(did, substs, movability) => {
228                         tcx.mk_generator(did, substs, movability)
229                     }
230                 }
231             }
232         }
233     }
234
235     #[inline]
236     /// Returns `true` if this rvalue is deeply initialized (most rvalues) or
237     /// whether its only shallowly initialized (`Rvalue::Box`).
238     pub fn initialization_state(&self) -> RvalueInitializationState {
239         match *self {
240             Rvalue::NullaryOp(NullOp::Box, _) => RvalueInitializationState::Shallow,
241             _ => RvalueInitializationState::Deep
242         }
243     }
244 }
245
246 impl<'tcx> Operand<'tcx> {
247     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
248     where
249         D: HasLocalDecls<'tcx>,
250     {
251         match self {
252             &Operand::Copy(ref l) |
253             &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
254             &Operand::Constant(ref c) => c.ty,
255         }
256     }
257 }
258
259 impl<'tcx> BinOp {
260     pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
261         // FIXME: handle SIMD correctly
262         match self {
263             &BinOp::Add | &BinOp::Sub | &BinOp::Mul | &BinOp::Div | &BinOp::Rem |
264             &BinOp::BitXor | &BinOp::BitAnd | &BinOp::BitOr => {
265                 // these should be integers or floats of the same size.
266                 assert_eq!(lhs_ty, rhs_ty);
267                 lhs_ty
268             }
269             &BinOp::Shl | &BinOp::Shr | &BinOp::Offset => {
270                 lhs_ty // lhs_ty can be != rhs_ty
271             }
272             &BinOp::Eq | &BinOp::Lt | &BinOp::Le |
273             &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
274                 tcx.types.bool
275             }
276         }
277     }
278 }
279
280 impl BorrowKind {
281     pub fn to_mutbl_lossy(self) -> hir::Mutability {
282         match self {
283             BorrowKind::Mut { .. } => hir::MutMutable,
284             BorrowKind::Shared => hir::MutImmutable,
285
286             // We have no type corresponding to a unique imm borrow, so
287             // use `&mut`. It gives all the capabilities of an `&uniq`
288             // and hence is a safe "over approximation".
289             BorrowKind::Unique => hir::MutMutable,
290
291             // We have no type corresponding to a shallow borrow, so use
292             // `&` as an approximation.
293             BorrowKind::Shallow => hir::MutImmutable,
294         }
295     }
296 }
297
298 impl BinOp {
299     pub fn to_hir_binop(self) -> hir::BinOpKind {
300         match self {
301             BinOp::Add => hir::BinOpKind::Add,
302             BinOp::Sub => hir::BinOpKind::Sub,
303             BinOp::Mul => hir::BinOpKind::Mul,
304             BinOp::Div => hir::BinOpKind::Div,
305             BinOp::Rem => hir::BinOpKind::Rem,
306             BinOp::BitXor => hir::BinOpKind::BitXor,
307             BinOp::BitAnd => hir::BinOpKind::BitAnd,
308             BinOp::BitOr => hir::BinOpKind::BitOr,
309             BinOp::Shl => hir::BinOpKind::Shl,
310             BinOp::Shr => hir::BinOpKind::Shr,
311             BinOp::Eq => hir::BinOpKind::Eq,
312             BinOp::Ne => hir::BinOpKind::Ne,
313             BinOp::Lt => hir::BinOpKind::Lt,
314             BinOp::Gt => hir::BinOpKind::Gt,
315             BinOp::Le => hir::BinOpKind::Le,
316             BinOp::Ge => hir::BinOpKind::Ge,
317             BinOp::Offset => unreachable!()
318         }
319     }
320 }