1 //! See docs in build/expr/mod.rs
3 use crate::build::expr::category::Category;
4 use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
5 use crate::build::{BlockAnd, BlockAndExtension, Builder};
7 use rustc::middle::region;
8 use rustc::mir::interpret::{PanicInfo::BoundsCheck};
10 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance};
13 use rustc_index::vec::Idx;
15 /// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
16 /// place by pushing more and more projections onto the end, and then convert the final set into a
17 /// place using the `into_place` method.
19 /// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
20 /// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
22 struct PlaceBuilder<'tcx> {
23 base: PlaceBase<'tcx>,
24 projection: Vec<PlaceElem<'tcx>>,
27 impl PlaceBuilder<'tcx> {
28 fn into_place(self, tcx: TyCtxt<'tcx>) -> Place<'tcx> {
31 projection: tcx.intern_place_elems(&self.projection),
35 fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
36 self.project(PlaceElem::Field(f, ty))
39 fn deref(self) -> Self {
40 self.project(PlaceElem::Deref)
43 fn index(self, index: Local) -> Self {
44 self.project(PlaceElem::Index(index))
47 fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
48 self.projection.push(elem);
53 impl From<Local> for PlaceBuilder<'tcx> {
54 fn from(local: Local) -> Self {
57 projection: Vec::new(),
62 impl From<PlaceBase<'tcx>> for PlaceBuilder<'tcx> {
63 fn from(base: PlaceBase<'tcx>) -> Self {
66 projection: Vec::new(),
71 impl<'a, 'tcx> Builder<'a, 'tcx> {
72 /// Compile `expr`, yielding a place that we can move from etc.
74 /// WARNING: Any user code might:
75 /// * Invalidate any slice bounds checks performed.
76 /// * Change the address that this `Place` refers to.
77 /// * Modify the memory that this place refers to.
78 /// * Invalidate the memory that this place refers to, this will be caught
79 /// by borrow checking.
81 /// Extra care is needed if any user code is allowed to run between calling
82 /// this method and using it, as is the case for `match` and index
84 pub fn as_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
86 M: Mirror<'tcx, Output = Expr<'tcx>>,
88 let place_builder = unpack!(block = self.as_place_builder(block, expr));
89 block.and(place_builder.into_place(self.hir.tcx()))
92 /// This is used when constructing a compound `Place`, so that we can avoid creating
93 /// intermediate `Place` values until we know the full set of projections.
94 fn as_place_builder<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<PlaceBuilder<'tcx>>
96 M: Mirror<'tcx, Output = Expr<'tcx>>,
98 let expr = self.hir.mirror(expr);
99 self.expr_as_place(block, expr, Mutability::Mut, None)
102 /// Compile `expr`, yielding a place that we can move from etc.
103 /// Mutability note: The caller of this method promises only to read from the resulting
104 /// place. The place itself may or may not be mutable:
105 /// * If this expr is a place expr like a.b, then we will return that place.
106 /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
107 pub fn as_read_only_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
109 M: Mirror<'tcx, Output = Expr<'tcx>>,
111 let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
112 block.and(place_builder.into_place(self.hir.tcx()))
115 /// This is used when constructing a compound `Place`, so that we can avoid creating
116 /// intermediate `Place` values until we know the full set of projections.
117 /// Mutability note: The caller of this method promises only to read from the resulting
118 /// place. The place itself may or may not be mutable:
119 /// * If this expr is a place expr like a.b, then we will return that place.
120 /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
121 fn as_read_only_place_builder<M>(
125 ) -> BlockAnd<PlaceBuilder<'tcx>>
127 M: Mirror<'tcx, Output = Expr<'tcx>>,
129 let expr = self.hir.mirror(expr);
130 self.expr_as_place(block, expr, Mutability::Not, None)
135 mut block: BasicBlock,
137 mutability: Mutability,
138 fake_borrow_temps: Option<&mut Vec<Local>>,
139 ) -> BlockAnd<PlaceBuilder<'tcx>> {
141 "expr_as_place(block={:?}, expr={:?}, mutability={:?})",
142 block, expr, mutability
146 let expr_span = expr.span;
147 let source_info = this.source_info(expr_span);
153 } => this.in_scope((region_scope, source_info), lint_level, |this| {
154 let value = this.hir.mirror(value);
155 this.expr_as_place(block, value, mutability, fake_borrow_temps)
157 ExprKind::Field { lhs, name } => {
158 let lhs = this.hir.mirror(lhs);
159 let place_builder = unpack!(block = this.expr_as_place(
165 block.and(place_builder.field(name, expr.ty))
167 ExprKind::Deref { arg } => {
168 let arg = this.hir.mirror(arg);
169 let place_builder = unpack!(block = this.expr_as_place(
175 block.and(place_builder.deref())
177 ExprKind::Index { lhs, index } => {
178 this.lower_index_expression(
189 ExprKind::SelfRef => block.and(PlaceBuilder::from(Local::new(1))),
190 ExprKind::VarRef { id } => {
191 let place_builder = if this.is_bound_var_in_guard(id) {
192 let index = this.var_local_id(id, RefWithinGuard);
193 PlaceBuilder::from(index).deref()
195 let index = this.var_local_id(id, OutsideGuard);
196 PlaceBuilder::from(index)
198 block.and(place_builder)
201 ExprKind::PlaceTypeAscription { source, user_ty } => {
202 let source = this.hir.mirror(source);
203 let place_builder = unpack!(block = this.expr_as_place(
209 if let Some(user_ty) = user_ty {
210 let annotation_index = this.canonical_user_type_annotations.push(
211 CanonicalUserTypeAnnotation {
212 span: source_info.span,
214 inferred_ty: expr.ty,
218 let place = place_builder.clone().into_place(this.hir.tcx());
223 kind: StatementKind::AscribeUserType(
226 UserTypeProjection { base: annotation_index, projs: vec![], }
233 block.and(place_builder)
235 ExprKind::ValueTypeAscription { source, user_ty } => {
236 let source = this.hir.mirror(source);
238 block = this.as_temp(block, source.temp_lifetime, source, mutability)
240 if let Some(user_ty) = user_ty {
241 let annotation_index = this.canonical_user_type_annotations.push(
242 CanonicalUserTypeAnnotation {
243 span: source_info.span,
245 inferred_ty: expr.ty,
252 kind: StatementKind::AscribeUserType(
254 Place::from(temp.clone()),
255 UserTypeProjection { base: annotation_index, projs: vec![], },
262 block.and(PlaceBuilder::from(temp))
265 ExprKind::Array { .. }
266 | ExprKind::Tuple { .. }
267 | ExprKind::Adt { .. }
268 | ExprKind::Closure { .. }
269 | ExprKind::Unary { .. }
270 | ExprKind::Binary { .. }
271 | ExprKind::LogicalOp { .. }
272 | ExprKind::Box { .. }
273 | ExprKind::Cast { .. }
274 | ExprKind::Use { .. }
275 | ExprKind::NeverToAny { .. }
276 | ExprKind::Pointer { .. }
277 | ExprKind::Repeat { .. }
278 | ExprKind::Borrow { .. }
279 | ExprKind::Match { .. }
280 | ExprKind::Loop { .. }
281 | ExprKind::Block { .. }
282 | ExprKind::Assign { .. }
283 | ExprKind::AssignOp { .. }
284 | ExprKind::Break { .. }
285 | ExprKind::Continue { .. }
286 | ExprKind::Return { .. }
287 | ExprKind::Literal { .. }
288 | ExprKind::StaticRef { .. }
289 | ExprKind::InlineAsm { .. }
290 | ExprKind::Yield { .. }
291 | ExprKind::Call { .. } => {
292 // these are not places, so we need to make a temporary.
293 debug_assert!(match Category::of(&expr.kind) {
294 Some(Category::Place) => false,
298 unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
299 block.and(PlaceBuilder::from(temp))
304 /// Lower an index expression
306 /// This has two complications;
308 /// * We need to do a bounds check.
309 /// * We need to ensure that the bounds check can't be invalidated using an
310 /// expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
311 /// that this is the case.
312 fn lower_index_expression(
314 mut block: BasicBlock,
316 index: ExprRef<'tcx>,
317 mutability: Mutability,
318 fake_borrow_temps: Option<&mut Vec<Local>>,
319 temp_lifetime: Option<region::Scope>,
321 source_info: SourceInfo
322 ) -> BlockAnd<PlaceBuilder<'tcx>> {
323 let lhs = self.hir.mirror(base);
325 let base_fake_borrow_temps = &mut Vec::new();
326 let is_outermost_index = fake_borrow_temps.is_none();
327 let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
329 let base_place = unpack!(block = self.expr_as_place(
333 Some(fake_borrow_temps),
336 // Making this a *fresh* temporary means we do not have to worry about
337 // the index changing later: Nothing will ever change this temporary.
338 // The "retagging" transformation (for Stacked Borrows) relies on this.
339 let idx = unpack!(block = self.as_temp(
346 block = self.bounds_check(
348 base_place.clone().into_place(self.hir.tcx()),
354 if is_outermost_index {
355 self.read_fake_borrows(block, fake_borrow_temps, source_info)
357 self.add_fake_borrows_of_base(
366 block.and(base_place.index(idx))
375 source_info: SourceInfo,
377 let usize_ty = self.hir.usize_ty();
378 let bool_ty = self.hir.bool_ty();
380 let len = self.temp(usize_ty, expr_span);
381 let lt = self.temp(bool_ty, expr_span);
384 self.cfg.push_assign(
391 self.cfg.push_assign(
397 Operand::Copy(Place::from(index)),
398 Operand::Copy(len.clone()),
401 let msg = BoundsCheck {
402 len: Operand::Move(len),
403 index: Operand::Copy(Place::from(index)),
405 // assert!(lt, "...")
406 self.assert(block, Operand::Move(lt), true, msg, expr_span)
409 fn add_fake_borrows_of_base(
411 base_place: &PlaceBuilder<'tcx>,
413 fake_borrow_temps: &mut Vec<Local>,
415 source_info: SourceInfo,
417 let tcx = self.hir.tcx();
418 let place_ty = Place::ty_from(
420 &base_place.projection,
424 if let ty::Slice(_) = place_ty.ty.kind {
425 // We need to create fake borrows to ensure that the bounds
426 // check that we just did stays valid. Since we can't assign to
427 // unsized values, we only need to ensure that none of the
428 // pointers in the base place are modified.
429 for (idx, elem) in base_place.projection.iter().enumerate().rev() {
431 ProjectionElem::Deref => {
432 let fake_borrow_deref_ty = Place::ty_from(
434 &base_place.projection[..idx],
438 let fake_borrow_ty = tcx.mk_imm_ref(
439 tcx.lifetimes.re_erased,
440 fake_borrow_deref_ty,
442 let fake_borrow_temp = self.local_decls.push(
443 LocalDecl::new_temp(fake_borrow_ty, expr_span)
445 let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
446 self.cfg.push_assign(
449 &fake_borrow_temp.into(),
451 tcx.lifetimes.re_erased,
454 base: base_place.base.clone(),
459 fake_borrow_temps.push(fake_borrow_temp);
461 ProjectionElem::Index(_) => {
462 let index_ty = Place::ty_from(
464 &base_place.projection[..idx],
468 match index_ty.ty.kind {
469 // The previous index expression has already
470 // done any index expressions needed here.
471 ty::Slice(_) => break,
473 _ => bug!("unexpected index base"),
476 ProjectionElem::Field(..)
477 | ProjectionElem::Downcast(..)
478 | ProjectionElem::ConstantIndex { .. }
479 | ProjectionElem::Subslice { .. } => (),
485 fn read_fake_borrows(
488 fake_borrow_temps: &mut Vec<Local>,
489 source_info: SourceInfo,
491 // All indexes have been evaluated now, read all of the
492 // fake borrows so that they are live across those index
494 for temp in fake_borrow_temps {
499 kind: StatementKind::FakeRead(
500 FakeReadCause::ForIndex,
501 Box::new(Place::from(*temp)),