Skip to main content

rustc_borrowck/
lib.rs

1//! This crate implemens MIR typeck and MIR borrowck.
2
3// tidy-alphabetical-start
4#![allow(internal_features)]
5#![feature(default_field_values)]
6#![feature(deref_patterns)]
7#![feature(file_buffered)]
8#![feature(negative_impls)]
9#![feature(option_into_flat_iter)]
10#![feature(rustc_attrs)]
11#![feature(stmt_expr_attributes)]
12#![feature(try_blocks)]
13// tidy-alphabetical-end
14
15use std::borrow::Cow;
16use std::cell::{OnceCell, RefCell};
17use std::marker::PhantomData;
18use std::ops::{ControlFlow, Deref};
19use std::rc::Rc;
20
21use borrow_set::LocalsStateAtExit;
22use polonius_engine::AllFacts;
23use root_cx::BorrowCheckRootCtxt;
24use rustc_abi::FieldIdx;
25use rustc_data_structures::frozen::Frozen;
26use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
27use rustc_data_structures::graph::dominators::Dominators;
28use rustc_hir as hir;
29use rustc_hir::CRATE_HIR_ID;
30use rustc_hir::def_id::LocalDefId;
31use rustc_index::bit_set::MixedBitSet;
32use rustc_index::{IndexSlice, IndexVec};
33use rustc_infer::infer::outlives::env::RegionBoundPairs;
34use rustc_infer::infer::{
35    InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt,
36};
37use rustc_lint_defs::builtin::{TAIL_EXPR_DROP_ORDER, UNUSED_MUT};
38use rustc_middle::mir::*;
39use rustc_middle::query::Providers;
40use rustc_middle::ty::{
41    self, ParamEnv, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypingMode, fold_regions,
42};
43use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces};
44use rustc_mir_dataflow::move_paths::{
45    InitIndex, InitLocation, LookupResult, MoveData, MovePathIndex,
46};
47use rustc_mir_dataflow::points::DenseLocationMap;
48use rustc_mir_dataflow::{Analysis, EntryStates, Results, ResultsVisitor, visit_results};
49use rustc_span::{ErrorGuaranteed, Span, Symbol, bug, span_bug};
50use rustc_trait_selection::traits::query::type_op::{QueryTypeOp, TypeOp, TypeOpOutput};
51use smallvec::SmallVec;
52use tracing::{debug, instrument};
53
54use crate::borrow_set::{BorrowData, BorrowSet};
55use crate::consumers::{BodyWithBorrowckFacts, RustcFacts};
56use crate::dataflow::{BorrowIndex, Borrowck, BorrowckDomain, Borrows};
57use crate::diagnostics::{
58    AccessKind, BorrowckDiagnosticsBuffer, IllegalMoveOriginKind, MoveError, RegionName,
59};
60use crate::implied_bounds::mir_borrowck_implied_outlives_bounds;
61use crate::path_utils::*;
62use crate::place_ext::PlaceExt;
63use crate::places_conflict::{PlaceConflictBias, places_conflict};
64use crate::polonius::PoloniusContext;
65use crate::polonius::legacy::{
66    PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput,
67};
68use crate::prefixes::PrefixSet;
69use crate::region_infer::RegionInferenceContext;
70use crate::region_infer::opaque_types::DeferredOpaqueTypeError;
71use crate::renumber::RegionCtxt;
72use crate::session_diagnostics::VarNeedNotMut;
73use crate::type_check::free_region_relations::UniversalRegionRelations;
74use crate::type_check::{Locations, MirTypeckRegionConstraints, MirTypeckResults};
75
76mod borrow_set;
77mod borrowck_errors;
78mod constraints;
79mod dataflow;
80mod def_use;
81mod diagnostics;
82mod handle_placeholders;
83mod implied_bounds;
84mod nll;
85mod path_utils;
86mod place_ext;
87mod places_conflict;
88mod polonius;
89mod prefixes;
90mod region_infer;
91mod renumber;
92mod root_cx;
93mod session_diagnostics;
94mod type_check;
95mod universal_regions;
96mod used_muts;
97
98/// A public API provided for the Rust compiler consumers.
99pub mod consumers;
100
101/// Associate some local constants with the `'tcx` lifetime
102struct TyCtxtConsts<'tcx>(PhantomData<&'tcx ()>);
103
104impl<'tcx> TyCtxtConsts<'tcx> {
105    const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
106}
107
108pub fn provide(providers: &mut Providers) {
109    *providers = Providers { mir_borrowck, mir_borrowck_implied_outlives_bounds, ..*providers };
110}
111
112/// Provider for `query mir_borrowck`. Unlike `typeck`, this must
113/// only be called for typeck roots which *similar* to `typeck` will
114/// then borrowck all nested bodies as well.
115fn mir_borrowck(
116    tcx: TyCtxt<'_>,
117    def: LocalDefId,
118) -> Result<&FxIndexMap<LocalDefId, ty::DefinitionSiteHiddenType<'_>>, ErrorGuaranteed> {
119    if !!tcx.is_typeck_child(def.to_def_id()) {
    ::core::panicking::panic("assertion failed: !tcx.is_typeck_child(def.to_def_id())")
};assert!(!tcx.is_typeck_child(def.to_def_id()));
120    if tcx.is_trivial_const(def) {
121        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:121",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(121u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("Skipping borrowck because of trivial const")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Skipping borrowck because of trivial const");
122        let opaque_types = Default::default();
123        return Ok(tcx.arena.alloc(opaque_types));
124    }
125    let (input_body, _) = tcx.mir_promoted(def);
126    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:126",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(126u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("run query mir_borrowck: {0}",
                                                    tcx.def_path_str(def)) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("run query mir_borrowck: {}", tcx.def_path_str(def));
127
128    // We should eagerly check stalled coroutine obligations from HIR typeck.
129    // Not doing so leads to silent normalization failures later, which will
130    // fail to register opaque types in the next solver.
131    tcx.ensure_result().check_coroutine_obligations(def)?;
132
133    let input_body: &Body<'_> = &input_body.borrow();
134    if let Some(guar) = input_body.tainted_by_errors {
135        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:135",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(135u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("Skipping borrowck because of tainted body")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Skipping borrowck because of tainted body");
136        Err(guar)
137    } else if input_body.should_skip() {
138        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:138",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(138u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("Skipping borrowck because of injected body")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Skipping borrowck because of injected body");
139        let opaque_types = Default::default();
140        Ok(tcx.arena.alloc(opaque_types))
141    } else {
142        let tainted_by_errors = Default::default();
143        let mut root_cx = BorrowCheckRootCtxt::new(tcx, def, None, &tainted_by_errors);
144        root_cx.do_mir_borrowck();
145        root_cx.finalize()
146    }
147}
148
149/// Data propagated to the typeck parent by nested items.
150/// This should always be empty for the typeck root.
151#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PropagatedBorrowCheckResults<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "PropagatedBorrowCheckResults", "closure_requirements",
            &self.closure_requirements, "used_mut_upvars",
            &&self.used_mut_upvars)
    }
}Debug)]
152struct PropagatedBorrowCheckResults<'tcx> {
153    closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
154    used_mut_upvars: SmallVec<[FieldIdx; 8]>,
155}
156
157type DeferredClosureRequirements<'tcx> = Vec<(LocalDefId, ty::GenericArgsRef<'tcx>, Locations)>;
158
159/// After we borrow check a closure, we are left with various
160/// requirements that we have inferred between the free regions that
161/// appear in the closure's signature or on its field types. These
162/// requirements are then verified and proved by the closure's
163/// creating function. This struct encodes those requirements.
164///
165/// The requirements are listed as being between various `RegionVid`. The 0th
166/// region refers to `'static`; subsequent region vids refer to the free
167/// regions that appear in the closure (or coroutine's) type, in order of
168/// appearance. (This numbering is actually defined by the `UniversalRegions`
169/// struct in the NLL region checker. See for example
170/// `UniversalRegions::closure_mapping`.) Note the free regions in the
171/// closure's signature and captures are erased.
172///
173/// Example: If type check produces a closure with the closure args:
174///
175/// ```text
176/// ClosureArgs = [
177///     'a,                                         // From the parent.
178///     'b,
179///     i8,                                         // the "closure kind"
180///     for<'x> fn(&'<erased> &'x u32) -> &'x u32,  // the "closure signature"
181///     &'<erased> String,                          // some upvar
182/// ]
183/// ```
184///
185/// We would "renumber" each free region to a unique vid, as follows:
186///
187/// ```text
188/// ClosureArgs = [
189///     '1,                                         // From the parent.
190///     '2,
191///     i8,                                         // the "closure kind"
192///     for<'x> fn(&'3 &'x u32) -> &'x u32,         // the "closure signature"
193///     &'4 String,                                 // some upvar
194/// ]
195/// ```
196///
197/// Now the code might impose a requirement like `'1: '2`. When an
198/// instance of the closure is created, the corresponding free regions
199/// can be extracted from its type and constrained to have the given
200/// outlives relationship.
201#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureRegionRequirements<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        ClosureRegionRequirements {
            num_external_vids: ::core::clone::Clone::clone(&self.num_external_vids),
            outlives_requirements: ::core::clone::Clone::clone(&self.outlives_requirements),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureRegionRequirements<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ClosureRegionRequirements", "num_external_vids",
            &self.num_external_vids, "outlives_requirements",
            &&self.outlives_requirements)
    }
}Debug)]
202pub struct ClosureRegionRequirements<'tcx> {
203    /// The number of external regions defined on the closure. In our
204    /// example above, it would be 3 -- one for `'static`, then `'1`
205    /// and `'2`. This is just used for a sanity check later on, to
206    /// make sure that the number of regions we see at the callsite
207    /// matches.
208    pub num_external_vids: usize,
209
210    /// Requirements between the various free regions defined in
211    /// indices.
212    pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
213}
214
215/// Indicates an outlives-constraint between a type or between two
216/// free regions declared on the closure.
217#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesRequirement<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for
    ClosureOutlivesRequirement<'tcx> {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesRequirement<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<ClosureOutlivesSubject<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ty::RegionVid>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<ConstraintCategory<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureOutlivesRequirement<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ClosureOutlivesRequirement", "subject", &self.subject,
            "outlived_free_region", &self.outlived_free_region, "blame_span",
            &self.blame_span, "category", &&self.category)
    }
}Debug)]
218pub struct ClosureOutlivesRequirement<'tcx> {
219    // This region or type ...
220    pub subject: ClosureOutlivesSubject<'tcx>,
221
222    // ... must outlive this one.
223    pub outlived_free_region: ty::RegionVid,
224
225    // If not, report an error here ...
226    pub blame_span: Span,
227
228    // ... due to this reason.
229    pub category: ConstraintCategory<'tcx>,
230}
231
232// Make sure this enum doesn't unintentionally grow
233#[cfg(target_pointer_width = "64")]
234const _: [(); 24] = [(); ::std::mem::size_of::<ConstraintCategory<'_>>()];rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 24);
235
236/// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
237/// that must outlive some region.
238#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesSubject<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ClosureOutlivesSubject<'tcx>
    {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesSubject<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<ClosureOutlivesSubjectTy<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ty::RegionVid>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureOutlivesSubject<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Ty(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
                    &__self_0),
            Self::Region(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Region",
                    &__self_0),
        }
    }
}Debug)]
239pub enum ClosureOutlivesSubject<'tcx> {
240    /// Subject is a type, typically a type parameter, but could also
241    /// be a projection. Indicates a requirement like `T: 'a` being
242    /// passed to the caller, where the type here is `T`.
243    Ty(ClosureOutlivesSubjectTy<'tcx>),
244
245    /// Subject is a free region from the closure. Indicates a requirement
246    /// like `'a: 'b` being passed to the caller; the region here is `'a`.
247    Region(ty::RegionVid),
248}
249
250/// Represents a `ty::Ty` for use in [`ClosureOutlivesSubject`].
251///
252/// This abstraction is necessary because the type may include `ReVar` regions,
253/// which is what we use internally within NLL code, and they can't be used in
254/// a query response.
255#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesSubjectTy<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for
    ClosureOutlivesSubjectTy<'tcx> {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesSubjectTy<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureOutlivesSubjectTy<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "ClosureOutlivesSubjectTy", "inner", &&self.inner)
    }
}Debug)]
256pub struct ClosureOutlivesSubjectTy<'tcx> {
257    inner: Ty<'tcx>,
258}
259// DO NOT implement `TypeVisitable` or `TypeFoldable` traits, because this
260// type is not recognized as a binder for late-bound region.
261impl<'tcx, I> !TypeVisitable<I> for ClosureOutlivesSubjectTy<'tcx> {}
262impl<'tcx, I> !TypeFoldable<I> for ClosureOutlivesSubjectTy<'tcx> {}
263
264impl<'tcx> ClosureOutlivesSubjectTy<'tcx> {
265    /// All regions of `ty` must be of kind `ReVar` and must represent
266    /// universal regions *external* to the closure.
267    pub fn bind(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
268        let inner = fold_regions(tcx, ty, |r, depth| match r.kind() {
269            ty::ReVar(vid) => {
270                let br = ty::BoundRegion {
271                    var: ty::BoundVar::from_usize(vid.index()),
272                    kind: ty::BoundRegionKind::Anon,
273                };
274                ty::Region::new_bound(tcx, depth, br)
275            }
276            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected region in ClosureOutlivesSubjectTy: {0:?}", r),
    Location::caller())bug!("unexpected region in ClosureOutlivesSubjectTy: {r:?}"),
277        });
278
279        Self { inner }
280    }
281
282    pub fn instantiate(
283        self,
284        tcx: TyCtxt<'tcx>,
285        mut map: impl FnMut(ty::RegionVid) -> ty::Region<'tcx>,
286    ) -> Ty<'tcx> {
287        fold_regions(tcx, self.inner, |r, depth| match r.kind() {
288            ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), br) => {
289                if true {
    {
        match (&debruijn, &depth) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(debruijn, depth);
290                map(ty::RegionVid::from_usize(br.var.index()))
291            }
292            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected region {0:?}", r), Location::caller())bug!("unexpected region {r:?}"),
293        })
294    }
295}
296
297struct CollectRegionConstraintsResult<'tcx> {
298    infcx: BorrowckInferCtxt<'tcx>,
299    body_owned: Body<'tcx>,
300    promoted: IndexVec<Promoted, Body<'tcx>>,
301    move_data: MoveData<'tcx>,
302    borrow_set: BorrowSet<'tcx>,
303    location_table: PoloniusLocationTable,
304    location_map: Rc<DenseLocationMap>,
305    universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
306    region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
307    known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesClause<'tcx>>>,
308    constraints: MirTypeckRegionConstraints<'tcx>,
309    deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
310    deferred_opaque_type_errors: Vec<DeferredOpaqueTypeError<'tcx>>,
311    polonius_facts: Option<AllFacts<RustcFacts>>,
312    polonius_context: Option<PoloniusContext<'tcx>>,
313}
314
315/// Start borrow checking by collecting the region constraints for
316/// the current body. This initializes the relevant data structures
317/// and then type checks the MIR body.
318fn borrowck_collect_region_constraints<'tcx>(
319    root_cx: &mut BorrowCheckRootCtxt<'_, 'tcx>,
320    def: LocalDefId,
321) -> CollectRegionConstraintsResult<'tcx> {
322    let tcx = root_cx.tcx;
323    let infcx = BorrowckInferCtxt::new(tcx, def, root_cx.root_def_id());
324    let (input_body, promoted) = tcx.mir_promoted(def);
325    let input_body: &Body<'_> = &input_body.borrow();
326    let input_promoted: &IndexSlice<_, _> = &promoted.borrow();
327    if let Some(e) = input_body.tainted_by_errors {
328        infcx.set_tainted_by_errors(e);
329    }
330
331    // Replace all regions with fresh inference variables. This
332    // requires first making our own copy of the MIR. This copy will
333    // be modified (in place) to contain non-lexical lifetimes. It
334    // will have a lifetime tied to the inference context.
335    let mut body_owned = input_body.clone();
336    let mut promoted = input_promoted.to_owned();
337    let universal_regions = nll::replace_regions_in_mir(&infcx, &mut body_owned, &mut promoted);
338    let body = &body_owned; // no further changes
339
340    let location_table = PoloniusLocationTable::new(body);
341
342    let move_data = MoveData::gather_moves(body, tcx, |_| true);
343
344    let locals_are_invalidated_at_exit = tcx.hir_body_owner_kind(def).is_fn_or_closure();
345    let borrow_set = BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &move_data);
346
347    let location_map = Rc::new(DenseLocationMap::new(body));
348
349    let polonius_input = root_cx.consumer.as_ref().is_some_and(|c| c.polonius_input())
350        || infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
351    let mut polonius_facts =
352        (polonius_input || PoloniusFacts::enabled(infcx.tcx)).then_some(PoloniusFacts::default());
353
354    // Run the MIR type-checker.
355    let MirTypeckResults {
356        constraints,
357        universal_region_relations,
358        region_bound_pairs,
359        known_type_outlives_obligations,
360        deferred_closure_requirements,
361        polonius_context,
362    } = type_check::type_check(
363        &infcx,
364        body,
365        &promoted,
366        universal_regions,
367        &location_table,
368        &borrow_set,
369        &mut polonius_facts,
370        &move_data,
371        Rc::clone(&location_map),
372    );
373
374    CollectRegionConstraintsResult {
375        infcx,
376        body_owned,
377        promoted,
378        move_data,
379        borrow_set,
380        location_table,
381        location_map,
382        universal_region_relations,
383        region_bound_pairs,
384        known_type_outlives_obligations,
385        constraints,
386        deferred_closure_requirements,
387        deferred_opaque_type_errors: Default::default(),
388        polonius_facts,
389        polonius_context,
390    }
391}
392
393/// Using the region constraints computed by [borrowck_collect_region_constraints]
394/// and the additional constraints from [BorrowCheckRootCtxt::handle_opaque_type_uses],
395/// compute the region graph and actually check for any borrowck errors.
396fn borrowck_check_region_constraints<'diag, 'tcx>(
397    root_cx: &mut BorrowCheckRootCtxt<'diag, 'tcx>,
398    diags_buffer: &mut BorrowckDiagnosticsBuffer<'diag, 'tcx>,
399    CollectRegionConstraintsResult {
400        infcx,
401        body_owned,
402        promoted,
403        move_data,
404        borrow_set,
405        location_table,
406        location_map,
407        universal_region_relations,
408        region_bound_pairs: _,
409        known_type_outlives_obligations: _,
410        constraints,
411        deferred_closure_requirements,
412        deferred_opaque_type_errors,
413        polonius_facts,
414        polonius_context,
415    }: CollectRegionConstraintsResult<'tcx>,
416) -> PropagatedBorrowCheckResults<'tcx> {
417    if !!infcx.has_opaque_types_in_storage() {
    ::core::panicking::panic("assertion failed: !infcx.has_opaque_types_in_storage()")
};assert!(!infcx.has_opaque_types_in_storage());
418    if !deferred_closure_requirements.is_empty() {
    ::core::panicking::panic("assertion failed: deferred_closure_requirements.is_empty()")
};assert!(deferred_closure_requirements.is_empty());
419    let tcx = root_cx.tcx;
420    let body = &body_owned;
421    let def = body.source.def_id().expect_local();
422
423    // Compute non-lexical lifetimes using the constraints computed
424    // by typechecking the MIR body.
425    let nll::NllOutput {
426        regioncx,
427        polonius_input,
428        polonius_output,
429        opt_closure_req,
430        nll_errors,
431        polonius_context,
432    } = nll::compute_regions(
433        root_cx,
434        &infcx,
435        body,
436        &location_table,
437        &move_data,
438        &borrow_set,
439        location_map,
440        universal_region_relations,
441        constraints,
442        polonius_facts,
443        polonius_context,
444    );
445
446    // Dump MIR results into a file, if that is enabled. This lets us
447    // write unit-tests, as well as helping with debugging.
448    nll::dump_nll_mir(&infcx, body, &regioncx, &opt_closure_req, &borrow_set);
449    polonius::dump_polonius_mir(
450        &infcx,
451        body,
452        &regioncx,
453        &opt_closure_req,
454        &borrow_set,
455        polonius_context.as_ref(),
456    );
457
458    // We also have a `#[rustc_regions]` annotation that causes us to dump
459    // information.
460    nll::dump_annotation(&infcx, body, &regioncx, &opt_closure_req);
461
462    let movable_coroutine = body.coroutine.is_some()
463        && tcx.coroutine_movability(def.to_def_id()) == hir::Movability::Movable;
464
465    // While promoteds should mostly be correct by construction, we need to check them for
466    // invalid moves to detect moving out of arrays:`struct S; fn main() { &([S][0]); }`.
467    for promoted_body in &promoted {
468        use rustc_middle::mir::visit::Visitor;
469        // This assumes that we won't use some of the fields of the `promoted_mbcx`
470        // when detecting and reporting move errors. While it would be nice to move
471        // this check out of `MirBorrowckCtxt`, actually doing so is far from trivial.
472        let move_data = MoveData::gather_moves(promoted_body, tcx, |_| true);
473        let mut promoted_mbcx = MirBorrowckCtxt {
474            root_cx,
475            infcx: &infcx,
476            body: promoted_body,
477            move_data: &move_data,
478            // no need to create a real location table for the promoted, it is not used
479            location_table: &location_table,
480            movable_coroutine,
481            fn_self_span_reported: Default::default(),
482            access_place_error_reported: Default::default(),
483            reservation_error_reported: Default::default(),
484            uninitialized_error_reported: Default::default(),
485            regioncx: &regioncx,
486            used_mut: Default::default(),
487            used_mut_upvars: SmallVec::new(),
488            borrow_set: &borrow_set,
489            upvars: &[],
490            local_names: OnceCell::from(IndexVec::from_elem(None, &promoted_body.local_decls)),
491            region_names: RefCell::default(),
492            next_region_name: RefCell::new(1),
493            polonius_output: None,
494            move_errors: Vec::new(),
495            diags_buffer,
496            polonius_context: polonius_context.as_ref(),
497        };
498        struct MoveVisitor<'a, 'b, 'diag, 'tcx> {
499            ctxt: &'a mut MirBorrowckCtxt<'b, 'diag, 'tcx>,
500        }
501
502        impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, '_, 'tcx> {
503            fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
504                if let Operand::Move(place) = operand {
505                    self.ctxt.check_movable_place(location, *place);
506                }
507            }
508        }
509        MoveVisitor { ctxt: &mut promoted_mbcx }.visit_body(promoted_body);
510        promoted_mbcx.report_move_errors();
511    }
512
513    let mut mbcx = MirBorrowckCtxt {
514        root_cx,
515        infcx: &infcx,
516        body,
517        move_data: &move_data,
518        location_table: &location_table,
519        movable_coroutine,
520        fn_self_span_reported: Default::default(),
521        access_place_error_reported: Default::default(),
522        reservation_error_reported: Default::default(),
523        uninitialized_error_reported: Default::default(),
524        regioncx: &regioncx,
525        used_mut: Default::default(),
526        used_mut_upvars: SmallVec::new(),
527        borrow_set: &borrow_set,
528        upvars: tcx.closure_captures(def),
529        local_names: OnceCell::new(),
530        region_names: RefCell::default(),
531        next_region_name: RefCell::new(1),
532        move_errors: Vec::new(),
533        diags_buffer,
534        polonius_output: polonius_output.as_deref(),
535        polonius_context: polonius_context.as_ref(),
536    };
537
538    // Compute and report region errors, if any.
539    if nll_errors.is_empty() {
540        mbcx.report_opaque_type_errors(deferred_opaque_type_errors);
541    } else {
542        mbcx.report_region_errors(nll_errors);
543    }
544
545    let flow_results = get_flow_results(tcx, body, &move_data, &borrow_set, &regioncx);
546    visit_results(
547        body,
548        traversal::reverse_postorder(body).map(|(bb, _)| bb),
549        &flow_results,
550        &mut mbcx,
551    );
552
553    mbcx.report_move_errors();
554
555    // For each non-user used mutable variable, check if it's been assigned from
556    // a user-declared local. If so, then put that local into the used_mut set.
557    // Note that this set is expected to be small - only upvars from closures
558    // would have a chance of erroneously adding non-user-defined mutable vars
559    // to the set.
560    let temporary_used_locals: FxIndexSet<Local> = mbcx
561        .used_mut
562        .iter()
563        .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
564        .cloned()
565        .collect();
566    // For the remaining unused locals that are marked as mutable, we avoid linting any that
567    // were never initialized. These locals may have been removed as unreachable code; or will be
568    // linted as unused variables.
569    let unused_mut_locals =
570        mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
571    mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
572
573    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:573",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(573u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("mbcx.used_mut: {0:?}",
                                                    mbcx.used_mut) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
574    mbcx.lint_unused_mut();
575
576    let result = PropagatedBorrowCheckResults {
577        closure_requirements: opt_closure_req,
578        used_mut_upvars: mbcx.used_mut_upvars,
579    };
580
581    if let Some(guar) = infcx.tainted_by_errors() {
582        root_cx.set_tainted_by_errors(guar);
583    }
584
585    if let Some(consumer) = &mut root_cx.consumer {
586        consumer.insert_body(
587            def,
588            BodyWithBorrowckFacts {
589                body: body_owned,
590                promoted,
591                borrow_set,
592                region_inference_context: regioncx,
593                location_table: polonius_input.as_ref().map(|_| location_table),
594                input_facts: polonius_input,
595                output_facts: polonius_output,
596            },
597        );
598    }
599
600    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:600",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(600u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("do_mir_borrowck: result = {0:#?}",
                                                    result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("do_mir_borrowck: result = {:#?}", result);
601
602    result
603}
604
605fn get_flow_results<'a, 'tcx>(
606    tcx: TyCtxt<'tcx>,
607    body: &'a Body<'tcx>,
608    move_data: &'a MoveData<'tcx>,
609    borrow_set: &'a BorrowSet<'tcx>,
610    regioncx: &RegionInferenceContext<'tcx>,
611) -> Results<'tcx, Borrowck<'a, 'tcx>> {
612    // We compute these three analyses individually, but them combine them into
613    // a single results so that `mbcx` can visit them all together.
614    let borrows = {
615        let _timer = tcx.prof.generic_activity("borrowck_dataflow_borrows");
616        Borrows::new(tcx, body, regioncx, borrow_set).iterate_to_fixpoint(
617            tcx,
618            body,
619            Some("borrowck"),
620        )
621    };
622    let uninits = {
623        let _timer = tcx.prof.generic_activity("borrowck_dataflow_maybe_uninits");
624        MaybeUninitializedPlaces::new(tcx, body, move_data).iterate_to_fixpoint(
625            tcx,
626            body,
627            Some("borrowck"),
628        )
629    };
630    let ever_inits = {
631        let _timer = tcx.prof.generic_activity("borrowck_dataflow_ever_inits");
632        EverInitializedPlaces::new(body, move_data).iterate_to_fixpoint(tcx, body, Some("borrowck"))
633    };
634
635    let analysis = Borrowck {
636        borrows: borrows.analysis,
637        uninits: uninits.analysis,
638        ever_inits: ever_inits.analysis,
639    };
640
641    {
    match (&borrows.entry_states.len(), &uninits.entry_states.len()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(borrows.entry_states.len(), uninits.entry_states.len());
642    {
    match (&borrows.entry_states.len(), &ever_inits.entry_states.len()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(borrows.entry_states.len(), ever_inits.entry_states.len());
643    let entry_states: EntryStates<_> =
644        ::itertools::__std_iter::Iterator::map(::itertools::__std_iter::Iterator::zip(::itertools::__std_iter::IntoIterator::into_iter(borrows.entry_states),
        ::itertools::__std_iter::Iterator::zip(::itertools::__std_iter::IntoIterator::into_iter(uninits.entry_states),
            ::itertools::__std_iter::IntoIterator::into_iter(ever_inits.entry_states))),
    |(b, (b, a))| (b, b, a))itertools::izip!(borrows.entry_states, uninits.entry_states, ever_inits.entry_states)
645            .map(|(borrows, uninits, ever_inits)| BorrowckDomain { borrows, uninits, ever_inits })
646            .collect();
647
648    Results { analysis, entry_states }
649}
650
651pub(crate) struct BorrowckInferCtxt<'tcx> {
652    pub(crate) infcx: InferCtxt<'tcx>,
653    pub(crate) root_def_id: LocalDefId,
654    pub(crate) param_env: ParamEnv<'tcx>,
655    pub(crate) reg_var_to_origin: RefCell<FxIndexMap<ty::RegionVid, RegionCtxt>>,
656}
657
658impl<'tcx> BorrowckInferCtxt<'tcx> {
659    pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, root_def_id: LocalDefId) -> Self {
660        let typing_mode = if tcx.use_typing_mode_post_typeck_until_borrowck() {
661            TypingMode::borrowck(tcx, def_id)
662        } else {
663            TypingMode::analysis_in_body(tcx, def_id)
664        };
665        let infcx = tcx.infer_ctxt().build(typing_mode);
666        let param_env = tcx.param_env(def_id);
667        BorrowckInferCtxt {
668            infcx,
669            root_def_id,
670            reg_var_to_origin: RefCell::new(Default::default()),
671            param_env,
672        }
673    }
674
675    pub(crate) fn next_region_var<F>(
676        &self,
677        origin: RegionVariableOrigin<'tcx>,
678        get_ctxt_fn: F,
679    ) -> ty::Region<'tcx>
680    where
681        F: Fn() -> RegionCtxt,
682    {
683        let next_region = self.infcx.next_region_var(origin);
684        let vid = next_region.as_var();
685
686        if truecfg!(debug_assertions) {
687            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:687",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(687u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("inserting vid {0:?} with origin {1:?} into var_to_origin",
                                                    vid, origin) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
688            let ctxt = get_ctxt_fn();
689            let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
690            {
    match (&var_to_origin.insert(vid, ctxt), &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(var_to_origin.insert(vid, ctxt), None);
691        }
692
693        next_region
694    }
695
696    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("next_nll_region_var",
                                    "rustc_borrowck", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(696u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("origin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("origin");
                                                        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::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::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(&origin)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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: ty::Region<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let next_region = self.infcx.next_nll_region_var(origin);
            let vid = next_region.as_var();
            if true {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:709",
                                        "rustc_borrowck", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                        ::tracing_core::__macro_support::Option::Some(709u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                        ::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!("inserting vid {0:?} with origin {1:?} into var_to_origin",
                                                                    vid, origin) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                let ctxt = get_ctxt_fn();
                let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
                {
                    match (&var_to_origin.insert(vid, ctxt), &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
            }
            next_region
        }
    }
}#[instrument(skip(self, get_ctxt_fn), level = "debug")]
697    pub(crate) fn next_nll_region_var<F>(
698        &self,
699        origin: NllRegionVariableOrigin<'tcx>,
700        get_ctxt_fn: F,
701    ) -> ty::Region<'tcx>
702    where
703        F: Fn() -> RegionCtxt,
704    {
705        let next_region = self.infcx.next_nll_region_var(origin);
706        let vid = next_region.as_var();
707
708        if cfg!(debug_assertions) {
709            debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
710            let ctxt = get_ctxt_fn();
711            let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
712            assert_eq!(var_to_origin.insert(vid, ctxt), None);
713        }
714
715        next_region
716    }
717
718    fn fully_perform<Q: QueryTypeOp<'tcx> + TypeVisitable<TyCtxt<'tcx>>>(
719        &self,
720        q: Q,
721        span: Span,
722    ) -> Result<TypeOpOutput<'tcx, ty::ParamEnvAnd<'tcx, Q>>, ErrorGuaranteed> {
723        self.param_env.and(q).fully_perform(&self.infcx, self.root_def_id, span)
724    }
725}
726
727impl<'tcx> Deref for BorrowckInferCtxt<'tcx> {
728    type Target = InferCtxt<'tcx>;
729
730    fn deref(&self) -> &Self::Target {
731        &self.infcx
732    }
733}
734
735pub(crate) struct MirBorrowckCtxt<'a, 'diag, 'tcx> {
736    root_cx: &'a BorrowCheckRootCtxt<'diag, 'tcx>,
737    infcx: &'a BorrowckInferCtxt<'tcx>,
738    body: &'a Body<'tcx>,
739    move_data: &'a MoveData<'tcx>,
740
741    /// Map from MIR `Location` to `LocationIndex`; created
742    /// when MIR borrowck begins.
743    location_table: &'a PoloniusLocationTable,
744
745    movable_coroutine: bool,
746    /// This field keeps track of when borrow errors are reported in the access_place function
747    /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
748    /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
749    /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
750    /// errors.
751    access_place_error_reported: FxIndexSet<(Place<'tcx>, Span)>,
752    /// This field keeps track of when borrow conflict errors are reported
753    /// for reservations, so that we don't report seemingly duplicate
754    /// errors for corresponding activations.
755    //
756    // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
757    // but it is currently inconvenient to track down the `BorrowIndex`
758    // at the time we detect and report a reservation error.
759    reservation_error_reported: FxIndexSet<Place<'tcx>>,
760    /// This fields keeps track of the `Span`s that we have
761    /// used to report extra information for `FnSelfUse`, to avoid
762    /// unnecessarily verbose errors.
763    fn_self_span_reported: FxIndexSet<Span>,
764    /// This field keeps track of errors reported in the checking of uninitialized variables,
765    /// so that we don't report seemingly duplicate errors.
766    uninitialized_error_reported: FxIndexSet<Local>,
767    /// This field keeps track of all the local variables that are declared mut and are mutated.
768    /// Used for the warning issued by an unused mutable local variable.
769    used_mut: FxIndexSet<Local>,
770    /// If the function we're checking is a closure, then we'll need to report back the list of
771    /// mutable upvars that have been used. This field keeps track of them.
772    used_mut_upvars: SmallVec<[FieldIdx; 8]>,
773    /// Region inference context. This contains the results from region inference and lets us e.g.
774    /// find out which CFG points are contained in each borrow region.
775    regioncx: &'a RegionInferenceContext<'tcx>,
776
777    /// The set of borrows extracted from the MIR
778    borrow_set: &'a BorrowSet<'tcx>,
779
780    /// Information about upvars not necessarily preserved in types or MIR
781    upvars: &'tcx [&'tcx ty::CapturedPlace<'tcx>],
782
783    /// Names of local (user) variables (extracted from `var_debug_info`).
784    local_names: OnceCell<IndexVec<Local, Option<Symbol>>>,
785
786    /// Record the region names generated for each region in the given
787    /// MIR def so that we can reuse them later in help/error messages.
788    region_names: RefCell<FxIndexMap<RegionVid, RegionName>>,
789
790    /// The counter for generating new region names.
791    next_region_name: RefCell<usize>,
792
793    diags_buffer: &'a mut BorrowckDiagnosticsBuffer<'diag, 'tcx>,
794    move_errors: Vec<MoveError<'tcx>>,
795
796    /// Results of Polonius analysis.
797    polonius_output: Option<&'a PoloniusOutput>,
798    /// When using `-Zpolonius=next`: the data used to compute errors and diagnostics.
799    polonius_context: Option<&'a PoloniusContext<'tcx>>,
800}
801
802// Check that:
803// 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
804// 2. loans made in overlapping scopes do not conflict
805// 3. assignments do not affect things loaned out as immutable
806// 4. moves do not affect things loaned out in any way
807impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
808    fn visit_after_early_statement_effect(
809        &mut self,
810        state: &BorrowckDomain,
811        stmt: &Statement<'tcx>,
812        location: Location,
813    ) {
814        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:814",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(814u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("MirBorrowckCtxt::process_statement({0:?}, {1:?}): {2:?}",
                                                    location, stmt, state) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
815        let span = stmt.source_info.span;
816
817        self.check_activations(location, span, state);
818
819        match &stmt.kind {
820            StatementKind::Assign((lhs, rhs)) => {
821                self.consume_rvalue(location, (rhs, span), state);
822
823                self.mutate_place(location, (*lhs, span), Shallow(None), state);
824            }
825            StatementKind::FakeRead((_, place)) => {
826                // Read for match doesn't access any memory and is used to
827                // assert that a place is safe and live. So we don't have to
828                // do any checks here.
829                //
830                // FIXME: Remove check that the place is initialized. This is
831                // needed for now because matches don't have never patterns yet.
832                // So this is the only place we prevent
833                //      let x: !;
834                //      match x {};
835                // from compiling.
836                self.check_if_path_or_subpath_is_moved(
837                    location,
838                    InitializationRequiringAction::Use,
839                    (place.as_ref(), span),
840                    state,
841                );
842            }
843            StatementKind::Intrinsic(kind) => match kind {
844                NonDivergingIntrinsic::Assume(op) => {
845                    self.consume_operand(location, (op, span), state);
846                }
847                NonDivergingIntrinsic::CopyNonOverlapping(..) => ::rustc_span::macros::bug_impl(Some(span),
    format_args!("Unexpected CopyNonOverlapping, should only appear after lower_intrinsics"),
    Location::caller())span_bug!(
848                    span,
849                    "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
850                ),
851            },
852            // Only relevant for mir typeck
853            StatementKind::AscribeUserType(..) => {}
854            // Only relevant for liveness and unsafeck
855            StatementKind::PlaceMention(..) => {}
856            // Doesn't have any language semantics
857            StatementKind::Coverage(..) => {}
858            // These do not actually affect borrowck
859            StatementKind::ConstEvalCounter | StatementKind::StorageLive(..) => {}
860            // This does not affect borrowck
861            StatementKind::BackwardIncompatibleDropHint {
862                place,
863                reason: BackwardIncompatibleDropReason::Edition2024,
864            } => {
865                self.check_backward_incompatible_drop(location, **place, state);
866            }
867            StatementKind::StorageDead(local) => {
868                self.access_place(
869                    location,
870                    (Place::from(*local), span),
871                    (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
872                    LocalMutationIsAllowed::Yes,
873                    state,
874                );
875            }
876            StatementKind::Nop | StatementKind::SetDiscriminant { .. } => {
877                ::rustc_span::macros::bug_impl(None,
    format_args!("Statement not allowed in this MIR phase"),
    Location::caller())bug!("Statement not allowed in this MIR phase")
878            }
879        }
880    }
881
882    fn visit_after_early_terminator_effect(
883        &mut self,
884        state: &BorrowckDomain,
885        term: &Terminator<'tcx>,
886        loc: Location,
887    ) {
888        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:888",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(888u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("MirBorrowckCtxt::process_terminator({0:?}, {1:?}): {2:?}",
                                                    loc, term, state) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
889        let span = term.source_info.span;
890
891        self.check_activations(loc, span, state);
892
893        match &term.kind {
894            TerminatorKind::SwitchInt { discr, targets: _ } => {
895                self.consume_operand(loc, (discr, span), state);
896            }
897            TerminatorKind::Drop { place, target: _, unwind: _, replace, drop: _ } => {
898                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:898",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(898u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("visit_terminator_drop loc: {0:?} term: {1:?} place: {2:?} span: {3:?}",
                                                    loc, term, place, span) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
899                    "visit_terminator_drop \
900                     loc: {:?} term: {:?} place: {:?} span: {:?}",
901                    loc, term, place, span
902                );
903
904                let write_kind =
905                    if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
906                self.access_place(
907                    loc,
908                    (*place, span),
909                    (AccessDepth::Drop, Write(write_kind)),
910                    LocalMutationIsAllowed::Yes,
911                    state,
912                );
913            }
914            TerminatorKind::Call {
915                func,
916                args,
917                destination,
918                target: _,
919                unwind: _,
920                call_source: _,
921                fn_span: _,
922            } => {
923                self.consume_operand(loc, (func, span), state);
924                for arg in args {
925                    self.consume_operand(loc, (&arg.node, arg.span), state);
926                }
927                self.mutate_place(loc, (*destination, span), Deep, state);
928            }
929            TerminatorKind::TailCall { func, args, fn_span: _ } => {
930                self.consume_operand(loc, (func, span), state);
931                for arg in args {
932                    self.consume_operand(loc, (&arg.node, arg.span), state);
933                }
934            }
935            TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
936                self.consume_operand(loc, (cond, span), state);
937                if let AssertKind::BoundsCheck { len, index } = &**msg {
938                    self.consume_operand(loc, (len, span), state);
939                    self.consume_operand(loc, (index, span), state);
940                }
941            }
942
943            TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
944                self.consume_operand(loc, (value, span), state);
945                self.mutate_place(loc, (*resume_arg, span), Deep, state);
946            }
947
948            TerminatorKind::InlineAsm {
949                asm_macro: _,
950                template: _,
951                operands,
952                options: _,
953                line_spans: _,
954                targets: _,
955                unwind: _,
956            } => {
957                for op in operands {
958                    match op {
959                        InlineAsmOperand::In { reg: _, value } => {
960                            self.consume_operand(loc, (value, span), state);
961                        }
962                        InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
963                            if let Some(place) = place {
964                                self.mutate_place(loc, (*place, span), Shallow(None), state);
965                            }
966                        }
967                        InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
968                            self.consume_operand(loc, (in_value, span), state);
969                            if let &Some(out_place) = out_place {
970                                self.mutate_place(loc, (out_place, span), Shallow(None), state);
971                            }
972                        }
973                        InlineAsmOperand::Const { value: _ }
974                        | InlineAsmOperand::SymFn { value: _ }
975                        | InlineAsmOperand::SymStatic { def_id: _ }
976                        | InlineAsmOperand::Label { target_index: _ } => {}
977                    }
978                }
979            }
980
981            TerminatorKind::Goto { target: _, loop_hint_attrs: _ }
982            | TerminatorKind::UnwindTerminate(_)
983            | TerminatorKind::Unreachable
984            | TerminatorKind::UnwindResume
985            | TerminatorKind::Return
986            | TerminatorKind::CoroutineDrop
987            | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
988            | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
989                // no data used, thus irrelevant to borrowck
990            }
991        }
992    }
993
994    fn visit_after_primary_terminator_effect(
995        &mut self,
996        state: &BorrowckDomain,
997        term: &Terminator<'tcx>,
998        loc: Location,
999    ) {
1000        let span = term.source_info.span;
1001
1002        match term.kind {
1003            TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
1004                if self.movable_coroutine {
1005                    // Look for any active borrows to locals
1006                    for i in state.borrows.iter() {
1007                        let borrow = &self.borrow_set[i];
1008                        self.check_for_local_borrow(borrow, span);
1009                    }
1010                }
1011            }
1012
1013            TerminatorKind::UnwindResume
1014            | TerminatorKind::Return
1015            | TerminatorKind::TailCall { .. }
1016            | TerminatorKind::CoroutineDrop => {
1017                match self.borrow_set.locals_state_at_exit() {
1018                    LocalsStateAtExit::AllAreInvalidated => {
1019                        // Returning from the function implicitly kills storage for all locals and statics.
1020                        // Often, the storage will already have been killed by an explicit
1021                        // StorageDead, but we don't always emit those (notably on unwind paths),
1022                        // so this "extra check" serves as a kind of backup.
1023                        for i in state.borrows.iter() {
1024                            let borrow = &self.borrow_set[i];
1025                            self.check_for_invalidation_at_exit(loc, borrow, span);
1026                        }
1027                    }
1028                    // If we do not implicitly invalidate all locals on exit,
1029                    // we check for conflicts when dropping or moving this local.
1030                    LocalsStateAtExit::SomeAreInvalidated { has_storage_dead_or_moved: _ } => {}
1031                }
1032            }
1033
1034            TerminatorKind::UnwindTerminate(_)
1035            | TerminatorKind::Assert { .. }
1036            | TerminatorKind::Call { .. }
1037            | TerminatorKind::Drop { .. }
1038            | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
1039            | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
1040            | TerminatorKind::Goto { .. }
1041            | TerminatorKind::SwitchInt { .. }
1042            | TerminatorKind::Unreachable
1043            | TerminatorKind::InlineAsm { .. } => {}
1044        }
1045    }
1046}
1047
1048use self::AccessDepth::{Deep, Shallow};
1049use self::ReadOrWrite::{Activation, Read, Reservation, Write};
1050
1051#[derive(#[automatically_derived]
impl ::core::marker::Copy for ArtificialField { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ArtificialField { }
#[automatically_derived]
impl ::core::clone::Clone for ArtificialField {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ArtificialField { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ArtificialField {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ArtificialField { }Eq, #[automatically_derived]
impl ::core::fmt::Debug for ArtificialField {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ArtificialField::ArrayLength => "ArrayLength",
                ArtificialField::FakeBorrow => "FakeBorrow",
            })
    }
}Debug)]
1052enum ArtificialField {
1053    ArrayLength,
1054    FakeBorrow,
1055}
1056
1057#[derive(#[automatically_derived]
impl ::core::marker::Copy for AccessDepth { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AccessDepth { }
#[automatically_derived]
impl ::core::clone::Clone for AccessDepth {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<ArtificialField>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AccessDepth { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AccessDepth {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Shallow(__self_0), Self::Shallow(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AccessDepth {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<ArtificialField>>;
    }
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for AccessDepth {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Shallow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Shallow", &__self_0),
            Self::Deep => ::core::fmt::Formatter::write_str(f, "Deep"),
            Self::Drop => ::core::fmt::Formatter::write_str(f, "Drop"),
        }
    }
}Debug)]
1058enum AccessDepth {
1059    /// From the RFC: "A *shallow* access means that the immediate
1060    /// fields reached at P are accessed, but references or pointers
1061    /// found within are not dereferenced. Right now, the only access
1062    /// that is shallow is an assignment like `x = ...;`, which would
1063    /// be a *shallow write* of `x`."
1064    Shallow(Option<ArtificialField>),
1065
1066    /// From the RFC: "A *deep* access means that all data reachable
1067    /// through the given place may be invalidated or accesses by
1068    /// this action."
1069    Deep,
1070
1071    /// Access is Deep only when there is a Drop implementation that
1072    /// can reach the data behind the reference.
1073    Drop,
1074}
1075
1076/// Kind of access to a value: read or write
1077/// (For informational purposes only)
1078#[derive(#[automatically_derived]
impl ::core::marker::Copy for ReadOrWrite { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ReadOrWrite { }
#[automatically_derived]
impl ::core::clone::Clone for ReadOrWrite {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<ReadKind>;
        let _: ::core::clone::AssertParamIsClone<WriteKind>;
        let _: ::core::clone::AssertParamIsClone<BorrowIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ReadOrWrite { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ReadOrWrite {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Read(__self_0), Self::Read(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Write(__self_0), Self::Write(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Reservation(__self_0), Self::Reservation(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Activation(__self_0, __self_1),
                    Self::Activation(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReadOrWrite {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ReadKind>;
        let _: ::core::cmp::AssertParamIsEq<WriteKind>;
        let _: ::core::cmp::AssertParamIsEq<BorrowIndex>;
    }
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ReadOrWrite {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Read(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Read",
                    &__self_0),
            Self::Write(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Write",
                    &__self_0),
            Self::Reservation(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Reservation", &__self_0),
            Self::Activation(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Activation", __self_0, &__self_1),
        }
    }
}Debug)]
1079enum ReadOrWrite {
1080    /// From the RFC: "A *read* means that the existing data may be
1081    /// read, but will not be changed."
1082    Read(ReadKind),
1083
1084    /// From the RFC: "A *write* means that the data may be mutated to
1085    /// new values or otherwise invalidated (for example, it could be
1086    /// de-initialized, as in a move operation).
1087    Write(WriteKind),
1088
1089    /// For two-phase borrows, we distinguish a reservation (which is treated
1090    /// like a Read) from an activation (which is treated like a write), and
1091    /// each of those is furthermore distinguished from Reads/Writes above.
1092    Reservation(WriteKind),
1093    Activation(WriteKind, BorrowIndex),
1094}
1095
1096/// Kind of read access to a value
1097/// (For informational purposes only)
1098#[derive(#[automatically_derived]
impl ::core::marker::Copy for ReadKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ReadKind { }
#[automatically_derived]
impl ::core::clone::Clone for ReadKind {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<BorrowKind>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ReadKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ReadKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Borrow(__self_0), Self::Borrow(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReadKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<BorrowKind>;
    }
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ReadKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Borrow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Borrow",
                    &__self_0),
            Self::Copy => ::core::fmt::Formatter::write_str(f, "Copy"),
        }
    }
}Debug)]
1099enum ReadKind {
1100    Borrow(BorrowKind),
1101    Copy,
1102}
1103
1104/// Kind of write access to a value
1105/// (For informational purposes only)
1106#[derive(#[automatically_derived]
impl ::core::marker::Copy for WriteKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for WriteKind { }
#[automatically_derived]
impl ::core::clone::Clone for WriteKind {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<BorrowKind>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for WriteKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for WriteKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::MutableBorrow(__self_0), Self::MutableBorrow(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for WriteKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<BorrowKind>;
    }
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for WriteKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::StorageDeadOrDrop =>
                ::core::fmt::Formatter::write_str(f, "StorageDeadOrDrop"),
            Self::Replace => ::core::fmt::Formatter::write_str(f, "Replace"),
            Self::MutableBorrow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MutableBorrow", &__self_0),
            Self::Mutate => ::core::fmt::Formatter::write_str(f, "Mutate"),
            Self::Move => ::core::fmt::Formatter::write_str(f, "Move"),
        }
    }
}Debug)]
1107enum WriteKind {
1108    StorageDeadOrDrop,
1109    Replace,
1110    MutableBorrow(BorrowKind),
1111    Mutate,
1112    Move,
1113}
1114
1115/// When checking permissions for a place access, this flag is used to indicate that an immutable
1116/// local place can be mutated.
1117//
1118// FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
1119// - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
1120//   `is_declared_mutable()`.
1121// - Take flow state into consideration in `is_assignable()` for local variables.
1122#[derive(#[automatically_derived]
impl ::core::marker::Copy for LocalMutationIsAllowed { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LocalMutationIsAllowed { }
#[automatically_derived]
impl ::core::clone::Clone for LocalMutationIsAllowed {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for LocalMutationIsAllowed { }
#[automatically_derived]
impl ::core::cmp::PartialEq for LocalMutationIsAllowed {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LocalMutationIsAllowed { }Eq, #[automatically_derived]
impl ::core::fmt::Debug for LocalMutationIsAllowed {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                LocalMutationIsAllowed::Yes => "Yes",
                LocalMutationIsAllowed::ExceptUpvars => "ExceptUpvars",
                LocalMutationIsAllowed::No => "No",
            })
    }
}Debug)]
1123enum LocalMutationIsAllowed {
1124    Yes,
1125    /// We want use of immutable upvars to cause a "write to immutable upvar"
1126    /// error, not an "reassignment" error.
1127    ExceptUpvars,
1128    No,
1129}
1130
1131#[derive(#[automatically_derived]
impl ::core::marker::Copy for InitializationRequiringAction { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InitializationRequiringAction { }
#[automatically_derived]
impl ::core::clone::Clone for InitializationRequiringAction {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for InitializationRequiringAction {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                InitializationRequiringAction::Borrow => "Borrow",
                InitializationRequiringAction::MatchOn => "MatchOn",
                InitializationRequiringAction::Use => "Use",
                InitializationRequiringAction::Assignment => "Assignment",
                InitializationRequiringAction::PartialAssignment =>
                    "PartialAssignment",
            })
    }
}Debug)]
1132enum InitializationRequiringAction {
1133    Borrow,
1134    MatchOn,
1135    Use,
1136    Assignment,
1137    PartialAssignment,
1138}
1139
1140#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RootPlace<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "RootPlace",
            "place_local", &self.place_local, "place_projection",
            &self.place_projection, "is_local_mutation_allowed",
            &&self.is_local_mutation_allowed)
    }
}Debug)]
1141struct RootPlace<'tcx> {
1142    place_local: Local,
1143    place_projection: &'tcx [PlaceElem<'tcx>],
1144    is_local_mutation_allowed: LocalMutationIsAllowed,
1145}
1146
1147impl InitializationRequiringAction {
1148    fn as_noun(self) -> &'static str {
1149        match self {
1150            InitializationRequiringAction::Borrow => "borrow",
1151            InitializationRequiringAction::MatchOn => "use", // no good noun
1152            InitializationRequiringAction::Use => "use",
1153            InitializationRequiringAction::Assignment => "assign",
1154            InitializationRequiringAction::PartialAssignment => "assign to part",
1155        }
1156    }
1157
1158    fn as_verb_in_past_tense(self) -> &'static str {
1159        match self {
1160            InitializationRequiringAction::Borrow => "borrowed",
1161            InitializationRequiringAction::MatchOn => "matched on",
1162            InitializationRequiringAction::Use => "used",
1163            InitializationRequiringAction::Assignment => "assigned",
1164            InitializationRequiringAction::PartialAssignment => "partially assigned",
1165        }
1166    }
1167
1168    fn as_general_verb_in_past_tense(self) -> &'static str {
1169        match self {
1170            InitializationRequiringAction::Borrow
1171            | InitializationRequiringAction::MatchOn
1172            | InitializationRequiringAction::Use => "used",
1173            InitializationRequiringAction::Assignment => "assigned",
1174            InitializationRequiringAction::PartialAssignment => "partially assigned",
1175        }
1176    }
1177}
1178
1179impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
1180    fn body(&self) -> &'a Body<'tcx> {
1181        self.body
1182    }
1183
1184    /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
1185    /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
1186    /// place is initialized and (b) it is not borrowed in some way that would prevent this
1187    /// access.
1188    ///
1189    /// Returns `true` if an error is reported.
1190    fn access_place(
1191        &mut self,
1192        location: Location,
1193        place_span: (Place<'tcx>, Span),
1194        kind: (AccessDepth, ReadOrWrite),
1195        is_local_mutation_allowed: LocalMutationIsAllowed,
1196        state: &BorrowckDomain,
1197    ) {
1198        let (sd, rw) = kind;
1199
1200        if let Activation(_, borrow_index) = rw {
1201            if self.reservation_error_reported.contains(&place_span.0) {
1202                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1202",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1202u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("skipping access_place for activation of invalid reservation place: {0:?} borrow_index: {1:?}",
                                                    place_span.0, borrow_index) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1203                    "skipping access_place for activation of invalid reservation \
1204                     place: {:?} borrow_index: {:?}",
1205                    place_span.0, borrow_index
1206                );
1207                return;
1208            }
1209        }
1210
1211        // Check is_empty() first because it's the common case, and doing that
1212        // way we avoid the clone() call.
1213        if !self.access_place_error_reported.is_empty()
1214            && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1215        {
1216            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1216",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1216u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("access_place: suppressing error place_span=`{0:?}` kind=`{1:?}`",
                                                    place_span, kind) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1217                "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1218                place_span, kind
1219            );
1220
1221            // If the place is being mutated, then mark it as such anyway in order to suppress the
1222            // `unused_mut` lint, which is likely incorrect once the access place error has been
1223            // resolved.
1224            if rw == ReadOrWrite::Write(WriteKind::Mutate)
1225                && let Ok(root_place) =
1226                    self.is_mutable(place_span.0.as_ref(), is_local_mutation_allowed)
1227            {
1228                self.add_used_mut(root_place, state);
1229            }
1230
1231            return;
1232        }
1233
1234        let mutability_error = self.check_access_permissions(
1235            place_span,
1236            rw,
1237            is_local_mutation_allowed,
1238            state,
1239            location,
1240        );
1241        let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
1242
1243        if conflict_error || mutability_error {
1244            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1244",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1244u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("access_place: logging error place_span=`{0:?}` kind=`{1:?}`",
                                                    place_span, kind) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1245            self.access_place_error_reported.insert((place_span.0, place_span.1));
1246        }
1247    }
1248
1249    fn borrows_in_scope<'s>(
1250        &self,
1251        location: Location,
1252        state: &'s BorrowckDomain,
1253    ) -> Cow<'s, MixedBitSet<BorrowIndex>> {
1254        if let Some(polonius) = &self.polonius_output {
1255            // Use polonius output if it has been enabled.
1256            let location = self.location_table.start_index(location);
1257            let mut polonius_output = MixedBitSet::new_empty(self.borrow_set.len());
1258            for &idx in polonius.errors_at(location) {
1259                polonius_output.insert(idx);
1260            }
1261            Cow::Owned(polonius_output)
1262        } else {
1263            Cow::Borrowed(&state.borrows)
1264        }
1265    }
1266
1267    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("check_access_for_conflict",
                                    "rustc_borrowck", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1267u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sd")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sd");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rw")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rw");
                                                        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::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::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(&location)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sd)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rw)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut error_reported = false;
            let borrows_in_scope = self.borrows_in_scope(location, state);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1279",
                                    "rustc_borrowck", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1279u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("borrows_in_scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("borrows_in_scope");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    }], ::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(&::tracing::field::debug(&borrows_in_scope)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            each_borrow_involving_path(self, self.infcx.tcx, self.body,
                (sd, place_span.0), self.borrow_set,
                |borrow_index| borrows_in_scope.contains(borrow_index),
                |this, borrow_index, borrow|
                    match (rw, borrow.kind) {
                        (Activation(_, activating), _) if activating == borrow_index
                            => {
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1296",
                                                    "rustc_borrowck", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(1296u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                                    ::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!("check_access_for_conflict place_span: {0:?} sd: {1:?} rw: {2:?} skipping {3:?} b/c activation of same borrow_index",
                                                                                place_span, sd, rw, (borrow_index, borrow)) as
                                                                        &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                            ControlFlow::Continue(())
                        }
                        (Read(_), BorrowKind::Shared | BorrowKind::Fake(_)) |
                            (Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
                            BorrowKind::Mut { .. }) => ControlFlow::Continue(()),
                        (Reservation(_), BorrowKind::Fake(_) | BorrowKind::Shared)
                            => {
                            ControlFlow::Continue(())
                        }
                        (Write(WriteKind::Move),
                            BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
                            ControlFlow::Continue(())
                        }
                        (Read(kind), BorrowKind::Mut { .. }) => {
                            if !is_active(this.dominators(), borrow, location) {
                                if !borrow.kind.is_two_phase_borrow() {
                                    ::core::panicking::panic("assertion failed: borrow.kind.is_two_phase_borrow()")
                                };
                                return ControlFlow::Continue(());
                            }
                            error_reported = true;
                            match kind {
                                ReadKind::Copy => {
                                    let err =
                                        this.report_use_while_mutably_borrowed(location, place_span,
                                            borrow);
                                    this.buffer_error(err);
                                }
                                ReadKind::Borrow(bk) => {
                                    let err =
                                        this.report_conflicting_borrow(location, place_span, bk,
                                            borrow);
                                    this.buffer_error(err);
                                }
                            }
                            ControlFlow::Break(())
                        }
                        (Reservation(kind) | Activation(kind, _) | Write(kind), _)
                            => {
                            match rw {
                                Reservation(..) => {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1350",
                                                            "rustc_borrowck", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(1350u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                                            ::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!("recording invalid reservation of place: {0:?}",
                                                                                        place_span.0) as &dyn ::tracing::field::Value))])
                                                });
                                        } else { ; }
                                    };
                                    this.reservation_error_reported.insert(place_span.0);
                                }
                                Activation(_, activating) => {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1358",
                                                            "rustc_borrowck", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(1358u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                                            ::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!("observing check_place for activation of borrow_index: {0:?}",
                                                                                        activating) as &dyn ::tracing::field::Value))])
                                                });
                                        } else { ; }
                                    };
                                }
                                Read(..) | Write(..) => {}
                            }
                            error_reported = true;
                            match kind {
                                WriteKind::MutableBorrow(bk) => {
                                    let err =
                                        this.report_conflicting_borrow(location, place_span, bk,
                                            borrow);
                                    this.buffer_error(err);
                                }
                                WriteKind::StorageDeadOrDrop =>
                                    this.report_borrowed_value_does_not_live_long_enough(location,
                                        borrow, place_span, Some(WriteKind::StorageDeadOrDrop)),
                                WriteKind::Mutate => {
                                    this.report_illegal_mutation_of_borrowed(location,
                                        place_span, borrow)
                                }
                                WriteKind::Move => {
                                    this.report_move_out_while_borrowed(location, place_span,
                                        borrow)
                                }
                                WriteKind::Replace => {
                                    this.report_illegal_mutation_of_borrowed(location,
                                        place_span, borrow)
                                }
                            }
                            ControlFlow::Break(())
                        }
                    });
            error_reported
        }
    }
}#[instrument(level = "debug", skip(self, state))]
1268    fn check_access_for_conflict(
1269        &mut self,
1270        location: Location,
1271        place_span: (Place<'tcx>, Span),
1272        sd: AccessDepth,
1273        rw: ReadOrWrite,
1274        state: &BorrowckDomain,
1275    ) -> bool {
1276        let mut error_reported = false;
1277
1278        let borrows_in_scope = self.borrows_in_scope(location, state);
1279        debug!(?borrows_in_scope, ?location);
1280
1281        each_borrow_involving_path(
1282            self,
1283            self.infcx.tcx,
1284            self.body,
1285            (sd, place_span.0),
1286            self.borrow_set,
1287            |borrow_index| borrows_in_scope.contains(borrow_index),
1288            |this, borrow_index, borrow| match (rw, borrow.kind) {
1289                // Obviously an activation is compatible with its own
1290                // reservation (or even prior activating uses of same
1291                // borrow); so don't check if they interfere.
1292                //
1293                // NOTE: *reservations* do conflict with themselves;
1294                // thus aren't injecting unsoundness w/ this check.)
1295                (Activation(_, activating), _) if activating == borrow_index => {
1296                    debug!(
1297                        "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1298                         skipping {:?} b/c activation of same borrow_index",
1299                        place_span,
1300                        sd,
1301                        rw,
1302                        (borrow_index, borrow),
1303                    );
1304                    ControlFlow::Continue(())
1305                }
1306
1307                (Read(_), BorrowKind::Shared | BorrowKind::Fake(_))
1308                | (
1309                    Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
1310                    BorrowKind::Mut { .. },
1311                ) => ControlFlow::Continue(()),
1312
1313                (Reservation(_), BorrowKind::Fake(_) | BorrowKind::Shared) => {
1314                    // This used to be a future compatibility warning (to be
1315                    // disallowed on NLL). See rust-lang/rust#56254
1316                    ControlFlow::Continue(())
1317                }
1318
1319                (Write(WriteKind::Move), BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1320                    // Handled by initialization checks.
1321                    ControlFlow::Continue(())
1322                }
1323
1324                (Read(kind), BorrowKind::Mut { .. }) => {
1325                    // Reading from mere reservations of mutable-borrows is OK.
1326                    if !is_active(this.dominators(), borrow, location) {
1327                        assert!(borrow.kind.is_two_phase_borrow());
1328                        return ControlFlow::Continue(());
1329                    }
1330
1331                    error_reported = true;
1332                    match kind {
1333                        ReadKind::Copy => {
1334                            let err = this
1335                                .report_use_while_mutably_borrowed(location, place_span, borrow);
1336                            this.buffer_error(err);
1337                        }
1338                        ReadKind::Borrow(bk) => {
1339                            let err =
1340                                this.report_conflicting_borrow(location, place_span, bk, borrow);
1341                            this.buffer_error(err);
1342                        }
1343                    }
1344                    ControlFlow::Break(())
1345                }
1346
1347                (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1348                    match rw {
1349                        Reservation(..) => {
1350                            debug!(
1351                                "recording invalid reservation of \
1352                                 place: {:?}",
1353                                place_span.0
1354                            );
1355                            this.reservation_error_reported.insert(place_span.0);
1356                        }
1357                        Activation(_, activating) => {
1358                            debug!(
1359                                "observing check_place for activation of \
1360                                 borrow_index: {:?}",
1361                                activating
1362                            );
1363                        }
1364                        Read(..) | Write(..) => {}
1365                    }
1366
1367                    error_reported = true;
1368                    match kind {
1369                        WriteKind::MutableBorrow(bk) => {
1370                            let err =
1371                                this.report_conflicting_borrow(location, place_span, bk, borrow);
1372                            this.buffer_error(err);
1373                        }
1374                        WriteKind::StorageDeadOrDrop => this
1375                            .report_borrowed_value_does_not_live_long_enough(
1376                                location,
1377                                borrow,
1378                                place_span,
1379                                Some(WriteKind::StorageDeadOrDrop),
1380                            ),
1381                        WriteKind::Mutate => {
1382                            this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1383                        }
1384                        WriteKind::Move => {
1385                            this.report_move_out_while_borrowed(location, place_span, borrow)
1386                        }
1387                        WriteKind::Replace => {
1388                            this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1389                        }
1390                    }
1391                    ControlFlow::Break(())
1392                }
1393            },
1394        );
1395
1396        error_reported
1397    }
1398
1399    /// Through #123739, `BackwardIncompatibleDropHint`s (BIDs) are introduced.
1400    /// We would like to emit lints whether borrow checking fails at these future drop locations.
1401    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("check_backward_incompatible_drop",
                                    "rustc_borrowck", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1401u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place");
                                                        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::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::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(&location)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.infcx.tcx;
            let sd =
                if place.ty(self.body,
                                tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
                    AccessDepth::Drop
                } else { AccessDepth::Shallow(None) };
            let borrows_in_scope = self.borrows_in_scope(location, state);
            each_borrow_involving_path(self, self.infcx.tcx, self.body,
                (sd, place), self.borrow_set,
                |borrow_index| borrows_in_scope.contains(borrow_index),
                |this, _borrow_index, borrow|
                    {
                        if #[allow(non_exhaustive_omitted_patterns)] match borrow.kind
                                {
                                BorrowKind::Fake(_) => true,
                                _ => false,
                            } {
                            return ControlFlow::Continue(());
                        }
                        let borrowed =
                            this.retrieve_borrow_spans(borrow).var_or_use_path_span();
                        let explain =
                            this.explain_why_borrow_contains_point(location, borrow,
                                Some((WriteKind::StorageDeadOrDrop, place)));
                        this.infcx.tcx.emit_node_span_lint(TAIL_EXPR_DROP_ORDER,
                            CRATE_HIR_ID, borrowed,
                            session_diagnostics::TailExprDropOrder {
                                borrowed,
                                callback: |diag|
                                    {
                                        explain.add_explanation_to_diagnostic(&this, diag, "", None,
                                            None);
                                    },
                            });
                        ControlFlow::Break(())
                    });
        }
    }
}#[instrument(level = "debug", skip(self, state))]
1402    fn check_backward_incompatible_drop(
1403        &mut self,
1404        location: Location,
1405        place: Place<'tcx>,
1406        state: &BorrowckDomain,
1407    ) {
1408        let tcx = self.infcx.tcx;
1409        // If this type does not need `Drop`, then treat it like a `StorageDead`.
1410        // This is needed because we track the borrows of refs to thread locals,
1411        // and we'll ICE because we don't track borrows behind shared references.
1412        let sd = if place.ty(self.body, tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
1413            AccessDepth::Drop
1414        } else {
1415            AccessDepth::Shallow(None)
1416        };
1417
1418        let borrows_in_scope = self.borrows_in_scope(location, state);
1419
1420        // This is a very simplified version of `Self::check_access_for_conflict`.
1421        // We are here checking on BIDs and specifically still-live borrows of data involving the BIDs.
1422        each_borrow_involving_path(
1423            self,
1424            self.infcx.tcx,
1425            self.body,
1426            (sd, place),
1427            self.borrow_set,
1428            |borrow_index| borrows_in_scope.contains(borrow_index),
1429            |this, _borrow_index, borrow| {
1430                if matches!(borrow.kind, BorrowKind::Fake(_)) {
1431                    return ControlFlow::Continue(());
1432                }
1433                let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span();
1434                let explain = this.explain_why_borrow_contains_point(
1435                    location,
1436                    borrow,
1437                    Some((WriteKind::StorageDeadOrDrop, place)),
1438                );
1439                this.infcx.tcx.emit_node_span_lint(
1440                    TAIL_EXPR_DROP_ORDER,
1441                    CRATE_HIR_ID,
1442                    borrowed,
1443                    session_diagnostics::TailExprDropOrder {
1444                        borrowed,
1445                        callback: |diag| {
1446                            explain.add_explanation_to_diagnostic(&this, diag, "", None, None);
1447                        },
1448                    },
1449                );
1450                // We may stop at the first case
1451                ControlFlow::Break(())
1452            },
1453        );
1454    }
1455
1456    fn mutate_place(
1457        &mut self,
1458        location: Location,
1459        place_span: (Place<'tcx>, Span),
1460        kind: AccessDepth,
1461        state: &BorrowckDomain,
1462    ) {
1463        // Write of P[i] or *P requires P init'd.
1464        self.check_if_assigned_path_is_moved(location, place_span, state);
1465
1466        self.access_place(
1467            location,
1468            place_span,
1469            (kind, Write(WriteKind::Mutate)),
1470            LocalMutationIsAllowed::No,
1471            state,
1472        );
1473    }
1474
1475    fn consume_rvalue(
1476        &mut self,
1477        location: Location,
1478        (rvalue, span): (&Rvalue<'tcx>, Span),
1479        state: &BorrowckDomain,
1480    ) {
1481        match rvalue {
1482            &Rvalue::Ref(_ /*rgn*/, bk, place) => {
1483                let access_kind = match bk {
1484                    BorrowKind::Fake(FakeBorrowKind::Shallow) => {
1485                        (Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
1486                    }
1487                    BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
1488                        (Deep, Read(ReadKind::Borrow(bk)))
1489                    }
1490                    BorrowKind::Mut { .. } => {
1491                        let wk = WriteKind::MutableBorrow(bk);
1492                        if bk.is_two_phase_borrow() {
1493                            (Deep, Reservation(wk))
1494                        } else {
1495                            (Deep, Write(wk))
1496                        }
1497                    }
1498                };
1499
1500                self.access_place(
1501                    location,
1502                    (place, span),
1503                    access_kind,
1504                    LocalMutationIsAllowed::No,
1505                    state,
1506                );
1507
1508                let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
1509                    InitializationRequiringAction::MatchOn
1510                } else {
1511                    InitializationRequiringAction::Borrow
1512                };
1513
1514                self.check_if_path_or_subpath_is_moved(
1515                    location,
1516                    action,
1517                    (place.as_ref(), span),
1518                    state,
1519                );
1520            }
1521
1522            &Rvalue::Reborrow(_target, mutability, place) => {
1523                let access_kind = (
1524                    Deep,
1525                    if mutability == Mutability::Mut {
1526                        Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1527                            kind: MutBorrowKind::Default,
1528                        }))
1529                    } else {
1530                        Read(ReadKind::Borrow(BorrowKind::Shared))
1531                    },
1532                );
1533
1534                self.access_place(
1535                    location,
1536                    (place, span),
1537                    access_kind,
1538                    LocalMutationIsAllowed::Yes,
1539                    state,
1540                );
1541
1542                let action = InitializationRequiringAction::Borrow;
1543
1544                self.check_if_path_or_subpath_is_moved(
1545                    location,
1546                    action,
1547                    (place.as_ref(), span),
1548                    state,
1549                );
1550            }
1551
1552            &Rvalue::RawPtr(kind, place) => {
1553                let access_kind = match kind {
1554                    RawPtrKind::Mut => (
1555                        Deep,
1556                        Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1557                            kind: MutBorrowKind::Default,
1558                        })),
1559                    ),
1560                    RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1561                    RawPtrKind::FakeForPtrMetadata => {
1562                        (Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
1563                    }
1564                };
1565
1566                self.access_place(
1567                    location,
1568                    (place, span),
1569                    access_kind,
1570                    LocalMutationIsAllowed::No,
1571                    state,
1572                );
1573
1574                self.check_if_path_or_subpath_is_moved(
1575                    location,
1576                    InitializationRequiringAction::Borrow,
1577                    (place.as_ref(), span),
1578                    state,
1579                );
1580            }
1581
1582            Rvalue::ThreadLocalRef(_) => {}
1583
1584            Rvalue::Use(operand, _)
1585            | Rvalue::Repeat(operand, _)
1586            | Rvalue::UnaryOp(_ /*un_op*/, operand)
1587            | Rvalue::Cast(_ /*cast_kind*/, operand, _ /*ty*/) => {
1588                self.consume_operand(location, (operand, span), state)
1589            }
1590
1591            &Rvalue::Discriminant(place) => {
1592                let af = match *rvalue {
1593                    Rvalue::Discriminant(..) => None,
1594                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1595                };
1596                self.access_place(
1597                    location,
1598                    (place, span),
1599                    (Shallow(af), Read(ReadKind::Copy)),
1600                    LocalMutationIsAllowed::No,
1601                    state,
1602                );
1603                self.check_if_path_or_subpath_is_moved(
1604                    location,
1605                    InitializationRequiringAction::Use,
1606                    (place.as_ref(), span),
1607                    state,
1608                );
1609            }
1610
1611            Rvalue::BinaryOp(_bin_op, (operand1, operand2)) => {
1612                self.consume_operand(location, (operand1, span), state);
1613                self.consume_operand(location, (operand2, span), state);
1614            }
1615
1616            Rvalue::Aggregate(aggregate_kind, operands) => {
1617                // We need to report back the list of mutable upvars that were
1618                // moved into the closure and subsequently used by the closure,
1619                // in order to populate our used_mut set.
1620                match **aggregate_kind {
1621                    AggregateKind::Closure(def_id, _)
1622                    | AggregateKind::CoroutineClosure(def_id, _)
1623                    | AggregateKind::Coroutine(def_id, _) => {
1624                        let def_id = def_id.expect_local();
1625                        let used_mut_upvars = self.root_cx.used_mut_upvars(def_id);
1626                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1626",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1626u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("{0:?} used_mut_upvars={1:?}",
                                                    def_id, used_mut_upvars) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1627                        // FIXME: We're cloning the `SmallVec` here to avoid borrowing `root_cx`
1628                        // when calling `propagate_closure_used_mut_upvar`. This should ideally
1629                        // be unnecessary.
1630                        for field in used_mut_upvars.clone() {
1631                            self.propagate_closure_used_mut_upvar(&operands[field]);
1632                        }
1633                    }
1634                    AggregateKind::Adt(..)
1635                    | AggregateKind::Array(..)
1636                    | AggregateKind::Tuple { .. }
1637                    | AggregateKind::RawPtr(..) => (),
1638                }
1639
1640                for operand in operands {
1641                    self.consume_operand(location, (operand, span), state);
1642                }
1643            }
1644
1645            Rvalue::WrapUnsafeBinder(op, _) => {
1646                self.consume_operand(location, (op, span), state);
1647            }
1648
1649            Rvalue::CopyForDeref(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("`CopyForDeref` in borrowck"), Location::caller())bug!("`CopyForDeref` in borrowck"),
1650        }
1651    }
1652
1653    fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1654        let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1655            // We have three possibilities here:
1656            // a. We are modifying something through a mut-ref
1657            // b. We are modifying something that is local to our parent
1658            // c. Current body is a nested closure, and we are modifying path starting from
1659            //    a Place captured by our parent closure.
1660
1661            // Handle (c), the path being modified is exactly the path captured by our parent
1662            if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1663                this.used_mut_upvars.push(field);
1664                return;
1665            }
1666
1667            for (place_ref, proj) in place.iter_projections().rev() {
1668                // Handle (a)
1669                if proj == ProjectionElem::Deref {
1670                    match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1671                        // We aren't modifying a variable directly
1672                        ty::Ref(_, _, hir::Mutability::Mut) => return,
1673
1674                        _ => {}
1675                    }
1676                }
1677
1678                // Handle (c)
1679                if let Some(field) = this.is_upvar_field_projection(place_ref) {
1680                    this.used_mut_upvars.push(field);
1681                    return;
1682                }
1683            }
1684
1685            // Handle(b)
1686            this.used_mut.insert(place.local);
1687        };
1688
1689        // This relies on the current way that by-value
1690        // captures of a closure are copied/moved directly
1691        // when generating MIR.
1692        match *operand {
1693            Operand::Move(place) | Operand::Copy(place) => {
1694                match place.as_local() {
1695                    Some(local) if !self.body.local_decls[local].is_user_variable() => {
1696                        if self.body.local_decls[local].ty.is_mutable_ptr() {
1697                            // The variable will be marked as mutable by the borrow.
1698                            return;
1699                        }
1700                        // This is an edge case where we have a `move` closure
1701                        // inside a non-move closure, and the inner closure
1702                        // contains a mutation:
1703                        //
1704                        // let mut i = 0;
1705                        // || { move || { i += 1; }; };
1706                        //
1707                        // In this case our usual strategy of assuming that the
1708                        // variable will be captured by mutable reference is
1709                        // wrong, since `i` can be copied into the inner
1710                        // closure from a shared reference.
1711                        //
1712                        // As such we have to search for the local that this
1713                        // capture comes from and mark it as being used as mut.
1714
1715                        let Some(temp_mpi) = self.move_data.rev_lookup.find_local(local) else {
1716                            ::rustc_span::macros::bug_impl(None,
    format_args!("temporary should be tracked"), Location::caller());bug!("temporary should be tracked");
1717                        };
1718                        let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1719                            &self.move_data.inits[init_index]
1720                        } else {
1721                            ::rustc_span::macros::bug_impl(None,
    format_args!("temporary should be initialized exactly once"),
    Location::caller())bug!("temporary should be initialized exactly once")
1722                        };
1723
1724                        let InitLocation::Statement(loc) = init.location else {
1725                            ::rustc_span::macros::bug_impl(None,
    format_args!("temporary initialized in arguments"), Location::caller())bug!("temporary initialized in arguments")
1726                        };
1727
1728                        let body = self.body;
1729                        let bbd = &body[loc.block];
1730                        let stmt = &bbd.statements[loc.statement_index];
1731                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1731",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1731u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("temporary assigned in: stmt={0:?}",
                                                    stmt) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("temporary assigned in: stmt={:?}", stmt);
1732
1733                        match stmt.kind {
1734                            StatementKind::Assign((
1735                                _,
1736                                Rvalue::Ref(_, _, source)
1737                                | Rvalue::Use(Operand::Copy(source) | Operand::Move(source), _),
1738                            )) => {
1739                                propagate_closure_used_mut_place(self, source);
1740                            }
1741                            _ => {
1742                                ::rustc_span::macros::bug_impl(None,
    format_args!("closures should only capture user variables or references to user variables"),
    Location::caller());bug!(
1743                                    "closures should only capture user variables \
1744                                 or references to user variables"
1745                                );
1746                            }
1747                        }
1748                    }
1749                    _ => propagate_closure_used_mut_place(self, place),
1750                }
1751            }
1752            Operand::Constant(..) | Operand::RuntimeChecks(_) => {}
1753        }
1754    }
1755
1756    fn consume_operand(
1757        &mut self,
1758        location: Location,
1759        (operand, span): (&Operand<'tcx>, Span),
1760        state: &BorrowckDomain,
1761    ) {
1762        match *operand {
1763            Operand::Copy(place) => {
1764                // copy of place: check if this is "copy of frozen path"
1765                // (FIXME: see check_loans.rs)
1766                self.access_place(
1767                    location,
1768                    (place, span),
1769                    (Deep, Read(ReadKind::Copy)),
1770                    LocalMutationIsAllowed::No,
1771                    state,
1772                );
1773
1774                // Finally, check if path was already moved.
1775                self.check_if_path_or_subpath_is_moved(
1776                    location,
1777                    InitializationRequiringAction::Use,
1778                    (place.as_ref(), span),
1779                    state,
1780                );
1781            }
1782            Operand::Move(place) => {
1783                // Check if moving from this place makes sense.
1784                self.check_movable_place(location, place);
1785
1786                // move of place: check if this is move of already borrowed path
1787                self.access_place(
1788                    location,
1789                    (place, span),
1790                    (Deep, Write(WriteKind::Move)),
1791                    LocalMutationIsAllowed::Yes,
1792                    state,
1793                );
1794
1795                // Finally, check if path was already moved.
1796                self.check_if_path_or_subpath_is_moved(
1797                    location,
1798                    InitializationRequiringAction::Use,
1799                    (place.as_ref(), span),
1800                    state,
1801                );
1802            }
1803            Operand::Constant(_) | Operand::RuntimeChecks(_) => {}
1804        }
1805    }
1806
1807    /// Checks whether a borrow of this place is invalidated when the function
1808    /// exits
1809    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("check_for_invalidation_at_exit",
                                    "rustc_borrowck", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1809u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("borrow")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("borrow");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        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::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::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(&location)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let place = borrow.borrowed_place;
            let mut root_place =
                PlaceRef { local: place.local, projection: &[] };
            let might_be_alive =
                if self.body.local_decls[root_place.local].is_ref_to_thread_local()
                    {
                    root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
                    true
                } else { false };
            let sd = if might_be_alive { Deep } else { Shallow(None) };
            if places_conflict::borrow_conflicts_with_place(self.infcx.tcx,
                    self.body, place, borrow.kind, root_place, sd,
                    places_conflict::PlaceConflictBias::Overlap) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1845",
                                        "rustc_borrowck", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1845u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                        ::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!("check_for_invalidation_at_exit({0:?}): INVALID",
                                                                    place) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                let span = self.infcx.tcx.sess.source_map().end_point(span);
                self.report_borrowed_value_does_not_live_long_enough(location,
                    borrow, (place, span), None)
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1810    fn check_for_invalidation_at_exit(
1811        &mut self,
1812        location: Location,
1813        borrow: &BorrowData<'tcx>,
1814        span: Span,
1815    ) {
1816        let place = borrow.borrowed_place;
1817        let mut root_place = PlaceRef { local: place.local, projection: &[] };
1818
1819        // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1820        // we just know that all locals are dropped at function exit (otherwise
1821        // we'll have a memory leak) and assume that all statics have a destructor.
1822        //
1823        // FIXME: allow thread-locals to borrow other thread locals?
1824        let might_be_alive = if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1825            // Thread-locals might be dropped after the function exits
1826            // We have to dereference the outer reference because
1827            // borrows don't conflict behind shared references.
1828            root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1829            true
1830        } else {
1831            false
1832        };
1833
1834        let sd = if might_be_alive { Deep } else { Shallow(None) };
1835
1836        if places_conflict::borrow_conflicts_with_place(
1837            self.infcx.tcx,
1838            self.body,
1839            place,
1840            borrow.kind,
1841            root_place,
1842            sd,
1843            places_conflict::PlaceConflictBias::Overlap,
1844        ) {
1845            debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1846            // FIXME: should be talking about the region lifetime instead
1847            // of just a span here.
1848            let span = self.infcx.tcx.sess.source_map().end_point(span);
1849            self.report_borrowed_value_does_not_live_long_enough(
1850                location,
1851                borrow,
1852                (place, span),
1853                None,
1854            )
1855        }
1856    }
1857
1858    /// Reports an error if this is a borrow of local data.
1859    /// This is called for all Yield expressions on movable coroutines
1860    fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1861        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:1861",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1861u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("check_for_local_borrow({0:?})",
                                                    borrow) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("check_for_local_borrow({:?})", borrow);
1862
1863        if borrow_of_local_data(borrow.borrowed_place) {
1864            let err = self.cannot_borrow_across_coroutine_yield(
1865                self.retrieve_borrow_spans(borrow).var_or_use(),
1866                yield_span,
1867            );
1868
1869            self.buffer_error(err);
1870        }
1871    }
1872
1873    fn check_activations(&mut self, location: Location, span: Span, state: &BorrowckDomain) {
1874        // Two-phase borrow support: For each activation that is newly
1875        // generated at this statement, check if it interferes with
1876        // another borrow.
1877        for &borrow_index in self.borrow_set.activations_at_location(&location) {
1878            let borrow = &self.borrow_set[borrow_index];
1879
1880            // only mutable borrows should be 2-phase
1881            if !match borrow.kind {
            BorrowKind::Shared | BorrowKind::Fake(_) => false,
            BorrowKind::Mut { .. } => true,
        } {
    ::core::panicking::panic("assertion failed: match borrow.kind {\n    BorrowKind::Shared | BorrowKind::Fake(_) => false,\n    BorrowKind::Mut { .. } => true,\n}")
};assert!(match borrow.kind {
1882                BorrowKind::Shared | BorrowKind::Fake(_) => false,
1883                BorrowKind::Mut { .. } => true,
1884            });
1885
1886            self.access_place(
1887                location,
1888                (borrow.borrowed_place, span),
1889                (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1890                LocalMutationIsAllowed::No,
1891                state,
1892            );
1893            // We do not need to call `check_if_path_or_subpath_is_moved`
1894            // again, as we already called it when we made the
1895            // initial reservation.
1896        }
1897    }
1898
1899    fn check_movable_place(&mut self, location: Location, place: Place<'tcx>) {
1900        use IllegalMoveOriginKind::*;
1901
1902        let body = self.body;
1903        let tcx = self.infcx.tcx;
1904        let mut place_ty = PlaceTy::from_ty(body.local_decls[place.local].ty);
1905        for (place_ref, elem) in place.iter_projections() {
1906            match elem {
1907                ProjectionElem::Deref => match place_ty.ty.kind() {
1908                    ty::Ref(..) | ty::RawPtr(..) => {
1909                        self.move_errors.push(MoveError::new(
1910                            place,
1911                            location,
1912                            BorrowedContent {
1913                                target_place: place_ref.project_deeper(&[elem], tcx),
1914                            },
1915                        ));
1916                        return;
1917                    }
1918                    ty::Adt(adt, _) => {
1919                        if !adt.is_box() {
1920                            ::rustc_span::macros::bug_impl(None,
    format_args!("Adt should be a box type when Place is deref"),
    Location::caller());bug!("Adt should be a box type when Place is deref");
1921                        }
1922                    }
1923                    ty::Bool
1924                    | ty::Char
1925                    | ty::Int(_)
1926                    | ty::Uint(_)
1927                    | ty::Float(_)
1928                    | ty::Foreign(_)
1929                    | ty::Str
1930                    | ty::Array(_, _)
1931                    | ty::Pat(_, _)
1932                    | ty::Slice(_)
1933                    | ty::FnDef(_, _)
1934                    | ty::FnPtr(..)
1935                    | ty::Dynamic(_, _)
1936                    | ty::Closure(_, _)
1937                    | ty::CoroutineClosure(_, _)
1938                    | ty::Coroutine(_, _)
1939                    | ty::CoroutineWitness(..)
1940                    | ty::Never
1941                    | ty::Tuple(_)
1942                    | ty::UnsafeBinder(_)
1943                    | ty::Alias(_, _)
1944                    | ty::Param(_)
1945                    | ty::Bound(_, _)
1946                    | ty::Infer(_)
1947                    | ty::Error(_)
1948                    | ty::Placeholder(_) => {
1949                        ::rustc_span::macros::bug_impl(None,
    format_args!("When Place is Deref it\'s type shouldn\'t be {0:#?}",
        place_ty), Location::caller())bug!("When Place is Deref it's type shouldn't be {place_ty:#?}")
1950                    }
1951                },
1952                ProjectionElem::Field(_, _) => match place_ty.ty.kind() {
1953                    ty::Adt(adt, _) => {
1954                        if adt.has_dtor(tcx) {
1955                            self.move_errors.push(MoveError::new(
1956                                place,
1957                                location,
1958                                InteriorOfTypeWithDestructor { container_ty: place_ty.ty },
1959                            ));
1960                            return;
1961                        }
1962                    }
1963                    ty::Closure(..)
1964                    | ty::CoroutineClosure(..)
1965                    | ty::Coroutine(_, _)
1966                    | ty::Tuple(_) => (),
1967                    ty::Bool
1968                    | ty::Char
1969                    | ty::Int(_)
1970                    | ty::Uint(_)
1971                    | ty::Float(_)
1972                    | ty::Foreign(_)
1973                    | ty::Str
1974                    | ty::Array(_, _)
1975                    | ty::Pat(_, _)
1976                    | ty::Slice(_)
1977                    | ty::RawPtr(_, _)
1978                    | ty::Ref(_, _, _)
1979                    | ty::FnDef(_, _)
1980                    | ty::FnPtr(..)
1981                    | ty::Dynamic(_, _)
1982                    | ty::CoroutineWitness(..)
1983                    | ty::Never
1984                    | ty::UnsafeBinder(_)
1985                    | ty::Alias(_, _)
1986                    | ty::Param(_)
1987                    | ty::Bound(_, _)
1988                    | ty::Infer(_)
1989                    | ty::Error(_)
1990                    | ty::Placeholder(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("When Place contains ProjectionElem::Field it\'s type shouldn\'t be {0:#?}",
        place_ty), Location::caller())bug!(
1991                        "When Place contains ProjectionElem::Field it's type shouldn't be {place_ty:#?}"
1992                    ),
1993                },
1994                ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1995                    match place_ty.ty.kind() {
1996                        ty::Slice(_) => {
1997                            self.move_errors.push(MoveError::new(
1998                                place,
1999                                location,
2000                                InteriorOfSliceOrArray { ty: place_ty.ty, is_index: false },
2001                            ));
2002                            return;
2003                        }
2004                        ty::Array(_, _) => (),
2005                        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Unexpected type {0:#?}", place_ty.ty), Location::caller())bug!("Unexpected type {:#?}", place_ty.ty),
2006                    }
2007                }
2008                ProjectionElem::Index(_) => match place_ty.ty.kind() {
2009                    ty::Array(..) | ty::Slice(..) => {
2010                        self.move_errors.push(MoveError::new(
2011                            place,
2012                            location,
2013                            InteriorOfSliceOrArray { ty: place_ty.ty, is_index: true },
2014                        ));
2015                        return;
2016                    }
2017                    _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Unexpected type {0:#?}", place_ty), Location::caller())bug!("Unexpected type {place_ty:#?}"),
2018                },
2019                // `OpaqueCast`: only transmutes the type, so no moves there.
2020                // `Downcast`  : only changes information about a `Place` without moving.
2021                // So it's safe to skip these.
2022                ProjectionElem::OpaqueCast(_)
2023                | ProjectionElem::Downcast(_, _)
2024                | ProjectionElem::UnwrapUnsafeBinder(_)
2025                | ProjectionElem::PhantomDeref => (),
2026            }
2027
2028            place_ty = place_ty.projection_ty(tcx, elem);
2029        }
2030    }
2031
2032    fn check_if_full_path_is_moved(
2033        &mut self,
2034        location: Location,
2035        desired_action: InitializationRequiringAction,
2036        place_span: (PlaceRef<'tcx>, Span),
2037        state: &BorrowckDomain,
2038    ) {
2039        let maybe_uninits = &state.uninits;
2040
2041        // Bad scenarios:
2042        //
2043        // 1. Move of `a.b.c`, use of `a.b.c`
2044        // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
2045        // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
2046        //    partial initialization support, one might have `a.x`
2047        //    initialized but not `a.b`.
2048        //
2049        // OK scenarios:
2050        //
2051        // 4. Move of `a.b.c`, use of `a.b.d`
2052        // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
2053        // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
2054        //    must have been initialized for the use to be sound.
2055        // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
2056
2057        // The dataflow tracks shallow prefixes distinctly (that is,
2058        // field-accesses on P distinctly from P itself), in order to
2059        // track substructure initialization separately from the whole
2060        // structure.
2061        //
2062        // E.g., when looking at (*a.b.c).d, if the closest prefix for
2063        // which we have a MovePath is `a.b`, then that means that the
2064        // initialization state of `a.b` is all we need to inspect to
2065        // know if `a.b.c` is valid (and from that we infer that the
2066        // dereference and `.d` access is also valid, since we assume
2067        // `a.b.c` is assigned a reference to an initialized and
2068        // well-formed record structure.)
2069
2070        // Therefore, if we seek out the *closest* prefix for which we
2071        // have a MovePath, that should capture the initialization
2072        // state for the place scenario.
2073        //
2074        // This code covers scenarios 1, 2, and 3.
2075
2076        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:2076",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2076u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("check_if_full_path_is_moved place: {0:?}",
                                                    place_span.0) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
2077        let (prefix, mpi) = self.move_path_closest_to(place_span.0);
2078        if maybe_uninits.contains(mpi) {
2079            self.report_use_of_moved_or_uninitialized(
2080                location,
2081                desired_action,
2082                (prefix, place_span.0, place_span.1),
2083                mpi,
2084            );
2085        } // Only query longest prefix with a MovePath, not further
2086        // ancestors; dataflow recurs on children when parents
2087        // move (to support partial (re)inits).
2088        //
2089        // (I.e., querying parents breaks scenario 7; but may want
2090        // to do such a query based on partial-init feature-gate.)
2091    }
2092
2093    /// Subslices correspond to multiple move paths, so we iterate through the
2094    /// elements of the base array. For each element we check
2095    ///
2096    /// * Does this element overlap with our slice.
2097    /// * Is any part of it uninitialized.
2098    fn check_if_subslice_element_is_moved(
2099        &mut self,
2100        location: Location,
2101        desired_action: InitializationRequiringAction,
2102        place_span: (PlaceRef<'tcx>, Span),
2103        maybe_uninits: &MixedBitSet<MovePathIndex>,
2104        from: u64,
2105        to: u64,
2106    ) {
2107        if let Some(mpi) = self.move_path_for_place(place_span.0) {
2108            let move_paths = &self.move_data.move_paths;
2109
2110            let root_path = &move_paths[mpi];
2111            for (child_mpi, child_move_path) in root_path.children(move_paths) {
2112                let last_proj = child_move_path.place.projection.last().unwrap();
2113                if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
2114                    if true {
    if !!from_end {
        {
            ::core::panicking::panic_fmt(format_args!("Array constant indexing shouldn\'t be `from_end`."));
        }
    };
};debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
2115
2116                    if (from..to).contains(offset) {
2117                        let uninit_child =
2118                            self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
2119                                maybe_uninits.contains(mpi)
2120                            });
2121
2122                        if let Some(uninit_child) = uninit_child {
2123                            self.report_use_of_moved_or_uninitialized(
2124                                location,
2125                                desired_action,
2126                                (place_span.0, place_span.0, place_span.1),
2127                                uninit_child,
2128                            );
2129                            return; // don't bother finding other problems.
2130                        }
2131                    }
2132                }
2133            }
2134        }
2135    }
2136
2137    fn check_if_path_or_subpath_is_moved(
2138        &mut self,
2139        location: Location,
2140        desired_action: InitializationRequiringAction,
2141        place_span: (PlaceRef<'tcx>, Span),
2142        state: &BorrowckDomain,
2143    ) {
2144        let maybe_uninits = &state.uninits;
2145
2146        // Bad scenarios:
2147        //
2148        // 1. Move of `a.b.c`, use of `a` or `a.b`
2149        //    partial initialization support, one might have `a.x`
2150        //    initialized but not `a.b`.
2151        // 2. All bad scenarios from `check_if_full_path_is_moved`
2152        //
2153        // OK scenarios:
2154        //
2155        // 3. Move of `a.b.c`, use of `a.b.d`
2156        // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
2157        // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
2158        //    must have been initialized for the use to be sound.
2159        // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
2160
2161        self.check_if_full_path_is_moved(location, desired_action, place_span, state);
2162
2163        if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
2164            place_span.0.last_projection()
2165        {
2166            let place_ty = place_base.ty(self.body(), self.infcx.tcx);
2167            if let ty::Array(..) = place_ty.ty.kind() {
2168                self.check_if_subslice_element_is_moved(
2169                    location,
2170                    desired_action,
2171                    (place_base, place_span.1),
2172                    maybe_uninits,
2173                    from,
2174                    to,
2175                );
2176                return;
2177            }
2178        }
2179
2180        // A move of any shallow suffix of `place` also interferes
2181        // with an attempt to use `place`. This is scenario 3 above.
2182        //
2183        // (Distinct from handling of scenarios 1+2+4 above because
2184        // `place` does not interfere with suffixes of its prefixes,
2185        // e.g., `a.b.c` does not interfere with `a.b.d`)
2186        //
2187        // This code covers scenario 1.
2188
2189        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:2189",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2189u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("check_if_path_or_subpath_is_moved place: {0:?}",
                                                    place_span.0) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
2190        if let Some(mpi) = self.move_path_for_place(place_span.0) {
2191            let uninit_mpi = self
2192                .move_data
2193                .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
2194
2195            if let Some(uninit_mpi) = uninit_mpi {
2196                self.report_use_of_moved_or_uninitialized(
2197                    location,
2198                    desired_action,
2199                    (place_span.0, place_span.0, place_span.1),
2200                    uninit_mpi,
2201                );
2202                return; // don't bother finding other problems.
2203            }
2204        }
2205    }
2206
2207    /// Currently MoveData does not store entries for all places in
2208    /// the input MIR. For example it will currently filter out
2209    /// places that are Copy; thus we do not track places of shared
2210    /// reference type. This routine will walk up a place along its
2211    /// prefixes, searching for a foundational place that *is*
2212    /// tracked in the MoveData.
2213    ///
2214    /// An Err result includes a tag indicated why the search failed.
2215    /// Currently this can only occur if the place is built off of a
2216    /// static variable, as we do not track those in the MoveData.
2217    fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
2218        match self.move_data.rev_lookup.find(place) {
2219            LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
2220                (self.move_data.move_paths[mpi].place.as_ref(), mpi)
2221            }
2222            LookupResult::Parent(None) => {
    ::core::panicking::panic_fmt(format_args!("should have move path for every Local"));
}panic!("should have move path for every Local"),
2223        }
2224    }
2225
2226    fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
2227        // If returns None, then there is no move path corresponding
2228        // to a direct owner of `place` (which means there is nothing
2229        // that borrowck tracks for its analysis).
2230
2231        match self.move_data.rev_lookup.find(place) {
2232            LookupResult::Parent(_) => None,
2233            LookupResult::Exact(mpi) => Some(mpi),
2234        }
2235    }
2236
2237    fn check_if_assigned_path_is_moved(
2238        &mut self,
2239        location: Location,
2240        (place, span): (Place<'tcx>, Span),
2241        state: &BorrowckDomain,
2242    ) {
2243        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:2243",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2243u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("check_if_assigned_path_is_moved place: {0:?}",
                                                    place) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("check_if_assigned_path_is_moved place: {:?}", place);
2244
2245        // None case => assigning to `x` does not require `x` be initialized.
2246        for (place_base, elem) in place.iter_projections().rev() {
2247            match elem {
2248                ProjectionElem::Index(_/*operand*/)
2249                | ProjectionElem::OpaqueCast(_)
2250                // assigning to P[i] requires P to be valid.
2251                | ProjectionElem::ConstantIndex { .. }
2252                // assigning to (P->variant) is okay if assigning to `P` is okay
2253                //
2254                // FIXME: is this true even if P is an adt with a dtor?
2255                | ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
2256                    {}
2257
2258                ProjectionElem::UnwrapUnsafeBinder(_) => {
2259                    check_parent_of_field(self, location, place_base, span, state);
2260                }
2261
2262                // assigning to (*P) requires P to be initialized
2263                ProjectionElem::Deref => {
2264                    self.check_if_full_path_is_moved(
2265                        location,
2266                        InitializationRequiringAction::Use,
2267                        (place_base, span),
2268                        state,
2269                    );
2270                    // (base initialized; no need to
2271                    // recur further)
2272                    break;
2273                }
2274
2275                ProjectionElem::PhantomDeref => {
2276                    {
    ::core::panicking::panic_fmt(format_args!("we don\'t allow assignments to PhantomDeref, location {0:?}",
            location));
};panic!("we don't allow assignments to PhantomDeref, location {location:?}");
2277                }
2278
2279                ProjectionElem::Subslice { .. } => {
2280                    {
    ::core::panicking::panic_fmt(format_args!("we don\'t allow assignments to subslices, location: {0:?}",
            location));
};panic!("we don't allow assignments to subslices, location: {location:?}");
2281                }
2282
2283                ProjectionElem::Field(..) => {
2284                    // if type of `P` has a dtor, then
2285                    // assigning to `P.f` requires `P` itself
2286                    // be already initialized
2287                    let tcx = self.infcx.tcx;
2288                    let base_ty = place_base.ty(self.body(), tcx).ty;
2289                    match base_ty.kind() {
2290                        ty::Adt(def, _) if def.has_dtor(tcx) => {
2291                            self.check_if_path_or_subpath_is_moved(
2292                                location,
2293                                InitializationRequiringAction::Assignment,
2294                                (place_base, span),
2295                                state,
2296                            );
2297
2298                            // (base initialized; no need to
2299                            // recur further)
2300                            break;
2301                        }
2302
2303                        // Once `let s; s.x = V; read(s.x);`,
2304                        // is allowed, remove this match arm.
2305                        ty::Adt(..) | ty::Tuple(..) => {
2306                            check_parent_of_field(self, location, place_base, span, state);
2307                        }
2308
2309                        _ => {}
2310                    }
2311                }
2312            }
2313        }
2314
2315        fn check_parent_of_field<'a, 'tcx>(
2316            this: &mut MirBorrowckCtxt<'a, '_, 'tcx>,
2317            location: Location,
2318            base: PlaceRef<'tcx>,
2319            span: Span,
2320            state: &BorrowckDomain,
2321        ) {
2322            // rust-lang/rust#21232: Until Rust allows reads from the
2323            // initialized parts of partially initialized structs, we
2324            // will, starting with the 2018 edition, reject attempts
2325            // to write to structs that are not fully initialized.
2326            //
2327            // In other words, *until* we allow this:
2328            //
2329            // 1. `let mut s; s.x = Val; read(s.x);`
2330            //
2331            // we will for now disallow this:
2332            //
2333            // 2. `let mut s; s.x = Val;`
2334            //
2335            // and also this:
2336            //
2337            // 3. `let mut s = ...; drop(s); s.x=Val;`
2338            //
2339            // This does not use check_if_path_or_subpath_is_moved,
2340            // because we want to *allow* reinitializations of fields:
2341            // e.g., want to allow
2342            //
2343            // `let mut s = ...; drop(s.x); s.x=Val;`
2344            //
2345            // This does not use check_if_full_path_is_moved on
2346            // `base`, because that would report an error about the
2347            // `base` as a whole, but in this scenario we *really*
2348            // want to report an error about the actual thing that was
2349            // moved, which may be some prefix of `base`.
2350
2351            // Shallow so that we'll stop at any dereference; we'll
2352            // report errors about issues with such bases elsewhere.
2353            let maybe_uninits = &state.uninits;
2354
2355            // Find the shortest uninitialized prefix you can reach
2356            // without going over a Deref.
2357            let mut shortest_uninit_seen = None;
2358            for prefix in this.prefixes(base, PrefixSet::Shallow) {
2359                let Some(mpi) = this.move_path_for_place(prefix) else { continue };
2360
2361                if maybe_uninits.contains(mpi) {
2362                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:2362",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2362u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("check_parent_of_field updating shortest_uninit_seen from {0:?} to {1:?}",
                                                    shortest_uninit_seen, Some((prefix, mpi))) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2363                        "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
2364                        shortest_uninit_seen,
2365                        Some((prefix, mpi))
2366                    );
2367                    shortest_uninit_seen = Some((prefix, mpi));
2368                } else {
2369                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:2369",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2369u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("check_parent_of_field {0:?} is definitely initialized",
                                                    (prefix, mpi)) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
2370                }
2371            }
2372
2373            if let Some((prefix, mpi)) = shortest_uninit_seen {
2374                // Check for a reassignment into an uninitialized field of a union (for example,
2375                // after a move out). In this case, do not report an error here. There is an
2376                // exception, if this is the first assignment into the union (that is, there is
2377                // no move out from an earlier location) then this is an attempt at initialization
2378                // of the union - we should error in that case.
2379                let tcx = this.infcx.tcx;
2380                if base.ty(this.body(), tcx).ty.is_union()
2381                    && this.move_data.move_out_path_map[mpi].iter().any(|moi| {
2382                        this.move_data.move_outs[*moi].source.is_predecessor_of(location, this.body)
2383                    })
2384                {
2385                    return;
2386                }
2387
2388                this.report_use_of_moved_or_uninitialized(
2389                    location,
2390                    InitializationRequiringAction::PartialAssignment,
2391                    (prefix, base, span),
2392                    mpi,
2393                );
2394
2395                // rust-lang/rust#21232, #54499, #54986: during period where we reject
2396                // partial initialization, do not complain about unnecessary `mut` on
2397                // an attempt to do a partial initialization.
2398                this.used_mut.insert(base.local);
2399            }
2400        }
2401    }
2402
2403    /// Checks the permissions for the given place and read or write kind
2404    ///
2405    /// Returns `true` if an error is reported.
2406    fn check_access_permissions(
2407        &mut self,
2408        (place, span): (Place<'tcx>, Span),
2409        kind: ReadOrWrite,
2410        is_local_mutation_allowed: LocalMutationIsAllowed,
2411        state: &BorrowckDomain,
2412        location: Location,
2413    ) -> bool {
2414        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:2414",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2414u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("check_access_permissions({0:?}, {1:?}, is_local_mutation_allowed: {2:?})",
                                                    place, kind, is_local_mutation_allowed) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2415            "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2416            place, kind, is_local_mutation_allowed
2417        );
2418
2419        let error_access;
2420        let the_place_err;
2421
2422        match kind {
2423            Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind }))
2424            | Write(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind })) => {
2425                let is_local_mutation_allowed = match mut_borrow_kind {
2426                    // `ClosureCapture` is used for mutable variable with an immutable binding.
2427                    // This is only behaviour difference between `ClosureCapture` and mutable
2428                    // borrows.
2429                    MutBorrowKind::ClosureCapture => LocalMutationIsAllowed::Yes,
2430                    MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow => {
2431                        is_local_mutation_allowed
2432                    }
2433                };
2434                match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2435                    Ok(root_place) => {
2436                        self.add_used_mut(root_place, state);
2437                        return false;
2438                    }
2439                    Err(place_err) => {
2440                        error_access = AccessKind::MutableBorrow;
2441                        the_place_err = place_err;
2442                    }
2443                }
2444            }
2445            Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2446                match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2447                    Ok(root_place) => {
2448                        self.add_used_mut(root_place, state);
2449                        return false;
2450                    }
2451                    Err(place_err) => {
2452                        error_access = AccessKind::Mutate;
2453                        the_place_err = place_err;
2454                    }
2455                }
2456            }
2457
2458            Reservation(
2459                WriteKind::Move
2460                | WriteKind::Replace
2461                | WriteKind::StorageDeadOrDrop
2462                | WriteKind::MutableBorrow(BorrowKind::Shared)
2463                | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2464            )
2465            | Write(
2466                WriteKind::Move
2467                | WriteKind::Replace
2468                | WriteKind::StorageDeadOrDrop
2469                | WriteKind::MutableBorrow(BorrowKind::Shared)
2470                | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2471            ) => {
2472                if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2473                    && !self.has_buffered_diags()
2474                {
2475                    // rust-lang/rust#46908: In pure NLL mode this code path should be
2476                    // unreachable, but we use `span_delayed_bug` because we can hit this when
2477                    // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2478                    // enabled. We don't want to ICE for that case, as other errors will have
2479                    // been emitted (#52262).
2480                    self.dcx().span_delayed_bug(
2481                        span,
2482                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Accessing `{0:?}` with the kind `{1:?}` shouldn\'t be possible",
                place, kind))
    })format!(
2483                            "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
2484                        ),
2485                    );
2486                }
2487                return false;
2488            }
2489            Activation(..) => {
2490                // permission checks are done at Reservation point.
2491                return false;
2492            }
2493            Read(
2494                ReadKind::Borrow(BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_))
2495                | ReadKind::Copy,
2496            ) => {
2497                // Access authorized
2498                return false;
2499            }
2500        }
2501
2502        // rust-lang/rust#21232, #54986: during period where we reject
2503        // partial initialization, do not complain about mutability
2504        // errors except for actual mutation (as opposed to an attempt
2505        // to do a partial initialization).
2506        let previously_initialized = state.ever_inits.contains(place.local);
2507
2508        // at this point, we have set up the error reporting state.
2509        if previously_initialized {
2510            if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2511                // If this is a mutate access to an immutable local variable with no projections
2512                // report the error as an illegal reassignment
2513                let init_index = self.first_reaching_init(place.local, location).unwrap();
2514                let init = &self.move_data.inits[init_index];
2515                let assigned_span = init.span(self.body);
2516                self.report_illegal_reassignment((place, span), assigned_span, place);
2517            } else {
2518                self.report_mutability_error(place, span, the_place_err, error_access, location)
2519            }
2520            true
2521        } else {
2522            false
2523        }
2524    }
2525
2526    /// Returns the first init of `local` (in gather order) that may have executed on some path
2527    /// reaching `location` without an intervening `StorageDead(local)`.
2528    fn first_reaching_init(&self, local: Local, location: Location) -> Option<InitIndex> {
2529        let mpi = self.move_data.rev_lookup.find_local(local)?;
2530        self.move_data.init_path_map[mpi].iter().copied().find(|&ii| {
2531            let init = self.move_data.inits[ii];
2532            EverInitializedPlaces::init_reaches_location(self.body, local, init, location)
2533        })
2534    }
2535
2536    /// Adds the place into the used mutable variables set
2537    fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain) {
2538        match root_place {
2539            RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2540                // If the local may have been initialized, and it is now currently being
2541                // mutated, then it is justified to be annotated with the `mut`
2542                // keyword, since the mutation may be a possible reassignment.
2543                if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2544                    && state.ever_inits.contains(local)
2545                {
2546                    self.used_mut.insert(local);
2547                }
2548            }
2549            RootPlace {
2550                place_local: _,
2551                place_projection: _,
2552                is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2553            } => {}
2554            RootPlace {
2555                place_local,
2556                place_projection: place_projection @ [.., _],
2557                is_local_mutation_allowed: _,
2558            } => {
2559                if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2560                    local: place_local,
2561                    projection: place_projection,
2562                }) {
2563                    self.used_mut_upvars.push(field);
2564                }
2565            }
2566        }
2567    }
2568
2569    /// Whether this value can be written or borrowed mutably.
2570    /// Returns the root place if the place passed in is a projection.
2571    fn is_mutable(
2572        &self,
2573        place: PlaceRef<'tcx>,
2574        is_local_mutation_allowed: LocalMutationIsAllowed,
2575    ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2576        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:2576",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2576u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("is_mutable: place={0:?}, is_local...={1:?}",
                                                    place, is_local_mutation_allowed) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2577        match place.last_projection() {
2578            None => {
2579                let local = &self.body.local_decls[place.local];
2580                match local.mutability {
2581                    Mutability::Not => match is_local_mutation_allowed {
2582                        LocalMutationIsAllowed::Yes => Ok(RootPlace {
2583                            place_local: place.local,
2584                            place_projection: place.projection,
2585                            is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2586                        }),
2587                        LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2588                            place_local: place.local,
2589                            place_projection: place.projection,
2590                            is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2591                        }),
2592                        LocalMutationIsAllowed::No => Err(place),
2593                    },
2594                    Mutability::Mut => Ok(RootPlace {
2595                        place_local: place.local,
2596                        place_projection: place.projection,
2597                        is_local_mutation_allowed,
2598                    }),
2599                }
2600            }
2601            Some((place_base, elem)) => {
2602                match elem {
2603                    ProjectionElem::Deref => {
2604                        let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2605
2606                        // Check the kind of deref to decide
2607                        match base_ty.kind() {
2608                            ty::Ref(_, _, mutbl) => {
2609                                match mutbl {
2610                                    // Shared borrowed data is never mutable
2611                                    hir::Mutability::Not => Err(place),
2612                                    // Mutably borrowed data is mutable, but only if we have a
2613                                    // unique path to the `&mut`
2614                                    hir::Mutability::Mut => {
2615                                        let mode = match self.is_upvar_field_projection(place) {
2616                                            Some(field)
2617                                                if self.upvars[field.index()].is_by_ref() =>
2618                                            {
2619                                                is_local_mutation_allowed
2620                                            }
2621                                            _ => LocalMutationIsAllowed::Yes,
2622                                        };
2623
2624                                        self.is_mutable(place_base, mode)
2625                                    }
2626                                }
2627                            }
2628                            ty::RawPtr(_, mutbl) => {
2629                                match mutbl {
2630                                    // `*const` raw pointers are not mutable
2631                                    hir::Mutability::Not => Err(place),
2632                                    // `*mut` raw pointers are always mutable, regardless of
2633                                    // context. The users have to check by themselves.
2634                                    hir::Mutability::Mut => Ok(RootPlace {
2635                                        place_local: place.local,
2636                                        place_projection: place.projection,
2637                                        is_local_mutation_allowed,
2638                                    }),
2639                                }
2640                            }
2641                            // `Box<T>` owns its content, so mutable if its location is mutable
2642                            _ if base_ty.is_box() => {
2643                                self.is_mutable(place_base, is_local_mutation_allowed)
2644                            }
2645                            // Deref should only be for reference, pointers or boxes
2646                            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Deref of unexpected type: {0:?}", base_ty),
    Location::caller())bug!("Deref of unexpected type: {:?}", base_ty),
2647                        }
2648                    }
2649                    ProjectionElem::PhantomDeref => {
2650                        ::rustc_span::macros::bug_impl(None,
    format_args!("encountered PhantomDeref in is_mutable"),
    Location::caller())bug!("encountered PhantomDeref in is_mutable")
2651                    }
2652                    // Check as the inner reference type if it is a field projection
2653                    // from the `&pin` pattern
2654                    ProjectionElem::Field(FieldIdx::ZERO, _)
2655                        if let Some(adt) =
2656                            place_base.ty(self.body(), self.infcx.tcx).ty.ty_adt_def()
2657                            && adt.is_pin()
2658                            && self.infcx.tcx.features().pin_ergonomics() =>
2659                    {
2660                        self.is_mutable(place_base, is_local_mutation_allowed)
2661                    }
2662                    // All other projections are owned by their base path, so mutable if
2663                    // base path is mutable
2664                    ProjectionElem::Field(..)
2665                    | ProjectionElem::Index(..)
2666                    | ProjectionElem::ConstantIndex { .. }
2667                    | ProjectionElem::Subslice { .. }
2668                    | ProjectionElem::OpaqueCast { .. }
2669                    | ProjectionElem::Downcast(..)
2670                    | ProjectionElem::UnwrapUnsafeBinder(_) => {
2671                        let upvar_field_projection = self.is_upvar_field_projection(place);
2672                        if let Some(field) = upvar_field_projection {
2673                            let upvar = &self.upvars[field.index()];
2674                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs:2674",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2674u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                        ::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!("is_mutable: upvar.mutability={0:?} local_mutation_is_allowed={1:?} place={2:?}, place_base={3:?}",
                                                    upvar, is_local_mutation_allowed, place, place_base) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2675                                "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2676                                 place={:?}, place_base={:?}",
2677                                upvar, is_local_mutation_allowed, place, place_base
2678                            );
2679                            match (upvar.mutability, is_local_mutation_allowed) {
2680                                (
2681                                    Mutability::Not,
2682                                    LocalMutationIsAllowed::No
2683                                    | LocalMutationIsAllowed::ExceptUpvars,
2684                                ) => Err(place),
2685                                (Mutability::Not, LocalMutationIsAllowed::Yes)
2686                                | (Mutability::Mut, _) => {
2687                                    // Subtle: this is an upvar reference, so it looks like
2688                                    // `self.foo` -- we want to double check that the location
2689                                    // `*self` is mutable (i.e., this is not a `Fn` closure). But
2690                                    // if that check succeeds, we want to *blame* the mutability on
2691                                    // `place` (that is, `self.foo`). This is used to propagate the
2692                                    // info about whether mutability declarations are used
2693                                    // outwards, so that we register the outer variable as mutable.
2694                                    // Otherwise a test like this fails to record the `mut` as
2695                                    // needed:
2696                                    // ```
2697                                    // fn foo<F: FnOnce()>(_f: F) { }
2698                                    // fn main() {
2699                                    //     let var = Vec::new();
2700                                    //     foo(move || {
2701                                    //         var.push(1);
2702                                    //     });
2703                                    // }
2704                                    // ```
2705                                    let _ =
2706                                        self.is_mutable(place_base, is_local_mutation_allowed)?;
2707                                    Ok(RootPlace {
2708                                        place_local: place.local,
2709                                        place_projection: place.projection,
2710                                        is_local_mutation_allowed,
2711                                    })
2712                                }
2713                            }
2714                        } else {
2715                            self.is_mutable(place_base, is_local_mutation_allowed)
2716                        }
2717                    }
2718                }
2719            }
2720        }
2721    }
2722
2723    /// If `place` is a field projection, and the field is being projected from a closure type,
2724    /// then returns the index of the field being projected. Note that this closure will always
2725    /// be `self` in the current MIR, because that is the only time we directly access the fields
2726    /// of a closure type.
2727    fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
2728        path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2729    }
2730
2731    fn dominators(&self) -> &Dominators<BasicBlock> {
2732        // `BasicBlocks` computes dominators on-demand and caches them.
2733        self.body.basic_blocks.dominators()
2734    }
2735
2736    fn lint_unused_mut(&self) {
2737        let tcx = self.infcx.tcx;
2738        let body = self.body;
2739        for local in body.mut_vars_and_args_iter().filter(|local| !self.used_mut.contains(local)) {
2740            let local_decl = &body.local_decls[local];
2741            let ClearCrossCrate::Set(SourceScopeLocalData { lint_root, .. }) =
2742                body.source_scopes[local_decl.source_info.scope].local_data
2743            else {
2744                continue;
2745            };
2746
2747            // Skip over locals that begin with an underscore or have no name
2748            if self.local_excluded_from_unused_mut_lint(local) {
2749                continue;
2750            }
2751
2752            let span = local_decl.source_info.span;
2753            if span.desugaring_kind().is_some() {
2754                // If the `mut` arises as part of a desugaring, we should ignore it.
2755                continue;
2756            }
2757
2758            let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
2759
2760            tcx.emit_node_span_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
2761        }
2762    }
2763}
2764
2765/// The degree of overlap between 2 places for borrow-checking.
2766enum Overlap {
2767    /// The places might partially overlap - in this case, we give
2768    /// up and say that they might conflict. This occurs when
2769    /// different fields of a union are borrowed. For example,
2770    /// if `u` is a union, we have no way of telling how disjoint
2771    /// `u.a.x` and `a.b.y` are.
2772    Arbitrary,
2773    /// The places have the same type, and are either completely disjoint
2774    /// or equal - i.e., they can't "partially" overlap as can occur with
2775    /// unions. This is the "base case" on which we recur for extensions
2776    /// of the place.
2777    EqualOrDisjoint,
2778    /// The places are disjoint, so we know all extensions of them
2779    /// will also be disjoint.
2780    Disjoint,
2781}