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