Skip to main content

rustc_hir_typeck/
upvar.rs

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