]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_place.rs
Rollup merge of #81485 - jackh726:atb-issues, r=Mark-Simulacrum
[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::middle::region;
10 use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
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 /// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
64 /// place by pushing more and more projections onto the end, and then convert the final set into a
65 /// place using the `into_place` method.
66 ///
67 /// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
68 /// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
69 #[derive(Clone)]
70 crate struct PlaceBuilder<'tcx> {
71     base: PlaceBase,
72     projection: Vec<PlaceElem<'tcx>>,
73 }
74
75 /// Given a list of MIR projections, convert them to list of HIR ProjectionKind.
76 /// The projections are truncated to represent a path that might be captured by a
77 /// closure/generator. This implies the vector returned from this function doesn't contain
78 /// ProjectionElems `Downcast`, `ConstantIndex`, `Index`, or `Subslice` because those will never be
79 /// part of a path that is captued by a closure. We stop applying projections once we see the first
80 /// projection that isn't captured by a closure.
81 fn convert_to_hir_projections_and_truncate_for_capture<'tcx>(
82     mir_projections: &[PlaceElem<'tcx>],
83 ) -> Vec<HirProjectionKind> {
84
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) =
217                 if let Some(capture_details) = 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,
237                             from_builder.projection,
238                         );
239                     }
240                     return Err(var_hir_id);
241                 };
242
243             let closure_ty =
244                 typeck_results.node_type(tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local()));
245
246             let substs = match closure_ty.kind() {
247                 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
248                 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
249                 _ => bug!("Lowering capture for non-closure type {:?}", closure_ty),
250             };
251
252             // Access the capture by accessing the field within the Closure struct.
253             //
254             // We must have inferred the capture types since we are building MIR, therefore
255             // it's safe to call `tuple_element_ty` and we can unwrap here because
256             // we know that the capture exists and is the `capture_index`-th capture.
257             let var_ty = substs.tupled_upvars_ty().tuple_element_ty(capture_index).unwrap();
258
259             upvar_resolved_place_builder = 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.projection.extend(
274                 curr_projections.drain(next_projection..));
275
276             Ok(upvar_resolved_place_builder)
277         }
278     }
279 }
280
281 impl<'tcx> PlaceBuilder<'tcx> {
282     crate fn into_place<'a>(
283         self,
284         tcx: TyCtxt<'tcx>,
285         typeck_results: &'a ty::TypeckResults<'tcx>,
286     ) -> Place<'tcx> {
287         if let PlaceBase::Local(local) = self.base {
288             Place { local, projection: tcx.intern_place_elems(&self.projection) }
289         } else {
290             self.expect_upvars_resolved(tcx, typeck_results).into_place(tcx, typeck_results)
291         }
292     }
293
294     fn expect_upvars_resolved<'a>(
295         self,
296         tcx: TyCtxt<'tcx>,
297         typeck_results: &'a ty::TypeckResults<'tcx>,
298     ) -> PlaceBuilder<'tcx> {
299         to_upvars_resolved_place_builder(self, tcx, typeck_results).unwrap()
300     }
301
302     crate fn base(&self) -> PlaceBase {
303         self.base
304     }
305
306     crate fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
307         self.project(PlaceElem::Field(f, ty))
308     }
309
310     fn deref(self) -> Self {
311         self.project(PlaceElem::Deref)
312     }
313
314     fn index(self, index: Local) -> Self {
315         self.project(PlaceElem::Index(index))
316     }
317
318     fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
319         self.projection.push(elem);
320         self
321     }
322 }
323
324 impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
325     fn from(local: Local) -> Self {
326         Self { base: PlaceBase::Local(local), projection: Vec::new() }
327     }
328 }
329
330 impl<'tcx> From<PlaceBase> for PlaceBuilder<'tcx> {
331     fn from(base: PlaceBase) -> Self {
332         Self { base, projection: Vec::new() }
333     }
334 }
335
336 impl<'a, 'tcx> Builder<'a, 'tcx> {
337     /// Compile `expr`, yielding a place that we can move from etc.
338     ///
339     /// WARNING: Any user code might:
340     /// * Invalidate any slice bounds checks performed.
341     /// * Change the address that this `Place` refers to.
342     /// * Modify the memory that this place refers to.
343     /// * Invalidate the memory that this place refers to, this will be caught
344     ///   by borrow checking.
345     ///
346     /// Extra care is needed if any user code is allowed to run between calling
347     /// this method and using it, as is the case for `match` and index
348     /// expressions.
349     crate fn as_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
350     where
351         M: Mirror<'tcx, Output = Expr<'tcx>>,
352     {
353         let place_builder = unpack!(block = self.as_place_builder(block, expr));
354         block.and(place_builder.into_place(self.hir.tcx(), self.hir.typeck_results()))
355     }
356
357     /// This is used when constructing a compound `Place`, so that we can avoid creating
358     /// intermediate `Place` values until we know the full set of projections.
359     crate fn as_place_builder<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<PlaceBuilder<'tcx>>
360     where
361         M: Mirror<'tcx, Output = Expr<'tcx>>,
362     {
363         let expr = self.hir.mirror(expr);
364         self.expr_as_place(block, expr, Mutability::Mut, None)
365     }
366
367     /// Compile `expr`, yielding a place that we can move from etc.
368     /// Mutability note: The caller of this method promises only to read from the resulting
369     /// place. The place itself may or may not be mutable:
370     /// * If this expr is a place expr like a.b, then we will return that place.
371     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
372     crate fn as_read_only_place<M>(
373         &mut self,
374         mut block: BasicBlock,
375         expr: M,
376     ) -> BlockAnd<Place<'tcx>>
377     where
378         M: Mirror<'tcx, Output = Expr<'tcx>>,
379     {
380         let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
381         block.and(place_builder.into_place(self.hir.tcx(), self.hir.typeck_results()))
382     }
383
384     /// This is used when constructing a compound `Place`, so that we can avoid creating
385     /// intermediate `Place` values until we know the full set of projections.
386     /// Mutability note: The caller of this method promises only to read from the resulting
387     /// place. The place itself may or may not be mutable:
388     /// * If this expr is a place expr like a.b, then we will return that place.
389     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
390     fn as_read_only_place_builder<M>(
391         &mut self,
392         block: BasicBlock,
393         expr: M,
394     ) -> BlockAnd<PlaceBuilder<'tcx>>
395     where
396         M: Mirror<'tcx, Output = Expr<'tcx>>,
397     {
398         let expr = self.hir.mirror(expr);
399         self.expr_as_place(block, expr, Mutability::Not, None)
400     }
401
402     fn expr_as_place(
403         &mut self,
404         mut block: BasicBlock,
405         expr: Expr<'tcx>,
406         mutability: Mutability,
407         fake_borrow_temps: Option<&mut Vec<Local>>,
408     ) -> BlockAnd<PlaceBuilder<'tcx>> {
409         debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
410
411         let this = self;
412         let expr_span = expr.span;
413         let source_info = this.source_info(expr_span);
414         match expr.kind {
415             ExprKind::Scope { region_scope, lint_level, value } => {
416                 this.in_scope((region_scope, source_info), lint_level, |this| {
417                     let value = this.hir.mirror(value);
418                     this.expr_as_place(block, value, mutability, fake_borrow_temps)
419                 })
420             }
421             ExprKind::Field { lhs, name } => {
422                 let lhs = this.hir.mirror(lhs);
423                 let place_builder =
424                     unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
425                 block.and(place_builder.field(name, expr.ty))
426             }
427             ExprKind::Deref { arg } => {
428                 let arg = this.hir.mirror(arg);
429                 let place_builder =
430                     unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
431                 block.and(place_builder.deref())
432             }
433             ExprKind::Index { lhs, index } => this.lower_index_expression(
434                 block,
435                 lhs,
436                 index,
437                 mutability,
438                 fake_borrow_temps,
439                 expr.temp_lifetime,
440                 expr_span,
441                 source_info,
442             ),
443             ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
444                 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id.expect_local());
445                 this.lower_captured_upvar(block, upvar_id)
446             }
447
448             ExprKind::VarRef { id } => {
449                 let place_builder = if this.is_bound_var_in_guard(id) {
450                     let index = this.var_local_id(id, RefWithinGuard);
451                     PlaceBuilder::from(index).deref()
452                 } else {
453                     let index = this.var_local_id(id, OutsideGuard);
454                     PlaceBuilder::from(index)
455                 };
456                 block.and(place_builder)
457             }
458
459             ExprKind::PlaceTypeAscription { source, user_ty } => {
460                 let source = this.hir.mirror(source);
461                 let place_builder = unpack!(
462                     block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
463                 );
464                 if let Some(user_ty) = user_ty {
465                     let annotation_index =
466                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
467                             span: source_info.span,
468                             user_ty,
469                             inferred_ty: expr.ty,
470                         });
471
472                     let place =
473                         place_builder.clone().into_place(this.hir.tcx(), this.hir.typeck_results());
474                     this.cfg.push(
475                         block,
476                         Statement {
477                             source_info,
478                             kind: StatementKind::AscribeUserType(
479                                 box (
480                                     place,
481                                     UserTypeProjection { base: annotation_index, projs: vec![] },
482                                 ),
483                                 Variance::Invariant,
484                             ),
485                         },
486                     );
487                 }
488                 block.and(place_builder)
489             }
490             ExprKind::ValueTypeAscription { source, user_ty } => {
491                 let source = this.hir.mirror(source);
492                 let temp =
493                     unpack!(block = this.as_temp(block, source.temp_lifetime, source, mutability));
494                 if let Some(user_ty) = user_ty {
495                     let annotation_index =
496                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
497                             span: source_info.span,
498                             user_ty,
499                             inferred_ty: expr.ty,
500                         });
501                     this.cfg.push(
502                         block,
503                         Statement {
504                             source_info,
505                             kind: StatementKind::AscribeUserType(
506                                 box (
507                                     Place::from(temp),
508                                     UserTypeProjection { base: annotation_index, projs: vec![] },
509                                 ),
510                                 Variance::Invariant,
511                             ),
512                         },
513                     );
514                 }
515                 block.and(PlaceBuilder::from(temp))
516             }
517
518             ExprKind::Array { .. }
519             | ExprKind::Tuple { .. }
520             | ExprKind::Adt { .. }
521             | ExprKind::Closure { .. }
522             | ExprKind::Unary { .. }
523             | ExprKind::Binary { .. }
524             | ExprKind::LogicalOp { .. }
525             | ExprKind::Box { .. }
526             | ExprKind::Cast { .. }
527             | ExprKind::Use { .. }
528             | ExprKind::NeverToAny { .. }
529             | ExprKind::Pointer { .. }
530             | ExprKind::Repeat { .. }
531             | ExprKind::Borrow { .. }
532             | ExprKind::AddressOf { .. }
533             | ExprKind::Match { .. }
534             | ExprKind::If { .. }
535             | ExprKind::Loop { .. }
536             | ExprKind::Block { .. }
537             | ExprKind::Assign { .. }
538             | ExprKind::AssignOp { .. }
539             | ExprKind::Break { .. }
540             | ExprKind::Continue { .. }
541             | ExprKind::Return { .. }
542             | ExprKind::Literal { .. }
543             | ExprKind::ConstBlock { .. }
544             | ExprKind::StaticRef { .. }
545             | ExprKind::InlineAsm { .. }
546             | ExprKind::LlvmInlineAsm { .. }
547             | ExprKind::Yield { .. }
548             | ExprKind::ThreadLocalRef(_)
549             | ExprKind::Call { .. } => {
550                 // these are not places, so we need to make a temporary.
551                 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
552                 let temp =
553                     unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
554                 block.and(PlaceBuilder::from(temp))
555             }
556         }
557     }
558
559     /// Lower a captured upvar. Note we might not know the actual capture index,
560     /// so we create a place starting from `PlaceBase::Upvar`, which will be resolved
561     /// once all projections that allow us to indentify a capture have been applied.
562     fn lower_captured_upvar(
563         &mut self,
564         block: BasicBlock,
565         upvar_id: ty::UpvarId,
566     ) -> BlockAnd<PlaceBuilder<'tcx>> {
567         let closure_ty = self
568             .hir
569             .typeck_results()
570             .node_type(self.hir.tcx().hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
571
572         let closure_kind = if let ty::Closure(_, closure_substs) = closure_ty.kind() {
573             self.hir.infcx().closure_kind(closure_substs).unwrap()
574         } else {
575             // Generators are considered FnOnce.
576             ty::ClosureKind::FnOnce
577         };
578
579         block.and(PlaceBuilder::from(PlaceBase::Upvar {
580             var_hir_id: upvar_id.var_path.hir_id,
581             closure_def_id: upvar_id.closure_expr_id.to_def_id(),
582             closure_kind,
583         }))
584     }
585
586     /// Lower an index expression
587     ///
588     /// This has two complications;
589     ///
590     /// * We need to do a bounds check.
591     /// * We need to ensure that the bounds check can't be invalidated using an
592     ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
593     ///   that this is the case.
594     fn lower_index_expression(
595         &mut self,
596         mut block: BasicBlock,
597         base: ExprRef<'tcx>,
598         index: ExprRef<'tcx>,
599         mutability: Mutability,
600         fake_borrow_temps: Option<&mut Vec<Local>>,
601         temp_lifetime: Option<region::Scope>,
602         expr_span: Span,
603         source_info: SourceInfo,
604     ) -> BlockAnd<PlaceBuilder<'tcx>> {
605         let lhs = self.hir.mirror(base);
606
607         let base_fake_borrow_temps = &mut Vec::new();
608         let is_outermost_index = fake_borrow_temps.is_none();
609         let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
610
611         let mut base_place =
612             unpack!(block = self.expr_as_place(block, lhs, mutability, Some(fake_borrow_temps),));
613
614         // Making this a *fresh* temporary means we do not have to worry about
615         // the index changing later: Nothing will ever change this temporary.
616         // The "retagging" transformation (for Stacked Borrows) relies on this.
617         let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
618
619         block = self.bounds_check(
620             block,
621             base_place.clone().into_place(self.hir.tcx(), self.hir.typeck_results()),
622             idx,
623             expr_span,
624             source_info,
625         );
626
627         if is_outermost_index {
628             self.read_fake_borrows(block, fake_borrow_temps, source_info)
629         } else {
630             base_place = base_place.expect_upvars_resolved(self.hir.tcx(), self.hir.typeck_results());
631             self.add_fake_borrows_of_base(
632                 &base_place,
633                 block,
634                 fake_borrow_temps,
635                 expr_span,
636                 source_info,
637             );
638         }
639
640         block.and(base_place.index(idx))
641     }
642
643     fn bounds_check(
644         &mut self,
645         block: BasicBlock,
646         slice: Place<'tcx>,
647         index: Local,
648         expr_span: Span,
649         source_info: SourceInfo,
650     ) -> BasicBlock {
651         let usize_ty = self.hir.usize_ty();
652         let bool_ty = self.hir.bool_ty();
653         // bounds check:
654         let len = self.temp(usize_ty, expr_span);
655         let lt = self.temp(bool_ty, expr_span);
656
657         // len = len(slice)
658         self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice));
659         // lt = idx < len
660         self.cfg.push_assign(
661             block,
662             source_info,
663             lt,
664             Rvalue::BinaryOp(BinOp::Lt, Operand::Copy(Place::from(index)), Operand::Copy(len)),
665         );
666         let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
667         // assert!(lt, "...")
668         self.assert(block, Operand::Move(lt), true, msg, expr_span)
669     }
670
671     fn add_fake_borrows_of_base(
672         &mut self,
673         base_place: &PlaceBuilder<'tcx>,
674         block: BasicBlock,
675         fake_borrow_temps: &mut Vec<Local>,
676         expr_span: Span,
677         source_info: SourceInfo,
678     ) {
679         let tcx = self.hir.tcx();
680         let local = match base_place.base {
681             PlaceBase::Local(local) => local,
682             PlaceBase::Upvar { .. } => bug!("Expected PlacseBase::Local found Upvar")
683         };
684
685         let place_ty = Place::ty_from(local, &base_place.projection, &self.local_decls, tcx);
686         if let ty::Slice(_) = place_ty.ty.kind() {
687             // We need to create fake borrows to ensure that the bounds
688             // check that we just did stays valid. Since we can't assign to
689             // unsized values, we only need to ensure that none of the
690             // pointers in the base place are modified.
691             for (idx, elem) in base_place.projection.iter().enumerate().rev() {
692                 match elem {
693                     ProjectionElem::Deref => {
694                         let fake_borrow_deref_ty = Place::ty_from(
695                             local,
696                             &base_place.projection[..idx],
697                             &self.local_decls,
698                             tcx,
699                         )
700                         .ty;
701                         let fake_borrow_ty =
702                             tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
703                         let fake_borrow_temp =
704                             self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
705                         let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
706                         self.cfg.push_assign(
707                             block,
708                             source_info,
709                             fake_borrow_temp.into(),
710                             Rvalue::Ref(
711                                 tcx.lifetimes.re_erased,
712                                 BorrowKind::Shallow,
713                                 Place { local, projection },
714                             ),
715                         );
716                         fake_borrow_temps.push(fake_borrow_temp);
717                     }
718                     ProjectionElem::Index(_) => {
719                         let index_ty = Place::ty_from(
720                             local,
721                             &base_place.projection[..idx],
722                             &self.local_decls,
723                             tcx,
724                         );
725                         match index_ty.ty.kind() {
726                             // The previous index expression has already
727                             // done any index expressions needed here.
728                             ty::Slice(_) => break,
729                             ty::Array(..) => (),
730                             _ => bug!("unexpected index base"),
731                         }
732                     }
733                     ProjectionElem::Field(..)
734                     | ProjectionElem::Downcast(..)
735                     | ProjectionElem::ConstantIndex { .. }
736                     | ProjectionElem::Subslice { .. } => (),
737                 }
738             }
739         }
740     }
741
742     fn read_fake_borrows(
743         &mut self,
744         bb: BasicBlock,
745         fake_borrow_temps: &mut Vec<Local>,
746         source_info: SourceInfo,
747     ) {
748         // All indexes have been evaluated now, read all of the
749         // fake borrows so that they are live across those index
750         // expressions.
751         for temp in fake_borrow_temps {
752             self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
753         }
754     }
755 }