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_attr_ir::lang_items::LangItem;
7use rustc_data_structures::fx::FxIndexMap;
8use rustc_errors::formatting::DiagMessageAddArg;
9use rustc_errors::{Applicability, Diag, DiagMessage, MultiSpan, listify, msg};
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 {
        BorrowckDiagnosticsBuffer {
            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.lo_hi());
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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:228",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:231",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:233",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:247",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:255",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:266",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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.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        place.projection.iter().find_map(|elem| match elem {
429            ProjectionElem::Downcast(Some(name), _) => Some(*name),
430            _ => None,
431        })
432    }
433
434    /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
435    /// a name, or its name was generated by the compiler, then `Err` is returned
436    fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
437        let decl = &self.body.local_decls[local];
438        match self.local_name(local) {
439            Some(name) if !decl.from_compiler_desugaring() => {
440                buf.push_str(name.as_str());
441                Ok(())
442            }
443            _ => Err(()),
444        }
445    }
446
447    /// End-user visible description of the `field`nth field of `base`
448    fn describe_field(
449        &self,
450        place: PlaceRef<'tcx>,
451        field: FieldIdx,
452        including_tuple_field: IncludingTupleField,
453    ) -> Option<String> {
454        let place_ty = match place {
455            PlaceRef { local, projection: [] } => PlaceTy::from_ty(self.body.local_decls[local].ty),
456            PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {
457                ProjectionElem::Deref
458                | ProjectionElem::Index(..)
459                | ProjectionElem::ConstantIndex { .. }
460                | ProjectionElem::Subslice { .. } => {
461                    PlaceRef { local, projection: proj_base }.ty(self.body, self.infcx.tcx)
462                }
463                ProjectionElem::Downcast(..) => place.ty(self.body, self.infcx.tcx),
464                ProjectionElem::OpaqueCast(ty) | ProjectionElem::UnwrapUnsafeBinder(ty) => {
465                    PlaceTy::from_ty(*ty)
466                }
467                ProjectionElem::Field(_, field_type) => PlaceTy::from_ty(*field_type),
468                ProjectionElem::PhantomDeref => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("not a field")));
}unreachable!("not a field"),
469            },
470        };
471        self.describe_field_from_ty(
472            place_ty.ty,
473            field,
474            place_ty.variant_index,
475            including_tuple_field,
476        )
477    }
478
479    /// End-user visible description of the `field_index`nth field of `ty`
480    fn describe_field_from_ty(
481        &self,
482        ty: Ty<'_>,
483        field: FieldIdx,
484        variant_index: Option<VariantIdx>,
485        including_tuple_field: IncludingTupleField,
486    ) -> Option<String> {
487        if let Some(boxed_ty) = ty.boxed_ty() {
488            // If the type is a box, the field is described from the boxed type
489            self.describe_field_from_ty(boxed_ty, field, variant_index, including_tuple_field)
490        } else {
491            match *ty.kind() {
492                ty::Adt(def, _) => {
493                    let variant = if let Some(idx) = variant_index {
494                        if !def.is_enum() {
    ::core::panicking::panic("assertion failed: def.is_enum()")
};assert!(def.is_enum());
495                        def.variant(idx)
496                    } else {
497                        def.non_enum_variant()
498                    };
499                    if !including_tuple_field.0 && variant.ctor_kind() == Some(CtorKind::Fn) {
500                        return None;
501                    }
502                    Some(variant.fields[field].name.to_string())
503                }
504                ty::Tuple(_) => Some(field.index().to_string()),
505                ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
506                    self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
507                }
508                ty::Array(ty, _) | ty::Slice(ty) => {
509                    self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
510                }
511                ty::Closure(def_id, _) | ty::Coroutine(def_id, _) => {
512                    // We won't be borrowck'ing here if the closure came from another crate,
513                    // so it's safe to call `expect_local`.
514                    //
515                    // We know the field exists so it's safe to call operator[] and `unwrap` here.
516                    let def_id = def_id.expect_local();
517                    let var_id =
518                        self.infcx.tcx.closure_captures(def_id)[field.index()].get_root_variable();
519
520                    Some(self.infcx.tcx.hir_name(var_id).to_string())
521                }
522                _ => {
523                    // This can happen for field accesses on `Box<T>`: the field is
524                    // described from the boxed type, which may have no named fields
525                    Some(field.index().to_string())
526                }
527            }
528        }
529    }
530
531    pub(super) fn borrowed_content_source(
532        &self,
533        deref_base: PlaceRef<'tcx>,
534    ) -> BorrowedContentSource<'tcx> {
535        let tcx = self.infcx.tcx;
536
537        // Look up the provided place and work out the move path index for it,
538        // we'll use this to check whether it was originally from an overloaded
539        // operator.
540        match self.move_data.rev_lookup.find(deref_base) {
541            LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
542                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:542",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(542u32),
                        ::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);
543
544                for i in &self.move_data.init_path_map[mpi] {
545                    let init = &self.move_data.inits[*i];
546                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:546",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(546u32),
                        ::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);
547                    // We're only interested in statements that initialized a value, not the
548                    // initializations from arguments.
549                    let InitLocation::Statement(loc) = init.location else { continue };
550
551                    let bbd = &self.body[loc.block];
552                    let is_terminator = bbd.statements.len() == loc.statement_index;
553                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:553",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(553u32),
                        ::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!(
554                        "borrowed_content_source: loc={:?} is_terminator={:?}",
555                        loc, is_terminator,
556                    );
557                    if !is_terminator {
558                        continue;
559                    } else if let Some(Terminator {
560                        kind:
561                            TerminatorKind::Call {
562                                func,
563                                call_source: CallSource::OverloadedOperator,
564                                ..
565                            },
566                        ..
567                    }) = &bbd.terminator
568                    {
569                        if let Some(source) =
570                            BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
571                        {
572                            return source;
573                        }
574                    }
575                }
576            }
577            // Base is a `static` so won't be from an overloaded operator
578            _ => (),
579        };
580
581        // If we didn't find an overloaded deref or index, then assume it's a
582        // built in deref and check the type of the base.
583        let base_ty = deref_base.ty(self.body, tcx).ty;
584        if base_ty.is_raw_ptr() {
585            BorrowedContentSource::DerefRawPointer
586        } else if base_ty.is_mutable_ptr() {
587            BorrowedContentSource::DerefMutableRef
588        } else if base_ty.is_ref() {
589            BorrowedContentSource::DerefSharedRef
590        } else {
591            // Custom type implementing `Deref` (e.g. `MyBox<T>`, `Rc<T>`, `Arc<T>`)
592            // that wasn't detected via the MIR init trace above. This can happen
593            // when the deref base is initialized by a regular statement rather than
594            // a `TerminatorKind::Call` with `CallSource::OverloadedOperator`.
595            BorrowedContentSource::OverloadedDeref(base_ty)
596        }
597    }
598
599    /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
600    /// name where required.
601    pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
602        let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
603
604        // We need to add synthesized lifetimes where appropriate. We do
605        // this by hooking into the pretty printer and telling it to label the
606        // lifetimes without names with the value `'0`.
607        if let ty::Ref(region, ..) = ty.kind() {
608            match region.kind() {
609                ty::ReBound(_, ty::BoundRegion { kind: br, .. })
610                | ty::RePlaceholder(ty::PlaceholderRegion {
611                    bound: ty::BoundRegion { kind: br, .. },
612                    ..
613                }) => p.region_highlight_mode.highlighting_bound_region(br, counter),
614                _ => {}
615            }
616        }
617
618        ty.print(&mut p).unwrap();
619        p.into_buffer()
620    }
621
622    /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
623    /// synthesized lifetime name where required.
624    pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
625        let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
626
627        let region = if let ty::Ref(region, ..) = ty.kind() {
628            match region.kind() {
629                ty::ReBound(_, ty::BoundRegion { kind: br, .. })
630                | ty::RePlaceholder(ty::PlaceholderRegion {
631                    bound: ty::BoundRegion { kind: br, .. },
632                    ..
633                }) => p.region_highlight_mode.highlighting_bound_region(br, counter),
634                _ => {}
635            }
636            region
637        } else {
638            ::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");
639        };
640
641        region.print(&mut p).unwrap();
642        p.into_buffer()
643    }
644
645    /// Add a note to region errors and borrow explanations when higher-ranked regions in predicates
646    /// implicitly introduce an "outlives `'static`" constraint.
647    ///
648    /// This is very similar to `fn suggest_static_lifetime_for_gat_from_hrtb` which handles this
649    /// note for failed type tests instead of outlives errors.
650    fn add_placeholder_from_predicate_note(
651        &self,
652        diag: &mut Diag<'_>,
653        path: &[OutlivesConstraint<'tcx>],
654    ) {
655        let tcx = self.infcx.tcx;
656        let Some((gat_hir_id, generics)) = path.iter().find_map(|constraint| {
657            let outlived = constraint.sub;
658            if let Some(origin) = self.regioncx.definitions.get(outlived)
659                && let NllRegionVariableOrigin::Placeholder(placeholder) = origin.origin
660                && let Some(id) = placeholder.bound.kind.get_id()
661                && let Some(placeholder_id) = id.as_local()
662                && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
663                && let Some(generics_impl) =
664                    tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
665            {
666                Some((gat_hir_id, generics_impl))
667            } else {
668                None
669            }
670        }) else {
671            return;
672        };
673
674        // Look for the where-bound which introduces the placeholder.
675        // As we're using the HIR, we need to handle both `for<'a> T: Trait<'a>`
676        // and `T: for<'a> Trait`<'a>.
677        for pred in generics.predicates {
678            let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
679                bound_generic_params,
680                bounds,
681                ..
682            }) = pred.kind
683            else {
684                continue;
685            };
686            if bound_generic_params
687                .iter()
688                .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
689                .is_some()
690            {
691                diag.span_note(pred.span, LIMITATION_NOTE);
692                return;
693            }
694            for bound in bounds.iter() {
695                if let GenericBound::Trait(bound) = bound {
696                    if bound
697                        .bound_generic_params
698                        .iter()
699                        .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
700                        .is_some()
701                    {
702                        diag.span_note(bound.span, LIMITATION_NOTE);
703                        return;
704                    }
705                }
706            }
707        }
708    }
709
710    /// Add a label to region errors and borrow explanations when outlives constraints arise from
711    /// proving a type implements `Sized` or `Copy`.
712    fn add_sized_or_copy_bound_info(
713        &self,
714        err: &mut Diag<'_>,
715        blamed_category: ConstraintCategory<'tcx>,
716        path: &[OutlivesConstraint<'tcx>],
717    ) {
718        for sought_category in [ConstraintCategory::SizedBound, ConstraintCategory::CopyBound] {
719            if sought_category != blamed_category
720                && let Some(sought_constraint) = path.iter().find(|c| c.category == sought_category)
721            {
722                let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("requirement occurs due to {0}",
                sought_category.description().trim_end()))
    })format!(
723                    "requirement occurs due to {}",
724                    sought_category.description().trim_end()
725                );
726                err.span_label(sought_constraint.span, label);
727            }
728        }
729    }
730}
731
732/// The span(s) associated to a use of a place.
733#[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]
    #[rustc_trivial_field_reads]
    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]
    #[rustc_trivial_field_reads]
    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 args_span capture_kind_span path_span",
                    __self_0, __self_1, __self_2, &__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 fn_call_span fn_span kind", __self_0,
                    __self_1, __self_2, &__self_3),
            Self::PatUse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "PatUse", &__self_0),
            Self::OtherUse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OtherUse", &__self_0),
        }
    }
}Debug)]
734pub(super) enum UseSpans<'tcx> {
735    /// The access is caused by capturing a variable for a closure.
736    ClosureUse {
737        /// This is true if the captured variable was from a coroutine.
738        closure_kind: hir::ClosureKind,
739        /// The span of the args of the closure, including the `move` keyword if
740        /// it's present.
741        args_span: Span,
742        /// The span of the use resulting in capture kind
743        /// Check `ty::CaptureInfo` for more details
744        capture_kind_span: Span,
745        /// The span of the use resulting in the captured path
746        /// Check `ty::CaptureInfo` for more details
747        path_span: Span,
748    },
749    /// The access is caused by using a variable as the receiver of a method
750    /// that takes 'self'
751    FnSelfUse {
752        /// The span of the variable being moved
753        var_span: Span,
754        /// The span of the method call on the variable
755        fn_call_span: Span,
756        /// The definition span of the method being called
757        fn_span: Span,
758        kind: CallKind<'tcx>,
759    },
760    /// This access is caused by a `match` or `if let` pattern.
761    PatUse(Span),
762    /// This access has a single span associated to it: common case.
763    OtherUse(Span),
764}
765
766impl UseSpans<'_> {
767    pub(super) fn args_or_use(self) -> Span {
768        match self {
769            UseSpans::ClosureUse { args_span: span, .. }
770            | UseSpans::PatUse(span)
771            | UseSpans::OtherUse(span) => span,
772            UseSpans::FnSelfUse { var_span, .. } => var_span,
773        }
774    }
775
776    /// Returns the span of `self`, in the case of a `ClosureUse` returns the `path_span`
777    pub(super) fn var_or_use_path_span(self) -> Span {
778        match self {
779            UseSpans::ClosureUse { path_span: span, .. }
780            | UseSpans::PatUse(span)
781            | UseSpans::OtherUse(span) => span,
782            UseSpans::FnSelfUse { var_span, .. } => var_span,
783        }
784    }
785
786    /// Returns the span of `self`, in the case of a `ClosureUse` returns the `capture_kind_span`
787    pub(super) fn var_or_use(self) -> Span {
788        match self {
789            UseSpans::ClosureUse { capture_kind_span: span, .. }
790            | UseSpans::PatUse(span)
791            | UseSpans::OtherUse(span) => span,
792            UseSpans::FnSelfUse { var_span, .. } => var_span,
793        }
794    }
795
796    // FIXME(coroutines): Make this just return the `ClosureKind` directly?
797    pub(super) fn coroutine_kind(self) -> Option<CoroutineKind> {
798        match self {
799            UseSpans::ClosureUse {
800                closure_kind: hir::ClosureKind::Coroutine(coroutine_kind),
801                ..
802            } => Some(coroutine_kind),
803            _ => None,
804        }
805    }
806
807    /// Add a span label to the arguments of the closure, if it exists.
808    pub(super) fn args_subdiag(self, err: &mut Diag<'_>, f: impl FnOnce(Span) -> CaptureArgLabel) {
809        if let UseSpans::ClosureUse { args_span, .. } = self {
810            err.subdiagnostic(f(args_span));
811        }
812    }
813
814    /// Add a span label to the use of the captured variable, if it exists.
815    /// only adds label to the `path_span`
816    pub(super) fn var_path_only_subdiag(
817        self,
818        err: &mut Diag<'_>,
819        action: crate::InitializationRequiringAction,
820    ) {
821        use CaptureVarPathUseCause::*;
822
823        use crate::InitializationRequiringAction::*;
824        if let UseSpans::ClosureUse { closure_kind, path_span, .. } = self {
825            match closure_kind {
826                hir::ClosureKind::Coroutine(_) => {
827                    err.subdiagnostic(match action {
828                        Borrow => BorrowInCoroutine { path_span },
829                        MatchOn | Use => UseInCoroutine { path_span },
830                        Assignment => AssignInCoroutine { path_span },
831                        PartialAssignment => AssignPartInCoroutine { path_span },
832                    });
833                }
834                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
835                    err.subdiagnostic(match action {
836                        Borrow => BorrowInClosure { path_span },
837                        MatchOn | Use => UseInClosure { path_span },
838                        Assignment => AssignInClosure { path_span },
839                        PartialAssignment => AssignPartInClosure { path_span },
840                    });
841                }
842            }
843        }
844    }
845
846    /// Add a subdiagnostic to the use of the captured variable, if it exists.
847    pub(super) fn var_subdiag(
848        self,
849        err: &mut Diag<'_>,
850        kind: Option<rustc_middle::mir::BorrowKind>,
851        f: impl FnOnce(hir::ClosureKind, Span) -> CaptureVarCause,
852    ) {
853        if let UseSpans::ClosureUse { closure_kind, capture_kind_span, path_span, .. } = self {
854            if capture_kind_span != path_span {
855                err.subdiagnostic(match kind {
856                    Some(kd) => match kd {
857                        rustc_middle::mir::BorrowKind::Shared
858                        | rustc_middle::mir::BorrowKind::Fake(_) => {
859                            CaptureVarKind::Immut { kind_span: capture_kind_span }
860                        }
861
862                        rustc_middle::mir::BorrowKind::Mut { .. } => {
863                            CaptureVarKind::Mut { kind_span: capture_kind_span }
864                        }
865                    },
866                    None => CaptureVarKind::Move { kind_span: capture_kind_span },
867                });
868            };
869            let diag = f(closure_kind, path_span);
870            err.subdiagnostic(diag);
871        }
872    }
873
874    /// Returns `false` if this place is not used in a closure.
875    pub(super) fn for_closure(&self) -> bool {
876        match *self {
877            UseSpans::ClosureUse { closure_kind, .. } => {
878                #[allow(non_exhaustive_omitted_patterns)] match closure_kind {
    hir::ClosureKind::Closure => true,
    _ => false,
}matches!(closure_kind, hir::ClosureKind::Closure)
879            }
880            _ => false,
881        }
882    }
883
884    /// Returns `false` if this place is not used in a coroutine.
885    pub(super) fn for_coroutine(&self) -> bool {
886        match *self {
887            // FIXME(coroutines): Do we want this to apply to synthetic coroutines?
888            UseSpans::ClosureUse { closure_kind, .. } => {
889                #[allow(non_exhaustive_omitted_patterns)] match closure_kind {
    hir::ClosureKind::Coroutine(..) => true,
    _ => false,
}matches!(closure_kind, hir::ClosureKind::Coroutine(..))
890            }
891            _ => false,
892        }
893    }
894
895    pub(super) fn or_else<F>(self, if_other: F) -> Self
896    where
897        F: FnOnce() -> Self,
898    {
899        match self {
900            closure @ UseSpans::ClosureUse { .. } => closure,
901            UseSpans::PatUse(_) | UseSpans::OtherUse(_) => if_other(),
902            fn_self @ UseSpans::FnSelfUse { .. } => fn_self,
903        }
904    }
905}
906
907pub(super) enum BorrowedContentSource<'tcx> {
908    DerefRawPointer,
909    DerefMutableRef,
910    DerefSharedRef,
911    OverloadedDeref(Ty<'tcx>),
912    OverloadedIndex(Ty<'tcx>),
913}
914
915impl<'tcx> BorrowedContentSource<'tcx> {
916    pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {
917        match *self {
918            BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),
919            BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),
920            BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),
921            BorrowedContentSource::OverloadedDeref(ty) => ty
922                .ty_adt_def()
923                .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
924                    name @ (sym::Rc | sym::Arc) => Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an `{0}`", name))
    })format!("an `{name}`")),
925                    _ => None,
926                })
927                .unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("dereference of `{0}`", ty))
    })format!("dereference of `{ty}`")),
928            BorrowedContentSource::OverloadedIndex(ty) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("index of `{0}`", ty))
    })format!("index of `{ty}`"),
929        }
930    }
931
932    pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
933        match *self {
934            BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
935            BorrowedContentSource::DerefSharedRef => Some("shared reference"),
936            BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
937            // Overloaded deref and index operators should be evaluated into a
938            // temporary. So we don't need a description here.
939            BorrowedContentSource::OverloadedDeref(_)
940            | BorrowedContentSource::OverloadedIndex(_) => None,
941        }
942    }
943
944    pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
945        match *self {
946            BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
947            BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
948            BorrowedContentSource::DerefMutableRef => {
949                ::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")
950            }
951            BorrowedContentSource::OverloadedDeref(ty) => ty
952                .ty_adt_def()
953                .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
954                    name @ (sym::Rc | sym::Arc) => Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an `{0}`", name))
    })format!("an `{name}`")),
955                    _ => None,
956                })
957                .unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("dereference of `{0}`", ty))
    })format!("dereference of `{ty}`")),
958            BorrowedContentSource::OverloadedIndex(ty) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an index of `{0}`", ty))
    })format!("an index of `{ty}`"),
959        }
960    }
961
962    fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
963        match *func.kind() {
964            ty::FnDef(def_id, args) => {
965                let trait_id = tcx.trait_of_assoc(def_id)?;
966
967                let args = args.no_bound_vars().unwrap();
968
969                if tcx.is_lang_item(trait_id, LangItem::Deref)
970                    || tcx.is_lang_item(trait_id, LangItem::DerefMut)
971                {
972                    Some(BorrowedContentSource::OverloadedDeref(args.type_at(0)))
973                } else if tcx.is_lang_item(trait_id, LangItem::Index)
974                    || tcx.is_lang_item(trait_id, LangItem::IndexMut)
975                {
976                    Some(BorrowedContentSource::OverloadedIndex(args.type_at(0)))
977                } else {
978                    None
979                }
980            }
981            _ => None,
982        }
983    }
984}
985
986/// Helper struct for `explain_captures`.
987struct CapturedMessageOpt {
988    is_partial_move: bool,
989    is_loop_message: bool,
990    is_move_msg: bool,
991    is_loop_move: bool,
992    has_suggest_reborrow: bool,
993    maybe_reinitialized_locations_is_empty: bool,
994}
995
996/// Tracks whether [`MirBorrowckCtxt::explain_captures`] emitted a clone
997/// suggestion, so callers can avoid emitting redundant suggestions downstream.
998#[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]
    #[rustc_trivial_field_reads]
    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)]
999pub(super) enum CloneSuggestion {
1000    Emitted,
1001    NotEmitted,
1002}
1003
1004impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
1005    /// Finds the spans associated to a move or copy of move_place at location.
1006    pub(super) fn move_spans(
1007        &self,
1008        moved_place: PlaceRef<'tcx>, // Could also be an upvar.
1009        location: Location,
1010    ) -> UseSpans<'tcx> {
1011        use self::UseSpans::*;
1012
1013        let Some(stmt) = self.body[location.block].statements.get(location.statement_index) else {
1014            return OtherUse(self.body.source_info(location).span);
1015        };
1016
1017        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1017",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1017u32),
                        ::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);
1018        if let StatementKind::Assign((_, Rvalue::Aggregate(kind, places))) = &stmt.kind
1019            && let AggregateKind::Closure(def_id, _) | AggregateKind::Coroutine(def_id, _) = **kind
1020        {
1021            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1021",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1021u32),
                        ::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);
1022            let def_id = def_id.expect_local();
1023            if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1024                self.closure_span(def_id, moved_place, places)
1025            {
1026                return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };
1027            }
1028        }
1029
1030        // StatementKind::FakeRead only contains a def_id if they are introduced as a result
1031        // of pattern matching within a closure.
1032        if let StatementKind::FakeRead((
1033            FakeReadCause::ForMatchedPlace(Some(closure_def_id))
1034            | FakeReadCause::ForLet(Some(closure_def_id)),
1035            place,
1036        )) = stmt.kind
1037        {
1038            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1038",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1038u32),
                        ::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);
1039            let places = &[Operand::Move(place)];
1040            if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1041                self.closure_span(closure_def_id, moved_place, IndexSlice::from_raw(places))
1042            {
1043                return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };
1044            }
1045        }
1046
1047        let normal_ret =
1048            if moved_place.projection.iter().any(|p| #[allow(non_exhaustive_omitted_patterns)] match p {
    ProjectionElem::Downcast(..) => true,
    _ => false,
}matches!(p, ProjectionElem::Downcast(..))) {
1049                PatUse(stmt.source_info.span)
1050            } else {
1051                OtherUse(stmt.source_info.span)
1052            };
1053
1054        // We are trying to find MIR of the form:
1055        // ```
1056        // _temp = _moved_val;
1057        // ...
1058        // FnSelfCall(_temp, ...)
1059        // ```
1060        //
1061        // where `_moved_val` is the place we generated the move error for,
1062        // `_temp` is some other local, and `FnSelfCall` is a function
1063        // that has a `self` parameter.
1064
1065        let target_temp = match stmt.kind {
1066            StatementKind::Assign((temp, _)) if temp.as_local().is_some() => {
1067                temp.as_local().unwrap()
1068            }
1069            _ => return normal_ret,
1070        };
1071
1072        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1072",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1072u32),
                        ::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);
1073
1074        if let Some(Terminator {
1075            kind: TerminatorKind::Call { fn_span, call_source, .. }, ..
1076        }) = &self.body[location.block].terminator
1077        {
1078            let Some((method_did, method_args)) =
1079                find_self_call(self.infcx.tcx, self.body, target_temp, location.block)
1080            else {
1081                return normal_ret;
1082            };
1083
1084            let kind = call_kind(
1085                self.infcx.tcx,
1086                self.infcx.typing_env(self.infcx.param_env),
1087                method_did,
1088                method_args,
1089                *fn_span,
1090                call_source.from_hir_call(),
1091                self.infcx.tcx.fn_arg_idents(method_did)[0],
1092            );
1093
1094            return FnSelfUse {
1095                var_span: stmt.source_info.span,
1096                fn_call_span: *fn_span,
1097                fn_span: self.infcx.tcx.def_span(method_did),
1098                kind,
1099            };
1100        }
1101
1102        normal_ret
1103    }
1104
1105    /// Finds the span of arguments of a closure (within `maybe_closure_span`)
1106    /// and its usage of the local assigned at `location`.
1107    /// This is done by searching in statements succeeding `location`
1108    /// and originating from `maybe_closure_span`.
1109    pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans<'tcx> {
1110        use self::UseSpans::*;
1111        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1111",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1111u32),
                        ::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);
1112
1113        let Some(Statement { kind: StatementKind::Assign((place, _)), .. }) =
1114            self.body[location.block].statements.get(location.statement_index)
1115        else {
1116            return OtherUse(use_span);
1117        };
1118        let Some(target) = place.as_local() else { return OtherUse(use_span) };
1119
1120        if self.body.local_kind(target) != LocalKind::Temp {
1121            // operands are always temporaries.
1122            return OtherUse(use_span);
1123        }
1124
1125        // drop and replace might have moved the assignment to the next block
1126        let maybe_additional_statement =
1127            if let TerminatorKind::Drop { target: drop_target, .. } =
1128                self.body[location.block].terminator().kind
1129            {
1130                self.body[drop_target].statements.first()
1131            } else {
1132                None
1133            };
1134
1135        let statements =
1136            self.body[location.block].statements[location.statement_index + 1..].iter();
1137
1138        for stmt in statements.chain(maybe_additional_statement) {
1139            if let StatementKind::Assign((_, Rvalue::Aggregate(kind, places))) = &stmt.kind {
1140                let (&def_id, is_coroutine) = match kind {
1141                    AggregateKind::Closure(def_id, _) => (def_id, false),
1142                    AggregateKind::Coroutine(def_id, _) => (def_id, true),
1143                    _ => continue,
1144                };
1145                let def_id = def_id.expect_local();
1146
1147                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1147",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1147u32),
                        ::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!(
1148                    "borrow_spans: def_id={:?} is_coroutine={:?} places={:?}",
1149                    def_id, is_coroutine, places
1150                );
1151                if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1152                    self.closure_span(def_id, Place::from(target).as_ref(), places)
1153                {
1154                    return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };
1155                } else {
1156                    return OtherUse(use_span);
1157                }
1158            }
1159
1160            if use_span != stmt.source_info.span {
1161                break;
1162            }
1163        }
1164
1165        OtherUse(use_span)
1166    }
1167
1168    /// Finds the spans of a captured place within a closure or coroutine.
1169    /// The first span is the location of the use resulting in the capture kind of the capture
1170    /// The second span is the location the use resulting in the captured path of the capture
1171    fn closure_span(
1172        &self,
1173        def_id: LocalDefId,
1174        target_place: PlaceRef<'tcx>,
1175        places: &IndexSlice<FieldIdx, Operand<'tcx>>,
1176    ) -> Option<(Span, hir::ClosureKind, Span, Span)> {
1177        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1177",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1177u32),
                        ::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!(
1178            "closure_span: def_id={:?} target_place={:?} places={:?}",
1179            def_id, target_place, places
1180        );
1181        let hir_id = self.infcx.tcx.local_def_id_to_hir_id(def_id);
1182        let expr = &self.infcx.tcx.hir_expect_expr(hir_id).kind;
1183        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1183",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1183u32),
                        ::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);
1184        if let &hir::ExprKind::Closure(&hir::Closure { kind, fn_decl_span, .. }) = expr {
1185            for (captured_place, place) in
1186                self.infcx.tcx.closure_captures(def_id).iter().zip(places)
1187            {
1188                match place {
1189                    Operand::Copy(place) | Operand::Move(place)
1190                        if target_place == place.as_ref() =>
1191                    {
1192                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs:1192",
                        "rustc_borrowck::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1192u32),
                        ::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);
1193                        return Some((
1194                            fn_decl_span,
1195                            kind,
1196                            captured_place.get_capture_kind_span(self.infcx.tcx),
1197                            captured_place.get_path_span(self.infcx.tcx),
1198                        ));
1199                    }
1200                    _ => {}
1201                }
1202            }
1203        }
1204        None
1205    }
1206
1207    /// Helper to retrieve span(s) of given borrow from the current MIR
1208    /// representation
1209    pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans<'tcx> {
1210        let span = self.body.source_info(borrow.reserve_location).span;
1211        self.borrow_spans(span, borrow.reserve_location)
1212    }
1213
1214    fn explain_captures(
1215        &mut self,
1216        err: &mut Diag<'_>,
1217        span: Span,
1218        move_span: Span,
1219        move_spans: UseSpans<'tcx>,
1220        moved_place: Place<'tcx>,
1221        msg_opt: CapturedMessageOpt,
1222    ) -> CloneSuggestion {
1223        let CapturedMessageOpt {
1224            is_partial_move: is_partial,
1225            is_loop_message,
1226            is_move_msg,
1227            is_loop_move,
1228            has_suggest_reborrow,
1229            maybe_reinitialized_locations_is_empty,
1230        } = msg_opt;
1231        let mut suggested_cloning = false;
1232        if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } = move_spans {
1233            let place_name = self
1234                .describe_place(moved_place.as_ref())
1235                .map(|n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`"))
1236                .unwrap_or_else(|| "value".to_owned());
1237            match kind {
1238                CallKind::FnCall { fn_trait_id, self_ty }
1239                    if self.infcx.tcx.is_lang_item(fn_trait_id, LangItem::FnOnce) =>
1240                {
1241                    err.subdiagnostic(CaptureReasonLabel::Call {
1242                        fn_call_span,
1243                        place_name: &place_name,
1244                        is_partial,
1245                        is_loop_message,
1246                    });
1247                    // Check if the move occurs on a value because of a call on a closure that comes
1248                    // from a type parameter `F: FnOnce()`. If so, we provide a targeted `note`:
1249                    // ```
1250                    // error[E0382]: use of moved value: `blk`
1251                    //   --> $DIR/once-cant-call-twice-on-heap.rs:8:5
1252                    //    |
1253                    // LL | fn foo<F:FnOnce()>(blk: F) {
1254                    //    |                    --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
1255                    // LL | blk();
1256                    //    | ----- `blk` moved due to this call
1257                    // LL | blk();
1258                    //    | ^^^ value used here after move
1259                    //    |
1260                    // note: `FnOnce` closures can only be called once
1261                    //   --> $DIR/once-cant-call-twice-on-heap.rs:6:10
1262                    //    |
1263                    // LL | fn foo<F:FnOnce()>(blk: F) {
1264                    //    |        ^^^^^^^^ `F` is made to be an `FnOnce` closure here
1265                    // LL | blk();
1266                    //    | ----- this value implements `FnOnce`, which causes it to be moved when called
1267                    // ```
1268                    if let ty::Param(param_ty) = *self_ty.kind()
1269                        && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1270                        && let param = generics.type_param(param_ty, self.infcx.tcx)
1271                        && let Some(hir_generics) = self.infcx.tcx.hir_get_generics(
1272                            self.infcx.tcx.typeck_root_def_id_local(self.mir_def_id()),
1273                        )
1274                        && let spans = hir_generics
1275                            .predicates
1276                            .iter()
1277                            .filter_map(|pred| match pred.kind {
1278                                hir::WherePredicateKind::BoundPredicate(pred) => Some(pred),
1279                                _ => None,
1280                            })
1281                            .filter(|pred| {
1282                                if let Some((id, _)) = pred.bounded_ty.as_generic_param() {
1283                                    id == param.def_id
1284                                } else {
1285                                    false
1286                                }
1287                            })
1288                            .flat_map(|pred| pred.bounds)
1289                            .filter_map(|bound| {
1290                                if let Some(trait_ref) = bound.trait_ref()
1291                                    && let Some(trait_def_id) = trait_ref.trait_def_id()
1292                                    && trait_def_id == fn_trait_id
1293                                {
1294                                    Some(bound.span())
1295                                } else {
1296                                    None
1297                                }
1298                            })
1299                            .collect::<Vec<Span>>()
1300                        && !spans.is_empty()
1301                    {
1302                        let mut span: MultiSpan = spans.clone().into();
1303                        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")
1304                            .arg("ty", param_ty.to_string())
1305                            .format();
1306                        for sp in spans {
1307                            span.push_span_label(sp, msg.clone());
1308                        }
1309                        span.push_span_label(
1310                            fn_call_span,
1311                            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"),
1312                        );
1313                        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"));
1314                    } else {
1315                        err.subdiagnostic(CaptureReasonNote::FnOnceMoveInCall { var_span });
1316                    }
1317                }
1318                CallKind::Operator { self_arg, trait_id, .. } => {
1319                    let self_arg = self_arg.unwrap();
1320                    err.subdiagnostic(CaptureReasonLabel::OperatorUse {
1321                        fn_call_span,
1322                        place_name: &place_name,
1323                        is_partial,
1324                        is_loop_message,
1325                    });
1326                    if self.fn_self_span_reported.insert(fn_span) {
1327                        let lang = self.infcx.tcx.lang_items();
1328                        err.subdiagnostic(
1329                            if [lang.not_trait(), lang.deref_trait(), lang.neg_trait()]
1330                                .contains(&Some(trait_id))
1331                            {
1332                                CaptureReasonNote::UnOpMoveByOperator { span: self_arg.span }
1333                            } else {
1334                                CaptureReasonNote::LhsMoveByOperator { span: self_arg.span }
1335                            },
1336                        );
1337                    }
1338                }
1339                CallKind::Normal { self_arg, desugaring, method_did, method_args } => {
1340                    let self_arg = self_arg.unwrap();
1341                    let mut has_sugg = false;
1342                    let tcx = self.infcx.tcx;
1343                    // Avoid pointing to the same function in multiple different
1344                    // error messages.
1345                    if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) {
1346                        self.explain_iterator_advancement_in_for_loop_if_applicable(
1347                            err,
1348                            span,
1349                            &move_spans,
1350                        );
1351
1352                        let func = { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(method_did) }with_no_trimmed_paths!(tcx.def_path_str(method_did));
1353                        let mut span: MultiSpan = self_arg.span.into();
1354                        span.push_span_context(tcx.def_span(method_did).shrink_to_lo());
1355                        span.push_span_context(tcx.def_span(tcx.parent(method_did)).shrink_to_lo());
1356                        if let Some((kind, _)) = desugaring {
1357                            err.subdiagnostic(CaptureReasonNote::DesugaringFuncTakeSelf {
1358                                func,
1359                                desugar_name: kind.name(),
1360                                place_name: place_name.clone(),
1361                                span,
1362                            });
1363                        } else {
1364                            err.subdiagnostic(CaptureReasonNote::FuncTakeSelf {
1365                                func,
1366                                place_name: place_name.clone(),
1367                                span,
1368                            });
1369                        }
1370                    }
1371                    let parent_did = tcx.parent(method_did);
1372                    let parent_self_ty =
1373                        #[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 { .. })
1374                            .then_some(parent_did)
1375                            .and_then(|did| {
1376                                match tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()
1377                                {
1378                                    ty::Adt(def, ..) => Some(def.did()),
1379                                    _ => None,
1380                                }
1381                            });
1382                    let is_option_or_result = parent_self_ty.is_some_and(|def_id| {
1383                        #[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))
1384                    });
1385                    if is_option_or_result && maybe_reinitialized_locations_is_empty {
1386                        err.subdiagnostic(CaptureReasonLabel::BorrowContent {
1387                            var_span: var_span.shrink_to_hi(),
1388                        });
1389                    }
1390                    if let Some((
1391                        kind @ (CallDesugaringKind::ForLoopIntoIter
1392                        | CallDesugaringKind::ForLoopIntoAsyncIter),
1393                        _,
1394                    )) = desugaring
1395                    {
1396                        let ty = moved_place.ty(self.body, tcx).ty;
1397                        let def_id = kind.trait_def_id(tcx);
1398                        let suggest = type_known_to_meet_bound_modulo_regions(
1399                            self.infcx,
1400                            self.infcx.param_env,
1401                            Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty),
1402                            def_id,
1403                        );
1404                        if suggest {
1405                            err.subdiagnostic(CaptureReasonSuggest::IterateSlice {
1406                                ty,
1407                                span: move_span.shrink_to_lo(),
1408                            });
1409                        }
1410
1411                        match kind {
1412                            CallDesugaringKind::ForLoopIntoIter => {
1413                                err.subdiagnostic(CaptureReasonLabel::ImplicitCall {
1414                                    fn_call_span,
1415                                    place_name: &place_name,
1416                                    is_partial,
1417                                    is_loop_message,
1418                                });
1419                            }
1420                            CallDesugaringKind::ForLoopIntoAsyncIter => {
1421                                err.subdiagnostic(CaptureReasonLabel::ImplicitAsyncCall {
1422                                    fn_call_span,
1423                                    place_name: &place_name,
1424                                    is_partial,
1425                                    is_loop_message,
1426                                });
1427                            }
1428                            _ => {}
1429                        }
1430                        // If the moved place was a `&mut` ref, then we can
1431                        // suggest to reborrow it where it was moved, so it
1432                        // will still be valid by the time we get to the usage.
1433                        if let ty::Ref(_, _, hir::Mutability::Mut) =
1434                            moved_place.ty(self.body, self.infcx.tcx).ty.kind()
1435                        {
1436                            // The `&mut *place` reborrow suggestion is `MachineApplicable`, so
1437                            // only offer it where `*place` can be borrowed mutably: a value
1438                            // captured by an `Fn` closure (held via `&self`) cannot, and the
1439                            // suggestion would otherwise fail to compile with E0596.
1440                            let reborrow_place = self.infcx.tcx.mk_place_deref(moved_place);
1441                            let reborrow_is_valid = self
1442                                .is_mutable(reborrow_place.as_ref(), LocalMutationIsAllowed::No)
1443                                .is_ok();
1444                            // Suggest `reborrow` in other place for following situations:
1445                            // 1. If we are in a loop this will be suggested later.
1446                            // 2. If the moved value is a mut reference, it is used in a
1447                            // generic function and the corresponding arg's type is generic param.
1448                            if !is_loop_move && !has_suggest_reborrow && reborrow_is_valid {
1449                                self.suggest_reborrow(
1450                                    err,
1451                                    move_span.shrink_to_lo(),
1452                                    moved_place.as_ref(),
1453                                );
1454                            }
1455                        }
1456                    } else {
1457                        match desugaring {
1458                            Some((CallDesugaringKind::Await, _)) => {
1459                                err.subdiagnostic(CaptureReasonLabel::Await {
1460                                    fn_call_span,
1461                                    place_name: &place_name,
1462                                    is_partial,
1463                                    is_loop_message,
1464                                });
1465                            }
1466                            Some((CallDesugaringKind::QuestionBranch, _)) => {
1467                                err.subdiagnostic(CaptureReasonLabel::QuestionMark {
1468                                    fn_call_span,
1469                                    place_name: &place_name,
1470                                    is_partial,
1471                                    is_loop_message,
1472                                });
1473                            }
1474                            _ => {
1475                                err.subdiagnostic(CaptureReasonLabel::MethodCall {
1476                                    fn_call_span,
1477                                    place_name: &place_name,
1478                                    is_partial,
1479                                    is_loop_message,
1480                                });
1481                            }
1482                        }
1483                        // Erase and shadow everything that could be passed to the new infcx.
1484                        let ty = moved_place.ty(self.body, tcx).ty;
1485
1486                        if let ty::Adt(def, args) = ty.peel_refs().kind()
1487                            && tcx.is_lang_item(def.did(), LangItem::Pin)
1488                            && let ty::Ref(_, _, hir::Mutability::Mut) = args.type_at(0).kind()
1489                            && let self_ty = self.infcx.instantiate_binder_with_fresh_vars(
1490                                fn_call_span,
1491                                BoundRegionConversionTime::FnCall,
1492                                tcx.fn_sig(method_did)
1493                                    .instantiate(tcx, method_args)
1494                                    .skip_norm_wip()
1495                                    .input(0),
1496                            )
1497                            && self.infcx.can_eq(self.infcx.param_env, ty, self_ty)
1498                        {
1499                            err.subdiagnostic(CaptureReasonSuggest::FreshReborrow {
1500                                span: move_span.shrink_to_hi(),
1501                            });
1502                            has_sugg = true;
1503                        }
1504                        if let Some(clone_trait) = tcx.lang_items().clone_trait() {
1505                            // Check whether the deref is from a custom Deref impl
1506                            // (e.g. Rc, Box) or a built-in reference deref.
1507                            // For built-in derefs with Clone fully satisfied, we skip
1508                            // the UFCS suggestion here and let `suggest_cloning`
1509                            // downstream emit a simpler `.clone()` suggestion instead.
1510                            let has_overloaded_deref =
1511                                moved_place.iter_projections().any(|(place, elem)| {
1512                                    #[allow(non_exhaustive_omitted_patterns)] match elem {
    ProjectionElem::Deref => true,
    _ => false,
}matches!(elem, ProjectionElem::Deref)
1513                                        && #[allow(non_exhaustive_omitted_patterns)] match self.borrowed_content_source(place)
    {
    BorrowedContentSource::OverloadedDeref(_) |
        BorrowedContentSource::OverloadedIndex(_) => true,
    _ => false,
}matches!(
1514                                            self.borrowed_content_source(place),
1515                                            BorrowedContentSource::OverloadedDeref(_)
1516                                                | BorrowedContentSource::OverloadedIndex(_)
1517                                        )
1518                                });
1519
1520                            let has_deref = moved_place
1521                                .iter_projections()
1522                                .any(|(_, elem)| #[allow(non_exhaustive_omitted_patterns)] match elem {
    ProjectionElem::Deref => true,
    _ => false,
}matches!(elem, ProjectionElem::Deref));
1523
1524                            let sugg = if has_deref {
1525                                let (start, end) = if let Some(expr) = self.find_expr(move_span)
1526                                    && let Some(_) = self.clone_on_reference(expr)
1527                                    && let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind
1528                                {
1529                                    (move_span.shrink_to_lo(), move_span.with_lo(rcvr.span.hi()))
1530                                } else {
1531                                    (move_span.shrink_to_lo(), move_span.shrink_to_hi())
1532                                };
1533                                ::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![
1534                                    // We use the fully-qualified path because `.clone()` can
1535                                    // sometimes choose `<&T as Clone>` instead of `<T as Clone>`
1536                                    // when going through auto-deref, so this ensures that doesn't
1537                                    // happen, causing suggestions for `.clone().clone()`.
1538                                    (start, format!("<{ty} as Clone>::clone(&")),
1539                                    (end, ")".to_string()),
1540                                ]
1541                            } else {
1542                                ::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())]
1543                            };
1544                            if let Some(errors) = self.infcx.type_implements_trait_shallow(
1545                                clone_trait,
1546                                ty,
1547                                self.infcx.param_env,
1548                            ) && !has_sugg
1549                            {
1550                                let skip_for_simple_clone =
1551                                    has_deref && !has_overloaded_deref && errors.no_errors();
1552                                if !skip_for_simple_clone {
1553                                    let msg = match errors.as_slice() {
1554                                        [] => "you can `clone` the value and consume it, but \
1555                                               this might not be your desired behavior"
1556                                            .to_string(),
1557                                        [error] => {
1558                                            ::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!(
1559                                                "you could `clone` the value and consume it, if \
1560                                                 the `{}` trait bound could be satisfied",
1561                                                error.obligation.predicate,
1562                                            )
1563                                        }
1564                                        _ => {
1565                                            ::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!(
1566                                                "you could `clone` the value and consume it, if \
1567                                                 the following trait bounds could be satisfied: \
1568                                                 {}",
1569                                                listify(
1570                                                    errors.as_slice(),
1571                                                    |e: &FulfillmentError<'tcx>| format!(
1572                                                        "`{}`",
1573                                                        e.obligation.predicate
1574                                                    )
1575                                                )
1576                                                .unwrap(),
1577                                            )
1578                                        }
1579                                    };
1580                                    err.multipart_suggestion(
1581                                        msg,
1582                                        sugg,
1583                                        Applicability::MaybeIncorrect,
1584                                    );
1585
1586                                    suggested_cloning = errors.no_errors();
1587
1588                                    for error in errors {
1589                                        if let FulfillmentErrorCode::Select(
1590                                            SelectionError::Unimplemented,
1591                                        ) = error.code
1592                                            && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(
1593                                                pred,
1594                                            )) = error.obligation.predicate.kind().skip_binder()
1595                                        {
1596                                            self.infcx.err_ctxt().suggest_derive(
1597                                                &error.obligation,
1598                                                err,
1599                                                error.obligation.predicate.kind().rebind(pred),
1600                                            );
1601                                        }
1602                                    }
1603                                }
1604                            }
1605                        }
1606                    }
1607                }
1608                // Other desugarings takes &self, which cannot cause a move
1609                _ => {}
1610            }
1611        } else {
1612            if move_span != span || is_loop_message {
1613                err.subdiagnostic(CaptureReasonLabel::MovedHere {
1614                    move_span,
1615                    is_partial,
1616                    is_move_msg,
1617                    is_loop_message,
1618                });
1619            }
1620            // If the move error occurs due to a loop, don't show
1621            // another message for the same span
1622            if !is_loop_message {
1623                move_spans.var_subdiag(err, None, |kind, var_span| match kind {
1624                    hir::ClosureKind::Coroutine(_) => {
1625                        CaptureVarCause::PartialMoveUseInCoroutine { var_span, is_partial }
1626                    }
1627                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1628                        CaptureVarCause::PartialMoveUseInClosure { var_span, is_partial }
1629                    }
1630                })
1631            }
1632        }
1633        if suggested_cloning { CloneSuggestion::Emitted } else { CloneSuggestion::NotEmitted }
1634    }
1635
1636    /// Skip over locals that begin with an underscore or have no name
1637    pub(crate) fn local_excluded_from_unused_mut_lint(&self, index: Local) -> bool {
1638        self.local_name(index).is_none_or(|name| name.as_str().starts_with('_'))
1639    }
1640}
1641
1642const LIMITATION_NOTE: DiagMessage =
1643    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");