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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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