]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/tcx.rs
e9f7636ba85ae72b92bd730e0cfd51c1d9c22058
[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, ty::ParamEnv::empty(), 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         param_env: ty::ParamEnv<'tcx>,
72         elem: &ProjectionElem<V, T>,
73         mut handle_field: impl FnMut(&Self, &Field, &T) -> Ty<'tcx>,
74     ) -> PlaceTy<'tcx>
75     where
76         V: ::std::fmt::Debug,
77         T: ::std::fmt::Debug,
78     {
79         let answer = match *elem {
80             ProjectionElem::Deref => {
81                 let ty = self.ty
82                              .builtin_deref(true)
83                              .unwrap_or_else(|| {
84                                  bug!("deref projection of non-dereferencable ty {:?}", self)
85                              })
86                              .ty;
87                 PlaceTy::from_ty(ty)
88             }
89             ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } =>
90                 PlaceTy::from_ty(self.ty.builtin_index().unwrap()),
91             ProjectionElem::Subslice { from, to } => {
92                 PlaceTy::from_ty(match self.ty.sty {
93                     ty::Array(inner, size) => {
94                         let size = size.eval_usize(tcx, param_env);
95                         let len = size - (from as u64) - (to as u64);
96                         tcx.mk_array(inner, len)
97                     }
98                     ty::Slice(..) => self.ty,
99                     _ => {
100                         bug!("cannot subslice non-array type: `{:?}`", self)
101                     }
102                 })
103             }
104             ProjectionElem::Downcast(_name, index) =>
105                 PlaceTy { ty: self.ty, variant_index: Some(index) },
106             ProjectionElem::Field(ref f, ref fty) =>
107                 PlaceTy::from_ty(handle_field(&self, f, fty)),
108         };
109         debug!("projection_ty self: {:?} elem: {:?} yields: {:?}", self, elem, answer);
110         answer
111     }
112 }
113
114 BraceStructTypeFoldableImpl! {
115     impl<'tcx> TypeFoldable<'tcx> for PlaceTy<'tcx> {
116         ty,
117         variant_index,
118     }
119 }
120
121 impl<'tcx> Place<'tcx> {
122     pub fn ty_from<D>(
123         base: &PlaceBase<'tcx>,
124         projection: &Option<Box<Projection<'tcx>>>,
125         local_decls: &D,
126         tcx: TyCtxt<'tcx>
127     ) -> PlaceTy<'tcx>
128         where D: HasLocalDecls<'tcx>
129     {
130         Place::iterate_over(base, projection, |place_base, place_projections| {
131             let mut place_ty = place_base.ty(local_decls);
132
133             for proj in place_projections {
134                 place_ty = place_ty.projection_ty(tcx, &proj.elem);
135             }
136
137             place_ty
138         })
139     }
140
141     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
142     where
143         D: HasLocalDecls<'tcx>,
144     {
145         Place::ty_from(&self.base, &self.projection, local_decls, tcx)
146     }
147 }
148
149 impl<'tcx> PlaceBase<'tcx> {
150     pub fn ty<D>(&self, local_decls: &D) -> PlaceTy<'tcx>
151         where D: HasLocalDecls<'tcx>
152     {
153         match self {
154             PlaceBase::Local(index) => PlaceTy::from_ty(local_decls.local_decls()[*index].ty),
155             PlaceBase::Static(data) => PlaceTy::from_ty(data.ty),
156         }
157     }
158 }
159
160 pub enum RvalueInitializationState {
161     Shallow,
162     Deep
163 }
164
165 impl<'tcx> Rvalue<'tcx> {
166     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
167     where
168         D: HasLocalDecls<'tcx>,
169     {
170         match *self {
171             Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
172             Rvalue::Repeat(ref operand, count) => {
173                 tcx.mk_array(operand.ty(local_decls, tcx), count)
174             }
175             Rvalue::Ref(reg, bk, ref place) => {
176                 let place_ty = place.ty(local_decls, tcx).ty;
177                 tcx.mk_ref(reg,
178                     ty::TypeAndMut {
179                         ty: place_ty,
180                         mutbl: bk.to_mutbl_lossy()
181                     }
182                 )
183             }
184             Rvalue::Len(..) => tcx.types.usize,
185             Rvalue::Cast(.., ty) => ty,
186             Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
187                 let lhs_ty = lhs.ty(local_decls, tcx);
188                 let rhs_ty = rhs.ty(local_decls, tcx);
189                 op.ty(tcx, lhs_ty, rhs_ty)
190             }
191             Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
192                 let lhs_ty = lhs.ty(local_decls, tcx);
193                 let rhs_ty = rhs.ty(local_decls, tcx);
194                 let ty = op.ty(tcx, lhs_ty, rhs_ty);
195                 tcx.intern_tup(&[ty, tcx.types.bool])
196             }
197             Rvalue::UnaryOp(UnOp::Not, ref operand) |
198             Rvalue::UnaryOp(UnOp::Neg, ref operand) => {
199                 operand.ty(local_decls, tcx)
200             }
201             Rvalue::Discriminant(ref place) => {
202                 let ty = place.ty(local_decls, tcx).ty;
203                 match ty.sty {
204                     ty::Adt(adt_def, _) => adt_def.repr.discr_type().to_ty(tcx),
205                     ty::Generator(_, substs, _) => substs.discr_ty(tcx),
206                     _ => {
207                         // This can only be `0`, for now, so `u8` will suffice.
208                         tcx.types.u8
209                     }
210                 }
211             }
212             Rvalue::NullaryOp(NullOp::Box, t) => tcx.mk_box(t),
213             Rvalue::NullaryOp(NullOp::SizeOf, _) => tcx.types.usize,
214             Rvalue::Aggregate(ref ak, ref ops) => {
215                 match **ak {
216                     AggregateKind::Array(ty) => {
217                         tcx.mk_array(ty, ops.len() as u64)
218                     }
219                     AggregateKind::Tuple => {
220                         tcx.mk_tup(ops.iter().map(|op| op.ty(local_decls, tcx)))
221                     }
222                     AggregateKind::Adt(def, _, substs, _, _) => {
223                         tcx.type_of(def.did).subst(tcx, substs)
224                     }
225                     AggregateKind::Closure(did, substs) => {
226                         tcx.mk_closure(did, substs)
227                     }
228                     AggregateKind::Generator(did, substs, movability) => {
229                         tcx.mk_generator(did, substs, movability)
230                     }
231                 }
232             }
233         }
234     }
235
236     #[inline]
237     /// Returns `true` if this rvalue is deeply initialized (most rvalues) or
238     /// whether its only shallowly initialized (`Rvalue::Box`).
239     pub fn initialization_state(&self) -> RvalueInitializationState {
240         match *self {
241             Rvalue::NullaryOp(NullOp::Box, _) => RvalueInitializationState::Shallow,
242             _ => RvalueInitializationState::Deep
243         }
244     }
245 }
246
247 impl<'tcx> Operand<'tcx> {
248     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
249     where
250         D: HasLocalDecls<'tcx>,
251     {
252         match self {
253             &Operand::Copy(ref l) |
254             &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
255             &Operand::Constant(ref c) => c.literal.ty,
256         }
257     }
258 }
259
260 impl<'tcx> BinOp {
261     pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
262         // FIXME: handle SIMD correctly
263         match self {
264             &BinOp::Add | &BinOp::Sub | &BinOp::Mul | &BinOp::Div | &BinOp::Rem |
265             &BinOp::BitXor | &BinOp::BitAnd | &BinOp::BitOr => {
266                 // these should be integers or floats of the same size.
267                 assert_eq!(lhs_ty, rhs_ty);
268                 lhs_ty
269             }
270             &BinOp::Shl | &BinOp::Shr | &BinOp::Offset => {
271                 lhs_ty // lhs_ty can be != rhs_ty
272             }
273             &BinOp::Eq | &BinOp::Lt | &BinOp::Le |
274             &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
275                 tcx.types.bool
276             }
277         }
278     }
279 }
280
281 impl BorrowKind {
282     pub fn to_mutbl_lossy(self) -> hir::Mutability {
283         match self {
284             BorrowKind::Mut { .. } => hir::MutMutable,
285             BorrowKind::Shared => hir::MutImmutable,
286
287             // We have no type corresponding to a unique imm borrow, so
288             // use `&mut`. It gives all the capabilities of an `&uniq`
289             // and hence is a safe "over approximation".
290             BorrowKind::Unique => hir::MutMutable,
291
292             // We have no type corresponding to a shallow borrow, so use
293             // `&` as an approximation.
294             BorrowKind::Shallow => hir::MutImmutable,
295         }
296     }
297 }
298
299 impl BinOp {
300     pub fn to_hir_binop(self) -> hir::BinOpKind {
301         match self {
302             BinOp::Add => hir::BinOpKind::Add,
303             BinOp::Sub => hir::BinOpKind::Sub,
304             BinOp::Mul => hir::BinOpKind::Mul,
305             BinOp::Div => hir::BinOpKind::Div,
306             BinOp::Rem => hir::BinOpKind::Rem,
307             BinOp::BitXor => hir::BinOpKind::BitXor,
308             BinOp::BitAnd => hir::BinOpKind::BitAnd,
309             BinOp::BitOr => hir::BinOpKind::BitOr,
310             BinOp::Shl => hir::BinOpKind::Shl,
311             BinOp::Shr => hir::BinOpKind::Shr,
312             BinOp::Eq => hir::BinOpKind::Eq,
313             BinOp::Ne => hir::BinOpKind::Ne,
314             BinOp::Lt => hir::BinOpKind::Lt,
315             BinOp::Gt => hir::BinOpKind::Gt,
316             BinOp::Le => hir::BinOpKind::Le,
317             BinOp::Ge => hir::BinOpKind::Ge,
318             BinOp::Offset => unreachable!()
319         }
320     }
321 }