Skip to main content

rustc_mir_build/builder/expr/
as_place.rs

1//! See docs in build/expr/mod.rs
2
3use std::{assert_matches, iter};
4
5use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
6use rustc_hir::def_id::LocalDefId;
7use rustc_middle::hir::place::{Projection as HirProjection, ProjectionKind as HirProjectionKind};
8use rustc_middle::mir::AssertKind::BoundsCheck;
9use rustc_middle::mir::*;
10use rustc_middle::thir::*;
11use rustc_middle::ty::{self, AdtDef, CanonicalUserTypeAnnotation, Ty, Variance};
12use rustc_span::{Span, bug, span_bug};
13use tracing::{debug, instrument, trace};
14
15use crate::builder::ForGuard::{OutsideGuard, RefWithinGuard};
16use crate::builder::expr::category::Category;
17use crate::builder::scope::LintLevel;
18use crate::builder::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap};
19
20/// The "outermost" place that holds this value.
21#[derive(#[automatically_derived]
impl ::core::marker::Copy for PlaceBase { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PlaceBase { }
#[automatically_derived]
impl ::core::clone::Clone for PlaceBase {
    #[inline]
    fn clone(&self) -> PlaceBase {
        let _: ::core::clone::AssertParamIsClone<Local>;
        let _: ::core::clone::AssertParamIsClone<LocalVarId>;
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PlaceBase {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PlaceBase::Local(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Local",
                    &__self_0),
            PlaceBase::Upvar { var_hir_id: __self_0, closure_def_id: __self_1
                } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Upvar",
                    "var_hir_id", __self_0, "closure_def_id", &__self_1),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for PlaceBase { }
#[automatically_derived]
impl ::core::cmp::PartialEq for PlaceBase {
    #[inline]
    fn eq(&self, other: &PlaceBase) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (PlaceBase::Local(__self_0), PlaceBase::Local(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (PlaceBase::Upvar {
                    var_hir_id: __self_0, closure_def_id: __self_1 },
                    PlaceBase::Upvar {
                    var_hir_id: __arg1_0, closure_def_id: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
22pub(crate) enum PlaceBase {
23    /// Denotes the start of a `Place`.
24    Local(Local),
25
26    /// When building place for an expression within a closure, the place might start off a
27    /// captured path. When `capture_disjoint_fields` is enabled, we might not know the capture
28    /// index (within the desugared closure) of the captured path until most of the projections
29    /// are applied. We use `PlaceBase::Upvar` to keep track of the root variable off of which the
30    /// captured path starts, the closure the capture belongs to and the trait the closure
31    /// implements.
32    ///
33    /// Once we have figured out the capture index, we can convert the place builder to start from
34    /// `PlaceBase::Local`.
35    ///
36    /// Consider the following example
37    /// ```rust
38    /// let t = (((10, 10), 10), 10);
39    ///
40    /// let c = || {
41    ///     println!("{}", t.0.0.0);
42    /// };
43    /// ```
44    /// Here the THIR expression for `t.0.0.0` will be something like
45    ///
46    /// ```ignore (illustrative)
47    /// * Field(0)
48    ///     * Field(0)
49    ///         * Field(0)
50    ///             * UpvarRef(t)
51    /// ```
52    ///
53    /// When `capture_disjoint_fields` is enabled, `t.0.0.0` is captured and we won't be able to
54    /// figure out that it is captured until all the `Field` projections are applied.
55    Upvar {
56        /// HirId of the upvar
57        var_hir_id: LocalVarId,
58        /// DefId of the closure
59        closure_def_id: LocalDefId,
60    },
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 `to_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(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for PlaceBuilder<'tcx> {
    #[inline]
    fn clone(&self) -> PlaceBuilder<'tcx> {
        PlaceBuilder {
            base: ::core::clone::Clone::clone(&self.base),
            projection: ::core::clone::Clone::clone(&self.projection),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PlaceBuilder<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "PlaceBuilder",
            "base", &self.base, "projection", &&self.projection)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for PlaceBuilder<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for PlaceBuilder<'tcx> {
    #[inline]
    fn eq(&self, other: &PlaceBuilder<'tcx>) -> bool {
        self.base == other.base && self.projection == other.projection
    }
}PartialEq)]
70pub(in crate::builder) 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/coroutine. 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 captured by a closure. We stop applying projections once we see the first
80/// projection that isn't captured by a closure.
81fn convert_to_hir_projections_and_truncate_for_capture(
82    mir_projections: &[PlaceElem<'_>],
83) -> Vec<HirProjectionKind> {
84    let mut hir_projections = Vec::new();
85    let mut variant = None;
86
87    for mir_projection in mir_projections {
88        let hir_projection = match mir_projection {
89            ProjectionElem::Deref => HirProjectionKind::Deref,
90            ProjectionElem::PhantomDeref => continue,
91            ProjectionElem::Field(field, _) => {
92                let variant = variant.unwrap_or(FIRST_VARIANT);
93                HirProjectionKind::Field(*field, variant)
94            }
95            ProjectionElem::Downcast(.., idx) => {
96                // We don't expect to see multi-variant enums here, as earlier
97                // phases will have truncated them already. However, there can
98                // still be downcasts, thanks to single-variant enums.
99                // We keep track of VariantIdx so we can use this information
100                // if the next ProjectionElem is a Field.
101                variant = Some(*idx);
102                continue;
103            }
104            ProjectionElem::UnwrapUnsafeBinder(_) => HirProjectionKind::UnwrapUnsafeBinder,
105            // These do not affect anything, they just make sure we know the right type.
106            ProjectionElem::OpaqueCast(_) => continue,
107            ProjectionElem::Index(..)
108            | ProjectionElem::ConstantIndex { .. }
109            | ProjectionElem::Subslice { .. } => {
110                // We don't capture array-access projections.
111                // We can stop here as arrays are captured completely.
112                break;
113            }
114        };
115        variant = None;
116        hir_projections.push(hir_projection);
117    }
118
119    hir_projections
120}
121
122/// Return true if the `proj_possible_ancestor` represents an ancestor path
123/// to `proj_capture` or `proj_possible_ancestor` is same as `proj_capture`,
124/// assuming they both start off of the same root variable.
125///
126/// **Note:** It's the caller's responsibility to ensure that both lists of projections
127///           start off of the same root variable.
128///
129/// Eg: 1. `foo.x` which is represented using `projections=[Field(x)]` is an ancestor of
130///        `foo.x.y` which is represented using `projections=[Field(x), Field(y)]`.
131///        Note both `foo.x` and `foo.x.y` start off of the same root variable `foo`.
132///     2. Since we only look at the projections here function will return `bar.x` as a valid
133///        ancestor of `foo.x.y`. It's the caller's responsibility to ensure that both projections
134///        list are being applied to the same root variable.
135fn is_ancestor_or_same_capture(
136    proj_possible_ancestor: &[HirProjectionKind],
137    proj_capture: &[HirProjectionKind],
138) -> bool {
139    // We want to make sure `is_ancestor_or_same_capture("x.0.0", "x.0")` to return false.
140    // Therefore we can't just check if all projections are same in the zipped iterator below.
141    if proj_possible_ancestor.len() > proj_capture.len() {
142        return false;
143    }
144
145    iter::zip(proj_possible_ancestor, proj_capture).all(|(a, b)| a == b)
146}
147
148/// Given a closure, returns the index of a capture within the desugared closure struct and the
149/// `ty::CapturedPlace` which is the ancestor of the Place represented using the `var_hir_id`
150/// and `projection`.
151///
152/// Note there will be at most one ancestor for any given Place.
153///
154/// Returns None, when the ancestor is not found.
155fn find_capture_matching_projections<'a, 'tcx>(
156    upvars: &'a CaptureMap<'tcx>,
157    var_hir_id: LocalVarId,
158    projections: &[PlaceElem<'tcx>],
159) -> Option<(usize, &'a Capture<'tcx>)> {
160    let hir_projections = convert_to_hir_projections_and_truncate_for_capture(projections);
161
162    upvars.get_by_key_enumerated(var_hir_id.0.local_id).find(|(_, capture)| {
163        let possible_ancestor_proj_kinds: Vec<_> =
164            capture.captured_place.place.projections.iter().map(|proj| proj.kind).collect();
165        is_ancestor_or_same_capture(&possible_ancestor_proj_kinds, &hir_projections)
166    })
167}
168
169/// Takes an upvar place and tries to resolve it into a `PlaceBuilder`
170/// with `PlaceBase::Local`
171{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::TRACE <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("to_upvars_resolved_place_builder",
                                "rustc_mir_build::builder::expr::as_place",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs"),
                                ::tracing_core::__macro_support::Option::Some(171u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_place"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("var_hir_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("var_hir_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("closure_def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("closure_def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("projection")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("projection");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_hir_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&projection)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: Option<PlaceBuilder<'tcx>> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let Some((capture_index, capture)) =
                            find_capture_matching_projections(&cx.upvars, var_hir_id,
                                projection) else {
                                let closure_span = cx.tcx.def_span(closure_def_id);
                                if !enable_precise_capture(closure_span) {
                                    bug_impl(None,
                                        format_args!("No associated capture found for {0:?}[{1:#?}] even though capture_disjoint_fields isn\'t enabled",
                                            var_hir_id, projection), Location::caller())
                                } else {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs:190",
                                                            "rustc_mir_build::builder::expr::as_place",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(190u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_place"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("No associated capture found for {0:?}[{1:#?}]",
                                                                                        var_hir_id, projection) as &dyn ::tracing::field::Value))])
                                                });
                                        } else { ; }
                                    };
                                }
                                return None;
                            };
                        let capture_info = &cx.upvars[capture_index];
                        let mut upvar_resolved_place_builder =
                            PlaceBuilder::from(capture_info.use_place);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs:202",
                                                "rustc_mir_build::builder::expr::as_place",
                                                ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs"),
                                                ::tracing_core::__macro_support::Option::Some(202u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_place"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("capture.captured_place")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("capture.captured_place");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("projection")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("projection");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture.captured_place)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&projection)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let remaining_projections =
                            strip_prefix(capture.captured_place.place.base_ty,
                                projection, &capture.captured_place.place.projections);
                        upvar_resolved_place_builder.projection.extend(remaining_projections);
                        Some(upvar_resolved_place_builder)
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs:171",
                        "rustc_mir_build::builder::expr::as_place",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs"),
                        ::tracing_core::__macro_support::Option::Some(171u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_place"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "trace", skip(cx), ret)]
172fn to_upvars_resolved_place_builder<'tcx>(
173    cx: &Builder<'_, 'tcx>,
174    var_hir_id: LocalVarId,
175    closure_def_id: LocalDefId,
176    projection: &[PlaceElem<'tcx>],
177) -> Option<PlaceBuilder<'tcx>> {
178    let Some((capture_index, capture)) =
179        find_capture_matching_projections(&cx.upvars, var_hir_id, projection)
180    else {
181        let closure_span = cx.tcx.def_span(closure_def_id);
182        if !enable_precise_capture(closure_span) {
183            bug!(
184                "No associated capture found for {:?}[{:#?}] even though \
185                    capture_disjoint_fields isn't enabled",
186                var_hir_id,
187                projection
188            )
189        } else {
190            debug!("No associated capture found for {:?}[{:#?}]", var_hir_id, projection,);
191        }
192        return None;
193    };
194
195    // Access the capture by accessing the field within the Closure struct.
196    let capture_info = &cx.upvars[capture_index];
197
198    let mut upvar_resolved_place_builder = PlaceBuilder::from(capture_info.use_place);
199
200    // We used some of the projections to build the capture itself,
201    // now we apply the remaining to the upvar resolved place.
202    trace!(?capture.captured_place, ?projection);
203    let remaining_projections = strip_prefix(
204        capture.captured_place.place.base_ty,
205        projection,
206        &capture.captured_place.place.projections,
207    );
208    upvar_resolved_place_builder.projection.extend(remaining_projections);
209
210    Some(upvar_resolved_place_builder)
211}
212
213/// Returns projections remaining after stripping an initial prefix of HIR
214/// projections.
215///
216/// Supports only HIR projection kinds that represent a path that might be
217/// captured by a closure or a coroutine, i.e., an `Index` or a `Subslice`
218/// projection kinds are unsupported.
219fn strip_prefix<'tcx>(
220    mut base_ty: Ty<'tcx>,
221    projections: &[PlaceElem<'tcx>],
222    prefix_projections: &[HirProjection<'tcx>],
223) -> impl Iterator<Item = PlaceElem<'tcx>> {
224    let mut iter = projections
225        .iter()
226        .copied()
227        // Filter out opaque casts, they are unnecessary in the prefix.
228        .filter(|elem| !#[allow(non_exhaustive_omitted_patterns)] match elem {
    ProjectionElem::OpaqueCast(..) => true,
    _ => false,
}matches!(elem, ProjectionElem::OpaqueCast(..)));
229    for projection in prefix_projections {
230        match projection.kind {
231            HirProjectionKind::Deref => {
232                {
    match iter.next() {
        Some(ProjectionElem::Deref) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Some(ProjectionElem::Deref)", ::core::option::Option::None);
        }
    }
};assert_matches!(iter.next(), Some(ProjectionElem::Deref));
233            }
234            HirProjectionKind::Field(..) => {
235                if base_ty.is_enum() {
236                    {
    match iter.next() {
        Some(ProjectionElem::Downcast(..)) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Some(ProjectionElem::Downcast(..))",
                ::core::option::Option::None);
        }
    }
};assert_matches!(iter.next(), Some(ProjectionElem::Downcast(..)));
237                }
238                {
    match iter.next() {
        Some(ProjectionElem::Field(..)) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Some(ProjectionElem::Field(..))",
                ::core::option::Option::None);
        }
    }
};assert_matches!(iter.next(), Some(ProjectionElem::Field(..)));
239            }
240            HirProjectionKind::OpaqueCast => {
241                {
    match iter.next() {
        Some(ProjectionElem::OpaqueCast(..)) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Some(ProjectionElem::OpaqueCast(..))",
                ::core::option::Option::None);
        }
    }
};assert_matches!(iter.next(), Some(ProjectionElem::OpaqueCast(..)));
242            }
243            HirProjectionKind::UnwrapUnsafeBinder => {
244                {
    match iter.next() {
        Some(ProjectionElem::UnwrapUnsafeBinder(..)) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Some(ProjectionElem::UnwrapUnsafeBinder(..))",
                ::core::option::Option::None);
        }
    }
};assert_matches!(iter.next(), Some(ProjectionElem::UnwrapUnsafeBinder(..)));
245            }
246            HirProjectionKind::Index | HirProjectionKind::Subslice => {
247                bug_impl(None, format_args!("unexpected projection kind: {0:?}", projection),
    Location::caller());bug!("unexpected projection kind: {:?}", projection);
248            }
249        }
250        base_ty = projection.ty;
251    }
252    iter
253}
254
255impl<'tcx> PlaceBuilder<'tcx> {
256    pub(in crate::builder) fn to_place(&self, cx: &Builder<'_, 'tcx>) -> Place<'tcx> {
257        self.try_to_place(cx).unwrap_or_else(|| match self.base {
258            PlaceBase::Local(local) => bug_impl(Some(cx.local_decls[local].source_info.span),
    format_args!("could not resolve local: {1:#?} + {0:?}", self.projection,
        local), Location::caller())span_bug!(
259                cx.local_decls[local].source_info.span,
260                "could not resolve local: {local:#?} + {:?}",
261                self.projection
262            ),
263            PlaceBase::Upvar { var_hir_id, closure_def_id: _ } => bug_impl(Some(cx.tcx.hir_span(var_hir_id.0)),
    format_args!("could not resolve upvar: {1:?} + {0:?}", self.projection,
        var_hir_id), Location::caller())span_bug!(
264                cx.tcx.hir_span(var_hir_id.0),
265                "could not resolve upvar: {var_hir_id:?} + {:?}",
266                self.projection
267            ),
268        })
269    }
270
271    /// Creates a `Place` or returns `None` if an upvar cannot be resolved
272    pub(in crate::builder) fn try_to_place(&self, cx: &Builder<'_, 'tcx>) -> Option<Place<'tcx>> {
273        let resolved = self.resolve_upvar(cx);
274        let builder = resolved.as_ref().unwrap_or(self);
275        let PlaceBase::Local(local) = builder.base else { return None };
276        let projection = cx.tcx.mk_place_elems(&builder.projection);
277        Some(Place { local, projection })
278    }
279
280    /// Attempts to resolve the `PlaceBuilder`.
281    /// Returns `None` if this is not an upvar.
282    ///
283    /// Upvars resolve may fail for a `PlaceBuilder` when attempting to
284    /// resolve a disjoint field whose root variable is not captured
285    /// (destructured assignments) or when attempting to resolve a root
286    /// variable (discriminant matching with only wildcard arm) that is
287    /// not captured. This can happen because the final mir that will be
288    /// generated doesn't require a read for this place. Failures will only
289    /// happen inside closures.
290    pub(in crate::builder) fn resolve_upvar(
291        &self,
292        cx: &Builder<'_, 'tcx>,
293    ) -> Option<PlaceBuilder<'tcx>> {
294        let PlaceBase::Upvar { var_hir_id, closure_def_id } = self.base else {
295            return None;
296        };
297        to_upvars_resolved_place_builder(cx, var_hir_id, closure_def_id, &self.projection)
298    }
299
300    pub(crate) fn base(&self) -> PlaceBase {
301        self.base
302    }
303
304    pub(crate) fn projection(&self) -> &[PlaceElem<'tcx>] {
305        &self.projection
306    }
307
308    pub(crate) fn field(self, f: FieldIdx, ty: Ty<'tcx>) -> Self {
309        self.project(PlaceElem::Field(f, ty))
310    }
311
312    pub(crate) fn deref(self) -> Self {
313        self.project(PlaceElem::Deref)
314    }
315
316    pub(crate) fn downcast(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx) -> Self {
317        self.project(PlaceElem::Downcast(Some(adt_def.variant(variant_index).name), variant_index))
318    }
319
320    fn index(self, index: Local) -> Self {
321        self.project(PlaceElem::Index(index))
322    }
323
324    pub(crate) fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
325        self.projection.push(elem);
326        self
327    }
328
329    /// Same as `.clone().project(..)` but more efficient
330    pub(crate) fn clone_project(&self, elem: PlaceElem<'tcx>) -> Self {
331        Self {
332            base: self.base,
333            projection: Vec::from_iter(self.projection.iter().copied().chain([elem])),
334        }
335    }
336}
337
338impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
339    fn from(local: Local) -> Self {
340        Self { base: PlaceBase::Local(local), projection: Vec::new() }
341    }
342}
343
344impl<'tcx> From<PlaceBase> for PlaceBuilder<'tcx> {
345    fn from(base: PlaceBase) -> Self {
346        Self { base, projection: Vec::new() }
347    }
348}
349
350impl<'tcx> From<Place<'tcx>> for PlaceBuilder<'tcx> {
351    fn from(p: Place<'tcx>) -> Self {
352        Self { base: PlaceBase::Local(p.local), projection: p.projection.to_vec() }
353    }
354}
355
356impl<'a, 'tcx> Builder<'a, 'tcx> {
357    /// Compile `expr`, yielding a place that we can move from etc.
358    ///
359    /// WARNING: Any user code might:
360    /// * Invalidate any slice bounds checks performed.
361    /// * Change the address that this `Place` refers to.
362    /// * Modify the memory that this place refers to.
363    /// * Invalidate the memory that this place refers to, this will be caught
364    ///   by borrow checking.
365    ///
366    /// Extra care is needed if any user code is allowed to run between calling
367    /// this method and using it, as is the case for `match` and index
368    /// expressions.
369    pub(crate) fn as_place(
370        &mut self,
371        mut block: BasicBlock,
372        expr_id: ExprId,
373    ) -> BlockAnd<Place<'tcx>> {
374        let place_builder = { let BlockAnd(b, v) = self.as_place_builder(block, expr_id); block = b; v }unpack!(block = self.as_place_builder(block, expr_id));
375        block.and(place_builder.to_place(self))
376    }
377
378    /// This is used when constructing a compound `Place`, so that we can avoid creating
379    /// intermediate `Place` values until we know the full set of projections.
380    pub(crate) fn as_place_builder(
381        &mut self,
382        block: BasicBlock,
383        expr_id: ExprId,
384    ) -> BlockAnd<PlaceBuilder<'tcx>> {
385        self.expr_as_place(block, expr_id, Mutability::Mut, None)
386    }
387
388    /// Compile `expr`, yielding a place that we can move from etc.
389    /// Mutability note: The caller of this method promises only to read from the resulting
390    /// place. The place itself may or may not be mutable:
391    /// * If this expr is a place expr like a.b, then we will return that place.
392    /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
393    pub(crate) fn as_read_only_place(
394        &mut self,
395        mut block: BasicBlock,
396        expr_id: ExprId,
397    ) -> BlockAnd<Place<'tcx>> {
398        let place_builder = {
    let BlockAnd(b, v) = self.as_read_only_place_builder(block, expr_id);
    block = b;
    v
}unpack!(block = self.as_read_only_place_builder(block, expr_id));
399        block.and(place_builder.to_place(self))
400    }
401
402    /// This is used when constructing a compound `Place`, so that we can avoid creating
403    /// intermediate `Place` values until we know the full set of projections.
404    /// Mutability note: The caller of this method promises only to read from the resulting
405    /// place. The place itself may or may not be mutable:
406    /// * If this expr is a place expr like a.b, then we will return that place.
407    /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
408    fn as_read_only_place_builder(
409        &mut self,
410        block: BasicBlock,
411        expr_id: ExprId,
412    ) -> BlockAnd<PlaceBuilder<'tcx>> {
413        self.expr_as_place(block, expr_id, Mutability::Not, None)
414    }
415
416    fn expr_as_place(
417        &mut self,
418        mut block: BasicBlock,
419        expr_id: ExprId,
420        mutability: Mutability,
421        fake_borrow_temps: Option<&mut Vec<Local>>,
422    ) -> BlockAnd<PlaceBuilder<'tcx>> {
423        let expr = &self.thir[expr_id];
424        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs:424",
                        "rustc_mir_build::builder::expr::as_place",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_place.rs"),
                        ::tracing_core::__macro_support::Option::Some(424u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_place"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expr_as_place(block={0:?}, expr={1:?}, mutability={2:?})",
                                                    block, expr, mutability) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
425
426        let this = self; // See "LET_THIS_SELF".
427        let expr_span = expr.span;
428        let source_info = this.source_info(expr_span);
429        match expr.kind {
430            ExprKind::Scope { region_scope, hir_id, value } => {
431                this.in_scope((region_scope, source_info), LintLevel::Explicit(hir_id), |this| {
432                    this.push_coverage_point_for_expr(block, source_info, hir_id);
433                    this.expr_as_place(block, value, mutability, fake_borrow_temps)
434                })
435            }
436            ExprKind::Field { lhs, variant_index, name } => {
437                let lhs_expr = &this.thir[lhs];
438                let mut place_builder =
439                    {
    let BlockAnd(b, v) =
        this.expr_as_place(block, lhs, mutability, fake_borrow_temps);
    block = b;
    v
}unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
440                if let ty::Adt(adt_def, _) = lhs_expr.ty.kind() {
441                    if adt_def.is_enum() {
442                        place_builder = place_builder.downcast(*adt_def, variant_index);
443                    }
444                }
445                block.and(place_builder.field(name, expr.ty))
446            }
447            ExprKind::Deref { arg } => {
448                let place_builder =
449                    {
    let BlockAnd(b, v) =
        this.expr_as_place(block, arg, mutability, fake_borrow_temps);
    block = b;
    v
}unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
450                block.and(place_builder.deref())
451            }
452            ExprKind::Index { lhs, index } => this.lower_index_expression(
453                block,
454                lhs,
455                index,
456                mutability,
457                fake_borrow_temps,
458                expr_span,
459                source_info,
460            ),
461            ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
462                this.lower_captured_upvar(block, closure_def_id.expect_local(), var_hir_id)
463            }
464
465            ExprKind::VarRef { id } => {
466                let place_builder = if this.is_bound_var_in_guard(id) {
467                    let index = this.var_local_id(id, RefWithinGuard);
468                    PlaceBuilder::from(index).deref()
469                } else {
470                    let index = this.var_local_id(id, OutsideGuard);
471                    PlaceBuilder::from(index)
472                };
473                block.and(place_builder)
474            }
475
476            ExprKind::PlaceTypeAscription { source, ref user_ty, user_ty_span } => {
477                let place_builder = {
    let BlockAnd(b, v) =
        this.expr_as_place(block, source, mutability, fake_borrow_temps);
    block = b;
    v
}unpack!(
478                    block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
479                );
480                if let Some(user_ty) = user_ty {
481                    let ty_source_info = this.source_info(user_ty_span);
482                    let annotation_index =
483                        this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
484                            span: user_ty_span,
485                            user_ty: user_ty.clone(),
486                            inferred_ty: expr.ty,
487                        });
488
489                    let place = place_builder.to_place(this);
490                    this.cfg.push(
491                        block,
492                        Statement::new(
493                            ty_source_info,
494                            StatementKind::AscribeUserType(
495                                Box::new((
496                                    place,
497                                    UserTypeProjection { base: annotation_index, projs: ::alloc::vec::Vec::new()vec![] },
498                                )),
499                                Variance::Invariant,
500                            ),
501                        ),
502                    );
503                }
504                block.and(place_builder)
505            }
506            ExprKind::ValueTypeAscription { source, ref user_ty, user_ty_span } => {
507                let temp_lifetime =
508                    this.region_scope_tree.temporary_scope(this.thir[source].temp_scope_id);
509                let temp = {
    let BlockAnd(b, v) =
        this.as_temp(block, temp_lifetime, source, mutability);
    block = b;
    v
}unpack!(block = this.as_temp(block, temp_lifetime, source, mutability));
510                if let Some(user_ty) = user_ty {
511                    let ty_source_info = this.source_info(user_ty_span);
512                    let annotation_index =
513                        this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
514                            span: user_ty_span,
515                            user_ty: user_ty.clone(),
516                            inferred_ty: expr.ty,
517                        });
518                    this.cfg.push(
519                        block,
520                        Statement::new(
521                            ty_source_info,
522                            StatementKind::AscribeUserType(
523                                Box::new((
524                                    Place::from(temp),
525                                    UserTypeProjection { base: annotation_index, projs: ::alloc::vec::Vec::new()vec![] },
526                                )),
527                                Variance::Invariant,
528                            ),
529                        ),
530                    );
531                }
532                block.and(PlaceBuilder::from(temp))
533            }
534
535            ExprKind::PlaceUnwrapUnsafeBinder { source } => {
536                let place_builder = {
    let BlockAnd(b, v) =
        this.expr_as_place(block, source, mutability, fake_borrow_temps);
    block = b;
    v
}unpack!(
537                    block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
538                );
539                block.and(place_builder.project(PlaceElem::UnwrapUnsafeBinder(expr.ty)))
540            }
541            ExprKind::ValueUnwrapUnsafeBinder { source } => {
542                let temp_lifetime =
543                    this.region_scope_tree.temporary_scope(this.thir[source].temp_scope_id);
544                let temp = {
    let BlockAnd(b, v) =
        this.as_temp(block, temp_lifetime, source, mutability);
    block = b;
    v
}unpack!(block = this.as_temp(block, temp_lifetime, source, mutability));
545                block.and(PlaceBuilder::from(temp).project(PlaceElem::UnwrapUnsafeBinder(expr.ty)))
546            }
547
548            ExprKind::Array { .. }
549            | ExprKind::Tuple { .. }
550            | ExprKind::Adt { .. }
551            | ExprKind::Closure { .. }
552            | ExprKind::Unary { .. }
553            | ExprKind::Binary { .. }
554            | ExprKind::LogicalOp { .. }
555            | ExprKind::Cast { .. }
556            | ExprKind::ValueExpr { .. }
557            | ExprKind::NeverToAny { .. }
558            | ExprKind::PointerCoercion { .. }
559            | ExprKind::Repeat { .. }
560            | ExprKind::Borrow { .. }
561            | ExprKind::RawBorrow { .. }
562            | ExprKind::Match { .. }
563            | ExprKind::If { .. }
564            | ExprKind::Loop { .. }
565            | ExprKind::LoopMatch { .. }
566            | ExprKind::Block { .. }
567            | ExprKind::Let { .. }
568            | ExprKind::Assign { .. }
569            | ExprKind::AssignOp { .. }
570            | ExprKind::Break { .. }
571            | ExprKind::Continue { .. }
572            | ExprKind::ConstContinue { .. }
573            | ExprKind::Return { .. }
574            | ExprKind::Become { .. }
575            | ExprKind::Literal { .. }
576            | ExprKind::NamedConst { .. }
577            | ExprKind::NonHirLiteral { .. }
578            | ExprKind::ZstLiteral { .. }
579            | ExprKind::ConstParam { .. }
580            | ExprKind::ConstBlock { .. }
581            | ExprKind::StaticRef { .. }
582            | ExprKind::InlineAsm { .. }
583            | ExprKind::Yield { .. }
584            | ExprKind::ThreadLocalRef(_)
585            | ExprKind::Call { .. }
586            | ExprKind::ByUse { .. }
587            // A reborrow is an rvalue. If a place is needed for it, materialize
588            // the rvalue in a temporary instead of treating the reborrow
589            // expression itself as an assignable place.
590            | ExprKind::Reborrow { .. }
591            | ExprKind::WrapUnsafeBinder { .. } => {
592                // these are not places, so we need to make a temporary.
593                if true {
    if !!#[allow(non_exhaustive_omitted_patterns)] match Category::of(&expr.kind)
                    {
                    Some(Category::Place) => true,
                    _ => false,
                } {
        ::core::panicking::panic("assertion failed: !matches!(Category::of(&expr.kind), Some(Category::Place))")
    };
};debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
594                let temp_lifetime = this.region_scope_tree.temporary_scope(expr.temp_scope_id);
595                let temp = {
    let BlockAnd(b, v) =
        this.as_temp(block, temp_lifetime, expr_id, mutability);
    block = b;
    v
}unpack!(block = this.as_temp(block, temp_lifetime, expr_id, mutability));
596                block.and(PlaceBuilder::from(temp))
597            }
598        }
599    }
600
601    /// Lower a captured upvar. Note we might not know the actual capture index,
602    /// so we create a place starting from `PlaceBase::Upvar`, which will be resolved
603    /// once all projections that allow us to identify a capture have been applied.
604    fn lower_captured_upvar(
605        &mut self,
606        block: BasicBlock,
607        closure_def_id: LocalDefId,
608        var_hir_id: LocalVarId,
609    ) -> BlockAnd<PlaceBuilder<'tcx>> {
610        block.and(PlaceBuilder::from(PlaceBase::Upvar { var_hir_id, closure_def_id }))
611    }
612
613    /// Lower an index expression
614    ///
615    /// This has two complications;
616    ///
617    /// * We need to do a bounds check.
618    /// * We need to ensure that the bounds check can't be invalidated using an
619    ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
620    ///   that this is the case.
621    fn lower_index_expression(
622        &mut self,
623        mut block: BasicBlock,
624        base: ExprId,
625        index: ExprId,
626        mutability: Mutability,
627        fake_borrow_temps: Option<&mut Vec<Local>>,
628        expr_span: Span,
629        source_info: SourceInfo,
630    ) -> BlockAnd<PlaceBuilder<'tcx>> {
631        let base_fake_borrow_temps = &mut Vec::new();
632        let is_outermost_index = fake_borrow_temps.is_none();
633        let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
634
635        let base_place =
636            {
    let BlockAnd(b, v) =
        self.expr_as_place(block, base, mutability, Some(fake_borrow_temps));
    block = b;
    v
}unpack!(block = self.expr_as_place(block, base, mutability, Some(fake_borrow_temps),));
637
638        // Making this a *fresh* temporary means we do not have to worry about
639        // the index changing later: Nothing will ever change this temporary.
640        // The "retagging" transformation (for Stacked Borrows) relies on this.
641        // Using the enclosing temporary scope for the index ensures it will live past where this
642        // place is used. This lifetime may be larger than strictly necessary but it means we don't
643        // need to pass a scope for operands to `as_place`.
644        let index_lifetime = self.region_scope_tree.temporary_scope(self.thir[index].temp_scope_id);
645        let idx = {
    let BlockAnd(b, v) =
        self.as_temp(block, index_lifetime, index, Mutability::Not);
    block = b;
    v
}unpack!(block = self.as_temp(block, index_lifetime, index, Mutability::Not));
646
647        block = self.bounds_check(block, &base_place, idx, expr_span, source_info);
648
649        if is_outermost_index {
650            self.read_fake_borrows(block, fake_borrow_temps, source_info)
651        } else {
652            self.add_fake_borrows_of_base(
653                base_place.to_place(self),
654                block,
655                fake_borrow_temps,
656                expr_span,
657                source_info,
658            );
659        }
660
661        block.and(base_place.index(idx))
662    }
663
664    /// Given a place that's either an array or a slice, returns an operand
665    /// with the length of the array/slice.
666    ///
667    /// For arrays it'll be `Operand::Constant` with the actual length;
668    /// For slices it'll be `Operand::Move` of a local using `PtrMetadata`.
669    pub(in crate::builder) fn len_of_slice_or_array(
670        &mut self,
671        block: BasicBlock,
672        place: Place<'tcx>,
673        span: Span,
674        source_info: SourceInfo,
675    ) -> Operand<'tcx> {
676        let place_ty = place.ty(&self.local_decls, self.tcx).ty;
677        match place_ty.kind() {
678            ty::Array(_elem_ty, len_const) => {
679                // We know how long an array is, so just use that as a constant
680                // directly -- no locals needed. We do need one statement so
681                // that borrow- and initialization-checking consider it used,
682                // though. FIXME: Do we really *need* to count this as a use?
683                // Could partial array tracking work off something else instead?
684                self.cfg.push_fake_read(block, source_info, FakeReadCause::ForIndex, place);
685                let const_ = Const::Ty(self.tcx.types.usize, *len_const);
686                Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
687            }
688            ty::Slice(_elem_ty) => {
689                let ptr_or_ref = if let [PlaceElem::Deref] = place.projection[..]
690                    && let local_ty = self.local_decls[place.local].ty
691                    && local_ty.is_trivially_pure_clone_copy()
692                {
693                    // It's extremely common that we have something that can be
694                    // directly passed to `PtrMetadata`, so avoid an unnecessary
695                    // temporary and statement in those cases. Note that we can
696                    // only do that for `Copy` types -- not `&mut [_]` -- because
697                    // the MIR we're building here needs to pass NLL later.
698                    Operand::Copy(Place::from(place.local))
699                } else {
700                    let ptr_ty = Ty::new_imm_ptr(self.tcx, place_ty);
701                    let slice_ptr = self.temp(ptr_ty, span);
702                    self.cfg.push_assign(
703                        block,
704                        source_info,
705                        slice_ptr,
706                        Rvalue::RawPtr(RawPtrKind::FakeForPtrMetadata, place),
707                    );
708                    Operand::Move(slice_ptr)
709                };
710
711                let len = self.temp(self.tcx.types.usize, span);
712                self.cfg.push_assign(
713                    block,
714                    source_info,
715                    len,
716                    Rvalue::UnaryOp(UnOp::PtrMetadata, ptr_or_ref),
717                );
718
719                Operand::Move(len)
720            }
721            _ => {
722                bug_impl(Some(span),
    format_args!("len called on place of type {0:?}", place_ty),
    Location::caller())span_bug!(span, "len called on place of type {place_ty:?}")
723            }
724        }
725    }
726
727    fn bounds_check(
728        &mut self,
729        block: BasicBlock,
730        slice: &PlaceBuilder<'tcx>,
731        index: Local,
732        expr_span: Span,
733        source_info: SourceInfo,
734    ) -> BasicBlock {
735        let slice = slice.to_place(self);
736
737        // len = len(slice)
738        let len = self.len_of_slice_or_array(block, slice, expr_span, source_info);
739
740        // lt = idx < len
741        let bool_ty = self.tcx.types.bool;
742        let lt = self.temp(bool_ty, expr_span);
743        self.cfg.push_assign(
744            block,
745            source_info,
746            lt,
747            Rvalue::BinaryOp(
748                BinOp::Lt,
749                Box::new((Operand::Copy(Place::from(index)), len.to_copy())),
750            ),
751        );
752        let msg = BoundsCheck { len, index: Operand::Copy(Place::from(index)) };
753
754        // assert!(lt, "...")
755        self.assert(block, Operand::Move(lt), true, msg, expr_span)
756    }
757
758    fn add_fake_borrows_of_base(
759        &mut self,
760        base_place: Place<'tcx>,
761        block: BasicBlock,
762        fake_borrow_temps: &mut Vec<Local>,
763        expr_span: Span,
764        source_info: SourceInfo,
765    ) {
766        let tcx = self.tcx;
767
768        let place_ty = base_place.ty(&self.local_decls, tcx);
769        if let ty::Slice(_) = place_ty.ty.kind() {
770            // We need to create fake borrows to ensure that the bounds
771            // check that we just did stays valid. Since we can't assign to
772            // unsized values, we only need to ensure that none of the
773            // pointers in the base place are modified.
774            for (base_place, elem) in base_place.iter_projections().rev() {
775                match elem {
776                    ProjectionElem::Deref => {
777                        let fake_borrow_deref_ty = base_place.ty(&self.local_decls, tcx).ty;
778                        let fake_borrow_ty =
779                            Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, fake_borrow_deref_ty);
780                        let fake_borrow_temp =
781                            self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
782                        let projection = tcx.mk_place_elems(base_place.projection);
783                        self.cfg.push_assign(
784                            block,
785                            source_info,
786                            fake_borrow_temp.into(),
787                            Rvalue::Ref(
788                                tcx.lifetimes.re_erased,
789                                BorrowKind::Fake(FakeBorrowKind::Shallow),
790                                Place { local: base_place.local, projection },
791                            ),
792                        );
793                        fake_borrow_temps.push(fake_borrow_temp);
794                    }
795                    ProjectionElem::Index(_) => {
796                        let index_ty = base_place.ty(&self.local_decls, tcx);
797                        match index_ty.ty.kind() {
798                            // The previous index expression has already
799                            // done any index expressions needed here.
800                            ty::Slice(_) => break,
801                            ty::Array(..) => (),
802                            _ => bug_impl(None, format_args!("unexpected index base"), Location::caller())bug!("unexpected index base"),
803                        }
804                    }
805                    ProjectionElem::Field(..)
806                    | ProjectionElem::PhantomDeref
807                    | ProjectionElem::Downcast(..)
808                    | ProjectionElem::OpaqueCast(..)
809                    | ProjectionElem::ConstantIndex { .. }
810                    | ProjectionElem::Subslice { .. }
811                    | ProjectionElem::UnwrapUnsafeBinder(_) => (),
812                }
813            }
814        }
815    }
816
817    fn read_fake_borrows(
818        &mut self,
819        bb: BasicBlock,
820        fake_borrow_temps: &mut Vec<Local>,
821        source_info: SourceInfo,
822    ) {
823        // All indexes have been evaluated now, read all of the
824        // fake borrows so that they are live across those index
825        // expressions.
826        for temp in fake_borrow_temps {
827            self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
828        }
829    }
830}
831
832/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
833fn enable_precise_capture(closure_span: Span) -> bool {
834    closure_span.at_least_rust_2021()
835}