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::def_id::LocalDefId;
40use rustc_hir::intravisit::{self, Visitor};
41use rustc_hir::{self as hir, HirId, find_attr};
42use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
43use rustc_middle::mir::FakeReadCause;
44use rustc_middle::traits::ObligationCauseCode;
45use rustc_middle::ty::{
46    self, BorrowKind, ClosureSizeProfileData, Ty, TyCtxt, TypeVisitableExt as _, TypeckResults,
47    UpvarArgs, UpvarCapture,
48};
49use rustc_middle::{bug, span_bug};
50use rustc_session::lint;
51use rustc_span::{BytePos, Pos, Span, Symbol, sym};
52use rustc_trait_selection::error_reporting::InferCtxtErrorExt as _;
53use rustc_trait_selection::infer::InferCtxtExt;
54use rustc_trait_selection::solve;
55use tracing::{debug, instrument};
56
57use super::FnCtxt;
58use crate::expr_use_visitor as euv;
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> {
        match ::core::cmp::PartialOrd::partial_cmp(&self.auto_traits,
                &other.auto_traits) {
            ::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
                ::core::cmp::PartialOrd::partial_cmp(&self.drop_order,
                    &other.drop_order),
            cmp => cmp,
        }
    }
}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(&["closure_hir_id",
                                                    "span", "body_id", "capture_clause"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_hir_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_clause)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let 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);
            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:303",
                                    "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(303u32),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("For closure={0:?}, capture_information={1:#?}",
                                                                closure_def_id, delegate.capture_information) as
                                                        &dyn 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:332",
                                                "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(332u32),
                                                ::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};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("seed place {0:?}",
                                                                            place) as &dyn 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 &&
                    !args.references_error() {
                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([],
                                tupled_upvars_ty_for_borrow, false, hir::Safety::Safe,
                                rustc_abi::ExternAbi::Rust),
                            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:494",
                                    "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(494u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["closure_hir_id",
                                                    "args", "final_upvar_tys"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&closure_hir_id)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&args) as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&final_upvar_tys)
                                                        as &dyn 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        let _ = euv::ExprUseVisitor::new(&closure_fcx, &mut delegate).consume_body(body);
212
213        // There are several curious situations with coroutine-closures where
214        // analysis is too aggressive with borrows when the coroutine-closure is
215        // marked `move`. Specifically:
216        //
217        // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
218        // inference, then it's still possible that we try to borrow upvars from
219        // the coroutine-closure because they are not used by the coroutine body
220        // in a way that forces a move. See the test:
221        // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
222        //
223        // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
224        // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
225        // would force the closure to `FnOnce`.
226        // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
227        //
228        // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
229        // coroutine bodies can't borrow from their parent closure. To fix this,
230        // we force the inner coroutine to also be `move`. This only matters for
231        // coroutine-closures that are `move` since otherwise they themselves will
232        // be borrowing from the outer environment, so there's no self-borrows occurring.
233        if let UpvarArgs::Coroutine(..) = args
234            && let hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) =
235                self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
236            && let parent_hir_id =
237                self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
238            && let parent_ty = self.node_ty(parent_hir_id)
239            && let hir::CaptureBy::Value { move_kw } =
240                self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
241        {
242            // (1.) Closure signature inference forced this closure to `FnOnce`.
243            if let Some(ty::ClosureKind::FnOnce) = self.closure_kind(parent_ty) {
244                capture_clause = hir::CaptureBy::Value { move_kw };
245            }
246            // (2.) The way that the closure uses its upvars means it's `FnOnce`.
247            else if self.coroutine_body_consumes_upvars(closure_def_id, body) {
248                capture_clause = hir::CaptureBy::Value { move_kw };
249            }
250        }
251
252        // As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
253        // to `ByRef` for the `async {}` block internal to async fns/closure. This means
254        // that we would *not* be moving all of the parameters into the async block in all cases.
255        // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
256        // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
257        //
258        // We force all of these arguments to be captured by move before we do expr use analysis.
259        //
260        // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
261        // moving all of the `LocalSource::AsyncFn` locals here.
262        if let Some(hir::CoroutineKind::Desugared(
263            _,
264            hir::CoroutineSource::Fn | hir::CoroutineSource::Closure,
265        )) = self.tcx.coroutine_kind(closure_def_id)
266        {
267            let hir::ExprKind::Block(block, _) = body.value.kind else {
268                bug!();
269            };
270            for stmt in block.stmts {
271                let hir::StmtKind::Let(hir::LetStmt {
272                    init: Some(init),
273                    source: hir::LocalSource::AsyncFn,
274                    pat,
275                    ..
276                }) = stmt.kind
277                else {
278                    bug!();
279                };
280                let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), _, _, _) = pat.kind
281                else {
282                    // Complex pattern, skip the non-upvar local.
283                    continue;
284                };
285                let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = init.kind else {
286                    bug!();
287                };
288                let hir::def::Res::Local(local_id) = path.res else {
289                    bug!();
290                };
291                let place = closure_fcx.place_for_root_variable(closure_def_id, local_id);
292                delegate.capture_information.push((
293                    place,
294                    ty::CaptureInfo {
295                        capture_kind_expr_id: Some(init.hir_id),
296                        path_expr_id: Some(init.hir_id),
297                        capture_kind: UpvarCapture::ByValue,
298                    },
299                ));
300            }
301        }
302
303        debug!(
304            "For closure={:?}, capture_information={:#?}",
305            closure_def_id, delegate.capture_information
306        );
307
308        self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
309
310        let (capture_information, closure_kind, origin) = self
311            .process_collected_capture_information(capture_clause, &delegate.capture_information);
312
313        self.compute_min_captures(closure_def_id, capture_information, span);
314
315        let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
316
317        if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
318            self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
319        }
320
321        let after_feature_tys = self.final_upvar_tys(closure_def_id);
322
323        // We now fake capture information for all variables that are mentioned within the closure
324        // We do this after handling migrations so that min_captures computes before
325        if !enable_precise_capture(span) {
326            let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
327
328            if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
329                for var_hir_id in upvars.keys() {
330                    let place = closure_fcx.place_for_root_variable(closure_def_id, *var_hir_id);
331
332                    debug!("seed place {:?}", place);
333
334                    let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
335                    let fake_info = ty::CaptureInfo {
336                        capture_kind_expr_id: None,
337                        path_expr_id: None,
338                        capture_kind,
339                    };
340
341                    capture_information.push((place, fake_info));
342                }
343            }
344
345            // This will update the min captures based on this new fake information.
346            self.compute_min_captures(closure_def_id, capture_information, span);
347        }
348
349        let before_feature_tys = self.final_upvar_tys(closure_def_id);
350
351        if infer_kind {
352            // Unify the (as yet unbound) type variable in the closure
353            // args with the kind we inferred.
354            let closure_kind_ty = match args {
355                UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
356                UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
357                UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
358            };
359            self.demand_eqtype(
360                span,
361                Ty::from_closure_kind(self.tcx, closure_kind),
362                closure_kind_ty,
363            );
364
365            // If we have an origin, store it.
366            if let Some(mut origin) = origin {
367                if !enable_precise_capture(span) {
368                    // Without precise captures, we just capture the base and ignore
369                    // the projections.
370                    origin.1.projections.clear()
371                }
372
373                self.typeck_results
374                    .borrow_mut()
375                    .closure_kind_origins_mut()
376                    .insert(closure_hir_id, origin);
377            }
378        }
379
380        // For coroutine-closures, we additionally must compute the
381        // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
382        // version of the coroutine-closure's output coroutine.
383        if let UpvarArgs::CoroutineClosure(args) = args
384            && !args.references_error()
385        {
386            let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
387                self.tcx,
388                ty::INNERMOST,
389                ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::ClosureEnv },
390            );
391
392            let num_args = args
393                .as_coroutine_closure()
394                .coroutine_closure_sig()
395                .skip_binder()
396                .tupled_inputs_ty
397                .tuple_fields()
398                .len();
399            let typeck_results = self.typeck_results.borrow();
400
401            let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
402                self.tcx,
403                ty::analyze_coroutine_closure_captures(
404                    typeck_results.closure_min_captures_flattened(closure_def_id),
405                    typeck_results
406                        .closure_min_captures_flattened(
407                            self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
408                        )
409                        // Skip the captures that are just moving the closure's args
410                        // into the coroutine. These are always by move, and we append
411                        // those later in the `CoroutineClosureSignature` helper functions.
412                        .skip(num_args),
413                    |(_, parent_capture), (_, child_capture)| {
414                        // This is subtle. See documentation on function.
415                        let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
416                            parent_capture,
417                            child_capture,
418                        );
419
420                        let upvar_ty = child_capture.place.ty();
421                        let capture = child_capture.info.capture_kind;
422                        // Not all upvars are captured by ref, so use
423                        // `apply_capture_kind_on_capture_ty` to ensure that we
424                        // compute the right captured type.
425                        apply_capture_kind_on_capture_ty(
426                            self.tcx,
427                            upvar_ty,
428                            capture,
429                            if needs_ref {
430                                closure_env_region
431                            } else {
432                                self.tcx.lifetimes.re_erased
433                            },
434                        )
435                    },
436                ),
437            );
438            let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
439                self.tcx,
440                ty::Binder::bind_with_vars(
441                    self.tcx.mk_fn_sig(
442                        [],
443                        tupled_upvars_ty_for_borrow,
444                        false,
445                        hir::Safety::Safe,
446                        rustc_abi::ExternAbi::Rust,
447                    ),
448                    self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
449                        ty::BoundRegionKind::ClosureEnv,
450                    )]),
451                ),
452            );
453            self.demand_eqtype(
454                span,
455                args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
456                coroutine_captures_by_ref_ty,
457            );
458
459            // Additionally, we can now constrain the coroutine's kind type.
460            //
461            // We only do this if `infer_kind`, because if we have constrained
462            // the kind from closure signature inference, the kind inferred
463            // for the inner coroutine may actually be more restrictive.
464            if infer_kind {
465                let ty::Coroutine(_, coroutine_args) =
466                    *self.typeck_results.borrow().expr_ty(body.value).kind()
467                else {
468                    bug!();
469                };
470                self.demand_eqtype(
471                    span,
472                    coroutine_args.as_coroutine().kind_ty(),
473                    Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
474                );
475            }
476        }
477
478        self.log_closure_min_capture_info(closure_def_id, span);
479
480        // Now that we've analyzed the closure, we know how each
481        // variable is borrowed, and we know what traits the closure
482        // implements (Fn vs FnMut etc). We now have some updates to do
483        // with that information.
484        //
485        // Note that no closure type C may have an upvar of type C
486        // (though it may reference itself via a trait object). This
487        // results from the desugaring of closures to a struct like
488        // `Foo<..., UV0...UVn>`. If one of those upvars referenced
489        // C, then the type would have infinite size (and the
490        // inference algorithm will reject it).
491
492        // Equate the type variables for the upvars with the actual types.
493        let final_upvar_tys = self.final_upvar_tys(closure_def_id);
494        debug!(?closure_hir_id, ?args, ?final_upvar_tys);
495
496        if self.tcx.features().unsized_fn_params() {
497            for capture in
498                self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
499            {
500                if let UpvarCapture::ByValue = capture.info.capture_kind {
501                    self.require_type_is_sized(
502                        capture.place.ty(),
503                        capture.get_path_span(self.tcx),
504                        ObligationCauseCode::SizedClosureCapture(closure_def_id),
505                    );
506                }
507            }
508        }
509
510        // Build a tuple (U0..Un) of the final upvar types U0..Un
511        // and unify the upvar tuple type in the closure with it:
512        let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
513        self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
514
515        let fake_reads = delegate.fake_reads;
516
517        self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
518
519        if self.tcx.sess.opts.unstable_opts.profile_closures {
520            self.typeck_results.borrow_mut().closure_size_eval.insert(
521                closure_def_id,
522                ClosureSizeProfileData {
523                    before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
524                    after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
525                },
526            );
527        }
528
529        // If we are also inferred the closure kind here,
530        // process any deferred resolutions.
531        let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
532        for deferred_call_resolution in deferred_call_resolutions {
533            deferred_call_resolution.resolve(&FnCtxt::new(self, self.param_env, closure_def_id));
534        }
535    }
536
537    /// Determines whether the body of the coroutine uses its upvars in a way that
538    /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
539    /// In a more detailed comment above, we care whether this happens, since if
540    /// this happens, we want to force the coroutine to move all of the upvars it
541    /// would've borrowed from the parent coroutine-closure.
542    ///
543    /// This only really makes sense to be called on the child coroutine of a
544    /// coroutine-closure.
545    fn coroutine_body_consumes_upvars(
546        &self,
547        coroutine_def_id: LocalDefId,
548        body: &'tcx hir::Body<'tcx>,
549    ) -> bool {
550        // This block contains argument capturing details. Since arguments
551        // aren't upvars, we do not care about them for determining if the
552        // coroutine body actually consumes its upvars.
553        let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
554        else {
555            ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
556        };
557        // Specifically, we only care about the *real* body of the coroutine.
558        // We skip out into the drop-temps within the block of the body in order
559        // to skip over the args of the desugaring.
560        let hir::ExprKind::DropTemps(body) = body.kind else {
561            ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
562        };
563
564        let coroutine_fcx =
565            FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id);
566
567        let mut delegate = InferBorrowKind {
568            fcx: &coroutine_fcx,
569            closure_def_id: coroutine_def_id,
570            capture_information: Default::default(),
571            fake_reads: Default::default(),
572        };
573
574        let _ = euv::ExprUseVisitor::new(&coroutine_fcx, &mut delegate).consume_expr(body);
575
576        let (_, kind, _) = self.process_collected_capture_information(
577            hir::CaptureBy::Ref,
578            &delegate.capture_information,
579        );
580
581        #[allow(non_exhaustive_omitted_patterns)] match kind {
    ty::ClosureKind::FnOnce => true,
    _ => false,
}matches!(kind, ty::ClosureKind::FnOnce)
582    }
583
584    // Returns a list of `Ty`s for each upvar.
585    fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
586        self.typeck_results
587            .borrow()
588            .closure_min_captures_flattened(closure_id)
589            .map(|captured_place| {
590                let upvar_ty = captured_place.place.ty();
591                let capture = captured_place.info.capture_kind;
592
593                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:593",
                        "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(593u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                        ::tracing_core::field::FieldSet::new(&["captured_place.place",
                                        "upvar_ty", "capture", "captured_place.mutability"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&captured_place.place)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&upvar_ty)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&capture) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&captured_place.mutability)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?captured_place.place, ?upvar_ty, ?capture, ?captured_place.mutability);
594
595                apply_capture_kind_on_capture_ty(
596                    self.tcx,
597                    upvar_ty,
598                    capture,
599                    self.tcx.lifetimes.re_erased,
600                )
601            })
602            .collect()
603    }
604
605    /// Adjusts the closure capture information to ensure that the operations aren't unsafe,
606    /// and that the path can be captured with required capture kind (depending on use in closure,
607    /// move closure etc.)
608    ///
609    /// Returns the set of adjusted information along with the inferred closure kind and span
610    /// associated with the closure kind inference.
611    ///
612    /// Note that we *always* infer a minimal kind, even if
613    /// we don't always *use* that in the final result (i.e., sometimes
614    /// we've taken the closure kind from the expectations instead, and
615    /// for coroutines we don't even implement the closure traits
616    /// really).
617    ///
618    /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
619    /// contains a `Some()` with the `Place` that caused us to do so.
620    fn process_collected_capture_information(
621        &self,
622        capture_clause: hir::CaptureBy,
623        capture_information: &InferredCaptureInformation<'tcx>,
624    ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
625        let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
626        let mut origin: Option<(Span, Place<'tcx>)> = None;
627
628        let processed = capture_information
629            .iter()
630            .cloned()
631            .map(|(place, mut capture_info)| {
632                // Apply rules for safety before inferring closure kind
633                let (place, capture_kind) =
634                    restrict_capture_precision(place, capture_info.capture_kind);
635
636                let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
637
638                let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
639                    self.tcx.hir_span(usage_expr)
640                } else {
641                    ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
642                };
643
644                let updated = match capture_kind {
645                    ty::UpvarCapture::ByValue => match closure_kind {
646                        ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
647                            (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
648                        }
649                        // If closure is already FnOnce, don't update
650                        ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
651                    },
652
653                    ty::UpvarCapture::ByRef(
654                        ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
655                    ) => {
656                        match closure_kind {
657                            ty::ClosureKind::Fn => {
658                                (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
659                            }
660                            // Don't update the origin
661                            ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
662                                (closure_kind, origin.take())
663                            }
664                        }
665                    }
666
667                    _ => (closure_kind, origin.take()),
668                };
669
670                closure_kind = updated.0;
671                origin = updated.1;
672
673                let (place, capture_kind) = match capture_clause {
674                    hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
675                    hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
676                    hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
677                };
678
679                // This restriction needs to be applied after we have handled adjustments for `move`
680                // closures. We want to make sure any adjustment that might make us move the place into
681                // the closure gets handled.
682                let (place, capture_kind) =
683                    restrict_precision_for_drop_types(self, place, capture_kind);
684
685                capture_info.capture_kind = capture_kind;
686                (place, capture_info)
687            })
688            .collect();
689
690        (processed, closure_kind, origin)
691    }
692
693    /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
694    /// Places (and corresponding capture kind) that we need to keep track of to support all
695    /// the required captured paths.
696    ///
697    ///
698    /// Note: If this function is called multiple times for the same closure, it will update
699    ///       the existing min_capture map that is stored in TypeckResults.
700    ///
701    /// Eg:
702    /// ```
703    /// #[derive(Debug)]
704    /// struct Point { x: i32, y: i32 }
705    ///
706    /// let s = String::from("s");  // hir_id_s
707    /// let mut p = Point { x: 2, y: -2 }; // his_id_p
708    /// let c = || {
709    ///        println!("{s:?}");  // L1
710    ///        p.x += 10;  // L2
711    ///        println!("{}" , p.y); // L3
712    ///        println!("{p:?}"); // L4
713    ///        drop(s);   // L5
714    /// };
715    /// ```
716    /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
717    /// the lines L1..5 respectively.
718    ///
719    /// InferBorrowKind results in a structure like this:
720    ///
721    /// ```ignore (illustrative)
722    /// {
723    ///       Place(base: hir_id_s, projections: [], ....) -> {
724    ///                                                            capture_kind_expr: hir_id_L5,
725    ///                                                            path_expr_id: hir_id_L5,
726    ///                                                            capture_kind: ByValue
727    ///                                                       },
728    ///       Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
729    ///                                                                     capture_kind_expr: hir_id_L2,
730    ///                                                                     path_expr_id: hir_id_L2,
731    ///                                                                     capture_kind: ByValue
732    ///                                                                 },
733    ///       Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
734    ///                                                                     capture_kind_expr: hir_id_L3,
735    ///                                                                     path_expr_id: hir_id_L3,
736    ///                                                                     capture_kind: ByValue
737    ///                                                                 },
738    ///       Place(base: hir_id_p, projections: [], ...) -> {
739    ///                                                          capture_kind_expr: hir_id_L4,
740    ///                                                          path_expr_id: hir_id_L4,
741    ///                                                          capture_kind: ByValue
742    ///                                                      },
743    /// }
744    /// ```
745    ///
746    /// After the min capture analysis, we get:
747    /// ```ignore (illustrative)
748    /// {
749    ///       hir_id_s -> [
750    ///            Place(base: hir_id_s, projections: [], ....) -> {
751    ///                                                                capture_kind_expr: hir_id_L5,
752    ///                                                                path_expr_id: hir_id_L5,
753    ///                                                                capture_kind: ByValue
754    ///                                                            },
755    ///       ],
756    ///       hir_id_p -> [
757    ///            Place(base: hir_id_p, projections: [], ...) -> {
758    ///                                                               capture_kind_expr: hir_id_L2,
759    ///                                                               path_expr_id: hir_id_L4,
760    ///                                                               capture_kind: ByValue
761    ///                                                           },
762    ///       ],
763    /// }
764    /// ```
765    #[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(765u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["closure_def_id",
                                                    "capture_information", "closure_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_information)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            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:890",
                                    "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(890u32),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("For closure={0:?}, min_captures before sorting={1:?}",
                                                                closure_def_id, root_var_min_capture_list) as &dyn 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:951",
                                    "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(951u32),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("For closure={0:?}, min_captures after sorting={1:#?}",
                                                                closure_def_id, root_var_min_capture_list) as &dyn Value))])
                        });
                } else { ; }
            };
            typeck_results.closure_min_captures.insert(closure_def_id,
                root_var_min_capture_list);
        }
    }
}#[instrument(level = "debug", skip(self))]
766    fn compute_min_captures(
767        &self,
768        closure_def_id: LocalDefId,
769        capture_information: InferredCaptureInformation<'tcx>,
770        closure_span: Span,
771    ) {
772        if capture_information.is_empty() {
773            return;
774        }
775
776        let mut typeck_results = self.typeck_results.borrow_mut();
777
778        let mut root_var_min_capture_list =
779            typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
780
781        for (mut place, capture_info) in capture_information.into_iter() {
782            let var_hir_id = match place.base {
783                PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
784                base => bug!("Expected upvar, found={:?}", base),
785            };
786            let var_ident = self.tcx.hir_ident(var_hir_id);
787
788            let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
789                let mutability = self.determine_capture_mutability(&typeck_results, &place);
790                let min_cap_list =
791                    vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
792                root_var_min_capture_list.insert(var_hir_id, min_cap_list);
793                continue;
794            };
795
796            // Go through each entry in the current list of min_captures
797            // - if ancestor is found, update its capture kind to account for current place's
798            // capture information.
799            //
800            // - if descendant is found, remove it from the list, and update the current place's
801            // capture information to account for the descendant's capture kind.
802            //
803            // We can never be in a case where the list contains both an ancestor and a descendant
804            // Also there can only be ancestor but in case of descendants there might be
805            // multiple.
806
807            let mut descendant_found = false;
808            let mut updated_capture_info = capture_info;
809            min_cap_list.retain(|possible_descendant| {
810                match determine_place_ancestry_relation(&place, &possible_descendant.place) {
811                    // current place is ancestor of possible_descendant
812                    PlaceAncestryRelation::Ancestor => {
813                        descendant_found = true;
814
815                        let mut possible_descendant = possible_descendant.clone();
816                        let backup_path_expr_id = updated_capture_info.path_expr_id;
817
818                        // Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
819                        // possible change in capture mode.
820                        truncate_place_to_len_and_update_capture_kind(
821                            &mut possible_descendant.place,
822                            &mut possible_descendant.info.capture_kind,
823                            place.projections.len(),
824                        );
825
826                        updated_capture_info =
827                            determine_capture_info(updated_capture_info, possible_descendant.info);
828
829                        // we need to keep the ancestor's `path_expr_id`
830                        updated_capture_info.path_expr_id = backup_path_expr_id;
831                        false
832                    }
833
834                    _ => true,
835                }
836            });
837
838            let mut ancestor_found = false;
839            if !descendant_found {
840                for possible_ancestor in min_cap_list.iter_mut() {
841                    match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
842                        PlaceAncestryRelation::SamePlace => {
843                            ancestor_found = true;
844                            possible_ancestor.info = determine_capture_info(
845                                possible_ancestor.info,
846                                updated_capture_info,
847                            );
848
849                            // Only one related place will be in the list.
850                            break;
851                        }
852                        // current place is descendant of possible_ancestor
853                        PlaceAncestryRelation::Descendant => {
854                            ancestor_found = true;
855                            let backup_path_expr_id = possible_ancestor.info.path_expr_id;
856
857                            // Truncate the descendant (current place) to be same as the ancestor to handle any
858                            // possible change in capture mode.
859                            truncate_place_to_len_and_update_capture_kind(
860                                &mut place,
861                                &mut updated_capture_info.capture_kind,
862                                possible_ancestor.place.projections.len(),
863                            );
864
865                            possible_ancestor.info = determine_capture_info(
866                                possible_ancestor.info,
867                                updated_capture_info,
868                            );
869
870                            // we need to keep the ancestor's `path_expr_id`
871                            possible_ancestor.info.path_expr_id = backup_path_expr_id;
872
873                            // Only one related place will be in the list.
874                            break;
875                        }
876                        _ => {}
877                    }
878                }
879            }
880
881            // Only need to insert when we don't have an ancestor in the existing min capture list
882            if !ancestor_found {
883                let mutability = self.determine_capture_mutability(&typeck_results, &place);
884                let captured_place =
885                    ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
886                min_cap_list.push(captured_place);
887            }
888        }
889
890        debug!(
891            "For closure={:?}, min_captures before sorting={:?}",
892            closure_def_id, root_var_min_capture_list
893        );
894
895        // Now that we have the minimized list of captures, sort the captures by field id.
896        // This causes the closure to capture the upvars in the same order as the fields are
897        // declared which is also the drop order. Thus, in situations where we capture all the
898        // fields of some type, the observable drop order will remain the same as it previously
899        // was even though we're dropping each capture individually.
900        // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
901        // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
902        for (_, captures) in &mut root_var_min_capture_list {
903            captures.sort_by(|capture1, capture2| {
904                fn is_field<'a>(p: &&Projection<'a>) -> bool {
905                    match p.kind {
906                        ProjectionKind::Field(_, _) => true,
907                        ProjectionKind::Deref
908                        | ProjectionKind::OpaqueCast
909                        | ProjectionKind::UnwrapUnsafeBinder => false,
910                        p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
911                            bug!("ProjectionKind {:?} was unexpected", p)
912                        }
913                    }
914                }
915
916                // Need to sort only by Field projections, so filter away others.
917                // A previous implementation considered other projection types too
918                // but that caused ICE #118144
919                let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
920                let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
921
922                for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
923                    // We do not need to look at the `Projection.ty` fields here because at each
924                    // step of the iteration, the projections will either be the same and therefore
925                    // the types must be as well or the current projection will be different and
926                    // we will return the result of comparing the field indexes.
927                    match (p1.kind, p2.kind) {
928                        (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
929                            // Compare only if paths are different.
930                            // Otherwise continue to the next iteration
931                            if i1 != i2 {
932                                return i1.cmp(&i2);
933                            }
934                        }
935                        // Given the filter above, this arm should never be hit
936                        (l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
937                    }
938                }
939
940                self.dcx().span_delayed_bug(
941                    closure_span,
942                    format!(
943                        "two identical projections: ({:?}, {:?})",
944                        capture1.place.projections, capture2.place.projections
945                    ),
946                );
947                std::cmp::Ordering::Equal
948            });
949        }
950
951        debug!(
952            "For closure={:?}, min_captures after sorting={:#?}",
953            closure_def_id, root_var_min_capture_list
954        );
955        typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
956    }
957
958    /// Perform the migration analysis for RFC 2229, and emit lint
959    /// `disjoint_capture_drop_reorder` if needed.
960    fn perform_2229_migration_analysis(
961        &self,
962        closure_def_id: LocalDefId,
963        body_id: hir::BodyId,
964        capture_clause: hir::CaptureBy,
965        span: Span,
966    ) {
967        struct MigrationLint<'a, 'b, 'tcx> {
968            closure_def_id: LocalDefId,
969            this: &'a FnCtxt<'b, 'tcx>,
970            body_id: hir::BodyId,
971            need_migrations: Vec<NeededMigration>,
972            migration_message: String,
973        }
974
975        impl<'a, 'b, 'c, 'tcx> Diagnostic<'a, ()> for MigrationLint<'b, 'c, 'tcx> {
976            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
977                let Self { closure_def_id, this, body_id, need_migrations, migration_message } =
978                    self;
979                let mut lint = Diag::new(dcx, level, migration_message);
980
981                let (migration_string, migrated_variables_concat) =
982                    migration_suggestion_for_2229(this.tcx, &need_migrations);
983
984                let closure_hir_id = this.tcx.local_def_id_to_hir_id(closure_def_id);
985                let closure_head_span = this.tcx.def_span(closure_def_id);
986
987                for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
988                    // Labels all the usage of the captured variable and why they are responsible
989                    // for migration being needed
990                    for lint_note in diagnostics_info.iter() {
991                        match &lint_note.captures_info {
992                            UpvarMigrationInfo::CapturingPrecise {
993                                source_expr: Some(capture_expr_id),
994                                var_name: captured_name,
995                            } => {
996                                let cause_span = this.tcx.hir_span(*capture_expr_id);
997                                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 `{}`",
998                                    this.tcx.hir_name(*var_hir_id),
999                                    captured_name,
1000                                ));
1001                            }
1002                            UpvarMigrationInfo::CapturingNothing { use_span } => {
1003                                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",
1004                                    this.tcx.hir_name(*var_hir_id),
1005                                ));
1006                            }
1007
1008                            _ => {}
1009                        }
1010
1011                        // Add a label pointing to where a captured variable affected by drop order
1012                        // is dropped
1013                        if lint_note.reason.drop_order {
1014                            let drop_location_span = drop_location_span(this.tcx, closure_hir_id);
1015
1016                            match &lint_note.captures_info {
1017                                UpvarMigrationInfo::CapturingPrecise {
1018                                    var_name: captured_name,
1019                                    ..
1020                                } => {
1021                                    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",
1022                                        this.tcx.hir_name(*var_hir_id),
1023                                        captured_name,
1024                                    ));
1025                                }
1026                                UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1027                                    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",
1028                                        v = this.tcx.hir_name(*var_hir_id),
1029                                    ));
1030                                }
1031                            }
1032                        }
1033
1034                        // Add a label explaining why a closure no longer implements a trait
1035                        for &missing_trait in &lint_note.reason.auto_traits {
1036                            // not capturing something anymore cannot cause a trait to fail to be implemented:
1037                            match &lint_note.captures_info {
1038                                UpvarMigrationInfo::CapturingPrecise {
1039                                    var_name: captured_name,
1040                                    ..
1041                                } => {
1042                                    let var_name = this.tcx.hir_name(*var_hir_id);
1043                                    lint.span_label(
1044                                        closure_head_span,
1045                                        ::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!(
1046                                            "\
1047                                    in Rust 2018, this closure implements {missing_trait} \
1048                                    as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1049                                    this closure will no longer implement {missing_trait} \
1050                                    because `{var_name}` is not fully captured \
1051                                    and `{captured_name}` does not implement {missing_trait}"
1052                                        ),
1053                                    );
1054                                }
1055
1056                                // Cannot happen: if we don't capture a variable, we impl strictly more traits
1057                                UpvarMigrationInfo::CapturingNothing { use_span } => ::rustc_middle::util::bug::span_bug_fmt(*use_span,
    format_args!("missing trait from not capturing something"))span_bug!(
1058                                    *use_span,
1059                                    "missing trait from not capturing something"
1060                                ),
1061                            }
1062                        }
1063                    }
1064                }
1065
1066                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!(
1067                    "add a dummy let to cause {migrated_variables_concat} to be fully captured"
1068                );
1069
1070                let closure_span = this.tcx.hir_span_with_body(closure_hir_id);
1071                let mut closure_body_span = {
1072                    // If the body was entirely expanded from a macro
1073                    // invocation, i.e. the body is not contained inside the
1074                    // closure span, then we walk up the expansion until we
1075                    // find the span before the expansion.
1076                    let s = this.tcx.hir_span_with_body(body_id.hir_id);
1077                    s.find_ancestor_inside(closure_span).unwrap_or(s)
1078                };
1079
1080                if let Ok(mut s) = this.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1081                    if s.starts_with('$') {
1082                        // Looks like a macro fragment. Try to find the real block.
1083                        if let hir::Node::Expr(&hir::Expr {
1084                            kind: hir::ExprKind::Block(block, ..),
1085                            ..
1086                        }) = this.tcx.hir_node(body_id.hir_id)
1087                        {
1088                            // If the body is a block (with `{..}`), we use the span of that block.
1089                            // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1090                            // Since we know it's a block, we know we can insert the `let _ = ..` without
1091                            // breaking the macro syntax.
1092                            if let Ok(snippet) =
1093                                this.tcx.sess.source_map().span_to_snippet(block.span)
1094                            {
1095                                closure_body_span = block.span;
1096                                s = snippet;
1097                            }
1098                        }
1099                    }
1100
1101                    let mut lines = s.lines();
1102                    let line1 = lines.next().unwrap_or_default();
1103
1104                    if line1.trim_end() == "{" {
1105                        // This is a multi-line closure with just a `{` on the first line,
1106                        // so we put the `let` on its own line.
1107                        // We take the indentation from the next non-empty line.
1108                        let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1109                        let indent =
1110                            line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1111                        lint.span_suggestion(
1112                            closure_body_span
1113                                .with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len()))
1114                                .shrink_to_lo(),
1115                            diagnostic_msg,
1116                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}{1};", indent,
                migration_string))
    })format!("\n{indent}{migration_string};"),
1117                            Applicability::MachineApplicable,
1118                        );
1119                    } else if line1.starts_with('{') {
1120                        // This is a closure with its body wrapped in
1121                        // braces, but with more than just the opening
1122                        // brace on the first line. We put the `let`
1123                        // directly after the `{`.
1124                        lint.span_suggestion(
1125                            closure_body_span
1126                                .with_lo(closure_body_span.lo() + BytePos(1))
1127                                .shrink_to_lo(),
1128                            diagnostic_msg,
1129                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0};", migration_string))
    })format!(" {migration_string};"),
1130                            Applicability::MachineApplicable,
1131                        );
1132                    } else {
1133                        // This is a closure without braces around the body.
1134                        // We add braces to add the `let` before the body.
1135                        lint.multipart_suggestion(
1136                            diagnostic_msg,
1137                            ::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![
1138                                (
1139                                    closure_body_span.shrink_to_lo(),
1140                                    format!("{{ {migration_string}; "),
1141                                ),
1142                                (closure_body_span.shrink_to_hi(), " }".to_string()),
1143                            ],
1144                            Applicability::MachineApplicable,
1145                        );
1146                    }
1147                } else {
1148                    lint.span_suggestion(
1149                        closure_span,
1150                        diagnostic_msg,
1151                        migration_string,
1152                        Applicability::HasPlaceholders,
1153                    );
1154                }
1155                lint
1156            }
1157        }
1158
1159        let (need_migrations, reasons) = self.compute_2229_migrations(
1160            closure_def_id,
1161            span,
1162            capture_clause,
1163            self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
1164        );
1165
1166        if !need_migrations.is_empty() {
1167            self.tcx.emit_node_span_lint(
1168                lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
1169                self.tcx.local_def_id_to_hir_id(closure_def_id),
1170                self.tcx.def_span(closure_def_id),
1171                MigrationLint {
1172                    this: self,
1173                    migration_message: reasons.migration_message(),
1174                    closure_def_id,
1175                    body_id,
1176                    need_migrations,
1177                },
1178            );
1179        }
1180    }
1181    fn normalize_capture_place(&self, span: Span, place: Place<'tcx>) -> Place<'tcx> {
1182        let mut place = self.resolve_vars_if_possible(place);
1183
1184        // In the new solver, types in HIR `Place`s can contain unnormalized aliases,
1185        // which can ICE later (e.g. when projecting fields for diagnostics).
1186        if self.next_trait_solver() {
1187            let cause = self.misc(span);
1188            let at = self.at(&cause, self.param_env);
1189            match solve::deeply_normalize_with_skipped_universes_and_ambiguous_coroutine_goals(
1190                at,
1191                place.clone(),
1192                ::alloc::vec::Vec::new()vec![],
1193            ) {
1194                Ok((normalized, goals)) => {
1195                    if !goals.is_empty() {
1196                        let mut typeck_results = self.typeck_results.borrow_mut();
1197                        typeck_results.coroutine_stalled_predicates.extend(
1198                            goals
1199                                .into_iter()
1200                                // FIXME: throwing away the param-env :(
1201                                .map(|goal| (goal.predicate, self.misc(span))),
1202                        );
1203                    }
1204                    normalized
1205                }
1206                Err(errors) => {
1207                    let guar = self.infcx.err_ctxt().report_fulfillment_errors(errors);
1208                    place.base_ty = Ty::new_error(self.tcx, guar);
1209                    for proj in &mut place.projections {
1210                        proj.ty = Ty::new_error(self.tcx, guar);
1211                    }
1212                    place
1213                }
1214            }
1215        } else {
1216            // For the old solver we can rely on `normalize` to eagerly normalize aliases.
1217            self.normalize(span, place)
1218        }
1219    }
1220
1221    /// Combines all the reasons for 2229 migrations
1222    fn compute_2229_migrations_reasons(
1223        &self,
1224        auto_trait_reasons: UnordSet<&'static str>,
1225        drop_order: bool,
1226    ) -> MigrationWarningReason {
1227        MigrationWarningReason {
1228            auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1229            drop_order,
1230        }
1231    }
1232
1233    /// Figures out the list of root variables (and their types) that aren't completely
1234    /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1235    /// differ between the root variable and the captured paths.
1236    ///
1237    /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1238    /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1239    fn compute_2229_migrations_for_trait(
1240        &self,
1241        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1242        var_hir_id: HirId,
1243        closure_clause: hir::CaptureBy,
1244    ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1245        let auto_traits_def_id = [
1246            self.tcx.lang_items().clone_trait(),
1247            self.tcx.lang_items().sync_trait(),
1248            self.tcx.get_diagnostic_item(sym::Send),
1249            self.tcx.lang_items().unpin_trait(),
1250            self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1251            self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1252        ];
1253        const AUTO_TRAITS: [&str; 6] =
1254            ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
1255
1256        let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
1257
1258        let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
1259
1260        let ty = match closure_clause {
1261            hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1262            hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1263                // For non move closure the capture kind is the max capture kind of all captures
1264                // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1265                let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1266                for capture in root_var_min_capture_list.iter() {
1267                    max_capture_info = determine_capture_info(max_capture_info, capture.info);
1268                }
1269
1270                apply_capture_kind_on_capture_ty(
1271                    self.tcx,
1272                    ty,
1273                    max_capture_info.capture_kind,
1274                    self.tcx.lifetimes.re_erased,
1275                )
1276            }
1277        };
1278
1279        let mut obligations_should_hold = Vec::new();
1280        // Checks if a root variable implements any of the auto traits
1281        for check_trait in auto_traits_def_id.iter() {
1282            obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1283                self.infcx
1284                    .type_implements_trait(check_trait, [ty], self.param_env)
1285                    .must_apply_modulo_regions()
1286            }));
1287        }
1288
1289        let mut problematic_captures = FxIndexMap::default();
1290        // Check whether captured fields also implement the trait
1291        for capture in root_var_min_capture_list.iter() {
1292            let ty = apply_capture_kind_on_capture_ty(
1293                self.tcx,
1294                capture.place.ty(),
1295                capture.info.capture_kind,
1296                self.tcx.lifetimes.re_erased,
1297            );
1298
1299            // Checks if a capture implements any of the auto traits
1300            let mut obligations_holds_for_capture = Vec::new();
1301            for check_trait in auto_traits_def_id.iter() {
1302                obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1303                    self.infcx
1304                        .type_implements_trait(check_trait, [ty], self.param_env)
1305                        .must_apply_modulo_regions()
1306                }));
1307            }
1308
1309            let mut capture_problems = UnordSet::default();
1310
1311            // Checks if for any of the auto traits, one or more trait is implemented
1312            // by the root variable but not by the capture
1313            for (idx, _) in obligations_should_hold.iter().enumerate() {
1314                if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1315                    capture_problems.insert(AUTO_TRAITS[idx]);
1316                }
1317            }
1318
1319            if !capture_problems.is_empty() {
1320                problematic_captures.insert(
1321                    UpvarMigrationInfo::CapturingPrecise {
1322                        source_expr: capture.info.path_expr_id,
1323                        var_name: capture.to_string(self.tcx),
1324                    },
1325                    capture_problems,
1326                );
1327            }
1328        }
1329        if !problematic_captures.is_empty() {
1330            return Some(problematic_captures);
1331        }
1332        None
1333    }
1334
1335    /// Figures out the list of root variables (and their types) that aren't completely
1336    /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1337    /// some path starting at that root variable **might** be affected.
1338    ///
1339    /// The output list would include a root variable if:
1340    /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1341    ///   enabled, **and**
1342    /// - It wasn't completely captured by the closure, **and**
1343    /// - One of the paths starting at this root variable, that is not captured needs Drop.
1344    ///
1345    /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1346    /// are no significant drops than None is returned
1347    #[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(1347u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["closure_def_id",
                                                    "closure_span", "min_captures", "closure_clause",
                                                    "var_hir_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_captures)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_clause)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_hir_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    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: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};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("does not have significant drop")
                                                            as &dyn 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:1376",
                                            "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(1376u32),
                                            ::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};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("no path starting from it is used")
                                                                as &dyn 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:1394",
                                    "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(1394u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["root_var_min_capture_list"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&root_var_min_capture_list)
                                                        as &dyn 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:1413",
                                    "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(1413u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["projections_list"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&projections_list)
                                                        as &dyn 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:1414",
                                    "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(1414u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["diagnostics_info"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&diagnostics_info)
                                                        as &dyn 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:1417",
                                    "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(1417u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["is_moved"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&is_moved)
                                                        as &dyn 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:1421",
                                    "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(1421u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["is_not_completely_captured"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&is_not_completely_captured)
                                                        as &dyn 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))]
1348    fn compute_2229_migrations_for_drop(
1349        &self,
1350        closure_def_id: LocalDefId,
1351        closure_span: Span,
1352        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1353        closure_clause: hir::CaptureBy,
1354        var_hir_id: HirId,
1355    ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1356        let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
1357
1358        // FIXME(#132279): Using `non_body_analysis` here feels wrong.
1359        if !ty.has_significant_drop(
1360            self.tcx,
1361            ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1362        ) {
1363            debug!("does not have significant drop");
1364            return None;
1365        }
1366
1367        let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1368            // The upvar is mentioned within the closure but no path starting from it is
1369            // used. This occurs when you have (e.g.)
1370            //
1371            // ```
1372            // let x = move || {
1373            //     let _ = y;
1374            // });
1375            // ```
1376            debug!("no path starting from it is used");
1377
1378            match closure_clause {
1379                // Only migrate if closure is a move closure
1380                hir::CaptureBy::Value { .. } => {
1381                    let mut diagnostics_info = FxIndexSet::default();
1382                    let upvars =
1383                        self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1384                    let upvar = upvars[&var_hir_id];
1385                    diagnostics_info
1386                        .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1387                    return Some(diagnostics_info);
1388                }
1389                hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1390            }
1391
1392            return None;
1393        };
1394        debug!(?root_var_min_capture_list);
1395
1396        let mut projections_list = Vec::new();
1397        let mut diagnostics_info = FxIndexSet::default();
1398
1399        for captured_place in root_var_min_capture_list.iter() {
1400            match captured_place.info.capture_kind {
1401                // Only care about captures that are moved into the closure
1402                ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1403                    projections_list.push(captured_place.place.projections.as_slice());
1404                    diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1405                        source_expr: captured_place.info.path_expr_id,
1406                        var_name: captured_place.to_string(self.tcx),
1407                    });
1408                }
1409                ty::UpvarCapture::ByRef(..) => {}
1410            }
1411        }
1412
1413        debug!(?projections_list);
1414        debug!(?diagnostics_info);
1415
1416        let is_moved = !projections_list.is_empty();
1417        debug!(?is_moved);
1418
1419        let is_not_completely_captured =
1420            root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1421        debug!(?is_not_completely_captured);
1422
1423        if is_moved
1424            && is_not_completely_captured
1425            && self.has_significant_drop_outside_of_captures(
1426                closure_def_id,
1427                closure_span,
1428                ty,
1429                projections_list,
1430            )
1431        {
1432            return Some(diagnostics_info);
1433        }
1434
1435        None
1436    }
1437
1438    /// Figures out the list of root variables (and their types) that aren't completely
1439    /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1440    /// order of some path starting at that root variable **might** be affected or auto-traits
1441    /// differ between the root variable and the captured paths.
1442    ///
1443    /// The output list would include a root variable if:
1444    /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1445    ///   enabled, **and**
1446    /// - It wasn't completely captured by the closure, **and**
1447    /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1448    /// - One of the paths captured does not implement all the auto-traits its root variable
1449    ///   implements.
1450    ///
1451    /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1452    /// containing the reason why root variables whose HirId is contained in the vector should
1453    /// be captured
1454    #[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(1454u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["closure_def_id",
                                                    "closure_span", "closure_clause", "min_captures"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_clause)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_captures)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    (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))]
1455    fn compute_2229_migrations(
1456        &self,
1457        closure_def_id: LocalDefId,
1458        closure_span: Span,
1459        closure_clause: hir::CaptureBy,
1460        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1461    ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1462        let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1463            return (Vec::new(), MigrationWarningReason::default());
1464        };
1465
1466        let mut need_migrations = Vec::new();
1467        let mut auto_trait_migration_reasons = UnordSet::default();
1468        let mut drop_migration_needed = false;
1469
1470        // Perform auto-trait analysis
1471        for (&var_hir_id, _) in upvars.iter() {
1472            let mut diagnostics_info = Vec::new();
1473
1474            let auto_trait_diagnostic = self
1475                .compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1476                .unwrap_or_default();
1477
1478            let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1479                .compute_2229_migrations_for_drop(
1480                    closure_def_id,
1481                    closure_span,
1482                    min_captures,
1483                    closure_clause,
1484                    var_hir_id,
1485                ) {
1486                drop_migration_needed = true;
1487                diagnostics_info
1488            } else {
1489                FxIndexSet::default()
1490            };
1491
1492            // Combine all the captures responsible for needing migrations into one IndexSet
1493            let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1494            for key in auto_trait_diagnostic.keys() {
1495                capture_diagnostic.insert(key.clone());
1496            }
1497
1498            let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1499            capture_diagnostic.sort_by_cached_key(|info| match info {
1500                UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1501                    (0, Some(var_name.clone()))
1502                }
1503                UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1504            });
1505            for captures_info in capture_diagnostic {
1506                // Get the auto trait reasons of why migration is needed because of that capture, if there are any
1507                let capture_trait_reasons =
1508                    if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1509                        reasons.clone()
1510                    } else {
1511                        UnordSet::default()
1512                    };
1513
1514                // Check if migration is needed because of drop reorder as a result of that capture
1515                let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
1516
1517                // Combine all the reasons of why the root variable should be captured as a result of
1518                // auto trait implementation issues
1519                auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
1520
1521                diagnostics_info.push(MigrationLintNote {
1522                    captures_info,
1523                    reason: self.compute_2229_migrations_reasons(
1524                        capture_trait_reasons,
1525                        capture_drop_reorder_reason,
1526                    ),
1527                });
1528            }
1529
1530            if !diagnostics_info.is_empty() {
1531                need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1532            }
1533        }
1534        (
1535            need_migrations,
1536            self.compute_2229_migrations_reasons(
1537                auto_trait_migration_reasons,
1538                drop_migration_needed,
1539            ),
1540        )
1541    }
1542
1543    /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1544    /// of a root variable and a list of captured paths starting at this root variable (expressed
1545    /// using list of `Projection` slices), it returns true if there is a path that is not
1546    /// captured starting at this root variable that implements Drop.
1547    ///
1548    /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1549    /// path say P and then list of projection slices which represent the different captures moved
1550    /// into the closure starting off of P.
1551    ///
1552    /// This will make more sense with an example:
1553    ///
1554    /// ```rust,edition2021
1555    ///
1556    /// struct FancyInteger(i32); // This implements Drop
1557    ///
1558    /// struct Point { x: FancyInteger, y: FancyInteger }
1559    /// struct Color;
1560    ///
1561    /// struct Wrapper { p: Point, c: Color }
1562    ///
1563    /// fn f(w: Wrapper) {
1564    ///   let c = || {
1565    ///       // Closure captures w.p.x and w.c by move.
1566    ///   };
1567    ///
1568    ///   c();
1569    /// }
1570    /// ```
1571    ///
1572    /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1573    /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1574    /// therefore Drop ordering would change and we want this function to return true.
1575    ///
1576    /// Call stack to figure out if we need to migrate for `w` would look as follows:
1577    ///
1578    /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1579    /// `w[c]`.
1580    /// Notation:
1581    /// - Ty(place): Type of place
1582    /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1583    ///   respectively.
1584    /// ```ignore (illustrative)
1585    ///                  (Ty(w), [ &[p, x], &[c] ])
1586    /// //                              |
1587    /// //                 ----------------------------
1588    /// //                 |                          |
1589    /// //                 v                          v
1590    ///        (Ty(w.p), [ &[x] ])          (Ty(w.c), [ &[] ]) // I(1)
1591    /// //                 |                          |
1592    /// //                 v                          v
1593    ///        (Ty(w.p), [ &[x] ])                 false
1594    /// //                 |
1595    /// //                 |
1596    /// //       -------------------------------
1597    /// //       |                             |
1598    /// //       v                             v
1599    ///     (Ty((w.p).x), [ &[] ])     (Ty((w.p).y), []) // IMP 2
1600    /// //       |                             |
1601    /// //       v                             v
1602    ///        false              NeedsSignificantDrop(Ty(w.p.y))
1603    /// //                                     |
1604    /// //                                     v
1605    ///                                      true
1606    /// ```
1607    ///
1608    /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1609    ///                             This implies that the `w.c` is completely captured by the closure.
1610    ///                             Since drop for this path will be called when the closure is
1611    ///                             dropped we don't need to migrate for it.
1612    ///
1613    /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1614    ///                             path wasn't captured by the closure. Also note that even
1615    ///                             though we didn't capture this path, the function visits it,
1616    ///                             which is kind of the point of this function. We then return
1617    ///                             if the type of `w.p.y` implements Drop, which in this case is
1618    ///                             true.
1619    ///
1620    /// Consider another example:
1621    ///
1622    /// ```ignore (pseudo-rust)
1623    /// struct X;
1624    /// impl Drop for X {}
1625    ///
1626    /// struct Y(X);
1627    /// impl Drop for Y {}
1628    ///
1629    /// fn foo() {
1630    ///     let y = Y(X);
1631    ///     let c = || move(y.0);
1632    /// }
1633    /// ```
1634    ///
1635    /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1636    /// return true, because even though all paths starting at `y` are captured, `y` itself
1637    /// implements Drop which will be affected since `y` isn't completely captured.
1638    fn has_significant_drop_outside_of_captures(
1639        &self,
1640        closure_def_id: LocalDefId,
1641        closure_span: Span,
1642        base_path_ty: Ty<'tcx>,
1643        captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1644    ) -> bool {
1645        // FIXME(#132279): Using `non_body_analysis` here feels wrong.
1646        let needs_drop = |ty: Ty<'tcx>| {
1647            ty.has_significant_drop(
1648                self.tcx,
1649                ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1650            )
1651        };
1652
1653        let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1654            let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, closure_span);
1655            self.infcx
1656                .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1657                .must_apply_modulo_regions()
1658        };
1659
1660        let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
1661
1662        // If there is a case where no projection is applied on top of current place
1663        // then there must be exactly one capture corresponding to such a case. Note that this
1664        // represents the case of the path being completely captured by the variable.
1665        //
1666        // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1667        //     capture `a.b.c`, because that violates min capture.
1668        let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
1669
1670        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));
1671
1672        if is_completely_captured {
1673            // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1674            // when the closure is dropped.
1675            return false;
1676        }
1677
1678        if captured_by_move_projs.is_empty() {
1679            return needs_drop(base_path_ty);
1680        }
1681
1682        if is_drop_defined_for_ty {
1683            // If drop is implemented for this type then we need it to be fully captured,
1684            // and we know it is not completely captured because of the previous checks.
1685
1686            // Note that this is a bug in the user code that will be reported by the
1687            // borrow checker, since we can't move out of drop types.
1688
1689            // The bug exists in the user's code pre-migration, and we don't migrate here.
1690            return false;
1691        }
1692
1693        match base_path_ty.kind() {
1694            // Observations:
1695            // - `captured_by_move_projs` is not empty. Therefore we can call
1696            //   `captured_by_move_projs.first().unwrap()` safely.
1697            // - All entries in `captured_by_move_projs` have at least one projection.
1698            //   Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
1699
1700            // We don't capture derefs in case of move captures, which would have be applied to
1701            // access any further paths.
1702            ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1703            ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1704            ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1705
1706            ty::Adt(def, args) => {
1707                // Multi-variant enums are captured in entirety,
1708                // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1709                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);
1710
1711                // Only Field projections can be applied to a non-box Adt.
1712                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!(
1713                    captured_by_move_projs.iter().all(|projs| matches!(
1714                        projs.first().unwrap().kind,
1715                        ProjectionKind::Field(..)
1716                    ))
1717                );
1718                def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1719                    |(i, field)| {
1720                        let paths_using_field = captured_by_move_projs
1721                            .iter()
1722                            .filter_map(|projs| {
1723                                if let ProjectionKind::Field(field_idx, _) =
1724                                    projs.first().unwrap().kind
1725                                {
1726                                    if field_idx == i { Some(&projs[1..]) } else { None }
1727                                } else {
1728                                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1729                                }
1730                            })
1731                            .collect();
1732
1733                        let after_field_ty = field.ty(self.tcx, args);
1734                        self.has_significant_drop_outside_of_captures(
1735                            closure_def_id,
1736                            closure_span,
1737                            after_field_ty,
1738                            paths_using_field,
1739                        )
1740                    },
1741                )
1742            }
1743
1744            ty::Tuple(fields) => {
1745                // Only Field projections can be applied to a tuple.
1746                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!(
1747                    captured_by_move_projs.iter().all(|projs| matches!(
1748                        projs.first().unwrap().kind,
1749                        ProjectionKind::Field(..)
1750                    ))
1751                );
1752
1753                fields.iter().enumerate().any(|(i, element_ty)| {
1754                    let paths_using_field = captured_by_move_projs
1755                        .iter()
1756                        .filter_map(|projs| {
1757                            if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1758                            {
1759                                if field_idx.index() == i { Some(&projs[1..]) } else { None }
1760                            } else {
1761                                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1762                            }
1763                        })
1764                        .collect();
1765
1766                    self.has_significant_drop_outside_of_captures(
1767                        closure_def_id,
1768                        closure_span,
1769                        element_ty,
1770                        paths_using_field,
1771                    )
1772                })
1773            }
1774
1775            // Anything else would be completely captured and therefore handled already.
1776            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1777        }
1778    }
1779
1780    fn init_capture_kind_for_place(
1781        &self,
1782        place: &Place<'tcx>,
1783        capture_clause: hir::CaptureBy,
1784    ) -> ty::UpvarCapture {
1785        match capture_clause {
1786            // In case of a move closure if the data is accessed through a reference we
1787            // want to capture by ref to allow precise capture using reborrows.
1788            //
1789            // If the data will be moved out of this place, then the place will be truncated
1790            // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1791            //
1792            // For example:
1793            //
1794            // struct Buffer<'a> {
1795            //     x: &'a String,
1796            //     y: Vec<u8>,
1797            // }
1798            //
1799            // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1800            //     let c = move || b.x;
1801            //     drop(b);
1802            //     c
1803            // }
1804            //
1805            // Even though the closure is declared as move, when we are capturing borrowed data (in
1806            // this case, *b.x) we prefer to capture by reference.
1807            // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1808            // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1809            // before, which is also an error.
1810            hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1811                ty::UpvarCapture::ByValue
1812            }
1813            hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1814                ty::UpvarCapture::ByUse
1815            }
1816            hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1817                ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1818            }
1819        }
1820    }
1821
1822    fn place_for_root_variable(
1823        &self,
1824        closure_def_id: LocalDefId,
1825        var_hir_id: HirId,
1826    ) -> Place<'tcx> {
1827        let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
1828
1829        let place = Place {
1830            base_ty: self.node_ty(var_hir_id),
1831            base: PlaceBase::Upvar(upvar_id),
1832            projections: Default::default(),
1833        };
1834
1835        // Normalize eagerly when inserting into `capture_information`, so all downstream
1836        // capture analysis can assume a normalized `Place`.
1837        self.normalize_capture_place(self.tcx.hir_span(var_hir_id), place)
1838    }
1839
1840    fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1841        self.has_rustc_attrs && {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in self.tcx.get_all_attrs(closure_def_id) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcCaptureAnalysis) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(self.tcx, closure_def_id, RustcCaptureAnalysis)
1842    }
1843
1844    fn log_capture_analysis_first_pass(
1845        &self,
1846        closure_def_id: LocalDefId,
1847        capture_information: &InferredCaptureInformation<'tcx>,
1848        closure_span: Span,
1849    ) {
1850        if self.should_log_capture_analysis(closure_def_id) {
1851            let mut diag =
1852                self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1853            for (place, capture_info) in capture_information {
1854                let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1855                let output_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
    })format!("Capturing {capture_str}");
1856
1857                let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1858                diag.span_note(span, output_str);
1859            }
1860            diag.emit();
1861        }
1862    }
1863
1864    fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1865        if self.should_log_capture_analysis(closure_def_id) {
1866            if let Some(min_captures) =
1867                self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1868            {
1869                let mut diag =
1870                    self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
1871
1872                for (_, min_captures_for_var) in min_captures {
1873                    for capture in min_captures_for_var {
1874                        let place = &capture.place;
1875                        let capture_info = &capture.info;
1876
1877                        let capture_str =
1878                            construct_capture_info_string(self.tcx, place, capture_info);
1879                        let output_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
    })format!("Min Capture {capture_str}");
1880
1881                        if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1882                            let path_span = capture_info
1883                                .path_expr_id
1884                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1885                            let capture_kind_span = capture_info
1886                                .capture_kind_expr_id
1887                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1888
1889                            let mut multi_span: MultiSpan =
1890                                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]);
1891
1892                            let capture_kind_label =
1893                                construct_capture_kind_reason_string(self.tcx, place, capture_info);
1894                            let path_label = construct_path_string(self.tcx, place);
1895
1896                            multi_span.push_span_label(path_span, path_label);
1897                            multi_span.push_span_label(capture_kind_span, capture_kind_label);
1898
1899                            diag.span_note(multi_span, output_str);
1900                        } else {
1901                            let span = capture_info
1902                                .path_expr_id
1903                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1904
1905                            diag.span_note(span, output_str);
1906                        };
1907                    }
1908                }
1909                diag.emit();
1910            }
1911        }
1912    }
1913
1914    /// A captured place is mutable if
1915    /// 1. Projections don't include a Deref of an immut-borrow, **and**
1916    /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1917    fn determine_capture_mutability(
1918        &self,
1919        typeck_results: &'a TypeckResults<'tcx>,
1920        place: &Place<'tcx>,
1921    ) -> hir::Mutability {
1922        let var_hir_id = match place.base {
1923            PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1924            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1925        };
1926
1927        let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1928
1929        let mut is_mutbl = bm.1;
1930
1931        for pointer_ty in place.deref_tys() {
1932            match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
1933                // We don't capture derefs of raw ptrs
1934                ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1935
1936                // Dereferencing a mut-ref allows us to mut the Place if we don't deref
1937                // an immut-ref after on top of this.
1938                ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1939
1940                // The place isn't mutable once we dereference an immutable reference.
1941                ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1942
1943                // Dereferencing a box doesn't change mutability
1944                ty::Adt(def, ..) if def.is_box() => {}
1945
1946                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!(
1947                    self.tcx.hir_span(var_hir_id),
1948                    "deref of unexpected pointer type {:?}",
1949                    unexpected_ty
1950                ),
1951            }
1952        }
1953
1954        is_mutbl
1955    }
1956}
1957
1958/// Determines whether a child capture that is derived from a parent capture
1959/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1960///
1961/// There are two cases when this needs to happen:
1962///
1963/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1964/// that is the case by checking if the parent capture is by move, EXCEPT if we
1965/// apply a deref projection of an immutable reference, reborrows of immutable
1966/// references which aren't restricted to the LUB of the lifetimes of the deref
1967/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1968///
1969/// ```rust
1970/// let x = &1i32; // Let's call this lifetime `'1`.
1971/// let c = async move || {
1972///     println!("{:?}", *x);
1973///     // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1974///     // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1975/// };
1976/// ```
1977///
1978/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1979/// mutable borrow cannot live for longer than either the parent *or* the borrow
1980/// that we have on the original upvar. Therefore we always need to borrow the
1981/// child capture with the lifetime of the parent coroutine-closure's env.
1982///
1983/// ```rust
1984/// let mut x = 1i32;
1985/// let c = async || {
1986///     x = 1;
1987///     // The parent borrows `x` for some `&'1 mut i32`.
1988///     // However, when we call `c()`, we implicitly autoref for the signature of
1989///     // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1990///     // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1991///     // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1992/// };
1993/// ```
1994///
1995/// If either of these cases apply, then we should capture the borrow with the
1996/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1997/// not correct, then the program is not unsound, since we still borrowck and validate
1998/// the choices made from this function -- the only side-effect is that the user
1999/// may receive unnecessary borrowck errors.
2000fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
2001    parent_capture: &ty::CapturedPlace<'tcx>,
2002    child_capture: &ty::CapturedPlace<'tcx>,
2003) -> bool {
2004    // (1.)
2005    (!parent_capture.is_by_ref()
2006        // This is just inlined `place.deref_tys()` but truncated to just
2007        // the child projections. Namely, look for a `&T` deref, since we
2008        // can always extend `&'short mut &'long T` to `&'long T`.
2009        && !child_capture
2010            .place
2011            .projections
2012            .iter()
2013            .enumerate()
2014            .skip(parent_capture.place.projections.len())
2015            .any(|(idx, proj)| {
2016                #[allow(non_exhaustive_omitted_patterns)] match proj.kind {
    ProjectionKind::Deref => true,
    _ => false,
}matches!(proj.kind, ProjectionKind::Deref)
2017                    && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
    {
    ty::Ref(.., ty::Mutability::Not) => true,
    _ => false,
}matches!(
2018                        child_capture.place.ty_before_projection(idx).kind(),
2019                        ty::Ref(.., ty::Mutability::Not)
2020                    )
2021            }))
2022        // (2.)
2023        || #[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))
2024}
2025
2026/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
2027/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
2028fn restrict_repr_packed_field_ref_capture<'tcx>(
2029    mut place: Place<'tcx>,
2030    mut curr_borrow_kind: ty::UpvarCapture,
2031) -> (Place<'tcx>, ty::UpvarCapture) {
2032    let pos = place.projections.iter().enumerate().position(|(i, p)| {
2033        let ty = place.ty_before_projection(i);
2034
2035        // Return true for fields of packed structs.
2036        match p.kind {
2037            ProjectionKind::Field(..) => match ty.kind() {
2038                ty::Adt(def, _) if def.repr().packed() => {
2039                    // We stop here regardless of field alignment. Field alignment can change as
2040                    // types change, including the types of private fields in other crates, and that
2041                    // shouldn't affect how we compute our captures.
2042                    true
2043                }
2044
2045                _ => false,
2046            },
2047            _ => false,
2048        }
2049    });
2050
2051    if let Some(pos) = pos {
2052        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
2053    }
2054
2055    (place, curr_borrow_kind)
2056}
2057
2058/// Returns a Ty that applies the specified capture kind on the provided capture Ty
2059fn apply_capture_kind_on_capture_ty<'tcx>(
2060    tcx: TyCtxt<'tcx>,
2061    ty: Ty<'tcx>,
2062    capture_kind: UpvarCapture,
2063    region: ty::Region<'tcx>,
2064) -> Ty<'tcx> {
2065    match capture_kind {
2066        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
2067        ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
2068    }
2069}
2070
2071/// Returns the Span of where the value with the provided HirId would be dropped
2072fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
2073    let owner_id = tcx.hir_get_enclosing_scope(hir_id).unwrap();
2074
2075    let owner_node = tcx.hir_node(owner_id);
2076    let owner_span = match owner_node {
2077        hir::Node::Item(item) => match item.kind {
2078            hir::ItemKind::Fn { body: owner_id, .. } => tcx.hir_span(owner_id.hir_id),
2079            _ => {
2080                ::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);
2081            }
2082        },
2083        hir::Node::Block(block) => tcx.hir_span(block.hir_id),
2084        hir::Node::TraitItem(item) => tcx.hir_span(item.hir_id()),
2085        hir::Node::ImplItem(item) => tcx.hir_span(item.hir_id()),
2086        _ => {
2087            ::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);
2088        }
2089    };
2090    tcx.sess.source_map().end_point(owner_span)
2091}
2092
2093struct InferBorrowKind<'fcx, 'a, 'tcx> {
2094    fcx: &'fcx FnCtxt<'a, 'tcx>,
2095    // The def-id of the closure whose kind and upvar accesses are being inferred.
2096    closure_def_id: LocalDefId,
2097
2098    /// For each Place that is captured by the closure, we track the minimal kind of
2099    /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2100    ///
2101    /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2102    /// s.str2 via a MutableBorrow
2103    ///
2104    /// ```rust,no_run
2105    /// struct SomeStruct { str1: String, str2: String };
2106    ///
2107    /// // Assume that the HirId for the variable definition is `V1`
2108    /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2109    ///
2110    /// let fix_s = |new_s2| {
2111    ///     // Assume that the HirId for the expression `s.str1` is `E1`
2112    ///     println!("Updating SomeStruct with str1={0}", s.str1);
2113    ///     // Assume that the HirId for the expression `*s.str2` is `E2`
2114    ///     s.str2 = new_s2;
2115    /// };
2116    /// ```
2117    ///
2118    /// For closure `fix_s`, (at a high level) the map contains
2119    ///
2120    /// ```ignore (illustrative)
2121    /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2122    /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2123    /// ```
2124    capture_information: InferredCaptureInformation<'tcx>,
2125    fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2126}
2127
2128impl<'fcx, 'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'fcx, 'a, 'tcx> {
2129    #[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(2129u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["place_with_id",
                                                    "cause", "diag_expr_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let 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_capture_place(span,
                    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")]
2130    fn fake_read(
2131        &mut self,
2132        place_with_id: &PlaceWithHirId<'tcx>,
2133        cause: FakeReadCause,
2134        diag_expr_id: HirId,
2135    ) {
2136        let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
2137
2138        // We need to restrict Fake Read precision to avoid fake reading unsafe code,
2139        // such as deref of a raw pointer.
2140        let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2141
2142        let span = self.fcx.tcx.hir_span(diag_expr_id);
2143        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2144
2145        let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
2146
2147        let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2148        self.fake_reads.push((place, cause, diag_expr_id));
2149    }
2150
2151    #[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(2151u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["place_with_id",
                                                    "diag_expr_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let 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_capture_place(span,
                    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")]
2152    fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2153        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2154        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2155
2156        let span = self.fcx.tcx.hir_span(diag_expr_id);
2157        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2158
2159        self.capture_information.push((
2160            place,
2161            ty::CaptureInfo {
2162                capture_kind_expr_id: Some(diag_expr_id),
2163                path_expr_id: Some(diag_expr_id),
2164                capture_kind: ty::UpvarCapture::ByValue,
2165            },
2166        ));
2167    }
2168
2169    #[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(2169u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["place_with_id",
                                                    "diag_expr_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let 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_capture_place(span,
                    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")]
2170    fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2171        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2172        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2173
2174        let span = self.fcx.tcx.hir_span(diag_expr_id);
2175        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2176
2177        self.capture_information.push((
2178            place,
2179            ty::CaptureInfo {
2180                capture_kind_expr_id: Some(diag_expr_id),
2181                path_expr_id: Some(diag_expr_id),
2182                capture_kind: ty::UpvarCapture::ByUse,
2183            },
2184        ));
2185    }
2186
2187    #[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(2187u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["place_with_id",
                                                    "diag_expr_id", "bk"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bk)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let 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_capture_place(span,
                    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")]
2188    fn borrow(
2189        &mut self,
2190        place_with_id: &PlaceWithHirId<'tcx>,
2191        diag_expr_id: HirId,
2192        bk: ty::BorrowKind,
2193    ) {
2194        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2195        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2196
2197        // The region here will get discarded/ignored
2198        let capture_kind = ty::UpvarCapture::ByRef(bk);
2199
2200        let span = self.fcx.tcx.hir_span(diag_expr_id);
2201        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2202
2203        // We only want repr packed restriction to be applied to reading references into a packed
2204        // struct, and not when the data is being moved. Therefore we call this method here instead
2205        // of in `restrict_capture_precision`.
2206        let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(place, capture_kind);
2207
2208        // Raw pointers don't inherit mutability
2209        if place.deref_tys().any(Ty::is_raw_ptr) {
2210            capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2211        }
2212
2213        self.capture_information.push((
2214            place,
2215            ty::CaptureInfo {
2216                capture_kind_expr_id: Some(diag_expr_id),
2217                path_expr_id: Some(diag_expr_id),
2218                capture_kind,
2219            },
2220        ));
2221    }
2222
2223    #[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(2223u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["assignee_place",
                                                    "diag_expr_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&assignee_place)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.borrow(assignee_place, diag_expr_id,
                ty::BorrowKind::Mutable);
        }
    }
}#[instrument(skip(self), level = "debug")]
2224    fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2225        self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2226    }
2227}
2228
2229/// Rust doesn't permit moving fields out of a type that implements drop
2230x;#[instrument(skip(fcx), ret, level = "debug")]
2231fn restrict_precision_for_drop_types<'a, 'tcx>(
2232    fcx: &'a FnCtxt<'a, 'tcx>,
2233    mut place: Place<'tcx>,
2234    mut curr_mode: ty::UpvarCapture,
2235) -> (Place<'tcx>, ty::UpvarCapture) {
2236    let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
2237
2238    if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2239        for i in 0..place.projections.len() {
2240            match place.ty_before_projection(i).kind() {
2241                ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2242                    truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2243                    break;
2244                }
2245                _ => {}
2246            }
2247        }
2248    }
2249
2250    (place, curr_mode)
2251}
2252
2253/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2254/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2255///   them completely.
2256/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2257fn restrict_precision_for_unsafe(
2258    mut place: Place<'_>,
2259    mut curr_mode: ty::UpvarCapture,
2260) -> (Place<'_>, ty::UpvarCapture) {
2261    if place.base_ty.is_raw_ptr() {
2262        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2263    }
2264
2265    if place.base_ty.is_union() {
2266        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2267    }
2268
2269    for (i, proj) in place.projections.iter().enumerate() {
2270        if proj.ty.is_raw_ptr() {
2271            // Don't apply any projections on top of a raw ptr.
2272            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2273            break;
2274        }
2275
2276        if proj.ty.is_union() {
2277            // Don't capture precise fields of a union.
2278            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2279            break;
2280        }
2281    }
2282
2283    (place, curr_mode)
2284}
2285
2286/// Truncate projections so that the following rules are obeyed by the captured `place`:
2287/// - No Index projections are captured, since arrays are captured completely.
2288/// - No unsafe block is required to capture `place`.
2289///
2290/// Returns the truncated place and updated capture mode.
2291x;#[instrument(ret, level = "debug")]
2292fn restrict_capture_precision(
2293    place: Place<'_>,
2294    curr_mode: ty::UpvarCapture,
2295) -> (Place<'_>, ty::UpvarCapture) {
2296    let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
2297
2298    if place.projections.is_empty() {
2299        // Nothing to do here
2300        return (place, curr_mode);
2301    }
2302
2303    for (i, proj) in place.projections.iter().enumerate() {
2304        match proj.kind {
2305            ProjectionKind::Index | ProjectionKind::Subslice => {
2306                // Arrays are completely captured, so we drop Index and Subslice projections
2307                truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2308                return (place, curr_mode);
2309            }
2310            ProjectionKind::Deref => {}
2311            ProjectionKind::OpaqueCast => {}
2312            ProjectionKind::Field(..) => {}
2313            ProjectionKind::UnwrapUnsafeBinder => {}
2314        }
2315    }
2316
2317    (place, curr_mode)
2318}
2319
2320/// Truncate deref of any reference.
2321x;#[instrument(ret, level = "debug")]
2322fn adjust_for_move_closure(
2323    mut place: Place<'_>,
2324    mut kind: ty::UpvarCapture,
2325) -> (Place<'_>, ty::UpvarCapture) {
2326    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2327
2328    if let Some(idx) = first_deref {
2329        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2330    }
2331
2332    (place, ty::UpvarCapture::ByValue)
2333}
2334
2335/// Truncate deref of any reference.
2336x;#[instrument(ret, level = "debug")]
2337fn adjust_for_use_closure(
2338    mut place: Place<'_>,
2339    mut kind: ty::UpvarCapture,
2340) -> (Place<'_>, ty::UpvarCapture) {
2341    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2342
2343    if let Some(idx) = first_deref {
2344        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2345    }
2346
2347    (place, ty::UpvarCapture::ByUse)
2348}
2349
2350/// Adjust closure capture just that if taking ownership of data, only move data
2351/// from enclosing stack frame.
2352x;#[instrument(ret, level = "debug")]
2353fn adjust_for_non_move_closure(
2354    mut place: Place<'_>,
2355    mut kind: ty::UpvarCapture,
2356) -> (Place<'_>, ty::UpvarCapture) {
2357    let contains_deref =
2358        place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2359
2360    match kind {
2361        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2362            if let Some(idx) = contains_deref {
2363                truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2364            }
2365        }
2366
2367        ty::UpvarCapture::ByRef(..) => {}
2368    }
2369
2370    (place, kind)
2371}
2372
2373fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2374    let variable_name = match place.base {
2375        PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2376        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Capture_information should only contain upvars"))bug!("Capture_information should only contain upvars"),
2377    };
2378
2379    let mut projections_str = String::new();
2380    for (i, item) in place.projections.iter().enumerate() {
2381        let proj = match item.kind {
2382            ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
    })format!("({a:?}, {b:?})"),
2383            ProjectionKind::Deref => String::from("Deref"),
2384            ProjectionKind::Index => String::from("Index"),
2385            ProjectionKind::Subslice => String::from("Subslice"),
2386            ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2387            ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2388        };
2389        if i != 0 {
2390            projections_str.push(',');
2391        }
2392        projections_str.push_str(proj.as_str());
2393    }
2394
2395    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
                projections_str))
    })format!("{variable_name}[{projections_str}]")
2396}
2397
2398fn construct_capture_kind_reason_string<'tcx>(
2399    tcx: TyCtxt<'_>,
2400    place: &Place<'tcx>,
2401    capture_info: &ty::CaptureInfo,
2402) -> String {
2403    let place_str = construct_place_string(tcx, place);
2404
2405    let capture_kind_str = match capture_info.capture_kind {
2406        ty::UpvarCapture::ByValue => "ByValue".into(),
2407        ty::UpvarCapture::ByUse => "ByUse".into(),
2408        ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
2409    };
2410
2411    ::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")
2412}
2413
2414fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2415    let place_str = construct_place_string(tcx, place);
2416
2417    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} used here", place_str))
    })format!("{place_str} used here")
2418}
2419
2420fn construct_capture_info_string<'tcx>(
2421    tcx: TyCtxt<'_>,
2422    place: &Place<'tcx>,
2423    capture_info: &ty::CaptureInfo,
2424) -> String {
2425    let place_str = construct_place_string(tcx, place);
2426
2427    let capture_kind_str = match capture_info.capture_kind {
2428        ty::UpvarCapture::ByValue => "ByValue".into(),
2429        ty::UpvarCapture::ByUse => "ByUse".into(),
2430        ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
2431    };
2432    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
                capture_kind_str))
    })format!("{place_str} -> {capture_kind_str}")
2433}
2434
2435fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2436    tcx.hir_name(var_hir_id)
2437}
2438
2439#[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(2439u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["closure_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if tcx.sess.at_least_rust_2021() { return false; }
            let level =
                tcx.lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
                        closure_id).level;
            !#[allow(non_exhaustive_omitted_patterns)] match level {
                    lint::Level::Allow => true,
                    _ => false,
                }
        }
    }
}#[instrument(level = "debug", skip(tcx))]
2440fn should_do_rust_2021_incompatible_closure_captures_analysis(
2441    tcx: TyCtxt<'_>,
2442    closure_id: HirId,
2443) -> bool {
2444    if tcx.sess.at_least_rust_2021() {
2445        return false;
2446    }
2447
2448    let level = tcx
2449        .lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2450        .level;
2451
2452    !matches!(level, lint::Level::Allow)
2453}
2454
2455/// Return a two string tuple (s1, s2)
2456/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2457/// - s2: Comma separated names of the variables being migrated.
2458fn migration_suggestion_for_2229(
2459    tcx: TyCtxt<'_>,
2460    need_migrations: &[NeededMigration],
2461) -> (String, String) {
2462    let need_migrations_variables = need_migrations
2463        .iter()
2464        .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2465        .collect::<Vec<_>>();
2466
2467    let migration_ref_concat =
2468        need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
2469
2470    let migration_string = if 1 == need_migrations.len() {
2471        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let _ = {0}",
                migration_ref_concat))
    })format!("let _ = {migration_ref_concat}")
2472    } else {
2473        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let _ = ({0})",
                migration_ref_concat))
    })format!("let _ = ({migration_ref_concat})")
2474    };
2475
2476    let migrated_variables_concat =
2477        need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", v))
    })format!("`{v}`")).collect::<Vec<_>>().join(", ");
2478
2479    (migration_string, migrated_variables_concat)
2480}
2481
2482/// Helper function to determine if we need to escalate CaptureKind from
2483/// CaptureInfo A to B and returns the escalated CaptureInfo.
2484/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2485///
2486/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2487/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2488///
2489/// It is the caller's duty to figure out which path_expr_id to use.
2490///
2491/// If both the CaptureKind and Expression are considered to be equivalent,
2492/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2493/// expressions reported back to the user as part of diagnostics based on which appears earlier
2494/// in the closure. This can be achieved simply by calling
2495/// `determine_capture_info(existing_info, current_info)`. This works out because the
2496/// expressions that occur earlier in the closure body than the current expression are processed before.
2497/// Consider the following example
2498/// ```rust,no_run
2499/// struct Point { x: i32, y: i32 }
2500/// let mut p = Point { x: 10, y: 10 };
2501///
2502/// let c = || {
2503///     p.x += 10; // E1
2504///     // ...
2505///     // More code
2506///     // ...
2507///     p.x += 10; // E2
2508/// };
2509/// ```
2510/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2511/// and both have an expression associated, however for diagnostics we prefer reporting
2512/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2513/// would've already handled `E1`, and have an existing capture_information for it.
2514/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2515/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2516fn determine_capture_info(
2517    capture_info_a: ty::CaptureInfo,
2518    capture_info_b: ty::CaptureInfo,
2519) -> ty::CaptureInfo {
2520    // If the capture kind is equivalent then, we don't need to escalate and can compare the
2521    // expressions.
2522    let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2523        (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2524        (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2525        (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2526        (ty::UpvarCapture::ByValue, _)
2527        | (ty::UpvarCapture::ByUse, _)
2528        | (ty::UpvarCapture::ByRef(_), _) => false,
2529    };
2530
2531    if eq_capture_kind {
2532        match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2533            (Some(_), _) | (None, None) => capture_info_a,
2534            (None, Some(_)) => capture_info_b,
2535        }
2536    } else {
2537        // We select the CaptureKind which ranks higher based the following priority order:
2538        // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2539        match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2540            (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2541            | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2542                ::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")
2543            }
2544            (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2545            | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2546            | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2547                capture_info_a
2548            }
2549            (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2550                capture_info_b
2551            }
2552            (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2553                match (ref_a, ref_b) {
2554                    // Take LHS:
2555                    (BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2556                    | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
2557
2558                    // Take RHS:
2559                    (BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2560                    | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
2561
2562                    (BorrowKind::Immutable, BorrowKind::Immutable)
2563                    | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2564                    | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2565                        ::rustc_middle::util::bug::bug_fmt(format_args!("Expected unequal capture kinds"));bug!("Expected unequal capture kinds");
2566                    }
2567                }
2568            }
2569        }
2570    }
2571}
2572
2573/// Truncates `place` to have up to `len` projections.
2574/// `curr_mode` is the current required capture kind for the place.
2575/// Returns the truncated `place` and the updated required capture kind.
2576///
2577/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2578/// contained `Deref` of `&mut`.
2579fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2580    place: &mut Place<'tcx>,
2581    curr_mode: &mut ty::UpvarCapture,
2582    len: usize,
2583) {
2584    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));
2585
2586    // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2587    // UniqueImmBorrow
2588    // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2589    // we don't need to worry about that case here.
2590    match curr_mode {
2591        ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2592            for i in len..place.projections.len() {
2593                if place.projections[i].kind == ProjectionKind::Deref
2594                    && is_mut_ref(place.ty_before_projection(i))
2595                {
2596                    *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2597                    break;
2598                }
2599            }
2600        }
2601
2602        ty::UpvarCapture::ByRef(..) => {}
2603        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2604    }
2605
2606    place.projections.truncate(len);
2607}
2608
2609/// Determines the Ancestry relationship of Place A relative to Place B
2610///
2611/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2612/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2613/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2614fn determine_place_ancestry_relation<'tcx>(
2615    place_a: &Place<'tcx>,
2616    place_b: &Place<'tcx>,
2617) -> PlaceAncestryRelation {
2618    // If Place A and Place B don't start off from the same root variable, they are divergent.
2619    if place_a.base != place_b.base {
2620        return PlaceAncestryRelation::Divergent;
2621    }
2622
2623    // Assume of length of projections_a = n
2624    let projections_a = &place_a.projections;
2625
2626    // Assume of length of projections_b = m
2627    let projections_b = &place_b.projections;
2628
2629    let same_initial_projections =
2630        iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
2631
2632    if same_initial_projections {
2633        use std::cmp::Ordering;
2634
2635        // First min(n, m) projections are the same
2636        // Select Ancestor/Descendant
2637        match projections_b.len().cmp(&projections_a.len()) {
2638            Ordering::Greater => PlaceAncestryRelation::Ancestor,
2639            Ordering::Equal => PlaceAncestryRelation::SamePlace,
2640            Ordering::Less => PlaceAncestryRelation::Descendant,
2641        }
2642    } else {
2643        PlaceAncestryRelation::Divergent
2644    }
2645}
2646
2647/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2648/// borrow checking perspective, allowing us to save us on the size of the capture.
2649///
2650///
2651/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2652/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2653/// rightmost deref of the capture if the deref is applied to a shared ref.
2654///
2655/// Reason we only drop the last deref is because of the following edge case:
2656///
2657/// ```
2658/// # struct A { field_of_a: Box<i32> }
2659/// # struct B {}
2660/// # struct C<'a>(&'a i32);
2661/// struct MyStruct<'a> {
2662///    a: &'static A,
2663///    b: B,
2664///    c: C<'a>,
2665/// }
2666///
2667/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2668///     || drop(&*m.a.field_of_a)
2669///     // Here we really do want to capture `*m.a` because that outlives `'static`
2670///
2671///     // If we capture `m`, then the closure no longer outlives `'static`
2672///     // it is constrained to `'a`
2673/// }
2674/// ```
2675x;#[instrument(ret, level = "debug")]
2676fn truncate_capture_for_optimization(
2677    mut place: Place<'_>,
2678    mut curr_mode: ty::UpvarCapture,
2679) -> (Place<'_>, ty::UpvarCapture) {
2680    let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
2681
2682    // Find the rightmost deref (if any). All the projections that come after this
2683    // are fields or other "in-place pointer adjustments"; these refer therefore to
2684    // data owned by whatever pointer is being dereferenced here.
2685    let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
2686
2687    match idx {
2688        // If that pointer is a shared reference, then we don't need those fields.
2689        Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2690            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2691        }
2692        None | Some(_) => {}
2693    }
2694
2695    (place, curr_mode)
2696}
2697
2698/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2699/// `span` is the span of the closure.
2700fn enable_precise_capture(span: Span) -> bool {
2701    // We use span here to ensure that if the closure was generated by a macro with a different
2702    // edition.
2703    span.at_least_rust_2021()
2704}