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