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