]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_place.rs
156f8d2e7045c754e45c950b2b82e2b3266f4dce
[rust.git] / compiler / rustc_mir_build / src / build / expr / as_place.rs
1 //! See docs in build/expr/mod.rs
2
3 use crate::build::expr::category::Category;
4 use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
5 use crate::build::{BlockAnd, BlockAndExtension, Builder};
6 use crate::thir::*;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::HirId;
9 use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
10 use rustc_middle::middle::region;
11 use rustc_middle::mir::AssertKind::BoundsCheck;
12 use rustc_middle::mir::*;
13 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance};
14 use rustc_span::Span;
15 use rustc_target::abi::VariantIdx;
16
17 use rustc_index::vec::Idx;
18
19 /// The "outermost" place that holds this value.
20 #[derive(Copy, Clone)]
21 crate enum PlaceBase {
22     /// Denotes the start of a `Place`.
23     Local(Local),
24
25     /// When building place for an expression within a closure, the place might start off a
26     /// captured path. When `capture_disjoint_fields` is enabled, we might not know the capture
27     /// index (within the desugared closure) of the captured path until most of the projections
28     /// are applied. We use `PlaceBase::Upvar` to keep track of the root variable off of which the
29     /// captured path starts, the closure the capture belongs to and the trait the closure
30     /// implements.
31     ///
32     /// Once we have figured out the capture index, we can convert the place builder to start from
33     /// `PlaceBase::Local`.
34     ///
35     /// Consider the following example
36     /// ```rust
37     /// let t = (10, (10, (10, 10)));
38     ///
39     /// let c = || {
40     ///     println!("{}", t.0.0.0);
41     /// };
42     /// ```
43     /// Here the THIR expression for `t.0.0.0` will be something like
44     ///
45     /// ```
46     /// * Field(0)
47     ///     * Field(0)
48     ///         * Field(0)
49     ///             * UpvarRef(t)
50     /// ```
51     ///
52     /// When `capture_disjoint_fields` is enabled, `t.0.0.0` is captured and we won't be able to
53     /// figure out that it is captured until all the `Field` projections are applied.
54     Upvar {
55         /// HirId of the upvar
56         var_hir_id: HirId,
57         /// DefId of the closure
58         closure_def_id: DefId,
59         /// The trait closure implements, `Fn`, `FnMut`, `FnOnce`
60         closure_kind: ty::ClosureKind,
61     },
62 }
63
64 /// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
65 /// place by pushing more and more projections onto the end, and then convert the final set into a
66 /// place using the `into_place` method.
67 ///
68 /// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
69 /// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
70 #[derive(Clone)]
71 crate struct PlaceBuilder<'tcx> {
72     base: PlaceBase,
73     projection: Vec<PlaceElem<'tcx>>,
74 }
75
76 /// Given a list of MIR projections, convert them to list of HIR ProjectionKind.
77 /// The projections are truncated to represent a path that might be captured by a
78 /// closure/generator. This implies the vector returned from this function doesn't contain
79 /// ProjectionElems `Downcast`, `ConstantIndex`, `Index`, or `Subslice` because those will never be
80 /// part of a path that is captued by a closure. We stop applying projections once we see the first
81 /// projection that isn't captured by a closure.
82 fn convert_to_hir_projections_and_truncate_for_capture<'tcx>(
83     mir_projections: &[PlaceElem<'tcx>],
84 ) -> Vec<HirProjectionKind> {
85     let mut hir_projections = Vec::new();
86
87     for mir_projection in mir_projections {
88         let hir_projection = match mir_projection {
89             ProjectionElem::Deref => HirProjectionKind::Deref,
90             ProjectionElem::Field(field, _) => {
91                 // We will never encouter this for multivariant enums,
92                 // read the comment for `Downcast`.
93                 HirProjectionKind::Field(field.index() as u32, VariantIdx::new(0))
94             }
95             ProjectionElem::Downcast(..) => {
96                 // This projections exist only for enums that have
97                 // multiple variants. Since such enums that are captured
98                 // completely, we can stop here.
99                 break;
100             }
101             ProjectionElem::Index(..)
102             | ProjectionElem::ConstantIndex { .. }
103             | ProjectionElem::Subslice { .. } => {
104                 // We don't capture array-access projections.
105                 // We can stop here as arrays are captured completely.
106                 break;
107             }
108         };
109
110         hir_projections.push(hir_projection);
111     }
112
113     hir_projections
114 }
115
116 /// Return true if the `proj_possible_ancestor` represents an ancestor path
117 /// to `proj_capture` or `proj_possible_ancestor` is same as `proj_capture`,
118 /// assuming they both start off of the same root variable.
119 ///
120 /// **Note:** It's the caller's responsibility to ensure that both lists of projections
121 ///           start off of the same root variable.
122 ///
123 /// Eg: 1. `foo.x` which is represented using `projections=[Field(x)]` is an ancestor of
124 ///        `foo.x.y` which is represented using `projections=[Field(x), Field(y)]`.
125 ///        Note both `foo.x` and `foo.x.y` start off of the same root variable `foo`.
126 ///     2. Since we only look at the projections here function will return `bar.x` as an a valid
127 ///        ancestor of `foo.x.y`. It's the caller's responsibility to ensure that both projections
128 ///        list are being applied to the same root variable.
129 fn is_ancestor_or_same_capture(
130     proj_possible_ancestor: &Vec<HirProjectionKind>,
131     proj_capture: &[HirProjectionKind],
132 ) -> bool {
133     // We want to make sure `is_ancestor_or_same_capture("x.0.0", "x.0")` to return false.
134     // Therefore we can't just check if all projections are same in the zipped iterator below.
135     if proj_possible_ancestor.len() > proj_capture.len() {
136         return false;
137     }
138
139     proj_possible_ancestor.iter().zip(proj_capture).all(|(a, b)| a == b)
140 }
141
142 /// Computes the index of a capture within the desugared closure provided the closure's
143 /// `closure_min_captures` and the capture's index of the capture in the
144 /// `ty::MinCaptureList` of the root variable `var_hir_id`.
145 fn compute_capture_idx<'tcx>(
146     closure_min_captures: &ty::RootVariableMinCaptureList<'tcx>,
147     var_hir_id: HirId,
148     root_var_idx: usize,
149 ) -> usize {
150     let mut res = 0;
151     for (var_id, capture_list) in closure_min_captures {
152         if *var_id == var_hir_id {
153             res += root_var_idx;
154             break;
155         } else {
156             res += capture_list.len();
157         }
158     }
159
160     res
161 }
162
163 /// Given a closure, returns the index of a capture within the desugared closure struct and the
164 /// `ty::CapturedPlace` which is the ancestor of the Place represented using the `var_hir_id`
165 /// and `projection`.
166 ///
167 /// Note there will be at most one ancestor for any given Place.
168 ///
169 /// Returns None, when the ancestor is not found.
170 fn find_capture_matching_projections<'a, 'tcx>(
171     typeck_results: &'a ty::TypeckResults<'tcx>,
172     var_hir_id: HirId,
173     closure_def_id: DefId,
174     projections: &[PlaceElem<'tcx>],
175 ) -> Option<(usize, &'a ty::CapturedPlace<'tcx>)> {
176     let closure_min_captures = typeck_results.closure_min_captures.get(&closure_def_id)?;
177     let root_variable_min_captures = closure_min_captures.get(&var_hir_id)?;
178
179     let hir_projections = convert_to_hir_projections_and_truncate_for_capture(projections);
180
181     // If an ancestor is found, `idx` is the index within the list of captured places
182     // for root variable `var_hir_id` and `capture` is the `ty::CapturedPlace` itself.
183     let (idx, capture) = root_variable_min_captures.iter().enumerate().find(|(_, capture)| {
184         let possible_ancestor_proj_kinds =
185             capture.place.projections.iter().map(|proj| proj.kind).collect();
186         is_ancestor_or_same_capture(&possible_ancestor_proj_kinds, &hir_projections)
187     })?;
188
189     // Convert index to be from the presepective of the entire closure_min_captures map
190     // instead of just the root variable capture list
191     Some((compute_capture_idx(closure_min_captures, var_hir_id, idx), capture))
192 }
193
194 /// Takes a PlaceBuilder and resolves the upvar (if any) within it, so that the
195 /// `PlaceBuilder` now starts from `PlaceBase::Local`.
196 ///
197 /// Returns a Result with the error being the HirId of the Upvar that was not found.
198 fn to_upvars_resolved_place_builder<'a, 'tcx>(
199     from_builder: PlaceBuilder<'tcx>,
200     tcx: TyCtxt<'tcx>,
201     typeck_results: &'a ty::TypeckResults<'tcx>,
202 ) -> Result<PlaceBuilder<'tcx>, HirId> {
203     match from_builder.base {
204         PlaceBase::Local(_) => Ok(from_builder),
205         PlaceBase::Upvar { var_hir_id, closure_def_id, closure_kind } => {
206             // Captures are represented using fields inside a structure.
207             // This represents accessing self in the closure structure
208             let mut upvar_resolved_place_builder = PlaceBuilder::from(Local::new(1));
209             match closure_kind {
210                 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
211                     upvar_resolved_place_builder = upvar_resolved_place_builder.deref();
212                 }
213                 ty::ClosureKind::FnOnce => {}
214             }
215
216             let (capture_index, capture) = if let Some(capture_details) =
217                 find_capture_matching_projections(
218                     typeck_results,
219                     var_hir_id,
220                     closure_def_id,
221                     &from_builder.projection,
222                 ) {
223                 capture_details
224             } else {
225                 if !tcx.features().capture_disjoint_fields {
226                     bug!(
227                         "No associated capture found for {:?}[{:#?}] even though \
228                             capture_disjoint_fields isn't enabled",
229                         var_hir_id,
230                         from_builder.projection
231                     )
232                 } else {
233                     // FIXME(project-rfc-2229#24): Handle this case properly
234                     debug!(
235                         "No associated capture found for {:?}[{:#?}]",
236                         var_hir_id, from_builder.projection,
237                     );
238                 }
239                 return Err(var_hir_id);
240             };
241
242             let closure_ty = typeck_results
243                 .node_type(tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local()));
244
245             let substs = match closure_ty.kind() {
246                 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
247                 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
248                 _ => bug!("Lowering capture for non-closure type {:?}", closure_ty),
249             };
250
251             // Access the capture by accessing the field within the Closure struct.
252             //
253             // We must have inferred the capture types since we are building MIR, therefore
254             // it's safe to call `tuple_element_ty` and we can unwrap here because
255             // we know that the capture exists and is the `capture_index`-th capture.
256             let var_ty = substs.tupled_upvars_ty().tuple_element_ty(capture_index).unwrap();
257
258             upvar_resolved_place_builder =
259                 upvar_resolved_place_builder.field(Field::new(capture_index), var_ty);
260
261             // If the variable is captured via ByRef(Immutable/Mutable) Borrow,
262             // we need to deref it
263             upvar_resolved_place_builder = match capture.info.capture_kind {
264                 ty::UpvarCapture::ByRef(_) => upvar_resolved_place_builder.deref(),
265                 ty::UpvarCapture::ByValue(_) => upvar_resolved_place_builder,
266             };
267
268             let next_projection = capture.place.projections.len();
269             let mut curr_projections = from_builder.projection;
270
271             // We used some of the projections to build the capture itself,
272             // now we apply the remaining to the upvar resolved place.
273             upvar_resolved_place_builder
274                 .projection
275                 .extend(curr_projections.drain(next_projection..));
276
277             Ok(upvar_resolved_place_builder)
278         }
279     }
280 }
281
282 impl<'tcx> PlaceBuilder<'tcx> {
283     crate fn into_place<'a>(
284         self,
285         tcx: TyCtxt<'tcx>,
286         typeck_results: &'a ty::TypeckResults<'tcx>,
287     ) -> Place<'tcx> {
288         if let PlaceBase::Local(local) = self.base {
289             Place { local, projection: tcx.intern_place_elems(&self.projection) }
290         } else {
291             self.expect_upvars_resolved(tcx, typeck_results).into_place(tcx, typeck_results)
292         }
293     }
294
295     fn expect_upvars_resolved<'a>(
296         self,
297         tcx: TyCtxt<'tcx>,
298         typeck_results: &'a ty::TypeckResults<'tcx>,
299     ) -> PlaceBuilder<'tcx> {
300         to_upvars_resolved_place_builder(self, tcx, typeck_results).unwrap()
301     }
302
303     crate fn base(&self) -> PlaceBase {
304         self.base
305     }
306
307     crate fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
308         self.project(PlaceElem::Field(f, ty))
309     }
310
311     fn deref(self) -> Self {
312         self.project(PlaceElem::Deref)
313     }
314
315     fn index(self, index: Local) -> Self {
316         self.project(PlaceElem::Index(index))
317     }
318
319     fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
320         self.projection.push(elem);
321         self
322     }
323 }
324
325 impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
326     fn from(local: Local) -> Self {
327         Self { base: PlaceBase::Local(local), projection: Vec::new() }
328     }
329 }
330
331 impl<'tcx> From<PlaceBase> for PlaceBuilder<'tcx> {
332     fn from(base: PlaceBase) -> Self {
333         Self { base, projection: Vec::new() }
334     }
335 }
336
337 impl<'a, 'tcx> Builder<'a, 'tcx> {
338     /// Compile `expr`, yielding a place that we can move from etc.
339     ///
340     /// WARNING: Any user code might:
341     /// * Invalidate any slice bounds checks performed.
342     /// * Change the address that this `Place` refers to.
343     /// * Modify the memory that this place refers to.
344     /// * Invalidate the memory that this place refers to, this will be caught
345     ///   by borrow checking.
346     ///
347     /// Extra care is needed if any user code is allowed to run between calling
348     /// this method and using it, as is the case for `match` and index
349     /// expressions.
350     crate fn as_place(
351         &mut self,
352         mut block: BasicBlock,
353         expr: &Expr<'tcx>,
354     ) -> BlockAnd<Place<'tcx>> {
355         let place_builder = unpack!(block = self.as_place_builder(block, expr));
356         block.and(place_builder.into_place(self.hir.tcx(), self.hir.typeck_results()))
357     }
358
359     /// This is used when constructing a compound `Place`, so that we can avoid creating
360     /// intermediate `Place` values until we know the full set of projections.
361     crate fn as_place_builder(
362         &mut self,
363         block: BasicBlock,
364         expr: &Expr<'tcx>,
365     ) -> BlockAnd<PlaceBuilder<'tcx>> {
366         self.expr_as_place(block, expr, Mutability::Mut, None)
367     }
368
369     /// Compile `expr`, yielding a place that we can move from etc.
370     /// Mutability note: The caller of this method promises only to read from the resulting
371     /// place. The place itself may or may not be mutable:
372     /// * If this expr is a place expr like a.b, then we will return that place.
373     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
374     crate fn as_read_only_place(
375         &mut self,
376         mut block: BasicBlock,
377         expr: &Expr<'tcx>,
378     ) -> BlockAnd<Place<'tcx>> {
379         let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
380         block.and(place_builder.into_place(self.hir.tcx(), self.hir.typeck_results()))
381     }
382
383     /// This is used when constructing a compound `Place`, so that we can avoid creating
384     /// intermediate `Place` values until we know the full set of projections.
385     /// Mutability note: The caller of this method promises only to read from the resulting
386     /// place. The place itself may or may not be mutable:
387     /// * If this expr is a place expr like a.b, then we will return that place.
388     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
389     fn as_read_only_place_builder(
390         &mut self,
391         block: BasicBlock,
392         expr: &Expr<'tcx>,
393     ) -> BlockAnd<PlaceBuilder<'tcx>> {
394         self.expr_as_place(block, expr, Mutability::Not, None)
395     }
396
397     fn expr_as_place(
398         &mut self,
399         mut block: BasicBlock,
400         expr: &Expr<'tcx>,
401         mutability: Mutability,
402         fake_borrow_temps: Option<&mut Vec<Local>>,
403     ) -> BlockAnd<PlaceBuilder<'tcx>> {
404         debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
405
406         let this = self;
407         let expr_span = expr.span;
408         let source_info = this.source_info(expr_span);
409         match &expr.kind {
410             ExprKind::Scope { region_scope, lint_level, value } => {
411                 this.in_scope((*region_scope, source_info), *lint_level, |this| {
412                     this.expr_as_place(block, &value, mutability, fake_borrow_temps)
413                 })
414             }
415             ExprKind::Field { lhs, name } => {
416                 let place_builder = unpack!(
417                     block = this.expr_as_place(block, &lhs, mutability, fake_borrow_temps,)
418                 );
419                 block.and(place_builder.field(*name, expr.ty))
420             }
421             ExprKind::Deref { arg } => {
422                 let place_builder = unpack!(
423                     block = this.expr_as_place(block, &arg, mutability, fake_borrow_temps,)
424                 );
425                 block.and(place_builder.deref())
426             }
427             ExprKind::Index { lhs, index } => this.lower_index_expression(
428                 block,
429                 &lhs,
430                 &index,
431                 mutability,
432                 fake_borrow_temps,
433                 expr.temp_lifetime,
434                 expr_span,
435                 source_info,
436             ),
437             ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
438                 let upvar_id = ty::UpvarId::new(*var_hir_id, closure_def_id.expect_local());
439                 this.lower_captured_upvar(block, upvar_id)
440             }
441
442             ExprKind::VarRef { id } => {
443                 let place_builder = if this.is_bound_var_in_guard(*id) {
444                     let index = this.var_local_id(*id, RefWithinGuard);
445                     PlaceBuilder::from(index).deref()
446                 } else {
447                     let index = this.var_local_id(*id, OutsideGuard);
448                     PlaceBuilder::from(index)
449                 };
450                 block.and(place_builder)
451             }
452
453             ExprKind::PlaceTypeAscription { source, user_ty } => {
454                 let place_builder = unpack!(
455                     block = this.expr_as_place(block, &source, mutability, fake_borrow_temps,)
456                 );
457                 if let Some(user_ty) = user_ty {
458                     let annotation_index =
459                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
460                             span: source_info.span,
461                             user_ty: *user_ty,
462                             inferred_ty: expr.ty,
463                         });
464
465                     let place =
466                         place_builder.clone().into_place(this.hir.tcx(), this.hir.typeck_results());
467                     this.cfg.push(
468                         block,
469                         Statement {
470                             source_info,
471                             kind: StatementKind::AscribeUserType(
472                                 box (
473                                     place,
474                                     UserTypeProjection { base: annotation_index, projs: vec![] },
475                                 ),
476                                 Variance::Invariant,
477                             ),
478                         },
479                     );
480                 }
481                 block.and(place_builder)
482             }
483             ExprKind::ValueTypeAscription { source, user_ty } => {
484                 let temp =
485                     unpack!(block = this.as_temp(block, source.temp_lifetime, &source, mutability));
486                 if let Some(user_ty) = user_ty {
487                     let annotation_index =
488                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
489                             span: source_info.span,
490                             user_ty: *user_ty,
491                             inferred_ty: expr.ty,
492                         });
493                     this.cfg.push(
494                         block,
495                         Statement {
496                             source_info,
497                             kind: StatementKind::AscribeUserType(
498                                 box (
499                                     Place::from(temp),
500                                     UserTypeProjection { base: annotation_index, projs: vec![] },
501                                 ),
502                                 Variance::Invariant,
503                             ),
504                         },
505                     );
506                 }
507                 block.and(PlaceBuilder::from(temp))
508             }
509
510             ExprKind::Array { .. }
511             | ExprKind::Tuple { .. }
512             | ExprKind::Adt { .. }
513             | ExprKind::Closure { .. }
514             | ExprKind::Unary { .. }
515             | ExprKind::Binary { .. }
516             | ExprKind::LogicalOp { .. }
517             | ExprKind::Box { .. }
518             | ExprKind::Cast { .. }
519             | ExprKind::Use { .. }
520             | ExprKind::NeverToAny { .. }
521             | ExprKind::Pointer { .. }
522             | ExprKind::Repeat { .. }
523             | ExprKind::Borrow { .. }
524             | ExprKind::AddressOf { .. }
525             | ExprKind::Match { .. }
526             | ExprKind::If { .. }
527             | ExprKind::Loop { .. }
528             | ExprKind::Block { .. }
529             | ExprKind::Assign { .. }
530             | ExprKind::AssignOp { .. }
531             | ExprKind::Break { .. }
532             | ExprKind::Continue { .. }
533             | ExprKind::Return { .. }
534             | ExprKind::Literal { .. }
535             | ExprKind::ConstBlock { .. }
536             | ExprKind::StaticRef { .. }
537             | ExprKind::InlineAsm { .. }
538             | ExprKind::LlvmInlineAsm { .. }
539             | ExprKind::Yield { .. }
540             | ExprKind::ThreadLocalRef(_)
541             | ExprKind::Call { .. } => {
542                 // these are not places, so we need to make a temporary.
543                 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
544                 let temp =
545                     unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
546                 block.and(PlaceBuilder::from(temp))
547             }
548         }
549     }
550
551     /// Lower a captured upvar. Note we might not know the actual capture index,
552     /// so we create a place starting from `PlaceBase::Upvar`, which will be resolved
553     /// once all projections that allow us to indentify a capture have been applied.
554     fn lower_captured_upvar(
555         &mut self,
556         block: BasicBlock,
557         upvar_id: ty::UpvarId,
558     ) -> BlockAnd<PlaceBuilder<'tcx>> {
559         let closure_ty = self
560             .hir
561             .typeck_results()
562             .node_type(self.hir.tcx().hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
563
564         let closure_kind = if let ty::Closure(_, closure_substs) = closure_ty.kind() {
565             self.hir.infcx().closure_kind(closure_substs).unwrap()
566         } else {
567             // Generators are considered FnOnce.
568             ty::ClosureKind::FnOnce
569         };
570
571         block.and(PlaceBuilder::from(PlaceBase::Upvar {
572             var_hir_id: upvar_id.var_path.hir_id,
573             closure_def_id: upvar_id.closure_expr_id.to_def_id(),
574             closure_kind,
575         }))
576     }
577
578     /// Lower an index expression
579     ///
580     /// This has two complications;
581     ///
582     /// * We need to do a bounds check.
583     /// * We need to ensure that the bounds check can't be invalidated using an
584     ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
585     ///   that this is the case.
586     fn lower_index_expression(
587         &mut self,
588         mut block: BasicBlock,
589         base: &Expr<'tcx>,
590         index: &Expr<'tcx>,
591         mutability: Mutability,
592         fake_borrow_temps: Option<&mut Vec<Local>>,
593         temp_lifetime: Option<region::Scope>,
594         expr_span: Span,
595         source_info: SourceInfo,
596     ) -> BlockAnd<PlaceBuilder<'tcx>> {
597         let base_fake_borrow_temps = &mut Vec::new();
598         let is_outermost_index = fake_borrow_temps.is_none();
599         let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
600
601         let mut base_place =
602             unpack!(block = self.expr_as_place(block, base, mutability, Some(fake_borrow_temps),));
603
604         // Making this a *fresh* temporary means we do not have to worry about
605         // the index changing later: Nothing will ever change this temporary.
606         // The "retagging" transformation (for Stacked Borrows) relies on this.
607         let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
608
609         block = self.bounds_check(
610             block,
611             base_place.clone().into_place(self.hir.tcx(), self.hir.typeck_results()),
612             idx,
613             expr_span,
614             source_info,
615         );
616
617         if is_outermost_index {
618             self.read_fake_borrows(block, fake_borrow_temps, source_info)
619         } else {
620             base_place =
621                 base_place.expect_upvars_resolved(self.hir.tcx(), self.hir.typeck_results());
622             self.add_fake_borrows_of_base(
623                 &base_place,
624                 block,
625                 fake_borrow_temps,
626                 expr_span,
627                 source_info,
628             );
629         }
630
631         block.and(base_place.index(idx))
632     }
633
634     fn bounds_check(
635         &mut self,
636         block: BasicBlock,
637         slice: Place<'tcx>,
638         index: Local,
639         expr_span: Span,
640         source_info: SourceInfo,
641     ) -> BasicBlock {
642         let usize_ty = self.hir.usize_ty();
643         let bool_ty = self.hir.bool_ty();
644         // bounds check:
645         let len = self.temp(usize_ty, expr_span);
646         let lt = self.temp(bool_ty, expr_span);
647
648         // len = len(slice)
649         self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice));
650         // lt = idx < len
651         self.cfg.push_assign(
652             block,
653             source_info,
654             lt,
655             Rvalue::BinaryOp(
656                 BinOp::Lt,
657                 box (Operand::Copy(Place::from(index)), Operand::Copy(len)),
658             ),
659         );
660         let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
661         // assert!(lt, "...")
662         self.assert(block, Operand::Move(lt), true, msg, expr_span)
663     }
664
665     fn add_fake_borrows_of_base(
666         &mut self,
667         base_place: &PlaceBuilder<'tcx>,
668         block: BasicBlock,
669         fake_borrow_temps: &mut Vec<Local>,
670         expr_span: Span,
671         source_info: SourceInfo,
672     ) {
673         let tcx = self.hir.tcx();
674         let local = match base_place.base {
675             PlaceBase::Local(local) => local,
676             PlaceBase::Upvar { .. } => bug!("Expected PlacseBase::Local found Upvar"),
677         };
678
679         let place_ty = Place::ty_from(local, &base_place.projection, &self.local_decls, tcx);
680         if let ty::Slice(_) = place_ty.ty.kind() {
681             // We need to create fake borrows to ensure that the bounds
682             // check that we just did stays valid. Since we can't assign to
683             // unsized values, we only need to ensure that none of the
684             // pointers in the base place are modified.
685             for (idx, elem) in base_place.projection.iter().enumerate().rev() {
686                 match elem {
687                     ProjectionElem::Deref => {
688                         let fake_borrow_deref_ty = Place::ty_from(
689                             local,
690                             &base_place.projection[..idx],
691                             &self.local_decls,
692                             tcx,
693                         )
694                         .ty;
695                         let fake_borrow_ty =
696                             tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
697                         let fake_borrow_temp =
698                             self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
699                         let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
700                         self.cfg.push_assign(
701                             block,
702                             source_info,
703                             fake_borrow_temp.into(),
704                             Rvalue::Ref(
705                                 tcx.lifetimes.re_erased,
706                                 BorrowKind::Shallow,
707                                 Place { local, projection },
708                             ),
709                         );
710                         fake_borrow_temps.push(fake_borrow_temp);
711                     }
712                     ProjectionElem::Index(_) => {
713                         let index_ty = Place::ty_from(
714                             local,
715                             &base_place.projection[..idx],
716                             &self.local_decls,
717                             tcx,
718                         );
719                         match index_ty.ty.kind() {
720                             // The previous index expression has already
721                             // done any index expressions needed here.
722                             ty::Slice(_) => break,
723                             ty::Array(..) => (),
724                             _ => bug!("unexpected index base"),
725                         }
726                     }
727                     ProjectionElem::Field(..)
728                     | ProjectionElem::Downcast(..)
729                     | ProjectionElem::ConstantIndex { .. }
730                     | ProjectionElem::Subslice { .. } => (),
731                 }
732             }
733         }
734     }
735
736     fn read_fake_borrows(
737         &mut self,
738         bb: BasicBlock,
739         fake_borrow_temps: &mut Vec<Local>,
740         source_info: SourceInfo,
741     ) {
742         // All indexes have been evaluated now, read all of the
743         // fake borrows so that they are live across those index
744         // expressions.
745         for temp in fake_borrow_temps {
746             self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
747         }
748     }
749 }