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