Skip to main content

rustc_hir_typeck/
upvar.rs

1//! ### Inferring borrow kinds for upvars
2//!
3//! Whenever there is a closure expression, we need to determine how each
4//! upvar is used. We do this by initially assigning each upvar an
5//! immutable "borrow kind" (see `ty::BorrowKind` for details) and then
6//! "escalating" the kind as needed. The borrow kind proceeds according to
7//! the following lattice:
8//! ```ignore (not-rust)
9//! ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
10//! ```
11//! So, for example, if we see an assignment `x = 5` to an upvar `x`, we
12//! will promote its borrow kind to mutable borrow. If we see an `&mut x`
13//! we'll do the same. Naturally, this applies not just to the upvar, but
14//! to everything owned by `x`, so the result is the same for something
15//! like `x.f = 5` and so on (presuming `x` is not a borrowed pointer to a
16//! struct). These adjustments are performed in
17//! `adjust_for_non_move_closure` (you can trace backwards through the code
18//! from there).
19//!
20//! The fact that we are inferring borrow kinds as we go results in a
21//! semi-hacky interaction with the way `ExprUseVisitor` is computing
22//! `Place`s. In particular, it will query the current borrow kind as it
23//! goes, and we'll return the *current* value, but this may get
24//! adjusted later. Therefore, in this module, we generally ignore the
25//! borrow kind (and derived mutabilities) that `ExprUseVisitor` returns
26//! within `Place`s, since they may be inaccurate. (Another option
27//! would be to use a unification scheme, where instead of returning a
28//! concrete borrow kind like `ty::ImmBorrow`, we return a
29//! `ty::InferBorrow(upvar_id)` or something like that, but this would
30//! then mean that all later passes would have to check for these figments
31//! and report an error, and it just seems like more mess in the end.)
32
33use std::iter;
34
35use rustc_abi::FIRST_VARIANT;
36use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
37use rustc_data_structures::unord::{ExtendUnord, UnordSet};
38use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
39use rustc_hir::attrs::lang_items::LangItem;
40use rustc_hir::def_id::LocalDefId;
41use rustc_hir::intravisit::{self, Visitor};
42use rustc_hir::{self as hir, HirId, find_attr};
43use rustc_lint_defs::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES;
44use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
45use rustc_middle::mir::FakeReadCause;
46use rustc_middle::traits::ObligationCauseCode;
47use rustc_middle::ty::{
48    self, BorrowKind, ClosureSizeProfileData, Ty, TyCtxt, TypeVisitableExt as _, TypeckResults,
49    Unnormalized, UpvarArgs, UpvarCapture,
50};
51use rustc_span::{BytePos, Pos, Span, Symbol, bug, span_bug, sym};
52use rustc_trait_selection::infer::InferCtxtExt;
53use tracing::{debug, instrument};
54
55use super::FnCtxt;
56use crate::expr_use_visitor as euv;
57use crate::expr_use_visitor::Delegate as _;
58
59/// Describe the relationship between the paths of two places
60/// eg:
61/// - `foo` is ancestor of `foo.bar.baz`
62/// - `foo.bar.baz` is an descendant of `foo.bar`
63/// - `foo.bar` and `foo.baz` are divergent
64enum PlaceAncestryRelation {
65    Ancestor,
66    Descendant,
67    SamePlace,
68    Divergent,
69}
70
71/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
72/// during capture analysis. Information in this map feeds into the minimum capture
73/// analysis pass.
74type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
75
76impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
77    pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
78        InferBorrowKindVisitor { fcx: self }.visit_body(body);
79
80        // it's our job to process these.
81        if !self.deferred_call_resolutions.borrow().is_empty() {
    ::core::panicking::panic("assertion failed: self.deferred_call_resolutions.borrow().is_empty()")
};assert!(self.deferred_call_resolutions.borrow().is_empty());
82    }
83
84    pub(crate) fn infer_closure_kind_for_diagnostic(
85        &self,
86        closure_def_id: LocalDefId,
87    ) -> Option<(ty::ClosureKind, Option<(Span, Place<'tcx>)>)> {
88        let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
89        let hir::Node::Expr(expr) = self.tcx.hir_node_by_def_id(closure_def_id) else {
90            return None;
91        };
92        let hir::ExprKind::Closure(&hir::Closure {
93            capture_clause,
94            body: body_id,
95            explicit_captures,
96            ..
97        }) = expr.kind
98        else {
99            return None;
100        };
101        let body = self.tcx.hir_body(body_id);
102
103        // We cannot reliably infer the closure kind if there are nested closures whose
104        // captures have not yet been analyzed.
105        struct HasNestedClosure(bool);
106        impl<'v> Visitor<'v> for HasNestedClosure {
107            fn visit_expr(&mut self, expr: &'v hir::Expr<'v>) {
108                if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Closure(..) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Closure(..)) {
109                    self.0 = true;
110                    return;
111                }
112                intravisit::walk_expr(self, expr);
113            }
114        }
115        let mut has_nested = HasNestedClosure(false);
116        has_nested.visit_body(body);
117        if has_nested.0 {
118            return None;
119        }
120
121        let closure_fcx = FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id);
122
123        let mut delegate = InferBorrowKind {
124            fcx: &closure_fcx,
125            closure_def_id,
126            capture_information: Default::default(),
127            fake_reads: Default::default(),
128        };
129
130        let _ = euv::ExprUseVisitor::new(&closure_fcx, &mut delegate).consume_body(body);
131
132        for capture in explicit_captures {
133            let place = closure_fcx.place_for_root_variable(closure_def_id, capture.var_hir_id);
134            delegate.consume(&PlaceWithHirId { hir_id: capture.var_hir_id, place }, hir_id);
135        }
136
137        let (_, closure_kind, mut origin) = self
138            .process_collected_capture_information(capture_clause, &delegate.capture_information);
139
140        // Bail out if a by-value capture has unresolved inference variables, since
141        // fallback might later resolve the type to `Copy` (making the closure `Fn`).
142        if closure_kind == ty::ClosureKind::FnOnce {
143            for (place, capture_info) in &delegate.capture_information {
144                if #[allow(non_exhaustive_omitted_patterns)] match capture_info.capture_kind {
    ty::UpvarCapture::ByValue => true,
    _ => false,
}matches!(capture_info.capture_kind, ty::UpvarCapture::ByValue)
145                    && place.ty().has_infer()
146                {
147                    return None;
148                }
149            }
150        }
151
152        if !enable_precise_capture(expr.span) {
153            if let Some((_, ref mut place)) = origin {
154                place.projections.clear();
155            }
156        }
157
158        Some((closure_kind, origin))
159    }
160}
161
162/// Intermediate format to store the hir_id pointing to the use that resulted in the
163/// corresponding place being captured and a String which contains the captured value's
164/// name (i.e: a.b.c)
165#[derive(#[automatically_derived]
impl ::core::clone::Clone for UpvarMigrationInfo {
    #[inline]
    fn clone(&self) -> UpvarMigrationInfo {
        match self {
            UpvarMigrationInfo::CapturingPrecise {
                source_expr: __self_0, var_name: __self_1 } =>
                UpvarMigrationInfo::CapturingPrecise {
                    source_expr: ::core::clone::Clone::clone(__self_0),
                    var_name: ::core::clone::Clone::clone(__self_1),
                },
            UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
                UpvarMigrationInfo::CapturingNothing {
                    use_span: ::core::clone::Clone::clone(__self_0),
                },
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for UpvarMigrationInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            UpvarMigrationInfo::CapturingPrecise {
                source_expr: __self_0, var_name: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "CapturingPrecise", "source_expr", __self_0, "var_name",
                    &__self_1),
            UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "CapturingNothing", "use_span", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for UpvarMigrationInfo { }
#[automatically_derived]
impl ::core::cmp::PartialEq for UpvarMigrationInfo {
    #[inline]
    fn eq(&self, other: &UpvarMigrationInfo) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (UpvarMigrationInfo::CapturingPrecise {
                    source_expr: __self_0, var_name: __self_1 },
                    UpvarMigrationInfo::CapturingPrecise {
                    source_expr: __arg1_0, var_name: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (UpvarMigrationInfo::CapturingNothing { use_span: __self_0 },
                    UpvarMigrationInfo::CapturingNothing { use_span: __arg1_0 })
                    => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for UpvarMigrationInfo {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<HirId>>;
        let _: ::core::cmp::AssertParamIsEq<String>;
        let _: ::core::cmp::AssertParamIsEq<Span>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for UpvarMigrationInfo {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            UpvarMigrationInfo::CapturingPrecise {
                source_expr: __self_0, var_name: __self_1 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash)]
166enum UpvarMigrationInfo {
167    /// We previously captured all of `x`, but now we capture some sub-path.
168    CapturingPrecise { source_expr: Option<HirId>, var_name: String },
169    CapturingNothing {
170        // where the variable appears in the closure (but is not captured)
171        use_span: Span,
172    },
173}
174
175/// Reasons that we might issue a migration warning.
176#[derive(#[automatically_derived]
impl ::core::clone::Clone for MigrationWarningReason {
    #[inline]
    fn clone(&self) -> MigrationWarningReason {
        MigrationWarningReason {
            auto_traits: ::core::clone::Clone::clone(&self.auto_traits),
            drop_order: ::core::clone::Clone::clone(&self.drop_order),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for MigrationWarningReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "MigrationWarningReason", "auto_traits", &self.auto_traits,
            "drop_order", &&self.drop_order)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for MigrationWarningReason {
    #[inline]
    fn default() -> MigrationWarningReason {
        MigrationWarningReason {
            auto_traits: ::core::default::Default::default(),
            drop_order: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MigrationWarningReason { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MigrationWarningReason {
    #[inline]
    fn eq(&self, other: &MigrationWarningReason) -> bool {
        self.drop_order == other.drop_order &&
            self.auto_traits == other.auto_traits
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MigrationWarningReason {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Vec<&'static str>>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MigrationWarningReason {
    #[inline]
    fn partial_cmp(&self, other: &MigrationWarningReason)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MigrationWarningReason {
    #[inline]
    fn cmp(&self, other: &MigrationWarningReason) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.auto_traits, &other.auto_traits) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.drop_order, &other.drop_order),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::hash::Hash for MigrationWarningReason {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.auto_traits, state);
        ::core::hash::Hash::hash(&self.drop_order, state)
    }
}Hash)]
177struct MigrationWarningReason {
178    /// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
179    /// in this vec, but now we don't.
180    auto_traits: Vec<&'static str>,
181
182    /// When we used to capture `x` in its entirety, we would execute some destructors
183    /// at a different time.
184    drop_order: bool,
185}
186
187impl MigrationWarningReason {
188    fn migration_message(&self) -> String {
189        let base = "changes to closure capture in Rust 2021 will affect";
190        if !self.auto_traits.is_empty() && self.drop_order {
191            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} drop order and which traits the closure implements",
                base))
    })format!("{base} drop order and which traits the closure implements")
192        } else if self.drop_order {
193            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} drop order", base))
    })format!("{base} drop order")
194        } else {
195            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} which traits the closure implements",
                base))
    })format!("{base} which traits the closure implements")
196        }
197    }
198}
199
200/// Intermediate format to store information needed to generate a note in the migration lint.
201struct MigrationLintNote {
202    captures_info: UpvarMigrationInfo,
203
204    /// reasons why migration is needed for this capture
205    reason: MigrationWarningReason,
206}
207
208/// Intermediate format to store the hir id of the root variable and a HashSet containing
209/// information on why the root variable should be fully captured
210struct NeededMigration {
211    var_hir_id: HirId,
212    diagnostics_info: Vec<MigrationLintNote>,
213}
214
215struct InferBorrowKindVisitor<'a, 'tcx> {
216    fcx: &'a FnCtxt<'a, 'tcx>,
217}
218
219impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
220    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
221        match expr.kind {
222            hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
223                let body = self.fcx.tcx.hir_body(body_id);
224                self.visit_body(body);
225                self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
226            }
227            _ => {}
228        }
229
230        intravisit::walk_expr(self, expr);
231    }
232
233    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
234        let body = self.fcx.tcx.hir_body(c.body);
235        self.visit_body(body);
236    }
237}
238
239impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
240    /// Analysis starting point.
241    {}
#[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("analyze_closure",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(241u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("body_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("body_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("capture_clause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("capture_clause");
                                                        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(&closure_hir_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_clause)
                                                            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 ty = self.node_ty(closure_hir_id);
            let (closure_def_id, args, infer_kind) =
                match *ty.kind() {
                    ty::Closure(def_id, args) => {
                        (def_id, UpvarArgs::Closure(args),
                            self.closure_kind(ty).is_none())
                    }
                    ty::CoroutineClosure(def_id, args) => {
                        (def_id, UpvarArgs::CoroutineClosure(args),
                            self.closure_kind(ty).is_none())
                    }
                    ty::Coroutine(def_id, args) =>
                        (def_id, UpvarArgs::Coroutine(args), false),
                    ty::Error(_) => { return; }
                    _ => {
                        bug_impl(Some(span),
                            format_args!("type of closure expr {0:?} is not a closure {1:?}",
                                closure_hir_id, ty), Location::caller());
                    }
                };
            let args = self.deeply_resolve_ignoring_regions(args);
            let closure_def_id = closure_def_id.expect_local();
            {
                match (&self.tcx.hir_body_owner_def_id(body.id()),
                        &closure_def_id) {
                    (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);
                        }
                    }
                }
            };
            let closure_fcx =
                FnCtxt::new(self, self.tcx.param_env(closure_def_id),
                    closure_def_id);
            let mut delegate =
                InferBorrowKind {
                    fcx: &closure_fcx,
                    closure_def_id,
                    capture_information: Default::default(),
                    fake_reads: Default::default(),
                };
            let _ =
                euv::ExprUseVisitor::new(&closure_fcx,
                        &mut delegate).consume_body(body);
            let explicit_captures =
                match self.tcx.hir_node(closure_hir_id).expect_expr().kind {
                    hir::ExprKind::Closure(closure) =>
                        closure.explicit_captures,
                    _ =>
                        bug_impl(None,
                            format_args!("expected closure expr for {0:?}",
                                closure_hir_id), Location::caller()),
                };
            if let UpvarArgs::Coroutine(..) = args &&
                                let hir::CoroutineKind::Desugared(_,
                                    hir::CoroutineSource::Closure) =
                                    self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
                            &&
                            let parent_hir_id =
                                self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
                        && let parent_ty = self.node_ty(parent_hir_id) &&
                    let hir::CaptureBy::Value { move_kw } =
                        self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
                {
                if let Some(ty::ClosureKind::FnOnce) =
                        self.closure_kind(parent_ty) {
                    capture_clause = hir::CaptureBy::Value { move_kw };
                } else if self.coroutine_body_consumes_upvars(closure_def_id,
                        body) {
                    capture_clause = hir::CaptureBy::Value { move_kw };
                }
            }
            if let Some(hir::CoroutineKind::Desugared(_,
                    hir::CoroutineSource::Fn | hir::CoroutineSource::Closure)) =
                    self.tcx.coroutine_kind(closure_def_id) {
                let hir::ExprKind::Block(block, _) =
                    body.value.kind else {
                        bug_impl(None, format_args!("impossible case reached"),
                            Location::caller());
                    };
                for stmt in block.stmts {
                    let hir::StmtKind::Let(hir::LetStmt {
                            init: Some(init), source: hir::LocalSource::AsyncFn, pat, ..
                            }) =
                        stmt.kind else {
                            bug_impl(None, format_args!("impossible case reached"),
                                Location::caller());
                        };
                    let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No,
                            _), _, _, _) = pat.kind else { continue; };
                    let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) =
                        init.kind else {
                            bug_impl(None, format_args!("impossible case reached"),
                                Location::caller());
                        };
                    let hir::def::Res::Local(local_id) =
                        path.res else {
                            bug_impl(None, format_args!("impossible case reached"),
                                Location::caller());
                        };
                    let place =
                        closure_fcx.place_for_root_variable(closure_def_id,
                            local_id);
                    delegate.capture_information.push((place,
                            ty::CaptureInfo {
                                capture_kind_expr_id: Some(init.hir_id),
                                path_expr_id: Some(init.hir_id),
                                capture_kind: UpvarCapture::ByValue,
                            }));
                }
            }
            {
                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_hir_typeck/src/upvar.rs:389",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(389u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::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!("For closure={0:?}, capture_information={1:#?}",
                                                                closure_def_id, delegate.capture_information) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            self.log_capture_analysis_first_pass(closure_def_id,
                &delegate.capture_information, span);
            let (mut capture_information, closure_kind, origin) =
                self.process_collected_capture_information(capture_clause,
                    &delegate.capture_information);
            for capture in explicit_captures {
                let place =
                    closure_fcx.place_for_root_variable(closure_def_id,
                        capture.var_hir_id);
                capture_information.push((place,
                        ty::CaptureInfo {
                            capture_kind_expr_id: Some(closure_hir_id),
                            path_expr_id: Some(closure_hir_id),
                            capture_kind: UpvarCapture::ByValue,
                        }));
            }
            self.compute_min_captures(closure_def_id, capture_information,
                span);
            let closure_hir_id =
                self.tcx.local_def_id_to_hir_id(closure_def_id);
            if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx,
                    closure_hir_id) {
                self.perform_2229_migration_analysis(closure_def_id, body_id,
                    capture_clause, span);
            }
            let after_feature_tys = self.final_upvar_tys(closure_def_id);
            if !enable_precise_capture(span) {
                let mut capture_information:
                        InferredCaptureInformation<'tcx> = Default::default();
                if let Some(upvars) =
                        self.tcx.upvars_mentioned(closure_def_id) {
                    for var_hir_id in upvars.keys() {
                        let place =
                            closure_fcx.place_for_root_variable(closure_def_id,
                                *var_hir_id);
                        {
                            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_hir_typeck/src/upvar.rs:434",
                                                "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                                ::tracing_core::__macro_support::Option::Some(434u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                                ::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!("seed place {0:?}",
                                                                            place) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let capture_kind =
                            self.init_capture_kind_for_place(&place, capture_clause);
                        let fake_info =
                            ty::CaptureInfo {
                                capture_kind_expr_id: None,
                                path_expr_id: None,
                                capture_kind,
                            };
                        capture_information.push((place, fake_info));
                    }
                }
                self.compute_min_captures(closure_def_id, capture_information,
                    span);
            }
            let before_feature_tys = self.final_upvar_tys(closure_def_id);
            if infer_kind {
                let closure_kind_ty =
                    match args {
                        UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
                        UpvarArgs::CoroutineClosure(args) =>
                            args.as_coroutine_closure().kind_ty(),
                        UpvarArgs::Coroutine(_) => {
                            ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                    format_args!("coroutines don\'t have an inferred kind")));
                        }
                    };
                self.demand_eqtype(span,
                    Ty::from_closure_kind(self.tcx, closure_kind),
                    closure_kind_ty);
                if let Some(mut origin) = origin {
                    if !enable_precise_capture(span) {
                        origin.1.projections.clear()
                    }
                    self.typeck_results.borrow_mut().closure_kind_origins_mut().insert(closure_hir_id,
                        origin);
                }
            }
            if let UpvarArgs::CoroutineClosure(args) = args {
                if let Some(guar) = args.error_reported().err() {
                    self.demand_eqtype(span,
                        args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
                        Ty::new_error(self.tcx, guar));
                } else {
                    let closure_env_region: ty::Region<'_> =
                        ty::Region::new_bound(self.tcx, ty::INNERMOST,
                            ty::BoundRegion {
                                var: ty::BoundVar::ZERO,
                                kind: ty::BoundRegionKind::ClosureEnv,
                            });
                    let num_args =
                        args.as_coroutine_closure().coroutine_closure_sig().skip_binder().tupled_inputs_ty.tuple_fields().len();
                    let typeck_results = self.typeck_results.borrow();
                    let tupled_upvars_ty_for_borrow =
                        Ty::new_tup_from_iter(self.tcx,
                            ty::analyze_coroutine_closure_captures(typeck_results.closure_min_captures_flattened(closure_def_id),
                                typeck_results.closure_min_captures_flattened(self.tcx.coroutine_for_closure(closure_def_id).expect_local()).skip(num_args),
                                |(_, parent_capture), (_, child_capture)|
                                    {
                                        let needs_ref =
                                            should_reborrow_from_env_of_parent_coroutine_closure(parent_capture,
                                                child_capture);
                                        let upvar_ty = child_capture.place.ty();
                                        let capture = child_capture.info.capture_kind;
                                        apply_capture_kind_on_capture_ty(self.tcx, upvar_ty,
                                            capture,
                                            if needs_ref {
                                                closure_env_region
                                            } else { self.tcx.lifetimes.re_erased })
                                    }));
                    let coroutine_captures_by_ref_ty =
                        Ty::new_fn_ptr(self.tcx,
                            ty::Binder::bind_with_vars(self.tcx.mk_fn_sig_safe_rust_abi([],
                                    tupled_upvars_ty_for_borrow),
                                self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)])));
                    self.demand_eqtype(span,
                        args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
                        coroutine_captures_by_ref_ty);
                    if infer_kind {
                        let ty::Coroutine(_, coroutine_args) =
                            *self.typeck_results.borrow().expr_ty(body.value).kind() else {
                                bug_impl(None, format_args!("impossible case reached"),
                                    Location::caller());
                            };
                        self.demand_eqtype(span,
                            coroutine_args.as_coroutine().kind_ty(),
                            Ty::from_coroutine_closure_kind(self.tcx, closure_kind));
                    }
                }
            }
            self.log_closure_min_capture_info(closure_def_id, span);
            let final_upvar_tys = self.final_upvar_tys(closure_def_id);
            {
                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_hir_typeck/src/upvar.rs:606",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(606u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("final_upvar_tys")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("final_upvar_tys");
                                                        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(&closure_hir_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&final_upvar_tys)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if self.tcx.features().unsized_fn_params() {
                for capture in
                    self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
                    {
                    if let UpvarCapture::ByValue = capture.info.capture_kind {
                        self.require_type_is_sized(capture.place.ty(),
                            capture.get_path_span(self.tcx),
                            ObligationCauseCode::SizedClosureCapture(closure_def_id));
                    }
                }
            }
            let final_tupled_upvars_type =
                Ty::new_tup(self.tcx, &final_upvar_tys);
            self.demand_suptype(span, args.tupled_upvars_ty(),
                final_tupled_upvars_type);
            let fake_reads = delegate.fake_reads;
            self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id,
                fake_reads);
            if self.tcx.sess.opts.unstable_opts.profile_closures {
                self.typeck_results.borrow_mut().closure_size_eval.insert(closure_def_id,
                    ClosureSizeProfileData {
                        before_feature_tys: Ty::new_tup(self.tcx,
                            &before_feature_tys),
                        after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
                    });
            }
            let deferred_call_resolutions =
                self.remove_deferred_call_resolutions(closure_def_id);
            for deferred_call_resolution in deferred_call_resolutions {
                deferred_call_resolution.resolve(&FnCtxt::new(self,
                            self.param_env, closure_def_id));
            }
        }
    }
}#[instrument(skip(self, body), level = "debug")]
242    fn analyze_closure(
243        &self,
244        closure_hir_id: HirId,
245        span: Span,
246        body_id: hir::BodyId,
247        body: &'tcx hir::Body<'tcx>,
248        mut capture_clause: hir::CaptureBy,
249    ) {
250        // Extract the type of the closure.
251        let ty = self.node_ty(closure_hir_id);
252        let (closure_def_id, args, infer_kind) = match *ty.kind() {
253            ty::Closure(def_id, args) => {
254                (def_id, UpvarArgs::Closure(args), self.closure_kind(ty).is_none())
255            }
256            ty::CoroutineClosure(def_id, args) => {
257                (def_id, UpvarArgs::CoroutineClosure(args), self.closure_kind(ty).is_none())
258            }
259            ty::Coroutine(def_id, args) => (def_id, UpvarArgs::Coroutine(args), false),
260            ty::Error(_) => {
261                // #51714: skip analysis when we have already encountered type errors
262                return;
263            }
264            _ => {
265                span_bug!(
266                    span,
267                    "type of closure expr {:?} is not a closure {:?}",
268                    closure_hir_id,
269                    ty
270                );
271            }
272        };
273        let args = self.deeply_resolve_ignoring_regions(args);
274        let closure_def_id = closure_def_id.expect_local();
275
276        assert_eq!(self.tcx.hir_body_owner_def_id(body.id()), closure_def_id);
277
278        let closure_fcx = FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id);
279
280        let mut delegate = InferBorrowKind {
281            fcx: &closure_fcx,
282            closure_def_id,
283            capture_information: Default::default(),
284            fake_reads: Default::default(),
285        };
286
287        // First collect the captures implied by the operations in the closure
288        // body. This records how each place is actually used: borrowed, modified,
289        // moved, and so on.
290        let _ = euv::ExprUseVisitor::new(&closure_fcx, &mut delegate).consume_body(body);
291
292        // Save the captures that must be upgraded to by-value after inferring
293        // the closure kind from the operations in the body.
294        let explicit_captures = match self.tcx.hir_node(closure_hir_id).expect_expr().kind {
295            hir::ExprKind::Closure(closure) => closure.explicit_captures,
296            _ => bug!("expected closure expr for {:?}", closure_hir_id),
297        };
298
299        // There are several curious situations with coroutine-closures where
300        // analysis is too aggressive with borrows when the coroutine-closure is
301        // marked `move`. Specifically:
302        //
303        // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
304        // inference, then it's still possible that we try to borrow upvars from
305        // the coroutine-closure because they are not used by the coroutine body
306        // in a way that forces a move. See the test:
307        // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
308        //
309        // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
310        // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
311        // would force the closure to `FnOnce`.
312        // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
313        //
314        // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
315        // coroutine bodies can't borrow from their parent closure. To fix this,
316        // we force the inner coroutine to also be `move`. This only matters for
317        // coroutine-closures that are `move` since otherwise they themselves will
318        // be borrowing from the outer environment, so there's no self-borrows occurring.
319        if let UpvarArgs::Coroutine(..) = args
320            && let hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) =
321                self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
322            && let parent_hir_id =
323                self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
324            && let parent_ty = self.node_ty(parent_hir_id)
325            && let hir::CaptureBy::Value { move_kw } =
326                self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
327        {
328            // (1.) Closure signature inference forced this closure to `FnOnce`.
329            if let Some(ty::ClosureKind::FnOnce) = self.closure_kind(parent_ty) {
330                capture_clause = hir::CaptureBy::Value { move_kw };
331            }
332            // (2.) The way that the closure uses its upvars means it's `FnOnce`.
333            else if self.coroutine_body_consumes_upvars(closure_def_id, body) {
334                capture_clause = hir::CaptureBy::Value { move_kw };
335            }
336        }
337
338        // As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
339        // to `ByRef` for the `async {}` block internal to async fns/closure. This means
340        // that we would *not* be moving all of the parameters into the async block in all cases.
341        // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
342        // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
343        //
344        // We force all of these arguments to be captured by move before we do expr use analysis.
345        //
346        // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
347        // moving all of the `LocalSource::AsyncFn` locals here.
348        if let Some(hir::CoroutineKind::Desugared(
349            _,
350            hir::CoroutineSource::Fn | hir::CoroutineSource::Closure,
351        )) = self.tcx.coroutine_kind(closure_def_id)
352        {
353            let hir::ExprKind::Block(block, _) = body.value.kind else {
354                bug!();
355            };
356            for stmt in block.stmts {
357                let hir::StmtKind::Let(hir::LetStmt {
358                    init: Some(init),
359                    source: hir::LocalSource::AsyncFn,
360                    pat,
361                    ..
362                }) = stmt.kind
363                else {
364                    bug!();
365                };
366                let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), _, _, _) = pat.kind
367                else {
368                    // Complex pattern, skip the non-upvar local.
369                    continue;
370                };
371                let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = init.kind else {
372                    bug!();
373                };
374                let hir::def::Res::Local(local_id) = path.res else {
375                    bug!();
376                };
377                let place = closure_fcx.place_for_root_variable(closure_def_id, local_id);
378                delegate.capture_information.push((
379                    place,
380                    ty::CaptureInfo {
381                        capture_kind_expr_id: Some(init.hir_id),
382                        path_expr_id: Some(init.hir_id),
383                        capture_kind: UpvarCapture::ByValue,
384                    },
385                ));
386            }
387        }
388
389        debug!(
390            "For closure={:?}, capture_information={:#?}",
391            closure_def_id, delegate.capture_information
392        );
393
394        self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
395
396        let (mut capture_information, closure_kind, origin) = self
397            .process_collected_capture_information(capture_clause, &delegate.capture_information);
398
399        // `move(expr)` requires its synthetic local to be captured by value,
400        // regardless of how the closure body uses it. Apply that requirement
401        // after closure-kind inference so capturing a value does not by itself
402        // make the closure `FnOnce`.
403        for capture in explicit_captures {
404            let place = closure_fcx.place_for_root_variable(closure_def_id, capture.var_hir_id);
405            capture_information.push((
406                place,
407                ty::CaptureInfo {
408                    capture_kind_expr_id: Some(closure_hir_id),
409                    path_expr_id: Some(closure_hir_id),
410                    capture_kind: UpvarCapture::ByValue,
411                },
412            ));
413        }
414
415        self.compute_min_captures(closure_def_id, capture_information, span);
416
417        let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
418
419        if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
420            self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
421        }
422
423        let after_feature_tys = self.final_upvar_tys(closure_def_id);
424
425        // We now fake capture information for all variables that are mentioned within the closure
426        // We do this after handling migrations so that min_captures computes before
427        if !enable_precise_capture(span) {
428            let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
429
430            if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
431                for var_hir_id in upvars.keys() {
432                    let place = closure_fcx.place_for_root_variable(closure_def_id, *var_hir_id);
433
434                    debug!("seed place {:?}", place);
435
436                    let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
437                    let fake_info = ty::CaptureInfo {
438                        capture_kind_expr_id: None,
439                        path_expr_id: None,
440                        capture_kind,
441                    };
442
443                    capture_information.push((place, fake_info));
444                }
445            }
446
447            // This will update the min captures based on this new fake information.
448            self.compute_min_captures(closure_def_id, capture_information, span);
449        }
450
451        let before_feature_tys = self.final_upvar_tys(closure_def_id);
452
453        if infer_kind {
454            // Unify the (as yet unbound) type variable in the closure
455            // args with the kind we inferred.
456            let closure_kind_ty = match args {
457                UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
458                UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
459                UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
460            };
461            self.demand_eqtype(
462                span,
463                Ty::from_closure_kind(self.tcx, closure_kind),
464                closure_kind_ty,
465            );
466
467            // If we have an origin, store it.
468            if let Some(mut origin) = origin {
469                if !enable_precise_capture(span) {
470                    // Without precise captures, we just capture the base and ignore
471                    // the projections.
472                    origin.1.projections.clear()
473                }
474
475                self.typeck_results
476                    .borrow_mut()
477                    .closure_kind_origins_mut()
478                    .insert(closure_hir_id, origin);
479            }
480        }
481
482        // For coroutine-closures, we additionally must compute the
483        // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
484        // version of the coroutine-closure's output coroutine.
485        //
486        // If the args already reference an error, computing the by-ref upvar
487        // tuple may itself reach malformed types. We still equate the
488        // `coroutine_captures_by_ref_ty` inference variable to an error type
489        // so downstream consumers (e.g. `has_self_borrows`) can rely on it
490        // being resolved to either an `FnPtr` or `Error` rather than remaining
491        // an unconstrained inference variable.
492        if let UpvarArgs::CoroutineClosure(args) = args {
493            if let Some(guar) = args.error_reported().err() {
494                self.demand_eqtype(
495                    span,
496                    args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
497                    Ty::new_error(self.tcx, guar),
498                );
499            } else {
500                let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
501                    self.tcx,
502                    ty::INNERMOST,
503                    ty::BoundRegion {
504                        var: ty::BoundVar::ZERO,
505                        kind: ty::BoundRegionKind::ClosureEnv,
506                    },
507                );
508
509                let num_args = args
510                    .as_coroutine_closure()
511                    .coroutine_closure_sig()
512                    .skip_binder()
513                    .tupled_inputs_ty
514                    .tuple_fields()
515                    .len();
516                let typeck_results = self.typeck_results.borrow();
517
518                let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
519                    self.tcx,
520                    ty::analyze_coroutine_closure_captures(
521                        typeck_results.closure_min_captures_flattened(closure_def_id),
522                        typeck_results
523                            .closure_min_captures_flattened(
524                                self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
525                            )
526                            // Skip the captures that are just moving the closure's args
527                            // into the coroutine. These are always by move, and we append
528                            // those later in the `CoroutineClosureSignature` helper functions.
529                            .skip(num_args),
530                        |(_, parent_capture), (_, child_capture)| {
531                            // This is subtle. See documentation on function.
532                            let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
533                                parent_capture,
534                                child_capture,
535                            );
536
537                            let upvar_ty = child_capture.place.ty();
538                            let capture = child_capture.info.capture_kind;
539                            // Not all upvars are captured by ref, so use
540                            // `apply_capture_kind_on_capture_ty` to ensure that we
541                            // compute the right captured type.
542                            apply_capture_kind_on_capture_ty(
543                                self.tcx,
544                                upvar_ty,
545                                capture,
546                                if needs_ref {
547                                    closure_env_region
548                                } else {
549                                    self.tcx.lifetimes.re_erased
550                                },
551                            )
552                        },
553                    ),
554                );
555                let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
556                    self.tcx,
557                    ty::Binder::bind_with_vars(
558                        self.tcx.mk_fn_sig_safe_rust_abi([], tupled_upvars_ty_for_borrow),
559                        self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
560                            ty::BoundRegionKind::ClosureEnv,
561                        )]),
562                    ),
563                );
564                self.demand_eqtype(
565                    span,
566                    args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
567                    coroutine_captures_by_ref_ty,
568                );
569
570                // Additionally, we can now constrain the coroutine's kind type.
571                //
572                // We only do this if `infer_kind`, because if we have constrained
573                // the kind from closure signature inference, the kind inferred
574                // for the inner coroutine may actually be more restrictive.
575                if infer_kind {
576                    let ty::Coroutine(_, coroutine_args) =
577                        *self.typeck_results.borrow().expr_ty(body.value).kind()
578                    else {
579                        bug!();
580                    };
581                    self.demand_eqtype(
582                        span,
583                        coroutine_args.as_coroutine().kind_ty(),
584                        Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
585                    );
586                }
587            }
588        }
589
590        self.log_closure_min_capture_info(closure_def_id, span);
591
592        // Now that we've analyzed the closure, we know how each
593        // variable is borrowed, and we know what traits the closure
594        // implements (Fn vs FnMut etc). We now have some updates to do
595        // with that information.
596        //
597        // Note that no closure type C may have an upvar of type C
598        // (though it may reference itself via a trait object). This
599        // results from the desugaring of closures to a struct like
600        // `Foo<..., UV0...UVn>`. If one of those upvars referenced
601        // C, then the type would have infinite size (and the
602        // inference algorithm will reject it).
603
604        // Equate the type variables for the upvars with the actual types.
605        let final_upvar_tys = self.final_upvar_tys(closure_def_id);
606        debug!(?closure_hir_id, ?args, ?final_upvar_tys);
607
608        if self.tcx.features().unsized_fn_params() {
609            for capture in
610                self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
611            {
612                if let UpvarCapture::ByValue = capture.info.capture_kind {
613                    self.require_type_is_sized(
614                        capture.place.ty(),
615                        capture.get_path_span(self.tcx),
616                        ObligationCauseCode::SizedClosureCapture(closure_def_id),
617                    );
618                }
619            }
620        }
621
622        // Build a tuple (U0..Un) of the final upvar types U0..Un
623        // and unify the upvar tuple type in the closure with it:
624        let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
625        self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
626
627        let fake_reads = delegate.fake_reads;
628
629        self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
630
631        if self.tcx.sess.opts.unstable_opts.profile_closures {
632            self.typeck_results.borrow_mut().closure_size_eval.insert(
633                closure_def_id,
634                ClosureSizeProfileData {
635                    before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
636                    after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
637                },
638            );
639        }
640
641        // If we are also inferred the closure kind here,
642        // process any deferred resolutions.
643        let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
644        for deferred_call_resolution in deferred_call_resolutions {
645            deferred_call_resolution.resolve(&FnCtxt::new(self, self.param_env, closure_def_id));
646        }
647    }
648
649    /// Determines whether the body of the coroutine uses its upvars in a way that
650    /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
651    /// In a more detailed comment above, we care whether this happens, since if
652    /// this happens, we want to force the coroutine to move all of the upvars it
653    /// would've borrowed from the parent coroutine-closure.
654    ///
655    /// This only really makes sense to be called on the child coroutine of a
656    /// coroutine-closure.
657    fn coroutine_body_consumes_upvars(
658        &self,
659        coroutine_def_id: LocalDefId,
660        body: &'tcx hir::Body<'tcx>,
661    ) -> bool {
662        // This block contains argument capturing details. Since arguments
663        // aren't upvars, we do not care about them for determining if the
664        // coroutine body actually consumes its upvars.
665        let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
666        else {
667            bug_impl(None, format_args!("impossible case reached"), Location::caller());bug!();
668        };
669        // Specifically, we only care about the *real* body of the coroutine.
670        // We skip out into the drop-temps within the block of the body in order
671        // to skip over the args of the desugaring.
672        let hir::ExprKind::DropTemps(body) = body.kind else {
673            bug_impl(None, format_args!("impossible case reached"), Location::caller());bug!();
674        };
675
676        let coroutine_fcx =
677            FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id);
678
679        let mut delegate = InferBorrowKind {
680            fcx: &coroutine_fcx,
681            closure_def_id: coroutine_def_id,
682            capture_information: Default::default(),
683            fake_reads: Default::default(),
684        };
685
686        let _ = euv::ExprUseVisitor::new(&coroutine_fcx, &mut delegate).consume_expr(body);
687
688        let (_, kind, _) = self.process_collected_capture_information(
689            hir::CaptureBy::Ref,
690            &delegate.capture_information,
691        );
692
693        #[allow(non_exhaustive_omitted_patterns)] match kind {
    ty::ClosureKind::FnOnce => true,
    _ => false,
}matches!(kind, ty::ClosureKind::FnOnce)
694    }
695
696    // Returns a list of `Ty`s for each upvar.
697    fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
698        self.typeck_results
699            .borrow()
700            .closure_min_captures_flattened(closure_id)
701            .map(|captured_place| {
702                let upvar_ty = captured_place.place.ty();
703                let capture = captured_place.info.capture_kind;
704
705                {
    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_hir_typeck/src/upvar.rs:705",
                        "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                        ::tracing_core::__macro_support::Option::Some(705u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("captured_place.place")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("captured_place.place");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("upvar_ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("upvar_ty");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("capture")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("capture");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("captured_place.mutability")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("captured_place.mutability");
                                            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(&captured_place.place)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&upvar_ty)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&captured_place.mutability)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?captured_place.place, ?upvar_ty, ?capture, ?captured_place.mutability);
706
707                apply_capture_kind_on_capture_ty(
708                    self.tcx,
709                    upvar_ty,
710                    capture,
711                    self.tcx.lifetimes.re_erased,
712                )
713            })
714            .collect()
715    }
716
717    /// Adjusts the closure capture information to ensure that the operations aren't unsafe,
718    /// and that the path can be captured with required capture kind (depending on use in closure,
719    /// move closure etc.)
720    ///
721    /// Returns the set of adjusted information along with the inferred closure kind and span
722    /// associated with the closure kind inference.
723    ///
724    /// Note that we *always* infer a minimal kind, even if
725    /// we don't always *use* that in the final result (i.e., sometimes
726    /// we've taken the closure kind from the expectations instead, and
727    /// for coroutines we don't even implement the closure traits
728    /// really).
729    ///
730    /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
731    /// contains a `Some()` with the `Place` that caused us to do so.
732    fn process_collected_capture_information(
733        &self,
734        capture_clause: hir::CaptureBy,
735        capture_information: &InferredCaptureInformation<'tcx>,
736    ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
737        let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
738        let mut origin: Option<(Span, Place<'tcx>)> = None;
739
740        let processed = capture_information
741            .iter()
742            .cloned()
743            .map(|(place, mut capture_info)| {
744                // Apply rules for safety before inferring closure kind
745                let (place, capture_kind) =
746                    restrict_capture_precision(place, capture_info.capture_kind);
747
748                let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
749
750                let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
751                    self.tcx.hir_span(usage_expr)
752                } else {
753                    ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
754                };
755
756                let updated = match capture_kind {
757                    ty::UpvarCapture::ByValue => match closure_kind {
758                        ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
759                            (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
760                        }
761                        // If closure is already FnOnce, don't update
762                        ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
763                    },
764
765                    ty::UpvarCapture::ByRef(
766                        ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
767                    ) => {
768                        match closure_kind {
769                            ty::ClosureKind::Fn => {
770                                (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
771                            }
772                            // Don't update the origin
773                            ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
774                                (closure_kind, origin.take())
775                            }
776                        }
777                    }
778
779                    _ => (closure_kind, origin.take()),
780                };
781
782                closure_kind = updated.0;
783                origin = updated.1;
784
785                let (place, capture_kind) = match capture_clause {
786                    hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
787                    hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
788                    hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
789                };
790
791                // This restriction needs to be applied after we have handled adjustments for `move`
792                // closures. We want to make sure any adjustment that might make us move the place into
793                // the closure gets handled.
794                let (place, capture_kind) =
795                    restrict_precision_for_drop_types(self, place, capture_kind);
796
797                capture_info.capture_kind = capture_kind;
798                (place, capture_info)
799            })
800            .collect();
801
802        (processed, closure_kind, origin)
803    }
804
805    /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
806    /// Places (and corresponding capture kind) that we need to keep track of to support all
807    /// the required captured paths.
808    ///
809    ///
810    /// Note: If this function is called multiple times for the same closure, it will update
811    ///       the existing min_capture map that is stored in TypeckResults.
812    ///
813    /// Eg:
814    /// ```
815    /// #[derive(Debug)]
816    /// struct Point { x: i32, y: i32 }
817    ///
818    /// let s = String::from("s");  // hir_id_s
819    /// let mut p = Point { x: 2, y: -2 }; // his_id_p
820    /// let c = || {
821    ///        println!("{s:?}");  // L1
822    ///        p.x += 10;  // L2
823    ///        println!("{}" , p.y); // L3
824    ///        println!("{p:?}"); // L4
825    ///        drop(s);   // L5
826    /// };
827    /// ```
828    /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
829    /// the lines L1..5 respectively.
830    ///
831    /// InferBorrowKind results in a structure like this:
832    ///
833    /// ```ignore (illustrative)
834    /// {
835    ///       Place(base: hir_id_s, projections: [], ....) -> {
836    ///                                                            capture_kind_expr: hir_id_L5,
837    ///                                                            path_expr_id: hir_id_L5,
838    ///                                                            capture_kind: ByValue
839    ///                                                       },
840    ///       Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
841    ///                                                                     capture_kind_expr: hir_id_L2,
842    ///                                                                     path_expr_id: hir_id_L2,
843    ///                                                                     capture_kind: ByValue
844    ///                                                                 },
845    ///       Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
846    ///                                                                     capture_kind_expr: hir_id_L3,
847    ///                                                                     path_expr_id: hir_id_L3,
848    ///                                                                     capture_kind: ByValue
849    ///                                                                 },
850    ///       Place(base: hir_id_p, projections: [], ...) -> {
851    ///                                                          capture_kind_expr: hir_id_L4,
852    ///                                                          path_expr_id: hir_id_L4,
853    ///                                                          capture_kind: ByValue
854    ///                                                      },
855    /// }
856    /// ```
857    ///
858    /// After the min capture analysis, we get:
859    /// ```ignore (illustrative)
860    /// {
861    ///       hir_id_s -> [
862    ///            Place(base: hir_id_s, projections: [], ....) -> {
863    ///                                                                capture_kind_expr: hir_id_L5,
864    ///                                                                path_expr_id: hir_id_L5,
865    ///                                                                capture_kind: ByValue
866    ///                                                            },
867    ///       ],
868    ///       hir_id_p -> [
869    ///            Place(base: hir_id_p, projections: [], ...) -> {
870    ///                                                               capture_kind_expr: hir_id_L2,
871    ///                                                               path_expr_id: hir_id_L4,
872    ///                                                               capture_kind: ByValue
873    ///                                                           },
874    ///       ],
875    /// }
876    /// ```
877    {}
#[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("compute_min_captures",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(877u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("capture_information")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("capture_information");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_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(&closure_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_information)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_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;
        }
        {
            if capture_information.is_empty() { return; }
            let mut typeck_results = self.typeck_results.borrow_mut();
            let mut root_var_min_capture_list =
                typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
            for (mut place, capture_info) in capture_information.into_iter() {
                let var_hir_id =
                    match place.base {
                        PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
                        base =>
                            bug_impl(None,
                                format_args!("Expected upvar, found={0:?}", base),
                                Location::caller()),
                    };
                let var_ident = self.tcx.hir_ident(var_hir_id);
                let Some(min_cap_list) =
                    root_var_min_capture_list.get_mut(&var_hir_id) else {
                        let mutability =
                            self.determine_capture_mutability(&typeck_results, &place);
                        let min_cap_list =
                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                    [ty::CapturedPlace {
                                                var_ident,
                                                place,
                                                info: capture_info,
                                                mutability,
                                            }]));
                        root_var_min_capture_list.insert(var_hir_id, min_cap_list);
                        continue;
                    };
                let mut descendant_found = false;
                let mut updated_capture_info = capture_info;
                min_cap_list.retain(|possible_descendant|
                        {
                            match determine_place_ancestry_relation(&place,
                                    &possible_descendant.place) {
                                PlaceAncestryRelation::Ancestor => {
                                    descendant_found = true;
                                    let mut possible_descendant = possible_descendant.clone();
                                    let backup_path_expr_id = updated_capture_info.path_expr_id;
                                    truncate_place_to_len_and_update_capture_kind(&mut possible_descendant.place,
                                        &mut possible_descendant.info.capture_kind,
                                        place.projections.len());
                                    updated_capture_info =
                                        determine_capture_info(updated_capture_info,
                                            possible_descendant.info);
                                    updated_capture_info.path_expr_id = backup_path_expr_id;
                                    false
                                }
                                _ => true,
                            }
                        });
                let mut ancestor_found = false;
                if !descendant_found {
                    for possible_ancestor in min_cap_list.iter_mut() {
                        match determine_place_ancestry_relation(&place,
                                &possible_ancestor.place) {
                            PlaceAncestryRelation::SamePlace => {
                                ancestor_found = true;
                                possible_ancestor.info =
                                    determine_capture_info(possible_ancestor.info,
                                        updated_capture_info);
                                break;
                            }
                            PlaceAncestryRelation::Descendant => {
                                ancestor_found = true;
                                let backup_path_expr_id =
                                    possible_ancestor.info.path_expr_id;
                                truncate_place_to_len_and_update_capture_kind(&mut place,
                                    &mut updated_capture_info.capture_kind,
                                    possible_ancestor.place.projections.len());
                                possible_ancestor.info =
                                    determine_capture_info(possible_ancestor.info,
                                        updated_capture_info);
                                possible_ancestor.info.path_expr_id = backup_path_expr_id;
                                break;
                            }
                            _ => {}
                        }
                    }
                }
                if !ancestor_found {
                    let mutability =
                        self.determine_capture_mutability(&typeck_results, &place);
                    let captured_place =
                        ty::CapturedPlace {
                            var_ident,
                            place,
                            info: updated_capture_info,
                            mutability,
                        };
                    min_cap_list.push(captured_place);
                }
            }
            {
                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_hir_typeck/src/upvar.rs:1002",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1002u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::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!("For closure={0:?}, min_captures before sorting={1:?}",
                                                                closure_def_id, root_var_min_capture_list) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            for (_, captures) in &mut root_var_min_capture_list {
                captures.sort_by(|capture1, capture2|
                        {
                            fn is_field<'a>(p: &&Projection<'a>) -> bool {
                                match p.kind {
                                    ProjectionKind::Field(_, _) => true,
                                    ProjectionKind::Deref | ProjectionKind::OpaqueCast |
                                        ProjectionKind::UnwrapUnsafeBinder => false,
                                    p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
                                        bug_impl(None,
                                            format_args!("ProjectionKind {0:?} was unexpected", p),
                                            Location::caller())
                                    }
                                }
                            }
                            let capture1_field_projections =
                                capture1.place.projections.iter().filter(is_field);
                            let capture2_field_projections =
                                capture2.place.projections.iter().filter(is_field);
                            for (p1, p2) in
                                capture1_field_projections.zip(capture2_field_projections) {
                                match (p1.kind, p2.kind) {
                                    (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _))
                                        => {
                                        if i1 != i2 { return i1.cmp(&i2); }
                                    }
                                    (l, r) =>
                                        bug_impl(None,
                                            format_args!("ProjectionKinds {0:?} or {1:?} were unexpected",
                                                l, r), Location::caller()),
                                }
                            }
                            self.dcx().span_delayed_bug(closure_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("two identical projections: ({0:?}, {1:?})",
                                                capture1.place.projections, capture2.place.projections))
                                    }));
                            std::cmp::Ordering::Equal
                        });
            }
            {
                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_hir_typeck/src/upvar.rs:1063",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1063u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::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!("For closure={0:?}, min_captures after sorting={1:#?}",
                                                                closure_def_id, root_var_min_capture_list) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            typeck_results.closure_min_captures.insert(closure_def_id,
                root_var_min_capture_list);
        }
    }
}#[instrument(level = "debug", skip(self))]
878    fn compute_min_captures(
879        &self,
880        closure_def_id: LocalDefId,
881        capture_information: InferredCaptureInformation<'tcx>,
882        closure_span: Span,
883    ) {
884        if capture_information.is_empty() {
885            return;
886        }
887
888        let mut typeck_results = self.typeck_results.borrow_mut();
889
890        let mut root_var_min_capture_list =
891            typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
892
893        for (mut place, capture_info) in capture_information.into_iter() {
894            let var_hir_id = match place.base {
895                PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
896                base => bug!("Expected upvar, found={:?}", base),
897            };
898            let var_ident = self.tcx.hir_ident(var_hir_id);
899
900            let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
901                let mutability = self.determine_capture_mutability(&typeck_results, &place);
902                let min_cap_list =
903                    vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
904                root_var_min_capture_list.insert(var_hir_id, min_cap_list);
905                continue;
906            };
907
908            // Go through each entry in the current list of min_captures
909            // - if ancestor is found, update its capture kind to account for current place's
910            // capture information.
911            //
912            // - if descendant is found, remove it from the list, and update the current place's
913            // capture information to account for the descendant's capture kind.
914            //
915            // We can never be in a case where the list contains both an ancestor and a descendant
916            // Also there can only be ancestor but in case of descendants there might be
917            // multiple.
918
919            let mut descendant_found = false;
920            let mut updated_capture_info = capture_info;
921            min_cap_list.retain(|possible_descendant| {
922                match determine_place_ancestry_relation(&place, &possible_descendant.place) {
923                    // current place is ancestor of possible_descendant
924                    PlaceAncestryRelation::Ancestor => {
925                        descendant_found = true;
926
927                        let mut possible_descendant = possible_descendant.clone();
928                        let backup_path_expr_id = updated_capture_info.path_expr_id;
929
930                        // Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
931                        // possible change in capture mode.
932                        truncate_place_to_len_and_update_capture_kind(
933                            &mut possible_descendant.place,
934                            &mut possible_descendant.info.capture_kind,
935                            place.projections.len(),
936                        );
937
938                        updated_capture_info =
939                            determine_capture_info(updated_capture_info, possible_descendant.info);
940
941                        // we need to keep the ancestor's `path_expr_id`
942                        updated_capture_info.path_expr_id = backup_path_expr_id;
943                        false
944                    }
945
946                    _ => true,
947                }
948            });
949
950            let mut ancestor_found = false;
951            if !descendant_found {
952                for possible_ancestor in min_cap_list.iter_mut() {
953                    match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
954                        PlaceAncestryRelation::SamePlace => {
955                            ancestor_found = true;
956                            possible_ancestor.info = determine_capture_info(
957                                possible_ancestor.info,
958                                updated_capture_info,
959                            );
960
961                            // Only one related place will be in the list.
962                            break;
963                        }
964                        // current place is descendant of possible_ancestor
965                        PlaceAncestryRelation::Descendant => {
966                            ancestor_found = true;
967                            let backup_path_expr_id = possible_ancestor.info.path_expr_id;
968
969                            // Truncate the descendant (current place) to be same as the ancestor to handle any
970                            // possible change in capture mode.
971                            truncate_place_to_len_and_update_capture_kind(
972                                &mut place,
973                                &mut updated_capture_info.capture_kind,
974                                possible_ancestor.place.projections.len(),
975                            );
976
977                            possible_ancestor.info = determine_capture_info(
978                                possible_ancestor.info,
979                                updated_capture_info,
980                            );
981
982                            // we need to keep the ancestor's `path_expr_id`
983                            possible_ancestor.info.path_expr_id = backup_path_expr_id;
984
985                            // Only one related place will be in the list.
986                            break;
987                        }
988                        _ => {}
989                    }
990                }
991            }
992
993            // Only need to insert when we don't have an ancestor in the existing min capture list
994            if !ancestor_found {
995                let mutability = self.determine_capture_mutability(&typeck_results, &place);
996                let captured_place =
997                    ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
998                min_cap_list.push(captured_place);
999            }
1000        }
1001
1002        debug!(
1003            "For closure={:?}, min_captures before sorting={:?}",
1004            closure_def_id, root_var_min_capture_list
1005        );
1006
1007        // Now that we have the minimized list of captures, sort the captures by field id.
1008        // This causes the closure to capture the upvars in the same order as the fields are
1009        // declared which is also the drop order. Thus, in situations where we capture all the
1010        // fields of some type, the observable drop order will remain the same as it previously
1011        // was even though we're dropping each capture individually.
1012        // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
1013        // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
1014        for (_, captures) in &mut root_var_min_capture_list {
1015            captures.sort_by(|capture1, capture2| {
1016                fn is_field<'a>(p: &&Projection<'a>) -> bool {
1017                    match p.kind {
1018                        ProjectionKind::Field(_, _) => true,
1019                        ProjectionKind::Deref
1020                        | ProjectionKind::OpaqueCast
1021                        | ProjectionKind::UnwrapUnsafeBinder => false,
1022                        p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
1023                            bug!("ProjectionKind {:?} was unexpected", p)
1024                        }
1025                    }
1026                }
1027
1028                // Need to sort only by Field projections, so filter away others.
1029                // A previous implementation considered other projection types too
1030                // but that caused ICE #118144
1031                let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
1032                let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
1033
1034                for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
1035                    // We do not need to look at the `Projection.ty` fields here because at each
1036                    // step of the iteration, the projections will either be the same and therefore
1037                    // the types must be as well or the current projection will be different and
1038                    // we will return the result of comparing the field indexes.
1039                    match (p1.kind, p2.kind) {
1040                        (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
1041                            // Compare only if paths are different.
1042                            // Otherwise continue to the next iteration
1043                            if i1 != i2 {
1044                                return i1.cmp(&i2);
1045                            }
1046                        }
1047                        // Given the filter above, this arm should never be hit
1048                        (l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
1049                    }
1050                }
1051
1052                self.dcx().span_delayed_bug(
1053                    closure_span,
1054                    format!(
1055                        "two identical projections: ({:?}, {:?})",
1056                        capture1.place.projections, capture2.place.projections
1057                    ),
1058                );
1059                std::cmp::Ordering::Equal
1060            });
1061        }
1062
1063        debug!(
1064            "For closure={:?}, min_captures after sorting={:#?}",
1065            closure_def_id, root_var_min_capture_list
1066        );
1067        typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
1068    }
1069
1070    /// Perform the migration analysis for RFC 2229, and emit lint
1071    /// `disjoint_capture_drop_reorder` if needed.
1072    fn perform_2229_migration_analysis(
1073        &self,
1074        closure_def_id: LocalDefId,
1075        body_id: hir::BodyId,
1076        capture_clause: hir::CaptureBy,
1077        span: Span,
1078    ) {
1079        struct MigrationLint<'a, 'tcx> {
1080            closure_def_id: LocalDefId,
1081            closure_drop_location_span: Span,
1082            this: &'a FnCtxt<'a, 'tcx>,
1083            body_id: hir::BodyId,
1084            need_migrations: Vec<NeededMigration>,
1085            migration_message: String,
1086        }
1087
1088        impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for MigrationLint<'b, 'tcx> {
1089            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
1090                let Self {
1091                    closure_def_id,
1092                    closure_drop_location_span,
1093                    this,
1094                    body_id,
1095                    need_migrations,
1096                    migration_message,
1097                } = self;
1098                let mut lint = Diag::new(dcx, level, migration_message);
1099
1100                let (migration_string, migrated_variables_concat) =
1101                    migration_suggestion_for_2229(this.tcx, &need_migrations);
1102
1103                let closure_hir_id = this.tcx.local_def_id_to_hir_id(closure_def_id);
1104                let closure_head_span = this.tcx.def_span(closure_def_id);
1105
1106                for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
1107                    // Labels all the usage of the captured variable and why they are responsible
1108                    // for migration being needed
1109                    for lint_note in diagnostics_info.iter() {
1110                        match &lint_note.captures_info {
1111                            UpvarMigrationInfo::CapturingPrecise {
1112                                source_expr: Some(capture_expr_id),
1113                                var_name: captured_name,
1114                            } => {
1115                                let cause_span = this.tcx.hir_span(*capture_expr_id);
1116                                lint.span_label(cause_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in Rust 2018, this closure captures all of `{0}`, but in Rust 2021, it will only capture `{1}`",
                this.tcx.hir_name(*var_hir_id), captured_name))
    })format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`",
1117                                    this.tcx.hir_name(*var_hir_id),
1118                                    captured_name,
1119                                ));
1120                            }
1121                            UpvarMigrationInfo::CapturingNothing { use_span } => {
1122                                lint.span_label(*use_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in Rust 2018, this causes the closure to capture `{0}`, but in Rust 2021, it has no effect",
                this.tcx.hir_name(*var_hir_id)))
    })format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
1123                                    this.tcx.hir_name(*var_hir_id),
1124                                ));
1125                            }
1126
1127                            _ => {}
1128                        }
1129
1130                        // Add a label pointing to where a captured variable affected by drop
1131                        // order is dropped.
1132                        if lint_note.reason.drop_order {
1133                            let var_name = this.tcx.hir_name(*var_hir_id);
1134                            match &lint_note.captures_info {
1135                                UpvarMigrationInfo::CapturingPrecise {
1136                                    var_name: captured_name,
1137                                    ..
1138                                } => {
1139                                    lint.span_label(
1140                                            closure_drop_location_span,
1141                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in Rust 2018, `{0}` is dropped here, but in Rust 2021, only `{1}` will be dropped here as part of the closure",
                var_name, captured_name))
    })format!(
1142                                                "in Rust 2018, `{var_name}` is dropped here, but in Rust 2021, \
1143                                                only `{captured_name}` will be dropped here as part of the closure"
1144                                            ),
1145                                        );
1146                                }
1147                                UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1148                                    lint.span_label(
1149                                            closure_drop_location_span,
1150                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in Rust 2018, `{0}` is dropped here along with the closure, but in Rust 2021 `{0}` is not part of the closure",
                var_name))
    })format!(
1151                                                "in Rust 2018, `{var_name}` is dropped here along with \
1152                                                the closure, but in Rust 2021 `{var_name}` is not part \
1153                                                of the closure"
1154                                            ),
1155                                        );
1156                                }
1157                            }
1158                        }
1159
1160                        // Add a label explaining why a closure no longer implements a trait
1161                        for &missing_trait in &lint_note.reason.auto_traits {
1162                            // not capturing something anymore cannot cause a trait to fail to be implemented:
1163                            match &lint_note.captures_info {
1164                                UpvarMigrationInfo::CapturingPrecise {
1165                                    var_name: captured_name,
1166                                    ..
1167                                } => {
1168                                    let var_name = this.tcx.hir_name(*var_hir_id);
1169                                    lint.span_label(
1170                                        closure_head_span,
1171                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in Rust 2018, this closure implements {0} as `{1}` implements {0}, but in Rust 2021, this closure will no longer implement {0} because `{1}` is not fully captured and `{2}` does not implement {0}",
                missing_trait, var_name, captured_name))
    })format!(
1172                                            "\
1173                                    in Rust 2018, this closure implements {missing_trait} \
1174                                    as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1175                                    this closure will no longer implement {missing_trait} \
1176                                    because `{var_name}` is not fully captured \
1177                                    and `{captured_name}` does not implement {missing_trait}"
1178                                        ),
1179                                    );
1180                                }
1181
1182                                // Cannot happen: if we don't capture a variable, we impl strictly more traits
1183                                UpvarMigrationInfo::CapturingNothing { use_span } => bug_impl(Some(*use_span),
    format_args!("missing trait from not capturing something"),
    Location::caller())span_bug!(
1184                                    *use_span,
1185                                    "missing trait from not capturing something"
1186                                ),
1187                            }
1188                        }
1189                    }
1190                }
1191
1192                let diagnostic_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add a dummy let to cause {0} to be fully captured",
                migrated_variables_concat))
    })format!(
1193                    "add a dummy let to cause {migrated_variables_concat} to be fully captured"
1194                );
1195
1196                let closure_span = this.tcx.hir_span_with_body(closure_hir_id);
1197                let mut closure_body_span = {
1198                    // If the body was entirely expanded from a macro
1199                    // invocation, i.e. the body is not contained inside the
1200                    // closure span, then we walk up the expansion until we
1201                    // find the span before the expansion.
1202                    let s = this.tcx.hir_span_with_body(body_id.hir_id);
1203                    s.find_ancestor_inside(closure_span).unwrap_or(s)
1204                };
1205
1206                if let Ok(mut s) = this.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1207                    if s.starts_with('$') {
1208                        // Looks like a macro fragment. Try to find the real block.
1209                        if let hir::Node::Expr(&hir::Expr {
1210                            kind: hir::ExprKind::Block(block, ..),
1211                            ..
1212                        }) = this.tcx.hir_node(body_id.hir_id)
1213                        {
1214                            // If the body is a block (with `{..}`), we use the span of that block.
1215                            // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1216                            // Since we know it's a block, we know we can insert the `let _ = ..` without
1217                            // breaking the macro syntax.
1218                            if let Ok(snippet) =
1219                                this.tcx.sess.source_map().span_to_snippet(block.span)
1220                            {
1221                                closure_body_span = block.span;
1222                                s = snippet;
1223                            }
1224                        }
1225                    }
1226
1227                    let mut lines = s.lines();
1228                    let line1 = lines.next().unwrap_or_default();
1229
1230                    if line1.trim_end() == "{" {
1231                        // This is a multi-line closure with just a `{` on the first line,
1232                        // so we put the `let` on its own line.
1233                        // We take the indentation from the next non-empty line.
1234                        let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1235                        let indent =
1236                            line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1237                        lint.span_suggestion(
1238                            closure_body_span
1239                                .with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len()))
1240                                .shrink_to_lo(),
1241                            diagnostic_msg,
1242                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}{1};", indent,
                migration_string))
    })format!("\n{indent}{migration_string};"),
1243                            Applicability::MachineApplicable,
1244                        );
1245                    } else if line1.starts_with('{') {
1246                        // This is a closure with its body wrapped in
1247                        // braces, but with more than just the opening
1248                        // brace on the first line. We put the `let`
1249                        // directly after the `{`.
1250                        lint.span_suggestion(
1251                            closure_body_span
1252                                .with_lo(closure_body_span.lo() + BytePos(1))
1253                                .shrink_to_lo(),
1254                            diagnostic_msg,
1255                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0};", migration_string))
    })format!(" {migration_string};"),
1256                            Applicability::MachineApplicable,
1257                        );
1258                    } else {
1259                        // This is a closure without braces around the body.
1260                        // We add braces to add the `let` before the body.
1261                        lint.multipart_suggestion(
1262                            diagnostic_msg,
1263                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(closure_body_span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{{ {0}; ",
                                    migration_string))
                        })), (closure_body_span.shrink_to_hi(), " }".to_string())]))vec![
1264                                (
1265                                    closure_body_span.shrink_to_lo(),
1266                                    format!("{{ {migration_string}; "),
1267                                ),
1268                                (closure_body_span.shrink_to_hi(), " }".to_string()),
1269                            ],
1270                            Applicability::MachineApplicable,
1271                        );
1272                    }
1273                } else {
1274                    lint.span_suggestion(
1275                        closure_span,
1276                        diagnostic_msg,
1277                        migration_string,
1278                        Applicability::HasPlaceholders,
1279                    );
1280                }
1281                lint
1282            }
1283        }
1284
1285        let (need_migrations, reasons) = self.compute_2229_migrations(
1286            closure_def_id,
1287            span,
1288            capture_clause,
1289            self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
1290        );
1291
1292        // Without a valid drop location, the closure syntax is invalid, and
1293        // emitted lints become nonsensical.
1294        if !need_migrations.is_empty()
1295            && let Some(drop_location_span) =
1296                drop_location_span(self.tcx, self.tcx.local_def_id_to_hir_id(closure_def_id))
1297        {
1298            self.tcx.emit_node_span_lint(
1299                RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
1300                self.tcx.local_def_id_to_hir_id(closure_def_id),
1301                self.tcx.def_span(closure_def_id),
1302                MigrationLint {
1303                    this: self,
1304                    closure_drop_location_span: drop_location_span,
1305                    migration_message: reasons.migration_message(),
1306                    closure_def_id,
1307                    body_id,
1308                    need_migrations,
1309                },
1310            );
1311        }
1312    }
1313
1314    /// Combines all the reasons for 2229 migrations
1315    fn compute_2229_migrations_reasons(
1316        &self,
1317        auto_trait_reasons: UnordSet<&'static str>,
1318        drop_order: bool,
1319    ) -> MigrationWarningReason {
1320        MigrationWarningReason {
1321            auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1322            drop_order,
1323        }
1324    }
1325
1326    /// Figures out the list of root variables (and their types) that aren't completely
1327    /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1328    /// differ between the root variable and the captured paths.
1329    ///
1330    /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1331    /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1332    fn compute_2229_migrations_for_trait(
1333        &self,
1334        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1335        var_hir_id: HirId,
1336        closure_clause: hir::CaptureBy,
1337    ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1338        let auto_traits_def_id = [
1339            self.tcx.lang_items().clone_trait(),
1340            self.tcx.lang_items().sync_trait(),
1341            self.tcx.get_diagnostic_item(sym::Send),
1342            self.tcx.lang_items().unpin_trait(),
1343            self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1344            self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1345        ];
1346        const AUTO_TRAITS: [&str; 6] =
1347            ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
1348
1349        let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
1350
1351        let ty = self.deeply_resolve_ignoring_regions(self.node_ty(var_hir_id));
1352
1353        let ty = match closure_clause {
1354            hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1355            hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1356                // For non move closure the capture kind is the max capture kind of all captures
1357                // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1358                let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1359                for capture in root_var_min_capture_list.iter() {
1360                    max_capture_info = determine_capture_info(max_capture_info, capture.info);
1361                }
1362
1363                apply_capture_kind_on_capture_ty(
1364                    self.tcx,
1365                    ty,
1366                    max_capture_info.capture_kind,
1367                    self.tcx.lifetimes.re_erased,
1368                )
1369            }
1370        };
1371
1372        let mut obligations_should_hold = Vec::new();
1373        // Checks if a root variable implements any of the auto traits
1374        for check_trait in auto_traits_def_id.iter() {
1375            obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1376                self.infcx
1377                    .type_implements_trait(check_trait, [ty], self.param_env)
1378                    .must_apply_modulo_regions()
1379            }));
1380        }
1381
1382        let mut problematic_captures = FxIndexMap::default();
1383        // Check whether captured fields also implement the trait
1384        for capture in root_var_min_capture_list.iter() {
1385            let ty = apply_capture_kind_on_capture_ty(
1386                self.tcx,
1387                capture.place.ty(),
1388                capture.info.capture_kind,
1389                self.tcx.lifetimes.re_erased,
1390            );
1391
1392            // Checks if a capture implements any of the auto traits
1393            let mut obligations_holds_for_capture = Vec::new();
1394            for check_trait in auto_traits_def_id.iter() {
1395                obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1396                    self.infcx
1397                        .type_implements_trait(check_trait, [ty], self.param_env)
1398                        .must_apply_modulo_regions()
1399                }));
1400            }
1401
1402            let mut capture_problems = UnordSet::default();
1403
1404            // Checks if for any of the auto traits, one or more trait is implemented
1405            // by the root variable but not by the capture
1406            for (idx, _) in obligations_should_hold.iter().enumerate() {
1407                if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1408                    capture_problems.insert(AUTO_TRAITS[idx]);
1409                }
1410            }
1411
1412            if !capture_problems.is_empty() {
1413                problematic_captures.insert(
1414                    UpvarMigrationInfo::CapturingPrecise {
1415                        source_expr: capture.info.path_expr_id,
1416                        var_name: capture.to_string(self.tcx),
1417                    },
1418                    capture_problems,
1419                );
1420            }
1421        }
1422        if !problematic_captures.is_empty() {
1423            return Some(problematic_captures);
1424        }
1425        None
1426    }
1427
1428    /// Figures out the list of root variables (and their types) that aren't completely
1429    /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1430    /// some path starting at that root variable **might** be affected.
1431    ///
1432    /// The output list would include a root variable if:
1433    /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1434    ///   enabled, **and**
1435    /// - It wasn't completely captured by the closure, **and**
1436    /// - One of the paths starting at this root variable, that is not captured needs Drop.
1437    ///
1438    /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1439    /// are no significant drops than None is returned
1440    {}
#[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("compute_2229_migrations_for_drop",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1440u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("min_captures")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("min_captures");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_clause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_clause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("var_hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("var_hir_id");
                                                        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(&closure_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_captures)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_clause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_hir_id)
                                                            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:
                    Option<FxIndexSet<UpvarMigrationInfo>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty =
                self.deeply_resolve_ignoring_regions(self.node_ty(var_hir_id));
            if !ty.has_significant_drop(self.tcx,
                        ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id))
                {
                {
                    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_hir_typeck/src/upvar.rs:1456",
                                        "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1456u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                        ::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!("does not have significant drop")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return None;
            }
            let Some(root_var_min_capture_list) =
                min_captures.and_then(|m|
                        m.get(&var_hir_id)) else {
                    {
                        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_hir_typeck/src/upvar.rs:1469",
                                            "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                            ::tracing_core::__macro_support::Option::Some(1469u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                            ::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!("no path starting from it is used")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    match closure_clause {
                        hir::CaptureBy::Value { .. } => {
                            let mut diagnostics_info = FxIndexSet::default();
                            let upvars =
                                self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
                            let upvar = upvars[&var_hir_id];
                            diagnostics_info.insert(UpvarMigrationInfo::CapturingNothing {
                                    use_span: upvar.span,
                                });
                            return Some(diagnostics_info);
                        }
                        hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
                    }
                    return None;
                };
            {
                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_hir_typeck/src/upvar.rs:1487",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1487u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("root_var_min_capture_list")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("root_var_min_capture_list");
                                                        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(&root_var_min_capture_list)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let mut projections_list = Vec::new();
            let mut diagnostics_info = FxIndexSet::default();
            for captured_place in root_var_min_capture_list.iter() {
                match captured_place.info.capture_kind {
                    ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
                        projections_list.push(captured_place.place.projections.as_slice());
                        diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
                                source_expr: captured_place.info.path_expr_id,
                                var_name: captured_place.to_string(self.tcx),
                            });
                    }
                    ty::UpvarCapture::ByRef(..) => {}
                }
            }
            {
                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_hir_typeck/src/upvar.rs:1506",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1506u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("projections_list")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("projections_list");
                                                        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(&projections_list)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            {
                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_hir_typeck/src/upvar.rs:1507",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1507u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("diagnostics_info")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("diagnostics_info");
                                                        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(&diagnostics_info)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let is_moved = !projections_list.is_empty();
            {
                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_hir_typeck/src/upvar.rs:1510",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1510u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_moved")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_moved");
                                                        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(&is_moved)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let is_not_completely_captured =
                root_var_min_capture_list.iter().any(|capture|
                        !capture.place.projections.is_empty());
            {
                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_hir_typeck/src/upvar.rs:1514",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1514u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_not_completely_captured")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_not_completely_captured");
                                                        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(&is_not_completely_captured)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if is_moved && is_not_completely_captured &&
                    self.has_significant_drop_outside_of_captures(closure_def_id,
                        closure_span, ty, projections_list) {
                return Some(diagnostics_info);
            }
            None
        }
    }
}#[instrument(level = "debug", skip(self))]
1441    fn compute_2229_migrations_for_drop(
1442        &self,
1443        closure_def_id: LocalDefId,
1444        closure_span: Span,
1445        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1446        closure_clause: hir::CaptureBy,
1447        var_hir_id: HirId,
1448    ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1449        let ty = self.deeply_resolve_ignoring_regions(self.node_ty(var_hir_id));
1450
1451        // FIXME(#132279): Using `non_body_analysis` here feels wrong.
1452        if !ty.has_significant_drop(
1453            self.tcx,
1454            ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1455        ) {
1456            debug!("does not have significant drop");
1457            return None;
1458        }
1459
1460        let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1461            // The upvar is mentioned within the closure but no path starting from it is
1462            // used. This occurs when you have (e.g.)
1463            //
1464            // ```
1465            // let x = move || {
1466            //     let _ = y;
1467            // });
1468            // ```
1469            debug!("no path starting from it is used");
1470
1471            match closure_clause {
1472                // Only migrate if closure is a move closure
1473                hir::CaptureBy::Value { .. } => {
1474                    let mut diagnostics_info = FxIndexSet::default();
1475                    let upvars =
1476                        self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1477                    let upvar = upvars[&var_hir_id];
1478                    diagnostics_info
1479                        .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1480                    return Some(diagnostics_info);
1481                }
1482                hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1483            }
1484
1485            return None;
1486        };
1487        debug!(?root_var_min_capture_list);
1488
1489        let mut projections_list = Vec::new();
1490        let mut diagnostics_info = FxIndexSet::default();
1491
1492        for captured_place in root_var_min_capture_list.iter() {
1493            match captured_place.info.capture_kind {
1494                // Only care about captures that are moved into the closure
1495                ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1496                    projections_list.push(captured_place.place.projections.as_slice());
1497                    diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1498                        source_expr: captured_place.info.path_expr_id,
1499                        var_name: captured_place.to_string(self.tcx),
1500                    });
1501                }
1502                ty::UpvarCapture::ByRef(..) => {}
1503            }
1504        }
1505
1506        debug!(?projections_list);
1507        debug!(?diagnostics_info);
1508
1509        let is_moved = !projections_list.is_empty();
1510        debug!(?is_moved);
1511
1512        let is_not_completely_captured =
1513            root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1514        debug!(?is_not_completely_captured);
1515
1516        if is_moved
1517            && is_not_completely_captured
1518            && self.has_significant_drop_outside_of_captures(
1519                closure_def_id,
1520                closure_span,
1521                ty,
1522                projections_list,
1523            )
1524        {
1525            return Some(diagnostics_info);
1526        }
1527
1528        None
1529    }
1530
1531    /// Figures out the list of root variables (and their types) that aren't completely
1532    /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1533    /// order of some path starting at that root variable **might** be affected or auto-traits
1534    /// differ between the root variable and the captured paths.
1535    ///
1536    /// The output list would include a root variable if:
1537    /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1538    ///   enabled, **and**
1539    /// - It wasn't completely captured by the closure, **and**
1540    /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1541    /// - One of the paths captured does not implement all the auto-traits its root variable
1542    ///   implements.
1543    ///
1544    /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1545    /// containing the reason why root variables whose HirId is contained in the vector should
1546    /// be captured
1547    {}
#[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("compute_2229_migrations",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1547u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_clause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_clause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("min_captures")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("min_captures");
                                                        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(&closure_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_clause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_captures)
                                                            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:
                    (Vec<NeededMigration>, MigrationWarningReason) = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let Some(upvars) =
                self.tcx.upvars_mentioned(closure_def_id) else {
                    return (Vec::new(), MigrationWarningReason::default());
                };
            let mut need_migrations = Vec::new();
            let mut auto_trait_migration_reasons = UnordSet::default();
            let mut drop_migration_needed = false;
            for (&var_hir_id, _) in upvars.iter() {
                let mut diagnostics_info = Vec::new();
                let auto_trait_diagnostic =
                    self.compute_2229_migrations_for_trait(min_captures,
                            var_hir_id, closure_clause).unwrap_or_default();
                let drop_reorder_diagnostic =
                    if let Some(diagnostics_info) =
                            self.compute_2229_migrations_for_drop(closure_def_id,
                                closure_span, min_captures, closure_clause, var_hir_id) {
                        drop_migration_needed = true;
                        diagnostics_info
                    } else { FxIndexSet::default() };
                let mut capture_diagnostic = drop_reorder_diagnostic.clone();
                for key in auto_trait_diagnostic.keys() {
                    capture_diagnostic.insert(key.clone());
                }
                let mut capture_diagnostic =
                    capture_diagnostic.into_iter().collect::<Vec<_>>();
                capture_diagnostic.sort_by_cached_key(|info|
                        match info {
                            UpvarMigrationInfo::CapturingPrecise {
                                source_expr: _, var_name } => {
                                (0, Some(var_name.clone()))
                            }
                            UpvarMigrationInfo::CapturingNothing { use_span: _ } =>
                                (1, None),
                        });
                for captures_info in capture_diagnostic {
                    let capture_trait_reasons =
                        if let Some(reasons) =
                                auto_trait_diagnostic.get(&captures_info) {
                            reasons.clone()
                        } else { UnordSet::default() };
                    let capture_drop_reorder_reason =
                        drop_reorder_diagnostic.contains(&captures_info);
                    auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
                    diagnostics_info.push(MigrationLintNote {
                            captures_info,
                            reason: self.compute_2229_migrations_reasons(capture_trait_reasons,
                                capture_drop_reorder_reason),
                        });
                }
                if !diagnostics_info.is_empty() {
                    need_migrations.push(NeededMigration {
                            var_hir_id,
                            diagnostics_info,
                        });
                }
            }
            (need_migrations,
                self.compute_2229_migrations_reasons(auto_trait_migration_reasons,
                    drop_migration_needed))
        }
    }
}#[instrument(level = "debug", skip(self))]
1548    fn compute_2229_migrations(
1549        &self,
1550        closure_def_id: LocalDefId,
1551        closure_span: Span,
1552        closure_clause: hir::CaptureBy,
1553        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1554    ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1555        let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1556            return (Vec::new(), MigrationWarningReason::default());
1557        };
1558
1559        let mut need_migrations = Vec::new();
1560        let mut auto_trait_migration_reasons = UnordSet::default();
1561        let mut drop_migration_needed = false;
1562
1563        // Perform auto-trait analysis
1564        for (&var_hir_id, _) in upvars.iter() {
1565            let mut diagnostics_info = Vec::new();
1566
1567            let auto_trait_diagnostic = self
1568                .compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1569                .unwrap_or_default();
1570
1571            let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1572                .compute_2229_migrations_for_drop(
1573                    closure_def_id,
1574                    closure_span,
1575                    min_captures,
1576                    closure_clause,
1577                    var_hir_id,
1578                ) {
1579                drop_migration_needed = true;
1580                diagnostics_info
1581            } else {
1582                FxIndexSet::default()
1583            };
1584
1585            // Combine all the captures responsible for needing migrations into one IndexSet
1586            let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1587            for key in auto_trait_diagnostic.keys() {
1588                capture_diagnostic.insert(key.clone());
1589            }
1590
1591            let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1592            capture_diagnostic.sort_by_cached_key(|info| match info {
1593                UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1594                    (0, Some(var_name.clone()))
1595                }
1596                UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1597            });
1598            for captures_info in capture_diagnostic {
1599                // Get the auto trait reasons of why migration is needed because of that capture, if there are any
1600                let capture_trait_reasons =
1601                    if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1602                        reasons.clone()
1603                    } else {
1604                        UnordSet::default()
1605                    };
1606
1607                // Check if migration is needed because of drop reorder as a result of that capture
1608                let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
1609
1610                // Combine all the reasons of why the root variable should be captured as a result of
1611                // auto trait implementation issues
1612                auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
1613
1614                diagnostics_info.push(MigrationLintNote {
1615                    captures_info,
1616                    reason: self.compute_2229_migrations_reasons(
1617                        capture_trait_reasons,
1618                        capture_drop_reorder_reason,
1619                    ),
1620                });
1621            }
1622
1623            if !diagnostics_info.is_empty() {
1624                need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1625            }
1626        }
1627        (
1628            need_migrations,
1629            self.compute_2229_migrations_reasons(
1630                auto_trait_migration_reasons,
1631                drop_migration_needed,
1632            ),
1633        )
1634    }
1635
1636    /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1637    /// of a root variable and a list of captured paths starting at this root variable (expressed
1638    /// using list of `Projection` slices), it returns true if there is a path that is not
1639    /// captured starting at this root variable that implements Drop.
1640    ///
1641    /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1642    /// path say P and then list of projection slices which represent the different captures moved
1643    /// into the closure starting off of P.
1644    ///
1645    /// This will make more sense with an example:
1646    ///
1647    /// ```rust,edition2021
1648    ///
1649    /// struct FancyInteger(i32); // This implements Drop
1650    ///
1651    /// struct Point { x: FancyInteger, y: FancyInteger }
1652    /// struct Color;
1653    ///
1654    /// struct Wrapper { p: Point, c: Color }
1655    ///
1656    /// fn f(w: Wrapper) {
1657    ///   let c = || {
1658    ///       // Closure captures w.p.x and w.c by move.
1659    ///   };
1660    ///
1661    ///   c();
1662    /// }
1663    /// ```
1664    ///
1665    /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1666    /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1667    /// therefore Drop ordering would change and we want this function to return true.
1668    ///
1669    /// Call stack to figure out if we need to migrate for `w` would look as follows:
1670    ///
1671    /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1672    /// `w[c]`.
1673    /// Notation:
1674    /// - Ty(place): Type of place
1675    /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1676    ///   respectively.
1677    /// ```ignore (illustrative)
1678    ///                  (Ty(w), [ &[p, x], &[c] ])
1679    /// //                              |
1680    /// //                 ----------------------------
1681    /// //                 |                          |
1682    /// //                 v                          v
1683    ///        (Ty(w.p), [ &[x] ])          (Ty(w.c), [ &[] ]) // I(1)
1684    /// //                 |                          |
1685    /// //                 v                          v
1686    ///        (Ty(w.p), [ &[x] ])                 false
1687    /// //                 |
1688    /// //                 |
1689    /// //       -------------------------------
1690    /// //       |                             |
1691    /// //       v                             v
1692    ///     (Ty((w.p).x), [ &[] ])     (Ty((w.p).y), []) // IMP 2
1693    /// //       |                             |
1694    /// //       v                             v
1695    ///        false              NeedsSignificantDrop(Ty(w.p.y))
1696    /// //                                     |
1697    /// //                                     v
1698    ///                                      true
1699    /// ```
1700    ///
1701    /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1702    ///                             This implies that the `w.c` is completely captured by the closure.
1703    ///                             Since drop for this path will be called when the closure is
1704    ///                             dropped we don't need to migrate for it.
1705    ///
1706    /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1707    ///                             path wasn't captured by the closure. Also note that even
1708    ///                             though we didn't capture this path, the function visits it,
1709    ///                             which is kind of the point of this function. We then return
1710    ///                             if the type of `w.p.y` implements Drop, which in this case is
1711    ///                             true.
1712    ///
1713    /// Consider another example:
1714    ///
1715    /// ```ignore (pseudo-rust)
1716    /// struct X;
1717    /// impl Drop for X {}
1718    ///
1719    /// struct Y(X);
1720    /// impl Drop for Y {}
1721    ///
1722    /// fn foo() {
1723    ///     let y = Y(X);
1724    ///     let c = || move(y.0);
1725    /// }
1726    /// ```
1727    ///
1728    /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1729    /// return true, because even though all paths starting at `y` are captured, `y` itself
1730    /// implements Drop which will be affected since `y` isn't completely captured.
1731    fn has_significant_drop_outside_of_captures(
1732        &self,
1733        closure_def_id: LocalDefId,
1734        closure_span: Span,
1735        base_path_ty: Ty<'tcx>,
1736        captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1737    ) -> bool {
1738        // FIXME(#132279): Using `non_body_analysis` here feels wrong.
1739        let needs_drop = |ty: Ty<'tcx>| {
1740            ty.has_significant_drop(
1741                self.tcx,
1742                ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1743            )
1744        };
1745
1746        let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1747            let drop_trait = self.tcx.require_lang_item(LangItem::Drop, closure_span);
1748            self.infcx
1749                .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1750                .must_apply_modulo_regions()
1751        };
1752
1753        let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
1754
1755        // If there is a case where no projection is applied on top of current place
1756        // then there must be exactly one capture corresponding to such a case. Note that this
1757        // represents the case of the path being completely captured by the variable.
1758        //
1759        // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1760        //     capture `a.b.c`, because that violates min capture.
1761        let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
1762
1763        if !(!is_completely_captured || (captured_by_move_projs.len() == 1)) {
    ::core::panicking::panic("assertion failed: !is_completely_captured || (captured_by_move_projs.len() == 1)")
};assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
1764
1765        if is_completely_captured {
1766            // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1767            // when the closure is dropped.
1768            return false;
1769        }
1770
1771        if captured_by_move_projs.is_empty() {
1772            return needs_drop(base_path_ty);
1773        }
1774
1775        if is_drop_defined_for_ty {
1776            // If drop is implemented for this type then we need it to be fully captured,
1777            // and we know it is not completely captured because of the previous checks.
1778
1779            // Note that this is a bug in the user code that will be reported by the
1780            // borrow checker, since we can't move out of drop types.
1781
1782            // The bug exists in the user's code pre-migration, and we don't migrate here.
1783            return false;
1784        }
1785
1786        match base_path_ty.kind() {
1787            // Observations:
1788            // - `captured_by_move_projs` is not empty. Therefore we can call
1789            //   `captured_by_move_projs.first().unwrap()` safely.
1790            // - All entries in `captured_by_move_projs` have at least one projection.
1791            //   Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
1792
1793            // We don't capture derefs in case of move captures, which would have be applied to
1794            // access any further paths.
1795            ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1796            ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1797            ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1798
1799            ty::Adt(def, args) => {
1800                // Multi-variant enums are captured in entirety,
1801                // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1802                {
    match (&def.variants().len(), &1) {
        (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!(def.variants().len(), 1);
1803
1804                // Only Field projections can be applied to a non-box Adt.
1805                if !captured_by_move_projs.iter().all(|projs|
                #[allow(non_exhaustive_omitted_patterns)] match projs.first().unwrap().kind
                    {
                    ProjectionKind::Field(..) => true,
                    _ => false,
                }) {
    ::core::panicking::panic("assertion failed: captured_by_move_projs.iter().all(|projs|\n        matches!(projs.first().unwrap().kind, ProjectionKind::Field(..)))")
};assert!(
1806                    captured_by_move_projs.iter().all(|projs| matches!(
1807                        projs.first().unwrap().kind,
1808                        ProjectionKind::Field(..)
1809                    ))
1810                );
1811                def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1812                    |(i, field)| {
1813                        let paths_using_field = captured_by_move_projs
1814                            .iter()
1815                            .filter_map(|projs| {
1816                                if let ProjectionKind::Field(field_idx, _) =
1817                                    projs.first().unwrap().kind
1818                                {
1819                                    if field_idx == i { Some(&projs[1..]) } else { None }
1820                                } else {
1821                                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1822                                }
1823                            })
1824                            .collect();
1825
1826                        let after_field_ty = field.ty(self.tcx, args).skip_norm_wip();
1827                        self.has_significant_drop_outside_of_captures(
1828                            closure_def_id,
1829                            closure_span,
1830                            after_field_ty,
1831                            paths_using_field,
1832                        )
1833                    },
1834                )
1835            }
1836
1837            ty::Tuple(fields) => {
1838                // Only Field projections can be applied to a tuple.
1839                if !captured_by_move_projs.iter().all(|projs|
                #[allow(non_exhaustive_omitted_patterns)] match projs.first().unwrap().kind
                    {
                    ProjectionKind::Field(..) => true,
                    _ => false,
                }) {
    ::core::panicking::panic("assertion failed: captured_by_move_projs.iter().all(|projs|\n        matches!(projs.first().unwrap().kind, ProjectionKind::Field(..)))")
};assert!(
1840                    captured_by_move_projs.iter().all(|projs| matches!(
1841                        projs.first().unwrap().kind,
1842                        ProjectionKind::Field(..)
1843                    ))
1844                );
1845
1846                fields.iter().enumerate().any(|(i, element_ty)| {
1847                    let paths_using_field = captured_by_move_projs
1848                        .iter()
1849                        .filter_map(|projs| {
1850                            if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1851                            {
1852                                if field_idx.index() == i { Some(&projs[1..]) } else { None }
1853                            } else {
1854                                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1855                            }
1856                        })
1857                        .collect();
1858
1859                    self.has_significant_drop_outside_of_captures(
1860                        closure_def_id,
1861                        closure_span,
1862                        element_ty,
1863                        paths_using_field,
1864                    )
1865                })
1866            }
1867
1868            // Anything else would be completely captured and therefore handled already.
1869            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1870        }
1871    }
1872
1873    fn init_capture_kind_for_place(
1874        &self,
1875        place: &Place<'tcx>,
1876        capture_clause: hir::CaptureBy,
1877    ) -> ty::UpvarCapture {
1878        match capture_clause {
1879            // In case of a move closure if the data is accessed through a reference we
1880            // want to capture by ref to allow precise capture using reborrows.
1881            //
1882            // If the data will be moved out of this place, then the place will be truncated
1883            // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1884            //
1885            // For example:
1886            //
1887            // struct Buffer<'a> {
1888            //     x: &'a String,
1889            //     y: Vec<u8>,
1890            // }
1891            //
1892            // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1893            //     let c = move || b.x;
1894            //     drop(b);
1895            //     c
1896            // }
1897            //
1898            // Even though the closure is declared as move, when we are capturing borrowed data (in
1899            // this case, *b.x) we prefer to capture by reference.
1900            // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1901            // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1902            // before, which is also an error.
1903            hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1904                ty::UpvarCapture::ByValue
1905            }
1906            hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1907                ty::UpvarCapture::ByUse
1908            }
1909            hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1910                ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1911            }
1912        }
1913    }
1914
1915    fn place_for_root_variable(
1916        &self,
1917        closure_def_id: LocalDefId,
1918        var_hir_id: HirId,
1919    ) -> Place<'tcx> {
1920        let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
1921
1922        let place = Place {
1923            base_ty: self.node_ty(var_hir_id),
1924            base: PlaceBase::Upvar(upvar_id),
1925            projections: Default::default(),
1926        };
1927
1928        // Normalize eagerly when inserting into `capture_information`, so all downstream
1929        // capture analysis can assume a normalized `Place`.
1930        self.normalize(self.tcx.hir_span(var_hir_id), Unnormalized::new_wip(place))
1931    }
1932
1933    fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1934        self.has_rustc_attrs && {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(closure_def_id,
                        &self.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcCaptureAnalysis) =>
                            {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, closure_def_id, RustcCaptureAnalysis)
1935    }
1936
1937    fn log_capture_analysis_first_pass(
1938        &self,
1939        closure_def_id: LocalDefId,
1940        capture_information: &InferredCaptureInformation<'tcx>,
1941        closure_span: Span,
1942    ) {
1943        if self.should_log_capture_analysis(closure_def_id) {
1944            let mut diag =
1945                self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1946            for (place, capture_info) in capture_information {
1947                let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1948                let output_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
    })format!("Capturing {capture_str}");
1949
1950                let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1951                diag.span_note(span, output_str);
1952            }
1953            diag.emit();
1954        }
1955    }
1956
1957    fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1958        if self.should_log_capture_analysis(closure_def_id) {
1959            if let Some(min_captures) =
1960                self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1961            {
1962                let mut diag =
1963                    self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
1964
1965                for (_, min_captures_for_var) in min_captures {
1966                    for capture in min_captures_for_var {
1967                        let place = &capture.place;
1968                        let capture_info = &capture.info;
1969
1970                        let capture_str =
1971                            construct_capture_info_string(self.tcx, place, capture_info);
1972                        let output_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
    })format!("Min Capture {capture_str}");
1973
1974                        if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1975                            let path_span = capture_info
1976                                .path_expr_id
1977                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1978                            let capture_kind_span = capture_info
1979                                .capture_kind_expr_id
1980                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1981
1982                            let mut multi_span: MultiSpan =
1983                                MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [path_span, capture_kind_span]))vec![path_span, capture_kind_span]);
1984
1985                            let capture_kind_label =
1986                                construct_capture_kind_reason_string(self.tcx, place, capture_info);
1987                            let path_label = construct_path_string(self.tcx, place);
1988
1989                            multi_span.push_span_label(path_span, path_label);
1990                            multi_span.push_span_label(capture_kind_span, capture_kind_label);
1991
1992                            diag.span_note(multi_span, output_str);
1993                        } else {
1994                            let span = capture_info
1995                                .path_expr_id
1996                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1997
1998                            diag.span_note(span, output_str);
1999                        };
2000                    }
2001                }
2002                diag.emit();
2003            }
2004        }
2005    }
2006
2007    /// A captured place is mutable if
2008    /// 1. Projections don't include a Deref of an immut-borrow, **and**
2009    /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
2010    fn determine_capture_mutability(
2011        &self,
2012        typeck_results: &'a TypeckResults<'tcx>,
2013        place: &Place<'tcx>,
2014    ) -> hir::Mutability {
2015        let var_hir_id = match place.base {
2016            PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
2017            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2018        };
2019
2020        let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
2021
2022        let mut is_mutbl = bm.1;
2023
2024        for pointer_ty in place.deref_tys() {
2025            match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
2026                // We don't capture derefs of raw ptrs
2027                ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2028
2029                // Dereferencing a mut-ref allows us to mut the Place if we don't deref
2030                // an immut-ref after on top of this.
2031                ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
2032
2033                // The place isn't mutable once we dereference an immutable reference.
2034                ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
2035
2036                // Dereferencing a box doesn't change mutability
2037                ty::Adt(def, ..) if def.is_box() => {}
2038
2039                unexpected_ty => bug_impl(Some(self.tcx.hir_span(var_hir_id)),
    format_args!("deref of unexpected pointer type {0:?}", unexpected_ty),
    Location::caller())span_bug!(
2040                    self.tcx.hir_span(var_hir_id),
2041                    "deref of unexpected pointer type {:?}",
2042                    unexpected_ty
2043                ),
2044            }
2045        }
2046
2047        is_mutbl
2048    }
2049}
2050
2051/// Determines whether a child capture that is derived from a parent capture
2052/// should be borrowed with the lifetime of the parent coroutine-closure's env.
2053///
2054/// There are two cases when this needs to happen:
2055///
2056/// (1.) Are we borrowing data owned by the parent closure? We can determine if
2057/// that is the case by checking if the parent capture is by move, EXCEPT if we
2058/// apply a deref projection of an immutable reference, reborrows of immutable
2059/// references which aren't restricted to the LUB of the lifetimes of the deref
2060/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
2061///
2062/// ```rust
2063/// let x = &1i32; // Let's call this lifetime `'1`.
2064/// let c = async move || {
2065///     println!("{:?}", *x);
2066///     // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
2067///     // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
2068/// };
2069/// ```
2070///
2071/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
2072/// mutable borrow cannot live for longer than either the parent *or* the borrow
2073/// that we have on the original upvar. Therefore we always need to borrow the
2074/// child capture with the lifetime of the parent coroutine-closure's env.
2075///
2076/// ```rust
2077/// let mut x = 1i32;
2078/// let c = async || {
2079///     x = 1;
2080///     // The parent borrows `x` for some `&'1 mut i32`.
2081///     // However, when we call `c()`, we implicitly autoref for the signature of
2082///     // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
2083///     // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
2084///     // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
2085/// };
2086/// ```
2087///
2088/// If either of these cases apply, then we should capture the borrow with the
2089/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
2090/// not correct, then the program is not unsound, since we still borrowck and validate
2091/// the choices made from this function -- the only side-effect is that the user
2092/// may receive unnecessary borrowck errors.
2093fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
2094    parent_capture: &ty::CapturedPlace<'tcx>,
2095    child_capture: &ty::CapturedPlace<'tcx>,
2096) -> bool {
2097    // (1.)
2098    (!parent_capture.is_by_ref()
2099        // This is just inlined `place.deref_tys()` but truncated to just
2100        // the child projections. Namely, look for a `&T` deref, since we
2101        // can always extend `&'short mut &'long T` to `&'long T`.
2102        && !child_capture
2103            .place
2104            .projections
2105            .iter()
2106            .enumerate()
2107            .skip(parent_capture.place.projections.len())
2108            .any(|(idx, proj)| {
2109                #[allow(non_exhaustive_omitted_patterns)] match proj.kind {
    ProjectionKind::Deref => true,
    _ => false,
}matches!(proj.kind, ProjectionKind::Deref)
2110                    && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
    {
    ty::Ref(.., ty::Mutability::Not) => true,
    _ => false,
}matches!(
2111                        child_capture.place.ty_before_projection(idx).kind(),
2112                        ty::Ref(.., ty::Mutability::Not)
2113                    )
2114            }))
2115        // (2.)
2116        || #[allow(non_exhaustive_omitted_patterns)] match child_capture.info.capture_kind
    {
    UpvarCapture::ByRef(ty::BorrowKind::Mutable) => true,
    _ => false,
}matches!(child_capture.info.capture_kind, UpvarCapture::ByRef(ty::BorrowKind::Mutable))
2117}
2118
2119/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
2120/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
2121fn restrict_repr_packed_field_ref_capture<'tcx>(
2122    mut place: Place<'tcx>,
2123    mut curr_borrow_kind: ty::UpvarCapture,
2124) -> (Place<'tcx>, ty::UpvarCapture) {
2125    let pos = place.projections.iter().enumerate().position(|(i, p)| {
2126        let ty = place.ty_before_projection(i);
2127
2128        // Return true for fields of packed structs.
2129        match p.kind {
2130            ProjectionKind::Field(..) => match ty.kind() {
2131                ty::Adt(def, _) if def.repr().packed() => {
2132                    // We stop here regardless of field alignment. Field alignment can change as
2133                    // types change, including the types of private fields in other crates, and that
2134                    // shouldn't affect how we compute our captures.
2135                    true
2136                }
2137
2138                _ => false,
2139            },
2140            _ => false,
2141        }
2142    });
2143
2144    if let Some(pos) = pos {
2145        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
2146    }
2147
2148    (place, curr_borrow_kind)
2149}
2150
2151/// Returns a Ty that applies the specified capture kind on the provided capture Ty
2152fn apply_capture_kind_on_capture_ty<'tcx>(
2153    tcx: TyCtxt<'tcx>,
2154    ty: Ty<'tcx>,
2155    capture_kind: UpvarCapture,
2156    region: ty::Region<'tcx>,
2157) -> Ty<'tcx> {
2158    match capture_kind {
2159        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
2160        ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
2161    }
2162}
2163
2164/// Returns the Span of where the value with the provided HirId would be dropped
2165fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Option<Span> {
2166    let owner_id = tcx.hir_get_enclosing_scope(hir_id)?;
2167
2168    let hir_id = match tcx.hir_node(owner_id) {
2169        hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { body, .. }, .. }) => body.hir_id,
2170        hir::Node::Block(block) => block.hir_id,
2171        hir::Node::TraitItem(item) => item.hir_id(),
2172        hir::Node::ImplItem(item) => item.hir_id(),
2173        _ => return None,
2174    };
2175    Some(tcx.sess.source_map().end_point(tcx.hir_span(hir_id)))
2176}
2177
2178struct InferBorrowKind<'a, 'tcx> {
2179    fcx: &'a FnCtxt<'a, 'tcx>,
2180    // The def-id of the closure whose kind and upvar accesses are being inferred.
2181    closure_def_id: LocalDefId,
2182
2183    /// For each Place that is captured by the closure, we track the minimal kind of
2184    /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2185    ///
2186    /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2187    /// s.str2 via a MutableBorrow
2188    ///
2189    /// ```rust,no_run
2190    /// struct SomeStruct { str1: String, str2: String };
2191    ///
2192    /// // Assume that the HirId for the variable definition is `V1`
2193    /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2194    ///
2195    /// let fix_s = |new_s2| {
2196    ///     // Assume that the HirId for the expression `s.str1` is `E1`
2197    ///     println!("Updating SomeStruct with str1={0}", s.str1);
2198    ///     // Assume that the HirId for the expression `*s.str2` is `E2`
2199    ///     s.str2 = new_s2;
2200    /// };
2201    /// ```
2202    ///
2203    /// For closure `fix_s`, (at a high level) the map contains
2204    ///
2205    /// ```ignore (illustrative)
2206    /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2207    /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2208    /// ```
2209    capture_information: InferredCaptureInformation<'tcx>,
2210    fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2211}
2212
2213impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
2214    {}
#[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("fake_read",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2214u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place_with_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place_with_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("diag_expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("diag_expr_id");
                                                        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(&place_with_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            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 PlaceBase::Upvar(_) =
                place_with_id.place.base else { return };
            let dummy_capture_kind =
                ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
            let span = self.fcx.tcx.hir_span(diag_expr_id);
            let place =
                self.fcx.normalize(span,
                    Unnormalized::new_wip(place_with_id.place.clone()));
            let (place, _) =
                restrict_capture_precision(place, dummy_capture_kind);
            let (place, _) =
                restrict_repr_packed_field_ref_capture(place,
                    dummy_capture_kind);
            self.fake_reads.push((place, cause, diag_expr_id));
        }
    }
}#[instrument(skip(self), level = "debug")]
2215    fn fake_read(
2216        &mut self,
2217        place_with_id: &PlaceWithHirId<'tcx>,
2218        cause: FakeReadCause,
2219        diag_expr_id: HirId,
2220    ) {
2221        let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
2222
2223        // We need to restrict Fake Read precision to avoid fake reading unsafe code,
2224        // such as deref of a raw pointer.
2225        let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2226
2227        let span = self.fcx.tcx.hir_span(diag_expr_id);
2228        let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
2229
2230        let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
2231
2232        let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2233        self.fake_reads.push((place, cause, diag_expr_id));
2234    }
2235
2236    {}
#[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("consume",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2236u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place_with_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place_with_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("diag_expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("diag_expr_id");
                                                        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(&place_with_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            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 PlaceBase::Upvar(upvar_id) =
                place_with_id.place.base else { return };
            {
                match (&self.closure_def_id, &upvar_id.closure_expr_id) {
                    (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);
                        }
                    }
                }
            };
            let span = self.fcx.tcx.hir_span(diag_expr_id);
            let place =
                self.fcx.normalize(span,
                    Unnormalized::new_wip(place_with_id.place.clone()));
            self.capture_information.push((place,
                    ty::CaptureInfo {
                        capture_kind_expr_id: Some(diag_expr_id),
                        path_expr_id: Some(diag_expr_id),
                        capture_kind: ty::UpvarCapture::ByValue,
                    }));
        }
    }
}#[instrument(skip(self), level = "debug")]
2237    fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2238        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2239        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2240
2241        let span = self.fcx.tcx.hir_span(diag_expr_id);
2242        let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
2243
2244        self.capture_information.push((
2245            place,
2246            ty::CaptureInfo {
2247                capture_kind_expr_id: Some(diag_expr_id),
2248                path_expr_id: Some(diag_expr_id),
2249                capture_kind: ty::UpvarCapture::ByValue,
2250            },
2251        ));
2252    }
2253
2254    {}
#[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("use_cloned",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2254u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place_with_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place_with_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("diag_expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("diag_expr_id");
                                                        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(&place_with_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            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 PlaceBase::Upvar(upvar_id) =
                place_with_id.place.base else { return };
            {
                match (&self.closure_def_id, &upvar_id.closure_expr_id) {
                    (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);
                        }
                    }
                }
            };
            let span = self.fcx.tcx.hir_span(diag_expr_id);
            let place =
                self.fcx.normalize(span,
                    Unnormalized::new_wip(place_with_id.place.clone()));
            self.capture_information.push((place,
                    ty::CaptureInfo {
                        capture_kind_expr_id: Some(diag_expr_id),
                        path_expr_id: Some(diag_expr_id),
                        capture_kind: ty::UpvarCapture::ByUse,
                    }));
        }
    }
}#[instrument(skip(self), level = "debug")]
2255    fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2256        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2257        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2258
2259        let span = self.fcx.tcx.hir_span(diag_expr_id);
2260        let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
2261
2262        self.capture_information.push((
2263            place,
2264            ty::CaptureInfo {
2265                capture_kind_expr_id: Some(diag_expr_id),
2266                path_expr_id: Some(diag_expr_id),
2267                capture_kind: ty::UpvarCapture::ByUse,
2268            },
2269        ));
2270    }
2271
2272    {}
#[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("borrow",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2272u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place_with_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place_with_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("diag_expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("diag_expr_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("bk")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("bk");
                                                        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(&place_with_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bk)
                                                            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 PlaceBase::Upvar(upvar_id) =
                place_with_id.place.base else { return };
            {
                match (&self.closure_def_id, &upvar_id.closure_expr_id) {
                    (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);
                        }
                    }
                }
            };
            let capture_kind = ty::UpvarCapture::ByRef(bk);
            let span = self.fcx.tcx.hir_span(diag_expr_id);
            let place =
                self.fcx.normalize(span,
                    Unnormalized::new_wip(place_with_id.place.clone()));
            let (place, mut capture_kind) =
                restrict_repr_packed_field_ref_capture(place, capture_kind);
            if place.deref_tys().any(Ty::is_raw_ptr) {
                capture_kind =
                    ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
            }
            self.capture_information.push((place,
                    ty::CaptureInfo {
                        capture_kind_expr_id: Some(diag_expr_id),
                        path_expr_id: Some(diag_expr_id),
                        capture_kind,
                    }));
        }
    }
}#[instrument(skip(self), level = "debug")]
2273    fn borrow(
2274        &mut self,
2275        place_with_id: &PlaceWithHirId<'tcx>,
2276        diag_expr_id: HirId,
2277        bk: ty::BorrowKind,
2278    ) {
2279        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2280        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2281
2282        // The region here will get discarded/ignored
2283        let capture_kind = ty::UpvarCapture::ByRef(bk);
2284
2285        let span = self.fcx.tcx.hir_span(diag_expr_id);
2286        let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
2287
2288        // We only want repr packed restriction to be applied to reading references into a packed
2289        // struct, and not when the data is being moved. Therefore we call this method here instead
2290        // of in `restrict_capture_precision`.
2291        let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(place, capture_kind);
2292
2293        // Raw pointers don't inherit mutability
2294        if place.deref_tys().any(Ty::is_raw_ptr) {
2295            capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2296        }
2297
2298        self.capture_information.push((
2299            place,
2300            ty::CaptureInfo {
2301                capture_kind_expr_id: Some(diag_expr_id),
2302                path_expr_id: Some(diag_expr_id),
2303                capture_kind,
2304            },
2305        ));
2306    }
2307
2308    {}
#[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("mutate",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2308u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("assignee_place")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("assignee_place");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("diag_expr_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("diag_expr_id");
                                                        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(&assignee_place)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            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;
        }
        {
            self.borrow(assignee_place, diag_expr_id,
                ty::BorrowKind::Mutable);
        }
    }
}#[instrument(skip(self), level = "debug")]
2309    fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2310        self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2311    }
2312}
2313
2314/// Rust doesn't permit moving fields out of a type that implements drop
2315{}
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("restrict_precision_for_drop_types",
                                "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                ::tracing_core::__macro_support::Option::Some(2315u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("place")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("place");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("curr_mode")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("curr_mode");
                                                    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(&place)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&curr_mode)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                (Place<'tcx>, ty::UpvarCapture) = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let is_copy_type =
                            fcx.infcx.type_is_copy_modulo_regions(fcx.param_env,
                                place.ty());
                        if let (false, UpvarCapture::ByValue) =
                                (is_copy_type, curr_mode) {
                            for i in 0..place.projections.len() {
                                match place.ty_before_projection(i).kind() {
                                    ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
                                        truncate_place_to_len_and_update_capture_kind(&mut place,
                                            &mut curr_mode, i);
                                        break;
                                    }
                                    _ => {}
                                }
                            }
                        }
                        (place, curr_mode)
                    }
                })();
{
    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_hir_typeck/src/upvar.rs:2315",
                        "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                        ::tracing_core::__macro_support::Option::Some(2315u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            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(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(skip(fcx), ret, level = "debug")]
2316fn restrict_precision_for_drop_types<'a, 'tcx>(
2317    fcx: &'a FnCtxt<'a, 'tcx>,
2318    mut place: Place<'tcx>,
2319    mut curr_mode: ty::UpvarCapture,
2320) -> (Place<'tcx>, ty::UpvarCapture) {
2321    let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
2322
2323    if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2324        for i in 0..place.projections.len() {
2325            match place.ty_before_projection(i).kind() {
2326                ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2327                    truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2328                    break;
2329                }
2330                _ => {}
2331            }
2332        }
2333    }
2334
2335    (place, curr_mode)
2336}
2337
2338/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2339/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2340///   them completely.
2341/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2342fn restrict_precision_for_unsafe(
2343    mut place: Place<'_>,
2344    mut curr_mode: ty::UpvarCapture,
2345) -> (Place<'_>, ty::UpvarCapture) {
2346    if place.base_ty.is_raw_ptr() {
2347        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2348    }
2349
2350    if place.base_ty.is_union() {
2351        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2352    }
2353
2354    for (i, proj) in place.projections.iter().enumerate() {
2355        if proj.ty.is_raw_ptr() {
2356            // Don't apply any projections on top of a raw ptr.
2357            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2358            break;
2359        }
2360
2361        if proj.ty.is_union() {
2362            // Don't capture precise fields of a union.
2363            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2364            break;
2365        }
2366    }
2367
2368    (place, curr_mode)
2369}
2370
2371/// Truncate projections so that the following rules are obeyed by the captured `place`:
2372/// - No Index projections are captured, since arrays are captured completely.
2373/// - No unsafe block is required to capture `place`.
2374///
2375/// Returns the truncated place and updated capture mode.
2376{}
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("restrict_capture_precision",
                                "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                ::tracing_core::__macro_support::Option::Some(2376u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("place")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("place");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("curr_mode")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("curr_mode");
                                                    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(&place)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&curr_mode)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                (Place<'_>, ty::UpvarCapture) = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let (mut place, mut curr_mode) =
                            restrict_precision_for_unsafe(place, curr_mode);
                        if place.projections.is_empty() {
                            return (place, curr_mode);
                        }
                        for (i, proj) in place.projections.iter().enumerate() {
                            match proj.kind {
                                ProjectionKind::Index | ProjectionKind::Subslice => {
                                    truncate_place_to_len_and_update_capture_kind(&mut place,
                                        &mut curr_mode, i);
                                    return (place, curr_mode);
                                }
                                ProjectionKind::Deref => {}
                                ProjectionKind::OpaqueCast => {}
                                ProjectionKind::Field(..) => {}
                                ProjectionKind::UnwrapUnsafeBinder => {}
                            }
                        }
                        (place, curr_mode)
                    }
                })();
{
    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_hir_typeck/src/upvar.rs:2376",
                        "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                        ::tracing_core::__macro_support::Option::Some(2376u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            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(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(ret, level = "debug")]
2377fn restrict_capture_precision(
2378    place: Place<'_>,
2379    curr_mode: ty::UpvarCapture,
2380) -> (Place<'_>, ty::UpvarCapture) {
2381    let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
2382
2383    if place.projections.is_empty() {
2384        // Nothing to do here
2385        return (place, curr_mode);
2386    }
2387
2388    for (i, proj) in place.projections.iter().enumerate() {
2389        match proj.kind {
2390            ProjectionKind::Index | ProjectionKind::Subslice => {
2391                // Arrays are completely captured, so we drop Index and Subslice projections
2392                truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2393                return (place, curr_mode);
2394            }
2395            ProjectionKind::Deref => {}
2396            ProjectionKind::OpaqueCast => {}
2397            ProjectionKind::Field(..) => {}
2398            ProjectionKind::UnwrapUnsafeBinder => {}
2399        }
2400    }
2401
2402    (place, curr_mode)
2403}
2404
2405/// Truncate deref of any reference.
2406{}
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("adjust_for_move_closure",
                                "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                ::tracing_core::__macro_support::Option::Some(2406u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("place")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("place");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("kind")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("kind");
                                                    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(&place)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                (Place<'_>, ty::UpvarCapture) = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let first_deref =
                            place.projections.iter().position(|proj|
                                    proj.kind == ProjectionKind::Deref);
                        if let Some(idx) = first_deref {
                            truncate_place_to_len_and_update_capture_kind(&mut place,
                                &mut kind, idx);
                        }
                        (place, ty::UpvarCapture::ByValue)
                    }
                })();
{
    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_hir_typeck/src/upvar.rs:2406",
                        "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                        ::tracing_core::__macro_support::Option::Some(2406u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            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(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(ret, level = "debug")]
2407fn adjust_for_move_closure(
2408    mut place: Place<'_>,
2409    mut kind: ty::UpvarCapture,
2410) -> (Place<'_>, ty::UpvarCapture) {
2411    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2412
2413    if let Some(idx) = first_deref {
2414        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2415    }
2416
2417    (place, ty::UpvarCapture::ByValue)
2418}
2419
2420/// Truncate deref of any reference.
2421{}
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("adjust_for_use_closure",
                                "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                ::tracing_core::__macro_support::Option::Some(2421u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("place")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("place");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("kind")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("kind");
                                                    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(&place)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                (Place<'_>, ty::UpvarCapture) = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let first_deref =
                            place.projections.iter().position(|proj|
                                    proj.kind == ProjectionKind::Deref);
                        if let Some(idx) = first_deref {
                            truncate_place_to_len_and_update_capture_kind(&mut place,
                                &mut kind, idx);
                        }
                        (place, ty::UpvarCapture::ByUse)
                    }
                })();
{
    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_hir_typeck/src/upvar.rs:2421",
                        "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                        ::tracing_core::__macro_support::Option::Some(2421u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            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(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(ret, level = "debug")]
2422fn adjust_for_use_closure(
2423    mut place: Place<'_>,
2424    mut kind: ty::UpvarCapture,
2425) -> (Place<'_>, ty::UpvarCapture) {
2426    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2427
2428    if let Some(idx) = first_deref {
2429        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2430    }
2431
2432    (place, ty::UpvarCapture::ByUse)
2433}
2434
2435/// Adjust closure capture just that if taking ownership of data, only move data
2436/// from enclosing stack frame.
2437{}
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("adjust_for_non_move_closure",
                                "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                ::tracing_core::__macro_support::Option::Some(2437u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("place")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("place");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("kind")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("kind");
                                                    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(&place)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                (Place<'_>, ty::UpvarCapture) = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let contains_deref =
                            place.projections.iter().position(|proj|
                                    proj.kind == ProjectionKind::Deref);
                        match kind {
                            ty::UpvarCapture::ByValue => {
                                if let Some(idx) = contains_deref {
                                    truncate_place_to_len_and_update_capture_kind(&mut place,
                                        &mut kind, idx);
                                }
                            }
                            ty::UpvarCapture::ByUse => {
                                kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
                            }
                            ty::UpvarCapture::ByRef(..) => {}
                        }
                        (place, kind)
                    }
                })();
{
    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_hir_typeck/src/upvar.rs:2437",
                        "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                        ::tracing_core::__macro_support::Option::Some(2437u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            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(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(ret, level = "debug")]
2438fn adjust_for_non_move_closure(
2439    mut place: Place<'_>,
2440    mut kind: ty::UpvarCapture,
2441) -> (Place<'_>, ty::UpvarCapture) {
2442    let contains_deref =
2443        place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2444
2445    match kind {
2446        ty::UpvarCapture::ByValue => {
2447            if let Some(idx) = contains_deref {
2448                truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2449            }
2450        }
2451
2452        // A non-`move`/`use` closure that only `.use`s an upvar does not need to
2453        // own (and thus clone-on-capture) the value. The `ByUse` kind here can only
2454        // come from a `x.use` in the body (a `use ||` capture clause goes through
2455        // `adjust_for_use_closure` instead). Capturing such a place by immutable
2456        // borrow lets the `.use` expression clone per evaluation, rather than also
2457        // cloning the value into the closure at construction time. See #157141.
2458        ty::UpvarCapture::ByUse => {
2459            kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2460        }
2461
2462        ty::UpvarCapture::ByRef(..) => {}
2463    }
2464
2465    (place, kind)
2466}
2467
2468fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2469    let variable_name = match place.base {
2470        PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2471        _ => bug_impl(None, format_args!("Capture_information should only contain upvars"),
    Location::caller())bug!("Capture_information should only contain upvars"),
2472    };
2473
2474    let mut projections_str = String::new();
2475    for (i, item) in place.projections.iter().enumerate() {
2476        let proj = match item.kind {
2477            ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
    })format!("({a:?}, {b:?})"),
2478            ProjectionKind::Deref => String::from("Deref"),
2479            ProjectionKind::Index => String::from("Index"),
2480            ProjectionKind::Subslice => String::from("Subslice"),
2481            ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2482            ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2483        };
2484        if i != 0 {
2485            projections_str.push(',');
2486        }
2487        projections_str.push_str(proj.as_str());
2488    }
2489
2490    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
                projections_str))
    })format!("{variable_name}[{projections_str}]")
2491}
2492
2493fn construct_capture_kind_reason_string<'tcx>(
2494    tcx: TyCtxt<'_>,
2495    place: &Place<'tcx>,
2496    capture_info: &ty::CaptureInfo,
2497) -> String {
2498    let place_str = construct_place_string(tcx, place);
2499
2500    let capture_kind_str = match capture_info.capture_kind {
2501        ty::UpvarCapture::ByValue => "ByValue".into(),
2502        ty::UpvarCapture::ByUse => "ByUse".into(),
2503        ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
2504    };
2505
2506    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} captured as {1} here",
                place_str, capture_kind_str))
    })format!("{place_str} captured as {capture_kind_str} here")
2507}
2508
2509fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2510    let place_str = construct_place_string(tcx, place);
2511
2512    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} used here", place_str))
    })format!("{place_str} used here")
2513}
2514
2515fn construct_capture_info_string<'tcx>(
2516    tcx: TyCtxt<'_>,
2517    place: &Place<'tcx>,
2518    capture_info: &ty::CaptureInfo,
2519) -> String {
2520    let place_str = construct_place_string(tcx, place);
2521
2522    let capture_kind_str = match capture_info.capture_kind {
2523        ty::UpvarCapture::ByValue => "ByValue".into(),
2524        ty::UpvarCapture::ByUse => "ByUse".into(),
2525        ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
2526    };
2527    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
                capture_kind_str))
    })format!("{place_str} -> {capture_kind_str}")
2528}
2529
2530fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2531    tcx.hir_name(var_hir_id)
2532}
2533
2534{}
#[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("should_do_rust_2021_incompatible_closure_captures_analysis",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2534u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("closure_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("closure_id");
                                                        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(&closure_id)
                                                            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;
        }
        {
            if tcx.sess.at_least_rust_2021() { return false; }
            !tcx.lint_level_spec_at_node(RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
                        closure_id).is_allow()
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2535fn should_do_rust_2021_incompatible_closure_captures_analysis(
2536    tcx: TyCtxt<'_>,
2537    closure_id: HirId,
2538) -> bool {
2539    if tcx.sess.at_least_rust_2021() {
2540        return false;
2541    }
2542
2543    !tcx.lint_level_spec_at_node(RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id).is_allow()
2544}
2545
2546/// Return a two string tuple (s1, s2)
2547/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2548/// - s2: Comma separated names of the variables being migrated.
2549fn migration_suggestion_for_2229(
2550    tcx: TyCtxt<'_>,
2551    need_migrations: &[NeededMigration],
2552) -> (String, String) {
2553    let need_migrations_variables = need_migrations
2554        .iter()
2555        .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2556        .collect::<Vec<_>>();
2557
2558    let migration_ref_concat =
2559        need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
2560
2561    let migration_string = if 1 == need_migrations.len() {
2562        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let _ = {0}",
                migration_ref_concat))
    })format!("let _ = {migration_ref_concat}")
2563    } else {
2564        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let _ = ({0})",
                migration_ref_concat))
    })format!("let _ = ({migration_ref_concat})")
2565    };
2566
2567    let migrated_variables_concat =
2568        need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", v))
    })format!("`{v}`")).collect::<Vec<_>>().join(", ");
2569
2570    (migration_string, migrated_variables_concat)
2571}
2572
2573/// Helper function to determine if we need to escalate CaptureKind from
2574/// CaptureInfo A to B and returns the escalated CaptureInfo.
2575/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2576///
2577/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2578/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2579///
2580/// It is the caller's duty to figure out which path_expr_id to use.
2581///
2582/// If both the CaptureKind and Expression are considered to be equivalent,
2583/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2584/// expressions reported back to the user as part of diagnostics based on which appears earlier
2585/// in the closure. This can be achieved simply by calling
2586/// `determine_capture_info(existing_info, current_info)`. This works out because the
2587/// expressions that occur earlier in the closure body than the current expression are processed before.
2588/// Consider the following example
2589/// ```rust,no_run
2590/// struct Point { x: i32, y: i32 }
2591/// let mut p = Point { x: 10, y: 10 };
2592///
2593/// let c = || {
2594///     p.x += 10; // E1
2595///     // ...
2596///     // More code
2597///     // ...
2598///     p.x += 10; // E2
2599/// };
2600/// ```
2601/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2602/// and both have an expression associated, however for diagnostics we prefer reporting
2603/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2604/// would've already handled `E1`, and have an existing capture_information for it.
2605/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2606/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2607fn determine_capture_info(
2608    capture_info_a: ty::CaptureInfo,
2609    capture_info_b: ty::CaptureInfo,
2610) -> ty::CaptureInfo {
2611    // If the capture kind is equivalent then, we don't need to escalate and can compare the
2612    // expressions.
2613    let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2614        (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2615        (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2616        (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2617        (ty::UpvarCapture::ByValue, _)
2618        | (ty::UpvarCapture::ByUse, _)
2619        | (ty::UpvarCapture::ByRef(_), _) => false,
2620    };
2621
2622    if eq_capture_kind {
2623        match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2624            (Some(_), _) | (None, None) => capture_info_a,
2625            (None, Some(_)) => capture_info_b,
2626        }
2627    } else {
2628        // We select the CaptureKind which ranks higher based the following priority order:
2629        // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2630        match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2631            (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2632            | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2633                bug_impl(None,
    format_args!("Same capture can\'t be ByUse and ByValue at the same time"),
    Location::caller())bug!("Same capture can't be ByUse and ByValue at the same time")
2634            }
2635            (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2636            | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2637            | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2638                capture_info_a
2639            }
2640            (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2641                capture_info_b
2642            }
2643            (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2644                match (ref_a, ref_b) {
2645                    // Take LHS:
2646                    (BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2647                    | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
2648
2649                    // Take RHS:
2650                    (BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2651                    | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
2652
2653                    (BorrowKind::Immutable, BorrowKind::Immutable)
2654                    | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2655                    | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2656                        bug_impl(None, format_args!("Expected unequal capture kinds"),
    Location::caller());bug!("Expected unequal capture kinds");
2657                    }
2658                }
2659            }
2660        }
2661    }
2662}
2663
2664/// Truncates `place` to have up to `len` projections.
2665/// `curr_mode` is the current required capture kind for the place.
2666/// Returns the truncated `place` and the updated required capture kind.
2667///
2668/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2669/// contained `Deref` of `&mut`.
2670fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2671    place: &mut Place<'tcx>,
2672    curr_mode: &mut ty::UpvarCapture,
2673    len: usize,
2674) {
2675    let is_mut_ref = |ty: Ty<'_>| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Ref(.., hir::Mutability::Mut) => true,
    _ => false,
}matches!(ty.kind(), ty::Ref(.., hir::Mutability::Mut));
2676
2677    // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2678    // UniqueImmBorrow
2679    // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2680    // we don't need to worry about that case here.
2681    match curr_mode {
2682        ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2683            for i in len..place.projections.len() {
2684                if place.projections[i].kind == ProjectionKind::Deref
2685                    && is_mut_ref(place.ty_before_projection(i))
2686                {
2687                    *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2688                    break;
2689                }
2690            }
2691        }
2692
2693        ty::UpvarCapture::ByRef(..) => {}
2694        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2695    }
2696
2697    place.projections.truncate(len);
2698}
2699
2700/// Determines the Ancestry relationship of Place A relative to Place B
2701///
2702/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2703/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2704/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2705fn determine_place_ancestry_relation<'tcx>(
2706    place_a: &Place<'tcx>,
2707    place_b: &Place<'tcx>,
2708) -> PlaceAncestryRelation {
2709    // If Place A and Place B don't start off from the same root variable, they are divergent.
2710    if place_a.base != place_b.base {
2711        return PlaceAncestryRelation::Divergent;
2712    }
2713
2714    // Assume of length of projections_a = n
2715    let projections_a = &place_a.projections;
2716
2717    // Assume of length of projections_b = m
2718    let projections_b = &place_b.projections;
2719
2720    let same_initial_projections =
2721        iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
2722
2723    if same_initial_projections {
2724        use std::cmp::Ordering;
2725
2726        // First min(n, m) projections are the same
2727        // Select Ancestor/Descendant
2728        match projections_b.len().cmp(&projections_a.len()) {
2729            Ordering::Greater => PlaceAncestryRelation::Ancestor,
2730            Ordering::Equal => PlaceAncestryRelation::SamePlace,
2731            Ordering::Less => PlaceAncestryRelation::Descendant,
2732        }
2733    } else {
2734        PlaceAncestryRelation::Divergent
2735    }
2736}
2737
2738/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2739/// borrow checking perspective, allowing us to save us on the size of the capture.
2740///
2741///
2742/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2743/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2744/// rightmost deref of the capture if the deref is applied to a shared ref.
2745///
2746/// Reason we only drop the last deref is because of the following edge case:
2747///
2748/// ```
2749/// # struct A { field_of_a: Box<i32> }
2750/// # struct B {}
2751/// # struct C<'a>(&'a i32);
2752/// struct MyStruct<'a> {
2753///    a: &'static A,
2754///    b: B,
2755///    c: C<'a>,
2756/// }
2757///
2758/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2759///     || drop(&*m.a.field_of_a)
2760///     // Here we really do want to capture `*m.a` because that outlives `'static`
2761///
2762///     // If we capture `m`, then the closure no longer outlives `'static`
2763///     // it is constrained to `'a`
2764/// }
2765/// ```
2766{}
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("truncate_capture_for_optimization",
                                "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                                ::tracing_core::__macro_support::Option::Some(2766u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("place")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("place");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("curr_mode")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("curr_mode");
                                                    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(&place)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&curr_mode)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                (Place<'_>, ty::UpvarCapture) = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let is_shared_ref =
                            |ty: Ty<'_>|
                                #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
                                    ty::Ref(.., hir::Mutability::Not) => true,
                                    _ => false,
                                };
                        let idx =
                            place.projections.iter().rposition(|proj|
                                    ProjectionKind::Deref == proj.kind);
                        match idx {
                            Some(idx) if is_shared_ref(place.ty_before_projection(idx))
                                => {
                                truncate_place_to_len_and_update_capture_kind(&mut place,
                                    &mut curr_mode, idx + 1)
                            }
                            None | Some(_) => {}
                        }
                        (place, curr_mode)
                    }
                })();
{
    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_hir_typeck/src/upvar.rs:2766",
                        "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/upvar.rs"),
                        ::tracing_core::__macro_support::Option::Some(2766u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            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(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(ret, level = "debug")]
2767fn truncate_capture_for_optimization(
2768    mut place: Place<'_>,
2769    mut curr_mode: ty::UpvarCapture,
2770) -> (Place<'_>, ty::UpvarCapture) {
2771    let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
2772
2773    // Find the rightmost deref (if any). All the projections that come after this
2774    // are fields or other "in-place pointer adjustments"; these refer therefore to
2775    // data owned by whatever pointer is being dereferenced here.
2776    let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
2777
2778    match idx {
2779        // If that pointer is a shared reference, then we don't need those fields.
2780        Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2781            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2782        }
2783        None | Some(_) => {}
2784    }
2785
2786    (place, curr_mode)
2787}
2788
2789/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2790/// `span` is the span of the closure.
2791fn enable_precise_capture(span: Span) -> bool {
2792    // We use span here to ensure that if the closure was generated by a macro with a different
2793    // edition.
2794    span.at_least_rust_2021()
2795}