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, 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        let (need_migrations, reasons) = self.compute_2229_migrations(
968            closure_def_id,
969            span,
970            capture_clause,
971            self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
972        );
973
974        if !need_migrations.is_empty() {
975            let (migration_string, migrated_variables_concat) =
976                migration_suggestion_for_2229(self.tcx, &need_migrations);
977
978            let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
979            let closure_head_span = self.tcx.def_span(closure_def_id);
980            self.tcx.node_span_lint(
981                lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
982                closure_hir_id,
983                closure_head_span,
984                |lint| {
985                    lint.primary_message(reasons.migration_message());
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 { source_expr: Some(capture_expr_id), var_name: captured_name } => {
993                                    let cause_span = self.tcx.hir_span(*capture_expr_id);
994                                    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}`",
                self.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 `{}`",
995                                        self.tcx.hir_name(*var_hir_id),
996                                        captured_name,
997                                    ));
998                                }
999                                UpvarMigrationInfo::CapturingNothing { use_span } => {
1000                                    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",
                self.tcx.hir_name(*var_hir_id)))
    })format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
1001                                        self.tcx.hir_name(*var_hir_id),
1002                                    ));
1003                                }
1004
1005                                _ => { }
1006                            }
1007
1008                            // Add a label pointing to where a captured variable affected by drop order
1009                            // is dropped
1010                            if lint_note.reason.drop_order {
1011                                let drop_location_span = drop_location_span(self.tcx, closure_hir_id);
1012
1013                                match &lint_note.captures_info {
1014                                    UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
1015                                        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",
                self.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",
1016                                            self.tcx.hir_name(*var_hir_id),
1017                                            captured_name,
1018                                        ));
1019                                    }
1020                                    UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1021                                        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",
                self.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",
1022                                            v = self.tcx.hir_name(*var_hir_id),
1023                                        ));
1024                                    }
1025                                }
1026                            }
1027
1028                            // Add a label explaining why a closure no longer implements a trait
1029                            for &missing_trait in &lint_note.reason.auto_traits {
1030                                // not capturing something anymore cannot cause a trait to fail to be implemented:
1031                                match &lint_note.captures_info {
1032                                    UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
1033                                        let var_name = self.tcx.hir_name(*var_hir_id);
1034                                        lint.span_label(closure_head_span, ::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!("\
1035                                        in Rust 2018, this closure implements {missing_trait} \
1036                                        as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1037                                        this closure will no longer implement {missing_trait} \
1038                                        because `{var_name}` is not fully captured \
1039                                        and `{captured_name}` does not implement {missing_trait}"));
1040                                    }
1041
1042                                    // Cannot happen: if we don't capture a variable, we impl strictly more traits
1043                                    UpvarMigrationInfo::CapturingNothing { use_span } => ::rustc_middle::util::bug::span_bug_fmt(*use_span,
    format_args!("missing trait from not capturing something"))span_bug!(*use_span, "missing trait from not capturing something"),
1044                                }
1045                            }
1046                        }
1047                    }
1048
1049                    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!(
1050                        "add a dummy let to cause {migrated_variables_concat} to be fully captured"
1051                    );
1052
1053                    let closure_span = self.tcx.hir_span_with_body(closure_hir_id);
1054                    let mut closure_body_span = {
1055                        // If the body was entirely expanded from a macro
1056                        // invocation, i.e. the body is not contained inside the
1057                        // closure span, then we walk up the expansion until we
1058                        // find the span before the expansion.
1059                        let s = self.tcx.hir_span_with_body(body_id.hir_id);
1060                        s.find_ancestor_inside(closure_span).unwrap_or(s)
1061                    };
1062
1063                    if let Ok(mut s) = self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1064                        if s.starts_with('$') {
1065                            // Looks like a macro fragment. Try to find the real block.
1066                            if let hir::Node::Expr(&hir::Expr {
1067                                kind: hir::ExprKind::Block(block, ..), ..
1068                            }) = self.tcx.hir_node(body_id.hir_id) {
1069                                // If the body is a block (with `{..}`), we use the span of that block.
1070                                // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1071                                // Since we know it's a block, we know we can insert the `let _ = ..` without
1072                                // breaking the macro syntax.
1073                                if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(block.span) {
1074                                    closure_body_span = block.span;
1075                                    s = snippet;
1076                                }
1077                            }
1078                        }
1079
1080                        let mut lines = s.lines();
1081                        let line1 = lines.next().unwrap_or_default();
1082
1083                        if line1.trim_end() == "{" {
1084                            // This is a multi-line closure with just a `{` on the first line,
1085                            // so we put the `let` on its own line.
1086                            // We take the indentation from the next non-empty line.
1087                            let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1088                            let indent = line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1089                            lint.span_suggestion(
1090                                closure_body_span.with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len())).shrink_to_lo(),
1091                                diagnostic_msg,
1092                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}{1};", indent,
                migration_string))
    })format!("\n{indent}{migration_string};"),
1093                                Applicability::MachineApplicable,
1094                            );
1095                        } else if line1.starts_with('{') {
1096                            // This is a closure with its body wrapped in
1097                            // braces, but with more than just the opening
1098                            // brace on the first line. We put the `let`
1099                            // directly after the `{`.
1100                            lint.span_suggestion(
1101                                closure_body_span.with_lo(closure_body_span.lo() + BytePos(1)).shrink_to_lo(),
1102                                diagnostic_msg,
1103                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0};", migration_string))
    })format!(" {migration_string};"),
1104                                Applicability::MachineApplicable,
1105                            );
1106                        } else {
1107                            // This is a closure without braces around the body.
1108                            // We add braces to add the `let` before the body.
1109                            lint.multipart_suggestion(
1110                                diagnostic_msg,
1111                                ::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![
1112                                    (closure_body_span.shrink_to_lo(), format!("{{ {migration_string}; ")),
1113                                    (closure_body_span.shrink_to_hi(), " }".to_string()),
1114                                ],
1115                                Applicability::MachineApplicable
1116                            );
1117                        }
1118                    } else {
1119                        lint.span_suggestion(
1120                            closure_span,
1121                            diagnostic_msg,
1122                            migration_string,
1123                            Applicability::HasPlaceholders
1124                        );
1125                    }
1126                },
1127            );
1128        }
1129    }
1130    fn normalize_capture_place(&self, span: Span, place: Place<'tcx>) -> Place<'tcx> {
1131        let mut place = self.resolve_vars_if_possible(place);
1132
1133        // In the new solver, types in HIR `Place`s can contain unnormalized aliases,
1134        // which can ICE later (e.g. when projecting fields for diagnostics).
1135        if self.next_trait_solver() {
1136            let cause = self.misc(span);
1137            let at = self.at(&cause, self.param_env);
1138            match solve::deeply_normalize_with_skipped_universes_and_ambiguous_coroutine_goals(
1139                at,
1140                place.clone(),
1141                ::alloc::vec::Vec::new()vec![],
1142            ) {
1143                Ok((normalized, goals)) => {
1144                    if !goals.is_empty() {
1145                        let mut typeck_results = self.typeck_results.borrow_mut();
1146                        typeck_results.coroutine_stalled_predicates.extend(
1147                            goals
1148                                .into_iter()
1149                                // FIXME: throwing away the param-env :(
1150                                .map(|goal| (goal.predicate, self.misc(span))),
1151                        );
1152                    }
1153                    normalized
1154                }
1155                Err(errors) => {
1156                    let guar = self.infcx.err_ctxt().report_fulfillment_errors(errors);
1157                    place.base_ty = Ty::new_error(self.tcx, guar);
1158                    for proj in &mut place.projections {
1159                        proj.ty = Ty::new_error(self.tcx, guar);
1160                    }
1161                    place
1162                }
1163            }
1164        } else {
1165            // For the old solver we can rely on `normalize` to eagerly normalize aliases.
1166            self.normalize(span, place)
1167        }
1168    }
1169
1170    /// Combines all the reasons for 2229 migrations
1171    fn compute_2229_migrations_reasons(
1172        &self,
1173        auto_trait_reasons: UnordSet<&'static str>,
1174        drop_order: bool,
1175    ) -> MigrationWarningReason {
1176        MigrationWarningReason {
1177            auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1178            drop_order,
1179        }
1180    }
1181
1182    /// Figures out the list of root variables (and their types) that aren't completely
1183    /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1184    /// differ between the root variable and the captured paths.
1185    ///
1186    /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1187    /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1188    fn compute_2229_migrations_for_trait(
1189        &self,
1190        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1191        var_hir_id: HirId,
1192        closure_clause: hir::CaptureBy,
1193    ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1194        let auto_traits_def_id = [
1195            self.tcx.lang_items().clone_trait(),
1196            self.tcx.lang_items().sync_trait(),
1197            self.tcx.get_diagnostic_item(sym::Send),
1198            self.tcx.lang_items().unpin_trait(),
1199            self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1200            self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1201        ];
1202        const AUTO_TRAITS: [&str; 6] =
1203            ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
1204
1205        let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
1206
1207        let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
1208
1209        let ty = match closure_clause {
1210            hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1211            hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1212                // For non move closure the capture kind is the max capture kind of all captures
1213                // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1214                let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1215                for capture in root_var_min_capture_list.iter() {
1216                    max_capture_info = determine_capture_info(max_capture_info, capture.info);
1217                }
1218
1219                apply_capture_kind_on_capture_ty(
1220                    self.tcx,
1221                    ty,
1222                    max_capture_info.capture_kind,
1223                    self.tcx.lifetimes.re_erased,
1224                )
1225            }
1226        };
1227
1228        let mut obligations_should_hold = Vec::new();
1229        // Checks if a root variable implements any of the auto traits
1230        for check_trait in auto_traits_def_id.iter() {
1231            obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1232                self.infcx
1233                    .type_implements_trait(check_trait, [ty], self.param_env)
1234                    .must_apply_modulo_regions()
1235            }));
1236        }
1237
1238        let mut problematic_captures = FxIndexMap::default();
1239        // Check whether captured fields also implement the trait
1240        for capture in root_var_min_capture_list.iter() {
1241            let ty = apply_capture_kind_on_capture_ty(
1242                self.tcx,
1243                capture.place.ty(),
1244                capture.info.capture_kind,
1245                self.tcx.lifetimes.re_erased,
1246            );
1247
1248            // Checks if a capture implements any of the auto traits
1249            let mut obligations_holds_for_capture = Vec::new();
1250            for check_trait in auto_traits_def_id.iter() {
1251                obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1252                    self.infcx
1253                        .type_implements_trait(check_trait, [ty], self.param_env)
1254                        .must_apply_modulo_regions()
1255                }));
1256            }
1257
1258            let mut capture_problems = UnordSet::default();
1259
1260            // Checks if for any of the auto traits, one or more trait is implemented
1261            // by the root variable but not by the capture
1262            for (idx, _) in obligations_should_hold.iter().enumerate() {
1263                if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1264                    capture_problems.insert(AUTO_TRAITS[idx]);
1265                }
1266            }
1267
1268            if !capture_problems.is_empty() {
1269                problematic_captures.insert(
1270                    UpvarMigrationInfo::CapturingPrecise {
1271                        source_expr: capture.info.path_expr_id,
1272                        var_name: capture.to_string(self.tcx),
1273                    },
1274                    capture_problems,
1275                );
1276            }
1277        }
1278        if !problematic_captures.is_empty() {
1279            return Some(problematic_captures);
1280        }
1281        None
1282    }
1283
1284    /// Figures out the list of root variables (and their types) that aren't completely
1285    /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1286    /// some path starting at that root variable **might** be affected.
1287    ///
1288    /// The output list would include a root variable if:
1289    /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1290    ///   enabled, **and**
1291    /// - It wasn't completely captured by the closure, **and**
1292    /// - One of the paths starting at this root variable, that is not captured needs Drop.
1293    ///
1294    /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1295    /// are no significant drops than None is returned
1296    #[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(1296u32),
                                    ::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:1312",
                                        "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(1312u32),
                                        ::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:1325",
                                            "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(1325u32),
                                            ::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:1343",
                                    "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(1343u32),
                                    ::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:1362",
                                    "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(1362u32),
                                    ::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: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(&["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:1366",
                                    "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(1366u32),
                                    ::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:1370",
                                    "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(1370u32),
                                    ::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))]
1297    fn compute_2229_migrations_for_drop(
1298        &self,
1299        closure_def_id: LocalDefId,
1300        closure_span: Span,
1301        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1302        closure_clause: hir::CaptureBy,
1303        var_hir_id: HirId,
1304    ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1305        let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
1306
1307        // FIXME(#132279): Using `non_body_analysis` here feels wrong.
1308        if !ty.has_significant_drop(
1309            self.tcx,
1310            ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1311        ) {
1312            debug!("does not have significant drop");
1313            return None;
1314        }
1315
1316        let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1317            // The upvar is mentioned within the closure but no path starting from it is
1318            // used. This occurs when you have (e.g.)
1319            //
1320            // ```
1321            // let x = move || {
1322            //     let _ = y;
1323            // });
1324            // ```
1325            debug!("no path starting from it is used");
1326
1327            match closure_clause {
1328                // Only migrate if closure is a move closure
1329                hir::CaptureBy::Value { .. } => {
1330                    let mut diagnostics_info = FxIndexSet::default();
1331                    let upvars =
1332                        self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1333                    let upvar = upvars[&var_hir_id];
1334                    diagnostics_info
1335                        .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1336                    return Some(diagnostics_info);
1337                }
1338                hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1339            }
1340
1341            return None;
1342        };
1343        debug!(?root_var_min_capture_list);
1344
1345        let mut projections_list = Vec::new();
1346        let mut diagnostics_info = FxIndexSet::default();
1347
1348        for captured_place in root_var_min_capture_list.iter() {
1349            match captured_place.info.capture_kind {
1350                // Only care about captures that are moved into the closure
1351                ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1352                    projections_list.push(captured_place.place.projections.as_slice());
1353                    diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1354                        source_expr: captured_place.info.path_expr_id,
1355                        var_name: captured_place.to_string(self.tcx),
1356                    });
1357                }
1358                ty::UpvarCapture::ByRef(..) => {}
1359            }
1360        }
1361
1362        debug!(?projections_list);
1363        debug!(?diagnostics_info);
1364
1365        let is_moved = !projections_list.is_empty();
1366        debug!(?is_moved);
1367
1368        let is_not_completely_captured =
1369            root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1370        debug!(?is_not_completely_captured);
1371
1372        if is_moved
1373            && is_not_completely_captured
1374            && self.has_significant_drop_outside_of_captures(
1375                closure_def_id,
1376                closure_span,
1377                ty,
1378                projections_list,
1379            )
1380        {
1381            return Some(diagnostics_info);
1382        }
1383
1384        None
1385    }
1386
1387    /// Figures out the list of root variables (and their types) that aren't completely
1388    /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1389    /// order of some path starting at that root variable **might** be affected or auto-traits
1390    /// differ between the root variable and the captured paths.
1391    ///
1392    /// The output list would include a root variable if:
1393    /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1394    ///   enabled, **and**
1395    /// - It wasn't completely captured by the closure, **and**
1396    /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1397    /// - One of the paths captured does not implement all the auto-traits its root variable
1398    ///   implements.
1399    ///
1400    /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1401    /// containing the reason why root variables whose HirId is contained in the vector should
1402    /// be captured
1403    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("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(1403u32),
                                    ::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))]
1404    fn compute_2229_migrations(
1405        &self,
1406        closure_def_id: LocalDefId,
1407        closure_span: Span,
1408        closure_clause: hir::CaptureBy,
1409        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1410    ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1411        let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1412            return (Vec::new(), MigrationWarningReason::default());
1413        };
1414
1415        let mut need_migrations = Vec::new();
1416        let mut auto_trait_migration_reasons = UnordSet::default();
1417        let mut drop_migration_needed = false;
1418
1419        // Perform auto-trait analysis
1420        for (&var_hir_id, _) in upvars.iter() {
1421            let mut diagnostics_info = Vec::new();
1422
1423            let auto_trait_diagnostic = self
1424                .compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1425                .unwrap_or_default();
1426
1427            let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1428                .compute_2229_migrations_for_drop(
1429                    closure_def_id,
1430                    closure_span,
1431                    min_captures,
1432                    closure_clause,
1433                    var_hir_id,
1434                ) {
1435                drop_migration_needed = true;
1436                diagnostics_info
1437            } else {
1438                FxIndexSet::default()
1439            };
1440
1441            // Combine all the captures responsible for needing migrations into one IndexSet
1442            let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1443            for key in auto_trait_diagnostic.keys() {
1444                capture_diagnostic.insert(key.clone());
1445            }
1446
1447            let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1448            capture_diagnostic.sort_by_cached_key(|info| match info {
1449                UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1450                    (0, Some(var_name.clone()))
1451                }
1452                UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1453            });
1454            for captures_info in capture_diagnostic {
1455                // Get the auto trait reasons of why migration is needed because of that capture, if there are any
1456                let capture_trait_reasons =
1457                    if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1458                        reasons.clone()
1459                    } else {
1460                        UnordSet::default()
1461                    };
1462
1463                // Check if migration is needed because of drop reorder as a result of that capture
1464                let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
1465
1466                // Combine all the reasons of why the root variable should be captured as a result of
1467                // auto trait implementation issues
1468                auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
1469
1470                diagnostics_info.push(MigrationLintNote {
1471                    captures_info,
1472                    reason: self.compute_2229_migrations_reasons(
1473                        capture_trait_reasons,
1474                        capture_drop_reorder_reason,
1475                    ),
1476                });
1477            }
1478
1479            if !diagnostics_info.is_empty() {
1480                need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1481            }
1482        }
1483        (
1484            need_migrations,
1485            self.compute_2229_migrations_reasons(
1486                auto_trait_migration_reasons,
1487                drop_migration_needed,
1488            ),
1489        )
1490    }
1491
1492    /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1493    /// of a root variable and a list of captured paths starting at this root variable (expressed
1494    /// using list of `Projection` slices), it returns true if there is a path that is not
1495    /// captured starting at this root variable that implements Drop.
1496    ///
1497    /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1498    /// path say P and then list of projection slices which represent the different captures moved
1499    /// into the closure starting off of P.
1500    ///
1501    /// This will make more sense with an example:
1502    ///
1503    /// ```rust,edition2021
1504    ///
1505    /// struct FancyInteger(i32); // This implements Drop
1506    ///
1507    /// struct Point { x: FancyInteger, y: FancyInteger }
1508    /// struct Color;
1509    ///
1510    /// struct Wrapper { p: Point, c: Color }
1511    ///
1512    /// fn f(w: Wrapper) {
1513    ///   let c = || {
1514    ///       // Closure captures w.p.x and w.c by move.
1515    ///   };
1516    ///
1517    ///   c();
1518    /// }
1519    /// ```
1520    ///
1521    /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1522    /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1523    /// therefore Drop ordering would change and we want this function to return true.
1524    ///
1525    /// Call stack to figure out if we need to migrate for `w` would look as follows:
1526    ///
1527    /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1528    /// `w[c]`.
1529    /// Notation:
1530    /// - Ty(place): Type of place
1531    /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1532    ///   respectively.
1533    /// ```ignore (illustrative)
1534    ///                  (Ty(w), [ &[p, x], &[c] ])
1535    /// //                              |
1536    /// //                 ----------------------------
1537    /// //                 |                          |
1538    /// //                 v                          v
1539    ///        (Ty(w.p), [ &[x] ])          (Ty(w.c), [ &[] ]) // I(1)
1540    /// //                 |                          |
1541    /// //                 v                          v
1542    ///        (Ty(w.p), [ &[x] ])                 false
1543    /// //                 |
1544    /// //                 |
1545    /// //       -------------------------------
1546    /// //       |                             |
1547    /// //       v                             v
1548    ///     (Ty((w.p).x), [ &[] ])     (Ty((w.p).y), []) // IMP 2
1549    /// //       |                             |
1550    /// //       v                             v
1551    ///        false              NeedsSignificantDrop(Ty(w.p.y))
1552    /// //                                     |
1553    /// //                                     v
1554    ///                                      true
1555    /// ```
1556    ///
1557    /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1558    ///                             This implies that the `w.c` is completely captured by the closure.
1559    ///                             Since drop for this path will be called when the closure is
1560    ///                             dropped we don't need to migrate for it.
1561    ///
1562    /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1563    ///                             path wasn't captured by the closure. Also note that even
1564    ///                             though we didn't capture this path, the function visits it,
1565    ///                             which is kind of the point of this function. We then return
1566    ///                             if the type of `w.p.y` implements Drop, which in this case is
1567    ///                             true.
1568    ///
1569    /// Consider another example:
1570    ///
1571    /// ```ignore (pseudo-rust)
1572    /// struct X;
1573    /// impl Drop for X {}
1574    ///
1575    /// struct Y(X);
1576    /// impl Drop for Y {}
1577    ///
1578    /// fn foo() {
1579    ///     let y = Y(X);
1580    ///     let c = || move(y.0);
1581    /// }
1582    /// ```
1583    ///
1584    /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1585    /// return true, because even though all paths starting at `y` are captured, `y` itself
1586    /// implements Drop which will be affected since `y` isn't completely captured.
1587    fn has_significant_drop_outside_of_captures(
1588        &self,
1589        closure_def_id: LocalDefId,
1590        closure_span: Span,
1591        base_path_ty: Ty<'tcx>,
1592        captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1593    ) -> bool {
1594        // FIXME(#132279): Using `non_body_analysis` here feels wrong.
1595        let needs_drop = |ty: Ty<'tcx>| {
1596            ty.has_significant_drop(
1597                self.tcx,
1598                ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1599            )
1600        };
1601
1602        let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1603            let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, closure_span);
1604            self.infcx
1605                .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1606                .must_apply_modulo_regions()
1607        };
1608
1609        let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
1610
1611        // If there is a case where no projection is applied on top of current place
1612        // then there must be exactly one capture corresponding to such a case. Note that this
1613        // represents the case of the path being completely captured by the variable.
1614        //
1615        // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1616        //     capture `a.b.c`, because that violates min capture.
1617        let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
1618
1619        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));
1620
1621        if is_completely_captured {
1622            // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1623            // when the closure is dropped.
1624            return false;
1625        }
1626
1627        if captured_by_move_projs.is_empty() {
1628            return needs_drop(base_path_ty);
1629        }
1630
1631        if is_drop_defined_for_ty {
1632            // If drop is implemented for this type then we need it to be fully captured,
1633            // and we know it is not completely captured because of the previous checks.
1634
1635            // Note that this is a bug in the user code that will be reported by the
1636            // borrow checker, since we can't move out of drop types.
1637
1638            // The bug exists in the user's code pre-migration, and we don't migrate here.
1639            return false;
1640        }
1641
1642        match base_path_ty.kind() {
1643            // Observations:
1644            // - `captured_by_move_projs` is not empty. Therefore we can call
1645            //   `captured_by_move_projs.first().unwrap()` safely.
1646            // - All entries in `captured_by_move_projs` have at least one projection.
1647            //   Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
1648
1649            // We don't capture derefs in case of move captures, which would have be applied to
1650            // access any further paths.
1651            ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1652            ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1653            ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1654
1655            ty::Adt(def, args) => {
1656                // Multi-variant enums are captured in entirety,
1657                // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1658                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);
1659
1660                // Only Field projections can be applied to a non-box Adt.
1661                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!(
1662                    captured_by_move_projs.iter().all(|projs| matches!(
1663                        projs.first().unwrap().kind,
1664                        ProjectionKind::Field(..)
1665                    ))
1666                );
1667                def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1668                    |(i, field)| {
1669                        let paths_using_field = captured_by_move_projs
1670                            .iter()
1671                            .filter_map(|projs| {
1672                                if let ProjectionKind::Field(field_idx, _) =
1673                                    projs.first().unwrap().kind
1674                                {
1675                                    if field_idx == i { Some(&projs[1..]) } else { None }
1676                                } else {
1677                                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1678                                }
1679                            })
1680                            .collect();
1681
1682                        let after_field_ty = field.ty(self.tcx, args);
1683                        self.has_significant_drop_outside_of_captures(
1684                            closure_def_id,
1685                            closure_span,
1686                            after_field_ty,
1687                            paths_using_field,
1688                        )
1689                    },
1690                )
1691            }
1692
1693            ty::Tuple(fields) => {
1694                // Only Field projections can be applied to a tuple.
1695                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!(
1696                    captured_by_move_projs.iter().all(|projs| matches!(
1697                        projs.first().unwrap().kind,
1698                        ProjectionKind::Field(..)
1699                    ))
1700                );
1701
1702                fields.iter().enumerate().any(|(i, element_ty)| {
1703                    let paths_using_field = captured_by_move_projs
1704                        .iter()
1705                        .filter_map(|projs| {
1706                            if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1707                            {
1708                                if field_idx.index() == i { Some(&projs[1..]) } else { None }
1709                            } else {
1710                                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1711                            }
1712                        })
1713                        .collect();
1714
1715                    self.has_significant_drop_outside_of_captures(
1716                        closure_def_id,
1717                        closure_span,
1718                        element_ty,
1719                        paths_using_field,
1720                    )
1721                })
1722            }
1723
1724            // Anything else would be completely captured and therefore handled already.
1725            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1726        }
1727    }
1728
1729    fn init_capture_kind_for_place(
1730        &self,
1731        place: &Place<'tcx>,
1732        capture_clause: hir::CaptureBy,
1733    ) -> ty::UpvarCapture {
1734        match capture_clause {
1735            // In case of a move closure if the data is accessed through a reference we
1736            // want to capture by ref to allow precise capture using reborrows.
1737            //
1738            // If the data will be moved out of this place, then the place will be truncated
1739            // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1740            //
1741            // For example:
1742            //
1743            // struct Buffer<'a> {
1744            //     x: &'a String,
1745            //     y: Vec<u8>,
1746            // }
1747            //
1748            // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1749            //     let c = move || b.x;
1750            //     drop(b);
1751            //     c
1752            // }
1753            //
1754            // Even though the closure is declared as move, when we are capturing borrowed data (in
1755            // this case, *b.x) we prefer to capture by reference.
1756            // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1757            // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1758            // before, which is also an error.
1759            hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1760                ty::UpvarCapture::ByValue
1761            }
1762            hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1763                ty::UpvarCapture::ByUse
1764            }
1765            hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1766                ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1767            }
1768        }
1769    }
1770
1771    fn place_for_root_variable(
1772        &self,
1773        closure_def_id: LocalDefId,
1774        var_hir_id: HirId,
1775    ) -> Place<'tcx> {
1776        let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
1777
1778        let place = Place {
1779            base_ty: self.node_ty(var_hir_id),
1780            base: PlaceBase::Upvar(upvar_id),
1781            projections: Default::default(),
1782        };
1783
1784        // Normalize eagerly when inserting into `capture_information`, so all downstream
1785        // capture analysis can assume a normalized `Place`.
1786        self.normalize_capture_place(self.tcx.hir_span(var_hir_id), place)
1787    }
1788
1789    fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1790        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)
1791    }
1792
1793    fn log_capture_analysis_first_pass(
1794        &self,
1795        closure_def_id: LocalDefId,
1796        capture_information: &InferredCaptureInformation<'tcx>,
1797        closure_span: Span,
1798    ) {
1799        if self.should_log_capture_analysis(closure_def_id) {
1800            let mut diag =
1801                self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1802            for (place, capture_info) in capture_information {
1803                let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1804                let output_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
    })format!("Capturing {capture_str}");
1805
1806                let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1807                diag.span_note(span, output_str);
1808            }
1809            diag.emit();
1810        }
1811    }
1812
1813    fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1814        if self.should_log_capture_analysis(closure_def_id) {
1815            if let Some(min_captures) =
1816                self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1817            {
1818                let mut diag =
1819                    self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
1820
1821                for (_, min_captures_for_var) in min_captures {
1822                    for capture in min_captures_for_var {
1823                        let place = &capture.place;
1824                        let capture_info = &capture.info;
1825
1826                        let capture_str =
1827                            construct_capture_info_string(self.tcx, place, capture_info);
1828                        let output_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
    })format!("Min Capture {capture_str}");
1829
1830                        if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1831                            let path_span = capture_info
1832                                .path_expr_id
1833                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1834                            let capture_kind_span = capture_info
1835                                .capture_kind_expr_id
1836                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1837
1838                            let mut multi_span: MultiSpan =
1839                                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]);
1840
1841                            let capture_kind_label =
1842                                construct_capture_kind_reason_string(self.tcx, place, capture_info);
1843                            let path_label = construct_path_string(self.tcx, place);
1844
1845                            multi_span.push_span_label(path_span, path_label);
1846                            multi_span.push_span_label(capture_kind_span, capture_kind_label);
1847
1848                            diag.span_note(multi_span, output_str);
1849                        } else {
1850                            let span = capture_info
1851                                .path_expr_id
1852                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1853
1854                            diag.span_note(span, output_str);
1855                        };
1856                    }
1857                }
1858                diag.emit();
1859            }
1860        }
1861    }
1862
1863    /// A captured place is mutable if
1864    /// 1. Projections don't include a Deref of an immut-borrow, **and**
1865    /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1866    fn determine_capture_mutability(
1867        &self,
1868        typeck_results: &'a TypeckResults<'tcx>,
1869        place: &Place<'tcx>,
1870    ) -> hir::Mutability {
1871        let var_hir_id = match place.base {
1872            PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1873            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1874        };
1875
1876        let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1877
1878        let mut is_mutbl = bm.1;
1879
1880        for pointer_ty in place.deref_tys() {
1881            match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
1882                // We don't capture derefs of raw ptrs
1883                ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1884
1885                // Dereferencing a mut-ref allows us to mut the Place if we don't deref
1886                // an immut-ref after on top of this.
1887                ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1888
1889                // The place isn't mutable once we dereference an immutable reference.
1890                ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1891
1892                // Dereferencing a box doesn't change mutability
1893                ty::Adt(def, ..) if def.is_box() => {}
1894
1895                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!(
1896                    self.tcx.hir_span(var_hir_id),
1897                    "deref of unexpected pointer type {:?}",
1898                    unexpected_ty
1899                ),
1900            }
1901        }
1902
1903        is_mutbl
1904    }
1905}
1906
1907/// Determines whether a child capture that is derived from a parent capture
1908/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1909///
1910/// There are two cases when this needs to happen:
1911///
1912/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1913/// that is the case by checking if the parent capture is by move, EXCEPT if we
1914/// apply a deref projection of an immutable reference, reborrows of immutable
1915/// references which aren't restricted to the LUB of the lifetimes of the deref
1916/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1917///
1918/// ```rust
1919/// let x = &1i32; // Let's call this lifetime `'1`.
1920/// let c = async move || {
1921///     println!("{:?}", *x);
1922///     // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1923///     // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1924/// };
1925/// ```
1926///
1927/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1928/// mutable borrow cannot live for longer than either the parent *or* the borrow
1929/// that we have on the original upvar. Therefore we always need to borrow the
1930/// child capture with the lifetime of the parent coroutine-closure's env.
1931///
1932/// ```rust
1933/// let mut x = 1i32;
1934/// let c = async || {
1935///     x = 1;
1936///     // The parent borrows `x` for some `&'1 mut i32`.
1937///     // However, when we call `c()`, we implicitly autoref for the signature of
1938///     // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1939///     // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1940///     // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1941/// };
1942/// ```
1943///
1944/// If either of these cases apply, then we should capture the borrow with the
1945/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1946/// not correct, then the program is not unsound, since we still borrowck and validate
1947/// the choices made from this function -- the only side-effect is that the user
1948/// may receive unnecessary borrowck errors.
1949fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
1950    parent_capture: &ty::CapturedPlace<'tcx>,
1951    child_capture: &ty::CapturedPlace<'tcx>,
1952) -> bool {
1953    // (1.)
1954    (!parent_capture.is_by_ref()
1955        // This is just inlined `place.deref_tys()` but truncated to just
1956        // the child projections. Namely, look for a `&T` deref, since we
1957        // can always extend `&'short mut &'long T` to `&'long T`.
1958        && !child_capture
1959            .place
1960            .projections
1961            .iter()
1962            .enumerate()
1963            .skip(parent_capture.place.projections.len())
1964            .any(|(idx, proj)| {
1965                #[allow(non_exhaustive_omitted_patterns)] match proj.kind {
    ProjectionKind::Deref => true,
    _ => false,
}matches!(proj.kind, ProjectionKind::Deref)
1966                    && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
    {
    ty::Ref(.., ty::Mutability::Not) => true,
    _ => false,
}matches!(
1967                        child_capture.place.ty_before_projection(idx).kind(),
1968                        ty::Ref(.., ty::Mutability::Not)
1969                    )
1970            }))
1971        // (2.)
1972        || #[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))
1973}
1974
1975/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1976/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1977fn restrict_repr_packed_field_ref_capture<'tcx>(
1978    mut place: Place<'tcx>,
1979    mut curr_borrow_kind: ty::UpvarCapture,
1980) -> (Place<'tcx>, ty::UpvarCapture) {
1981    let pos = place.projections.iter().enumerate().position(|(i, p)| {
1982        let ty = place.ty_before_projection(i);
1983
1984        // Return true for fields of packed structs.
1985        match p.kind {
1986            ProjectionKind::Field(..) => match ty.kind() {
1987                ty::Adt(def, _) if def.repr().packed() => {
1988                    // We stop here regardless of field alignment. Field alignment can change as
1989                    // types change, including the types of private fields in other crates, and that
1990                    // shouldn't affect how we compute our captures.
1991                    true
1992                }
1993
1994                _ => false,
1995            },
1996            _ => false,
1997        }
1998    });
1999
2000    if let Some(pos) = pos {
2001        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
2002    }
2003
2004    (place, curr_borrow_kind)
2005}
2006
2007/// Returns a Ty that applies the specified capture kind on the provided capture Ty
2008fn apply_capture_kind_on_capture_ty<'tcx>(
2009    tcx: TyCtxt<'tcx>,
2010    ty: Ty<'tcx>,
2011    capture_kind: UpvarCapture,
2012    region: ty::Region<'tcx>,
2013) -> Ty<'tcx> {
2014    match capture_kind {
2015        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
2016        ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
2017    }
2018}
2019
2020/// Returns the Span of where the value with the provided HirId would be dropped
2021fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
2022    let owner_id = tcx.hir_get_enclosing_scope(hir_id).unwrap();
2023
2024    let owner_node = tcx.hir_node(owner_id);
2025    let owner_span = match owner_node {
2026        hir::Node::Item(item) => match item.kind {
2027            hir::ItemKind::Fn { body: owner_id, .. } => tcx.hir_span(owner_id.hir_id),
2028            _ => {
2029                ::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);
2030            }
2031        },
2032        hir::Node::Block(block) => tcx.hir_span(block.hir_id),
2033        hir::Node::TraitItem(item) => tcx.hir_span(item.hir_id()),
2034        hir::Node::ImplItem(item) => tcx.hir_span(item.hir_id()),
2035        _ => {
2036            ::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);
2037        }
2038    };
2039    tcx.sess.source_map().end_point(owner_span)
2040}
2041
2042struct InferBorrowKind<'fcx, 'a, 'tcx> {
2043    fcx: &'fcx FnCtxt<'a, 'tcx>,
2044    // The def-id of the closure whose kind and upvar accesses are being inferred.
2045    closure_def_id: LocalDefId,
2046
2047    /// For each Place that is captured by the closure, we track the minimal kind of
2048    /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2049    ///
2050    /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2051    /// s.str2 via a MutableBorrow
2052    ///
2053    /// ```rust,no_run
2054    /// struct SomeStruct { str1: String, str2: String };
2055    ///
2056    /// // Assume that the HirId for the variable definition is `V1`
2057    /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2058    ///
2059    /// let fix_s = |new_s2| {
2060    ///     // Assume that the HirId for the expression `s.str1` is `E1`
2061    ///     println!("Updating SomeStruct with str1={0}", s.str1);
2062    ///     // Assume that the HirId for the expression `*s.str2` is `E2`
2063    ///     s.str2 = new_s2;
2064    /// };
2065    /// ```
2066    ///
2067    /// For closure `fix_s`, (at a high level) the map contains
2068    ///
2069    /// ```ignore (illustrative)
2070    /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2071    /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2072    /// ```
2073    capture_information: InferredCaptureInformation<'tcx>,
2074    fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2075}
2076
2077impl<'fcx, 'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'fcx, 'a, 'tcx> {
2078    #[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(2078u32),
                                    ::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")]
2079    fn fake_read(
2080        &mut self,
2081        place_with_id: &PlaceWithHirId<'tcx>,
2082        cause: FakeReadCause,
2083        diag_expr_id: HirId,
2084    ) {
2085        let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
2086
2087        // We need to restrict Fake Read precision to avoid fake reading unsafe code,
2088        // such as deref of a raw pointer.
2089        let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2090
2091        let span = self.fcx.tcx.hir_span(diag_expr_id);
2092        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2093
2094        let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
2095
2096        let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2097        self.fake_reads.push((place, cause, diag_expr_id));
2098    }
2099
2100    #[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(2100u32),
                                    ::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")]
2101    fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2102        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2103        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2104
2105        let span = self.fcx.tcx.hir_span(diag_expr_id);
2106        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2107
2108        self.capture_information.push((
2109            place,
2110            ty::CaptureInfo {
2111                capture_kind_expr_id: Some(diag_expr_id),
2112                path_expr_id: Some(diag_expr_id),
2113                capture_kind: ty::UpvarCapture::ByValue,
2114            },
2115        ));
2116    }
2117
2118    #[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(2118u32),
                                    ::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")]
2119    fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2120        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2121        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2122
2123        let span = self.fcx.tcx.hir_span(diag_expr_id);
2124        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2125
2126        self.capture_information.push((
2127            place,
2128            ty::CaptureInfo {
2129                capture_kind_expr_id: Some(diag_expr_id),
2130                path_expr_id: Some(diag_expr_id),
2131                capture_kind: ty::UpvarCapture::ByUse,
2132            },
2133        ));
2134    }
2135
2136    #[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(2136u32),
                                    ::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")]
2137    fn borrow(
2138        &mut self,
2139        place_with_id: &PlaceWithHirId<'tcx>,
2140        diag_expr_id: HirId,
2141        bk: ty::BorrowKind,
2142    ) {
2143        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2144        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2145
2146        // The region here will get discarded/ignored
2147        let capture_kind = ty::UpvarCapture::ByRef(bk);
2148
2149        let span = self.fcx.tcx.hir_span(diag_expr_id);
2150        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2151
2152        // We only want repr packed restriction to be applied to reading references into a packed
2153        // struct, and not when the data is being moved. Therefore we call this method here instead
2154        // of in `restrict_capture_precision`.
2155        let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(place, capture_kind);
2156
2157        // Raw pointers don't inherit mutability
2158        if place.deref_tys().any(Ty::is_raw_ptr) {
2159            capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2160        }
2161
2162        self.capture_information.push((
2163            place,
2164            ty::CaptureInfo {
2165                capture_kind_expr_id: Some(diag_expr_id),
2166                path_expr_id: Some(diag_expr_id),
2167                capture_kind,
2168            },
2169        ));
2170    }
2171
2172    #[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(2172u32),
                                    ::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")]
2173    fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2174        self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2175    }
2176}
2177
2178/// Rust doesn't permit moving fields out of a type that implements drop
2179x;#[instrument(skip(fcx), ret, level = "debug")]
2180fn restrict_precision_for_drop_types<'a, 'tcx>(
2181    fcx: &'a FnCtxt<'a, 'tcx>,
2182    mut place: Place<'tcx>,
2183    mut curr_mode: ty::UpvarCapture,
2184) -> (Place<'tcx>, ty::UpvarCapture) {
2185    let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
2186
2187    if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2188        for i in 0..place.projections.len() {
2189            match place.ty_before_projection(i).kind() {
2190                ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2191                    truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2192                    break;
2193                }
2194                _ => {}
2195            }
2196        }
2197    }
2198
2199    (place, curr_mode)
2200}
2201
2202/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2203/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2204///   them completely.
2205/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2206fn restrict_precision_for_unsafe(
2207    mut place: Place<'_>,
2208    mut curr_mode: ty::UpvarCapture,
2209) -> (Place<'_>, ty::UpvarCapture) {
2210    if place.base_ty.is_raw_ptr() {
2211        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2212    }
2213
2214    if place.base_ty.is_union() {
2215        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2216    }
2217
2218    for (i, proj) in place.projections.iter().enumerate() {
2219        if proj.ty.is_raw_ptr() {
2220            // Don't apply any projections on top of a raw ptr.
2221            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2222            break;
2223        }
2224
2225        if proj.ty.is_union() {
2226            // Don't capture precise fields of a union.
2227            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2228            break;
2229        }
2230    }
2231
2232    (place, curr_mode)
2233}
2234
2235/// Truncate projections so that the following rules are obeyed by the captured `place`:
2236/// - No Index projections are captured, since arrays are captured completely.
2237/// - No unsafe block is required to capture `place`.
2238///
2239/// Returns the truncated place and updated capture mode.
2240x;#[instrument(ret, level = "debug")]
2241fn restrict_capture_precision(
2242    place: Place<'_>,
2243    curr_mode: ty::UpvarCapture,
2244) -> (Place<'_>, ty::UpvarCapture) {
2245    let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
2246
2247    if place.projections.is_empty() {
2248        // Nothing to do here
2249        return (place, curr_mode);
2250    }
2251
2252    for (i, proj) in place.projections.iter().enumerate() {
2253        match proj.kind {
2254            ProjectionKind::Index | ProjectionKind::Subslice => {
2255                // Arrays are completely captured, so we drop Index and Subslice projections
2256                truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2257                return (place, curr_mode);
2258            }
2259            ProjectionKind::Deref => {}
2260            ProjectionKind::OpaqueCast => {}
2261            ProjectionKind::Field(..) => {}
2262            ProjectionKind::UnwrapUnsafeBinder => {}
2263        }
2264    }
2265
2266    (place, curr_mode)
2267}
2268
2269/// Truncate deref of any reference.
2270x;#[instrument(ret, level = "debug")]
2271fn adjust_for_move_closure(
2272    mut place: Place<'_>,
2273    mut kind: ty::UpvarCapture,
2274) -> (Place<'_>, ty::UpvarCapture) {
2275    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2276
2277    if let Some(idx) = first_deref {
2278        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2279    }
2280
2281    (place, ty::UpvarCapture::ByValue)
2282}
2283
2284/// Truncate deref of any reference.
2285x;#[instrument(ret, level = "debug")]
2286fn adjust_for_use_closure(
2287    mut place: Place<'_>,
2288    mut kind: ty::UpvarCapture,
2289) -> (Place<'_>, ty::UpvarCapture) {
2290    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2291
2292    if let Some(idx) = first_deref {
2293        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2294    }
2295
2296    (place, ty::UpvarCapture::ByUse)
2297}
2298
2299/// Adjust closure capture just that if taking ownership of data, only move data
2300/// from enclosing stack frame.
2301x;#[instrument(ret, level = "debug")]
2302fn adjust_for_non_move_closure(
2303    mut place: Place<'_>,
2304    mut kind: ty::UpvarCapture,
2305) -> (Place<'_>, ty::UpvarCapture) {
2306    let contains_deref =
2307        place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2308
2309    match kind {
2310        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2311            if let Some(idx) = contains_deref {
2312                truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2313            }
2314        }
2315
2316        ty::UpvarCapture::ByRef(..) => {}
2317    }
2318
2319    (place, kind)
2320}
2321
2322fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2323    let variable_name = match place.base {
2324        PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2325        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Capture_information should only contain upvars"))bug!("Capture_information should only contain upvars"),
2326    };
2327
2328    let mut projections_str = String::new();
2329    for (i, item) in place.projections.iter().enumerate() {
2330        let proj = match item.kind {
2331            ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
    })format!("({a:?}, {b:?})"),
2332            ProjectionKind::Deref => String::from("Deref"),
2333            ProjectionKind::Index => String::from("Index"),
2334            ProjectionKind::Subslice => String::from("Subslice"),
2335            ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2336            ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2337        };
2338        if i != 0 {
2339            projections_str.push(',');
2340        }
2341        projections_str.push_str(proj.as_str());
2342    }
2343
2344    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
                projections_str))
    })format!("{variable_name}[{projections_str}]")
2345}
2346
2347fn construct_capture_kind_reason_string<'tcx>(
2348    tcx: TyCtxt<'_>,
2349    place: &Place<'tcx>,
2350    capture_info: &ty::CaptureInfo,
2351) -> String {
2352    let place_str = construct_place_string(tcx, place);
2353
2354    let capture_kind_str = match capture_info.capture_kind {
2355        ty::UpvarCapture::ByValue => "ByValue".into(),
2356        ty::UpvarCapture::ByUse => "ByUse".into(),
2357        ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
2358    };
2359
2360    ::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")
2361}
2362
2363fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2364    let place_str = construct_place_string(tcx, place);
2365
2366    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} used here", place_str))
    })format!("{place_str} used here")
2367}
2368
2369fn construct_capture_info_string<'tcx>(
2370    tcx: TyCtxt<'_>,
2371    place: &Place<'tcx>,
2372    capture_info: &ty::CaptureInfo,
2373) -> String {
2374    let place_str = construct_place_string(tcx, place);
2375
2376    let capture_kind_str = match capture_info.capture_kind {
2377        ty::UpvarCapture::ByValue => "ByValue".into(),
2378        ty::UpvarCapture::ByUse => "ByUse".into(),
2379        ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
2380    };
2381    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
                capture_kind_str))
    })format!("{place_str} -> {capture_kind_str}")
2382}
2383
2384fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2385    tcx.hir_name(var_hir_id)
2386}
2387
2388#[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(2388u32),
                                    ::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))]
2389fn should_do_rust_2021_incompatible_closure_captures_analysis(
2390    tcx: TyCtxt<'_>,
2391    closure_id: HirId,
2392) -> bool {
2393    if tcx.sess.at_least_rust_2021() {
2394        return false;
2395    }
2396
2397    let level = tcx
2398        .lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2399        .level;
2400
2401    !matches!(level, lint::Level::Allow)
2402}
2403
2404/// Return a two string tuple (s1, s2)
2405/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2406/// - s2: Comma separated names of the variables being migrated.
2407fn migration_suggestion_for_2229(
2408    tcx: TyCtxt<'_>,
2409    need_migrations: &[NeededMigration],
2410) -> (String, String) {
2411    let need_migrations_variables = need_migrations
2412        .iter()
2413        .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2414        .collect::<Vec<_>>();
2415
2416    let migration_ref_concat =
2417        need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
2418
2419    let migration_string = if 1 == need_migrations.len() {
2420        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let _ = {0}",
                migration_ref_concat))
    })format!("let _ = {migration_ref_concat}")
2421    } else {
2422        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let _ = ({0})",
                migration_ref_concat))
    })format!("let _ = ({migration_ref_concat})")
2423    };
2424
2425    let migrated_variables_concat =
2426        need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", v))
    })format!("`{v}`")).collect::<Vec<_>>().join(", ");
2427
2428    (migration_string, migrated_variables_concat)
2429}
2430
2431/// Helper function to determine if we need to escalate CaptureKind from
2432/// CaptureInfo A to B and returns the escalated CaptureInfo.
2433/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2434///
2435/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2436/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2437///
2438/// It is the caller's duty to figure out which path_expr_id to use.
2439///
2440/// If both the CaptureKind and Expression are considered to be equivalent,
2441/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2442/// expressions reported back to the user as part of diagnostics based on which appears earlier
2443/// in the closure. This can be achieved simply by calling
2444/// `determine_capture_info(existing_info, current_info)`. This works out because the
2445/// expressions that occur earlier in the closure body than the current expression are processed before.
2446/// Consider the following example
2447/// ```rust,no_run
2448/// struct Point { x: i32, y: i32 }
2449/// let mut p = Point { x: 10, y: 10 };
2450///
2451/// let c = || {
2452///     p.x += 10; // E1
2453///     // ...
2454///     // More code
2455///     // ...
2456///     p.x += 10; // E2
2457/// };
2458/// ```
2459/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2460/// and both have an expression associated, however for diagnostics we prefer reporting
2461/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2462/// would've already handled `E1`, and have an existing capture_information for it.
2463/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2464/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2465fn determine_capture_info(
2466    capture_info_a: ty::CaptureInfo,
2467    capture_info_b: ty::CaptureInfo,
2468) -> ty::CaptureInfo {
2469    // If the capture kind is equivalent then, we don't need to escalate and can compare the
2470    // expressions.
2471    let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2472        (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2473        (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2474        (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2475        (ty::UpvarCapture::ByValue, _)
2476        | (ty::UpvarCapture::ByUse, _)
2477        | (ty::UpvarCapture::ByRef(_), _) => false,
2478    };
2479
2480    if eq_capture_kind {
2481        match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2482            (Some(_), _) | (None, None) => capture_info_a,
2483            (None, Some(_)) => capture_info_b,
2484        }
2485    } else {
2486        // We select the CaptureKind which ranks higher based the following priority order:
2487        // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2488        match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2489            (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2490            | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2491                ::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")
2492            }
2493            (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2494            | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2495            | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2496                capture_info_a
2497            }
2498            (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2499                capture_info_b
2500            }
2501            (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2502                match (ref_a, ref_b) {
2503                    // Take LHS:
2504                    (BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2505                    | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
2506
2507                    // Take RHS:
2508                    (BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2509                    | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
2510
2511                    (BorrowKind::Immutable, BorrowKind::Immutable)
2512                    | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2513                    | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2514                        ::rustc_middle::util::bug::bug_fmt(format_args!("Expected unequal capture kinds"));bug!("Expected unequal capture kinds");
2515                    }
2516                }
2517            }
2518        }
2519    }
2520}
2521
2522/// Truncates `place` to have up to `len` projections.
2523/// `curr_mode` is the current required capture kind for the place.
2524/// Returns the truncated `place` and the updated required capture kind.
2525///
2526/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2527/// contained `Deref` of `&mut`.
2528fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2529    place: &mut Place<'tcx>,
2530    curr_mode: &mut ty::UpvarCapture,
2531    len: usize,
2532) {
2533    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));
2534
2535    // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2536    // UniqueImmBorrow
2537    // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2538    // we don't need to worry about that case here.
2539    match curr_mode {
2540        ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2541            for i in len..place.projections.len() {
2542                if place.projections[i].kind == ProjectionKind::Deref
2543                    && is_mut_ref(place.ty_before_projection(i))
2544                {
2545                    *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2546                    break;
2547                }
2548            }
2549        }
2550
2551        ty::UpvarCapture::ByRef(..) => {}
2552        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2553    }
2554
2555    place.projections.truncate(len);
2556}
2557
2558/// Determines the Ancestry relationship of Place A relative to Place B
2559///
2560/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2561/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2562/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2563fn determine_place_ancestry_relation<'tcx>(
2564    place_a: &Place<'tcx>,
2565    place_b: &Place<'tcx>,
2566) -> PlaceAncestryRelation {
2567    // If Place A and Place B don't start off from the same root variable, they are divergent.
2568    if place_a.base != place_b.base {
2569        return PlaceAncestryRelation::Divergent;
2570    }
2571
2572    // Assume of length of projections_a = n
2573    let projections_a = &place_a.projections;
2574
2575    // Assume of length of projections_b = m
2576    let projections_b = &place_b.projections;
2577
2578    let same_initial_projections =
2579        iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
2580
2581    if same_initial_projections {
2582        use std::cmp::Ordering;
2583
2584        // First min(n, m) projections are the same
2585        // Select Ancestor/Descendant
2586        match projections_b.len().cmp(&projections_a.len()) {
2587            Ordering::Greater => PlaceAncestryRelation::Ancestor,
2588            Ordering::Equal => PlaceAncestryRelation::SamePlace,
2589            Ordering::Less => PlaceAncestryRelation::Descendant,
2590        }
2591    } else {
2592        PlaceAncestryRelation::Divergent
2593    }
2594}
2595
2596/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2597/// borrow checking perspective, allowing us to save us on the size of the capture.
2598///
2599///
2600/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2601/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2602/// rightmost deref of the capture if the deref is applied to a shared ref.
2603///
2604/// Reason we only drop the last deref is because of the following edge case:
2605///
2606/// ```
2607/// # struct A { field_of_a: Box<i32> }
2608/// # struct B {}
2609/// # struct C<'a>(&'a i32);
2610/// struct MyStruct<'a> {
2611///    a: &'static A,
2612///    b: B,
2613///    c: C<'a>,
2614/// }
2615///
2616/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2617///     || drop(&*m.a.field_of_a)
2618///     // Here we really do want to capture `*m.a` because that outlives `'static`
2619///
2620///     // If we capture `m`, then the closure no longer outlives `'static`
2621///     // it is constrained to `'a`
2622/// }
2623/// ```
2624x;#[instrument(ret, level = "debug")]
2625fn truncate_capture_for_optimization(
2626    mut place: Place<'_>,
2627    mut curr_mode: ty::UpvarCapture,
2628) -> (Place<'_>, ty::UpvarCapture) {
2629    let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
2630
2631    // Find the rightmost deref (if any). All the projections that come after this
2632    // are fields or other "in-place pointer adjustments"; these refer therefore to
2633    // data owned by whatever pointer is being dereferenced here.
2634    let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
2635
2636    match idx {
2637        // If that pointer is a shared reference, then we don't need those fields.
2638        Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2639            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2640        }
2641        None | Some(_) => {}
2642    }
2643
2644    (place, curr_mode)
2645}
2646
2647/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2648/// `span` is the span of the closure.
2649fn enable_precise_capture(span: Span) -> bool {
2650    // We use span here to ensure that if the closure was generated by a macro with a different
2651    // edition.
2652    span.at_least_rust_2021()
2653}