Skip to main content

rustc_borrowck/
lib.rs

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