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::error_reporting::InferCtxtErrorExt as _;
53use rustc_trait_selection::infer::InferCtxtExt;
54use rustc_trait_selection::solve;
55use tracing::{debug, instrument};
56
57use super::FnCtxt;
58use crate::expr_use_visitor as euv;
59
60/// Describe the relationship between the paths of two places
61/// eg:
62/// - `foo` is ancestor of `foo.bar.baz`
63/// - `foo.bar.baz` is an descendant of `foo.bar`
64/// - `foo.bar` and `foo.baz` are divergent
65enum PlaceAncestryRelation {
66    Ancestor,
67    Descendant,
68    SamePlace,
69    Divergent,
70}
71
72/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
73/// during capture analysis. Information in this map feeds into the minimum capture
74/// analysis pass.
75type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
76
77impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
78    pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
79        InferBorrowKindVisitor { fcx: self }.visit_body(body);
80
81        // it's our job to process these.
82        if !self.deferred_call_resolutions.borrow().is_empty() {
    ::core::panicking::panic("assertion failed: self.deferred_call_resolutions.borrow().is_empty()")
};assert!(self.deferred_call_resolutions.borrow().is_empty());
83    }
84}
85
86/// Intermediate format to store the hir_id pointing to the use that resulted in the
87/// corresponding place being captured and a String which contains the captured value's
88/// name (i.e: a.b.c)
89#[derive(#[automatically_derived]
impl ::core::clone::Clone for UpvarMigrationInfo {
    #[inline]
    fn clone(&self) -> UpvarMigrationInfo {
        match self {
            UpvarMigrationInfo::CapturingPrecise {
                source_expr: __self_0, var_name: __self_1 } =>
                UpvarMigrationInfo::CapturingPrecise {
                    source_expr: ::core::clone::Clone::clone(__self_0),
                    var_name: ::core::clone::Clone::clone(__self_1),
                },
            UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
                UpvarMigrationInfo::CapturingNothing {
                    use_span: ::core::clone::Clone::clone(__self_0),
                },
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for UpvarMigrationInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            UpvarMigrationInfo::CapturingPrecise {
                source_expr: __self_0, var_name: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "CapturingPrecise", "source_expr", __self_0, "var_name",
                    &__self_1),
            UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "CapturingNothing", "use_span", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for UpvarMigrationInfo {
    #[inline]
    fn eq(&self, other: &UpvarMigrationInfo) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (UpvarMigrationInfo::CapturingPrecise {
                    source_expr: __self_0, var_name: __self_1 },
                    UpvarMigrationInfo::CapturingPrecise {
                    source_expr: __arg1_0, var_name: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (UpvarMigrationInfo::CapturingNothing { use_span: __self_0 },
                    UpvarMigrationInfo::CapturingNothing { use_span: __arg1_0 })
                    => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for UpvarMigrationInfo {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<HirId>>;
        let _: ::core::cmp::AssertParamIsEq<String>;
        let _: ::core::cmp::AssertParamIsEq<Span>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for UpvarMigrationInfo {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            UpvarMigrationInfo::CapturingPrecise {
                source_expr: __self_0, var_name: __self_1 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash)]
90enum UpvarMigrationInfo {
91    /// We previously captured all of `x`, but now we capture some sub-path.
92    CapturingPrecise { source_expr: Option<HirId>, var_name: String },
93    CapturingNothing {
94        // where the variable appears in the closure (but is not captured)
95        use_span: Span,
96    },
97}
98
99/// Reasons that we might issue a migration warning.
100#[derive(#[automatically_derived]
impl ::core::clone::Clone for MigrationWarningReason {
    #[inline]
    fn clone(&self) -> MigrationWarningReason {
        MigrationWarningReason {
            auto_traits: ::core::clone::Clone::clone(&self.auto_traits),
            drop_order: ::core::clone::Clone::clone(&self.drop_order),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for MigrationWarningReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "MigrationWarningReason", "auto_traits", &self.auto_traits,
            "drop_order", &&self.drop_order)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for MigrationWarningReason {
    #[inline]
    fn default() -> MigrationWarningReason {
        MigrationWarningReason {
            auto_traits: ::core::default::Default::default(),
            drop_order: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl ::core::cmp::PartialEq for MigrationWarningReason {
    #[inline]
    fn eq(&self, other: &MigrationWarningReason) -> bool {
        self.drop_order == other.drop_order &&
            self.auto_traits == other.auto_traits
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MigrationWarningReason {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Vec<&'static str>>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MigrationWarningReason {
    #[inline]
    fn partial_cmp(&self, other: &MigrationWarningReason)
        -> ::core::option::Option<::core::cmp::Ordering> {
        match ::core::cmp::PartialOrd::partial_cmp(&self.auto_traits,
                &other.auto_traits) {
            ::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
                ::core::cmp::PartialOrd::partial_cmp(&self.drop_order,
                    &other.drop_order),
            cmp => cmp,
        }
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MigrationWarningReason {
    #[inline]
    fn cmp(&self, other: &MigrationWarningReason) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.auto_traits, &other.auto_traits) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.drop_order, &other.drop_order),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::hash::Hash for MigrationWarningReason {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.auto_traits, state);
        ::core::hash::Hash::hash(&self.drop_order, state)
    }
}Hash)]
101struct MigrationWarningReason {
102    /// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
103    /// in this vec, but now we don't.
104    auto_traits: Vec<&'static str>,
105
106    /// When we used to capture `x` in its entirety, we would execute some destructors
107    /// at a different time.
108    drop_order: bool,
109}
110
111impl MigrationWarningReason {
112    fn migration_message(&self) -> String {
113        let base = "changes to closure capture in Rust 2021 will affect";
114        if !self.auto_traits.is_empty() && self.drop_order {
115            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} drop order and which traits the closure implements",
                base))
    })format!("{base} drop order and which traits the closure implements")
116        } else if self.drop_order {
117            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} drop order", base))
    })format!("{base} drop order")
118        } else {
119            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} which traits the closure implements",
                base))
    })format!("{base} which traits the closure implements")
120        }
121    }
122}
123
124/// Intermediate format to store information needed to generate a note in the migration lint.
125struct MigrationLintNote {
126    captures_info: UpvarMigrationInfo,
127
128    /// reasons why migration is needed for this capture
129    reason: MigrationWarningReason,
130}
131
132/// Intermediate format to store the hir id of the root variable and a HashSet containing
133/// information on why the root variable should be fully captured
134struct NeededMigration {
135    var_hir_id: HirId,
136    diagnostics_info: Vec<MigrationLintNote>,
137}
138
139struct InferBorrowKindVisitor<'a, 'tcx> {
140    fcx: &'a FnCtxt<'a, 'tcx>,
141}
142
143impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
144    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
145        match expr.kind {
146            hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
147                let body = self.fcx.tcx.hir_body(body_id);
148                self.visit_body(body);
149                self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
150            }
151            _ => {}
152        }
153
154        intravisit::walk_expr(self, expr);
155    }
156
157    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
158        let body = self.fcx.tcx.hir_body(c.body);
159        self.visit_body(body);
160    }
161}
162
163impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
164    /// Analysis starting point.
165    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("analyze_closure",
                                    "rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
                                    ::tracing_core::__macro_support::Option::Some(165u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
                                    ::tracing_core::field::FieldSet::new(&["closure_hir_id",
                                                    "span", "body_id", "capture_clause"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_hir_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_clause)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let PlaceBase::Upvar(upvar_id) =
                place_with_id.place.base else { return };
            match (&self.closure_def_id, &upvar_id.closure_expr_id) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            let capture_kind = ty::UpvarCapture::ByRef(bk);
            let span = self.fcx.tcx.hir_span(diag_expr_id);
            let place =
                self.fcx.normalize_capture_place(span,
                    place_with_id.place.clone());
            let (place, mut capture_kind) =
                restrict_repr_packed_field_ref_capture(place, capture_kind);
            if place.deref_tys().any(Ty::is_raw_ptr) {
                capture_kind =
                    ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
            }
            self.capture_information.push((place,
                    ty::CaptureInfo {
                        capture_kind_expr_id: Some(diag_expr_id),
                        path_expr_id: Some(diag_expr_id),
                        capture_kind,
                    }));
        }
    }
}#[instrument(skip(self), level = "debug")]
2182    fn borrow(
2183        &mut self,
2184        place_with_id: &PlaceWithHirId<'tcx>,
2185        diag_expr_id: HirId,
2186        bk: ty::BorrowKind,
2187    ) {
2188        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2189        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2190
2191        // The region here will get discarded/ignored
2192        let capture_kind = ty::UpvarCapture::ByRef(bk);
2193
2194        let span = self.fcx.tcx.hir_span(diag_expr_id);
2195        let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
2196
2197        // We only want repr packed restriction to be applied to reading references into a packed
2198        // struct, and not when the data is being moved. Therefore we call this method here instead
2199        // of in `restrict_capture_precision`.
2200        let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(place, capture_kind);
2201
2202        // Raw pointers don't inherit mutability
2203        if place.deref_tys().any(Ty::is_raw_ptr) {
2204            capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2205        }
2206
2207        self.capture_information.push((
2208            place,
2209            ty::CaptureInfo {
2210                capture_kind_expr_id: Some(diag_expr_id),
2211                path_expr_id: Some(diag_expr_id),
2212                capture_kind,
2213            },
2214        ));
2215    }
2216
2217    #[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(2217u32),
                                    ::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")]
2218    fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2219        self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2220    }
2221}
2222
2223/// Rust doesn't permit moving fields out of a type that implements drop
2224x;#[instrument(skip(fcx), ret, level = "debug")]
2225fn restrict_precision_for_drop_types<'a, 'tcx>(
2226    fcx: &'a FnCtxt<'a, 'tcx>,
2227    mut place: Place<'tcx>,
2228    mut curr_mode: ty::UpvarCapture,
2229) -> (Place<'tcx>, ty::UpvarCapture) {
2230    let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
2231
2232    if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2233        for i in 0..place.projections.len() {
2234            match place.ty_before_projection(i).kind() {
2235                ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2236                    truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2237                    break;
2238                }
2239                _ => {}
2240            }
2241        }
2242    }
2243
2244    (place, curr_mode)
2245}
2246
2247/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2248/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2249///   them completely.
2250/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2251fn restrict_precision_for_unsafe(
2252    mut place: Place<'_>,
2253    mut curr_mode: ty::UpvarCapture,
2254) -> (Place<'_>, ty::UpvarCapture) {
2255    if place.base_ty.is_raw_ptr() {
2256        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2257    }
2258
2259    if place.base_ty.is_union() {
2260        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2261    }
2262
2263    for (i, proj) in place.projections.iter().enumerate() {
2264        if proj.ty.is_raw_ptr() {
2265            // Don't apply any projections on top of a raw ptr.
2266            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2267            break;
2268        }
2269
2270        if proj.ty.is_union() {
2271            // Don't capture precise fields of a union.
2272            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2273            break;
2274        }
2275    }
2276
2277    (place, curr_mode)
2278}
2279
2280/// Truncate projections so that the following rules are obeyed by the captured `place`:
2281/// - No Index projections are captured, since arrays are captured completely.
2282/// - No unsafe block is required to capture `place`.
2283///
2284/// Returns the truncated place and updated capture mode.
2285x;#[instrument(ret, level = "debug")]
2286fn restrict_capture_precision(
2287    place: Place<'_>,
2288    curr_mode: ty::UpvarCapture,
2289) -> (Place<'_>, ty::UpvarCapture) {
2290    let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
2291
2292    if place.projections.is_empty() {
2293        // Nothing to do here
2294        return (place, curr_mode);
2295    }
2296
2297    for (i, proj) in place.projections.iter().enumerate() {
2298        match proj.kind {
2299            ProjectionKind::Index | ProjectionKind::Subslice => {
2300                // Arrays are completely captured, so we drop Index and Subslice projections
2301                truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2302                return (place, curr_mode);
2303            }
2304            ProjectionKind::Deref => {}
2305            ProjectionKind::OpaqueCast => {}
2306            ProjectionKind::Field(..) => {}
2307            ProjectionKind::UnwrapUnsafeBinder => {}
2308        }
2309    }
2310
2311    (place, curr_mode)
2312}
2313
2314/// Truncate deref of any reference.
2315x;#[instrument(ret, level = "debug")]
2316fn adjust_for_move_closure(
2317    mut place: Place<'_>,
2318    mut kind: ty::UpvarCapture,
2319) -> (Place<'_>, ty::UpvarCapture) {
2320    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2321
2322    if let Some(idx) = first_deref {
2323        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2324    }
2325
2326    (place, ty::UpvarCapture::ByValue)
2327}
2328
2329/// Truncate deref of any reference.
2330x;#[instrument(ret, level = "debug")]
2331fn adjust_for_use_closure(
2332    mut place: Place<'_>,
2333    mut kind: ty::UpvarCapture,
2334) -> (Place<'_>, ty::UpvarCapture) {
2335    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2336
2337    if let Some(idx) = first_deref {
2338        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2339    }
2340
2341    (place, ty::UpvarCapture::ByUse)
2342}
2343
2344/// Adjust closure capture just that if taking ownership of data, only move data
2345/// from enclosing stack frame.
2346x;#[instrument(ret, level = "debug")]
2347fn adjust_for_non_move_closure(
2348    mut place: Place<'_>,
2349    mut kind: ty::UpvarCapture,
2350) -> (Place<'_>, ty::UpvarCapture) {
2351    let contains_deref =
2352        place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2353
2354    match kind {
2355        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2356            if let Some(idx) = contains_deref {
2357                truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2358            }
2359        }
2360
2361        ty::UpvarCapture::ByRef(..) => {}
2362    }
2363
2364    (place, kind)
2365}
2366
2367fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2368    let variable_name = match place.base {
2369        PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2370        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Capture_information should only contain upvars"))bug!("Capture_information should only contain upvars"),
2371    };
2372
2373    let mut projections_str = String::new();
2374    for (i, item) in place.projections.iter().enumerate() {
2375        let proj = match item.kind {
2376            ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
    })format!("({a:?}, {b:?})"),
2377            ProjectionKind::Deref => String::from("Deref"),
2378            ProjectionKind::Index => String::from("Index"),
2379            ProjectionKind::Subslice => String::from("Subslice"),
2380            ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2381            ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2382        };
2383        if i != 0 {
2384            projections_str.push(',');
2385        }
2386        projections_str.push_str(proj.as_str());
2387    }
2388
2389    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
                projections_str))
    })format!("{variable_name}[{projections_str}]")
2390}
2391
2392fn construct_capture_kind_reason_string<'tcx>(
2393    tcx: TyCtxt<'_>,
2394    place: &Place<'tcx>,
2395    capture_info: &ty::CaptureInfo,
2396) -> String {
2397    let place_str = construct_place_string(tcx, place);
2398
2399    let capture_kind_str = match capture_info.capture_kind {
2400        ty::UpvarCapture::ByValue => "ByValue".into(),
2401        ty::UpvarCapture::ByUse => "ByUse".into(),
2402        ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
2403    };
2404
2405    ::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")
2406}
2407
2408fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2409    let place_str = construct_place_string(tcx, place);
2410
2411    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} used here", place_str))
    })format!("{place_str} used here")
2412}
2413
2414fn construct_capture_info_string<'tcx>(
2415    tcx: TyCtxt<'_>,
2416    place: &Place<'tcx>,
2417    capture_info: &ty::CaptureInfo,
2418) -> String {
2419    let place_str = construct_place_string(tcx, place);
2420
2421    let capture_kind_str = match capture_info.capture_kind {
2422        ty::UpvarCapture::ByValue => "ByValue".into(),
2423        ty::UpvarCapture::ByUse => "ByUse".into(),
2424        ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
2425    };
2426    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
                capture_kind_str))
    })format!("{place_str} -> {capture_kind_str}")
2427}
2428
2429fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2430    tcx.hir_name(var_hir_id)
2431}
2432
2433#[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(2433u32),
                                    ::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))]
2434fn should_do_rust_2021_incompatible_closure_captures_analysis(
2435    tcx: TyCtxt<'_>,
2436    closure_id: HirId,
2437) -> bool {
2438    if tcx.sess.at_least_rust_2021() {
2439        return false;
2440    }
2441
2442    let level = tcx
2443        .lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2444        .level;
2445
2446    !matches!(level, lint::Level::Allow)
2447}
2448
2449/// Return a two string tuple (s1, s2)
2450/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2451/// - s2: Comma separated names of the variables being migrated.
2452fn migration_suggestion_for_2229(
2453    tcx: TyCtxt<'_>,
2454    need_migrations: &[NeededMigration],
2455) -> (String, String) {
2456    let need_migrations_variables = need_migrations
2457        .iter()
2458        .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2459        .collect::<Vec<_>>();
2460
2461    let migration_ref_concat =
2462        need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
2463
2464    let migration_string = if 1 == need_migrations.len() {
2465        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let _ = {0}",
                migration_ref_concat))
    })format!("let _ = {migration_ref_concat}")
2466    } else {
2467        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let _ = ({0})",
                migration_ref_concat))
    })format!("let _ = ({migration_ref_concat})")
2468    };
2469
2470    let migrated_variables_concat =
2471        need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", v))
    })format!("`{v}`")).collect::<Vec<_>>().join(", ");
2472
2473    (migration_string, migrated_variables_concat)
2474}
2475
2476/// Helper function to determine if we need to escalate CaptureKind from
2477/// CaptureInfo A to B and returns the escalated CaptureInfo.
2478/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2479///
2480/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2481/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2482///
2483/// It is the caller's duty to figure out which path_expr_id to use.
2484///
2485/// If both the CaptureKind and Expression are considered to be equivalent,
2486/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2487/// expressions reported back to the user as part of diagnostics based on which appears earlier
2488/// in the closure. This can be achieved simply by calling
2489/// `determine_capture_info(existing_info, current_info)`. This works out because the
2490/// expressions that occur earlier in the closure body than the current expression are processed before.
2491/// Consider the following example
2492/// ```rust,no_run
2493/// struct Point { x: i32, y: i32 }
2494/// let mut p = Point { x: 10, y: 10 };
2495///
2496/// let c = || {
2497///     p.x += 10; // E1
2498///     // ...
2499///     // More code
2500///     // ...
2501///     p.x += 10; // E2
2502/// };
2503/// ```
2504/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2505/// and both have an expression associated, however for diagnostics we prefer reporting
2506/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2507/// would've already handled `E1`, and have an existing capture_information for it.
2508/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2509/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2510fn determine_capture_info(
2511    capture_info_a: ty::CaptureInfo,
2512    capture_info_b: ty::CaptureInfo,
2513) -> ty::CaptureInfo {
2514    // If the capture kind is equivalent then, we don't need to escalate and can compare the
2515    // expressions.
2516    let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2517        (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2518        (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2519        (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2520        (ty::UpvarCapture::ByValue, _)
2521        | (ty::UpvarCapture::ByUse, _)
2522        | (ty::UpvarCapture::ByRef(_), _) => false,
2523    };
2524
2525    if eq_capture_kind {
2526        match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2527            (Some(_), _) | (None, None) => capture_info_a,
2528            (None, Some(_)) => capture_info_b,
2529        }
2530    } else {
2531        // We select the CaptureKind which ranks higher based the following priority order:
2532        // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2533        match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2534            (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2535            | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2536                ::rustc_middle::util::bug::bug_fmt(format_args!("Same capture can\'t be ByUse and ByValue at the same time"))bug!("Same capture can't be ByUse and ByValue at the same time")
2537            }
2538            (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2539            | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2540            | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2541                capture_info_a
2542            }
2543            (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2544                capture_info_b
2545            }
2546            (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2547                match (ref_a, ref_b) {
2548                    // Take LHS:
2549                    (BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2550                    | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
2551
2552                    // Take RHS:
2553                    (BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2554                    | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
2555
2556                    (BorrowKind::Immutable, BorrowKind::Immutable)
2557                    | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2558                    | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2559                        ::rustc_middle::util::bug::bug_fmt(format_args!("Expected unequal capture kinds"));bug!("Expected unequal capture kinds");
2560                    }
2561                }
2562            }
2563        }
2564    }
2565}
2566
2567/// Truncates `place` to have up to `len` projections.
2568/// `curr_mode` is the current required capture kind for the place.
2569/// Returns the truncated `place` and the updated required capture kind.
2570///
2571/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2572/// contained `Deref` of `&mut`.
2573fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2574    place: &mut Place<'tcx>,
2575    curr_mode: &mut ty::UpvarCapture,
2576    len: usize,
2577) {
2578    let is_mut_ref = |ty: Ty<'_>| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Ref(.., hir::Mutability::Mut) => true,
    _ => false,
}matches!(ty.kind(), ty::Ref(.., hir::Mutability::Mut));
2579
2580    // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2581    // UniqueImmBorrow
2582    // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2583    // we don't need to worry about that case here.
2584    match curr_mode {
2585        ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2586            for i in len..place.projections.len() {
2587                if place.projections[i].kind == ProjectionKind::Deref
2588                    && is_mut_ref(place.ty_before_projection(i))
2589                {
2590                    *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2591                    break;
2592                }
2593            }
2594        }
2595
2596        ty::UpvarCapture::ByRef(..) => {}
2597        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2598    }
2599
2600    place.projections.truncate(len);
2601}
2602
2603/// Determines the Ancestry relationship of Place A relative to Place B
2604///
2605/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2606/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2607/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2608fn determine_place_ancestry_relation<'tcx>(
2609    place_a: &Place<'tcx>,
2610    place_b: &Place<'tcx>,
2611) -> PlaceAncestryRelation {
2612    // If Place A and Place B don't start off from the same root variable, they are divergent.
2613    if place_a.base != place_b.base {
2614        return PlaceAncestryRelation::Divergent;
2615    }
2616
2617    // Assume of length of projections_a = n
2618    let projections_a = &place_a.projections;
2619
2620    // Assume of length of projections_b = m
2621    let projections_b = &place_b.projections;
2622
2623    let same_initial_projections =
2624        iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
2625
2626    if same_initial_projections {
2627        use std::cmp::Ordering;
2628
2629        // First min(n, m) projections are the same
2630        // Select Ancestor/Descendant
2631        match projections_b.len().cmp(&projections_a.len()) {
2632            Ordering::Greater => PlaceAncestryRelation::Ancestor,
2633            Ordering::Equal => PlaceAncestryRelation::SamePlace,
2634            Ordering::Less => PlaceAncestryRelation::Descendant,
2635        }
2636    } else {
2637        PlaceAncestryRelation::Divergent
2638    }
2639}
2640
2641/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2642/// borrow checking perspective, allowing us to save us on the size of the capture.
2643///
2644///
2645/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2646/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2647/// rightmost deref of the capture if the deref is applied to a shared ref.
2648///
2649/// Reason we only drop the last deref is because of the following edge case:
2650///
2651/// ```
2652/// # struct A { field_of_a: Box<i32> }
2653/// # struct B {}
2654/// # struct C<'a>(&'a i32);
2655/// struct MyStruct<'a> {
2656///    a: &'static A,
2657///    b: B,
2658///    c: C<'a>,
2659/// }
2660///
2661/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2662///     || drop(&*m.a.field_of_a)
2663///     // Here we really do want to capture `*m.a` because that outlives `'static`
2664///
2665///     // If we capture `m`, then the closure no longer outlives `'static`
2666///     // it is constrained to `'a`
2667/// }
2668/// ```
2669x;#[instrument(ret, level = "debug")]
2670fn truncate_capture_for_optimization(
2671    mut place: Place<'_>,
2672    mut curr_mode: ty::UpvarCapture,
2673) -> (Place<'_>, ty::UpvarCapture) {
2674    let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
2675
2676    // Find the rightmost deref (if any). All the projections that come after this
2677    // are fields or other "in-place pointer adjustments"; these refer therefore to
2678    // data owned by whatever pointer is being dereferenced here.
2679    let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
2680
2681    match idx {
2682        // If that pointer is a shared reference, then we don't need those fields.
2683        Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2684            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2685        }
2686        None | Some(_) => {}
2687    }
2688
2689    (place, curr_mode)
2690}
2691
2692/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2693/// `span` is the span of the closure.
2694fn enable_precise_capture(span: Span) -> bool {
2695    // We use span here to ensure that if the closure was generated by a macro with a different
2696    // edition.
2697    span.at_least_rust_2021()
2698}