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};
6 use rustc_hir::def_id::{DefId, LocalDefId};
7 use rustc_middle::hir::place::Projection as HirProjection;
8 use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
9 use rustc_middle::middle::region;
10 use rustc_middle::mir::tcx::PlaceTy;
11 use rustc_middle::mir::AssertKind::BoundsCheck;
12 use rustc_middle::mir::*;
13 use rustc_middle::thir::*;
14 use rustc_middle::ty::AdtDef;
15 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance};
17 use rustc_target::abi::VariantIdx;
19 use rustc_index::vec::Idx;
23 /// The "outermost" place that holds this value.
24 #[derive(Copy, Clone, Debug, PartialEq)]
25 pub(crate) enum PlaceBase {
26 /// Denotes the start of a `Place`.
29 /// When building place for an expression within a closure, the place might start off a
30 /// captured path. When `capture_disjoint_fields` is enabled, we might not know the capture
31 /// index (within the desugared closure) of the captured path until most of the projections
32 /// are applied. We use `PlaceBase::Upvar` to keep track of the root variable off of which the
33 /// captured path starts, the closure the capture belongs to and the trait the closure
36 /// Once we have figured out the capture index, we can convert the place builder to start from
37 /// `PlaceBase::Local`.
39 /// Consider the following example
41 /// let t = (((10, 10), 10), 10);
44 /// println!("{}", t.0.0.0);
47 /// Here the THIR expression for `t.0.0.0` will be something like
49 /// ```ignore (illustrative)
56 /// When `capture_disjoint_fields` is enabled, `t.0.0.0` is captured and we won't be able to
57 /// figure out that it is captured until all the `Field` projections are applied.
59 /// HirId of the upvar
60 var_hir_id: LocalVarId,
61 /// DefId of the closure
62 closure_def_id: DefId,
63 /// The trait closure implements, `Fn`, `FnMut`, `FnOnce`
64 closure_kind: ty::ClosureKind,
68 /// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
69 /// place by pushing more and more projections onto the end, and then convert the final set into a
70 /// place using the `into_place` method.
72 /// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
73 /// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
74 #[derive(Clone, Debug, PartialEq)]
75 pub(in crate::build) struct PlaceBuilder<'tcx> {
77 projection: Vec<PlaceElem<'tcx>>,
80 /// Given a list of MIR projections, convert them to list of HIR ProjectionKind.
81 /// The projections are truncated to represent a path that might be captured by a
82 /// closure/generator. This implies the vector returned from this function doesn't contain
83 /// ProjectionElems `Downcast`, `ConstantIndex`, `Index`, or `Subslice` because those will never be
84 /// part of a path that is captured by a closure. We stop applying projections once we see the first
85 /// projection that isn't captured by a closure.
86 fn convert_to_hir_projections_and_truncate_for_capture<'tcx>(
87 mir_projections: &[PlaceElem<'tcx>],
88 ) -> Vec<HirProjectionKind> {
89 let mut hir_projections = Vec::new();
90 let mut variant = None;
92 for mir_projection in mir_projections {
93 let hir_projection = match mir_projection {
94 ProjectionElem::Deref => HirProjectionKind::Deref,
95 ProjectionElem::Field(field, _) => {
96 let variant = variant.unwrap_or(VariantIdx::new(0));
97 HirProjectionKind::Field(field.index() as u32, variant)
99 ProjectionElem::Downcast(.., idx) => {
100 // We don't expect to see multi-variant enums here, as earlier
101 // phases will have truncated them already. However, there can
102 // still be downcasts, thanks to single-variant enums.
103 // We keep track of VariantIdx so we can use this information
104 // if the next ProjectionElem is a Field.
105 variant = Some(*idx);
108 // These do not affect anything, they just make sure we know the right type.
109 ProjectionElem::OpaqueCast(_) => continue,
110 ProjectionElem::Index(..)
111 | ProjectionElem::ConstantIndex { .. }
112 | ProjectionElem::Subslice { .. } => {
113 // We don't capture array-access projections.
114 // We can stop here as arrays are captured completely.
119 hir_projections.push(hir_projection);
125 /// Return true if the `proj_possible_ancestor` represents an ancestor path
126 /// to `proj_capture` or `proj_possible_ancestor` is same as `proj_capture`,
127 /// assuming they both start off of the same root variable.
129 /// **Note:** It's the caller's responsibility to ensure that both lists of projections
130 /// start off of the same root variable.
132 /// Eg: 1. `foo.x` which is represented using `projections=[Field(x)]` is an ancestor of
133 /// `foo.x.y` which is represented using `projections=[Field(x), Field(y)]`.
134 /// Note both `foo.x` and `foo.x.y` start off of the same root variable `foo`.
135 /// 2. Since we only look at the projections here function will return `bar.x` as an a valid
136 /// ancestor of `foo.x.y`. It's the caller's responsibility to ensure that both projections
137 /// list are being applied to the same root variable.
138 fn is_ancestor_or_same_capture(
139 proj_possible_ancestor: &[HirProjectionKind],
140 proj_capture: &[HirProjectionKind],
142 // We want to make sure `is_ancestor_or_same_capture("x.0.0", "x.0")` to return false.
143 // Therefore we can't just check if all projections are same in the zipped iterator below.
144 if proj_possible_ancestor.len() > proj_capture.len() {
148 iter::zip(proj_possible_ancestor, proj_capture).all(|(a, b)| a == b)
151 /// Computes the index of a capture within the desugared closure provided the closure's
152 /// `closure_min_captures` and the capture's index of the capture in the
153 /// `ty::MinCaptureList` of the root variable `var_hir_id`.
154 fn compute_capture_idx<'tcx>(
155 closure_min_captures: &ty::RootVariableMinCaptureList<'tcx>,
156 var_hir_id: LocalVarId,
160 for (var_id, capture_list) in closure_min_captures {
161 if *var_id == var_hir_id.0 {
165 res += capture_list.len();
172 /// Given a closure, returns the index of a capture within the desugared closure struct and the
173 /// `ty::CapturedPlace` which is the ancestor of the Place represented using the `var_hir_id`
174 /// and `projection`.
176 /// Note there will be at most one ancestor for any given Place.
178 /// Returns None, when the ancestor is not found.
179 fn find_capture_matching_projections<'a, 'tcx>(
180 typeck_results: &'a ty::TypeckResults<'tcx>,
181 var_hir_id: LocalVarId,
182 closure_def_id: DefId,
183 projections: &[PlaceElem<'tcx>],
184 ) -> Option<(usize, &'a ty::CapturedPlace<'tcx>)> {
185 let closure_min_captures = typeck_results.closure_min_captures.get(&closure_def_id)?;
186 let root_variable_min_captures = closure_min_captures.get(&var_hir_id.0)?;
188 let hir_projections = convert_to_hir_projections_and_truncate_for_capture(projections);
190 // If an ancestor is found, `idx` is the index within the list of captured places
191 // for root variable `var_hir_id` and `capture` is the `ty::CapturedPlace` itself.
192 let (idx, capture) = root_variable_min_captures.iter().enumerate().find(|(_, capture)| {
193 let possible_ancestor_proj_kinds: Vec<_> =
194 capture.place.projections.iter().map(|proj| proj.kind).collect();
195 is_ancestor_or_same_capture(&possible_ancestor_proj_kinds, &hir_projections)
198 // Convert index to be from the perspective of the entire closure_min_captures map
199 // instead of just the root variable capture list
200 Some((compute_capture_idx(closure_min_captures, var_hir_id, idx), capture))
203 /// Takes a PlaceBuilder and resolves the upvar (if any) within it, so that the
204 /// `PlaceBuilder` now starts from `PlaceBase::Local`.
206 /// Returns a Result with the error being the PlaceBuilder (`from_builder`) that was not found.
207 #[instrument(level = "trace", skip(cx))]
208 fn to_upvars_resolved_place_builder<'tcx>(
209 from_builder: PlaceBuilder<'tcx>,
210 cx: &Builder<'_, 'tcx>,
211 ) -> Result<PlaceBuilder<'tcx>, PlaceBuilder<'tcx>> {
212 match from_builder.base {
213 PlaceBase::Local(_) => Ok(from_builder),
214 PlaceBase::Upvar { var_hir_id, closure_def_id, closure_kind } => {
215 let mut upvar_resolved_place_builder = PlaceBuilder::from(ty::CAPTURE_STRUCT_LOCAL);
217 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
218 upvar_resolved_place_builder = upvar_resolved_place_builder.deref();
220 ty::ClosureKind::FnOnce => {}
223 let Some((capture_index, capture)) =
224 find_capture_matching_projections(
228 &from_builder.projection,
230 let closure_span = cx.tcx.def_span(closure_def_id);
231 if !enable_precise_capture(cx.tcx, closure_span) {
233 "No associated capture found for {:?}[{:#?}] even though \
234 capture_disjoint_fields isn't enabled",
236 from_builder.projection
240 "No associated capture found for {:?}[{:#?}]",
241 var_hir_id, from_builder.projection,
244 return Err(from_builder);
247 // We won't be building MIR if the closure wasn't local
248 let closure_hir_id = cx.tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local());
249 let closure_ty = cx.typeck_results.node_type(closure_hir_id);
251 let substs = match closure_ty.kind() {
252 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
253 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
254 _ => bug!("Lowering capture for non-closure type {:?}", closure_ty),
257 // Access the capture by accessing the field within the Closure struct.
259 // We must have inferred the capture types since we are building MIR, therefore
260 // it's safe to call `tuple_element_ty` and we can unwrap here because
261 // we know that the capture exists and is the `capture_index`-th capture.
262 let var_ty = substs.tupled_upvars_ty().tuple_fields()[capture_index];
264 upvar_resolved_place_builder =
265 upvar_resolved_place_builder.field(Field::new(capture_index), var_ty);
267 // If the variable is captured via ByRef(Immutable/Mutable) Borrow,
268 // we need to deref it
269 upvar_resolved_place_builder = match capture.info.capture_kind {
270 ty::UpvarCapture::ByRef(_) => upvar_resolved_place_builder.deref(),
271 ty::UpvarCapture::ByValue => upvar_resolved_place_builder,
274 // We used some of the projections to build the capture itself,
275 // now we apply the remaining to the upvar resolved place.
276 trace!(?capture.place, ?from_builder.projection);
277 let remaining_projections = strip_prefix(
278 capture.place.base_ty,
279 from_builder.projection,
280 &capture.place.projections,
282 upvar_resolved_place_builder.projection.extend(remaining_projections);
283 trace!(?upvar_resolved_place_builder);
285 Ok(upvar_resolved_place_builder)
290 /// Returns projections remaining after stripping an initial prefix of HIR
293 /// Supports only HIR projection kinds that represent a path that might be
294 /// captured by a closure or a generator, i.e., an `Index` or a `Subslice`
295 /// projection kinds are unsupported.
296 fn strip_prefix<'tcx>(
297 mut base_ty: Ty<'tcx>,
298 projections: Vec<PlaceElem<'tcx>>,
299 prefix_projections: &[HirProjection<'tcx>],
300 ) -> impl Iterator<Item = PlaceElem<'tcx>> {
301 let mut iter = projections.into_iter();
302 let mut next = || match iter.next()? {
303 // Filter out opaque casts, they are unnecessary in the prefix.
304 ProjectionElem::OpaqueCast(..) => iter.next(),
305 other => Some(other),
307 for projection in prefix_projections {
308 match projection.kind {
309 HirProjectionKind::Deref => {
310 assert!(matches!(next(), Some(ProjectionElem::Deref)));
312 HirProjectionKind::Field(..) => {
313 if base_ty.is_enum() {
314 assert!(matches!(next(), Some(ProjectionElem::Downcast(..))));
316 assert!(matches!(next(), Some(ProjectionElem::Field(..))));
318 HirProjectionKind::Index | HirProjectionKind::Subslice => {
319 bug!("unexpected projection kind: {:?}", projection);
322 base_ty = projection.ty;
327 impl<'tcx> PlaceBuilder<'tcx> {
328 pub(crate) fn into_place(self, cx: &Builder<'_, 'tcx>) -> Place<'tcx> {
329 if let PlaceBase::Local(local) = self.base {
330 let mut projections = vec![];
331 let mut ty = PlaceTy::from_ty(cx.local_decls[local].ty);
332 for projection in self.projection {
333 // Only preserve those opaque casts that actually go from an opaque type
335 if let ProjectionElem::OpaqueCast(t) = projection {
336 if let ty::Opaque(..) = ty.ty.kind() {
338 projections.push(ProjectionElem::OpaqueCast(t));
342 projections.push(projection);
344 ty = ty.projection_ty(cx.tcx, projection);
346 Place { local, projection: cx.tcx.intern_place_elems(&projections) }
348 self.expect_upvars_resolved(cx).into_place(cx)
352 fn expect_upvars_resolved(self, cx: &Builder<'_, 'tcx>) -> PlaceBuilder<'tcx> {
353 to_upvars_resolved_place_builder(self, cx).unwrap()
356 /// Attempts to resolve the `PlaceBuilder`.
357 /// On success, it will return the resolved `PlaceBuilder`.
358 /// On failure, it will return itself.
360 /// Upvars resolve may fail for a `PlaceBuilder` when attempting to
361 /// resolve a disjoint field whose root variable is not captured
362 /// (destructured assignments) or when attempting to resolve a root
363 /// variable (discriminant matching with only wildcard arm) that is
364 /// not captured. This can happen because the final mir that will be
365 /// generated doesn't require a read for this place. Failures will only
366 /// happen inside closures.
367 pub(crate) fn try_upvars_resolved(
369 cx: &Builder<'_, 'tcx>,
370 ) -> Result<PlaceBuilder<'tcx>, PlaceBuilder<'tcx>> {
371 to_upvars_resolved_place_builder(self, cx)
374 pub(crate) fn base(&self) -> PlaceBase {
378 pub(crate) fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
379 self.project(PlaceElem::Field(f, ty))
382 pub(crate) fn deref(self) -> Self {
383 self.project(PlaceElem::Deref)
386 pub(crate) fn downcast(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx) -> Self {
387 self.project(PlaceElem::Downcast(Some(adt_def.variant(variant_index).name), variant_index))
390 fn index(self, index: Local) -> Self {
391 self.project(PlaceElem::Index(index))
394 pub(crate) fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
395 self.projection.push(elem);
400 impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
401 fn from(local: Local) -> Self {
402 Self { base: PlaceBase::Local(local), projection: Vec::new() }
406 impl<'tcx> From<PlaceBase> for PlaceBuilder<'tcx> {
407 fn from(base: PlaceBase) -> Self {
408 Self { base, projection: Vec::new() }
412 impl<'a, 'tcx> Builder<'a, 'tcx> {
413 /// Compile `expr`, yielding a place that we can move from etc.
415 /// WARNING: Any user code might:
416 /// * Invalidate any slice bounds checks performed.
417 /// * Change the address that this `Place` refers to.
418 /// * Modify the memory that this place refers to.
419 /// * Invalidate the memory that this place refers to, this will be caught
420 /// by borrow checking.
422 /// Extra care is needed if any user code is allowed to run between calling
423 /// this method and using it, as is the case for `match` and index
425 pub(crate) fn as_place(
427 mut block: BasicBlock,
429 ) -> BlockAnd<Place<'tcx>> {
430 let place_builder = unpack!(block = self.as_place_builder(block, expr));
431 block.and(place_builder.into_place(self))
434 /// This is used when constructing a compound `Place`, so that we can avoid creating
435 /// intermediate `Place` values until we know the full set of projections.
436 pub(crate) fn as_place_builder(
440 ) -> BlockAnd<PlaceBuilder<'tcx>> {
441 self.expr_as_place(block, expr, Mutability::Mut, None)
444 /// Compile `expr`, yielding a place that we can move from etc.
445 /// Mutability note: The caller of this method promises only to read from the resulting
446 /// place. The place itself may or may not be mutable:
447 /// * If this expr is a place expr like a.b, then we will return that place.
448 /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
449 pub(crate) fn as_read_only_place(
451 mut block: BasicBlock,
453 ) -> BlockAnd<Place<'tcx>> {
454 let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
455 block.and(place_builder.into_place(self))
458 /// This is used when constructing a compound `Place`, so that we can avoid creating
459 /// intermediate `Place` values until we know the full set of projections.
460 /// Mutability note: The caller of this method promises only to read from the resulting
461 /// place. The place itself may or may not be mutable:
462 /// * If this expr is a place expr like a.b, then we will return that place.
463 /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
464 fn as_read_only_place_builder(
468 ) -> BlockAnd<PlaceBuilder<'tcx>> {
469 self.expr_as_place(block, expr, Mutability::Not, None)
474 mut block: BasicBlock,
476 mutability: Mutability,
477 fake_borrow_temps: Option<&mut Vec<Local>>,
478 ) -> BlockAnd<PlaceBuilder<'tcx>> {
479 debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
482 let expr_span = expr.span;
483 let source_info = this.source_info(expr_span);
485 ExprKind::Scope { region_scope, lint_level, value } => {
486 this.in_scope((region_scope, source_info), lint_level, |this| {
487 this.expr_as_place(block, &this.thir[value], mutability, fake_borrow_temps)
490 ExprKind::Field { lhs, variant_index, name } => {
491 let lhs = &this.thir[lhs];
492 let mut place_builder =
493 unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
494 if let ty::Adt(adt_def, _) = lhs.ty.kind() {
495 if adt_def.is_enum() {
496 place_builder = place_builder.downcast(*adt_def, variant_index);
499 block.and(place_builder.field(name, expr.ty))
501 ExprKind::Deref { arg } => {
502 let place_builder = unpack!(
504 this.expr_as_place(block, &this.thir[arg], mutability, fake_borrow_temps,)
506 block.and(place_builder.deref())
508 ExprKind::Index { lhs, index } => this.lower_index_expression(
518 ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
519 this.lower_captured_upvar(block, closure_def_id.expect_local(), var_hir_id)
522 ExprKind::VarRef { id } => {
523 let place_builder = if this.is_bound_var_in_guard(id) {
524 let index = this.var_local_id(id, RefWithinGuard);
525 PlaceBuilder::from(index).deref()
527 let index = this.var_local_id(id, OutsideGuard);
528 PlaceBuilder::from(index)
530 block.and(place_builder)
533 ExprKind::PlaceTypeAscription { source, user_ty } => {
534 let place_builder = unpack!(
535 block = this.expr_as_place(
542 if let Some(user_ty) = user_ty {
543 let annotation_index =
544 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
545 span: source_info.span,
547 inferred_ty: expr.ty,
550 let place = place_builder.clone().into_place(this);
555 kind: StatementKind::AscribeUserType(
558 UserTypeProjection { base: annotation_index, projs: vec![] },
565 block.and(place_builder)
567 ExprKind::ValueTypeAscription { source, user_ty } => {
568 let source = &this.thir[source];
570 unpack!(block = this.as_temp(block, source.temp_lifetime, source, mutability));
571 if let Some(user_ty) = user_ty {
572 let annotation_index =
573 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
574 span: source_info.span,
576 inferred_ty: expr.ty,
582 kind: StatementKind::AscribeUserType(
585 UserTypeProjection { base: annotation_index, projs: vec![] },
592 block.and(PlaceBuilder::from(temp))
595 ExprKind::Array { .. }
596 | ExprKind::Tuple { .. }
597 | ExprKind::Adt { .. }
598 | ExprKind::Closure { .. }
599 | ExprKind::Unary { .. }
600 | ExprKind::Binary { .. }
601 | ExprKind::LogicalOp { .. }
602 | ExprKind::Box { .. }
603 | ExprKind::Cast { .. }
604 | ExprKind::Use { .. }
605 | ExprKind::NeverToAny { .. }
606 | ExprKind::Pointer { .. }
607 | ExprKind::Repeat { .. }
608 | ExprKind::Borrow { .. }
609 | ExprKind::AddressOf { .. }
610 | ExprKind::Match { .. }
611 | ExprKind::If { .. }
612 | ExprKind::Loop { .. }
613 | ExprKind::Block { .. }
614 | ExprKind::Let { .. }
615 | ExprKind::Assign { .. }
616 | ExprKind::AssignOp { .. }
617 | ExprKind::Break { .. }
618 | ExprKind::Continue { .. }
619 | ExprKind::Return { .. }
620 | ExprKind::Literal { .. }
621 | ExprKind::NamedConst { .. }
622 | ExprKind::NonHirLiteral { .. }
623 | ExprKind::ZstLiteral { .. }
624 | ExprKind::ConstParam { .. }
625 | ExprKind::ConstBlock { .. }
626 | ExprKind::StaticRef { .. }
627 | ExprKind::InlineAsm { .. }
628 | ExprKind::Yield { .. }
629 | ExprKind::ThreadLocalRef(_)
630 | ExprKind::Call { .. } => {
631 // these are not places, so we need to make a temporary.
632 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
634 unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
635 block.and(PlaceBuilder::from(temp))
640 /// Lower a captured upvar. Note we might not know the actual capture index,
641 /// so we create a place starting from `PlaceBase::Upvar`, which will be resolved
642 /// once all projections that allow us to identify a capture have been applied.
643 fn lower_captured_upvar(
646 closure_expr_id: LocalDefId,
647 var_hir_id: LocalVarId,
648 ) -> BlockAnd<PlaceBuilder<'tcx>> {
650 self.typeck_results.node_type(self.tcx.hir().local_def_id_to_hir_id(closure_expr_id));
652 let closure_kind = if let ty::Closure(_, closure_substs) = closure_ty.kind() {
653 self.infcx.closure_kind(closure_substs).unwrap()
655 // Generators are considered FnOnce.
656 ty::ClosureKind::FnOnce
659 block.and(PlaceBuilder::from(PlaceBase::Upvar {
661 closure_def_id: closure_expr_id.to_def_id(),
666 /// Lower an index expression
668 /// This has two complications;
670 /// * We need to do a bounds check.
671 /// * We need to ensure that the bounds check can't be invalidated using an
672 /// expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
673 /// that this is the case.
674 fn lower_index_expression(
676 mut block: BasicBlock,
679 mutability: Mutability,
680 fake_borrow_temps: Option<&mut Vec<Local>>,
681 temp_lifetime: Option<region::Scope>,
683 source_info: SourceInfo,
684 ) -> BlockAnd<PlaceBuilder<'tcx>> {
685 let base_fake_borrow_temps = &mut Vec::new();
686 let is_outermost_index = fake_borrow_temps.is_none();
687 let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
690 unpack!(block = self.expr_as_place(block, base, mutability, Some(fake_borrow_temps),));
692 // Making this a *fresh* temporary means we do not have to worry about
693 // the index changing later: Nothing will ever change this temporary.
694 // The "retagging" transformation (for Stacked Borrows) relies on this.
695 let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
697 block = self.bounds_check(block, base_place.clone(), idx, expr_span, source_info);
699 if is_outermost_index {
700 self.read_fake_borrows(block, fake_borrow_temps, source_info)
702 base_place = base_place.expect_upvars_resolved(self);
703 self.add_fake_borrows_of_base(
712 block.and(base_place.index(idx))
718 slice: PlaceBuilder<'tcx>,
721 source_info: SourceInfo,
723 let usize_ty = self.tcx.types.usize;
724 let bool_ty = self.tcx.types.bool;
726 let len = self.temp(usize_ty, expr_span);
727 let lt = self.temp(bool_ty, expr_span);
730 self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice.into_place(self)));
732 self.cfg.push_assign(
738 Box::new((Operand::Copy(Place::from(index)), Operand::Copy(len))),
741 let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
742 // assert!(lt, "...")
743 self.assert(block, Operand::Move(lt), true, msg, expr_span)
746 fn add_fake_borrows_of_base(
748 base_place: &PlaceBuilder<'tcx>,
750 fake_borrow_temps: &mut Vec<Local>,
752 source_info: SourceInfo,
755 let local = match base_place.base {
756 PlaceBase::Local(local) => local,
757 PlaceBase::Upvar { .. } => bug!("Expected PlacseBase::Local found Upvar"),
760 let place_ty = Place::ty_from(local, &base_place.projection, &self.local_decls, tcx);
761 if let ty::Slice(_) = place_ty.ty.kind() {
762 // We need to create fake borrows to ensure that the bounds
763 // check that we just did stays valid. Since we can't assign to
764 // unsized values, we only need to ensure that none of the
765 // pointers in the base place are modified.
766 for (idx, elem) in base_place.projection.iter().enumerate().rev() {
768 ProjectionElem::Deref => {
769 let fake_borrow_deref_ty = Place::ty_from(
771 &base_place.projection[..idx],
777 tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
778 let fake_borrow_temp =
779 self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
780 let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
781 self.cfg.push_assign(
784 fake_borrow_temp.into(),
786 tcx.lifetimes.re_erased,
788 Place { local, projection },
791 fake_borrow_temps.push(fake_borrow_temp);
793 ProjectionElem::Index(_) => {
794 let index_ty = Place::ty_from(
796 &base_place.projection[..idx],
800 match index_ty.ty.kind() {
801 // The previous index expression has already
802 // done any index expressions needed here.
803 ty::Slice(_) => break,
805 _ => bug!("unexpected index base"),
808 ProjectionElem::Field(..)
809 | ProjectionElem::Downcast(..)
810 | ProjectionElem::OpaqueCast(..)
811 | ProjectionElem::ConstantIndex { .. }
812 | ProjectionElem::Subslice { .. } => (),
818 fn read_fake_borrows(
821 fake_borrow_temps: &mut Vec<Local>,
822 source_info: SourceInfo,
824 // All indexes have been evaluated now, read all of the
825 // fake borrows so that they are live across those index
827 for temp in fake_borrow_temps {
828 self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
833 /// Precise capture is enabled if the feature gate `capture_disjoint_fields` is enabled or if
834 /// user is using Rust Edition 2021 or higher.
835 fn enable_precise_capture(tcx: TyCtxt<'_>, closure_span: Span) -> bool {
836 tcx.features().capture_disjoint_fields || closure_span.rust_2021()