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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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