Skip to main content

rustc_borrowck/diagnostics/
mod.rs

1//! Borrow checker diagnostics.
2
3use std::collections::BTreeMap;
4
5use rustc_abi::{FieldIdx, VariantIdx};
6use rustc_data_structures::fx::FxIndexMap;
7use rustc_errors::formatting::DiagMessageAddArg;
8use rustc_errors::{Applicability, Diag, DiagMessage, MultiSpan, listify, msg};
9use rustc_hir::attrs::lang_items::LangItem;
10use rustc_hir::def::{CtorKind, Namespace};
11use rustc_hir::{
12    self as hir, CoroutineKind, GenericBound, WhereBoundPredicate, WherePredicateKind,
13};
14use rustc_index::{IndexSlice, IndexVec};
15use rustc_infer::infer::{BoundRegionConversionTime, NllRegionVariableOrigin};
16use rustc_infer::traits::SelectionError;
17use rustc_middle::mir::{
18    AggregateKind, CallSource, ConstOperand, ConstraintCategory, FakeReadCause, Local, LocalInfo,
19    LocalKind, Location, Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement,
20    StatementKind, Terminator, TerminatorKind, VarDebugInfoContents, find_self_call,
21};
22use rustc_middle::ty::print::{Print, with_no_trimmed_paths};
23use rustc_middle::ty::{self, Ty, TyCtxt};
24use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveOutIndex};
25use rustc_span::def_id::LocalDefId;
26use rustc_span::{DUMMY_SP, Span, Spanned, Symbol, bug, span_bug, sym};
27use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
28use rustc_trait_selection::error_reporting::traits::call_kind::{CallDesugaringKind, call_kind};
29use rustc_trait_selection::infer::InferCtxtExt;
30use rustc_trait_selection::traits::{
31    FulfillmentError, FulfillmentErrorCode, type_known_to_meet_bound_modulo_regions,
32};
33use tracing::debug;
34
35use super::MirBorrowckCtxt;
36use super::borrow_set::BorrowData;
37use crate::LocalMutationIsAllowed;
38use crate::constraints::OutlivesConstraint;
39use crate::nll::ConstraintDescription;
40use crate::session_diagnostics::{
41    CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause,
42    CaptureVarKind, CaptureVarPathUseCause, OnClosureNote,
43};
44
45mod find_all_local_uses;
46mod find_use;
47mod outlives_suggestion;
48mod region_name;
49mod var_name;
50
51mod bound_region_errors;
52mod conflict_errors;
53mod explain_borrow;
54mod move_errors;
55mod mutability_errors;
56mod opaque_types;
57mod region_errors;
58
59pub(crate) use bound_region_errors::{ToUniverseInfo, UniverseInfo};
60pub(crate) use move_errors::{IllegalMoveOriginKind, MoveError};
61pub(crate) use mutability_errors::AccessKind;
62pub(crate) use outlives_suggestion::OutlivesSuggestionBuilder;
63pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
64pub(crate) use region_name::{RegionName, RegionNameSource};
65pub(crate) use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
66
67pub(super) struct DescribePlaceOpt {
68    including_downcast: bool,
69
70    /// Enable/Disable tuple fields.
71    /// For example `x` tuple. if it's `true` `x.0`. Otherwise `x`
72    including_tuple_field: bool,
73}
74
75pub(super) struct IncludingTupleField(pub(super) bool);
76
77#[derive(#[automatically_derived]
impl<'diag, 'tcx> ::core::default::Default for
    BorrowckDiagnosticsBuffer<'diag, 'tcx> {
    #[inline]
    fn default() -> Self {
        Self {
            buffered_move_errors: ::core::default::Default::default(),
            buffered_mut_errors: ::core::default::Default::default(),
            buffered_diags: ::core::default::Default::default(),
        }
    }
}Default)]
78pub(crate) struct BorrowckDiagnosticsBuffer<'diag, 'tcx> {
79    /// This field keeps track of move errors that are to be reported for given move indices.
80    ///
81    /// There are situations where many errors can be reported for a single move out (see
82    /// #53807) and we want only the best of those errors.
83    ///
84    /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
85    /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of
86    /// the `Place` of the previous most diagnostic. This happens instead of buffering the
87    /// error. Once all move errors have been reported, any diagnostics in this map are added
88    /// to the buffer to be emitted.
89    ///
90    /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
91    /// when errors in the map are being re-added to the error buffer so that errors with the
92    /// same primary span come out in a consistent order.
93    buffered_move_errors: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, Diag<'diag>)>,
94
95    buffered_mut_errors: FxIndexMap<Span, (Diag<'diag>, usize)>,
96
97    /// Buffer of diagnostics to be reported. Each one is paired with a span for sorting purposes;
98    /// by default it's the primary span.
99    buffered_diags: Vec<(Span, Diag<'diag>)>,
100}
101
102impl<'diag, 'tcx> BorrowckDiagnosticsBuffer<'diag, 'tcx> {
103    pub(crate) fn buffer_error(&mut self, diag: Diag<'diag>) {
104        let sort_span = diag.span.primary_span().unwrap_or(DUMMY_SP);
105        self.buffered_diags.push((sort_span, diag));
106    }
107
108    pub(crate) fn buffer_error_with_sort_span(&mut self, diag: Diag<'diag>, sort_span: Span) {
109        self.buffered_diags.push((sort_span, diag));
110    }
111
112    pub(crate) fn emit_errors(&mut self) {
113        // Buffer any move errors that we collected and de-duplicated.
114        for (_, (_, diag)) in std::mem::take(&mut self.buffered_move_errors) {
115            // We have already set tainted for this error, so just buffer it.
116            self.buffer_error(diag);
117        }
118        for (_, (mut diag, count)) in std::mem::take(&mut self.buffered_mut_errors) {
119            if count > 10 {
120                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("...and {0} other attempted mutable borrows",
                count - 10))
    })format!("...and {} other attempted mutable borrows", count - 10));
121            }
122            self.buffer_error(diag);
123        }
124
125        if !self.buffered_diags.is_empty() {
126            self.buffered_diags.sort_by_key(|(sort_span, _)| *sort_span);
127            for (_, diag) in self.buffered_diags.drain(..) {
128                diag.emit();
129            }
130        }
131    }
132}
133
134impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> {
135    pub(crate) fn buffer_error(&mut self, diag: Diag<'_>) {
136        self.diags_buffer.buffer_error(diag.with_dcx(self.dcx()));
137    }
138
139    pub(crate) fn buffer_error_with_sort_span(&mut self, diag: Diag<'_>, sort_span: Span) {
140        self.diags_buffer.buffer_error_with_sort_span(diag.with_dcx(self.dcx()), sort_span);
141    }
142
143    pub(crate) fn buffer_move_error(
144        &mut self,
145        move_out_indices: Vec<MoveOutIndex>,
146        place_and_err: (PlaceRef<'tcx>, Diag<'diag>),
147    ) -> bool {
148        if let Some((_, diag)) =
149            self.diags_buffer.buffered_move_errors.insert(move_out_indices, place_and_err)
150        {
151            // Cancel the old diagnostic so we don't ICE
152            diag.cancel();
153            false
154        } else {
155            true
156        }
157    }
158
159    pub(crate) fn get_buffered_mut_error(&mut self, span: Span) -> Option<(Diag<'diag>, usize)> {
160        // FIXME(#120456) - is `swap_remove` correct?
161        self.diags_buffer.buffered_mut_errors.swap_remove(&span)
162    }
163
164    pub(crate) fn buffer_mut_error(&mut self, span: Span, diag: Diag<'diag>, count: usize) {
165        self.diags_buffer.buffered_mut_errors.insert(span, (diag, count));
166    }
167
168    pub(crate) fn has_buffered_diags(&self) -> bool {
169        self.diags_buffer.buffered_diags.is_empty()
170    }
171
172    pub(crate) fn has_move_error(
173        &self,
174        move_out_indices: &[MoveOutIndex],
175    ) -> Option<&(PlaceRef<'tcx>, Diag<'diag>)> {
176        self.diags_buffer.buffered_move_errors.get(move_out_indices)
177    }
178
179    /// Uses `body.var_debug_info` to find the symbol
180    fn local_name(&self, index: Local) -> Option<Symbol> {
181        *self.local_names().get(index)?
182    }
183
184    fn local_names(&self) -> &IndexSlice<Local, Option<Symbol>> {
185        self.local_names.get_or_init(|| {
186            let mut local_names = IndexVec::from_elem(None, &self.body.local_decls);
187            for var_debug_info in &self.body.var_debug_info {
188                if let VarDebugInfoContents::Place(place) = var_debug_info.value {
189                    if let Some(local) = place.as_local() {
190                        if let Some(prev_name) = local_names[local]
191                            && var_debug_info.name != prev_name
192                        {
193                            ::rustc_span::macros::bug_impl(Some(var_debug_info.source_info.span),
    format_args!("local {0:?} has many names (`{1}` vs `{2}`)", local,
        prev_name, var_debug_info.name), Location::caller());span_bug!(
194                                var_debug_info.source_info.span,
195                                "local {:?} has many names (`{}` vs `{}`)",
196                                local,
197                                prev_name,
198                                var_debug_info.name
199                            );
200                        }
201                        local_names[local] = Some(var_debug_info.name);
202                    }
203                }
204            }
205            local_names
206        })
207    }
208}
209
210impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
211    /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
212    /// is moved after being invoked.
213    ///
214    /// ```text
215    /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
216    ///       its environment
217    ///   --> $DIR/issue-42065.rs:16:29
218    ///    |
219    /// LL |         for (key, value) in dict {
220    ///    |                             ^^^^
221    /// ```
222    pub(super) fn add_moved_or_invoked_closure_note(
223        &self,
224        location: Location,
225        place: PlaceRef<'tcx>,
226        diag: &mut Diag<'_>,
227    ) -> bool {
228        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:228",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(228u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_moved_or_invoked_closure_note: location={0:?} place={1:?}",
                                                    location, place) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
229        let mut target = place.local_or_deref_local();
230        for stmt in &self.body[location.block].statements[location.statement_index..] {
231            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:231",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(231u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_moved_or_invoked_closure_note: stmt={0:?} target={1:?}",
                                                    stmt, target) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
232            if let StatementKind::Assign((into, Rvalue::Use(from, _))) = &stmt.kind {
233                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:233",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(233u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_fnonce_closure_note: into={0:?} from={1:?}",
                                                    into, from) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
234                match from {
235                    Operand::Copy(place) | Operand::Move(place)
236                        if target == place.local_or_deref_local() =>
237                    {
238                        target = into.local_or_deref_local()
239                    }
240                    _ => {}
241                }
242            }
243        }
244
245        // Check if we are attempting to call a closure after it has been invoked.
246        let terminator = self.body[location.block].terminator();
247        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:247",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(247u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_moved_or_invoked_closure_note: terminator={0:?}",
                                                    terminator) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
248        if let TerminatorKind::Call {
249            func: Operand::Constant(ConstOperand { const_, .. }),
250            args,
251            ..
252        } = &terminator.kind
253            && let ty::FnDef(id, _) = *const_.ty().kind()
254        {
255            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:255",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(255u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_moved_or_invoked_closure_note: id={0:?}",
                                                    id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_moved_or_invoked_closure_note: id={:?}", id);
256            if self.infcx.tcx.is_lang_item(self.infcx.tcx.parent(id), LangItem::FnOnce) {
257                let closure = match args.first() {
258                    Some(Spanned { node: Operand::Copy(place) | Operand::Move(place), .. })
259                        if target == place.local_or_deref_local() =>
260                    {
261                        place.local_or_deref_local().unwrap()
262                    }
263                    _ => return false,
264                };
265
266                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:266",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(266u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_moved_or_invoked_closure_note: closure={0:?}",
                                                    closure) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
267                if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {
268                    let did = did.expect_local();
269                    if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
270                        diag.subdiagnostic(OnClosureNote::InvokedTwice {
271                            place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
272                            span: *span,
273                        });
274                        return true;
275                    }
276                }
277            }
278        }
279
280        // Check if we are just moving a closure after it has been invoked.
281        if let Some(target) = target
282            && let ty::Closure(did, _) = self.body.local_decls[target].ty.kind()
283        {
284            let did = did.expect_local();
285            if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
286                diag.subdiagnostic(OnClosureNote::MovedTwice {
287                    place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
288                    span: *span,
289                });
290                return true;
291            }
292        }
293        false
294    }
295
296    /// End-user visible description of `place` if one can be found.
297    /// If the place is a temporary for instance, `"value"` will be returned.
298    pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {
299        match self.describe_place(place_ref) {
300            Some(mut descr) => {
301                // Surround descr with `backticks`.
302                descr.reserve(2);
303                descr.insert(0, '`');
304                descr.push('`');
305                descr
306            }
307            None => "value".to_string(),
308        }
309    }
310
311    /// End-user visible description of `place` if one can be found.
312    /// If the place is a temporary for instance, `None` will be returned.
313    pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {
314        self.describe_place_with_options(
315            place_ref,
316            DescribePlaceOpt { including_downcast: false, including_tuple_field: true },
317        )
318    }
319
320    /// End-user visible description of `place` if one can be found. If the place is a temporary
321    /// for instance, `None` will be returned.
322    /// `IncludingDowncast` parameter makes the function return `None` if `ProjectionElem` is
323    /// `Downcast` and `IncludingDowncast` is true
324    pub(super) fn describe_place_with_options(
325        &self,
326        place: PlaceRef<'tcx>,
327        opt: DescribePlaceOpt,
328    ) -> Option<String> {
329        let local = place.local;
330        if self.body.local_decls[local]
331            .source_info
332            .span
333            .in_external_macro(self.infcx.tcx.sess.source_map())
334        {
335            return None;
336        }
337
338        let mut autoderef_index = None;
339        let mut buf = String::new();
340        let mut ok = self.append_local_to_string(local, &mut buf);
341
342        for (index, elem) in place.projection.into_iter().enumerate() {
343            match elem {
344                ProjectionElem::Deref => {
345                    if index == 0 {
346                        if self.body.local_decls[local].is_ref_for_guard() {
347                            continue;
348                        }
349                        if let LocalInfo::StaticRef { def_id, .. } =
350                            *self.body.local_decls[local].local_info()
351                        {
352                            buf.push_str(self.infcx.tcx.item_name(def_id).as_str());
353                            ok = Ok(());
354                            continue;
355                        }
356                    }
357                    if let Some(field) = self.is_upvar_field_projection(PlaceRef {
358                        local,
359                        projection: place.projection.split_at(index + 1).0,
360                    }) {
361                        let var_index = field.index();
362                        buf = self.upvars[var_index].to_string(self.infcx.tcx);
363                        ok = Ok(());
364                        if !self.upvars[var_index].is_by_ref() {
365                            buf.insert(0, '*');
366                        }
367                    } else {
368                        if autoderef_index.is_none() {
369                            autoderef_index = match place.projection.iter().rposition(|elem| {
370                                !#[allow(non_exhaustive_omitted_patterns)] match elem {
    ProjectionElem::Deref | ProjectionElem::Downcast(..) => true,
    _ => false,
}matches!(
371                                    elem,
372                                    ProjectionElem::Deref | ProjectionElem::Downcast(..)
373                                )
374                            }) {
375                                Some(index) => Some(index + 1),
376                                None => Some(0),
377                            };
378                        }
379                        if index >= autoderef_index.unwrap() {
380                            buf.insert(0, '*');
381                        }
382                    }
383                }
384                ProjectionElem::PhantomDeref => (),
385                ProjectionElem::Downcast(..) if opt.including_downcast => return None,
386                ProjectionElem::Downcast(..) => (),
387                ProjectionElem::OpaqueCast(..) => (),
388                ProjectionElem::UnwrapUnsafeBinder(_) => (),
389                ProjectionElem::Field(field, _ty) => {
390                    // FIXME(project-rfc_2229#36): print capture precisely here.
391                    if let Some(field) = self.is_upvar_field_projection(PlaceRef {
392                        local,
393                        projection: place.projection.split_at(index + 1).0,
394                    }) {
395                        buf = self.upvars[field.index()].to_string(self.infcx.tcx);
396                        ok = Ok(());
397                    } else {
398                        let field_name = self.describe_field(
399                            PlaceRef { local, projection: place.projection.split_at(index).0 },
400                            *field,
401                            IncludingTupleField(opt.including_tuple_field),
402                        );
403                        if let Some(field_name_str) = field_name {
404                            buf.push('.');
405                            buf.push_str(&field_name_str);
406                        }
407                    }
408                }
409                ProjectionElem::Index(index) => {
410                    buf.push('[');
411                    if self.append_local_to_string(*index, &mut buf).is_err() {
412                        buf.push('_');
413                    }
414                    buf.push(']');
415                }
416                ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
417                    // Since it isn't possible to borrow an element on a particular index and
418                    // then use another while the borrow is held, don't output indices details
419                    // to avoid confusing the end-user
420                    buf.push_str("[..]");
421                }
422            }
423        }
424        ok.ok().map(|_| buf)
425    }
426
427    fn describe_name(&self, place: PlaceRef<'tcx>) -> Option<Symbol> {
428        for elem in place.projection.into_iter() {
429            match elem {
430                ProjectionElem::Downcast(Some(name), _) => {
431                    return Some(*name);
432                }
433                _ => {}
434            }
435        }
436        None
437    }
438
439    /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
440    /// a name, or its name was generated by the compiler, then `Err` is returned
441    fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
442        let decl = &self.body.local_decls[local];
443        match self.local_name(local) {
444            Some(name) if !decl.from_compiler_desugaring() => {
445                buf.push_str(name.as_str());
446                Ok(())
447            }
448            _ => Err(()),
449        }
450    }
451
452    /// End-user visible description of the `field`nth field of `base`
453    fn describe_field(
454        &self,
455        place: PlaceRef<'tcx>,
456        field: FieldIdx,
457        including_tuple_field: IncludingTupleField,
458    ) -> Option<String> {
459        let place_ty = match place {
460            PlaceRef { local, projection: [] } => PlaceTy::from_ty(self.body.local_decls[local].ty),
461            PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {
462                ProjectionElem::Deref
463                | ProjectionElem::Index(..)
464                | ProjectionElem::ConstantIndex { .. }
465                | ProjectionElem::Subslice { .. } => {
466                    PlaceRef { local, projection: proj_base }.ty(self.body, self.infcx.tcx)
467                }
468                ProjectionElem::Downcast(..) => place.ty(self.body, self.infcx.tcx),
469                ProjectionElem::OpaqueCast(ty) | ProjectionElem::UnwrapUnsafeBinder(ty) => {
470                    PlaceTy::from_ty(*ty)
471                }
472                ProjectionElem::Field(_, field_type) => PlaceTy::from_ty(*field_type),
473                ProjectionElem::PhantomDeref => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("not a field")));
}unreachable!("not a field"),
474            },
475        };
476        self.describe_field_from_ty(
477            place_ty.ty,
478            field,
479            place_ty.variant_index,
480            including_tuple_field,
481        )
482    }
483
484    /// End-user visible description of the `field_index`nth field of `ty`
485    fn describe_field_from_ty(
486        &self,
487        ty: Ty<'_>,
488        field: FieldIdx,
489        variant_index: Option<VariantIdx>,
490        including_tuple_field: IncludingTupleField,
491    ) -> Option<String> {
492        if let Some(boxed_ty) = ty.boxed_ty() {
493            // If the type is a box, the field is described from the boxed type
494            self.describe_field_from_ty(boxed_ty, field, variant_index, including_tuple_field)
495        } else {
496            match *ty.kind() {
497                ty::Adt(def, _) => {
498                    let variant = if let Some(idx) = variant_index {
499                        if !def.is_enum() {
    ::core::panicking::panic("assertion failed: def.is_enum()")
};assert!(def.is_enum());
500                        def.variant(idx)
501                    } else {
502                        def.non_enum_variant()
503                    };
504                    if !including_tuple_field.0 && variant.ctor_kind() == Some(CtorKind::Fn) {
505                        return None;
506                    }
507                    Some(variant.fields[field].name.to_string())
508                }
509                ty::Tuple(_) => Some(field.index().to_string()),
510                ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
511                    self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
512                }
513                ty::Array(ty, _) | ty::Slice(ty) => {
514                    self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
515                }
516                ty::Closure(def_id, _) | ty::Coroutine(def_id, _) => {
517                    // We won't be borrowck'ing here if the closure came from another crate,
518                    // so it's safe to call `expect_local`.
519                    //
520                    // We know the field exists so it's safe to call operator[] and `unwrap` here.
521                    let def_id = def_id.expect_local();
522                    let var_id =
523                        self.infcx.tcx.closure_captures(def_id)[field.index()].get_root_variable();
524
525                    Some(self.infcx.tcx.hir_name(var_id).to_string())
526                }
527                _ => {
528                    // This can happen for field accesses on `Box<T>`: the field is
529                    // described from the boxed type, which may have no named fields
530                    Some(field.index().to_string())
531                }
532            }
533        }
534    }
535
536    pub(super) fn borrowed_content_source(
537        &self,
538        deref_base: PlaceRef<'tcx>,
539    ) -> BorrowedContentSource<'tcx> {
540        let tcx = self.infcx.tcx;
541
542        // Look up the provided place and work out the move path index for it,
543        // we'll use this to check whether it was originally from an overloaded
544        // operator.
545        match self.move_data.rev_lookup.find(deref_base) {
546            LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
547                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:547",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(547u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("borrowed_content_source: mpi={0:?}",
                                                    mpi) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("borrowed_content_source: mpi={:?}", mpi);
548
549                for i in &self.move_data.init_path_map[mpi] {
550                    let init = &self.move_data.inits[*i];
551                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:551",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(551u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("borrowed_content_source: init={0:?}",
                                                    init) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("borrowed_content_source: init={:?}", init);
552                    // We're only interested in statements that initialized a value, not the
553                    // initializations from arguments.
554                    let InitLocation::Statement(loc) = init.location else { continue };
555
556                    let bbd = &self.body[loc.block];
557                    let is_terminator = bbd.statements.len() == loc.statement_index;
558                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:558",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(558u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("borrowed_content_source: loc={0:?} is_terminator={1:?}",
                                                    loc, is_terminator) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
559                        "borrowed_content_source: loc={:?} is_terminator={:?}",
560                        loc, is_terminator,
561                    );
562                    if !is_terminator {
563                        continue;
564                    } else if let Some(Terminator {
565                        kind:
566                            TerminatorKind::Call {
567                                func,
568                                call_source: CallSource::OverloadedOperator,
569                                ..
570                            },
571                        ..
572                    }) = &bbd.terminator
573                    {
574                        if let Some(source) =
575                            BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
576                        {
577                            return source;
578                        }
579                    }
580                }
581            }
582            // Base is a `static` so won't be from an overloaded operator
583            _ => (),
584        };
585
586        // If we didn't find an overloaded deref or index, then assume it's a
587        // built in deref and check the type of the base.
588        let base_ty = deref_base.ty(self.body, tcx).ty;
589        if base_ty.is_raw_ptr() {
590            BorrowedContentSource::DerefRawPointer
591        } else if base_ty.is_mutable_ptr() {
592            BorrowedContentSource::DerefMutableRef
593        } else if base_ty.is_ref() {
594            BorrowedContentSource::DerefSharedRef
595        } else {
596            // Custom type implementing `Deref` (e.g. `MyBox<T>`, `Rc<T>`, `Arc<T>`)
597            // that wasn't detected via the MIR init trace above. This can happen
598            // when the deref base is initialized by a regular statement rather than
599            // a `TerminatorKind::Call` with `CallSource::OverloadedOperator`.
600            BorrowedContentSource::OverloadedDeref(base_ty)
601        }
602    }
603
604    /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
605    /// name where required.
606    pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
607        let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
608
609        // We need to add synthesized lifetimes where appropriate. We do
610        // this by hooking into the pretty printer and telling it to label the
611        // lifetimes without names with the value `'0`.
612        if let ty::Ref(region, ..) = ty.kind() {
613            match region.kind() {
614                ty::ReBound(_, ty::BoundRegion { kind: br, .. })
615                | ty::RePlaceholder(ty::PlaceholderRegion {
616                    bound: ty::BoundRegion { kind: br, .. },
617                    ..
618                }) => p.region_highlight_mode.highlighting_bound_region(br, counter),
619                _ => {}
620            }
621        }
622
623        ty.print(&mut p).unwrap();
624        p.into_buffer()
625    }
626
627    /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
628    /// synthesized lifetime name where required.
629    pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
630        let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
631
632        let region = if let ty::Ref(region, ..) = ty.kind() {
633            match region.kind() {
634                ty::ReBound(_, ty::BoundRegion { kind: br, .. })
635                | ty::RePlaceholder(ty::PlaceholderRegion {
636                    bound: ty::BoundRegion { kind: br, .. },
637                    ..
638                }) => p.region_highlight_mode.highlighting_bound_region(br, counter),
639                _ => {}
640            }
641            region
642        } else {
643            ::rustc_span::macros::bug_impl(None,
    format_args!("ty for annotation of borrow region is not a reference"),
    Location::caller());bug!("ty for annotation of borrow region is not a reference");
644        };
645
646        region.print(&mut p).unwrap();
647        p.into_buffer()
648    }
649
650    /// Add a note to region errors and borrow explanations when higher-ranked regions in predicates
651    /// implicitly introduce an "outlives `'static`" constraint.
652    ///
653    /// This is very similar to `fn suggest_static_lifetime_for_gat_from_hrtb` which handles this
654    /// note for failed type tests instead of outlives errors.
655    fn add_placeholder_from_predicate_note(
656        &self,
657        diag: &mut Diag<'_>,
658        path: &[OutlivesConstraint<'tcx>],
659    ) {
660        let tcx = self.infcx.tcx;
661        let Some((gat_hir_id, generics)) = path.iter().find_map(|constraint| {
662            let outlived = constraint.sub;
663            if let Some(origin) = self.regioncx.definitions.get(outlived)
664                && let NllRegionVariableOrigin::Placeholder(placeholder) = origin.origin
665                && let Some(id) = placeholder.bound.kind.get_id()
666                && let Some(placeholder_id) = id.as_local()
667                && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
668                && let Some(generics_impl) =
669                    tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
670            {
671                Some((gat_hir_id, generics_impl))
672            } else {
673                None
674            }
675        }) else {
676            return;
677        };
678
679        // Look for the where-bound which introduces the placeholder.
680        // As we're using the HIR, we need to handle both `for<'a> T: Trait<'a>`
681        // and `T: for<'a> Trait`<'a>.
682        for pred in generics.predicates {
683            let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
684                bound_generic_params,
685                bounds,
686                ..
687            }) = pred.kind
688            else {
689                continue;
690            };
691            if bound_generic_params
692                .iter()
693                .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
694                .is_some()
695            {
696                diag.span_note(pred.span, LIMITATION_NOTE);
697                return;
698            }
699            for bound in bounds.iter() {
700                if let GenericBound::Trait(bound) = bound {
701                    if bound
702                        .bound_generic_params
703                        .iter()
704                        .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
705                        .is_some()
706                    {
707                        diag.span_note(bound.span, LIMITATION_NOTE);
708                        return;
709                    }
710                }
711            }
712        }
713    }
714
715    /// Add a label to region errors and borrow explanations when outlives constraints arise from
716    /// proving a type implements `Sized` or `Copy`.
717    fn add_sized_or_copy_bound_info(
718        &self,
719        err: &mut Diag<'_>,
720        blamed_category: ConstraintCategory<'tcx>,
721        path: &[OutlivesConstraint<'tcx>],
722    ) {
723        for sought_category in [ConstraintCategory::SizedBound, ConstraintCategory::CopyBound] {
724            if sought_category != blamed_category
725                && let Some(sought_constraint) = path.iter().find(|c| c.category == sought_category)
726            {
727                let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("requirement occurs due to {0}",
                sought_category.description().trim_end()))
    })format!(
728                    "requirement occurs due to {}",
729                    sought_category.description().trim_end()
730                );
731                err.span_label(sought_constraint.span, label);
732            }
733        }
734    }
735}
736
737/// The span(s) associated to a use of a place.
738#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for UseSpans<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for UseSpans<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for UseSpans<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<hir::ClosureKind>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<CallKind<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for UseSpans<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for UseSpans<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::ClosureUse {
                    closure_kind: __self_0,
                    args_span: __self_1,
                    capture_kind_span: __self_2,
                    path_span: __self_3 }, Self::ClosureUse {
                    closure_kind: __arg1_0,
                    args_span: __arg1_1,
                    capture_kind_span: __arg1_2,
                    path_span: __arg1_3 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                            __self_2 == __arg1_2 && __self_3 == __arg1_3,
                (Self::FnSelfUse {
                    var_span: __self_0,
                    fn_call_span: __self_1,
                    fn_span: __self_2,
                    kind: __self_3 }, Self::FnSelfUse {
                    var_span: __arg1_0,
                    fn_call_span: __arg1_1,
                    fn_span: __arg1_2,
                    kind: __arg1_3 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                            __self_2 == __arg1_2 && __self_3 == __arg1_3,
                (Self::PatUse(__self_0), Self::PatUse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::OtherUse(__self_0), Self::OtherUse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for UseSpans<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<hir::ClosureKind>;
        let _: ::core::cmp::AssertParamIsEq<Span>;
        let _: ::core::cmp::AssertParamIsEq<CallKind<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for UseSpans<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ClosureUse {
                closure_kind: __self_0,
                args_span: __self_1,
                capture_kind_span: __self_2,
                path_span: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "ClosureUse", "closure_kind", __self_0, "args_span",
                    __self_1, "capture_kind_span", __self_2, "path_span",
                    &__self_3),
            Self::FnSelfUse {
                var_span: __self_0,
                fn_call_span: __self_1,
                fn_span: __self_2,
                kind: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "FnSelfUse", "var_span", __self_0, "fn_call_span", __self_1,
                    "fn_span", __self_2, "kind", &__self_3),
            Self::PatUse(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "PatUse",
                    &__self_0),
            Self::OtherUse(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "OtherUse", &__self_0),
        }
    }
}Debug)]
739pub(super) enum UseSpans<'tcx> {
740    /// The access is caused by capturing a variable for a closure.
741    ClosureUse {
742        /// This is true if the captured variable was from a coroutine.
743        closure_kind: hir::ClosureKind,
744        /// The span of the args of the closure, including the `move` keyword if
745        /// it's present.
746        args_span: Span,
747        /// The span of the use resulting in capture kind
748        /// Check `ty::CaptureInfo` for more details
749        capture_kind_span: Span,
750        /// The span of the use resulting in the captured path
751        /// Check `ty::CaptureInfo` for more details
752        path_span: Span,
753    },
754    /// The access is caused by using a variable as the receiver of a method
755    /// that takes 'self'
756    FnSelfUse {
757        /// The span of the variable being moved
758        var_span: Span,
759        /// The span of the method call on the variable
760        fn_call_span: Span,
761        /// The definition span of the method being called
762        fn_span: Span,
763        kind: CallKind<'tcx>,
764    },
765    /// This access is caused by a `match` or `if let` pattern.
766    PatUse(Span),
767    /// This access has a single span associated to it: common case.
768    OtherUse(Span),
769}
770
771impl UseSpans<'_> {
772    pub(super) fn args_or_use(self) -> Span {
773        match self {
774            UseSpans::ClosureUse { args_span: span, .. }
775            | UseSpans::PatUse(span)
776            | UseSpans::OtherUse(span) => span,
777            UseSpans::FnSelfUse { var_span, .. } => var_span,
778        }
779    }
780
781    /// Returns the span of `self`, in the case of a `ClosureUse` returns the `path_span`
782    pub(super) fn var_or_use_path_span(self) -> Span {
783        match self {
784            UseSpans::ClosureUse { path_span: span, .. }
785            | UseSpans::PatUse(span)
786            | UseSpans::OtherUse(span) => span,
787            UseSpans::FnSelfUse { var_span, .. } => var_span,
788        }
789    }
790
791    /// Returns the span of `self`, in the case of a `ClosureUse` returns the `capture_kind_span`
792    pub(super) fn var_or_use(self) -> Span {
793        match self {
794            UseSpans::ClosureUse { capture_kind_span: span, .. }
795            | UseSpans::PatUse(span)
796            | UseSpans::OtherUse(span) => span,
797            UseSpans::FnSelfUse { var_span, .. } => var_span,
798        }
799    }
800
801    // FIXME(coroutines): Make this just return the `ClosureKind` directly?
802    pub(super) fn coroutine_kind(self) -> Option<CoroutineKind> {
803        match self {
804            UseSpans::ClosureUse {
805                closure_kind: hir::ClosureKind::Coroutine(coroutine_kind),
806                ..
807            } => Some(coroutine_kind),
808            _ => None,
809        }
810    }
811
812    /// Add a span label to the arguments of the closure, if it exists.
813    pub(super) fn args_subdiag(self, err: &mut Diag<'_>, f: impl FnOnce(Span) -> CaptureArgLabel) {
814        if let UseSpans::ClosureUse { args_span, .. } = self {
815            err.subdiagnostic(f(args_span));
816        }
817    }
818
819    /// Add a span label to the use of the captured variable, if it exists.
820    /// only adds label to the `path_span`
821    pub(super) fn var_path_only_subdiag(
822        self,
823        err: &mut Diag<'_>,
824        action: crate::InitializationRequiringAction,
825    ) {
826        use CaptureVarPathUseCause::*;
827
828        use crate::InitializationRequiringAction::*;
829        if let UseSpans::ClosureUse { closure_kind, path_span, .. } = self {
830            match closure_kind {
831                hir::ClosureKind::Coroutine(_) => {
832                    err.subdiagnostic(match action {
833                        Borrow => BorrowInCoroutine { path_span },
834                        MatchOn | Use => UseInCoroutine { path_span },
835                        Assignment => AssignInCoroutine { path_span },
836                        PartialAssignment => AssignPartInCoroutine { path_span },
837                    });
838                }
839                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
840                    err.subdiagnostic(match action {
841                        Borrow => BorrowInClosure { path_span },
842                        MatchOn | Use => UseInClosure { path_span },
843                        Assignment => AssignInClosure { path_span },
844                        PartialAssignment => AssignPartInClosure { path_span },
845                    });
846                }
847            }
848        }
849    }
850
851    /// Add a subdiagnostic to the use of the captured variable, if it exists.
852    pub(super) fn var_subdiag(
853        self,
854        err: &mut Diag<'_>,
855        kind: Option<rustc_middle::mir::BorrowKind>,
856        f: impl FnOnce(hir::ClosureKind, Span) -> CaptureVarCause,
857    ) {
858        if let UseSpans::ClosureUse { closure_kind, capture_kind_span, path_span, .. } = self {
859            if capture_kind_span != path_span {
860                err.subdiagnostic(match kind {
861                    Some(kd) => match kd {
862                        rustc_middle::mir::BorrowKind::Shared
863                        | rustc_middle::mir::BorrowKind::Fake(_) => {
864                            CaptureVarKind::Immut { kind_span: capture_kind_span }
865                        }
866
867                        rustc_middle::mir::BorrowKind::Mut { .. } => {
868                            CaptureVarKind::Mut { kind_span: capture_kind_span }
869                        }
870                    },
871                    None => CaptureVarKind::Move { kind_span: capture_kind_span },
872                });
873            };
874            let diag = f(closure_kind, path_span);
875            err.subdiagnostic(diag);
876        }
877    }
878
879    /// Returns `false` if this place is not used in a closure.
880    pub(super) fn for_closure(&self) -> bool {
881        match *self {
882            UseSpans::ClosureUse { closure_kind, .. } => {
883                #[allow(non_exhaustive_omitted_patterns)] match closure_kind {
    hir::ClosureKind::Closure => true,
    _ => false,
}matches!(closure_kind, hir::ClosureKind::Closure)
884            }
885            _ => false,
886        }
887    }
888
889    /// Returns `false` if this place is not used in a coroutine.
890    pub(super) fn for_coroutine(&self) -> bool {
891        match *self {
892            // FIXME(coroutines): Do we want this to apply to synthetic coroutines?
893            UseSpans::ClosureUse { closure_kind, .. } => {
894                #[allow(non_exhaustive_omitted_patterns)] match closure_kind {
    hir::ClosureKind::Coroutine(..) => true,
    _ => false,
}matches!(closure_kind, hir::ClosureKind::Coroutine(..))
895            }
896            _ => false,
897        }
898    }
899
900    pub(super) fn or_else<F>(self, if_other: F) -> Self
901    where
902        F: FnOnce() -> Self,
903    {
904        match self {
905            closure @ UseSpans::ClosureUse { .. } => closure,
906            UseSpans::PatUse(_) | UseSpans::OtherUse(_) => if_other(),
907            fn_self @ UseSpans::FnSelfUse { .. } => fn_self,
908        }
909    }
910}
911
912pub(super) enum BorrowedContentSource<'tcx> {
913    DerefRawPointer,
914    DerefMutableRef,
915    DerefSharedRef,
916    OverloadedDeref(Ty<'tcx>),
917    OverloadedIndex(Ty<'tcx>),
918}
919
920impl<'tcx> BorrowedContentSource<'tcx> {
921    pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {
922        match *self {
923            BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),
924            BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),
925            BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),
926            BorrowedContentSource::OverloadedDeref(ty) => ty
927                .ty_adt_def()
928                .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
929                    name @ (sym::Rc | sym::Arc) => Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an `{0}`", name))
    })format!("an `{name}`")),
930                    _ => None,
931                })
932                .unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("dereference of `{0}`", ty))
    })format!("dereference of `{ty}`")),
933            BorrowedContentSource::OverloadedIndex(ty) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("index of `{0}`", ty))
    })format!("index of `{ty}`"),
934        }
935    }
936
937    pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
938        match *self {
939            BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
940            BorrowedContentSource::DerefSharedRef => Some("shared reference"),
941            BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
942            // Overloaded deref and index operators should be evaluated into a
943            // temporary. So we don't need a description here.
944            BorrowedContentSource::OverloadedDeref(_)
945            | BorrowedContentSource::OverloadedIndex(_) => None,
946        }
947    }
948
949    pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
950        match *self {
951            BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
952            BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
953            BorrowedContentSource::DerefMutableRef => {
954                ::rustc_span::macros::bug_impl(None,
    format_args!("describe_for_immutable_place: DerefMutableRef isn\'t immutable"),
    Location::caller())bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
955            }
956            BorrowedContentSource::OverloadedDeref(ty) => ty
957                .ty_adt_def()
958                .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
959                    name @ (sym::Rc | sym::Arc) => Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an `{0}`", name))
    })format!("an `{name}`")),
960                    _ => None,
961                })
962                .unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("dereference of `{0}`", ty))
    })format!("dereference of `{ty}`")),
963            BorrowedContentSource::OverloadedIndex(ty) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an index of `{0}`", ty))
    })format!("an index of `{ty}`"),
964        }
965    }
966
967    fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
968        match *func.kind() {
969            ty::FnDef(def_id, args) => {
970                let trait_id = tcx.trait_of_assoc(def_id)?;
971
972                let args = args.no_bound_vars().unwrap();
973
974                if tcx.is_lang_item(trait_id, LangItem::Deref)
975                    || tcx.is_lang_item(trait_id, LangItem::DerefMut)
976                {
977                    Some(BorrowedContentSource::OverloadedDeref(args.type_at(0)))
978                } else if tcx.is_lang_item(trait_id, LangItem::Index)
979                    || tcx.is_lang_item(trait_id, LangItem::IndexMut)
980                {
981                    Some(BorrowedContentSource::OverloadedIndex(args.type_at(0)))
982                } else {
983                    None
984                }
985            }
986            _ => None,
987        }
988    }
989}
990
991/// Helper struct for `explain_captures`.
992struct CapturedMessageOpt {
993    is_partial_move: bool,
994    is_loop_message: bool,
995    is_move_msg: bool,
996    is_loop_move: bool,
997    has_suggest_reborrow: bool,
998    maybe_reinitialized_locations_is_empty: bool,
999}
1000
1001/// Tracks whether [`MirBorrowckCtxt::explain_captures`] emitted a clone
1002/// suggestion, so callers can avoid emitting redundant suggestions downstream.
1003#[derive(#[automatically_derived]
impl ::core::marker::Copy for CloneSuggestion { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CloneSuggestion { }
#[automatically_derived]
impl ::core::clone::Clone for CloneSuggestion {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CloneSuggestion { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CloneSuggestion {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CloneSuggestion { }Eq)]
1004pub(super) enum CloneSuggestion {
1005    Emitted,
1006    NotEmitted,
1007}
1008
1009impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
1010    /// Finds the spans associated to a move or copy of move_place at location.
1011    pub(super) fn move_spans(
1012        &self,
1013        moved_place: PlaceRef<'tcx>, // Could also be an upvar.
1014        location: Location,
1015    ) -> UseSpans<'tcx> {
1016        use self::UseSpans::*;
1017
1018        let Some(stmt) = self.body[location.block].statements.get(location.statement_index) else {
1019            return OtherUse(self.body.source_info(location).span);
1020        };
1021
1022        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1022",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1022u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("move_spans: moved_place={0:?} location={1:?} stmt={2:?}",
                                                    moved_place, location, stmt) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
1023        if let StatementKind::Assign((_, Rvalue::Aggregate(kind, places))) = &stmt.kind
1024            && let AggregateKind::Closure(def_id, _) | AggregateKind::Coroutine(def_id, _) = **kind
1025        {
1026            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1026",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1026u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("move_spans: def_id={0:?} places={1:?}",
                                                    def_id, places) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("move_spans: def_id={:?} places={:?}", def_id, places);
1027            let def_id = def_id.expect_local();
1028            if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1029                self.closure_span(def_id, moved_place, places)
1030            {
1031                return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };
1032            }
1033        }
1034
1035        // StatementKind::FakeRead only contains a def_id if they are introduced as a result
1036        // of pattern matching within a closure.
1037        if let StatementKind::FakeRead((cause, place)) = stmt.kind {
1038            match cause {
1039                FakeReadCause::ForMatchedPlace(Some(closure_def_id))
1040                | FakeReadCause::ForLet(Some(closure_def_id)) => {
1041                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1041",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1041u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("move_spans: def_id={0:?} place={1:?}",
                                                    closure_def_id, place) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("move_spans: def_id={:?} place={:?}", closure_def_id, place);
1042                    let places = &[Operand::Move(place)];
1043                    if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1044                        self.closure_span(closure_def_id, moved_place, IndexSlice::from_raw(places))
1045                    {
1046                        return ClosureUse {
1047                            closure_kind,
1048                            args_span,
1049                            capture_kind_span,
1050                            path_span,
1051                        };
1052                    }
1053                }
1054                _ => {}
1055            }
1056        }
1057
1058        let normal_ret =
1059            if moved_place.projection.iter().any(|p| #[allow(non_exhaustive_omitted_patterns)] match p {
    ProjectionElem::Downcast(..) => true,
    _ => false,
}matches!(p, ProjectionElem::Downcast(..))) {
1060                PatUse(stmt.source_info.span)
1061            } else {
1062                OtherUse(stmt.source_info.span)
1063            };
1064
1065        // We are trying to find MIR of the form:
1066        // ```
1067        // _temp = _moved_val;
1068        // ...
1069        // FnSelfCall(_temp, ...)
1070        // ```
1071        //
1072        // where `_moved_val` is the place we generated the move error for,
1073        // `_temp` is some other local, and `FnSelfCall` is a function
1074        // that has a `self` parameter.
1075
1076        let target_temp = match stmt.kind {
1077            StatementKind::Assign((temp, _)) if temp.as_local().is_some() => {
1078                temp.as_local().unwrap()
1079            }
1080            _ => return normal_ret,
1081        };
1082
1083        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1083",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1083u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("move_spans: target_temp = {0:?}",
                                                    target_temp) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("move_spans: target_temp = {:?}", target_temp);
1084
1085        if let Some(Terminator {
1086            kind: TerminatorKind::Call { fn_span, call_source, .. }, ..
1087        }) = &self.body[location.block].terminator
1088        {
1089            let Some((method_did, method_args)) =
1090                find_self_call(self.infcx.tcx, self.body, target_temp, location.block)
1091            else {
1092                return normal_ret;
1093            };
1094
1095            let kind = call_kind(
1096                self.infcx.tcx,
1097                self.infcx.typing_env(self.infcx.param_env),
1098                method_did,
1099                method_args,
1100                *fn_span,
1101                call_source.from_hir_call(),
1102                self.infcx.tcx.fn_arg_idents(method_did)[0],
1103            );
1104
1105            return FnSelfUse {
1106                var_span: stmt.source_info.span,
1107                fn_call_span: *fn_span,
1108                fn_span: self.infcx.tcx.def_span(method_did),
1109                kind,
1110            };
1111        }
1112
1113        normal_ret
1114    }
1115
1116    /// Finds the span of arguments of a closure (within `maybe_closure_span`)
1117    /// and its usage of the local assigned at `location`.
1118    /// This is done by searching in statements succeeding `location`
1119    /// and originating from `maybe_closure_span`.
1120    pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans<'tcx> {
1121        use self::UseSpans::*;
1122        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1122",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1122u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("borrow_spans: use_span={0:?} location={1:?}",
                                                    use_span, location) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
1123
1124        let Some(Statement { kind: StatementKind::Assign((place, _)), .. }) =
1125            self.body[location.block].statements.get(location.statement_index)
1126        else {
1127            return OtherUse(use_span);
1128        };
1129        let Some(target) = place.as_local() else { return OtherUse(use_span) };
1130
1131        if self.body.local_kind(target) != LocalKind::Temp {
1132            // operands are always temporaries.
1133            return OtherUse(use_span);
1134        }
1135
1136        // drop and replace might have moved the assignment to the next block
1137        let maybe_additional_statement =
1138            if let TerminatorKind::Drop { target: drop_target, .. } =
1139                self.body[location.block].terminator().kind
1140            {
1141                self.body[drop_target].statements.first()
1142            } else {
1143                None
1144            };
1145
1146        let statements =
1147            self.body[location.block].statements[location.statement_index + 1..].iter();
1148
1149        for stmt in statements.chain(maybe_additional_statement) {
1150            if let StatementKind::Assign((_, Rvalue::Aggregate(kind, places))) = &stmt.kind {
1151                let (&def_id, is_coroutine) = match kind {
1152                    AggregateKind::Closure(def_id, _) => (def_id, false),
1153                    AggregateKind::Coroutine(def_id, _) => (def_id, true),
1154                    _ => continue,
1155                };
1156                let def_id = def_id.expect_local();
1157
1158                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1158",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1158u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("borrow_spans: def_id={0:?} is_coroutine={1:?} places={2:?}",
                                                    def_id, is_coroutine, places) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1159                    "borrow_spans: def_id={:?} is_coroutine={:?} places={:?}",
1160                    def_id, is_coroutine, places
1161                );
1162                if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1163                    self.closure_span(def_id, Place::from(target).as_ref(), places)
1164                {
1165                    return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };
1166                } else {
1167                    return OtherUse(use_span);
1168                }
1169            }
1170
1171            if use_span != stmt.source_info.span {
1172                break;
1173            }
1174        }
1175
1176        OtherUse(use_span)
1177    }
1178
1179    /// Finds the spans of a captured place within a closure or coroutine.
1180    /// The first span is the location of the use resulting in the capture kind of the capture
1181    /// The second span is the location the use resulting in the captured path of the capture
1182    fn closure_span(
1183        &self,
1184        def_id: LocalDefId,
1185        target_place: PlaceRef<'tcx>,
1186        places: &IndexSlice<FieldIdx, Operand<'tcx>>,
1187    ) -> Option<(Span, hir::ClosureKind, Span, Span)> {
1188        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1188",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1188u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("closure_span: def_id={0:?} target_place={1:?} places={2:?}",
                                                    def_id, target_place, places) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1189            "closure_span: def_id={:?} target_place={:?} places={:?}",
1190            def_id, target_place, places
1191        );
1192        let hir_id = self.infcx.tcx.local_def_id_to_hir_id(def_id);
1193        let expr = &self.infcx.tcx.hir_expect_expr(hir_id).kind;
1194        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1194",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1194u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("closure_span: hir_id={0:?} expr={1:?}",
                                                    hir_id, expr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
1195        if let &hir::ExprKind::Closure(&hir::Closure { kind, fn_decl_span, .. }) = expr {
1196            for (captured_place, place) in
1197                self.infcx.tcx.closure_captures(def_id).iter().zip(places)
1198            {
1199                match place {
1200                    Operand::Copy(place) | Operand::Move(place)
1201                        if target_place == place.as_ref() =>
1202                    {
1203                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs:1203",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1203u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("closure_span: found captured local {0:?}",
                                                    place) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("closure_span: found captured local {:?}", place);
1204                        return Some((
1205                            fn_decl_span,
1206                            kind,
1207                            captured_place.get_capture_kind_span(self.infcx.tcx),
1208                            captured_place.get_path_span(self.infcx.tcx),
1209                        ));
1210                    }
1211                    _ => {}
1212                }
1213            }
1214        }
1215        None
1216    }
1217
1218    /// Helper to retrieve span(s) of given borrow from the current MIR
1219    /// representation
1220    pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans<'tcx> {
1221        let span = self.body.source_info(borrow.reserve_location).span;
1222        self.borrow_spans(span, borrow.reserve_location)
1223    }
1224
1225    fn explain_captures(
1226        &mut self,
1227        err: &mut Diag<'_>,
1228        span: Span,
1229        move_span: Span,
1230        move_spans: UseSpans<'tcx>,
1231        moved_place: Place<'tcx>,
1232        msg_opt: CapturedMessageOpt,
1233    ) -> CloneSuggestion {
1234        let CapturedMessageOpt {
1235            is_partial_move: is_partial,
1236            is_loop_message,
1237            is_move_msg,
1238            is_loop_move,
1239            has_suggest_reborrow,
1240            maybe_reinitialized_locations_is_empty,
1241        } = msg_opt;
1242        let mut suggested_cloning = false;
1243        if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } = move_spans {
1244            let place_name = self
1245                .describe_place(moved_place.as_ref())
1246                .map(|n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`"))
1247                .unwrap_or_else(|| "value".to_owned());
1248            match kind {
1249                CallKind::FnCall { fn_trait_id, self_ty }
1250                    if self.infcx.tcx.is_lang_item(fn_trait_id, LangItem::FnOnce) =>
1251                {
1252                    err.subdiagnostic(CaptureReasonLabel::Call {
1253                        fn_call_span,
1254                        place_name: &place_name,
1255                        is_partial,
1256                        is_loop_message,
1257                    });
1258                    // Check if the move occurs on a value because of a call on a closure that comes
1259                    // from a type parameter `F: FnOnce()`. If so, we provide a targeted `note`:
1260                    // ```
1261                    // error[E0382]: use of moved value: `blk`
1262                    //   --> $DIR/once-cant-call-twice-on-heap.rs:8:5
1263                    //    |
1264                    // LL | fn foo<F:FnOnce()>(blk: F) {
1265                    //    |                    --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
1266                    // LL | blk();
1267                    //    | ----- `blk` moved due to this call
1268                    // LL | blk();
1269                    //    | ^^^ value used here after move
1270                    //    |
1271                    // note: `FnOnce` closures can only be called once
1272                    //   --> $DIR/once-cant-call-twice-on-heap.rs:6:10
1273                    //    |
1274                    // LL | fn foo<F:FnOnce()>(blk: F) {
1275                    //    |        ^^^^^^^^ `F` is made to be an `FnOnce` closure here
1276                    // LL | blk();
1277                    //    | ----- this value implements `FnOnce`, which causes it to be moved when called
1278                    // ```
1279                    if let ty::Param(param_ty) = *self_ty.kind()
1280                        && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1281                        && let param = generics.type_param(param_ty, self.infcx.tcx)
1282                        && let Some(hir_generics) = self.infcx.tcx.hir_get_generics(
1283                            self.infcx.tcx.typeck_root_def_id_local(self.mir_def_id()),
1284                        )
1285                        && let spans = hir_generics
1286                            .predicates
1287                            .iter()
1288                            .filter_map(|pred| match pred.kind {
1289                                hir::WherePredicateKind::BoundPredicate(pred) => Some(pred),
1290                                _ => None,
1291                            })
1292                            .filter(|pred| {
1293                                if let Some((id, _)) = pred.bounded_ty.as_generic_param() {
1294                                    id == param.def_id
1295                                } else {
1296                                    false
1297                                }
1298                            })
1299                            .flat_map(|pred| pred.bounds)
1300                            .filter_map(|bound| {
1301                                if let Some(trait_ref) = bound.trait_ref()
1302                                    && let Some(trait_def_id) = trait_ref.trait_def_id()
1303                                    && trait_def_id == fn_trait_id
1304                                {
1305                                    Some(bound.span())
1306                                } else {
1307                                    None
1308                                }
1309                            })
1310                            .collect::<Vec<Span>>()
1311                        && !spans.is_empty()
1312                    {
1313                        let mut span: MultiSpan = spans.clone().into();
1314                        let msg = rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`{$ty}` is made to be an `FnOnce` closure here"))msg!("`{$ty}` is made to be an `FnOnce` closure here")
1315                            .arg("ty", param_ty.to_string())
1316                            .format();
1317                        for sp in spans {
1318                            span.push_span_label(sp, msg.clone());
1319                        }
1320                        span.push_span_label(
1321                            fn_call_span,
1322                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this value implements `FnOnce`, which causes it to be moved when called"))msg!("this value implements `FnOnce`, which causes it to be moved when called"),
1323                        );
1324                        err.span_note(span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`FnOnce` closures can only be called once"))msg!("`FnOnce` closures can only be called once"));
1325                    } else {
1326                        err.subdiagnostic(CaptureReasonNote::FnOnceMoveInCall { var_span });
1327                    }
1328                }
1329                CallKind::Operator { self_arg, trait_id, .. } => {
1330                    let self_arg = self_arg.unwrap();
1331                    err.subdiagnostic(CaptureReasonLabel::OperatorUse {
1332                        fn_call_span,
1333                        place_name: &place_name,
1334                        is_partial,
1335                        is_loop_message,
1336                    });
1337                    if self.fn_self_span_reported.insert(fn_span) {
1338                        let lang = self.infcx.tcx.lang_items();
1339                        err.subdiagnostic(
1340                            if [lang.not_trait(), lang.deref_trait(), lang.neg_trait()]
1341                                .contains(&Some(trait_id))
1342                            {
1343                                CaptureReasonNote::UnOpMoveByOperator { span: self_arg.span }
1344                            } else {
1345                                CaptureReasonNote::LhsMoveByOperator { span: self_arg.span }
1346                            },
1347                        );
1348                    }
1349                }
1350                CallKind::Normal { self_arg, desugaring, method_did, method_args } => {
1351                    let self_arg = self_arg.unwrap();
1352                    let mut has_sugg = false;
1353                    let tcx = self.infcx.tcx;
1354                    // Avoid pointing to the same function in multiple different
1355                    // error messages.
1356                    if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) {
1357                        self.explain_iterator_advancement_in_for_loop_if_applicable(
1358                            err,
1359                            span,
1360                            &move_spans,
1361                        );
1362
1363                        let func = { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(method_did) }with_no_trimmed_paths!(tcx.def_path_str(method_did));
1364                        if let Some((kind, _)) = desugaring {
1365                            err.subdiagnostic(CaptureReasonNote::DesugaringFuncTakeSelf {
1366                                func,
1367                                desugar_name: kind.name(),
1368                                place_name: place_name.clone(),
1369                                span: self_arg.span,
1370                            });
1371                        } else {
1372                            err.subdiagnostic(CaptureReasonNote::FuncTakeSelf {
1373                                func,
1374                                place_name: place_name.clone(),
1375                                span: self_arg.span,
1376                            });
1377                        }
1378                    }
1379                    let parent_did = tcx.parent(method_did);
1380                    let parent_self_ty =
1381                        #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(parent_did) {
    rustc_hir::def::DefKind::Impl { .. } => true,
    _ => false,
}matches!(tcx.def_kind(parent_did), rustc_hir::def::DefKind::Impl { .. })
1382                            .then_some(parent_did)
1383                            .and_then(|did| {
1384                                match tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()
1385                                {
1386                                    ty::Adt(def, ..) => Some(def.did()),
1387                                    _ => None,
1388                                }
1389                            });
1390                    let is_option_or_result = parent_self_ty.is_some_and(|def_id| {
1391                        #[allow(non_exhaustive_omitted_patterns)] match tcx.get_diagnostic_name(def_id)
    {
    Some(sym::Option | sym::Result) => true,
    _ => false,
}matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
1392                    });
1393                    if is_option_or_result && maybe_reinitialized_locations_is_empty {
1394                        err.subdiagnostic(CaptureReasonLabel::BorrowContent {
1395                            var_span: var_span.shrink_to_hi(),
1396                        });
1397                    }
1398                    if let Some((
1399                        kind @ (CallDesugaringKind::ForLoopIntoIter
1400                        | CallDesugaringKind::ForLoopIntoAsyncIter),
1401                        _,
1402                    )) = desugaring
1403                    {
1404                        let ty = moved_place.ty(self.body, tcx).ty;
1405                        let def_id = kind.trait_def_id(tcx);
1406                        let suggest = type_known_to_meet_bound_modulo_regions(
1407                            self.infcx,
1408                            self.infcx.param_env,
1409                            Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty),
1410                            def_id,
1411                        );
1412                        if suggest {
1413                            err.subdiagnostic(CaptureReasonSuggest::IterateSlice {
1414                                ty,
1415                                span: move_span.shrink_to_lo(),
1416                            });
1417                        }
1418
1419                        match kind {
1420                            CallDesugaringKind::ForLoopIntoIter => {
1421                                err.subdiagnostic(CaptureReasonLabel::ImplicitCall {
1422                                    fn_call_span,
1423                                    place_name: &place_name,
1424                                    is_partial,
1425                                    is_loop_message,
1426                                });
1427                            }
1428                            CallDesugaringKind::ForLoopIntoAsyncIter => {
1429                                err.subdiagnostic(CaptureReasonLabel::ImplicitAsyncCall {
1430                                    fn_call_span,
1431                                    place_name: &place_name,
1432                                    is_partial,
1433                                    is_loop_message,
1434                                });
1435                            }
1436                            _ => {}
1437                        }
1438                        // If the moved place was a `&mut` ref, then we can
1439                        // suggest to reborrow it where it was moved, so it
1440                        // will still be valid by the time we get to the usage.
1441                        if let ty::Ref(_, _, hir::Mutability::Mut) =
1442                            moved_place.ty(self.body, self.infcx.tcx).ty.kind()
1443                        {
1444                            // The `&mut *place` reborrow suggestion is `MachineApplicable`, so
1445                            // only offer it where `*place` can be borrowed mutably: a value
1446                            // captured by an `Fn` closure (held via `&self`) cannot, and the
1447                            // suggestion would otherwise fail to compile with E0596.
1448                            let reborrow_place = self.infcx.tcx.mk_place_deref(moved_place);
1449                            let reborrow_is_valid = self
1450                                .is_mutable(reborrow_place.as_ref(), LocalMutationIsAllowed::No)
1451                                .is_ok();
1452                            // Suggest `reborrow` in other place for following situations:
1453                            // 1. If we are in a loop this will be suggested later.
1454                            // 2. If the moved value is a mut reference, it is used in a
1455                            // generic function and the corresponding arg's type is generic param.
1456                            if !is_loop_move && !has_suggest_reborrow && reborrow_is_valid {
1457                                self.suggest_reborrow(
1458                                    err,
1459                                    move_span.shrink_to_lo(),
1460                                    moved_place.as_ref(),
1461                                );
1462                            }
1463                        }
1464                    } else {
1465                        match desugaring {
1466                            Some((CallDesugaringKind::Await, _)) => {
1467                                err.subdiagnostic(CaptureReasonLabel::Await {
1468                                    fn_call_span,
1469                                    place_name: &place_name,
1470                                    is_partial,
1471                                    is_loop_message,
1472                                });
1473                            }
1474                            Some((CallDesugaringKind::QuestionBranch, _)) => {
1475                                err.subdiagnostic(CaptureReasonLabel::QuestionMark {
1476                                    fn_call_span,
1477                                    place_name: &place_name,
1478                                    is_partial,
1479                                    is_loop_message,
1480                                });
1481                            }
1482                            _ => {
1483                                err.subdiagnostic(CaptureReasonLabel::MethodCall {
1484                                    fn_call_span,
1485                                    place_name: &place_name,
1486                                    is_partial,
1487                                    is_loop_message,
1488                                });
1489                            }
1490                        }
1491                        // Erase and shadow everything that could be passed to the new infcx.
1492                        let ty = moved_place.ty(self.body, tcx).ty;
1493
1494                        if let ty::Adt(def, args) = ty.peel_refs().kind()
1495                            && tcx.is_lang_item(def.did(), LangItem::Pin)
1496                            && let ty::Ref(_, _, hir::Mutability::Mut) = args.type_at(0).kind()
1497                            && let self_ty = self.infcx.instantiate_binder_with_fresh_vars(
1498                                fn_call_span,
1499                                BoundRegionConversionTime::FnCall,
1500                                tcx.fn_sig(method_did)
1501                                    .instantiate(tcx, method_args)
1502                                    .skip_norm_wip()
1503                                    .input(0),
1504                            )
1505                            && self.infcx.can_eq(self.infcx.param_env, ty, self_ty)
1506                        {
1507                            err.subdiagnostic(CaptureReasonSuggest::FreshReborrow {
1508                                span: move_span.shrink_to_hi(),
1509                            });
1510                            has_sugg = true;
1511                        }
1512                        if let Some(clone_trait) = tcx.lang_items().clone_trait() {
1513                            // Check whether the deref is from a custom Deref impl
1514                            // (e.g. Rc, Box) or a built-in reference deref.
1515                            // For built-in derefs with Clone fully satisfied, we skip
1516                            // the UFCS suggestion here and let `suggest_cloning`
1517                            // downstream emit a simpler `.clone()` suggestion instead.
1518                            let has_overloaded_deref =
1519                                moved_place.iter_projections().any(|(place, elem)| {
1520                                    #[allow(non_exhaustive_omitted_patterns)] match elem {
    ProjectionElem::Deref => true,
    _ => false,
}matches!(elem, ProjectionElem::Deref)
1521                                        && #[allow(non_exhaustive_omitted_patterns)] match self.borrowed_content_source(place)
    {
    BorrowedContentSource::OverloadedDeref(_) |
        BorrowedContentSource::OverloadedIndex(_) => true,
    _ => false,
}matches!(
1522                                            self.borrowed_content_source(place),
1523                                            BorrowedContentSource::OverloadedDeref(_)
1524                                                | BorrowedContentSource::OverloadedIndex(_)
1525                                        )
1526                                });
1527
1528                            let has_deref = moved_place
1529                                .iter_projections()
1530                                .any(|(_, elem)| #[allow(non_exhaustive_omitted_patterns)] match elem {
    ProjectionElem::Deref => true,
    _ => false,
}matches!(elem, ProjectionElem::Deref));
1531
1532                            let sugg = if has_deref {
1533                                let (start, end) = if let Some(expr) = self.find_expr(move_span)
1534                                    && let Some(_) = self.clone_on_reference(expr)
1535                                    && let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind
1536                                {
1537                                    (move_span.shrink_to_lo(), move_span.with_lo(rcvr.span.hi()))
1538                                } else {
1539                                    (move_span.shrink_to_lo(), move_span.shrink_to_hi())
1540                                };
1541                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(start,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("<{0} as Clone>::clone(&",
                                    ty))
                        })), (end, ")".to_string())]))vec![
1542                                    // We use the fully-qualified path because `.clone()` can
1543                                    // sometimes choose `<&T as Clone>` instead of `<T as Clone>`
1544                                    // when going through auto-deref, so this ensures that doesn't
1545                                    // happen, causing suggestions for `.clone().clone()`.
1546                                    (start, format!("<{ty} as Clone>::clone(&")),
1547                                    (end, ")".to_string()),
1548                                ]
1549                            } else {
1550                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(move_span.shrink_to_hi(), ".clone()".to_string())]))vec![(move_span.shrink_to_hi(), ".clone()".to_string())]
1551                            };
1552                            if let Some(errors) = self.infcx.type_implements_trait_shallow(
1553                                clone_trait,
1554                                ty,
1555                                self.infcx.param_env,
1556                            ) && !has_sugg
1557                            {
1558                                let skip_for_simple_clone =
1559                                    has_deref && !has_overloaded_deref && errors.no_errors();
1560                                if !skip_for_simple_clone {
1561                                    let msg = match errors.as_slice() {
1562                                        [] => "you can `clone` the value and consume it, but \
1563                                               this might not be your desired behavior"
1564                                            .to_string(),
1565                                        [error] => {
1566                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you could `clone` the value and consume it, if the `{0}` trait bound could be satisfied",
                error.obligation.predicate))
    })format!(
1567                                                "you could `clone` the value and consume it, if \
1568                                                 the `{}` trait bound could be satisfied",
1569                                                error.obligation.predicate,
1570                                            )
1571                                        }
1572                                        _ => {
1573                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you could `clone` the value and consume it, if the following trait bounds could be satisfied: {0}",
                listify(errors.as_slice(),
                        |e: &FulfillmentError<'tcx>|
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("`{0}`",
                                            e.obligation.predicate))
                                })).unwrap()))
    })format!(
1574                                                "you could `clone` the value and consume it, if \
1575                                                 the following trait bounds could be satisfied: \
1576                                                 {}",
1577                                                listify(
1578                                                    errors.as_slice(),
1579                                                    |e: &FulfillmentError<'tcx>| format!(
1580                                                        "`{}`",
1581                                                        e.obligation.predicate
1582                                                    )
1583                                                )
1584                                                .unwrap(),
1585                                            )
1586                                        }
1587                                    };
1588                                    err.multipart_suggestion(
1589                                        msg,
1590                                        sugg,
1591                                        Applicability::MaybeIncorrect,
1592                                    );
1593
1594                                    suggested_cloning = errors.no_errors();
1595
1596                                    for error in errors {
1597                                        if let FulfillmentErrorCode::Select(
1598                                            SelectionError::Unimplemented,
1599                                        ) = error.code
1600                                            && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(
1601                                                pred,
1602                                            )) = error.obligation.predicate.kind().skip_binder()
1603                                        {
1604                                            self.infcx.err_ctxt().suggest_derive(
1605                                                &error.obligation,
1606                                                err,
1607                                                error.obligation.predicate.kind().rebind(pred),
1608                                            );
1609                                        }
1610                                    }
1611                                }
1612                            }
1613                        }
1614                    }
1615                }
1616                // Other desugarings takes &self, which cannot cause a move
1617                _ => {}
1618            }
1619        } else {
1620            if move_span != span || is_loop_message {
1621                err.subdiagnostic(CaptureReasonLabel::MovedHere {
1622                    move_span,
1623                    is_partial,
1624                    is_move_msg,
1625                    is_loop_message,
1626                });
1627            }
1628            // If the move error occurs due to a loop, don't show
1629            // another message for the same span
1630            if !is_loop_message {
1631                move_spans.var_subdiag(err, None, |kind, var_span| match kind {
1632                    hir::ClosureKind::Coroutine(_) => {
1633                        CaptureVarCause::PartialMoveUseInCoroutine { var_span, is_partial }
1634                    }
1635                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1636                        CaptureVarCause::PartialMoveUseInClosure { var_span, is_partial }
1637                    }
1638                })
1639            }
1640        }
1641        if suggested_cloning { CloneSuggestion::Emitted } else { CloneSuggestion::NotEmitted }
1642    }
1643
1644    /// Skip over locals that begin with an underscore or have no name
1645    pub(crate) fn local_excluded_from_unused_mut_lint(&self, index: Local) -> bool {
1646        self.local_name(index).is_none_or(|name| name.as_str().starts_with('_'))
1647    }
1648}
1649
1650const LIMITATION_NOTE: DiagMessage =
1651    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("due to a current limitation of the type system, this implies a `'static` lifetime"))msg!("due to a current limitation of the type system, this implies a `'static` lifetime");