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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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