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(assert_matches)]
6#![feature(box_patterns)]
7#![feature(default_field_values)]
8#![feature(file_buffered)]
9#![feature(if_let_guard)]
10#![feature(negative_impls)]
11#![feature(never_type)]
12#![feature(rustc_attrs)]
13#![feature(stmt_expr_attributes)]
14#![feature(try_blocks)]
15// tidy-alphabetical-end
16
17use std::borrow::Cow;
18use std::cell::{OnceCell, RefCell};
19use std::marker::PhantomData;
20use std::ops::{ControlFlow, Deref};
21use std::rc::Rc;
22
23use borrow_set::LocalsStateAtExit;
24use polonius_engine::AllFacts;
25use root_cx::BorrowCheckRootCtxt;
26use rustc_abi::FieldIdx;
27use rustc_data_structures::frozen::Frozen;
28use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
29use rustc_data_structures::graph::dominators::Dominators;
30use rustc_errors::LintDiagnostic;
31use rustc_hir as hir;
32use rustc_hir::CRATE_HIR_ID;
33use rustc_hir::def_id::LocalDefId;
34use rustc_index::bit_set::MixedBitSet;
35use rustc_index::{IndexSlice, IndexVec};
36use rustc_infer::infer::outlives::env::RegionBoundPairs;
37use rustc_infer::infer::{
38    InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt,
39};
40use rustc_middle::mir::*;
41use rustc_middle::query::Providers;
42use rustc_middle::ty::{
43    self, ParamEnv, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypingMode, fold_regions,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces};
47use rustc_mir_dataflow::move_paths::{
48    InitIndex, InitLocation, LookupResult, MoveData, MovePathIndex,
49};
50use rustc_mir_dataflow::points::DenseLocationMap;
51use rustc_mir_dataflow::{Analysis, EntryStates, Results, ResultsVisitor, visit_results};
52use rustc_session::lint::builtin::{TAIL_EXPR_DROP_ORDER, UNUSED_MUT};
53use rustc_span::{ErrorGuaranteed, Span, Symbol};
54use smallvec::SmallVec;
55use tracing::{debug, instrument};
56
57use crate::borrow_set::{BorrowData, BorrowSet};
58use crate::consumers::{BodyWithBorrowckFacts, RustcFacts};
59use crate::dataflow::{BorrowIndex, Borrowck, BorrowckDomain, Borrows};
60use crate::diagnostics::{
61    AccessKind, BorrowckDiagnosticsBuffer, IllegalMoveOriginKind, MoveError, RegionName,
62};
63use crate::path_utils::*;
64use crate::place_ext::PlaceExt;
65use crate::places_conflict::{PlaceConflictBias, places_conflict};
66use crate::polonius::legacy::{
67    PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput,
68};
69use crate::polonius::{PoloniusContext, PoloniusDiagnosticsContext};
70use crate::prefixes::PrefixSet;
71use crate::region_infer::RegionInferenceContext;
72use crate::region_infer::opaque_types::DeferredOpaqueTypeError;
73use crate::renumber::RegionCtxt;
74use crate::session_diagnostics::VarNeedNotMut;
75use crate::type_check::free_region_relations::UniversalRegionRelations;
76use crate::type_check::{Locations, MirTypeckRegionConstraints, MirTypeckResults};
77
78mod borrow_set;
79mod borrowck_errors;
80mod constraints;
81mod dataflow;
82mod def_use;
83mod diagnostics;
84mod handle_placeholders;
85mod nll;
86mod path_utils;
87mod place_ext;
88mod places_conflict;
89mod polonius;
90mod prefixes;
91mod region_infer;
92mod renumber;
93mod root_cx;
94mod session_diagnostics;
95mod type_check;
96mod universal_regions;
97mod used_muts;
98
99/// A public API provided for the Rust compiler consumers.
100pub mod consumers;
101
102/// Associate some local constants with the `'tcx` lifetime
103struct TyCtxtConsts<'tcx>(PhantomData<&'tcx ()>);
104
105impl<'tcx> TyCtxtConsts<'tcx> {
106    const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
107}
108
109pub fn provide(providers: &mut Providers) {
110    *providers = Providers { mir_borrowck, ..*providers };
111}
112
113/// Provider for `query mir_borrowck`. Unlike `typeck`, this must
114/// only be called for typeck roots which *similar* to `typeck` will
115/// then borrowck all nested bodies as well.
116fn mir_borrowck(
117    tcx: TyCtxt<'_>,
118    def: LocalDefId,
119) -> Result<&FxIndexMap<LocalDefId, ty::DefinitionSiteHiddenType<'_>>, ErrorGuaranteed> {
120    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()));
121    let (input_body, _) = tcx.mir_promoted(def);
122    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:122",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(122u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("run query mir_borrowck: {0}",
                                                    tcx.def_path_str(def)) as &dyn Value))])
            });
    } else { ; }
};debug!("run query mir_borrowck: {}", tcx.def_path_str(def));
123
124    let input_body: &Body<'_> = &input_body.borrow();
125    if let Some(guar) = input_body.tainted_by_errors {
126        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:126",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Skipping borrowck because of tainted body")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("Skipping borrowck because of tainted body");
127        Err(guar)
128    } else if input_body.should_skip() {
129        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:129",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(129u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Skipping borrowck because of injected body")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("Skipping borrowck because of injected body");
130        let opaque_types = Default::default();
131        Ok(tcx.arena.alloc(opaque_types))
132    } else {
133        let mut root_cx = BorrowCheckRootCtxt::new(tcx, def, None);
134        root_cx.do_mir_borrowck();
135        root_cx.finalize()
136    }
137}
138
139/// Data propagated to the typeck parent by nested items.
140/// This should always be empty for the typeck root.
141#[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)]
142struct PropagatedBorrowCheckResults<'tcx> {
143    closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
144    used_mut_upvars: SmallVec<[FieldIdx; 8]>,
145}
146
147type DeferredClosureRequirements<'tcx> = Vec<(LocalDefId, ty::GenericArgsRef<'tcx>, Locations)>;
148
149/// After we borrow check a closure, we are left with various
150/// requirements that we have inferred between the free regions that
151/// appear in the closure's signature or on its field types. These
152/// requirements are then verified and proved by the closure's
153/// creating function. This struct encodes those requirements.
154///
155/// The requirements are listed as being between various `RegionVid`. The 0th
156/// region refers to `'static`; subsequent region vids refer to the free
157/// regions that appear in the closure (or coroutine's) type, in order of
158/// appearance. (This numbering is actually defined by the `UniversalRegions`
159/// struct in the NLL region checker. See for example
160/// `UniversalRegions::closure_mapping`.) Note the free regions in the
161/// closure's signature and captures are erased.
162///
163/// Example: If type check produces a closure with the closure args:
164///
165/// ```text
166/// ClosureArgs = [
167///     'a,                                         // From the parent.
168///     'b,
169///     i8,                                         // the "closure kind"
170///     for<'x> fn(&'<erased> &'x u32) -> &'x u32,  // the "closure signature"
171///     &'<erased> String,                          // some upvar
172/// ]
173/// ```
174///
175/// We would "renumber" each free region to a unique vid, as follows:
176///
177/// ```text
178/// ClosureArgs = [
179///     '1,                                         // From the parent.
180///     '2,
181///     i8,                                         // the "closure kind"
182///     for<'x> fn(&'3 &'x u32) -> &'x u32,         // the "closure signature"
183///     &'4 String,                                 // some upvar
184/// ]
185/// ```
186///
187/// Now the code might impose a requirement like `'1: '2`. When an
188/// instance of the closure is created, the corresponding free regions
189/// can be extracted from its type and constrained to have the given
190/// outlives relationship.
191#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureRegionRequirements<'tcx> {
    #[inline]
    fn clone(&self) -> ClosureRegionRequirements<'tcx> {
        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)]
192pub struct ClosureRegionRequirements<'tcx> {
193    /// The number of external regions defined on the closure. In our
194    /// example above, it would be 3 -- one for `'static`, then `'1`
195    /// and `'2`. This is just used for a sanity check later on, to
196    /// make sure that the number of regions we see at the callsite
197    /// matches.
198    pub num_external_vids: usize,
199
200    /// Requirements between the various free regions defined in
201    /// indices.
202    pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
203}
204
205/// Indicates an outlives-constraint between a type or between two
206/// free regions declared on the closure.
207#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesRequirement<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesRequirement<'tcx> {
    #[inline]
    fn clone(&self) -> ClosureOutlivesRequirement<'tcx> {
        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)]
208pub struct ClosureOutlivesRequirement<'tcx> {
209    // This region or type ...
210    pub subject: ClosureOutlivesSubject<'tcx>,
211
212    // ... must outlive this one.
213    pub outlived_free_region: ty::RegionVid,
214
215    // If not, report an error here ...
216    pub blame_span: Span,
217
218    // ... due to this reason.
219    pub category: ConstraintCategory<'tcx>,
220}
221
222// Make sure this enum doesn't unintentionally grow
223#[cfg(target_pointer_width = "64")]
224const _: [(); 16] = [(); ::std::mem::size_of::<ConstraintCategory<'_>>()];rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 16);
225
226/// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
227/// that must outlive some region.
228#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesSubject<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesSubject<'tcx> {
    #[inline]
    fn clone(&self) -> ClosureOutlivesSubject<'tcx> {
        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 {
            ClosureOutlivesSubject::Ty(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
                    &__self_0),
            ClosureOutlivesSubject::Region(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Region",
                    &__self_0),
        }
    }
}Debug)]
229pub enum ClosureOutlivesSubject<'tcx> {
230    /// Subject is a type, typically a type parameter, but could also
231    /// be a projection. Indicates a requirement like `T: 'a` being
232    /// passed to the caller, where the type here is `T`.
233    Ty(ClosureOutlivesSubjectTy<'tcx>),
234
235    /// Subject is a free region from the closure. Indicates a requirement
236    /// like `'a: 'b` being passed to the caller; the region here is `'a`.
237    Region(ty::RegionVid),
238}
239
240/// Represents a `ty::Ty` for use in [`ClosureOutlivesSubject`].
241///
242/// This abstraction is necessary because the type may include `ReVar` regions,
243/// which is what we use internally within NLL code, and they can't be used in
244/// a query response.
245#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureOutlivesSubjectTy<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureOutlivesSubjectTy<'tcx> {
    #[inline]
    fn clone(&self) -> ClosureOutlivesSubjectTy<'tcx> {
        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)]
246pub struct ClosureOutlivesSubjectTy<'tcx> {
247    inner: Ty<'tcx>,
248}
249// DO NOT implement `TypeVisitable` or `TypeFoldable` traits, because this
250// type is not recognized as a binder for late-bound region.
251impl<'tcx, I> !TypeVisitable<I> for ClosureOutlivesSubjectTy<'tcx> {}
252impl<'tcx, I> !TypeFoldable<I> for ClosureOutlivesSubjectTy<'tcx> {}
253
254impl<'tcx> ClosureOutlivesSubjectTy<'tcx> {
255    /// All regions of `ty` must be of kind `ReVar` and must represent
256    /// universal regions *external* to the closure.
257    pub fn bind(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
258        let inner = fold_regions(tcx, ty, |r, depth| match r.kind() {
259            ty::ReVar(vid) => {
260                let br = ty::BoundRegion {
261                    var: ty::BoundVar::from_usize(vid.index()),
262                    kind: ty::BoundRegionKind::Anon,
263                };
264                ty::Region::new_bound(tcx, depth, br)
265            }
266            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected region in ClosureOutlivesSubjectTy: {0:?}",
        r))bug!("unexpected region in ClosureOutlivesSubjectTy: {r:?}"),
267        });
268
269        Self { inner }
270    }
271
272    pub fn instantiate(
273        self,
274        tcx: TyCtxt<'tcx>,
275        mut map: impl FnMut(ty::RegionVid) -> ty::Region<'tcx>,
276    ) -> Ty<'tcx> {
277        fold_regions(tcx, self.inner, |r, depth| match r.kind() {
278            ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), br) => {
279                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);
280                map(ty::RegionVid::from_usize(br.var.index()))
281            }
282            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected region {0:?}", r))bug!("unexpected region {r:?}"),
283        })
284    }
285}
286
287struct CollectRegionConstraintsResult<'tcx> {
288    infcx: BorrowckInferCtxt<'tcx>,
289    body_owned: Body<'tcx>,
290    promoted: IndexVec<Promoted, Body<'tcx>>,
291    move_data: MoveData<'tcx>,
292    borrow_set: BorrowSet<'tcx>,
293    location_table: PoloniusLocationTable,
294    location_map: Rc<DenseLocationMap>,
295    universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
296    region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
297    known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesPredicate<'tcx>>>,
298    constraints: MirTypeckRegionConstraints<'tcx>,
299    deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
300    deferred_opaque_type_errors: Vec<DeferredOpaqueTypeError<'tcx>>,
301    polonius_facts: Option<AllFacts<RustcFacts>>,
302    polonius_context: Option<PoloniusContext>,
303}
304
305/// Start borrow checking by collecting the region constraints for
306/// the current body. This initializes the relevant data structures
307/// and then type checks the MIR body.
308fn borrowck_collect_region_constraints<'tcx>(
309    root_cx: &mut BorrowCheckRootCtxt<'tcx>,
310    def: LocalDefId,
311) -> CollectRegionConstraintsResult<'tcx> {
312    let tcx = root_cx.tcx;
313    let infcx = BorrowckInferCtxt::new(tcx, def, root_cx.root_def_id());
314    let (input_body, promoted) = tcx.mir_promoted(def);
315    let input_body: &Body<'_> = &input_body.borrow();
316    let input_promoted: &IndexSlice<_, _> = &promoted.borrow();
317    if let Some(e) = input_body.tainted_by_errors {
318        infcx.set_tainted_by_errors(e);
319        root_cx.set_tainted_by_errors(e);
320    }
321
322    // Replace all regions with fresh inference variables. This
323    // requires first making our own copy of the MIR. This copy will
324    // be modified (in place) to contain non-lexical lifetimes. It
325    // will have a lifetime tied to the inference context.
326    let mut body_owned = input_body.clone();
327    let mut promoted = input_promoted.to_owned();
328    let universal_regions = nll::replace_regions_in_mir(&infcx, &mut body_owned, &mut promoted);
329    let body = &body_owned; // no further changes
330
331    let location_table = PoloniusLocationTable::new(body);
332
333    let move_data = MoveData::gather_moves(body, tcx, |_| true);
334
335    let locals_are_invalidated_at_exit = tcx.hir_body_owner_kind(def).is_fn_or_closure();
336    let borrow_set = BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &move_data);
337
338    let location_map = Rc::new(DenseLocationMap::new(body));
339
340    let polonius_input = root_cx.consumer.as_ref().map_or(false, |c| c.polonius_input())
341        || infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
342    let mut polonius_facts =
343        (polonius_input || PoloniusFacts::enabled(infcx.tcx)).then_some(PoloniusFacts::default());
344
345    // Run the MIR type-checker.
346    let MirTypeckResults {
347        constraints,
348        universal_region_relations,
349        region_bound_pairs,
350        known_type_outlives_obligations,
351        deferred_closure_requirements,
352        polonius_context,
353    } = type_check::type_check(
354        root_cx,
355        &infcx,
356        body,
357        &promoted,
358        universal_regions,
359        &location_table,
360        &borrow_set,
361        &mut polonius_facts,
362        &move_data,
363        Rc::clone(&location_map),
364    );
365
366    CollectRegionConstraintsResult {
367        infcx,
368        body_owned,
369        promoted,
370        move_data,
371        borrow_set,
372        location_table,
373        location_map,
374        universal_region_relations,
375        region_bound_pairs,
376        known_type_outlives_obligations,
377        constraints,
378        deferred_closure_requirements,
379        deferred_opaque_type_errors: Default::default(),
380        polonius_facts,
381        polonius_context,
382    }
383}
384
385/// Using the region constraints computed by [borrowck_collect_region_constraints]
386/// and the additional constraints from [BorrowCheckRootCtxt::handle_opaque_type_uses],
387/// compute the region graph and actually check for any borrowck errors.
388fn borrowck_check_region_constraints<'tcx>(
389    root_cx: &mut BorrowCheckRootCtxt<'tcx>,
390    CollectRegionConstraintsResult {
391        infcx,
392        body_owned,
393        promoted,
394        move_data,
395        borrow_set,
396        location_table,
397        location_map,
398        universal_region_relations,
399        region_bound_pairs: _,
400        known_type_outlives_obligations: _,
401        constraints,
402        deferred_closure_requirements,
403        deferred_opaque_type_errors,
404        polonius_facts,
405        polonius_context,
406    }: CollectRegionConstraintsResult<'tcx>,
407) -> PropagatedBorrowCheckResults<'tcx> {
408    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());
409    if !deferred_closure_requirements.is_empty() {
    ::core::panicking::panic("assertion failed: deferred_closure_requirements.is_empty()")
};assert!(deferred_closure_requirements.is_empty());
410    let tcx = root_cx.tcx;
411    let body = &body_owned;
412    let def = body.source.def_id().expect_local();
413
414    // Compute non-lexical lifetimes using the constraints computed
415    // by typechecking the MIR body.
416    let nll::NllOutput {
417        regioncx,
418        polonius_input,
419        polonius_output,
420        opt_closure_req,
421        nll_errors,
422        polonius_diagnostics,
423    } = nll::compute_regions(
424        root_cx,
425        &infcx,
426        body,
427        &location_table,
428        &move_data,
429        &borrow_set,
430        location_map,
431        universal_region_relations,
432        constraints,
433        polonius_facts,
434        polonius_context,
435    );
436
437    // Dump MIR results into a file, if that is enabled. This lets us
438    // write unit-tests, as well as helping with debugging.
439    nll::dump_nll_mir(&infcx, body, &regioncx, &opt_closure_req, &borrow_set);
440    polonius::dump_polonius_mir(
441        &infcx,
442        body,
443        &regioncx,
444        &opt_closure_req,
445        &borrow_set,
446        polonius_diagnostics.as_ref(),
447    );
448
449    // We also have a `#[rustc_regions]` annotation that causes us to dump
450    // information.
451    nll::dump_annotation(&infcx, body, &regioncx, &opt_closure_req);
452
453    let movable_coroutine = body.coroutine.is_some()
454        && tcx.coroutine_movability(def.to_def_id()) == hir::Movability::Movable;
455
456    let diags_buffer = &mut BorrowckDiagnosticsBuffer::default();
457    // While promoteds should mostly be correct by construction, we need to check them for
458    // invalid moves to detect moving out of arrays:`struct S; fn main() { &([S][0]); }`.
459    for promoted_body in &promoted {
460        use rustc_middle::mir::visit::Visitor;
461        // This assumes that we won't use some of the fields of the `promoted_mbcx`
462        // when detecting and reporting move errors. While it would be nice to move
463        // this check out of `MirBorrowckCtxt`, actually doing so is far from trivial.
464        let move_data = MoveData::gather_moves(promoted_body, tcx, |_| true);
465        let mut promoted_mbcx = MirBorrowckCtxt {
466            root_cx,
467            infcx: &infcx,
468            body: promoted_body,
469            move_data: &move_data,
470            // no need to create a real location table for the promoted, it is not used
471            location_table: &location_table,
472            movable_coroutine,
473            fn_self_span_reported: Default::default(),
474            access_place_error_reported: Default::default(),
475            reservation_error_reported: Default::default(),
476            uninitialized_error_reported: Default::default(),
477            regioncx: &regioncx,
478            used_mut: Default::default(),
479            used_mut_upvars: SmallVec::new(),
480            borrow_set: &borrow_set,
481            upvars: &[],
482            local_names: OnceCell::from(IndexVec::from_elem(None, &promoted_body.local_decls)),
483            region_names: RefCell::default(),
484            next_region_name: RefCell::new(1),
485            polonius_output: None,
486            move_errors: Vec::new(),
487            diags_buffer,
488            polonius_diagnostics: polonius_diagnostics.as_ref(),
489        };
490        struct MoveVisitor<'a, 'b, 'infcx, 'tcx> {
491            ctxt: &'a mut MirBorrowckCtxt<'b, 'infcx, 'tcx>,
492        }
493
494        impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, '_, 'tcx> {
495            fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
496                if let Operand::Move(place) = operand {
497                    self.ctxt.check_movable_place(location, *place);
498                }
499            }
500        }
501        MoveVisitor { ctxt: &mut promoted_mbcx }.visit_body(promoted_body);
502        promoted_mbcx.report_move_errors();
503    }
504
505    let mut mbcx = MirBorrowckCtxt {
506        root_cx,
507        infcx: &infcx,
508        body,
509        move_data: &move_data,
510        location_table: &location_table,
511        movable_coroutine,
512        fn_self_span_reported: Default::default(),
513        access_place_error_reported: Default::default(),
514        reservation_error_reported: Default::default(),
515        uninitialized_error_reported: Default::default(),
516        regioncx: &regioncx,
517        used_mut: Default::default(),
518        used_mut_upvars: SmallVec::new(),
519        borrow_set: &borrow_set,
520        upvars: tcx.closure_captures(def),
521        local_names: OnceCell::new(),
522        region_names: RefCell::default(),
523        next_region_name: RefCell::new(1),
524        move_errors: Vec::new(),
525        diags_buffer,
526        polonius_output: polonius_output.as_deref(),
527        polonius_diagnostics: polonius_diagnostics.as_ref(),
528    };
529
530    // Compute and report region errors, if any.
531    if nll_errors.is_empty() {
532        mbcx.report_opaque_type_errors(deferred_opaque_type_errors);
533    } else {
534        mbcx.report_region_errors(nll_errors);
535    }
536
537    let flow_results = get_flow_results(tcx, body, &move_data, &borrow_set, &regioncx);
538    visit_results(
539        body,
540        traversal::reverse_postorder(body).map(|(bb, _)| bb),
541        &flow_results,
542        &mut mbcx,
543    );
544
545    mbcx.report_move_errors();
546
547    // For each non-user used mutable variable, check if it's been assigned from
548    // a user-declared local. If so, then put that local into the used_mut set.
549    // Note that this set is expected to be small - only upvars from closures
550    // would have a chance of erroneously adding non-user-defined mutable vars
551    // to the set.
552    let temporary_used_locals: FxIndexSet<Local> = mbcx
553        .used_mut
554        .iter()
555        .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
556        .cloned()
557        .collect();
558    // For the remaining unused locals that are marked as mutable, we avoid linting any that
559    // were never initialized. These locals may have been removed as unreachable code; or will be
560    // linted as unused variables.
561    let unused_mut_locals =
562        mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
563    mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
564
565    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:565",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(565u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("mbcx.used_mut: {0:?}",
                                                    mbcx.used_mut) as &dyn Value))])
            });
    } else { ; }
};debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
566    mbcx.lint_unused_mut();
567    if let Some(guar) = mbcx.emit_errors() {
568        mbcx.root_cx.set_tainted_by_errors(guar);
569    }
570
571    let result = PropagatedBorrowCheckResults {
572        closure_requirements: opt_closure_req,
573        used_mut_upvars: mbcx.used_mut_upvars,
574    };
575
576    if let Some(consumer) = &mut root_cx.consumer {
577        consumer.insert_body(
578            def,
579            BodyWithBorrowckFacts {
580                body: body_owned,
581                promoted,
582                borrow_set,
583                region_inference_context: regioncx,
584                location_table: polonius_input.as_ref().map(|_| location_table),
585                input_facts: polonius_input,
586                output_facts: polonius_output,
587            },
588        );
589    }
590
591    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:591",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(591u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("do_mir_borrowck: result = {0:#?}",
                                                    result) as &dyn Value))])
            });
    } else { ; }
};debug!("do_mir_borrowck: result = {:#?}", result);
592
593    result
594}
595
596fn get_flow_results<'a, 'tcx>(
597    tcx: TyCtxt<'tcx>,
598    body: &'a Body<'tcx>,
599    move_data: &'a MoveData<'tcx>,
600    borrow_set: &'a BorrowSet<'tcx>,
601    regioncx: &RegionInferenceContext<'tcx>,
602) -> Results<'tcx, Borrowck<'a, 'tcx>> {
603    // We compute these three analyses individually, but them combine them into
604    // a single results so that `mbcx` can visit them all together.
605    let borrows = Borrows::new(tcx, body, regioncx, borrow_set).iterate_to_fixpoint(
606        tcx,
607        body,
608        Some("borrowck"),
609    );
610    let uninits = MaybeUninitializedPlaces::new(tcx, body, move_data).iterate_to_fixpoint(
611        tcx,
612        body,
613        Some("borrowck"),
614    );
615    let ever_inits = EverInitializedPlaces::new(body, move_data).iterate_to_fixpoint(
616        tcx,
617        body,
618        Some("borrowck"),
619    );
620
621    let analysis = Borrowck {
622        borrows: borrows.analysis,
623        uninits: uninits.analysis,
624        ever_inits: ever_inits.analysis,
625    };
626
627    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());
628    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());
629    let entry_states: EntryStates<_> =
630        ::itertools::__std_iter::IntoIterator::into_iter(borrows.entry_states).zip(uninits.entry_states).zip(ever_inits.entry_states).map(|((a,
            b), b)| (a, b, b))itertools::izip!(borrows.entry_states, uninits.entry_states, ever_inits.entry_states)
631            .map(|(borrows, uninits, ever_inits)| BorrowckDomain { borrows, uninits, ever_inits })
632            .collect();
633
634    Results { analysis, entry_states }
635}
636
637pub(crate) struct BorrowckInferCtxt<'tcx> {
638    pub(crate) infcx: InferCtxt<'tcx>,
639    pub(crate) root_def_id: LocalDefId,
640    pub(crate) param_env: ParamEnv<'tcx>,
641    pub(crate) reg_var_to_origin: RefCell<FxIndexMap<ty::RegionVid, RegionCtxt>>,
642}
643
644impl<'tcx> BorrowckInferCtxt<'tcx> {
645    pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, root_def_id: LocalDefId) -> Self {
646        let typing_mode = if tcx.use_typing_mode_borrowck() {
647            TypingMode::borrowck(tcx, def_id)
648        } else {
649            TypingMode::analysis_in_body(tcx, def_id)
650        };
651        let infcx = tcx.infer_ctxt().build(typing_mode);
652        let param_env = tcx.param_env(def_id);
653        BorrowckInferCtxt {
654            infcx,
655            root_def_id,
656            reg_var_to_origin: RefCell::new(Default::default()),
657            param_env,
658        }
659    }
660
661    pub(crate) fn next_region_var<F>(
662        &self,
663        origin: RegionVariableOrigin<'tcx>,
664        get_ctxt_fn: F,
665    ) -> ty::Region<'tcx>
666    where
667        F: Fn() -> RegionCtxt,
668    {
669        let next_region = self.infcx.next_region_var(origin);
670        let vid = next_region.as_var();
671
672        if truecfg!(debug_assertions) {
673            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:673",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(673u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("inserting vid {0:?} with origin {1:?} into var_to_origin",
                                                    vid, origin) as &dyn Value))])
            });
    } else { ; }
};debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
674            let ctxt = get_ctxt_fn();
675            let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
676            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);
677        }
678
679        next_region
680    }
681
682    #[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("compiler/rustc_borrowck/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(682u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                    ::tracing_core::field::FieldSet::new(&["origin"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                            as &dyn 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 compiler/rustc_borrowck/src/lib.rs:695",
                                        "rustc_borrowck", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                                        ::tracing_core::__macro_support::Option::Some(695u32),
                                        ::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};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("inserting vid {0:?} with origin {1:?} into var_to_origin",
                                                                    vid, origin) as &dyn 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")]
683    pub(crate) fn next_nll_region_var<F>(
684        &self,
685        origin: NllRegionVariableOrigin<'tcx>,
686        get_ctxt_fn: F,
687    ) -> ty::Region<'tcx>
688    where
689        F: Fn() -> RegionCtxt,
690    {
691        let next_region = self.infcx.next_nll_region_var(origin);
692        let vid = next_region.as_var();
693
694        if cfg!(debug_assertions) {
695            debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
696            let ctxt = get_ctxt_fn();
697            let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
698            assert_eq!(var_to_origin.insert(vid, ctxt), None);
699        }
700
701        next_region
702    }
703}
704
705impl<'tcx> Deref for BorrowckInferCtxt<'tcx> {
706    type Target = InferCtxt<'tcx>;
707
708    fn deref(&self) -> &Self::Target {
709        &self.infcx
710    }
711}
712
713struct MirBorrowckCtxt<'a, 'infcx, 'tcx> {
714    root_cx: &'a mut BorrowCheckRootCtxt<'tcx>,
715    infcx: &'infcx BorrowckInferCtxt<'tcx>,
716    body: &'a Body<'tcx>,
717    move_data: &'a MoveData<'tcx>,
718
719    /// Map from MIR `Location` to `LocationIndex`; created
720    /// when MIR borrowck begins.
721    location_table: &'a PoloniusLocationTable,
722
723    movable_coroutine: bool,
724    /// This field keeps track of when borrow errors are reported in the access_place function
725    /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
726    /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
727    /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
728    /// errors.
729    access_place_error_reported: FxIndexSet<(Place<'tcx>, Span)>,
730    /// This field keeps track of when borrow conflict errors are reported
731    /// for reservations, so that we don't report seemingly duplicate
732    /// errors for corresponding activations.
733    //
734    // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
735    // but it is currently inconvenient to track down the `BorrowIndex`
736    // at the time we detect and report a reservation error.
737    reservation_error_reported: FxIndexSet<Place<'tcx>>,
738    /// This fields keeps track of the `Span`s that we have
739    /// used to report extra information for `FnSelfUse`, to avoid
740    /// unnecessarily verbose errors.
741    fn_self_span_reported: FxIndexSet<Span>,
742    /// This field keeps track of errors reported in the checking of uninitialized variables,
743    /// so that we don't report seemingly duplicate errors.
744    uninitialized_error_reported: FxIndexSet<Local>,
745    /// This field keeps track of all the local variables that are declared mut and are mutated.
746    /// Used for the warning issued by an unused mutable local variable.
747    used_mut: FxIndexSet<Local>,
748    /// If the function we're checking is a closure, then we'll need to report back the list of
749    /// mutable upvars that have been used. This field keeps track of them.
750    used_mut_upvars: SmallVec<[FieldIdx; 8]>,
751    /// Region inference context. This contains the results from region inference and lets us e.g.
752    /// find out which CFG points are contained in each borrow region.
753    regioncx: &'a RegionInferenceContext<'tcx>,
754
755    /// The set of borrows extracted from the MIR
756    borrow_set: &'a BorrowSet<'tcx>,
757
758    /// Information about upvars not necessarily preserved in types or MIR
759    upvars: &'tcx [&'tcx ty::CapturedPlace<'tcx>],
760
761    /// Names of local (user) variables (extracted from `var_debug_info`).
762    local_names: OnceCell<IndexVec<Local, Option<Symbol>>>,
763
764    /// Record the region names generated for each region in the given
765    /// MIR def so that we can reuse them later in help/error messages.
766    region_names: RefCell<FxIndexMap<RegionVid, RegionName>>,
767
768    /// The counter for generating new region names.
769    next_region_name: RefCell<usize>,
770
771    diags_buffer: &'a mut BorrowckDiagnosticsBuffer<'infcx, 'tcx>,
772    move_errors: Vec<MoveError<'tcx>>,
773
774    /// Results of Polonius analysis.
775    polonius_output: Option<&'a PoloniusOutput>,
776    /// When using `-Zpolonius=next`: the data used to compute errors and diagnostics.
777    polonius_diagnostics: Option<&'a PoloniusDiagnosticsContext>,
778}
779
780// Check that:
781// 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
782// 2. loans made in overlapping scopes do not conflict
783// 3. assignments do not affect things loaned out as immutable
784// 4. moves do not affect things loaned out in any way
785impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
786    fn visit_after_early_statement_effect(
787        &mut self,
788        _analysis: &Borrowck<'a, 'tcx>,
789        state: &BorrowckDomain,
790        stmt: &Statement<'tcx>,
791        location: Location,
792    ) {
793        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:793",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(793u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("MirBorrowckCtxt::process_statement({0:?}, {1:?}): {2:?}",
                                                    location, stmt, state) as &dyn Value))])
            });
    } else { ; }
};debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
794        let span = stmt.source_info.span;
795
796        self.check_activations(location, span, state);
797
798        match &stmt.kind {
799            StatementKind::Assign(box (lhs, rhs)) => {
800                self.consume_rvalue(location, (rhs, span), state);
801
802                self.mutate_place(location, (*lhs, span), Shallow(None), state);
803            }
804            StatementKind::FakeRead(box (_, place)) => {
805                // Read for match doesn't access any memory and is used to
806                // assert that a place is safe and live. So we don't have to
807                // do any checks here.
808                //
809                // FIXME: Remove check that the place is initialized. This is
810                // needed for now because matches don't have never patterns yet.
811                // So this is the only place we prevent
812                //      let x: !;
813                //      match x {};
814                // from compiling.
815                self.check_if_path_or_subpath_is_moved(
816                    location,
817                    InitializationRequiringAction::Use,
818                    (place.as_ref(), span),
819                    state,
820                );
821            }
822            StatementKind::Intrinsic(box kind) => match kind {
823                NonDivergingIntrinsic::Assume(op) => {
824                    self.consume_operand(location, (op, span), state);
825                }
826                NonDivergingIntrinsic::CopyNonOverlapping(..) => ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("Unexpected CopyNonOverlapping, should only appear after lower_intrinsics"))span_bug!(
827                    span,
828                    "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
829                )
830            }
831            // Only relevant for mir typeck
832            StatementKind::AscribeUserType(..)
833            // Only relevant for liveness and unsafeck
834            | StatementKind::PlaceMention(..)
835            // Doesn't have any language semantics
836            | StatementKind::Coverage(..)
837            // These do not actually affect borrowck
838            | StatementKind::ConstEvalCounter
839            | StatementKind::StorageLive(..) => {}
840            // This does not affect borrowck
841            StatementKind::BackwardIncompatibleDropHint { place, reason: BackwardIncompatibleDropReason::Edition2024 } => {
842                self.check_backward_incompatible_drop(location, **place, state);
843            }
844            StatementKind::StorageDead(local) => {
845                self.access_place(
846                    location,
847                    (Place::from(*local), span),
848                    (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
849                    LocalMutationIsAllowed::Yes,
850                    state,
851                );
852            }
853            StatementKind::Nop
854            | StatementKind::Retag { .. }
855            | StatementKind::SetDiscriminant { .. } => {
856                ::rustc_middle::util::bug::bug_fmt(format_args!("Statement not allowed in this MIR phase"))bug!("Statement not allowed in this MIR phase")
857            }
858        }
859    }
860
861    fn visit_after_early_terminator_effect(
862        &mut self,
863        _analysis: &Borrowck<'a, 'tcx>,
864        state: &BorrowckDomain,
865        term: &Terminator<'tcx>,
866        loc: Location,
867    ) {
868        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:868",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(868u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("MirBorrowckCtxt::process_terminator({0:?}, {1:?}): {2:?}",
                                                    loc, term, state) as &dyn Value))])
            });
    } else { ; }
};debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
869        let span = term.source_info.span;
870
871        self.check_activations(loc, span, state);
872
873        match &term.kind {
874            TerminatorKind::SwitchInt { discr, targets: _ } => {
875                self.consume_operand(loc, (discr, span), state);
876            }
877            TerminatorKind::Drop {
878                place,
879                target: _,
880                unwind: _,
881                replace,
882                drop: _,
883                async_fut: _,
884            } => {
885                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:885",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(885u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("visit_terminator_drop loc: {0:?} term: {1:?} place: {2:?} span: {3:?}",
                                                    loc, term, place, span) as &dyn Value))])
            });
    } else { ; }
};debug!(
886                    "visit_terminator_drop \
887                     loc: {:?} term: {:?} place: {:?} span: {:?}",
888                    loc, term, place, span
889                );
890
891                let write_kind =
892                    if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
893                self.access_place(
894                    loc,
895                    (*place, span),
896                    (AccessDepth::Drop, Write(write_kind)),
897                    LocalMutationIsAllowed::Yes,
898                    state,
899                );
900            }
901            TerminatorKind::Call {
902                func,
903                args,
904                destination,
905                target: _,
906                unwind: _,
907                call_source: _,
908                fn_span: _,
909            } => {
910                self.consume_operand(loc, (func, span), state);
911                for arg in args {
912                    self.consume_operand(loc, (&arg.node, arg.span), state);
913                }
914                self.mutate_place(loc, (*destination, span), Deep, state);
915            }
916            TerminatorKind::TailCall { func, args, fn_span: _ } => {
917                self.consume_operand(loc, (func, span), state);
918                for arg in args {
919                    self.consume_operand(loc, (&arg.node, arg.span), state);
920                }
921            }
922            TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
923                self.consume_operand(loc, (cond, span), state);
924                if let AssertKind::BoundsCheck { len, index } = &**msg {
925                    self.consume_operand(loc, (len, span), state);
926                    self.consume_operand(loc, (index, span), state);
927                }
928            }
929
930            TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
931                self.consume_operand(loc, (value, span), state);
932                self.mutate_place(loc, (*resume_arg, span), Deep, state);
933            }
934
935            TerminatorKind::InlineAsm {
936                asm_macro: _,
937                template: _,
938                operands,
939                options: _,
940                line_spans: _,
941                targets: _,
942                unwind: _,
943            } => {
944                for op in operands {
945                    match op {
946                        InlineAsmOperand::In { reg: _, value } => {
947                            self.consume_operand(loc, (value, span), state);
948                        }
949                        InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
950                            if let Some(place) = place {
951                                self.mutate_place(loc, (*place, span), Shallow(None), state);
952                            }
953                        }
954                        InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
955                            self.consume_operand(loc, (in_value, span), state);
956                            if let &Some(out_place) = out_place {
957                                self.mutate_place(loc, (out_place, span), Shallow(None), state);
958                            }
959                        }
960                        InlineAsmOperand::Const { value: _ }
961                        | InlineAsmOperand::SymFn { value: _ }
962                        | InlineAsmOperand::SymStatic { def_id: _ }
963                        | InlineAsmOperand::Label { target_index: _ } => {}
964                    }
965                }
966            }
967
968            TerminatorKind::Goto { target: _ }
969            | TerminatorKind::UnwindTerminate(_)
970            | TerminatorKind::Unreachable
971            | TerminatorKind::UnwindResume
972            | TerminatorKind::Return
973            | TerminatorKind::CoroutineDrop
974            | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
975            | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
976                // no data used, thus irrelevant to borrowck
977            }
978        }
979    }
980
981    fn visit_after_primary_terminator_effect(
982        &mut self,
983        _analysis: &Borrowck<'a, 'tcx>,
984        state: &BorrowckDomain,
985        term: &Terminator<'tcx>,
986        loc: Location,
987    ) {
988        let span = term.source_info.span;
989
990        match term.kind {
991            TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
992                if self.movable_coroutine {
993                    // Look for any active borrows to locals
994                    for i in state.borrows.iter() {
995                        let borrow = &self.borrow_set[i];
996                        self.check_for_local_borrow(borrow, span);
997                    }
998                }
999            }
1000
1001            TerminatorKind::UnwindResume
1002            | TerminatorKind::Return
1003            | TerminatorKind::TailCall { .. }
1004            | TerminatorKind::CoroutineDrop => {
1005                match self.borrow_set.locals_state_at_exit() {
1006                    LocalsStateAtExit::AllAreInvalidated => {
1007                        // Returning from the function implicitly kills storage for all locals and statics.
1008                        // Often, the storage will already have been killed by an explicit
1009                        // StorageDead, but we don't always emit those (notably on unwind paths),
1010                        // so this "extra check" serves as a kind of backup.
1011                        for i in state.borrows.iter() {
1012                            let borrow = &self.borrow_set[i];
1013                            self.check_for_invalidation_at_exit(loc, borrow, span);
1014                        }
1015                    }
1016                    // If we do not implicitly invalidate all locals on exit,
1017                    // we check for conflicts when dropping or moving this local.
1018                    LocalsStateAtExit::SomeAreInvalidated { has_storage_dead_or_moved: _ } => {}
1019                }
1020            }
1021
1022            TerminatorKind::UnwindTerminate(_)
1023            | TerminatorKind::Assert { .. }
1024            | TerminatorKind::Call { .. }
1025            | TerminatorKind::Drop { .. }
1026            | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
1027            | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
1028            | TerminatorKind::Goto { .. }
1029            | TerminatorKind::SwitchInt { .. }
1030            | TerminatorKind::Unreachable
1031            | TerminatorKind::InlineAsm { .. } => {}
1032        }
1033    }
1034}
1035
1036use self::AccessDepth::{Deep, Shallow};
1037use self::ReadOrWrite::{Activation, Read, Reservation, Write};
1038
1039#[derive(#[automatically_derived]
impl ::core::marker::Copy for ArtificialField { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ArtificialField {
    #[inline]
    fn clone(&self) -> ArtificialField { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ArtificialField {
    #[inline]
    fn eq(&self, other: &ArtificialField) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ArtificialField {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {}
}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)]
1040enum ArtificialField {
1041    ArrayLength,
1042    FakeBorrow,
1043}
1044
1045#[derive(#[automatically_derived]
impl ::core::marker::Copy for AccessDepth { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AccessDepth {
    #[inline]
    fn clone(&self) -> AccessDepth {
        let _: ::core::clone::AssertParamIsClone<Option<ArtificialField>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AccessDepth {
    #[inline]
    fn eq(&self, other: &AccessDepth) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (AccessDepth::Shallow(__self_0),
                    AccessDepth::Shallow(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AccessDepth {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_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 {
            AccessDepth::Shallow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Shallow", &__self_0),
            AccessDepth::Deep => ::core::fmt::Formatter::write_str(f, "Deep"),
            AccessDepth::Drop => ::core::fmt::Formatter::write_str(f, "Drop"),
        }
    }
}Debug)]
1046enum AccessDepth {
1047    /// From the RFC: "A *shallow* access means that the immediate
1048    /// fields reached at P are accessed, but references or pointers
1049    /// found within are not dereferenced. Right now, the only access
1050    /// that is shallow is an assignment like `x = ...;`, which would
1051    /// be a *shallow write* of `x`."
1052    Shallow(Option<ArtificialField>),
1053
1054    /// From the RFC: "A *deep* access means that all data reachable
1055    /// through the given place may be invalidated or accesses by
1056    /// this action."
1057    Deep,
1058
1059    /// Access is Deep only when there is a Drop implementation that
1060    /// can reach the data behind the reference.
1061    Drop,
1062}
1063
1064/// Kind of access to a value: read or write
1065/// (For informational purposes only)
1066#[derive(#[automatically_derived]
impl ::core::marker::Copy for ReadOrWrite { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReadOrWrite {
    #[inline]
    fn clone(&self) -> ReadOrWrite {
        let _: ::core::clone::AssertParamIsClone<ReadKind>;
        let _: ::core::clone::AssertParamIsClone<WriteKind>;
        let _: ::core::clone::AssertParamIsClone<BorrowIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReadOrWrite {
    #[inline]
    fn eq(&self, other: &ReadOrWrite) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ReadOrWrite::Read(__self_0), ReadOrWrite::Read(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ReadOrWrite::Write(__self_0), ReadOrWrite::Write(__arg1_0))
                    => __self_0 == __arg1_0,
                (ReadOrWrite::Reservation(__self_0),
                    ReadOrWrite::Reservation(__arg1_0)) => __self_0 == __arg1_0,
                (ReadOrWrite::Activation(__self_0, __self_1),
                    ReadOrWrite::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_receiver_is_total_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 {
            ReadOrWrite::Read(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Read",
                    &__self_0),
            ReadOrWrite::Write(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Write",
                    &__self_0),
            ReadOrWrite::Reservation(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Reservation", &__self_0),
            ReadOrWrite::Activation(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Activation", __self_0, &__self_1),
        }
    }
}Debug)]
1067enum ReadOrWrite {
1068    /// From the RFC: "A *read* means that the existing data may be
1069    /// read, but will not be changed."
1070    Read(ReadKind),
1071
1072    /// From the RFC: "A *write* means that the data may be mutated to
1073    /// new values or otherwise invalidated (for example, it could be
1074    /// de-initialized, as in a move operation).
1075    Write(WriteKind),
1076
1077    /// For two-phase borrows, we distinguish a reservation (which is treated
1078    /// like a Read) from an activation (which is treated like a write), and
1079    /// each of those is furthermore distinguished from Reads/Writes above.
1080    Reservation(WriteKind),
1081    Activation(WriteKind, BorrowIndex),
1082}
1083
1084/// Kind of read access to a value
1085/// (For informational purposes only)
1086#[derive(#[automatically_derived]
impl ::core::marker::Copy for ReadKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReadKind {
    #[inline]
    fn clone(&self) -> ReadKind {
        let _: ::core::clone::AssertParamIsClone<BorrowKind>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReadKind {
    #[inline]
    fn eq(&self, other: &ReadKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ReadKind::Borrow(__self_0), ReadKind::Borrow(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReadKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_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 {
            ReadKind::Borrow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Borrow",
                    &__self_0),
            ReadKind::Copy => ::core::fmt::Formatter::write_str(f, "Copy"),
        }
    }
}Debug)]
1087enum ReadKind {
1088    Borrow(BorrowKind),
1089    Copy,
1090}
1091
1092/// Kind of write access to a value
1093/// (For informational purposes only)
1094#[derive(#[automatically_derived]
impl ::core::marker::Copy for WriteKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for WriteKind {
    #[inline]
    fn clone(&self) -> WriteKind {
        let _: ::core::clone::AssertParamIsClone<BorrowKind>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for WriteKind {
    #[inline]
    fn eq(&self, other: &WriteKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (WriteKind::MutableBorrow(__self_0),
                    WriteKind::MutableBorrow(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for WriteKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_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 {
            WriteKind::StorageDeadOrDrop =>
                ::core::fmt::Formatter::write_str(f, "StorageDeadOrDrop"),
            WriteKind::Replace =>
                ::core::fmt::Formatter::write_str(f, "Replace"),
            WriteKind::MutableBorrow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MutableBorrow", &__self_0),
            WriteKind::Mutate =>
                ::core::fmt::Formatter::write_str(f, "Mutate"),
            WriteKind::Move => ::core::fmt::Formatter::write_str(f, "Move"),
        }
    }
}Debug)]
1095enum WriteKind {
1096    StorageDeadOrDrop,
1097    Replace,
1098    MutableBorrow(BorrowKind),
1099    Mutate,
1100    Move,
1101}
1102
1103/// When checking permissions for a place access, this flag is used to indicate that an immutable
1104/// local place can be mutated.
1105//
1106// FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
1107// - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
1108//   `is_declared_mutable()`.
1109// - Take flow state into consideration in `is_assignable()` for local variables.
1110#[derive(#[automatically_derived]
impl ::core::marker::Copy for LocalMutationIsAllowed { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LocalMutationIsAllowed {
    #[inline]
    fn clone(&self) -> LocalMutationIsAllowed { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for LocalMutationIsAllowed {
    #[inline]
    fn eq(&self, other: &LocalMutationIsAllowed) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LocalMutationIsAllowed {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {}
}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)]
1111enum LocalMutationIsAllowed {
1112    Yes,
1113    /// We want use of immutable upvars to cause a "write to immutable upvar"
1114    /// error, not an "reassignment" error.
1115    ExceptUpvars,
1116    No,
1117}
1118
1119#[derive(#[automatically_derived]
impl ::core::marker::Copy for InitializationRequiringAction { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InitializationRequiringAction {
    #[inline]
    fn clone(&self) -> InitializationRequiringAction { *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)]
1120enum InitializationRequiringAction {
1121    Borrow,
1122    MatchOn,
1123    Use,
1124    Assignment,
1125    PartialAssignment,
1126}
1127
1128#[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)]
1129struct RootPlace<'tcx> {
1130    place_local: Local,
1131    place_projection: &'tcx [PlaceElem<'tcx>],
1132    is_local_mutation_allowed: LocalMutationIsAllowed,
1133}
1134
1135impl InitializationRequiringAction {
1136    fn as_noun(self) -> &'static str {
1137        match self {
1138            InitializationRequiringAction::Borrow => "borrow",
1139            InitializationRequiringAction::MatchOn => "use", // no good noun
1140            InitializationRequiringAction::Use => "use",
1141            InitializationRequiringAction::Assignment => "assign",
1142            InitializationRequiringAction::PartialAssignment => "assign to part",
1143        }
1144    }
1145
1146    fn as_verb_in_past_tense(self) -> &'static str {
1147        match self {
1148            InitializationRequiringAction::Borrow => "borrowed",
1149            InitializationRequiringAction::MatchOn => "matched on",
1150            InitializationRequiringAction::Use => "used",
1151            InitializationRequiringAction::Assignment => "assigned",
1152            InitializationRequiringAction::PartialAssignment => "partially assigned",
1153        }
1154    }
1155
1156    fn as_general_verb_in_past_tense(self) -> &'static str {
1157        match self {
1158            InitializationRequiringAction::Borrow
1159            | InitializationRequiringAction::MatchOn
1160            | InitializationRequiringAction::Use => "used",
1161            InitializationRequiringAction::Assignment => "assigned",
1162            InitializationRequiringAction::PartialAssignment => "partially assigned",
1163        }
1164    }
1165}
1166
1167impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
1168    fn body(&self) -> &'a Body<'tcx> {
1169        self.body
1170    }
1171
1172    /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
1173    /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
1174    /// place is initialized and (b) it is not borrowed in some way that would prevent this
1175    /// access.
1176    ///
1177    /// Returns `true` if an error is reported.
1178    fn access_place(
1179        &mut self,
1180        location: Location,
1181        place_span: (Place<'tcx>, Span),
1182        kind: (AccessDepth, ReadOrWrite),
1183        is_local_mutation_allowed: LocalMutationIsAllowed,
1184        state: &BorrowckDomain,
1185    ) {
1186        let (sd, rw) = kind;
1187
1188        if let Activation(_, borrow_index) = rw {
1189            if self.reservation_error_reported.contains(&place_span.0) {
1190                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1190",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1190u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::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 Value))])
            });
    } else { ; }
};debug!(
1191                    "skipping access_place for activation of invalid reservation \
1192                     place: {:?} borrow_index: {:?}",
1193                    place_span.0, borrow_index
1194                );
1195                return;
1196            }
1197        }
1198
1199        // Check is_empty() first because it's the common case, and doing that
1200        // way we avoid the clone() call.
1201        if !self.access_place_error_reported.is_empty()
1202            && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1203        {
1204            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1204",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1204u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("access_place: suppressing error place_span=`{0:?}` kind=`{1:?}`",
                                                    place_span, kind) as &dyn Value))])
            });
    } else { ; }
};debug!(
1205                "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1206                place_span, kind
1207            );
1208            return;
1209        }
1210
1211        let mutability_error = self.check_access_permissions(
1212            place_span,
1213            rw,
1214            is_local_mutation_allowed,
1215            state,
1216            location,
1217        );
1218        let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
1219
1220        if conflict_error || mutability_error {
1221            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1221",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1221u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("access_place: logging error place_span=`{0:?}` kind=`{1:?}`",
                                                    place_span, kind) as &dyn Value))])
            });
    } else { ; }
};debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1222            self.access_place_error_reported.insert((place_span.0, place_span.1));
1223        }
1224    }
1225
1226    fn borrows_in_scope<'s>(
1227        &self,
1228        location: Location,
1229        state: &'s BorrowckDomain,
1230    ) -> Cow<'s, MixedBitSet<BorrowIndex>> {
1231        if let Some(polonius) = &self.polonius_output {
1232            // Use polonius output if it has been enabled.
1233            let location = self.location_table.start_index(location);
1234            let mut polonius_output = MixedBitSet::new_empty(self.borrow_set.len());
1235            for &idx in polonius.errors_at(location) {
1236                polonius_output.insert(idx);
1237            }
1238            Cow::Owned(polonius_output)
1239        } else {
1240            Cow::Borrowed(&state.borrows)
1241        }
1242    }
1243
1244    #[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("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(&["location",
                                                    "place_span", "sd", "rw"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sd)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rw)
                                                            as &dyn 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);
            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 compiler/rustc_borrowck/src/lib.rs:1272",
                                                    "rustc_borrowck", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(1272u32),
                                                    ::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};
                                            let mut iter = __CALLSITE.metadata().fields().iter();
                                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::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 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 compiler/rustc_borrowck/src/lib.rs:1326",
                                                            "rustc_borrowck", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(1326u32),
                                                            ::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};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("recording invalid reservation of place: {0:?}",
                                                                                        place_span.0) as &dyn 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 compiler/rustc_borrowck/src/lib.rs:1334",
                                                            "rustc_borrowck", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(1334u32),
                                                            ::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};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("observing check_place for activation of borrow_index: {0:?}",
                                                                                        activating) as &dyn 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))]
1245    fn check_access_for_conflict(
1246        &mut self,
1247        location: Location,
1248        place_span: (Place<'tcx>, Span),
1249        sd: AccessDepth,
1250        rw: ReadOrWrite,
1251        state: &BorrowckDomain,
1252    ) -> bool {
1253        let mut error_reported = false;
1254
1255        let borrows_in_scope = self.borrows_in_scope(location, state);
1256
1257        each_borrow_involving_path(
1258            self,
1259            self.infcx.tcx,
1260            self.body,
1261            (sd, place_span.0),
1262            self.borrow_set,
1263            |borrow_index| borrows_in_scope.contains(borrow_index),
1264            |this, borrow_index, borrow| match (rw, borrow.kind) {
1265                // Obviously an activation is compatible with its own
1266                // reservation (or even prior activating uses of same
1267                // borrow); so don't check if they interfere.
1268                //
1269                // NOTE: *reservations* do conflict with themselves;
1270                // thus aren't injecting unsoundness w/ this check.)
1271                (Activation(_, activating), _) if activating == borrow_index => {
1272                    debug!(
1273                        "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1274                         skipping {:?} b/c activation of same borrow_index",
1275                        place_span,
1276                        sd,
1277                        rw,
1278                        (borrow_index, borrow),
1279                    );
1280                    ControlFlow::Continue(())
1281                }
1282
1283                (Read(_), BorrowKind::Shared | BorrowKind::Fake(_))
1284                | (
1285                    Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
1286                    BorrowKind::Mut { .. },
1287                ) => ControlFlow::Continue(()),
1288
1289                (Reservation(_), BorrowKind::Fake(_) | BorrowKind::Shared) => {
1290                    // This used to be a future compatibility warning (to be
1291                    // disallowed on NLL). See rust-lang/rust#56254
1292                    ControlFlow::Continue(())
1293                }
1294
1295                (Write(WriteKind::Move), BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1296                    // Handled by initialization checks.
1297                    ControlFlow::Continue(())
1298                }
1299
1300                (Read(kind), BorrowKind::Mut { .. }) => {
1301                    // Reading from mere reservations of mutable-borrows is OK.
1302                    if !is_active(this.dominators(), borrow, location) {
1303                        assert!(borrow.kind.is_two_phase_borrow());
1304                        return ControlFlow::Continue(());
1305                    }
1306
1307                    error_reported = true;
1308                    match kind {
1309                        ReadKind::Copy => {
1310                            let err = this
1311                                .report_use_while_mutably_borrowed(location, place_span, borrow);
1312                            this.buffer_error(err);
1313                        }
1314                        ReadKind::Borrow(bk) => {
1315                            let err =
1316                                this.report_conflicting_borrow(location, place_span, bk, borrow);
1317                            this.buffer_error(err);
1318                        }
1319                    }
1320                    ControlFlow::Break(())
1321                }
1322
1323                (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1324                    match rw {
1325                        Reservation(..) => {
1326                            debug!(
1327                                "recording invalid reservation of \
1328                                 place: {:?}",
1329                                place_span.0
1330                            );
1331                            this.reservation_error_reported.insert(place_span.0);
1332                        }
1333                        Activation(_, activating) => {
1334                            debug!(
1335                                "observing check_place for activation of \
1336                                 borrow_index: {:?}",
1337                                activating
1338                            );
1339                        }
1340                        Read(..) | Write(..) => {}
1341                    }
1342
1343                    error_reported = true;
1344                    match kind {
1345                        WriteKind::MutableBorrow(bk) => {
1346                            let err =
1347                                this.report_conflicting_borrow(location, place_span, bk, borrow);
1348                            this.buffer_error(err);
1349                        }
1350                        WriteKind::StorageDeadOrDrop => this
1351                            .report_borrowed_value_does_not_live_long_enough(
1352                                location,
1353                                borrow,
1354                                place_span,
1355                                Some(WriteKind::StorageDeadOrDrop),
1356                            ),
1357                        WriteKind::Mutate => {
1358                            this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1359                        }
1360                        WriteKind::Move => {
1361                            this.report_move_out_while_borrowed(location, place_span, borrow)
1362                        }
1363                        WriteKind::Replace => {
1364                            this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1365                        }
1366                    }
1367                    ControlFlow::Break(())
1368                }
1369            },
1370        );
1371
1372        error_reported
1373    }
1374
1375    /// Through #123739, `BackwardIncompatibleDropHint`s (BIDs) are introduced.
1376    /// We would like to emit lints whether borrow checking fails at these future drop locations.
1377    #[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("compiler/rustc_borrowck/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1377u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                    ::tracing_core::field::FieldSet::new(&["location", "place"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn 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.node_span_lint(TAIL_EXPR_DROP_ORDER,
                            CRATE_HIR_ID, borrowed,
                            |diag|
                                {
                                    session_diagnostics::TailExprDropOrder {
                                            borrowed,
                                        }.decorate_lint(diag);
                                    explain.add_explanation_to_diagnostic(&this, diag, "", None,
                                        None);
                                });
                        ControlFlow::Break(())
                    });
        }
    }
}#[instrument(level = "debug", skip(self, state))]
1378    fn check_backward_incompatible_drop(
1379        &mut self,
1380        location: Location,
1381        place: Place<'tcx>,
1382        state: &BorrowckDomain,
1383    ) {
1384        let tcx = self.infcx.tcx;
1385        // If this type does not need `Drop`, then treat it like a `StorageDead`.
1386        // This is needed because we track the borrows of refs to thread locals,
1387        // and we'll ICE because we don't track borrows behind shared references.
1388        let sd = if place.ty(self.body, tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
1389            AccessDepth::Drop
1390        } else {
1391            AccessDepth::Shallow(None)
1392        };
1393
1394        let borrows_in_scope = self.borrows_in_scope(location, state);
1395
1396        // This is a very simplified version of `Self::check_access_for_conflict`.
1397        // We are here checking on BIDs and specifically still-live borrows of data involving the BIDs.
1398        each_borrow_involving_path(
1399            self,
1400            self.infcx.tcx,
1401            self.body,
1402            (sd, place),
1403            self.borrow_set,
1404            |borrow_index| borrows_in_scope.contains(borrow_index),
1405            |this, _borrow_index, borrow| {
1406                if matches!(borrow.kind, BorrowKind::Fake(_)) {
1407                    return ControlFlow::Continue(());
1408                }
1409                let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span();
1410                let explain = this.explain_why_borrow_contains_point(
1411                    location,
1412                    borrow,
1413                    Some((WriteKind::StorageDeadOrDrop, place)),
1414                );
1415                this.infcx.tcx.node_span_lint(
1416                    TAIL_EXPR_DROP_ORDER,
1417                    CRATE_HIR_ID,
1418                    borrowed,
1419                    |diag| {
1420                        session_diagnostics::TailExprDropOrder { borrowed }.decorate_lint(diag);
1421                        explain.add_explanation_to_diagnostic(&this, diag, "", None, None);
1422                    },
1423                );
1424                // We may stop at the first case
1425                ControlFlow::Break(())
1426            },
1427        );
1428    }
1429
1430    fn mutate_place(
1431        &mut self,
1432        location: Location,
1433        place_span: (Place<'tcx>, Span),
1434        kind: AccessDepth,
1435        state: &BorrowckDomain,
1436    ) {
1437        // Write of P[i] or *P requires P init'd.
1438        self.check_if_assigned_path_is_moved(location, place_span, state);
1439
1440        self.access_place(
1441            location,
1442            place_span,
1443            (kind, Write(WriteKind::Mutate)),
1444            LocalMutationIsAllowed::No,
1445            state,
1446        );
1447    }
1448
1449    fn consume_rvalue(
1450        &mut self,
1451        location: Location,
1452        (rvalue, span): (&Rvalue<'tcx>, Span),
1453        state: &BorrowckDomain,
1454    ) {
1455        match rvalue {
1456            &Rvalue::Ref(_ /*rgn*/, bk, place) => {
1457                let access_kind = match bk {
1458                    BorrowKind::Fake(FakeBorrowKind::Shallow) => {
1459                        (Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
1460                    }
1461                    BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
1462                        (Deep, Read(ReadKind::Borrow(bk)))
1463                    }
1464                    BorrowKind::Mut { .. } => {
1465                        let wk = WriteKind::MutableBorrow(bk);
1466                        if bk.is_two_phase_borrow() {
1467                            (Deep, Reservation(wk))
1468                        } else {
1469                            (Deep, Write(wk))
1470                        }
1471                    }
1472                };
1473
1474                self.access_place(
1475                    location,
1476                    (place, span),
1477                    access_kind,
1478                    LocalMutationIsAllowed::No,
1479                    state,
1480                );
1481
1482                let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
1483                    InitializationRequiringAction::MatchOn
1484                } else {
1485                    InitializationRequiringAction::Borrow
1486                };
1487
1488                self.check_if_path_or_subpath_is_moved(
1489                    location,
1490                    action,
1491                    (place.as_ref(), span),
1492                    state,
1493                );
1494            }
1495
1496            &Rvalue::RawPtr(kind, place) => {
1497                let access_kind = match kind {
1498                    RawPtrKind::Mut => (
1499                        Deep,
1500                        Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1501                            kind: MutBorrowKind::Default,
1502                        })),
1503                    ),
1504                    RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1505                    RawPtrKind::FakeForPtrMetadata => {
1506                        (Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
1507                    }
1508                };
1509
1510                self.access_place(
1511                    location,
1512                    (place, span),
1513                    access_kind,
1514                    LocalMutationIsAllowed::No,
1515                    state,
1516                );
1517
1518                self.check_if_path_or_subpath_is_moved(
1519                    location,
1520                    InitializationRequiringAction::Borrow,
1521                    (place.as_ref(), span),
1522                    state,
1523                );
1524            }
1525
1526            Rvalue::ThreadLocalRef(_) => {}
1527
1528            Rvalue::Use(operand)
1529            | Rvalue::Repeat(operand, _)
1530            | Rvalue::UnaryOp(_ /*un_op*/, operand)
1531            | Rvalue::Cast(_ /*cast_kind*/, operand, _ /*ty*/)
1532            | Rvalue::ShallowInitBox(operand, _ /*ty*/) => {
1533                self.consume_operand(location, (operand, span), state)
1534            }
1535
1536            &Rvalue::Discriminant(place) => {
1537                let af = match *rvalue {
1538                    Rvalue::Discriminant(..) => None,
1539                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1540                };
1541                self.access_place(
1542                    location,
1543                    (place, span),
1544                    (Shallow(af), Read(ReadKind::Copy)),
1545                    LocalMutationIsAllowed::No,
1546                    state,
1547                );
1548                self.check_if_path_or_subpath_is_moved(
1549                    location,
1550                    InitializationRequiringAction::Use,
1551                    (place.as_ref(), span),
1552                    state,
1553                );
1554            }
1555
1556            Rvalue::BinaryOp(_bin_op, box (operand1, operand2)) => {
1557                self.consume_operand(location, (operand1, span), state);
1558                self.consume_operand(location, (operand2, span), state);
1559            }
1560
1561            Rvalue::Aggregate(aggregate_kind, operands) => {
1562                // We need to report back the list of mutable upvars that were
1563                // moved into the closure and subsequently used by the closure,
1564                // in order to populate our used_mut set.
1565                match **aggregate_kind {
1566                    AggregateKind::Closure(def_id, _)
1567                    | AggregateKind::CoroutineClosure(def_id, _)
1568                    | AggregateKind::Coroutine(def_id, _) => {
1569                        let def_id = def_id.expect_local();
1570                        let used_mut_upvars = self.root_cx.used_mut_upvars(def_id);
1571                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1571",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1571u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("{0:?} used_mut_upvars={1:?}",
                                                    def_id, used_mut_upvars) as &dyn Value))])
            });
    } else { ; }
};debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1572                        // FIXME: We're cloning the `SmallVec` here to avoid borrowing `root_cx`
1573                        // when calling `propagate_closure_used_mut_upvar`. This should ideally
1574                        // be unnecessary.
1575                        for field in used_mut_upvars.clone() {
1576                            self.propagate_closure_used_mut_upvar(&operands[field]);
1577                        }
1578                    }
1579                    AggregateKind::Adt(..)
1580                    | AggregateKind::Array(..)
1581                    | AggregateKind::Tuple { .. }
1582                    | AggregateKind::RawPtr(..) => (),
1583                }
1584
1585                for operand in operands {
1586                    self.consume_operand(location, (operand, span), state);
1587                }
1588            }
1589
1590            Rvalue::WrapUnsafeBinder(op, _) => {
1591                self.consume_operand(location, (op, span), state);
1592            }
1593
1594            Rvalue::CopyForDeref(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("`CopyForDeref` in borrowck"))bug!("`CopyForDeref` in borrowck"),
1595        }
1596    }
1597
1598    fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1599        let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1600            // We have three possibilities here:
1601            // a. We are modifying something through a mut-ref
1602            // b. We are modifying something that is local to our parent
1603            // c. Current body is a nested closure, and we are modifying path starting from
1604            //    a Place captured by our parent closure.
1605
1606            // Handle (c), the path being modified is exactly the path captured by our parent
1607            if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1608                this.used_mut_upvars.push(field);
1609                return;
1610            }
1611
1612            for (place_ref, proj) in place.iter_projections().rev() {
1613                // Handle (a)
1614                if proj == ProjectionElem::Deref {
1615                    match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1616                        // We aren't modifying a variable directly
1617                        ty::Ref(_, _, hir::Mutability::Mut) => return,
1618
1619                        _ => {}
1620                    }
1621                }
1622
1623                // Handle (c)
1624                if let Some(field) = this.is_upvar_field_projection(place_ref) {
1625                    this.used_mut_upvars.push(field);
1626                    return;
1627                }
1628            }
1629
1630            // Handle(b)
1631            this.used_mut.insert(place.local);
1632        };
1633
1634        // This relies on the current way that by-value
1635        // captures of a closure are copied/moved directly
1636        // when generating MIR.
1637        match *operand {
1638            Operand::Move(place) | Operand::Copy(place) => {
1639                match place.as_local() {
1640                    Some(local) if !self.body.local_decls[local].is_user_variable() => {
1641                        if self.body.local_decls[local].ty.is_mutable_ptr() {
1642                            // The variable will be marked as mutable by the borrow.
1643                            return;
1644                        }
1645                        // This is an edge case where we have a `move` closure
1646                        // inside a non-move closure, and the inner closure
1647                        // contains a mutation:
1648                        //
1649                        // let mut i = 0;
1650                        // || { move || { i += 1; }; };
1651                        //
1652                        // In this case our usual strategy of assuming that the
1653                        // variable will be captured by mutable reference is
1654                        // wrong, since `i` can be copied into the inner
1655                        // closure from a shared reference.
1656                        //
1657                        // As such we have to search for the local that this
1658                        // capture comes from and mark it as being used as mut.
1659
1660                        let Some(temp_mpi) = self.move_data.rev_lookup.find_local(local) else {
1661                            ::rustc_middle::util::bug::bug_fmt(format_args!("temporary should be tracked"));bug!("temporary should be tracked");
1662                        };
1663                        let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1664                            &self.move_data.inits[init_index]
1665                        } else {
1666                            ::rustc_middle::util::bug::bug_fmt(format_args!("temporary should be initialized exactly once"))bug!("temporary should be initialized exactly once")
1667                        };
1668
1669                        let InitLocation::Statement(loc) = init.location else {
1670                            ::rustc_middle::util::bug::bug_fmt(format_args!("temporary initialized in arguments"))bug!("temporary initialized in arguments")
1671                        };
1672
1673                        let body = self.body;
1674                        let bbd = &body[loc.block];
1675                        let stmt = &bbd.statements[loc.statement_index];
1676                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1676",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1676u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("temporary assigned in: stmt={0:?}",
                                                    stmt) as &dyn Value))])
            });
    } else { ; }
};debug!("temporary assigned in: stmt={:?}", stmt);
1677
1678                        match stmt.kind {
1679                            StatementKind::Assign(box (
1680                                _,
1681                                Rvalue::Ref(_, _, source)
1682                                | Rvalue::Use(Operand::Copy(source) | Operand::Move(source)),
1683                            )) => {
1684                                propagate_closure_used_mut_place(self, source);
1685                            }
1686                            _ => {
1687                                ::rustc_middle::util::bug::bug_fmt(format_args!("closures should only capture user variables or references to user variables"));bug!(
1688                                    "closures should only capture user variables \
1689                                 or references to user variables"
1690                                );
1691                            }
1692                        }
1693                    }
1694                    _ => propagate_closure_used_mut_place(self, place),
1695                }
1696            }
1697            Operand::Constant(..) | Operand::RuntimeChecks(_) => {}
1698        }
1699    }
1700
1701    fn consume_operand(
1702        &mut self,
1703        location: Location,
1704        (operand, span): (&Operand<'tcx>, Span),
1705        state: &BorrowckDomain,
1706    ) {
1707        match *operand {
1708            Operand::Copy(place) => {
1709                // copy of place: check if this is "copy of frozen path"
1710                // (FIXME: see check_loans.rs)
1711                self.access_place(
1712                    location,
1713                    (place, span),
1714                    (Deep, Read(ReadKind::Copy)),
1715                    LocalMutationIsAllowed::No,
1716                    state,
1717                );
1718
1719                // Finally, check if path was already moved.
1720                self.check_if_path_or_subpath_is_moved(
1721                    location,
1722                    InitializationRequiringAction::Use,
1723                    (place.as_ref(), span),
1724                    state,
1725                );
1726            }
1727            Operand::Move(place) => {
1728                // Check if moving from this place makes sense.
1729                self.check_movable_place(location, place);
1730
1731                // move of place: check if this is move of already borrowed path
1732                self.access_place(
1733                    location,
1734                    (place, span),
1735                    (Deep, Write(WriteKind::Move)),
1736                    LocalMutationIsAllowed::Yes,
1737                    state,
1738                );
1739
1740                // Finally, check if path was already moved.
1741                self.check_if_path_or_subpath_is_moved(
1742                    location,
1743                    InitializationRequiringAction::Use,
1744                    (place.as_ref(), span),
1745                    state,
1746                );
1747            }
1748            Operand::Constant(_) | Operand::RuntimeChecks(_) => {}
1749        }
1750    }
1751
1752    /// Checks whether a borrow of this place is invalidated when the function
1753    /// exits
1754    #[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("compiler/rustc_borrowck/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1754u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck"),
                                    ::tracing_core::field::FieldSet::new(&["location", "borrow",
                                                    "span"], ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn 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 compiler/rustc_borrowck/src/lib.rs:1790",
                                        "rustc_borrowck", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1790u32),
                                        ::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};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("check_for_invalidation_at_exit({0:?}): INVALID",
                                                                    place) as &dyn 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))]
1755    fn check_for_invalidation_at_exit(
1756        &mut self,
1757        location: Location,
1758        borrow: &BorrowData<'tcx>,
1759        span: Span,
1760    ) {
1761        let place = borrow.borrowed_place;
1762        let mut root_place = PlaceRef { local: place.local, projection: &[] };
1763
1764        // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1765        // we just know that all locals are dropped at function exit (otherwise
1766        // we'll have a memory leak) and assume that all statics have a destructor.
1767        //
1768        // FIXME: allow thread-locals to borrow other thread locals?
1769        let might_be_alive = if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1770            // Thread-locals might be dropped after the function exits
1771            // We have to dereference the outer reference because
1772            // borrows don't conflict behind shared references.
1773            root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1774            true
1775        } else {
1776            false
1777        };
1778
1779        let sd = if might_be_alive { Deep } else { Shallow(None) };
1780
1781        if places_conflict::borrow_conflicts_with_place(
1782            self.infcx.tcx,
1783            self.body,
1784            place,
1785            borrow.kind,
1786            root_place,
1787            sd,
1788            places_conflict::PlaceConflictBias::Overlap,
1789        ) {
1790            debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1791            // FIXME: should be talking about the region lifetime instead
1792            // of just a span here.
1793            let span = self.infcx.tcx.sess.source_map().end_point(span);
1794            self.report_borrowed_value_does_not_live_long_enough(
1795                location,
1796                borrow,
1797                (place, span),
1798                None,
1799            )
1800        }
1801    }
1802
1803    /// Reports an error if this is a borrow of local data.
1804    /// This is called for all Yield expressions on movable coroutines
1805    fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1806        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:1806",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1806u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_for_local_borrow({0:?})",
                                                    borrow) as &dyn Value))])
            });
    } else { ; }
};debug!("check_for_local_borrow({:?})", borrow);
1807
1808        if borrow_of_local_data(borrow.borrowed_place) {
1809            let err = self.cannot_borrow_across_coroutine_yield(
1810                self.retrieve_borrow_spans(borrow).var_or_use(),
1811                yield_span,
1812            );
1813
1814            self.buffer_error(err);
1815        }
1816    }
1817
1818    fn check_activations(&mut self, location: Location, span: Span, state: &BorrowckDomain) {
1819        // Two-phase borrow support: For each activation that is newly
1820        // generated at this statement, check if it interferes with
1821        // another borrow.
1822        for &borrow_index in self.borrow_set.activations_at_location(location) {
1823            let borrow = &self.borrow_set[borrow_index];
1824
1825            // only mutable borrows should be 2-phase
1826            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 {
1827                BorrowKind::Shared | BorrowKind::Fake(_) => false,
1828                BorrowKind::Mut { .. } => true,
1829            });
1830
1831            self.access_place(
1832                location,
1833                (borrow.borrowed_place, span),
1834                (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1835                LocalMutationIsAllowed::No,
1836                state,
1837            );
1838            // We do not need to call `check_if_path_or_subpath_is_moved`
1839            // again, as we already called it when we made the
1840            // initial reservation.
1841        }
1842    }
1843
1844    fn check_movable_place(&mut self, location: Location, place: Place<'tcx>) {
1845        use IllegalMoveOriginKind::*;
1846
1847        let body = self.body;
1848        let tcx = self.infcx.tcx;
1849        let mut place_ty = PlaceTy::from_ty(body.local_decls[place.local].ty);
1850        for (place_ref, elem) in place.iter_projections() {
1851            match elem {
1852                ProjectionElem::Deref => match place_ty.ty.kind() {
1853                    ty::Ref(..) | ty::RawPtr(..) => {
1854                        self.move_errors.push(MoveError::new(
1855                            place,
1856                            location,
1857                            BorrowedContent {
1858                                target_place: place_ref.project_deeper(&[elem], tcx),
1859                            },
1860                        ));
1861                        return;
1862                    }
1863                    ty::Adt(adt, _) => {
1864                        if !adt.is_box() {
1865                            ::rustc_middle::util::bug::bug_fmt(format_args!("Adt should be a box type when Place is deref"));bug!("Adt should be a box type when Place is deref");
1866                        }
1867                    }
1868                    ty::Bool
1869                    | ty::Char
1870                    | ty::Int(_)
1871                    | ty::Uint(_)
1872                    | ty::Float(_)
1873                    | ty::Foreign(_)
1874                    | ty::Str
1875                    | ty::Array(_, _)
1876                    | ty::Pat(_, _)
1877                    | ty::Slice(_)
1878                    | ty::FnDef(_, _)
1879                    | ty::FnPtr(..)
1880                    | ty::Dynamic(_, _)
1881                    | ty::Closure(_, _)
1882                    | ty::CoroutineClosure(_, _)
1883                    | ty::Coroutine(_, _)
1884                    | ty::CoroutineWitness(..)
1885                    | ty::Never
1886                    | ty::Tuple(_)
1887                    | ty::UnsafeBinder(_)
1888                    | ty::Alias(_, _)
1889                    | ty::Param(_)
1890                    | ty::Bound(_, _)
1891                    | ty::Infer(_)
1892                    | ty::Error(_)
1893                    | ty::Placeholder(_) => {
1894                        ::rustc_middle::util::bug::bug_fmt(format_args!("When Place is Deref it\'s type shouldn\'t be {0:#?}",
        place_ty))bug!("When Place is Deref it's type shouldn't be {place_ty:#?}")
1895                    }
1896                },
1897                ProjectionElem::Field(_, _) => match place_ty.ty.kind() {
1898                    ty::Adt(adt, _) => {
1899                        if adt.has_dtor(tcx) {
1900                            self.move_errors.push(MoveError::new(
1901                                place,
1902                                location,
1903                                InteriorOfTypeWithDestructor { container_ty: place_ty.ty },
1904                            ));
1905                            return;
1906                        }
1907                    }
1908                    ty::Closure(..)
1909                    | ty::CoroutineClosure(..)
1910                    | ty::Coroutine(_, _)
1911                    | ty::Tuple(_) => (),
1912                    ty::Bool
1913                    | ty::Char
1914                    | ty::Int(_)
1915                    | ty::Uint(_)
1916                    | ty::Float(_)
1917                    | ty::Foreign(_)
1918                    | ty::Str
1919                    | ty::Array(_, _)
1920                    | ty::Pat(_, _)
1921                    | ty::Slice(_)
1922                    | ty::RawPtr(_, _)
1923                    | ty::Ref(_, _, _)
1924                    | ty::FnDef(_, _)
1925                    | ty::FnPtr(..)
1926                    | ty::Dynamic(_, _)
1927                    | ty::CoroutineWitness(..)
1928                    | ty::Never
1929                    | ty::UnsafeBinder(_)
1930                    | ty::Alias(_, _)
1931                    | ty::Param(_)
1932                    | ty::Bound(_, _)
1933                    | ty::Infer(_)
1934                    | ty::Error(_)
1935                    | ty::Placeholder(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("When Place contains ProjectionElem::Field it\'s type shouldn\'t be {0:#?}",
        place_ty))bug!(
1936                        "When Place contains ProjectionElem::Field it's type shouldn't be {place_ty:#?}"
1937                    ),
1938                },
1939                ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1940                    match place_ty.ty.kind() {
1941                        ty::Slice(_) => {
1942                            self.move_errors.push(MoveError::new(
1943                                place,
1944                                location,
1945                                InteriorOfSliceOrArray { ty: place_ty.ty, is_index: false },
1946                            ));
1947                            return;
1948                        }
1949                        ty::Array(_, _) => (),
1950                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type {0:#?}",
        place_ty.ty))bug!("Unexpected type {:#?}", place_ty.ty),
1951                    }
1952                }
1953                ProjectionElem::Index(_) => match place_ty.ty.kind() {
1954                    ty::Array(..) | ty::Slice(..) => {
1955                        self.move_errors.push(MoveError::new(
1956                            place,
1957                            location,
1958                            InteriorOfSliceOrArray { ty: place_ty.ty, is_index: true },
1959                        ));
1960                        return;
1961                    }
1962                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type {0:#?}",
        place_ty))bug!("Unexpected type {place_ty:#?}"),
1963                },
1964                // `OpaqueCast`: only transmutes the type, so no moves there.
1965                // `Downcast`  : only changes information about a `Place` without moving.
1966                // So it's safe to skip these.
1967                ProjectionElem::OpaqueCast(_)
1968                | ProjectionElem::Downcast(_, _)
1969                | ProjectionElem::UnwrapUnsafeBinder(_) => (),
1970            }
1971
1972            place_ty = place_ty.projection_ty(tcx, elem);
1973        }
1974    }
1975
1976    fn check_if_full_path_is_moved(
1977        &mut self,
1978        location: Location,
1979        desired_action: InitializationRequiringAction,
1980        place_span: (PlaceRef<'tcx>, Span),
1981        state: &BorrowckDomain,
1982    ) {
1983        let maybe_uninits = &state.uninits;
1984
1985        // Bad scenarios:
1986        //
1987        // 1. Move of `a.b.c`, use of `a.b.c`
1988        // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1989        // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1990        //    partial initialization support, one might have `a.x`
1991        //    initialized but not `a.b`.
1992        //
1993        // OK scenarios:
1994        //
1995        // 4. Move of `a.b.c`, use of `a.b.d`
1996        // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1997        // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1998        //    must have been initialized for the use to be sound.
1999        // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
2000
2001        // The dataflow tracks shallow prefixes distinctly (that is,
2002        // field-accesses on P distinctly from P itself), in order to
2003        // track substructure initialization separately from the whole
2004        // structure.
2005        //
2006        // E.g., when looking at (*a.b.c).d, if the closest prefix for
2007        // which we have a MovePath is `a.b`, then that means that the
2008        // initialization state of `a.b` is all we need to inspect to
2009        // know if `a.b.c` is valid (and from that we infer that the
2010        // dereference and `.d` access is also valid, since we assume
2011        // `a.b.c` is assigned a reference to an initialized and
2012        // well-formed record structure.)
2013
2014        // Therefore, if we seek out the *closest* prefix for which we
2015        // have a MovePath, that should capture the initialization
2016        // state for the place scenario.
2017        //
2018        // This code covers scenarios 1, 2, and 3.
2019
2020        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2020",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2020u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_if_full_path_is_moved place: {0:?}",
                                                    place_span.0) as &dyn Value))])
            });
    } else { ; }
};debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
2021        let (prefix, mpi) = self.move_path_closest_to(place_span.0);
2022        if maybe_uninits.contains(mpi) {
2023            self.report_use_of_moved_or_uninitialized(
2024                location,
2025                desired_action,
2026                (prefix, place_span.0, place_span.1),
2027                mpi,
2028            );
2029        } // Only query longest prefix with a MovePath, not further
2030        // ancestors; dataflow recurs on children when parents
2031        // move (to support partial (re)inits).
2032        //
2033        // (I.e., querying parents breaks scenario 7; but may want
2034        // to do such a query based on partial-init feature-gate.)
2035    }
2036
2037    /// Subslices correspond to multiple move paths, so we iterate through the
2038    /// elements of the base array. For each element we check
2039    ///
2040    /// * Does this element overlap with our slice.
2041    /// * Is any part of it uninitialized.
2042    fn check_if_subslice_element_is_moved(
2043        &mut self,
2044        location: Location,
2045        desired_action: InitializationRequiringAction,
2046        place_span: (PlaceRef<'tcx>, Span),
2047        maybe_uninits: &MixedBitSet<MovePathIndex>,
2048        from: u64,
2049        to: u64,
2050    ) {
2051        if let Some(mpi) = self.move_path_for_place(place_span.0) {
2052            let move_paths = &self.move_data.move_paths;
2053
2054            let root_path = &move_paths[mpi];
2055            for (child_mpi, child_move_path) in root_path.children(move_paths) {
2056                let last_proj = child_move_path.place.projection.last().unwrap();
2057                if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
2058                    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`.");
2059
2060                    if (from..to).contains(offset) {
2061                        let uninit_child =
2062                            self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
2063                                maybe_uninits.contains(mpi)
2064                            });
2065
2066                        if let Some(uninit_child) = uninit_child {
2067                            self.report_use_of_moved_or_uninitialized(
2068                                location,
2069                                desired_action,
2070                                (place_span.0, place_span.0, place_span.1),
2071                                uninit_child,
2072                            );
2073                            return; // don't bother finding other problems.
2074                        }
2075                    }
2076                }
2077            }
2078        }
2079    }
2080
2081    fn check_if_path_or_subpath_is_moved(
2082        &mut self,
2083        location: Location,
2084        desired_action: InitializationRequiringAction,
2085        place_span: (PlaceRef<'tcx>, Span),
2086        state: &BorrowckDomain,
2087    ) {
2088        let maybe_uninits = &state.uninits;
2089
2090        // Bad scenarios:
2091        //
2092        // 1. Move of `a.b.c`, use of `a` or `a.b`
2093        //    partial initialization support, one might have `a.x`
2094        //    initialized but not `a.b`.
2095        // 2. All bad scenarios from `check_if_full_path_is_moved`
2096        //
2097        // OK scenarios:
2098        //
2099        // 3. Move of `a.b.c`, use of `a.b.d`
2100        // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
2101        // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
2102        //    must have been initialized for the use to be sound.
2103        // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
2104
2105        self.check_if_full_path_is_moved(location, desired_action, place_span, state);
2106
2107        if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
2108            place_span.0.last_projection()
2109        {
2110            let place_ty = place_base.ty(self.body(), self.infcx.tcx);
2111            if let ty::Array(..) = place_ty.ty.kind() {
2112                self.check_if_subslice_element_is_moved(
2113                    location,
2114                    desired_action,
2115                    (place_base, place_span.1),
2116                    maybe_uninits,
2117                    from,
2118                    to,
2119                );
2120                return;
2121            }
2122        }
2123
2124        // A move of any shallow suffix of `place` also interferes
2125        // with an attempt to use `place`. This is scenario 3 above.
2126        //
2127        // (Distinct from handling of scenarios 1+2+4 above because
2128        // `place` does not interfere with suffixes of its prefixes,
2129        // e.g., `a.b.c` does not interfere with `a.b.d`)
2130        //
2131        // This code covers scenario 1.
2132
2133        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2133",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2133u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_if_path_or_subpath_is_moved place: {0:?}",
                                                    place_span.0) as &dyn Value))])
            });
    } else { ; }
};debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
2134        if let Some(mpi) = self.move_path_for_place(place_span.0) {
2135            let uninit_mpi = self
2136                .move_data
2137                .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
2138
2139            if let Some(uninit_mpi) = uninit_mpi {
2140                self.report_use_of_moved_or_uninitialized(
2141                    location,
2142                    desired_action,
2143                    (place_span.0, place_span.0, place_span.1),
2144                    uninit_mpi,
2145                );
2146                return; // don't bother finding other problems.
2147            }
2148        }
2149    }
2150
2151    /// Currently MoveData does not store entries for all places in
2152    /// the input MIR. For example it will currently filter out
2153    /// places that are Copy; thus we do not track places of shared
2154    /// reference type. This routine will walk up a place along its
2155    /// prefixes, searching for a foundational place that *is*
2156    /// tracked in the MoveData.
2157    ///
2158    /// An Err result includes a tag indicated why the search failed.
2159    /// Currently this can only occur if the place is built off of a
2160    /// static variable, as we do not track those in the MoveData.
2161    fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
2162        match self.move_data.rev_lookup.find(place) {
2163            LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
2164                (self.move_data.move_paths[mpi].place.as_ref(), mpi)
2165            }
2166            LookupResult::Parent(None) => {
    ::core::panicking::panic_fmt(format_args!("should have move path for every Local"));
}panic!("should have move path for every Local"),
2167        }
2168    }
2169
2170    fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
2171        // If returns None, then there is no move path corresponding
2172        // to a direct owner of `place` (which means there is nothing
2173        // that borrowck tracks for its analysis).
2174
2175        match self.move_data.rev_lookup.find(place) {
2176            LookupResult::Parent(_) => None,
2177            LookupResult::Exact(mpi) => Some(mpi),
2178        }
2179    }
2180
2181    fn check_if_assigned_path_is_moved(
2182        &mut self,
2183        location: Location,
2184        (place, span): (Place<'tcx>, Span),
2185        state: &BorrowckDomain,
2186    ) {
2187        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2187",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2187u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_if_assigned_path_is_moved place: {0:?}",
                                                    place) as &dyn Value))])
            });
    } else { ; }
};debug!("check_if_assigned_path_is_moved place: {:?}", place);
2188
2189        // None case => assigning to `x` does not require `x` be initialized.
2190        for (place_base, elem) in place.iter_projections().rev() {
2191            match elem {
2192                ProjectionElem::Index(_/*operand*/) |
2193                ProjectionElem::OpaqueCast(_) |
2194                ProjectionElem::ConstantIndex { .. } |
2195                // assigning to P[i] requires P to be valid.
2196                ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
2197                // assigning to (P->variant) is okay if assigning to `P` is okay
2198                //
2199                // FIXME: is this true even if P is an adt with a dtor?
2200                { }
2201
2202                ProjectionElem::UnwrapUnsafeBinder(_) => {
2203                    check_parent_of_field(self, location, place_base, span, state);
2204                }
2205
2206                // assigning to (*P) requires P to be initialized
2207                ProjectionElem::Deref => {
2208                    self.check_if_full_path_is_moved(
2209                        location, InitializationRequiringAction::Use,
2210                        (place_base, span), state);
2211                    // (base initialized; no need to
2212                    // recur further)
2213                    break;
2214                }
2215
2216                ProjectionElem::Subslice { .. } => {
2217                    {
    ::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:?}");
2218                }
2219
2220                ProjectionElem::Field(..) => {
2221                    // if type of `P` has a dtor, then
2222                    // assigning to `P.f` requires `P` itself
2223                    // be already initialized
2224                    let tcx = self.infcx.tcx;
2225                    let base_ty = place_base.ty(self.body(), tcx).ty;
2226                    match base_ty.kind() {
2227                        ty::Adt(def, _) if def.has_dtor(tcx) => {
2228                            self.check_if_path_or_subpath_is_moved(
2229                                location, InitializationRequiringAction::Assignment,
2230                                (place_base, span), state);
2231
2232                            // (base initialized; no need to
2233                            // recur further)
2234                            break;
2235                        }
2236
2237                        // Once `let s; s.x = V; read(s.x);`,
2238                        // is allowed, remove this match arm.
2239                        ty::Adt(..) | ty::Tuple(..) => {
2240                            check_parent_of_field(self, location, place_base, span, state);
2241                        }
2242
2243                        _ => {}
2244                    }
2245                }
2246            }
2247        }
2248
2249        fn check_parent_of_field<'a, 'tcx>(
2250            this: &mut MirBorrowckCtxt<'a, '_, 'tcx>,
2251            location: Location,
2252            base: PlaceRef<'tcx>,
2253            span: Span,
2254            state: &BorrowckDomain,
2255        ) {
2256            // rust-lang/rust#21232: Until Rust allows reads from the
2257            // initialized parts of partially initialized structs, we
2258            // will, starting with the 2018 edition, reject attempts
2259            // to write to structs that are not fully initialized.
2260            //
2261            // In other words, *until* we allow this:
2262            //
2263            // 1. `let mut s; s.x = Val; read(s.x);`
2264            //
2265            // we will for now disallow this:
2266            //
2267            // 2. `let mut s; s.x = Val;`
2268            //
2269            // and also this:
2270            //
2271            // 3. `let mut s = ...; drop(s); s.x=Val;`
2272            //
2273            // This does not use check_if_path_or_subpath_is_moved,
2274            // because we want to *allow* reinitializations of fields:
2275            // e.g., want to allow
2276            //
2277            // `let mut s = ...; drop(s.x); s.x=Val;`
2278            //
2279            // This does not use check_if_full_path_is_moved on
2280            // `base`, because that would report an error about the
2281            // `base` as a whole, but in this scenario we *really*
2282            // want to report an error about the actual thing that was
2283            // moved, which may be some prefix of `base`.
2284
2285            // Shallow so that we'll stop at any dereference; we'll
2286            // report errors about issues with such bases elsewhere.
2287            let maybe_uninits = &state.uninits;
2288
2289            // Find the shortest uninitialized prefix you can reach
2290            // without going over a Deref.
2291            let mut shortest_uninit_seen = None;
2292            for prefix in this.prefixes(base, PrefixSet::Shallow) {
2293                let Some(mpi) = this.move_path_for_place(prefix) else { continue };
2294
2295                if maybe_uninits.contains(mpi) {
2296                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2296",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2296u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::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 Value))])
            });
    } else { ; }
};debug!(
2297                        "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
2298                        shortest_uninit_seen,
2299                        Some((prefix, mpi))
2300                    );
2301                    shortest_uninit_seen = Some((prefix, mpi));
2302                } else {
2303                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2303",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2303u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_parent_of_field {0:?} is definitely initialized",
                                                    (prefix, mpi)) as &dyn Value))])
            });
    } else { ; }
};debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
2304                }
2305            }
2306
2307            if let Some((prefix, mpi)) = shortest_uninit_seen {
2308                // Check for a reassignment into an uninitialized field of a union (for example,
2309                // after a move out). In this case, do not report an error here. There is an
2310                // exception, if this is the first assignment into the union (that is, there is
2311                // no move out from an earlier location) then this is an attempt at initialization
2312                // of the union - we should error in that case.
2313                let tcx = this.infcx.tcx;
2314                if base.ty(this.body(), tcx).ty.is_union()
2315                    && this.move_data.path_map[mpi].iter().any(|moi| {
2316                        this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
2317                    })
2318                {
2319                    return;
2320                }
2321
2322                this.report_use_of_moved_or_uninitialized(
2323                    location,
2324                    InitializationRequiringAction::PartialAssignment,
2325                    (prefix, base, span),
2326                    mpi,
2327                );
2328
2329                // rust-lang/rust#21232, #54499, #54986: during period where we reject
2330                // partial initialization, do not complain about unnecessary `mut` on
2331                // an attempt to do a partial initialization.
2332                this.used_mut.insert(base.local);
2333            }
2334        }
2335    }
2336
2337    /// Checks the permissions for the given place and read or write kind
2338    ///
2339    /// Returns `true` if an error is reported.
2340    fn check_access_permissions(
2341        &mut self,
2342        (place, span): (Place<'tcx>, Span),
2343        kind: ReadOrWrite,
2344        is_local_mutation_allowed: LocalMutationIsAllowed,
2345        state: &BorrowckDomain,
2346        location: Location,
2347    ) -> bool {
2348        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2348",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2348u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::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 Value))])
            });
    } else { ; }
};debug!(
2349            "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2350            place, kind, is_local_mutation_allowed
2351        );
2352
2353        let error_access;
2354        let the_place_err;
2355
2356        match kind {
2357            Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind }))
2358            | Write(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind })) => {
2359                let is_local_mutation_allowed = match mut_borrow_kind {
2360                    // `ClosureCapture` is used for mutable variable with an immutable binding.
2361                    // This is only behaviour difference between `ClosureCapture` and mutable
2362                    // borrows.
2363                    MutBorrowKind::ClosureCapture => LocalMutationIsAllowed::Yes,
2364                    MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow => {
2365                        is_local_mutation_allowed
2366                    }
2367                };
2368                match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2369                    Ok(root_place) => {
2370                        self.add_used_mut(root_place, state);
2371                        return false;
2372                    }
2373                    Err(place_err) => {
2374                        error_access = AccessKind::MutableBorrow;
2375                        the_place_err = place_err;
2376                    }
2377                }
2378            }
2379            Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2380                match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2381                    Ok(root_place) => {
2382                        self.add_used_mut(root_place, state);
2383                        return false;
2384                    }
2385                    Err(place_err) => {
2386                        error_access = AccessKind::Mutate;
2387                        the_place_err = place_err;
2388                    }
2389                }
2390            }
2391
2392            Reservation(
2393                WriteKind::Move
2394                | WriteKind::Replace
2395                | WriteKind::StorageDeadOrDrop
2396                | WriteKind::MutableBorrow(BorrowKind::Shared)
2397                | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2398            )
2399            | Write(
2400                WriteKind::Move
2401                | WriteKind::Replace
2402                | WriteKind::StorageDeadOrDrop
2403                | WriteKind::MutableBorrow(BorrowKind::Shared)
2404                | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2405            ) => {
2406                if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2407                    && !self.has_buffered_diags()
2408                {
2409                    // rust-lang/rust#46908: In pure NLL mode this code path should be
2410                    // unreachable, but we use `span_delayed_bug` because we can hit this when
2411                    // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2412                    // enabled. We don't want to ICE for that case, as other errors will have
2413                    // been emitted (#52262).
2414                    self.dcx().span_delayed_bug(
2415                        span,
2416                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Accessing `{0:?}` with the kind `{1:?}` shouldn\'t be possible",
                place, kind))
    })format!(
2417                            "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
2418                        ),
2419                    );
2420                }
2421                return false;
2422            }
2423            Activation(..) => {
2424                // permission checks are done at Reservation point.
2425                return false;
2426            }
2427            Read(
2428                ReadKind::Borrow(BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_))
2429                | ReadKind::Copy,
2430            ) => {
2431                // Access authorized
2432                return false;
2433            }
2434        }
2435
2436        // rust-lang/rust#21232, #54986: during period where we reject
2437        // partial initialization, do not complain about mutability
2438        // errors except for actual mutation (as opposed to an attempt
2439        // to do a partial initialization).
2440        let previously_initialized = self.is_local_ever_initialized(place.local, state);
2441
2442        // at this point, we have set up the error reporting state.
2443        if let Some(init_index) = previously_initialized {
2444            if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2445                // If this is a mutate access to an immutable local variable with no projections
2446                // report the error as an illegal reassignment
2447                let init = &self.move_data.inits[init_index];
2448                let assigned_span = init.span(self.body);
2449                self.report_illegal_reassignment((place, span), assigned_span, place);
2450            } else {
2451                self.report_mutability_error(place, span, the_place_err, error_access, location)
2452            }
2453            true
2454        } else {
2455            false
2456        }
2457    }
2458
2459    fn is_local_ever_initialized(&self, local: Local, state: &BorrowckDomain) -> Option<InitIndex> {
2460        let mpi = self.move_data.rev_lookup.find_local(local)?;
2461        let ii = &self.move_data.init_path_map[mpi];
2462        ii.into_iter().find(|&&index| state.ever_inits.contains(index)).copied()
2463    }
2464
2465    /// Adds the place into the used mutable variables set
2466    fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain) {
2467        match root_place {
2468            RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2469                // If the local may have been initialized, and it is now currently being
2470                // mutated, then it is justified to be annotated with the `mut`
2471                // keyword, since the mutation may be a possible reassignment.
2472                if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2473                    && self.is_local_ever_initialized(local, state).is_some()
2474                {
2475                    self.used_mut.insert(local);
2476                }
2477            }
2478            RootPlace {
2479                place_local: _,
2480                place_projection: _,
2481                is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2482            } => {}
2483            RootPlace {
2484                place_local,
2485                place_projection: place_projection @ [.., _],
2486                is_local_mutation_allowed: _,
2487            } => {
2488                if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2489                    local: place_local,
2490                    projection: place_projection,
2491                }) {
2492                    self.used_mut_upvars.push(field);
2493                }
2494            }
2495        }
2496    }
2497
2498    /// Whether this value can be written or borrowed mutably.
2499    /// Returns the root place if the place passed in is a projection.
2500    fn is_mutable(
2501        &self,
2502        place: PlaceRef<'tcx>,
2503        is_local_mutation_allowed: LocalMutationIsAllowed,
2504    ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2505        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2505",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2505u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("is_mutable: place={0:?}, is_local...={1:?}",
                                                    place, is_local_mutation_allowed) as &dyn Value))])
            });
    } else { ; }
};debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2506        match place.last_projection() {
2507            None => {
2508                let local = &self.body.local_decls[place.local];
2509                match local.mutability {
2510                    Mutability::Not => match is_local_mutation_allowed {
2511                        LocalMutationIsAllowed::Yes => Ok(RootPlace {
2512                            place_local: place.local,
2513                            place_projection: place.projection,
2514                            is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2515                        }),
2516                        LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2517                            place_local: place.local,
2518                            place_projection: place.projection,
2519                            is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2520                        }),
2521                        LocalMutationIsAllowed::No => Err(place),
2522                    },
2523                    Mutability::Mut => Ok(RootPlace {
2524                        place_local: place.local,
2525                        place_projection: place.projection,
2526                        is_local_mutation_allowed,
2527                    }),
2528                }
2529            }
2530            Some((place_base, elem)) => {
2531                match elem {
2532                    ProjectionElem::Deref => {
2533                        let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2534
2535                        // Check the kind of deref to decide
2536                        match base_ty.kind() {
2537                            ty::Ref(_, _, mutbl) => {
2538                                match mutbl {
2539                                    // Shared borrowed data is never mutable
2540                                    hir::Mutability::Not => Err(place),
2541                                    // Mutably borrowed data is mutable, but only if we have a
2542                                    // unique path to the `&mut`
2543                                    hir::Mutability::Mut => {
2544                                        let mode = match self.is_upvar_field_projection(place) {
2545                                            Some(field)
2546                                                if self.upvars[field.index()].is_by_ref() =>
2547                                            {
2548                                                is_local_mutation_allowed
2549                                            }
2550                                            _ => LocalMutationIsAllowed::Yes,
2551                                        };
2552
2553                                        self.is_mutable(place_base, mode)
2554                                    }
2555                                }
2556                            }
2557                            ty::RawPtr(_, mutbl) => {
2558                                match mutbl {
2559                                    // `*const` raw pointers are not mutable
2560                                    hir::Mutability::Not => Err(place),
2561                                    // `*mut` raw pointers are always mutable, regardless of
2562                                    // context. The users have to check by themselves.
2563                                    hir::Mutability::Mut => Ok(RootPlace {
2564                                        place_local: place.local,
2565                                        place_projection: place.projection,
2566                                        is_local_mutation_allowed,
2567                                    }),
2568                                }
2569                            }
2570                            // `Box<T>` owns its content, so mutable if its location is mutable
2571                            _ if base_ty.is_box() => {
2572                                self.is_mutable(place_base, is_local_mutation_allowed)
2573                            }
2574                            // Deref should only be for reference, pointers or boxes
2575                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Deref of unexpected type: {0:?}",
        base_ty))bug!("Deref of unexpected type: {:?}", base_ty),
2576                        }
2577                    }
2578                    // Check as the inner reference type if it is a field projection
2579                    // from the `&pin` pattern
2580                    ProjectionElem::Field(FieldIdx::ZERO, _)
2581                        if let Some(adt) =
2582                            place_base.ty(self.body(), self.infcx.tcx).ty.ty_adt_def()
2583                            && adt.is_pin()
2584                            && self.infcx.tcx.features().pin_ergonomics() =>
2585                    {
2586                        self.is_mutable(place_base, is_local_mutation_allowed)
2587                    }
2588                    // All other projections are owned by their base path, so mutable if
2589                    // base path is mutable
2590                    ProjectionElem::Field(..)
2591                    | ProjectionElem::Index(..)
2592                    | ProjectionElem::ConstantIndex { .. }
2593                    | ProjectionElem::Subslice { .. }
2594                    | ProjectionElem::OpaqueCast { .. }
2595                    | ProjectionElem::Downcast(..)
2596                    | ProjectionElem::UnwrapUnsafeBinder(_) => {
2597                        let upvar_field_projection = self.is_upvar_field_projection(place);
2598                        if let Some(field) = upvar_field_projection {
2599                            let upvar = &self.upvars[field.index()];
2600                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/lib.rs:2600",
                        "rustc_borrowck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2600u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::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 Value))])
            });
    } else { ; }
};debug!(
2601                                "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2602                                 place={:?}, place_base={:?}",
2603                                upvar, is_local_mutation_allowed, place, place_base
2604                            );
2605                            match (upvar.mutability, is_local_mutation_allowed) {
2606                                (
2607                                    Mutability::Not,
2608                                    LocalMutationIsAllowed::No
2609                                    | LocalMutationIsAllowed::ExceptUpvars,
2610                                ) => Err(place),
2611                                (Mutability::Not, LocalMutationIsAllowed::Yes)
2612                                | (Mutability::Mut, _) => {
2613                                    // Subtle: this is an upvar reference, so it looks like
2614                                    // `self.foo` -- we want to double check that the location
2615                                    // `*self` is mutable (i.e., this is not a `Fn` closure). But
2616                                    // if that check succeeds, we want to *blame* the mutability on
2617                                    // `place` (that is, `self.foo`). This is used to propagate the
2618                                    // info about whether mutability declarations are used
2619                                    // outwards, so that we register the outer variable as mutable.
2620                                    // Otherwise a test like this fails to record the `mut` as
2621                                    // needed:
2622                                    // ```
2623                                    // fn foo<F: FnOnce()>(_f: F) { }
2624                                    // fn main() {
2625                                    //     let var = Vec::new();
2626                                    //     foo(move || {
2627                                    //         var.push(1);
2628                                    //     });
2629                                    // }
2630                                    // ```
2631                                    let _ =
2632                                        self.is_mutable(place_base, is_local_mutation_allowed)?;
2633                                    Ok(RootPlace {
2634                                        place_local: place.local,
2635                                        place_projection: place.projection,
2636                                        is_local_mutation_allowed,
2637                                    })
2638                                }
2639                            }
2640                        } else {
2641                            self.is_mutable(place_base, is_local_mutation_allowed)
2642                        }
2643                    }
2644                }
2645            }
2646        }
2647    }
2648
2649    /// If `place` is a field projection, and the field is being projected from a closure type,
2650    /// then returns the index of the field being projected. Note that this closure will always
2651    /// be `self` in the current MIR, because that is the only time we directly access the fields
2652    /// of a closure type.
2653    fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
2654        path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2655    }
2656
2657    fn dominators(&self) -> &Dominators<BasicBlock> {
2658        // `BasicBlocks` computes dominators on-demand and caches them.
2659        self.body.basic_blocks.dominators()
2660    }
2661
2662    fn lint_unused_mut(&self) {
2663        let tcx = self.infcx.tcx;
2664        let body = self.body;
2665        for local in body.mut_vars_and_args_iter().filter(|local| !self.used_mut.contains(local)) {
2666            let local_decl = &body.local_decls[local];
2667            let ClearCrossCrate::Set(SourceScopeLocalData { lint_root, .. }) =
2668                body.source_scopes[local_decl.source_info.scope].local_data
2669            else {
2670                continue;
2671            };
2672
2673            // Skip over locals that begin with an underscore or have no name
2674            if self.local_excluded_from_unused_mut_lint(local) {
2675                continue;
2676            }
2677
2678            let span = local_decl.source_info.span;
2679            if span.desugaring_kind().is_some() {
2680                // If the `mut` arises as part of a desugaring, we should ignore it.
2681                continue;
2682            }
2683
2684            let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
2685
2686            tcx.emit_node_span_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
2687        }
2688    }
2689}
2690
2691/// The degree of overlap between 2 places for borrow-checking.
2692enum Overlap {
2693    /// The places might partially overlap - in this case, we give
2694    /// up and say that they might conflict. This occurs when
2695    /// different fields of a union are borrowed. For example,
2696    /// if `u` is a union, we have no way of telling how disjoint
2697    /// `u.a.x` and `a.b.y` are.
2698    Arbitrary,
2699    /// The places have the same type, and are either completely disjoint
2700    /// or equal - i.e., they can't "partially" overlap as can occur with
2701    /// unions. This is the "base case" on which we recur for extensions
2702    /// of the place.
2703    EqualOrDisjoint,
2704    /// The places are disjoint, so we know all extensions of them
2705    /// will also be disjoint.
2706    Disjoint,
2707}