Skip to main content

rustc_borrowck/diagnostics/
mod.rs

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