Skip to main content

rustc_borrowck/diagnostics/
conflict_errors.rs

1// ignore-tidy-filelength
2
3use std::iter;
4use std::ops::ControlFlow;
5
6use either::Either;
7use hir::{ClosureKind, Path};
8use rustc_data_structures::fx::FxIndexSet;
9use rustc_errors::codes::*;
10use rustc_errors::{Applicability, Diag, MultiSpan, struct_span_code_err};
11use rustc_hir as hir;
12use rustc_hir::attrs::diagnostic::{CustomDiagnostic, FormatArgs};
13use rustc_hir::def::{DefKind, Res};
14use rustc_hir::intravisit::{Visitor, walk_block, walk_expr};
15use rustc_hir::{
16    CoroutineDesugaring, CoroutineKind, CoroutineSource, LangItem, PatField, find_attr,
17};
18use rustc_index::bit_set::DenseBitSet;
19use rustc_middle::bug;
20use rustc_middle::hir::nested_filter::OnlyBodies;
21use rustc_middle::mir::{
22    self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
23    FakeBorrowKind, FakeReadCause, LocalDecl, LocalInfo, LocalKind, Location, MutBorrowKind,
24    Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement, StatementKind,
25    Terminator, TerminatorKind, VarBindingForm, VarDebugInfoContents,
26};
27use rustc_middle::ty::print::PrintTraitRefExt as _;
28use rustc_middle::ty::{
29    self, PredicateKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, Upcast,
30    suggest_constraining_type_params,
31};
32use rustc_mir_dataflow::move_paths::{Init, InitKind, InitLocation, MoveOutIndex, MovePathIndex};
33use rustc_span::def_id::{DefId, LocalDefId};
34use rustc_span::hygiene::DesugaringKind;
35use rustc_span::{BytePos, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym};
36use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
37use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
38use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
39use rustc_trait_selection::infer::InferCtxtExt;
40use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
41use rustc_trait_selection::traits::{
42    Obligation, ObligationCause, ObligationCtxt, supertrait_def_ids,
43};
44use tracing::{debug, instrument};
45
46use super::explain_borrow::{BorrowExplanation, LaterUseKind};
47use super::{DescribePlaceOpt, RegionName, RegionNameSource, UseSpans};
48use crate::borrow_set::{BorrowData, TwoPhaseActivation};
49use crate::diagnostics::conflict_errors::StorageDeadOrDrop::LocalStorageDead;
50use crate::diagnostics::{CapturedMessageOpt, call_kind, find_all_local_uses};
51use crate::{InitializationRequiringAction, MirBorrowckCtxt, WriteKind, borrowck_errors};
52
53#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MoveSite {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "MoveSite",
            "moi", &self.moi, "traversed_back_edge",
            &&self.traversed_back_edge)
    }
}Debug)]
54struct MoveSite {
55    /// Index of the "move out" that we found. The `MoveData` can
56    /// then tell us where the move occurred.
57    moi: MoveOutIndex,
58
59    /// `true` if we traversed a back edge while walking from the point
60    /// of error to the move site.
61    traversed_back_edge: bool,
62}
63
64/// Which case a StorageDeadOrDrop is for.
65#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for StorageDeadOrDrop<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for StorageDeadOrDrop<'tcx> {
    #[inline]
    fn clone(&self) -> StorageDeadOrDrop<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for StorageDeadOrDrop<'tcx> {
    #[inline]
    fn eq(&self, other: &StorageDeadOrDrop<'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) {
                (StorageDeadOrDrop::Destructor(__self_0),
                    StorageDeadOrDrop::Destructor(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for StorageDeadOrDrop<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for StorageDeadOrDrop<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            StorageDeadOrDrop::LocalStorageDead =>
                ::core::fmt::Formatter::write_str(f, "LocalStorageDead"),
            StorageDeadOrDrop::BoxedStorageDead =>
                ::core::fmt::Formatter::write_str(f, "BoxedStorageDead"),
            StorageDeadOrDrop::Destructor(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Destructor", &__self_0),
        }
    }
}Debug)]
66enum StorageDeadOrDrop<'tcx> {
67    LocalStorageDead,
68    BoxedStorageDead,
69    Destructor(Ty<'tcx>),
70}
71
72impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
73    pub(crate) fn report_use_of_moved_or_uninitialized(
74        &mut self,
75        location: Location,
76        desired_action: InitializationRequiringAction,
77        (moved_place, used_place, span): (PlaceRef<'tcx>, PlaceRef<'tcx>, Span),
78        mpi: MovePathIndex,
79    ) {
80        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:80",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(80u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: location={0:?} desired_action={1:?} moved_place={2:?} used_place={3:?} span={4:?} mpi={5:?}",
                                                    location, desired_action, moved_place, used_place, span,
                                                    mpi) as &dyn Value))])
            });
    } else { ; }
};debug!(
81            "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
82             moved_place={:?} used_place={:?} span={:?} mpi={:?}",
83            location, desired_action, moved_place, used_place, span, mpi
84        );
85
86        let use_spans =
87            self.move_spans(moved_place, location).or_else(|| self.borrow_spans(span, location));
88        let span = use_spans.args_or_use();
89
90        let (move_site_vec, maybe_reinitialized_locations) = self.get_moved_indexes(location, mpi);
91        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:91",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(91u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: move_site_vec={0:?} use_spans={1:?}",
                                                    move_site_vec, use_spans) as &dyn Value))])
            });
    } else { ; }
};debug!(
92            "report_use_of_moved_or_uninitialized: move_site_vec={:?} use_spans={:?}",
93            move_site_vec, use_spans
94        );
95        let move_out_indices: Vec<_> =
96            move_site_vec.iter().map(|move_site| move_site.moi).collect();
97
98        if move_out_indices.is_empty() {
99            let root_local = used_place.local;
100
101            if !self.uninitialized_error_reported.insert(root_local) {
102                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:102",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(102u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized place: error about {0:?} suppressed",
                                                    root_local) as &dyn Value))])
            });
    } else { ; }
};debug!(
103                    "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
104                    root_local
105                );
106                return;
107            }
108
109            let err = self.report_use_of_uninitialized(
110                mpi,
111                used_place,
112                moved_place,
113                desired_action,
114                location,
115                span,
116                use_spans,
117            );
118            self.buffer_error(err);
119        } else {
120            if let Some((reported_place, _)) = self.has_move_error(&move_out_indices) {
121                if used_place.is_prefix_of(*reported_place) {
122                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:122",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(122u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized place: error suppressed mois={0:?}",
                                                    move_out_indices) as &dyn Value))])
            });
    } else { ; }
};debug!(
123                        "report_use_of_moved_or_uninitialized place: error suppressed mois={:?}",
124                        move_out_indices
125                    );
126                    return;
127                }
128            }
129
130            let is_partial_move = move_site_vec.iter().any(|move_site| {
131                let move_out = self.move_data.moves[(*move_site).moi];
132                let moved_place = &self.move_data.move_paths[move_out.path].place;
133                // `*(_1)` where `_1` is a `Box` is actually a move out.
134                let is_box_move = moved_place.as_ref().projection == [ProjectionElem::Deref]
135                    && self.body.local_decls[moved_place.local].ty.is_box();
136
137                !is_box_move
138                    && used_place != moved_place.as_ref()
139                    && used_place.is_prefix_of(moved_place.as_ref())
140            });
141
142            let partial_str = if is_partial_move { "partial " } else { "" };
143            let partially_str = if is_partial_move { "partially " } else { "" };
144
145            let (on_move_message, on_move_label, on_move_notes) = if let ty::Adt(item_def, args) =
146                self.body.local_decls[moved_place.local].ty.kind()
147                && let Some(Some(directive)) = {
    {
        'done:
            {
            for i in
                ::rustc_hir::attrs::HasAttrs::get_attrs(item_def.did(),
                    &self.infcx.tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(OnMove { directive, .. }) => {
                        break 'done Some(directive);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.infcx.tcx, item_def.did(), OnMove { directive, .. }  => directive)
148            {
149                let this = self.infcx.tcx.item_name(item_def.did()).to_string();
150                let mut generic_args: Vec<_> = self
151                    .infcx
152                    .tcx
153                    .generics_of(item_def.did())
154                    .own_params
155                    .iter()
156                    .filter_map(|param| Some((param.name, args[param.index as usize].to_string())))
157                    .collect();
158                generic_args.push((kw::SelfUpper, this.clone()));
159
160                let args = FormatArgs { this, generic_args, .. };
161                let CustomDiagnostic { message, label, notes, parent_label: _ } =
162                    directive.eval(None, &args);
163
164                (message, label, notes)
165            } else {
166                (None, None, Vec::new())
167            };
168
169            let mut err = self.cannot_act_on_moved_value(
170                span,
171                desired_action.as_noun(),
172                partially_str,
173                self.describe_place_with_options(
174                    moved_place,
175                    DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
176                ),
177                on_move_message,
178            );
179
180            for note in on_move_notes {
181                err.note(note);
182            }
183
184            let reinit_spans = maybe_reinitialized_locations
185                .iter()
186                .take(3)
187                .map(|loc| {
188                    self.move_spans(self.move_data.move_paths[mpi].place.as_ref(), *loc)
189                        .args_or_use()
190                })
191                .collect::<Vec<Span>>();
192
193            let reinits = maybe_reinitialized_locations.len();
194            if reinits == 1 {
195                err.span_label(reinit_spans[0], "this reinitialization might get skipped");
196            } else if reinits > 1 {
197                err.span_note(
198                    MultiSpan::from_spans(reinit_spans),
199                    if reinits <= 3 {
200                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("these {0} reinitializations might get skipped",
                reinits))
    })format!("these {reinits} reinitializations might get skipped")
201                    } else {
202                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("these 3 reinitializations and {0} other{1} might get skipped",
                reinits - 3, if reinits == 4 { "" } else { "s" }))
    })format!(
203                            "these 3 reinitializations and {} other{} might get skipped",
204                            reinits - 3,
205                            if reinits == 4 { "" } else { "s" }
206                        )
207                    },
208                );
209            }
210
211            let closure = self.add_moved_or_invoked_closure_note(location, used_place, &mut err);
212
213            let mut is_loop_move = false;
214            let mut seen_spans = FxIndexSet::default();
215
216            for move_site in &move_site_vec {
217                let move_out = self.move_data.moves[(*move_site).moi];
218                let moved_place = &self.move_data.move_paths[move_out.path].place;
219
220                let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
221                let move_span = move_spans.args_or_use();
222
223                let is_move_msg = move_spans.for_closure();
224
225                let is_loop_message = location == move_out.source || move_site.traversed_back_edge;
226
227                if location == move_out.source {
228                    is_loop_move = true;
229                }
230
231                let mut has_suggest_reborrow = false;
232                if !seen_spans.contains(&move_span) {
233                    self.suggest_ref_or_clone(
234                        mpi,
235                        &mut err,
236                        move_spans,
237                        moved_place.as_ref(),
238                        &mut has_suggest_reborrow,
239                        closure,
240                    );
241
242                    let msg_opt = CapturedMessageOpt {
243                        is_partial_move,
244                        is_loop_message,
245                        is_move_msg,
246                        is_loop_move,
247                        has_suggest_reborrow,
248                        maybe_reinitialized_locations_is_empty: maybe_reinitialized_locations
249                            .is_empty(),
250                    };
251                    self.explain_captures(
252                        &mut err,
253                        span,
254                        move_span,
255                        move_spans,
256                        *moved_place,
257                        msg_opt,
258                    );
259                }
260                seen_spans.insert(move_span);
261            }
262
263            use_spans.var_path_only_subdiag(&mut err, desired_action);
264
265            if !is_loop_move {
266                err.span_label(
267                    span,
268                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("value {0} here after {1}move",
                desired_action.as_verb_in_past_tense(), partial_str))
    })format!(
269                        "value {} here after {partial_str}move",
270                        desired_action.as_verb_in_past_tense(),
271                    ),
272                );
273            }
274
275            let ty = used_place.ty(self.body, self.infcx.tcx).ty;
276            let needs_note = match ty.kind() {
277                ty::Closure(id, _) => {
278                    self.infcx.tcx.closure_kind_origin(id.expect_local()).is_none()
279                }
280                _ => true,
281            };
282
283            let mpi = self.move_data.moves[move_out_indices[0]].path;
284            let place = &self.move_data.move_paths[mpi].place;
285            let ty = place.ty(self.body, self.infcx.tcx).ty;
286
287            if self.infcx.param_env.caller_bounds().iter().any(|c| {
288                c.as_trait_clause().is_some_and(|pred| {
289                    pred.skip_binder().self_ty() == ty && self.infcx.tcx.is_fn_trait(pred.def_id())
290                })
291            }) {
292                // Suppress the next suggestion since we don't want to put more bounds onto
293                // something that already has `Fn`-like bounds (or is a closure), so we can't
294                // restrict anyways.
295            } else {
296                let copy_did = self.infcx.tcx.require_lang_item(LangItem::Copy, span);
297                self.suggest_adding_bounds(&mut err, ty, copy_did, span);
298            }
299
300            let opt_name = self.describe_place_with_options(
301                place.as_ref(),
302                DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
303            );
304            let note_msg = match opt_name {
305                Some(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"),
306                None => "value".to_owned(),
307            };
308            if needs_note {
309                if let Some(local) = place.as_local() {
310                    let span = self.body.local_decls[local].source_info.span;
311                    if let Some(on_move_label) = on_move_label {
312                        err.span_label(span, on_move_label);
313                    } else {
314                        err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
315                            is_partial_move,
316                            ty,
317                            place: &note_msg,
318                            span,
319                        });
320                    }
321                } else {
322                    err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Note {
323                        is_partial_move,
324                        ty,
325                        place: &note_msg,
326                    });
327                };
328            }
329
330            if let UseSpans::FnSelfUse {
331                kind: CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. },
332                ..
333            } = use_spans
334            {
335                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} occurs due to deref coercion to `{1}`",
                desired_action.as_noun(), deref_target_ty))
    })format!(
336                    "{} occurs due to deref coercion to `{deref_target_ty}`",
337                    desired_action.as_noun(),
338                ));
339
340                // Check first whether the source is accessible (issue #87060)
341                if let Some(deref_target_span) = deref_target_span
342                    && self.infcx.tcx.sess.source_map().is_span_accessible(deref_target_span)
343                {
344                    err.span_note(deref_target_span, "deref defined here");
345                }
346            }
347
348            self.buffer_move_error(move_out_indices, (used_place, err));
349        }
350    }
351
352    fn suggest_ref_or_clone(
353        &self,
354        mpi: MovePathIndex,
355        err: &mut Diag<'infcx>,
356        move_spans: UseSpans<'tcx>,
357        moved_place: PlaceRef<'tcx>,
358        has_suggest_reborrow: &mut bool,
359        moved_or_invoked_closure: bool,
360    ) {
361        let move_span = match move_spans {
362            UseSpans::ClosureUse { capture_kind_span, .. } => capture_kind_span,
363            _ => move_spans.args_or_use(),
364        };
365        struct ExpressionFinder<'hir> {
366            expr_span: Span,
367            expr: Option<&'hir hir::Expr<'hir>>,
368            pat: Option<&'hir hir::Pat<'hir>>,
369            parent_pat: Option<&'hir hir::Pat<'hir>>,
370            tcx: TyCtxt<'hir>,
371        }
372        impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
373            type NestedFilter = OnlyBodies;
374
375            fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
376                self.tcx
377            }
378
379            fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
380                if e.span == self.expr_span {
381                    self.expr = Some(e);
382                }
383                hir::intravisit::walk_expr(self, e);
384            }
385            fn visit_pat(&mut self, p: &'hir hir::Pat<'hir>) {
386                if p.span == self.expr_span {
387                    self.pat = Some(p);
388                }
389                if let hir::PatKind::Binding(hir::BindingMode::NONE, _, i, sub) = p.kind {
390                    if i.span == self.expr_span || p.span == self.expr_span {
391                        self.pat = Some(p);
392                    }
393                    // Check if we are in a situation of `ident @ ident` where we want to suggest
394                    // `ref ident @ ref ident` or `ref ident @ Struct { ref ident }`.
395                    if let Some(subpat) = sub
396                        && self.pat.is_none()
397                    {
398                        self.visit_pat(subpat);
399                        if self.pat.is_some() {
400                            self.parent_pat = Some(p);
401                        }
402                        return;
403                    }
404                }
405                hir::intravisit::walk_pat(self, p);
406            }
407        }
408        let tcx = self.infcx.tcx;
409        if let Some(body) = tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
410            let expr = body.value;
411            let place = &self.move_data.move_paths[mpi].place;
412            let span = place.as_local().map(|local| self.body.local_decls[local].source_info.span);
413            let mut finder = ExpressionFinder {
414                expr_span: move_span,
415                expr: None,
416                pat: None,
417                parent_pat: None,
418                tcx,
419            };
420            finder.visit_expr(expr);
421            if let Some(span) = span
422                && let Some(expr) = finder.expr
423            {
424                for (_, expr) in tcx.hir_parent_iter(expr.hir_id) {
425                    if let hir::Node::Expr(expr) = expr {
426                        if expr.span.contains(span) {
427                            // If the let binding occurs within the same loop, then that
428                            // loop isn't relevant, like in the following, the outermost `loop`
429                            // doesn't play into `x` being moved.
430                            // ```
431                            // loop {
432                            //     let x = String::new();
433                            //     loop {
434                            //         foo(x);
435                            //     }
436                            // }
437                            // ```
438                            break;
439                        }
440                        if let hir::ExprKind::Loop(.., loop_span) = expr.kind {
441                            err.span_label(loop_span, "inside of this loop");
442                        }
443                    }
444                }
445                let typeck = self.infcx.tcx.typeck(self.mir_def_id());
446                let parent = self.infcx.tcx.parent_hir_node(expr.hir_id);
447                let (def_id, args, offset) = if let hir::Node::Expr(parent_expr) = parent
448                    && let hir::ExprKind::MethodCall(_, _, args, _) = parent_expr.kind
449                {
450                    let def_id = typeck.type_dependent_def_id(parent_expr.hir_id);
451                    (def_id, args, 1)
452                } else if let hir::Node::Expr(parent_expr) = parent
453                    && let hir::ExprKind::Call(call, args) = parent_expr.kind
454                    && let ty::FnDef(def_id, _) = typeck.node_type(call.hir_id).kind()
455                {
456                    (Some(*def_id), args, 0)
457                } else {
458                    (None, &[][..], 0)
459                };
460                let ty = place.ty(self.body, self.infcx.tcx).ty;
461
462                let mut can_suggest_clone = true;
463                if let Some(def_id) = def_id
464                    && let Some(pos) = args.iter().position(|arg| arg.hir_id == expr.hir_id)
465                {
466                    // The move occurred as one of the arguments to a function call. Is that
467                    // argument generic? `def_id` can't be a closure here, so using `fn_sig` is fine
468                    let arg_param = if self.infcx.tcx.def_kind(def_id).is_fn_like()
469                        && let sig =
470                            self.infcx.tcx.fn_sig(def_id).instantiate_identity().skip_binder()
471                        && let Some(arg_ty) = sig.inputs().get(pos + offset)
472                        && let ty::Param(arg_param) = arg_ty.kind()
473                    {
474                        Some(arg_param)
475                    } else {
476                        None
477                    };
478
479                    // If the moved value is a mut reference, it is used in a
480                    // generic function and it's type is a generic param, it can be
481                    // reborrowed to avoid moving.
482                    // for example:
483                    // struct Y(u32);
484                    // x's type is '& mut Y' and it is used in `fn generic<T>(x: T) {}`.
485                    if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind()
486                        && arg_param.is_some()
487                    {
488                        *has_suggest_reborrow = true;
489                        self.suggest_reborrow(err, expr.span, moved_place);
490                        return;
491                    }
492
493                    // If the moved place is used generically by the callee and a reference to it
494                    // would still satisfy any bounds on its type, suggest borrowing.
495                    if let Some(&param) = arg_param
496                        && let hir::Node::Expr(call_expr) = parent
497                        && let Some(ref_mutability) = self.suggest_borrow_generic_arg(
498                            err,
499                            typeck,
500                            call_expr,
501                            def_id,
502                            param,
503                            moved_place,
504                            pos + offset,
505                            ty,
506                            expr.span,
507                        )
508                    {
509                        can_suggest_clone = ref_mutability.is_mut();
510                    } else if let Some(local_def_id) = def_id.as_local()
511                        && let node = self.infcx.tcx.hir_node_by_def_id(local_def_id)
512                        && let Some(fn_decl) = node.fn_decl()
513                        && let Some(ident) = node.ident()
514                        && let Some(arg) = fn_decl.inputs.get(pos + offset)
515                    {
516                        // If we can't suggest borrowing in the call, but the function definition
517                        // is local, instead offer changing the function to borrow that argument.
518                        let mut span: MultiSpan = arg.span.into();
519                        span.push_span_label(
520                            arg.span,
521                            "this parameter takes ownership of the value".to_string(),
522                        );
523                        let descr = match node.fn_kind() {
524                            Some(hir::intravisit::FnKind::ItemFn(..)) | None => "function",
525                            Some(hir::intravisit::FnKind::Method(..)) => "method",
526                            Some(hir::intravisit::FnKind::Closure) => "closure",
527                        };
528                        span.push_span_label(ident.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in this {0}", descr))
    })format!("in this {descr}"));
529                        err.span_note(
530                            span,
531                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider changing this parameter type in {0} `{1}` to borrow instead if owning the value isn\'t necessary",
                descr, ident))
    })format!(
532                                "consider changing this parameter type in {descr} `{ident}` to \
533                                 borrow instead if owning the value isn't necessary",
534                            ),
535                        );
536                    }
537                }
538                if let hir::Node::Expr(parent_expr) = parent
539                    && let hir::ExprKind::Call(call_expr, _) = parent_expr.kind
540                    && let hir::ExprKind::Path(qpath) = call_expr.kind
541                    && tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
542                {
543                    // Do not suggest `.clone()` in a `for` loop, we already suggest borrowing.
544                } else if let UseSpans::FnSelfUse { kind: CallKind::Normal { .. }, .. } = move_spans
545                {
546                    // We already suggest cloning for these cases in `explain_captures`.
547                } else if moved_or_invoked_closure {
548                    // Do not suggest `closure.clone()()`.
549                } else if let UseSpans::ClosureUse {
550                    closure_kind:
551                        ClosureKind::Coroutine(CoroutineKind::Desugared(_, CoroutineSource::Block)),
552                    ..
553                } = move_spans
554                    && can_suggest_clone
555                {
556                    self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans));
557                } else if self.suggest_hoisting_call_outside_loop(err, expr) && can_suggest_clone {
558                    // The place where the type moves would be misleading to suggest clone.
559                    // #121466
560                    self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans));
561                }
562            }
563
564            self.suggest_ref_for_dbg_args(expr, place, move_span, err);
565
566            // it's useless to suggest inserting `ref` when the span don't comes from local code
567            if let Some(pat) = finder.pat
568                && !move_span.is_dummy()
569                && !self.infcx.tcx.sess.source_map().is_imported(move_span)
570            {
571                let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(pat.span.shrink_to_lo(), "ref ".to_string())]))vec![(pat.span.shrink_to_lo(), "ref ".to_string())];
572                if let Some(pat) = finder.parent_pat {
573                    sugg.insert(0, (pat.span.shrink_to_lo(), "ref ".to_string()));
574                }
575                err.multipart_suggestion(
576                    "borrow this binding in the pattern to avoid moving the value",
577                    sugg,
578                    Applicability::MachineApplicable,
579                );
580            }
581        }
582    }
583
584    // for dbg!(x) which may take ownership, suggest dbg!(&x) instead
585    // but here we actually do not check whether the macro name is `dbg!`
586    // so that we may extend the scope a bit larger to cover more cases
587    fn suggest_ref_for_dbg_args(
588        &self,
589        body: &hir::Expr<'_>,
590        place: &Place<'tcx>,
591        move_span: Span,
592        err: &mut Diag<'infcx>,
593    ) {
594        let var_info = self.body.var_debug_info.iter().find(|info| match info.value {
595            VarDebugInfoContents::Place(ref p) => p == place,
596            _ => false,
597        });
598        let Some(var_info) = var_info else { return };
599        let arg_name = var_info.name;
600        struct MatchArgFinder {
601            expr_span: Span,
602            match_arg_span: Option<Span>,
603            arg_name: Symbol,
604        }
605        impl Visitor<'_> for MatchArgFinder {
606            fn visit_expr(&mut self, e: &hir::Expr<'_>) {
607                // dbg! is expanded into a match pattern, we need to find the right argument span
608                if let hir::ExprKind::Match(expr, ..) = &e.kind
609                    && let hir::ExprKind::Path(hir::QPath::Resolved(
610                        _,
611                        path @ Path { segments: [seg], .. },
612                    )) = &expr.kind
613                    && seg.ident.name == self.arg_name
614                    && self.expr_span.source_callsite().contains(expr.span)
615                {
616                    self.match_arg_span = Some(path.span);
617                }
618                hir::intravisit::walk_expr(self, e);
619            }
620        }
621
622        let mut finder = MatchArgFinder { expr_span: move_span, match_arg_span: None, arg_name };
623        finder.visit_expr(body);
624        if let Some(macro_arg_span) = finder.match_arg_span {
625            err.span_suggestion_verbose(
626                macro_arg_span.shrink_to_lo(),
627                "consider borrowing instead of transferring ownership",
628                "&",
629                Applicability::MachineApplicable,
630            );
631        }
632    }
633
634    pub(crate) fn suggest_reborrow(
635        &self,
636        err: &mut Diag<'infcx>,
637        span: Span,
638        moved_place: PlaceRef<'tcx>,
639    ) {
640        err.span_suggestion_verbose(
641            span.shrink_to_lo(),
642            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider creating a fresh reborrow of {0} here",
                self.describe_place(moved_place).map(|n|
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("`{0}`", n))
                                })).unwrap_or_else(|| "the mutable reference".to_string())))
    })format!(
643                "consider creating a fresh reborrow of {} here",
644                self.describe_place(moved_place)
645                    .map(|n| format!("`{n}`"))
646                    .unwrap_or_else(|| "the mutable reference".to_string()),
647            ),
648            "&mut *",
649            Applicability::MachineApplicable,
650        );
651    }
652
653    /// If a place is used after being moved as an argument to a function, the function is generic
654    /// in that argument, and a reference to the argument's type would still satisfy the function's
655    /// bounds, suggest borrowing. This covers, e.g., borrowing an `impl Fn()` argument being passed
656    /// in an `impl FnOnce()` position.
657    /// Returns `Some(mutability)` when suggesting to borrow with mutability `mutability`, or `None`
658    /// if no suggestion is made.
659    fn suggest_borrow_generic_arg(
660        &self,
661        err: &mut Diag<'_>,
662        typeck: &ty::TypeckResults<'tcx>,
663        call_expr: &hir::Expr<'tcx>,
664        callee_did: DefId,
665        param: ty::ParamTy,
666        moved_place: PlaceRef<'tcx>,
667        moved_arg_pos: usize,
668        moved_arg_ty: Ty<'tcx>,
669        place_span: Span,
670    ) -> Option<ty::Mutability> {
671        let tcx = self.infcx.tcx;
672        let sig = tcx.fn_sig(callee_did).instantiate_identity().skip_binder();
673        let clauses = tcx.predicates_of(callee_did);
674
675        let generic_args = match call_expr.kind {
676            // For method calls, generic arguments are attached to the call node.
677            hir::ExprKind::MethodCall(..) => typeck.node_args_opt(call_expr.hir_id)?,
678            // For normal calls, generic arguments are in the callee's type.
679            // This diagnostic is only run for `FnDef` callees.
680            hir::ExprKind::Call(callee, _)
681                if let &ty::FnDef(_, args) = typeck.node_type(callee.hir_id).kind() =>
682            {
683                args
684            }
685            _ => return None,
686        };
687
688        // First, is there at least one method on one of `param`'s trait bounds?
689        // This keeps us from suggesting borrowing the argument to `mem::drop`, e.g.
690        if !clauses.instantiate_identity(tcx).predicates.iter().any(|clause| {
691            clause.as_trait_clause().is_some_and(|tc| {
692                tc.self_ty().skip_binder().is_param(param.index)
693                    && tc.polarity() == ty::PredicatePolarity::Positive
694                    && supertrait_def_ids(tcx, tc.def_id())
695                        .flat_map(|trait_did| tcx.associated_items(trait_did).in_definition_order())
696                        .any(|item| item.is_method())
697            })
698        }) {
699            return None;
700        }
701
702        // Try borrowing a shared reference first, then mutably.
703        if let Some(mutbl) = [ty::Mutability::Not, ty::Mutability::Mut].into_iter().find(|&mutbl| {
704            let re = self.infcx.tcx.lifetimes.re_erased;
705            let ref_ty = Ty::new_ref(self.infcx.tcx, re, moved_arg_ty, mutbl);
706
707            // Ensure that substituting `ref_ty` in the callee's signature doesn't break
708            // other inputs or the return type.
709            let new_args = tcx.mk_args_from_iter(generic_args.iter().enumerate().map(
710                |(i, arg)| {
711                    if i == param.index as usize { ref_ty.into() } else { arg }
712                },
713            ));
714            let can_subst = |ty: Ty<'tcx>| {
715                // Normalize before comparing to see through type aliases and projections.
716                let old_ty = ty::EarlyBinder::bind(tcx, ty).instantiate(tcx, generic_args);
717                let new_ty = ty::EarlyBinder::bind(tcx, ty).instantiate(tcx, new_args);
718                if let Ok(old_ty) = tcx.try_normalize_erasing_regions(
719                    self.infcx.typing_env(self.infcx.param_env),
720                    old_ty,
721                ) && let Ok(new_ty) = tcx.try_normalize_erasing_regions(
722                    self.infcx.typing_env(self.infcx.param_env),
723                    new_ty,
724                ) {
725                    old_ty == new_ty
726                } else {
727                    false
728                }
729            };
730            if !can_subst(sig.output())
731                || sig
732                    .inputs()
733                    .iter()
734                    .enumerate()
735                    .any(|(i, &input_ty)| i != moved_arg_pos && !can_subst(input_ty))
736            {
737                return false;
738            }
739
740            // Test the callee's predicates, substituting in `ref_ty` for the moved argument type.
741            clauses.instantiate(tcx, new_args).predicates.iter().all(|clause| {
742                // Normalize before testing to see through type aliases and projections.
743                let normalized = tcx
744                    .try_normalize_erasing_regions(
745                        self.infcx.typing_env(self.infcx.param_env),
746                        *clause,
747                    )
748                    .unwrap_or_else(|_| clause.skip_norm_wip());
749                self.infcx.predicate_must_hold_modulo_regions(&Obligation::new(
750                    tcx,
751                    ObligationCause::dummy(),
752                    self.infcx.param_env,
753                    normalized,
754                ))
755            })
756        }) {
757            let place_desc = if let Some(desc) = self.describe_place(moved_place) {
758                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", desc))
    })format!("`{desc}`")
759            } else {
760                "here".to_owned()
761            };
762            err.span_suggestion_verbose(
763                place_span.shrink_to_lo(),
764                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider {0}borrowing {1}",
                mutbl.mutably_str(), place_desc))
    })format!("consider {}borrowing {place_desc}", mutbl.mutably_str()),
765                mutbl.ref_prefix_str(),
766                Applicability::MaybeIncorrect,
767            );
768            Some(mutbl)
769        } else {
770            None
771        }
772    }
773
774    /// Returns `true` if the given initialization can reach the error location.
775    ///
776    /// This is used to determine whether an initialization should be considered
777    /// when reporting diagnostics at `err_location`.
778    ///
779    /// The check proceeds in two stages:
780    ///
781    /// 1. If the initialization originates from a function argument, it is
782    ///    considered reachable by definition.
783    /// 2. If the initialization's basic block dominates the error block, then
784    ///    every path to the error must pass through the initialization, so it is
785    ///    reachable.
786    /// 3. Otherwise, perform a graph traversal over the MIR control-flow graph to
787    ///    determine whether any path exists from the initialization block to the
788    ///    error block.
789    ///
790    /// The dominance check acts as a fast path for the common case, while the CFG
791    /// traversal handles cases where the initialization does not dominate the
792    /// error location but can still reach it through an alternate control-flow
793    /// path.
794    fn is_init_reachable(&self, init: &Init, err_location: mir::Location) -> bool {
795        let dominators = self.body.basic_blocks.dominators();
796        let init_block = match init.location {
797            InitLocation::Argument(_) => return true,
798            InitLocation::Statement(location) => location.block,
799        };
800        let err_block = err_location.block;
801        if dominators.dominates(init_block, err_block) {
802            return true;
803        }
804        // If init_block doesn't dominate error_block, check if there is any valid path from the
805        // initialization block to the error block in the Control Flow Graph.
806        let mut visited = DenseBitSet::new_empty(self.body.basic_blocks.len());
807        let mut stack = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [init_block]))vec![init_block];
808        while let Some(block) = stack.pop() {
809            if block == err_block {
810                return true;
811            }
812            if visited.insert(block) {
813                let data = &self.body.basic_blocks[block];
814                for successor in data.terminator().successors() {
815                    stack.push(successor);
816                }
817            }
818        }
819        false
820    }
821
822    fn report_use_of_uninitialized(
823        &self,
824        mpi: MovePathIndex,
825        used_place: PlaceRef<'tcx>,
826        moved_place: PlaceRef<'tcx>,
827        desired_action: InitializationRequiringAction,
828        location: Location,
829        span: Span,
830        use_spans: UseSpans<'tcx>,
831    ) -> Diag<'infcx> {
832        // We need all statements in the body where the binding was assigned to later find all
833        // the branching code paths where the binding *wasn't* assigned to.
834        let inits = &self.move_data.init_path_map[mpi];
835        let move_path = &self.move_data.move_paths[mpi];
836        let decl_span = self.body.local_decls[move_path.place.local].source_info.span;
837        let mut all_init_spans_set = FxIndexSet::default();
838        let mut reachable_spans_set = FxIndexSet::default();
839        for init_idx in inits {
840            let init = &self.move_data.inits[*init_idx];
841            let span = init.span(self.body);
842            if !span.is_dummy() {
843                all_init_spans_set.insert(span);
844                if self.is_init_reachable(init, location) {
845                    reachable_spans_set.insert(span);
846                }
847            }
848        }
849        let all_init_spans: Vec<_> = all_init_spans_set.into_iter().collect();
850        let reachable_spans: Vec<_> = reachable_spans_set.into_iter().collect();
851
852        let (name, desc) = match self.describe_place_with_options(
853            moved_place,
854            DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
855        ) {
856            Some(name) => (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` ", name))
    })format!("`{name}` ")),
857            None => ("the variable".to_string(), String::new()),
858        };
859        let path = match self.describe_place_with_options(
860            used_place,
861            DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
862        ) {
863            Some(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"),
864            None => "value".to_string(),
865        };
866
867        // We use the statements were the binding was initialized, and inspect the HIR to look
868        // for the branching codepaths that aren't covered, to point at them.
869        let tcx = self.infcx.tcx;
870        let body = tcx.hir_body_owned_by(self.mir_def_id());
871        let mut visitor =
872            ConditionVisitor { tcx, spans: all_init_spans.clone(), name, errors: ::alloc::vec::Vec::new()vec![] };
873        visitor.visit_body(&body);
874
875        let mut show_assign_sugg = false;
876        let isnt_initialized = if let InitializationRequiringAction::PartialAssignment
877        | InitializationRequiringAction::Assignment = desired_action
878        {
879            // The same error is emitted for bindings that are *sometimes* initialized and the ones
880            // that are *partially* initialized by assigning to a field of an uninitialized
881            // binding. We differentiate between them for more accurate wording here.
882            "isn't fully initialized"
883        } else if !reachable_spans.iter().any(|i| {
884            // We filter these to avoid misleading wording in cases like the following,
885            // where `x` has an `init`, but it is in the same place we're looking at:
886            // ```
887            // let x;
888            // x += 1;
889            // ```
890            !i.contains(span)
891            // We filter these to avoid incorrect main message on `match-cfg-fake-edges.rs`
892            && !visitor
893                .errors
894                .iter()
895                .map(|error| error.span)
896                .any(|sp| span < sp && !sp.contains(span))
897        }) {
898            show_assign_sugg = true;
899            if all_init_spans.iter().any(|init_span| !init_span.contains(span))
900                && reachable_spans.is_empty()
901            {
902                "isn't initialized on any path leading to this point"
903            } else {
904                "isn't initialized"
905            }
906        } else {
907            "is possibly-uninitialized"
908        };
909
910        let used = desired_action.as_general_verb_in_past_tense();
911        let mut err = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} binding {1}{2}",
                            used, desc, isnt_initialized))
                })).with_code(E0381)
}struct_span_code_err!(
912            self.dcx(),
913            span,
914            E0381,
915            "{used} binding {desc}{isnt_initialized}"
916        );
917        use_spans.var_path_only_subdiag(&mut err, desired_action);
918
919        if let InitializationRequiringAction::PartialAssignment
920        | InitializationRequiringAction::Assignment = desired_action
921        {
922            err.help(
923                "partial initialization isn't supported, fully initialize the binding with a \
924                 default value and mutate it, or use `std::mem::MaybeUninit`",
925            );
926        }
927        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1} here but it {2}", path,
                used, isnt_initialized))
    })format!("{path} {used} here but it {isnt_initialized}"));
928
929        let mut shown = false;
930        let mut shown_condition_value = false;
931        for error in visitor.errors {
932            if error.span < span && !error.span.overlaps(span) {
933                // When we have a case like `match-cfg-fake-edges.rs`, we don't want to mention
934                // match arms coming after the primary span because they aren't relevant:
935                // ```
936                // let x;
937                // match y {
938                //     _ if { x = 2; true } => {}
939                //     _ if {
940                //         x; //~ ERROR
941                //         false
942                //     } => {}
943                //     _ => {} // We don't want to point to this.
944                // };
945                // ```
946                shown_condition_value |= error.kind.describes_condition_value();
947                err.span_label(error.span, error.label);
948                shown = true;
949            }
950        }
951        if !shown {
952            for sp in &reachable_spans {
953                if *sp < span && !sp.overlaps(span) {
954                    err.span_label(*sp, "binding initialized here in some conditions");
955                }
956            }
957        }
958
959        err.span_label(decl_span, "binding declared here but left uninitialized");
960        if shown_condition_value {
961            err.note(
962                "when checking initialization, the compiler describes possible control-flow paths \
963                 without evaluating whether branch conditions can actually have the values shown",
964            );
965        }
966        if show_assign_sugg {
967            struct LetVisitor {
968                decl_span: Span,
969                sugg: Option<(Span, bool)>,
970            }
971
972            impl<'v> Visitor<'v> for LetVisitor {
973                fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) {
974                    if self.sugg.is_some() {
975                        return;
976                    }
977
978                    // FIXME: We make sure that this is a normal top-level binding,
979                    // but we could suggest `todo!()` for all uninitialized bindings in the pattern
980                    if let hir::StmtKind::Let(hir::LetStmt { span, ty, init: None, pat, .. }) =
981                        &ex.kind
982                        && let hir::PatKind::Binding(binding_mode, ..) = pat.kind
983                        && span.contains(self.decl_span)
984                    {
985                        // Insert after the whole binding pattern so suggestions stay valid for
986                        // bindings with `@` subpatterns like `ref mut x @ v`.
987                        let strip_ref = #[allow(non_exhaustive_omitted_patterns)] match binding_mode.0 {
    hir::ByRef::Yes(..) => true,
    _ => false,
}matches!(binding_mode.0, hir::ByRef::Yes(..));
988                        self.sugg =
989                            ty.map_or(Some((pat.span, strip_ref)), |ty| Some((ty.span, strip_ref)));
990                    }
991                    hir::intravisit::walk_stmt(self, ex);
992                }
993            }
994
995            let mut visitor = LetVisitor { decl_span, sugg: None };
996            visitor.visit_body(&body);
997            if let Some((span, strip_ref)) = visitor.sugg {
998                self.suggest_assign_value(&mut err, moved_place, span, strip_ref);
999            }
1000        }
1001        err
1002    }
1003
1004    fn suggest_assign_value(
1005        &self,
1006        err: &mut Diag<'_>,
1007        moved_place: PlaceRef<'tcx>,
1008        sugg_span: Span,
1009        strip_ref: bool,
1010    ) {
1011        let mut ty = moved_place.ty(self.body, self.infcx.tcx).ty;
1012        if strip_ref && let ty::Ref(_, inner, _) = ty.kind() {
1013            ty = *inner;
1014        }
1015        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:1015",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1015u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ty: {0:?}, kind: {1:?}",
                                                    ty, ty.kind()) as &dyn Value))])
            });
    } else { ; }
};debug!("ty: {:?}, kind: {:?}", ty, ty.kind());
1016
1017        let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.infcx.param_env, ty)
1018        else {
1019            return;
1020        };
1021
1022        err.span_suggestion_verbose(
1023            sugg_span.shrink_to_hi(),
1024            "consider assigning a value",
1025            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" = {0}", assign_value))
    })format!(" = {assign_value}"),
1026            Applicability::MaybeIncorrect,
1027        );
1028    }
1029
1030    /// In a move error that occurs on a call within a loop, we try to identify cases where cloning
1031    /// the value would lead to a logic error. We infer these cases by seeing if the moved value is
1032    /// part of the logic to break the loop, either through an explicit `break` or if the expression
1033    /// is part of a `while let`.
1034    fn suggest_hoisting_call_outside_loop(&self, err: &mut Diag<'_>, expr: &hir::Expr<'_>) -> bool {
1035        let tcx = self.infcx.tcx;
1036        let mut can_suggest_clone = true;
1037
1038        // If the moved value is a locally declared binding, we'll look upwards on the expression
1039        // tree until the scope where it is defined, and no further, as suggesting to move the
1040        // expression beyond that point would be illogical.
1041        let local_hir_id = if let hir::ExprKind::Path(hir::QPath::Resolved(
1042            _,
1043            hir::Path { res: hir::def::Res::Local(local_hir_id), .. },
1044        )) = expr.kind
1045        {
1046            Some(local_hir_id)
1047        } else {
1048            // This case would be if the moved value comes from an argument binding, we'll just
1049            // look within the entire item, that's fine.
1050            None
1051        };
1052
1053        /// This will allow us to look for a specific `HirId`, in our case `local_hir_id` where the
1054        /// binding was declared, within any other expression. We'll use it to search for the
1055        /// binding declaration within every scope we inspect.
1056        struct Finder {
1057            hir_id: hir::HirId,
1058        }
1059        impl<'hir> Visitor<'hir> for Finder {
1060            type Result = ControlFlow<()>;
1061            fn visit_pat(&mut self, pat: &'hir hir::Pat<'hir>) -> Self::Result {
1062                if pat.hir_id == self.hir_id {
1063                    return ControlFlow::Break(());
1064                }
1065                hir::intravisit::walk_pat(self, pat)
1066            }
1067            fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) -> Self::Result {
1068                if ex.hir_id == self.hir_id {
1069                    return ControlFlow::Break(());
1070                }
1071                hir::intravisit::walk_expr(self, ex)
1072            }
1073        }
1074        // The immediate HIR parent of the moved expression. We'll look for it to be a call.
1075        let mut parent = None;
1076        // The top-most loop where the moved expression could be moved to a new binding.
1077        let mut outer_most_loop: Option<&hir::Expr<'_>> = None;
1078        for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
1079            let e = match node {
1080                hir::Node::Expr(e) => e,
1081                hir::Node::LetStmt(hir::LetStmt { els: Some(els), .. }) => {
1082                    let mut finder = BreakFinder { found_breaks: ::alloc::vec::Vec::new()vec![], found_continues: ::alloc::vec::Vec::new()vec![] };
1083                    finder.visit_block(els);
1084                    if !finder.found_breaks.is_empty() {
1085                        // Don't suggest clone as it could be will likely end in an infinite
1086                        // loop.
1087                        // let Some(_) = foo(non_copy.clone()) else { break; }
1088                        // ---                       ^^^^^^^^         -----
1089                        can_suggest_clone = false;
1090                    }
1091                    continue;
1092                }
1093                _ => continue,
1094            };
1095            if let Some(&hir_id) = local_hir_id {
1096                if (Finder { hir_id }).visit_expr(e).is_break() {
1097                    // The current scope includes the declaration of the binding we're accessing, we
1098                    // can't look up any further for loops.
1099                    break;
1100                }
1101            }
1102            if parent.is_none() {
1103                parent = Some(e);
1104            }
1105            match e.kind {
1106                hir::ExprKind::Let(_) => {
1107                    match tcx.parent_hir_node(e.hir_id) {
1108                        hir::Node::Expr(hir::Expr {
1109                            kind: hir::ExprKind::If(cond, ..), ..
1110                        }) => {
1111                            if (Finder { hir_id: expr.hir_id }).visit_expr(cond).is_break() {
1112                                // The expression where the move error happened is in a `while let`
1113                                // condition Don't suggest clone as it will likely end in an
1114                                // infinite loop.
1115                                // while let Some(_) = foo(non_copy.clone()) { }
1116                                // ---------                       ^^^^^^^^
1117                                can_suggest_clone = false;
1118                            }
1119                        }
1120                        _ => {}
1121                    }
1122                }
1123                hir::ExprKind::Loop(..) => {
1124                    outer_most_loop = Some(e);
1125                }
1126                _ => {}
1127            }
1128        }
1129        let loop_count: usize = tcx
1130            .hir_parent_iter(expr.hir_id)
1131            .map(|(_, node)| match node {
1132                hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Loop(..), .. }) => 1,
1133                _ => 0,
1134            })
1135            .sum();
1136
1137        let sm = tcx.sess.source_map();
1138        if let Some(in_loop) = outer_most_loop {
1139            let mut finder = BreakFinder { found_breaks: ::alloc::vec::Vec::new()vec![], found_continues: ::alloc::vec::Vec::new()vec![] };
1140            finder.visit_expr(in_loop);
1141            // All of the spans for `break` and `continue` expressions.
1142            let spans = finder
1143                .found_breaks
1144                .iter()
1145                .chain(finder.found_continues.iter())
1146                .map(|(_, span)| *span)
1147                .filter(|span| {
1148                    !#[allow(non_exhaustive_omitted_patterns)] match span.desugaring_kind() {
    Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => true,
    _ => false,
}matches!(
1149                        span.desugaring_kind(),
1150                        Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1151                    )
1152                })
1153                .collect::<Vec<Span>>();
1154            // All of the spans for the loops above the expression with the move error.
1155            let loop_spans: Vec<_> = tcx
1156                .hir_parent_iter(expr.hir_id)
1157                .filter_map(|(_, node)| match node {
1158                    hir::Node::Expr(hir::Expr { span, kind: hir::ExprKind::Loop(..), .. }) => {
1159                        Some(*span)
1160                    }
1161                    _ => None,
1162                })
1163                .collect();
1164            // It is possible that a user written `break` or `continue` is in the wrong place. We
1165            // point them out at the user for them to make a determination. (#92531)
1166            if !spans.is_empty() && loop_count > 1 {
1167                // Getting fancy: if the spans of the loops *do not* overlap, we only use the line
1168                // number when referring to them. If there *are* overlaps (multiple loops on the
1169                // same line) then we use the more verbose span output (`file.rs:col:ll`).
1170                let mut lines: Vec<_> =
1171                    loop_spans.iter().map(|sp| sm.lookup_char_pos(sp.lo()).line).collect();
1172                lines.sort();
1173                lines.dedup();
1174                let fmt_span = |span: Span| {
1175                    if lines.len() == loop_spans.len() {
1176                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("line {0}",
                sm.lookup_char_pos(span.lo()).line))
    })format!("line {}", sm.lookup_char_pos(span.lo()).line)
1177                    } else {
1178                        sm.span_to_diagnostic_string(span)
1179                    }
1180                };
1181                let mut spans: MultiSpan = spans.into();
1182                // Point at all the `continue`s and explicit `break`s in the relevant loops.
1183                for (desc, elements) in [
1184                    ("`break` exits", &finder.found_breaks),
1185                    ("`continue` advances", &finder.found_continues),
1186                ] {
1187                    for (destination, sp) in elements {
1188                        if let Ok(hir_id) = destination.target_id
1189                            && let hir::Node::Expr(expr) = tcx.hir_node(hir_id)
1190                            && !#[allow(non_exhaustive_omitted_patterns)] match sp.desugaring_kind() {
    Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => true,
    _ => false,
}matches!(
1191                                sp.desugaring_kind(),
1192                                Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1193                            )
1194                        {
1195                            spans.push_span_label(
1196                                *sp,
1197                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this {1} the loop at {0}",
                fmt_span(expr.span), desc))
    })format!("this {desc} the loop at {}", fmt_span(expr.span)),
1198                            );
1199                        }
1200                    }
1201                }
1202                // Point at all the loops that are between this move and the parent item.
1203                for span in loop_spans {
1204                    spans.push_span_label(sm.guess_head_span(span), "");
1205                }
1206
1207                // note: verify that your loop breaking logic is correct
1208                //   --> $DIR/nested-loop-moved-value-wrong-continue.rs:41:17
1209                //    |
1210                // 28 |     for foo in foos {
1211                //    |     ---------------
1212                // ...
1213                // 33 |         for bar in &bars {
1214                //    |         ----------------
1215                // ...
1216                // 41 |                 continue;
1217                //    |                 ^^^^^^^^ this `continue` advances the loop at line 33
1218                err.span_note(spans, "verify that your loop breaking logic is correct");
1219            }
1220            if let Some(parent) = parent
1221                && let hir::ExprKind::MethodCall(..) | hir::ExprKind::Call(..) = parent.kind
1222            {
1223                // FIXME: We could check that the call's *parent* takes `&mut val` to make the
1224                // suggestion more targeted to the `mk_iter(val).next()` case. Maybe do that only to
1225                // check for whether to suggest `let value` or `let mut value`.
1226
1227                let span = in_loop.span;
1228                if !finder.found_breaks.is_empty()
1229                    && let Ok(value) = sm.span_to_snippet(parent.span)
1230                {
1231                    // We know with high certainty that this move would affect the early return of a
1232                    // loop, so we suggest moving the expression with the move out of the loop.
1233                    let indent = if let Some(indent) = sm.indentation_before(span) {
1234                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}", indent))
    })format!("\n{indent}")
1235                    } else {
1236                        " ".to_string()
1237                    };
1238                    err.multipart_suggestion(
1239                        "consider moving the expression out of the loop so it is only moved once",
1240                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("let mut value = {0};{1}",
                                    value, indent))
                        })), (parent.span, "value".to_string())]))vec![
1241                            (span.shrink_to_lo(), format!("let mut value = {value};{indent}")),
1242                            (parent.span, "value".to_string()),
1243                        ],
1244                        Applicability::MaybeIncorrect,
1245                    );
1246                }
1247            }
1248        }
1249        can_suggest_clone
1250    }
1251
1252    /// We have `S { foo: val, ..base }`, and we suggest instead writing
1253    /// `S { foo: val, bar: base.bar.clone(), .. }` when valid.
1254    fn suggest_cloning_on_functional_record_update(
1255        &self,
1256        err: &mut Diag<'_>,
1257        ty: Ty<'tcx>,
1258        expr: &hir::Expr<'_>,
1259    ) {
1260        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1261        let hir::ExprKind::Struct(struct_qpath, fields, hir::StructTailExpr::Base(base)) =
1262            expr.kind
1263        else {
1264            return;
1265        };
1266        let hir::QPath::Resolved(_, path) = struct_qpath else { return };
1267        let hir::def::Res::Def(_, def_id) = path.res else { return };
1268        let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return };
1269        let ty::Adt(def, args) = expr_ty.kind() else { return };
1270        let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = base.kind else { return };
1271        let (hir::def::Res::Local(_)
1272        | hir::def::Res::Def(
1273            DefKind::Const { .. }
1274            | DefKind::ConstParam
1275            | DefKind::Static { .. }
1276            | DefKind::AssocConst { .. },
1277            _,
1278        )) = path.res
1279        else {
1280            return;
1281        };
1282        let Ok(base_str) = self.infcx.tcx.sess.source_map().span_to_snippet(base.span) else {
1283            return;
1284        };
1285
1286        // 1. look for the fields of type `ty`.
1287        // 2. check if they are clone and add them to suggestion
1288        // 3. check if there are any values left to `..` and remove it if not
1289        // 4. emit suggestion to clone the field directly as `bar: base.bar.clone()`
1290
1291        let mut final_field_count = fields.len();
1292        let Some(variant) = def.variants().iter().find(|variant| variant.def_id == def_id) else {
1293            // When we have an enum, look for the variant that corresponds to the variant the user
1294            // wrote.
1295            return;
1296        };
1297        let mut sugg = ::alloc::vec::Vec::new()vec![];
1298        for field in &variant.fields {
1299            // In practice unless there are more than one field with the same type, we'll be
1300            // suggesting a single field at a type, because we don't aggregate multiple borrow
1301            // checker errors involving the functional record update syntax into a single one.
1302            let field_ty = field.ty(self.infcx.tcx, args).skip_norm_wip();
1303            let ident = field.ident(self.infcx.tcx);
1304            if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) {
1305                // Suggest adding field and cloning it.
1306                sugg.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}.{0}.clone()", ident,
                base_str))
    })format!("{ident}: {base_str}.{ident}.clone()"));
1307                final_field_count += 1;
1308            }
1309        }
1310        let (span, sugg) = match fields {
1311            [.., last] => (
1312                if final_field_count == variant.fields.len() {
1313                    // We'll remove the `..base` as there aren't any fields left.
1314                    last.span.shrink_to_hi().with_hi(base.span.hi())
1315                } else {
1316                    last.span.shrink_to_hi()
1317                },
1318                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", sugg.join(", ")))
    })format!(", {}", sugg.join(", ")),
1319            ),
1320            // Account for no fields in suggestion span.
1321            [] => (
1322                expr.span.with_lo(struct_qpath.span().hi()),
1323                if final_field_count == variant.fields.len() {
1324                    // We'll remove the `..base` as there aren't any fields left.
1325                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0} }}", sugg.join(", ")))
    })format!(" {{ {} }}", sugg.join(", "))
1326                } else {
1327                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0}, ..{1} }}",
                sugg.join(", "), base_str))
    })format!(" {{ {}, ..{base_str} }}", sugg.join(", "))
1328                },
1329            ),
1330        };
1331        let prefix = if !self.implements_clone(ty) {
1332            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` doesn\'t implement `Copy` or `Clone`",
                ty))
    })format!("`{ty}` doesn't implement `Copy` or `Clone`");
1333            if let ty::Adt(def, _) = ty.kind() {
1334                err.span_note(self.infcx.tcx.def_span(def.did()), msg);
1335            } else {
1336                err.note(msg);
1337            }
1338            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could ",
                ty))
    })format!("if `{ty}` implemented `Clone`, you could ")
1339        } else {
1340            String::new()
1341        };
1342        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}clone the value from the field instead of using the functional record update syntax",
                prefix))
    })format!(
1343            "{prefix}clone the value from the field instead of using the functional record update \
1344             syntax",
1345        );
1346        err.span_suggestion_verbose(span, msg, sugg, Applicability::MachineApplicable);
1347    }
1348
1349    pub(crate) fn suggest_cloning(
1350        &self,
1351        err: &mut Diag<'_>,
1352        place: PlaceRef<'tcx>,
1353        ty: Ty<'tcx>,
1354        expr: &'tcx hir::Expr<'tcx>,
1355        use_spans: Option<UseSpans<'tcx>>,
1356    ) {
1357        if let hir::ExprKind::Struct(_, _, hir::StructTailExpr::Base(_)) = expr.kind {
1358            // We have `S { foo: val, ..base }`. In `check_aggregate_rvalue` we have a single
1359            // `Location` that covers both the `S { ... }` literal, all of its fields and the
1360            // `base`. If the move happens because of `S { foo: val, bar: base.bar }` the `expr`
1361            //  will already be correct. Instead, we see if we can suggest writing.
1362            self.suggest_cloning_on_functional_record_update(err, ty, expr);
1363            return;
1364        }
1365
1366        if self.implements_clone(ty) {
1367            if self.in_move_closure(expr) {
1368                if let Some(name) = self.describe_place(place) {
1369                    self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans);
1370                }
1371            } else {
1372                self.suggest_cloning_inner(err, ty, expr);
1373            }
1374        } else if let ty::Adt(def, args) = ty.kind()
1375            && let Some(local_did) = def.did().as_local()
1376            && def.variants().iter().all(|variant| {
1377                variant.fields.iter().all(|field| {
1378                    self.implements_clone(field.ty(self.infcx.tcx, args).skip_norm_wip())
1379                })
1380            })
1381        {
1382            let ty_span = self.infcx.tcx.def_span(def.did());
1383            let mut span: MultiSpan = ty_span.into();
1384            let mut derive_clone = false;
1385            self.infcx.tcx.for_each_relevant_impl(
1386                self.infcx.tcx.lang_items().clone_trait().unwrap(),
1387                ty,
1388                |def_id| {
1389                    if self.infcx.tcx.is_automatically_derived(def_id) {
1390                        derive_clone = true;
1391                        span.push_span_label(
1392                            self.infcx.tcx.def_span(def_id),
1393                            "derived `Clone` adds implicit bounds on type parameters",
1394                        );
1395                        if let Some(generics) = self.infcx.tcx.hir_get_generics(local_did) {
1396                            for param in generics.params {
1397                                if let hir::GenericParamKind::Type { .. } = param.kind {
1398                                    span.push_span_label(
1399                                        param.span,
1400                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("introduces an implicit `{0}: Clone` bound",
                param.name.ident()))
    })format!(
1401                                            "introduces an implicit `{}: Clone` bound",
1402                                            param.name.ident()
1403                                        ),
1404                                    );
1405                                }
1406                            }
1407                        }
1408                    }
1409                },
1410            );
1411            let msg = if !derive_clone {
1412                span.push_span_label(
1413                    ty_span,
1414                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider {0}implementing `Clone` for this type",
                if derive_clone { "manually " } else { "" }))
    })format!(
1415                        "consider {}implementing `Clone` for this type",
1416                        if derive_clone { "manually " } else { "" }
1417                    ),
1418                );
1419                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could clone the value",
                ty))
    })format!("if `{ty}` implemented `Clone`, you could clone the value")
1420            } else {
1421                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if all bounds were met, you could clone the value"))
    })format!("if all bounds were met, you could clone the value")
1422            };
1423            span.push_span_label(expr.span, "you could clone this value");
1424            err.span_note(span, msg);
1425            if derive_clone {
1426                err.help("consider manually implementing `Clone` to avoid undesired bounds");
1427            }
1428        } else if let ty::Param(param) = ty.kind()
1429            && let Some(_clone_trait_def) = self.infcx.tcx.lang_items().clone_trait()
1430            && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1431            && let generic_param = generics.type_param(*param, self.infcx.tcx)
1432            && let param_span = self.infcx.tcx.def_span(generic_param.def_id)
1433            && if let Some(UseSpans::FnSelfUse { kind, .. }) = use_spans
1434                && let CallKind::FnCall { fn_trait_id, self_ty } = kind
1435                && let ty::Param(_) = self_ty.kind()
1436                && ty == self_ty
1437                && self.infcx.tcx.fn_trait_kind_from_def_id(fn_trait_id).is_some()
1438            {
1439                // Do not suggest `F: FnOnce() + Clone`.
1440                false
1441            } else {
1442                true
1443            }
1444        {
1445            let mut span: MultiSpan = param_span.into();
1446            span.push_span_label(
1447                param_span,
1448                "consider constraining this type parameter with `Clone`",
1449            );
1450            span.push_span_label(expr.span, "you could clone this value");
1451            err.span_help(
1452                span,
1453                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could clone the value",
                ty))
    })format!("if `{ty}` implemented `Clone`, you could clone the value"),
1454            );
1455        } else if let ty::Adt(_, _) = ty.kind()
1456            && let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1457        {
1458            // For cases like `Option<NonClone>`, where `Option<T>: Clone` if `T: Clone`, we point
1459            // at the types that should be `Clone`.
1460            let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1461            let cause = ObligationCause::misc(expr.span, self.mir_def_id());
1462            ocx.register_bound(cause, self.infcx.param_env, ty, clone_trait);
1463            let errors = ocx.evaluate_obligations_error_on_ambiguity();
1464            if !errors.is_empty()
1465                && errors.iter().all(|error| {
1466                    match error.obligation.predicate.as_clause().and_then(|c| c.as_trait_clause()) {
1467                        Some(clause) => match clause.self_ty().skip_binder().kind() {
1468                            ty::Adt(def, _) => {
1469                                def.did().is_local() && clause.def_id() == clone_trait
1470                            }
1471                            _ => false,
1472                        },
1473                        None => false,
1474                    }
1475                })
1476            {
1477                let mut type_spans = ::alloc::vec::Vec::new()vec![];
1478                let mut types = FxIndexSet::default();
1479                for clause in errors
1480                    .iter()
1481                    .filter_map(|e| e.obligation.predicate.as_clause())
1482                    .filter_map(|c| c.as_trait_clause())
1483                {
1484                    let ty::Adt(def, _) = clause.self_ty().skip_binder().kind() else { continue };
1485                    type_spans.push(self.infcx.tcx.def_span(def.did()));
1486                    types.insert(
1487                        self.infcx
1488                            .tcx
1489                            .short_string(clause.self_ty().skip_binder(), &mut err.long_ty_path()),
1490                    );
1491                }
1492                let mut span: MultiSpan = type_spans.clone().into();
1493                for sp in type_spans {
1494                    span.push_span_label(sp, "consider implementing `Clone` for this type");
1495                }
1496                span.push_span_label(expr.span, "you could clone this value");
1497                let types: Vec<_> = types.into_iter().collect();
1498                let msg = match &types[..] {
1499                    [only] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", only))
    })format!("`{only}`"),
1500                    [head @ .., last] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} and `{1}`",
                head.iter().map(|t|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", t))
                                    })).collect::<Vec<_>>().join(", "), last))
    })format!(
1501                        "{} and `{last}`",
1502                        head.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")
1503                    ),
1504                    [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1505                };
1506                err.span_note(
1507                    span,
1508                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if {0} implemented `Clone`, you could clone the value",
                msg))
    })format!("if {msg} implemented `Clone`, you could clone the value"),
1509                );
1510            }
1511        }
1512    }
1513
1514    pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
1515        let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
1516        self.infcx
1517            .type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
1518            .must_apply_modulo_regions()
1519    }
1520
1521    /// Given an expression, check if it is a method call `foo.clone()`, where `foo` and
1522    /// `foo.clone()` both have the same type, returning the span for `.clone()` if so.
1523    pub(crate) fn clone_on_reference(&self, expr: &hir::Expr<'_>) -> Option<Span> {
1524        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1525        if let hir::ExprKind::MethodCall(segment, rcvr, args, span) = expr.kind
1526            && let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id)
1527            && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1528            && rcvr_ty == expr_ty
1529            && segment.ident.name == sym::clone
1530            && args.is_empty()
1531        {
1532            Some(span)
1533        } else {
1534            None
1535        }
1536    }
1537
1538    fn in_move_closure(&self, expr: &hir::Expr<'_>) -> bool {
1539        for (_, node) in self.infcx.tcx.hir_parent_iter(expr.hir_id) {
1540            if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) = node
1541                && let hir::CaptureBy::Value { .. } = closure.capture_clause
1542            {
1543                // `move || x.clone()` will not work. FIXME: suggest `let y = x.clone(); move || y`
1544                return true;
1545            }
1546        }
1547        false
1548    }
1549
1550    fn suggest_cloning_inner(
1551        &self,
1552        err: &mut Diag<'_>,
1553        ty: Ty<'tcx>,
1554        expr: &hir::Expr<'_>,
1555    ) -> bool {
1556        let tcx = self.infcx.tcx;
1557
1558        // Don't suggest `.clone()` in a derive macro expansion.
1559        if let ExpnKind::Macro(MacroKind::Derive, _) = self.body.span.ctxt().outer_expn_data().kind
1560        {
1561            return false;
1562        }
1563        if let Some(_) = self.clone_on_reference(expr) {
1564            // Avoid redundant clone suggestion already suggested in `explain_captures`.
1565            // See `tests/ui/moves/needs-clone-through-deref.rs`
1566            return false;
1567        }
1568        // We don't want to suggest `.clone()` in a move closure, since the value has already been
1569        // captured.
1570        if self.in_move_closure(expr) {
1571            return false;
1572        }
1573        // We also don't want to suggest cloning a closure itself, since the value has already been
1574        // captured.
1575        if let hir::ExprKind::Closure(_) = expr.kind {
1576            return false;
1577        }
1578        // Try to find predicates on *generic params* that would allow copying `ty`
1579        let mut suggestion =
1580            if let Some(symbol) = tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1581                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}.clone()", symbol))
    })format!(": {symbol}.clone()")
1582            } else {
1583                ".clone()".to_owned()
1584            };
1585        let mut sugg = Vec::with_capacity(2);
1586        let mut inner_expr = expr;
1587        let mut is_raw_ptr = false;
1588        let typeck_result = self.infcx.tcx.typeck(self.mir_def_id());
1589        // Remove uses of `&` and `*` when suggesting `.clone()`.
1590        while let hir::ExprKind::AddrOf(.., inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) =
1591            &inner_expr.kind
1592        {
1593            if let hir::ExprKind::AddrOf(_, hir::Mutability::Mut, _) = inner_expr.kind {
1594                // We assume that `&mut` refs are desired for their side-effects, so cloning the
1595                // value wouldn't do what the user wanted.
1596                return false;
1597            }
1598            inner_expr = inner;
1599            if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) {
1600                if #[allow(non_exhaustive_omitted_patterns)] match inner_type.kind() {
    ty::RawPtr(..) => true,
    _ => false,
}matches!(inner_type.kind(), ty::RawPtr(..)) {
1601                    is_raw_ptr = true;
1602                    break;
1603                }
1604            }
1605        }
1606        // Cloning the raw pointer doesn't make sense in some cases and would cause a type mismatch
1607        // error. (see #126863)
1608        if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
1609            // Remove "(*" or "(&"
1610            sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
1611        }
1612        // Check whether `expr` is surrounded by parentheses or not.
1613        let span = if inner_expr.span.hi() != expr.span.hi() {
1614            // Account for `(*x)` to suggest `x.clone()`.
1615            if is_raw_ptr {
1616                expr.span.shrink_to_hi()
1617            } else {
1618                // Remove the close parenthesis ")"
1619                expr.span.with_lo(inner_expr.span.hi())
1620            }
1621        } else {
1622            if is_raw_ptr {
1623                sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1624                suggestion = ").clone()".to_string();
1625            }
1626            expr.span.shrink_to_hi()
1627        };
1628        sugg.push((span, suggestion));
1629        let msg = if let ty::Adt(def, _) = ty.kind()
1630            && [tcx.get_diagnostic_item(sym::Arc), tcx.get_diagnostic_item(sym::Rc)]
1631                .contains(&Some(def.did()))
1632        {
1633            "clone the value to increment its reference count"
1634        } else {
1635            "consider cloning the value if the performance cost is acceptable"
1636        };
1637        err.multipart_suggestion(msg, sugg, Applicability::MachineApplicable);
1638        true
1639    }
1640
1641    fn suggest_adding_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, def_id: DefId, span: Span) {
1642        let tcx = self.infcx.tcx;
1643        let generics = tcx.generics_of(self.mir_def_id());
1644
1645        let Some(hir_generics) =
1646            tcx.hir_get_generics(tcx.typeck_root_def_id_local(self.mir_def_id()))
1647        else {
1648            return;
1649        };
1650        // Try to find predicates on *generic params* that would allow copying `ty`
1651        let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1652        let cause = ObligationCause::misc(span, self.mir_def_id());
1653
1654        ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
1655        let errors = ocx.evaluate_obligations_error_on_ambiguity();
1656
1657        // Only emit suggestion if all required predicates are on generic
1658        let predicates: Result<Vec<_>, _> = errors
1659            .into_iter()
1660            .map(|err| match err.obligation.predicate.kind().skip_binder() {
1661                PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
1662                    match *predicate.self_ty().kind() {
1663                        ty::Param(param_ty) => Ok((
1664                            generics.type_param(param_ty, tcx),
1665                            predicate.trait_ref.print_trait_sugared().to_string(),
1666                            Some(predicate.trait_ref.def_id),
1667                        )),
1668                        _ => Err(()),
1669                    }
1670                }
1671                _ => Err(()),
1672            })
1673            .collect();
1674
1675        if let Ok(predicates) = predicates {
1676            suggest_constraining_type_params(
1677                tcx,
1678                hir_generics,
1679                err,
1680                predicates.iter().map(|(param, constraint, def_id)| {
1681                    (param.name.as_str(), &**constraint, *def_id)
1682                }),
1683                None,
1684            );
1685        }
1686    }
1687
1688    pub(crate) fn report_move_out_while_borrowed(
1689        &mut self,
1690        location: Location,
1691        (place, span): (Place<'tcx>, Span),
1692        borrow: &BorrowData<'tcx>,
1693    ) {
1694        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:1694",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1694u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_move_out_while_borrowed: location={0:?} place={1:?} span={2:?} borrow={3:?}",
                                                    location, place, span, borrow) as &dyn Value))])
            });
    } else { ; }
};debug!(
1695            "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
1696            location, place, span, borrow
1697        );
1698        let value_msg = self.describe_any_place(place.as_ref());
1699        let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
1700
1701        let borrow_spans = self.retrieve_borrow_spans(borrow);
1702        let borrow_span = borrow_spans.args_or_use();
1703
1704        let move_spans = self.move_spans(place.as_ref(), location);
1705        let span = move_spans.args_or_use();
1706
1707        let mut err = self.cannot_move_when_borrowed(
1708            span,
1709            borrow_span,
1710            &self.describe_any_place(place.as_ref()),
1711            &borrow_msg,
1712            &value_msg,
1713        );
1714        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1715
1716        borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
1717
1718        move_spans.var_subdiag(&mut err, None, |kind, var_span| {
1719            use crate::session_diagnostics::CaptureVarCause::*;
1720            match kind {
1721                hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
1722                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1723                    MoveUseInClosure { var_span }
1724                }
1725            }
1726        });
1727
1728        self.explain_why_borrow_contains_point(location, borrow, None)
1729            .add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
1730        self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1731        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1732        if let Some(expr) = self.find_expr(borrow_span) {
1733            // This is a borrow span, so we want to suggest cloning the referent.
1734            if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind
1735                && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr)
1736            {
1737                self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans));
1738            } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| {
1739                #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(ty::adjustment::AutoBorrowMutability::Not
        | ty::adjustment::AutoBorrowMutability::Mut {
        allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No })) => true,
    _ => false,
}matches!(
1740                    adj.kind,
1741                    ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(
1742                        ty::adjustment::AutoBorrowMutability::Not
1743                            | ty::adjustment::AutoBorrowMutability::Mut {
1744                                allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No
1745                            }
1746                    ))
1747                )
1748            }) && let Some(ty) = typeck_results.expr_ty_opt(expr)
1749            {
1750                self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans));
1751            }
1752        }
1753        self.buffer_error(err);
1754    }
1755
1756    pub(crate) fn report_use_while_mutably_borrowed(
1757        &self,
1758        location: Location,
1759        (place, _span): (Place<'tcx>, Span),
1760        borrow: &BorrowData<'tcx>,
1761    ) -> Diag<'infcx> {
1762        let borrow_spans = self.retrieve_borrow_spans(borrow);
1763        let borrow_span = borrow_spans.args_or_use();
1764
1765        // Conflicting borrows are reported separately, so only check for move
1766        // captures.
1767        let use_spans = self.move_spans(place.as_ref(), location);
1768        let span = use_spans.var_or_use();
1769
1770        // If the attempted use is in a closure then we do not care about the path span of the
1771        // place we are currently trying to use we call `var_span_label` on `borrow_spans` to
1772        // annotate if the existing borrow was in a closure.
1773        let mut err = self.cannot_use_when_mutably_borrowed(
1774            span,
1775            &self.describe_any_place(place.as_ref()),
1776            borrow_span,
1777            &self.describe_any_place(borrow.borrowed_place.as_ref()),
1778        );
1779        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1780
1781        borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
1782            use crate::session_diagnostics::CaptureVarCause::*;
1783            let place = &borrow.borrowed_place;
1784            let desc_place = self.describe_any_place(place.as_ref());
1785            match kind {
1786                hir::ClosureKind::Coroutine(_) => {
1787                    BorrowUsePlaceCoroutine { place: desc_place, var_span, is_single_var: true }
1788                }
1789                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1790                    BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }
1791                }
1792            }
1793        });
1794
1795        self.explain_why_borrow_contains_point(location, borrow, None)
1796            .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
1797        err
1798    }
1799
1800    pub(crate) fn report_conflicting_borrow(
1801        &self,
1802        location: Location,
1803        (place, span): (Place<'tcx>, Span),
1804        gen_borrow_kind: BorrowKind,
1805        issued_borrow: &BorrowData<'tcx>,
1806    ) -> Diag<'infcx> {
1807        let issued_spans = self.retrieve_borrow_spans(issued_borrow);
1808        let issued_span = issued_spans.args_or_use();
1809
1810        let borrow_spans = self.borrow_spans(span, location);
1811        let span = borrow_spans.args_or_use();
1812
1813        let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() {
1814            "coroutine"
1815        } else {
1816            "closure"
1817        };
1818
1819        let (desc_place, msg_place, msg_borrow, union_type_name) =
1820            self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
1821
1822        let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
1823        let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
1824
1825        // FIXME: supply non-"" `opt_via` when appropriate
1826        let first_borrow_desc;
1827        let mut err = match (gen_borrow_kind, issued_borrow.kind) {
1828            (
1829                BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1830                BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1831            ) => {
1832                first_borrow_desc = "mutable ";
1833                let mut err = self.cannot_reborrow_already_borrowed(
1834                    span,
1835                    &desc_place,
1836                    &msg_place,
1837                    "immutable",
1838                    issued_span,
1839                    "it",
1840                    "mutable",
1841                    &msg_borrow,
1842                    None,
1843                );
1844                self.suggest_slice_method_if_applicable(
1845                    &mut err,
1846                    place,
1847                    issued_borrow.borrowed_place,
1848                    span,
1849                    issued_span,
1850                );
1851                err
1852            }
1853            (
1854                BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1855                BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1856            ) => {
1857                first_borrow_desc = "immutable ";
1858                let mut err = self.cannot_reborrow_already_borrowed(
1859                    span,
1860                    &desc_place,
1861                    &msg_place,
1862                    "mutable",
1863                    issued_span,
1864                    "it",
1865                    "immutable",
1866                    &msg_borrow,
1867                    None,
1868                );
1869                self.suggest_slice_method_if_applicable(
1870                    &mut err,
1871                    place,
1872                    issued_borrow.borrowed_place,
1873                    span,
1874                    issued_span,
1875                );
1876                self.suggest_binding_for_closure_capture_self(&mut err, &issued_spans);
1877                self.suggest_using_closure_argument_instead_of_capture(
1878                    &mut err,
1879                    issued_borrow.borrowed_place,
1880                    &issued_spans,
1881                );
1882                err
1883            }
1884
1885            (
1886                BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1887                BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1888            ) => {
1889                first_borrow_desc = "first ";
1890                let mut err = self.cannot_mutably_borrow_multiply(
1891                    span,
1892                    &desc_place,
1893                    &msg_place,
1894                    issued_span,
1895                    &msg_borrow,
1896                    None,
1897                );
1898                self.suggest_slice_method_if_applicable(
1899                    &mut err,
1900                    place,
1901                    issued_borrow.borrowed_place,
1902                    span,
1903                    issued_span,
1904                );
1905                self.suggest_using_closure_argument_instead_of_capture(
1906                    &mut err,
1907                    issued_borrow.borrowed_place,
1908                    &issued_spans,
1909                );
1910                self.explain_iterator_advancement_in_for_loop_if_applicable(
1911                    &mut err,
1912                    span,
1913                    &issued_spans,
1914                );
1915                err
1916            }
1917
1918            (
1919                BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1920                BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1921            ) => {
1922                first_borrow_desc = "first ";
1923                self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
1924            }
1925
1926            (BorrowKind::Mut { .. }, BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1927                if let Some(immutable_section_description) =
1928                    self.classify_immutable_section(issued_borrow.assigned_place)
1929                {
1930                    let mut err = self.cannot_mutate_in_immutable_section(
1931                        span,
1932                        issued_span,
1933                        &desc_place,
1934                        immutable_section_description,
1935                        "mutably borrow",
1936                    );
1937                    borrow_spans.var_subdiag(
1938                        &mut err,
1939                        Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
1940                        |kind, var_span| {
1941                            use crate::session_diagnostics::CaptureVarCause::*;
1942                            match kind {
1943                                hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1944                                    place: desc_place,
1945                                    var_span,
1946                                    is_single_var: true,
1947                                },
1948                                hir::ClosureKind::Closure
1949                                | hir::ClosureKind::CoroutineClosure(_) => BorrowUsePlaceClosure {
1950                                    place: desc_place,
1951                                    var_span,
1952                                    is_single_var: true,
1953                                },
1954                            }
1955                        },
1956                    );
1957                    return err;
1958                } else {
1959                    first_borrow_desc = "immutable ";
1960                    self.cannot_reborrow_already_borrowed(
1961                        span,
1962                        &desc_place,
1963                        &msg_place,
1964                        "mutable",
1965                        issued_span,
1966                        "it",
1967                        "immutable",
1968                        &msg_borrow,
1969                        None,
1970                    )
1971                }
1972            }
1973
1974            (BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }, _) => {
1975                first_borrow_desc = "first ";
1976                self.cannot_uniquely_borrow_by_one_closure(
1977                    span,
1978                    container_name,
1979                    &desc_place,
1980                    "",
1981                    issued_span,
1982                    "it",
1983                    "",
1984                    None,
1985                )
1986            }
1987
1988            (
1989                BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1990                BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1991            ) => {
1992                first_borrow_desc = "first ";
1993                self.cannot_reborrow_already_uniquely_borrowed(
1994                    span,
1995                    container_name,
1996                    &desc_place,
1997                    "",
1998                    "immutable",
1999                    issued_span,
2000                    "",
2001                    None,
2002                    second_borrow_desc,
2003                )
2004            }
2005
2006            (BorrowKind::Mut { .. }, BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }) => {
2007                first_borrow_desc = "first ";
2008                self.cannot_reborrow_already_uniquely_borrowed(
2009                    span,
2010                    container_name,
2011                    &desc_place,
2012                    "",
2013                    "mutable",
2014                    issued_span,
2015                    "",
2016                    None,
2017                    second_borrow_desc,
2018                )
2019            }
2020
2021            (
2022                BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
2023                BorrowKind::Shared | BorrowKind::Fake(_),
2024            )
2025            | (
2026                BorrowKind::Fake(FakeBorrowKind::Shallow),
2027                BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_),
2028            ) => {
2029                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2030            }
2031        };
2032        self.note_due_to_edition_2024_opaque_capture_rules(issued_borrow, &mut err);
2033
2034        if issued_spans == borrow_spans {
2035            borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
2036                use crate::session_diagnostics::CaptureVarCause::*;
2037                match kind {
2038                    hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
2039                        place: desc_place,
2040                        var_span,
2041                        is_single_var: false,
2042                    },
2043                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
2044                        BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
2045                    }
2046                }
2047            });
2048        } else {
2049            issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
2050                use crate::session_diagnostics::CaptureVarCause::*;
2051                let borrow_place = &issued_borrow.borrowed_place;
2052                let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
2053                match kind {
2054                    hir::ClosureKind::Coroutine(_) => {
2055                        FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
2056                    }
2057                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
2058                        FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
2059                    }
2060                }
2061            });
2062
2063            borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
2064                use crate::session_diagnostics::CaptureVarCause::*;
2065                match kind {
2066                    hir::ClosureKind::Coroutine(_) => {
2067                        SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
2068                    }
2069                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
2070                        SecondBorrowUsePlaceClosure { place: desc_place, var_span }
2071                    }
2072                }
2073            });
2074        }
2075
2076        if union_type_name != "" {
2077            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} is a field of the union `{1}`, so it overlaps the field {2}",
                msg_place, union_type_name, msg_borrow))
    })format!(
2078                "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
2079            ));
2080        }
2081
2082        explanation.add_explanation_to_diagnostic(
2083            &self,
2084            &mut err,
2085            first_borrow_desc,
2086            None,
2087            Some((issued_span, span)),
2088        );
2089
2090        self.suggest_using_local_if_applicable(&mut err, location, issued_borrow, explanation);
2091        self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
2092
2093        err
2094    }
2095
2096    fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
2097        let tcx = self.infcx.tcx;
2098        let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2099
2100        struct FindUselessClone<'tcx> {
2101            tcx: TyCtxt<'tcx>,
2102            typeck_results: &'tcx ty::TypeckResults<'tcx>,
2103            clones: Vec<&'tcx hir::Expr<'tcx>>,
2104        }
2105        impl<'tcx> FindUselessClone<'tcx> {
2106            fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2107                Self { tcx, typeck_results: tcx.typeck(def_id), clones: ::alloc::vec::Vec::new()vec![] }
2108            }
2109        }
2110        impl<'tcx> Visitor<'tcx> for FindUselessClone<'tcx> {
2111            fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2112                if let hir::ExprKind::MethodCall(..) = ex.kind
2113                    && let Some(method_def_id) =
2114                        self.typeck_results.type_dependent_def_id(ex.hir_id)
2115                    && self.tcx.is_lang_item(self.tcx.parent(method_def_id), LangItem::Clone)
2116                {
2117                    self.clones.push(ex);
2118                }
2119                hir::intravisit::walk_expr(self, ex);
2120            }
2121        }
2122
2123        let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
2124
2125        let body = tcx.hir_body(body_id).value;
2126        expr_finder.visit_expr(body);
2127
2128        struct Holds<'tcx> {
2129            ty: Ty<'tcx>,
2130        }
2131
2132        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Holds<'tcx> {
2133            type Result = std::ops::ControlFlow<()>;
2134
2135            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
2136                if t == self.ty {
2137                    return ControlFlow::Break(());
2138                }
2139                t.super_visit_with(self)
2140            }
2141        }
2142
2143        let mut types_to_constrain = FxIndexSet::default();
2144
2145        let local_ty = self.body.local_decls[place.local].ty;
2146        let typeck_results = tcx.typeck(self.mir_def_id());
2147        let clone = tcx.require_lang_item(LangItem::Clone, body.span);
2148        for expr in expr_finder.clones {
2149            if let hir::ExprKind::MethodCall(_, rcvr, _, span) = expr.kind
2150                && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
2151                && let Some(ty) = typeck_results.node_type_opt(expr.hir_id)
2152                && rcvr_ty == ty
2153                && let ty::Ref(_, inner, _) = rcvr_ty.kind()
2154                && let inner = inner.peel_refs()
2155                && (Holds { ty: inner }).visit_ty(local_ty).is_break()
2156                && let None =
2157                    self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
2158            {
2159                err.span_label(
2160                    span,
2161                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this call doesn\'t do anything, the result is still `{0}` because `{1}` doesn\'t implement `Clone`",
                rcvr_ty, inner))
    })format!(
2162                        "this call doesn't do anything, the result is still `{rcvr_ty}` \
2163                             because `{inner}` doesn't implement `Clone`",
2164                    ),
2165                );
2166                types_to_constrain.insert(inner);
2167            }
2168        }
2169        for ty in types_to_constrain {
2170            self.suggest_adding_bounds_or_derive(err, ty, clone, body.span);
2171        }
2172    }
2173
2174    pub(crate) fn suggest_adding_bounds_or_derive(
2175        &self,
2176        err: &mut Diag<'_>,
2177        ty: Ty<'tcx>,
2178        trait_def_id: DefId,
2179        span: Span,
2180    ) {
2181        self.suggest_adding_bounds(err, ty, trait_def_id, span);
2182        if let ty::Adt(..) = ty.kind() {
2183            // The type doesn't implement the trait.
2184            let trait_ref =
2185                ty::Binder::dummy(ty::TraitRef::new(self.infcx.tcx, trait_def_id, [ty]));
2186            let obligation = Obligation::new(
2187                self.infcx.tcx,
2188                ObligationCause::dummy(),
2189                self.infcx.param_env,
2190                trait_ref,
2191            );
2192            self.infcx.err_ctxt().suggest_derive(
2193                &obligation,
2194                err,
2195                trait_ref.upcast(self.infcx.tcx),
2196            );
2197        }
2198    }
2199
2200    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_using_local_if_applicable",
                                    "rustc_borrowck::diagnostics::conflict_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2200u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["location",
                                                    "issued_borrow", "explanation"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&issued_borrow)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&explanation)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let used_in_call =
                #[allow(non_exhaustive_omitted_patterns)] match explanation {
                    BorrowExplanation::UsedLater(_,
                        LaterUseKind::Call | LaterUseKind::Other, _call_span, _) =>
                        true,
                    _ => false,
                };
            if !used_in_call {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2218",
                                        "rustc_borrowck::diagnostics::conflict_errors",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                        ::tracing_core::__macro_support::Option::Some(2218u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("not later used in call")
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                return;
            }
            if #[allow(non_exhaustive_omitted_patterns)] match self.body.local_decls[issued_borrow.borrowed_place.local].local_info()
                    {
                    LocalInfo::IfThenRescopeTemp { .. } => true,
                    _ => false,
                } {
                return;
            }
            let use_span =
                if let BorrowExplanation::UsedLater(_, LaterUseKind::Other,
                        use_span, _) = explanation {
                    Some(use_span)
                } else { None };
            let outer_call_loc =
                if let TwoPhaseActivation::ActivatedAt(loc) =
                        issued_borrow.activation_location {
                    loc
                } else { issued_borrow.reserve_location };
            let outer_call_stmt = self.body.stmt_at(outer_call_loc);
            let inner_param_location = location;
            let Some(inner_param_stmt) =
                self.body.stmt_at(inner_param_location).left() else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2247",
                                            "rustc_borrowck::diagnostics::conflict_errors",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                            ::tracing_core::__macro_support::Option::Some(2247u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("`inner_param_location` {0:?} is not for a statement",
                                                                        inner_param_location) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return;
                };
            let Some(&inner_param) =
                inner_param_stmt.kind.as_assign().map(|(p, _)|
                        p) else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2251",
                                            "rustc_borrowck::diagnostics::conflict_errors",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                            ::tracing_core::__macro_support::Option::Some(2251u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("`inner_param_location` {0:?} is not for an assignment: {1:?}",
                                                                        inner_param_location, inner_param_stmt) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return;
                };
            let inner_param_uses =
                find_all_local_uses::find(self.body, inner_param.local);
            let Some((inner_call_loc, inner_call_term)) =
                inner_param_uses.into_iter().find_map(|loc|
                        {
                            let Either::Right(term) =
                                self.body.stmt_at(loc) else {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2261",
                                                            "rustc_borrowck::diagnostics::conflict_errors",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(2261u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("{0:?} is a statement, so it can\'t be a call",
                                                                                        loc) as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    return None;
                                };
                            let TerminatorKind::Call { args, .. } =
                                &term.kind else {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2265",
                                                            "rustc_borrowck::diagnostics::conflict_errors",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(2265u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("not a call: {0:?}",
                                                                                        term) as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    return None;
                                };
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2268",
                                                    "rustc_borrowck::diagnostics::conflict_errors",
                                                    ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(2268u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            let mut iter = __CALLSITE.metadata().fields().iter();
                                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::tracing::__macro_support::Option::Some(&format_args!("checking call args for uses of inner_param: {0:?}",
                                                                                args) as &dyn Value))])
                                        });
                                } else { ; }
                            };
                            args.iter().map(|a|
                                            &a.node).any(|a|
                                        a == &Operand::Move(inner_param)).then_some((loc, term))
                        }) else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2275",
                                            "rustc_borrowck::diagnostics::conflict_errors",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                            ::tracing_core::__macro_support::Option::Some(2275u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("no uses of inner_param found as a by-move call arg")
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return;
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2278",
                                    "rustc_borrowck::diagnostics::conflict_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2278u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("===> outer_call_loc = {0:?}, inner_call_loc = {1:?}",
                                                                outer_call_loc, inner_call_loc) as &dyn Value))])
                        });
                } else { ; }
            };
            let inner_call_span = inner_call_term.source_info.span;
            let outer_call_span =
                match use_span {
                    Some(span) => span,
                    None =>
                        outer_call_stmt.either(|s| s.source_info,
                                |t| t.source_info).span,
                };
            if outer_call_span == inner_call_span ||
                    !outer_call_span.contains(inner_call_span) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2288",
                                        "rustc_borrowck::diagnostics::conflict_errors",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                        ::tracing_core::__macro_support::Option::Some(2288u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("outer span {0:?} does not strictly contain inner span {1:?}",
                                                                    outer_call_span, inner_call_span) as &dyn Value))])
                            });
                    } else { ; }
                };
                return;
            }
            err.span_help(inner_call_span,
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("try adding a local storing this{0}...",
                                if use_span.is_some() { "" } else { " argument" }))
                    }));
            err.span_help(outer_call_span,
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("...and then using that local {0}",
                                if use_span.is_some() {
                                    "here"
                                } else { "as the argument to this call" }))
                    }));
        }
    }
}#[instrument(level = "debug", skip(self, err))]
2201    fn suggest_using_local_if_applicable(
2202        &self,
2203        err: &mut Diag<'_>,
2204        location: Location,
2205        issued_borrow: &BorrowData<'tcx>,
2206        explanation: BorrowExplanation<'tcx>,
2207    ) {
2208        let used_in_call = matches!(
2209            explanation,
2210            BorrowExplanation::UsedLater(
2211                _,
2212                LaterUseKind::Call | LaterUseKind::Other,
2213                _call_span,
2214                _
2215            )
2216        );
2217        if !used_in_call {
2218            debug!("not later used in call");
2219            return;
2220        }
2221        if matches!(
2222            self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
2223            LocalInfo::IfThenRescopeTemp { .. }
2224        ) {
2225            // A better suggestion will be issued by the `if_let_rescope` lint
2226            return;
2227        }
2228
2229        let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
2230            explanation
2231        {
2232            Some(use_span)
2233        } else {
2234            None
2235        };
2236
2237        let outer_call_loc =
2238            if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
2239                loc
2240            } else {
2241                issued_borrow.reserve_location
2242            };
2243        let outer_call_stmt = self.body.stmt_at(outer_call_loc);
2244
2245        let inner_param_location = location;
2246        let Some(inner_param_stmt) = self.body.stmt_at(inner_param_location).left() else {
2247            debug!("`inner_param_location` {:?} is not for a statement", inner_param_location);
2248            return;
2249        };
2250        let Some(&inner_param) = inner_param_stmt.kind.as_assign().map(|(p, _)| p) else {
2251            debug!(
2252                "`inner_param_location` {:?} is not for an assignment: {:?}",
2253                inner_param_location, inner_param_stmt
2254            );
2255            return;
2256        };
2257        let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local);
2258        let Some((inner_call_loc, inner_call_term)) =
2259            inner_param_uses.into_iter().find_map(|loc| {
2260                let Either::Right(term) = self.body.stmt_at(loc) else {
2261                    debug!("{:?} is a statement, so it can't be a call", loc);
2262                    return None;
2263                };
2264                let TerminatorKind::Call { args, .. } = &term.kind else {
2265                    debug!("not a call: {:?}", term);
2266                    return None;
2267                };
2268                debug!("checking call args for uses of inner_param: {:?}", args);
2269                args.iter()
2270                    .map(|a| &a.node)
2271                    .any(|a| a == &Operand::Move(inner_param))
2272                    .then_some((loc, term))
2273            })
2274        else {
2275            debug!("no uses of inner_param found as a by-move call arg");
2276            return;
2277        };
2278        debug!("===> outer_call_loc = {:?}, inner_call_loc = {:?}", outer_call_loc, inner_call_loc);
2279
2280        let inner_call_span = inner_call_term.source_info.span;
2281        let outer_call_span = match use_span {
2282            Some(span) => span,
2283            None => outer_call_stmt.either(|s| s.source_info, |t| t.source_info).span,
2284        };
2285        if outer_call_span == inner_call_span || !outer_call_span.contains(inner_call_span) {
2286            // FIXME: This stops the suggestion in some cases where it should be emitted.
2287            //        Fix the spans for those cases so it's emitted correctly.
2288            debug!(
2289                "outer span {:?} does not strictly contain inner span {:?}",
2290                outer_call_span, inner_call_span
2291            );
2292            return;
2293        }
2294        err.span_help(
2295            inner_call_span,
2296            format!(
2297                "try adding a local storing this{}...",
2298                if use_span.is_some() { "" } else { " argument" }
2299            ),
2300        );
2301        err.span_help(
2302            outer_call_span,
2303            format!(
2304                "...and then using that local {}",
2305                if use_span.is_some() { "here" } else { "as the argument to this call" }
2306            ),
2307        );
2308    }
2309
2310    pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
2311        let tcx = self.infcx.tcx;
2312        let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
2313        let mut expr_finder = FindExprBySpan::new(span, tcx);
2314        expr_finder.visit_expr(tcx.hir_body(body_id).value);
2315        expr_finder.result
2316    }
2317
2318    fn suggest_slice_method_if_applicable(
2319        &self,
2320        err: &mut Diag<'_>,
2321        place: Place<'tcx>,
2322        borrowed_place: Place<'tcx>,
2323        span: Span,
2324        issued_span: Span,
2325    ) {
2326        let tcx = self.infcx.tcx;
2327
2328        let has_split_at_mut = |ty: Ty<'tcx>| {
2329            let ty = ty.peel_refs();
2330            match ty.kind() {
2331                ty::Array(..) | ty::Slice(..) => true,
2332                ty::Adt(def, _) if tcx.get_diagnostic_item(sym::Vec) == Some(def.did()) => true,
2333                _ if ty == tcx.types.str_ => true,
2334                _ => false,
2335            }
2336        };
2337        if let ([ProjectionElem::Index(index1)], [ProjectionElem::Index(index2)])
2338        | (
2339            [ProjectionElem::Deref, ProjectionElem::Index(index1)],
2340            [ProjectionElem::Deref, ProjectionElem::Index(index2)],
2341        ) = (&place.projection[..], &borrowed_place.projection[..])
2342        {
2343            let decl1 = &self.body.local_decls[*index1];
2344            let decl2 = &self.body.local_decls[*index2];
2345
2346            let mut note_default_suggestion = || {
2347                err.help(
2348                    "consider using `.split_at_mut(position)` or similar method to obtain two \
2349                     mutable non-overlapping sub-slices",
2350                )
2351                .help(
2352                    "consider using `.swap(index_1, index_2)` to swap elements at the specified \
2353                     indices",
2354                );
2355            };
2356
2357            let Some(index1) = self.find_expr(decl1.source_info.span) else {
2358                note_default_suggestion();
2359                return;
2360            };
2361
2362            let Some(index2) = self.find_expr(decl2.source_info.span) else {
2363                note_default_suggestion();
2364                return;
2365            };
2366
2367            let sm = tcx.sess.source_map();
2368
2369            let Ok(index1_str) = sm.span_to_snippet(index1.span) else {
2370                note_default_suggestion();
2371                return;
2372            };
2373
2374            let Ok(index2_str) = sm.span_to_snippet(index2.span) else {
2375                note_default_suggestion();
2376                return;
2377            };
2378
2379            let Some(object) = tcx.hir_parent_id_iter(index1.hir_id).find_map(|id| {
2380                if let hir::Node::Expr(expr) = tcx.hir_node(id)
2381                    && let hir::ExprKind::Index(obj, ..) = expr.kind
2382                {
2383                    Some(obj)
2384                } else {
2385                    None
2386                }
2387            }) else {
2388                note_default_suggestion();
2389                return;
2390            };
2391
2392            let Ok(obj_str) = sm.span_to_snippet(object.span) else {
2393                note_default_suggestion();
2394                return;
2395            };
2396
2397            let Some(swap_call) = tcx.hir_parent_id_iter(object.hir_id).find_map(|id| {
2398                if let hir::Node::Expr(call) = tcx.hir_node(id)
2399                    && let hir::ExprKind::Call(callee, ..) = call.kind
2400                    && let hir::ExprKind::Path(qpath) = callee.kind
2401                    && let hir::QPath::Resolved(None, res) = qpath
2402                    && let hir::def::Res::Def(_, did) = res.res
2403                    && tcx.is_diagnostic_item(sym::mem_swap, did)
2404                {
2405                    Some(call)
2406                } else {
2407                    None
2408                }
2409            }) else {
2410                let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2411                let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2412                let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2413                let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2414                if !idx1.equivalent_for_indexing(idx2) {
2415                    err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2416                }
2417                return;
2418            };
2419
2420            err.span_suggestion(
2421                swap_call.span,
2422                "use `.swap()` to swap elements at the specified indices instead",
2423                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.swap({1}, {2})", obj_str,
                index1_str, index2_str))
    })format!("{obj_str}.swap({index1_str}, {index2_str})"),
2424                Applicability::MachineApplicable,
2425            );
2426            return;
2427        }
2428        let place_ty = PlaceRef::ty(&place.as_ref(), self.body, tcx).ty;
2429        let borrowed_place_ty = PlaceRef::ty(&borrowed_place.as_ref(), self.body, tcx).ty;
2430        if !has_split_at_mut(place_ty) && !has_split_at_mut(borrowed_place_ty) {
2431            // Only mention `split_at_mut` on `Vec`, array and slices.
2432            return;
2433        }
2434        let Some(index1) = self.find_expr(span) else { return };
2435        let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2436        let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2437        let Some(index2) = self.find_expr(issued_span) else { return };
2438        let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2439        let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2440        if idx1.equivalent_for_indexing(idx2) {
2441            // `let a = &mut foo[0]` and `let b = &mut foo[0]`? Don't mention `split_at_mut`
2442            return;
2443        }
2444        err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2445    }
2446
2447    /// Suggest using `while let` for call `next` on an iterator in a for loop.
2448    ///
2449    /// For example:
2450    /// ```ignore (illustrative)
2451    ///
2452    /// for x in iter {
2453    ///     ...
2454    ///     iter.next()
2455    /// }
2456    /// ```
2457    pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
2458        &self,
2459        err: &mut Diag<'_>,
2460        span: Span,
2461        issued_spans: &UseSpans<'tcx>,
2462    ) {
2463        let issue_span = issued_spans.args_or_use();
2464        let tcx = self.infcx.tcx;
2465
2466        let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2467        let typeck_results = tcx.typeck(self.mir_def_id());
2468
2469        struct ExprFinder<'hir> {
2470            tcx: TyCtxt<'hir>,
2471            issue_span: Span,
2472            expr_span: Span,
2473            body_expr: Option<&'hir hir::Expr<'hir>> = None,
2474            loop_bind: Option<&'hir Ident> = None,
2475            loop_span: Option<Span> = None,
2476            head_span: Option<Span> = None,
2477            pat_span: Option<Span> = None,
2478            head: Option<&'hir hir::Expr<'hir>> = None,
2479        }
2480        impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2481            fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2482                // Try to find
2483                // let result = match IntoIterator::into_iter(<head>) {
2484                //     mut iter => {
2485                //         [opt_ident]: loop {
2486                //             match Iterator::next(&mut iter) {
2487                //                 None => break,
2488                //                 Some(<pat>) => <body>,
2489                //             };
2490                //         }
2491                //     }
2492                // };
2493                // corresponding to the desugaring of a for loop `for <pat> in <head> { <body> }`.
2494                if let hir::ExprKind::Call(path, [arg]) = ex.kind
2495                    && let hir::ExprKind::Path(qpath) = path.kind
2496                    && self.tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
2497                    && arg.span.contains(self.issue_span)
2498                    && ex.span.desugaring_kind() == Some(DesugaringKind::ForLoop)
2499                {
2500                    // Find `IntoIterator::into_iter(<head>)`
2501                    self.head = Some(arg);
2502                }
2503                if let hir::ExprKind::Loop(
2504                    hir::Block { stmts: [stmt, ..], .. },
2505                    _,
2506                    hir::LoopSource::ForLoop,
2507                    _,
2508                ) = ex.kind
2509                    && let hir::StmtKind::Expr(hir::Expr {
2510                        kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2511                        span: head_span,
2512                        ..
2513                    }) = stmt.kind
2514                    && let hir::ExprKind::Call(path, _args) = call.kind
2515                    && let hir::ExprKind::Path(qpath) = path.kind
2516                    && self.tcx.qpath_is_lang_item(qpath, LangItem::IteratorNext)
2517                    && let hir::PatKind::Struct(qpath, [field, ..], _) = bind.pat.kind
2518                    && self.tcx.qpath_is_lang_item(qpath, LangItem::OptionSome)
2519                    && call.span.contains(self.issue_span)
2520                {
2521                    // Find `<pat>` and the span for the whole `for` loop.
2522                    if let PatField {
2523                        pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2524                        ..
2525                    } = field
2526                    {
2527                        self.loop_bind = Some(ident);
2528                    }
2529                    self.head_span = Some(*head_span);
2530                    self.pat_span = Some(bind.pat.span);
2531                    self.loop_span = Some(stmt.span);
2532                }
2533
2534                if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2535                    && body_call.ident.name == sym::next
2536                    && recv.span.source_equal(self.expr_span)
2537                {
2538                    self.body_expr = Some(ex);
2539                }
2540
2541                hir::intravisit::walk_expr(self, ex);
2542            }
2543        }
2544        let mut finder = ExprFinder { tcx, expr_span: span, issue_span, .. };
2545        finder.visit_expr(tcx.hir_body(body_id).value);
2546
2547        if let Some(body_expr) = finder.body_expr
2548            && let Some(loop_span) = finder.loop_span
2549            && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id)
2550            && let Some(trait_did) = tcx.trait_of_assoc(def_id)
2551            && tcx.is_diagnostic_item(sym::Iterator, trait_did)
2552        {
2553            if let Some(loop_bind) = finder.loop_bind {
2554                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a for loop advances the iterator for you, the result is stored in `{0}`",
                loop_bind.name))
    })format!(
2555                    "a for loop advances the iterator for you, the result is stored in `{}`",
2556                    loop_bind.name,
2557                ));
2558            } else {
2559                err.note(
2560                    "a for loop advances the iterator for you, the result is stored in its pattern",
2561                );
2562            }
2563            let msg = "if you want to call `next` on a iterator within the loop, consider using \
2564                       `while let`";
2565            if let Some(head) = finder.head
2566                && let Some(pat_span) = finder.pat_span
2567                && loop_span.contains(body_expr.span)
2568                && loop_span.contains(head.span)
2569            {
2570                let sm = self.infcx.tcx.sess.source_map();
2571
2572                let mut sugg = ::alloc::vec::Vec::new()vec![];
2573                if let hir::ExprKind::Path(hir::QPath::Resolved(None, _)) = head.kind {
2574                    // A bare path doesn't need a `let` assignment, it's already a simple
2575                    // binding access.
2576                    // As a new binding wasn't added, we don't need to modify the advancing call.
2577                    sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
2578                    sugg.push((
2579                        pat_span.shrink_to_hi().with_hi(head.span.lo()),
2580                        ") = ".to_string(),
2581                    ));
2582                    sugg.push((head.span.shrink_to_hi(), ".next()".to_string()));
2583                } else {
2584                    // Needs a new a `let` binding.
2585                    let indent = if let Some(indent) = sm.indentation_before(loop_span) {
2586                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}", indent))
    })format!("\n{indent}")
2587                    } else {
2588                        " ".to_string()
2589                    };
2590                    let Ok(head_str) = sm.span_to_snippet(head.span) else {
2591                        err.help(msg);
2592                        return;
2593                    };
2594                    sugg.push((
2595                        loop_span.with_hi(pat_span.lo()),
2596                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let iter = {0};{1}while let Some(",
                head_str, indent))
    })format!("let iter = {head_str};{indent}while let Some("),
2597                    ));
2598                    sugg.push((
2599                        pat_span.shrink_to_hi().with_hi(head.span.hi()),
2600                        ") = iter.next()".to_string(),
2601                    ));
2602                    // As a new binding was added, we should change how the iterator is advanced to
2603                    // use the newly introduced binding.
2604                    if let hir::ExprKind::MethodCall(_, recv, ..) = body_expr.kind
2605                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, ..)) = recv.kind
2606                    {
2607                        // As we introduced a `let iter = <head>;`, we need to change where the
2608                        // already borrowed value was accessed from `<recv>.next()` to
2609                        // `iter.next()`.
2610                        sugg.push((recv.span, "iter".to_string()));
2611                    }
2612                }
2613                err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2614            } else {
2615                err.help(msg);
2616            }
2617        }
2618    }
2619
2620    /// Suggest using closure argument instead of capture.
2621    ///
2622    /// For example:
2623    /// ```ignore (illustrative)
2624    /// struct S;
2625    ///
2626    /// impl S {
2627    ///     fn call(&mut self, f: impl Fn(&mut Self)) { /* ... */ }
2628    ///     fn x(&self) {}
2629    /// }
2630    ///
2631    ///     let mut v = S;
2632    ///     v.call(|this: &mut S| v.x());
2633    /// //  ^\                    ^-- help: try using the closure argument: `this`
2634    /// //    *-- error: cannot borrow `v` as mutable because it is also borrowed as immutable
2635    /// ```
2636    fn suggest_using_closure_argument_instead_of_capture(
2637        &self,
2638        err: &mut Diag<'_>,
2639        borrowed_place: Place<'tcx>,
2640        issued_spans: &UseSpans<'tcx>,
2641    ) {
2642        let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2643        let tcx = self.infcx.tcx;
2644
2645        // Get the type of the local that we are trying to borrow
2646        let local = borrowed_place.local;
2647        let local_ty = self.body.local_decls[local].ty;
2648
2649        // Get the body the error happens in
2650        let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2651
2652        let body_expr = tcx.hir_body(body_id).value;
2653
2654        struct ClosureFinder<'hir> {
2655            tcx: TyCtxt<'hir>,
2656            borrow_span: Span,
2657            res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
2658            /// The path expression with the `borrow_span` span
2659            error_path: Option<(&'hir hir::Expr<'hir>, &'hir hir::QPath<'hir>)>,
2660        }
2661        impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
2662            type NestedFilter = OnlyBodies;
2663
2664            fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2665                self.tcx
2666            }
2667
2668            fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2669                if let hir::ExprKind::Path(qpath) = &ex.kind
2670                    && ex.span == self.borrow_span
2671                {
2672                    self.error_path = Some((ex, qpath));
2673                }
2674
2675                if let hir::ExprKind::Closure(closure) = ex.kind
2676                    && ex.span.contains(self.borrow_span)
2677                    // To support cases like `|| { v.call(|this| v.get()) }`
2678                    // FIXME: actually support such cases (need to figure out how to move from the
2679                    // capture place to original local).
2680                    && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span))
2681                {
2682                    self.res = Some((ex, closure));
2683                }
2684
2685                hir::intravisit::walk_expr(self, ex);
2686            }
2687        }
2688
2689        // Find the closure that most tightly wraps `capture_kind_span`
2690        let mut finder =
2691            ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
2692        finder.visit_expr(body_expr);
2693        let Some((closure_expr, closure)) = finder.res else { return };
2694
2695        let typeck_results = tcx.typeck(self.mir_def_id());
2696
2697        // Check that the parent of the closure is a method call,
2698        // with receiver matching with local's type (modulo refs)
2699        if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id)
2700            && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind
2701        {
2702            let recv_ty = typeck_results.expr_ty(recv);
2703
2704            if recv_ty.peel_refs() != local_ty {
2705                return;
2706            }
2707        }
2708
2709        // Get closure's arguments
2710        let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else {
2711            /* hir::Closure can be a coroutine too */
2712            return;
2713        };
2714        let sig = args.as_closure().sig();
2715        let tupled_params = tcx.instantiate_bound_regions_with_erased(
2716            sig.inputs().iter().next().unwrap().map_bound(|&b| b),
2717        );
2718        let ty::Tuple(params) = tupled_params.kind() else { return };
2719
2720        // Find the first argument with a matching type and get its identifier.
2721        let Some(this_name) = params.iter().zip(tcx.hir_body_param_idents(closure.body)).find_map(
2722            |(param_ty, ident)| {
2723                // FIXME: also support deref for stuff like `Rc` arguments
2724                if param_ty.peel_refs() == local_ty { ident } else { None }
2725            },
2726        ) else {
2727            return;
2728        };
2729
2730        let spans;
2731        if let Some((_path_expr, qpath)) = finder.error_path
2732            && let hir::QPath::Resolved(_, path) = qpath
2733            && let hir::def::Res::Local(local_id) = path.res
2734        {
2735            // Find all references to the problematic variable in this closure body
2736
2737            struct VariableUseFinder {
2738                local_id: hir::HirId,
2739                spans: Vec<Span>,
2740            }
2741            impl<'hir> Visitor<'hir> for VariableUseFinder {
2742                fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2743                    if let hir::ExprKind::Path(qpath) = &ex.kind
2744                        && let hir::QPath::Resolved(_, path) = qpath
2745                        && let hir::def::Res::Local(local_id) = path.res
2746                        && local_id == self.local_id
2747                    {
2748                        self.spans.push(ex.span);
2749                    }
2750
2751                    hir::intravisit::walk_expr(self, ex);
2752                }
2753            }
2754
2755            let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
2756            finder.visit_expr(tcx.hir_body(closure.body).value);
2757
2758            spans = finder.spans;
2759        } else {
2760            spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [capture_kind_span]))vec![capture_kind_span];
2761        }
2762
2763        err.multipart_suggestion(
2764            "try using the closure argument",
2765            iter::zip(spans, iter::repeat(this_name.to_string())).collect(),
2766            Applicability::MaybeIncorrect,
2767        );
2768    }
2769
2770    fn suggest_binding_for_closure_capture_self(
2771        &self,
2772        err: &mut Diag<'_>,
2773        issued_spans: &UseSpans<'tcx>,
2774    ) {
2775        let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2776
2777        struct ExpressionFinder<'tcx> {
2778            capture_span: Span,
2779            closure_change_spans: Vec<Span> = ::alloc::vec::Vec::new()vec![],
2780            closure_arg_span: Option<Span> = None,
2781            in_closure: bool = false,
2782            suggest_arg: String = String::new(),
2783            tcx: TyCtxt<'tcx>,
2784            closure_local_id: Option<hir::HirId> = None,
2785            closure_call_changes: Vec<(Span, String)> = ::alloc::vec::Vec::new()vec![],
2786        }
2787        impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
2788            fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
2789                if e.span.contains(self.capture_span)
2790                    && let hir::ExprKind::Closure(&hir::Closure {
2791                        kind: hir::ClosureKind::Closure,
2792                        body,
2793                        fn_arg_span,
2794                        fn_decl: hir::FnDecl { inputs, .. },
2795                        ..
2796                    }) = e.kind
2797                    && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
2798                {
2799                    self.suggest_arg = "this: &Self".to_string();
2800                    if inputs.len() > 0 {
2801                        self.suggest_arg.push_str(", ");
2802                    }
2803                    self.in_closure = true;
2804                    self.closure_arg_span = fn_arg_span;
2805                    self.visit_expr(body);
2806                    self.in_closure = false;
2807                }
2808                if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
2809                    && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2810                    && seg.ident.name == kw::SelfLower
2811                    && self.in_closure
2812                {
2813                    self.closure_change_spans.push(e.span);
2814                }
2815                hir::intravisit::walk_expr(self, e);
2816            }
2817
2818            fn visit_local(&mut self, local: &'hir hir::LetStmt<'hir>) {
2819                if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
2820                    local.pat
2821                    && let Some(init) = local.init
2822                    && let &hir::Expr {
2823                        kind:
2824                            hir::ExprKind::Closure(&hir::Closure {
2825                                kind: hir::ClosureKind::Closure,
2826                                ..
2827                            }),
2828                        ..
2829                    } = init
2830                    && init.span.contains(self.capture_span)
2831                {
2832                    self.closure_local_id = Some(*hir_id);
2833                }
2834
2835                hir::intravisit::walk_local(self, local);
2836            }
2837
2838            fn visit_stmt(&mut self, s: &'hir hir::Stmt<'hir>) {
2839                if let hir::StmtKind::Semi(e) = s.kind
2840                    && let hir::ExprKind::Call(
2841                        hir::Expr { kind: hir::ExprKind::Path(path), .. },
2842                        args,
2843                    ) = e.kind
2844                    && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2845                    && let Res::Local(hir_id) = seg.res
2846                    && Some(hir_id) == self.closure_local_id
2847                {
2848                    let (span, arg_str) = if args.len() > 0 {
2849                        (args[0].span.shrink_to_lo(), "self, ".to_string())
2850                    } else {
2851                        let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
2852                        (span, "(self)".to_string())
2853                    };
2854                    self.closure_call_changes.push((span, arg_str));
2855                }
2856                hir::intravisit::walk_stmt(self, s);
2857            }
2858        }
2859
2860        if let hir::Node::ImplItem(hir::ImplItem {
2861            kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
2862            ..
2863        }) = self.infcx.tcx.hir_node(self.mir_hir_id())
2864            && let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
2865        {
2866            let mut finder =
2867                ExpressionFinder { capture_span: *capture_kind_span, tcx: self.infcx.tcx, .. };
2868            finder.visit_expr(expr);
2869
2870            if finder.closure_change_spans.is_empty() || finder.closure_call_changes.is_empty() {
2871                return;
2872            }
2873
2874            let sm = self.infcx.tcx.sess.source_map();
2875            let sugg = finder
2876                .closure_arg_span
2877                .map(|span| (sm.next_point(span.shrink_to_lo()).shrink_to_hi(), finder.suggest_arg))
2878                .into_iter()
2879                .chain(
2880                    finder.closure_change_spans.into_iter().map(|span| (span, "this".to_string())),
2881                )
2882                .chain(finder.closure_call_changes)
2883                .collect();
2884
2885            err.multipart_suggestion(
2886                "try explicitly passing `&Self` into the closure as an argument",
2887                sugg,
2888                Applicability::MachineApplicable,
2889            );
2890        }
2891    }
2892
2893    /// Returns the description of the root place for a conflicting borrow and the full
2894    /// descriptions of the places that caused the conflict.
2895    ///
2896    /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
2897    /// attempted while a shared borrow is live, then this function will return:
2898    /// ```
2899    /// ("x", "", "")
2900    /// # ;
2901    /// ```
2902    /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
2903    /// a shared borrow of another field `x.y`, then this function will return:
2904    /// ```
2905    /// ("x", "x.z", "x.y")
2906    /// # ;
2907    /// ```
2908    /// In the more complex union case, where the union is a field of a struct, then if a mutable
2909    /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
2910    /// another field `x.u.y`, then this function will return:
2911    /// ```
2912    /// ("x.u", "x.u.z", "x.u.y")
2913    /// # ;
2914    /// ```
2915    /// This is used when creating error messages like below:
2916    ///
2917    /// ```text
2918    /// cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
2919    /// mutable (via `a.u.s.b`) [E0502]
2920    /// ```
2921    fn describe_place_for_conflicting_borrow(
2922        &self,
2923        first_borrowed_place: Place<'tcx>,
2924        second_borrowed_place: Place<'tcx>,
2925    ) -> (String, String, String, String) {
2926        // Define a small closure that we can use to check if the type of a place
2927        // is a union.
2928        let union_ty = |place_base| {
2929            // Need to use fn call syntax `PlaceRef::ty` to determine the type of `place_base`;
2930            // using a type annotation in the closure argument instead leads to a lifetime error.
2931            let ty = PlaceRef::ty(&place_base, self.body, self.infcx.tcx).ty;
2932            ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
2933        };
2934
2935        // Start with an empty tuple, so we can use the functions on `Option` to reduce some
2936        // code duplication (particularly around returning an empty description in the failure
2937        // case).
2938        Some(())
2939            .filter(|_| {
2940                // If we have a conflicting borrow of the same place, then we don't want to add
2941                // an extraneous "via x.y" to our diagnostics, so filter out this case.
2942                first_borrowed_place != second_borrowed_place
2943            })
2944            .and_then(|_| {
2945                // We're going to want to traverse the first borrowed place to see if we can find
2946                // field access to a union. If we find that, then we will keep the place of the
2947                // union being accessed and the field that was being accessed so we can check the
2948                // second borrowed place for the same union and an access to a different field.
2949                for (place_base, elem) in first_borrowed_place.iter_projections().rev() {
2950                    match elem {
2951                        ProjectionElem::Field(field, _) if union_ty(place_base).is_some() => {
2952                            return Some((place_base, field));
2953                        }
2954                        _ => {}
2955                    }
2956                }
2957                None
2958            })
2959            .and_then(|(target_base, target_field)| {
2960                // With the place of a union and a field access into it, we traverse the second
2961                // borrowed place and look for an access to a different field of the same union.
2962                for (place_base, elem) in second_borrowed_place.iter_projections().rev() {
2963                    if let ProjectionElem::Field(field, _) = elem
2964                        && let Some(union_ty) = union_ty(place_base)
2965                    {
2966                        if field != target_field && place_base == target_base {
2967                            return Some((
2968                                self.describe_any_place(place_base),
2969                                self.describe_any_place(first_borrowed_place.as_ref()),
2970                                self.describe_any_place(second_borrowed_place.as_ref()),
2971                                union_ty.to_string(),
2972                            ));
2973                        }
2974                    }
2975                }
2976                None
2977            })
2978            .unwrap_or_else(|| {
2979                // If we didn't find a field access into a union, or both places match, then
2980                // only return the description of the first place.
2981                (
2982                    self.describe_any_place(first_borrowed_place.as_ref()),
2983                    "".to_string(),
2984                    "".to_string(),
2985                    "".to_string(),
2986                )
2987            })
2988    }
2989
2990    /// This means that some data referenced by `borrow` needs to live
2991    /// past the point where the StorageDeadOrDrop of `place` occurs.
2992    /// This is usually interpreted as meaning that `place` has too
2993    /// short a lifetime. (But sometimes it is more useful to report
2994    /// it as a more direct conflict between the execution of a
2995    /// `Drop::drop` with an aliasing borrow.)
2996    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("report_borrowed_value_does_not_live_long_enough",
                                    "rustc_borrowck::diagnostics::conflict_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2996u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["location", "borrow",
                                                    "place_span", "kind"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let drop_span = place_span.1;
            let borrowed_local = borrow.borrowed_place.local;
            let borrow_spans = self.retrieve_borrow_spans(borrow);
            let borrow_span = borrow_spans.var_or_use_path_span();
            let proper_span =
                self.body.local_decls[borrowed_local].source_info.span;
            if self.access_place_error_reported.contains(&(Place::from(borrowed_local),
                            borrow_span)) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3013",
                                        "rustc_borrowck::diagnostics::conflict_errors",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                        ::tracing_core::__macro_support::Option::Some(3013u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("suppressing access_place error when borrow doesn\'t live long enough for {0:?}",
                                                                    borrow_span) as &dyn Value))])
                            });
                    } else { ; }
                };
                return;
            }
            self.access_place_error_reported.insert((Place::from(borrowed_local),
                    borrow_span));
            if self.body.local_decls[borrowed_local].is_ref_to_thread_local()
                {
                let err =
                    self.report_thread_local_value_does_not_live_long_enough(drop_span,
                        borrow_span);
                self.buffer_error(err);
                return;
            }
            if let StorageDeadOrDrop::Destructor(dropped_ty) =
                    self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
                {
                if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref())
                    {
                    self.report_borrow_conflicts_with_destructor(location,
                        borrow, place_span, kind, dropped_ty);
                    return;
                }
            }
            let place_desc =
                self.describe_place(borrow.borrowed_place.as_ref());
            let kind_place =
                kind.filter(|_|
                            place_desc.is_some()).map(|k| (k, place_span.0));
            let explanation =
                self.explain_why_borrow_contains_point(location, borrow,
                    kind_place);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3049",
                                    "rustc_borrowck::diagnostics::conflict_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3049u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["place_desc",
                                                    "explanation"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&place_desc)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&explanation)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let mut err =
                match (place_desc, explanation) {
                    (Some(name),
                        BorrowExplanation::UsedLater(_,
                        LaterUseKind::ClosureCapture, var_or_use_span, _)) if
                        borrow_spans.for_coroutine() || borrow_spans.for_closure()
                        =>
                        self.report_escaping_closure_capture(borrow_spans,
                            borrow_span,
                            &RegionName {
                                    name: self.synthesize_region_name(),
                                    source: RegionNameSource::Static,
                                }, ConstraintCategory::CallArgument(None), var_or_use_span,
                            &::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", name))
                                    }), "block"),
                    (Some(name), BorrowExplanation::MustBeValidFor {
                        category: category
                            @
                            (ConstraintCategory::Return(_) |
                            ConstraintCategory::CallArgument(_) |
                            ConstraintCategory::OpaqueType),
                        from_closure: false,
                        ref region_name,
                        span, .. }) if
                        borrow_spans.for_coroutine() || borrow_spans.for_closure()
                        =>
                        self.report_escaping_closure_capture(borrow_spans,
                            borrow_span, region_name, category, span,
                            &::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", name))
                                    }), "function"),
                    (name, BorrowExplanation::MustBeValidFor {
                        category: ConstraintCategory::Assignment,
                        from_closure: false,
                        region_name: RegionName {
                            source: RegionNameSource::AnonRegionFromUpvar(upvar_span,
                                upvar_name),
                            ..
                            },
                        span, .. }) =>
                        self.report_escaping_data(borrow_span, &name, upvar_span,
                            upvar_name, span),
                    (Some(name), explanation) =>
                        self.report_local_value_does_not_live_long_enough(location,
                            &name, borrow, drop_span, borrow_spans, explanation),
                    (None, explanation) =>
                        self.report_temporary_value_does_not_live_long_enough(location,
                            borrow, drop_span, borrow_spans, proper_span, explanation),
                };
            self.note_due_to_edition_2024_opaque_capture_rules(borrow,
                &mut err);
            self.buffer_error(err);
        }
    }
}#[instrument(level = "debug", skip(self))]
2997    pub(crate) fn report_borrowed_value_does_not_live_long_enough(
2998        &mut self,
2999        location: Location,
3000        borrow: &BorrowData<'tcx>,
3001        place_span: (Place<'tcx>, Span),
3002        kind: Option<WriteKind>,
3003    ) {
3004        let drop_span = place_span.1;
3005        let borrowed_local = borrow.borrowed_place.local;
3006
3007        let borrow_spans = self.retrieve_borrow_spans(borrow);
3008        let borrow_span = borrow_spans.var_or_use_path_span();
3009
3010        let proper_span = self.body.local_decls[borrowed_local].source_info.span;
3011
3012        if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
3013            debug!(
3014                "suppressing access_place error when borrow doesn't live long enough for {:?}",
3015                borrow_span
3016            );
3017            return;
3018        }
3019
3020        self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
3021
3022        if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
3023            let err =
3024                self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
3025            self.buffer_error(err);
3026            return;
3027        }
3028
3029        if let StorageDeadOrDrop::Destructor(dropped_ty) =
3030            self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
3031        {
3032            // If a borrow of path `B` conflicts with drop of `D` (and
3033            // we're not in the uninteresting case where `B` is a
3034            // prefix of `D`), then report this as a more interesting
3035            // destructor conflict.
3036            if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
3037                self.report_borrow_conflicts_with_destructor(
3038                    location, borrow, place_span, kind, dropped_ty,
3039                );
3040                return;
3041            }
3042        }
3043
3044        let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
3045
3046        let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
3047        let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
3048
3049        debug!(?place_desc, ?explanation);
3050
3051        let mut err = match (place_desc, explanation) {
3052            // If the outlives constraint comes from inside the closure,
3053            // for example:
3054            //
3055            // let x = 0;
3056            // let y = &x;
3057            // Box::new(|| y) as Box<Fn() -> &'static i32>
3058            //
3059            // then just use the normal error. The closure isn't escaping
3060            // and `move` will not help here.
3061            (
3062                Some(name),
3063                BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
3064            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3065                .report_escaping_closure_capture(
3066                    borrow_spans,
3067                    borrow_span,
3068                    &RegionName {
3069                        name: self.synthesize_region_name(),
3070                        source: RegionNameSource::Static,
3071                    },
3072                    ConstraintCategory::CallArgument(None),
3073                    var_or_use_span,
3074                    &format!("`{name}`"),
3075                    "block",
3076                ),
3077            (
3078                Some(name),
3079                BorrowExplanation::MustBeValidFor {
3080                    category:
3081                        category @ (ConstraintCategory::Return(_)
3082                        | ConstraintCategory::CallArgument(_)
3083                        | ConstraintCategory::OpaqueType),
3084                    from_closure: false,
3085                    ref region_name,
3086                    span,
3087                    ..
3088                },
3089            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3090                .report_escaping_closure_capture(
3091                    borrow_spans,
3092                    borrow_span,
3093                    region_name,
3094                    category,
3095                    span,
3096                    &format!("`{name}`"),
3097                    "function",
3098                ),
3099            (
3100                name,
3101                BorrowExplanation::MustBeValidFor {
3102                    category: ConstraintCategory::Assignment,
3103                    from_closure: false,
3104                    region_name:
3105                        RegionName {
3106                            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
3107                            ..
3108                        },
3109                    span,
3110                    ..
3111                },
3112            ) => self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, span),
3113            (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
3114                location,
3115                &name,
3116                borrow,
3117                drop_span,
3118                borrow_spans,
3119                explanation,
3120            ),
3121            (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
3122                location,
3123                borrow,
3124                drop_span,
3125                borrow_spans,
3126                proper_span,
3127                explanation,
3128            ),
3129        };
3130        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
3131
3132        self.buffer_error(err);
3133    }
3134
3135    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("report_local_value_does_not_live_long_enough",
                                    "rustc_borrowck::diagnostics::conflict_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3135u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["location", "name",
                                                    "borrow", "drop_span", "borrow_spans"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&name as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&drop_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow_spans)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Diag<'infcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let borrow_span = borrow_spans.var_or_use_path_span();
            if let BorrowExplanation::MustBeValidFor {
                        category, span, ref opt_place_desc, from_closure: false, ..
                        } = explanation &&
                    let Err(diag) =
                        self.try_report_cannot_return_reference_to_local(borrow,
                            borrow_span, span, category, opt_place_desc.as_ref()) {
                return diag;
            }
            let name =
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("`{0}`", name))
                    });
            let mut err =
                self.path_does_not_live_long_enough(borrow_span, &name);
            if let Some(annotation) =
                    self.annotate_argument_and_return_for_borrow(borrow) {
                let region_name = annotation.emit(self, &mut err);
                err.span_label(borrow_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0} would have to be valid for `{1}`...",
                                    name, region_name))
                        }));
                err.span_label(drop_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("...but {1} will be dropped here, when the {0} returns",
                                    self.infcx.tcx.opt_item_name(self.mir_def_id().to_def_id()).map(|name|
                                                ::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("function `{0}`", name))
                                                    })).unwrap_or_else(||
                                            {
                                                match &self.infcx.tcx.def_kind(self.mir_def_id()) {
                                                        DefKind::Closure if
                                                            self.infcx.tcx.is_coroutine(self.mir_def_id().to_def_id())
                                                            => {
                                                            "enclosing coroutine"
                                                        }
                                                        DefKind::Closure => "enclosing closure",
                                                        kind =>
                                                            ::rustc_middle::util::bug::bug_fmt(format_args!("expected closure or coroutine, found {0:?}",
                                                                    kind)),
                                                    }.to_string()
                                            }), name))
                        }));
                err.note("functions cannot return a borrow to data owned within the function's scope, \
                    functions can only return borrows to data passed as arguments");
                err.note("to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
                    references-and-borrowing.html#dangling-references>");
                if let BorrowExplanation::MustBeValidFor { .. } = explanation
                    {} else {
                    explanation.add_explanation_to_diagnostic(&self, &mut err,
                        "", None, None);
                }
            } else {
                err.span_label(borrow_span,
                    "borrowed value does not live long enough");
                err.span_label(drop_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0} dropped here while still borrowed",
                                    name))
                        }));
                borrow_spans.args_subdiag(&mut err,
                    |args_span|
                        {
                            crate::session_diagnostics::CaptureArgLabel::Capture {
                                is_within: borrow_spans.for_coroutine(),
                                args_span,
                            }
                        });
                explanation.add_explanation_to_diagnostic(&self, &mut err, "",
                    Some(borrow_span), None);
                if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) =
                        explanation {
                    for (local, local_decl) in
                        self.body.local_decls.iter_enumerated() {
                        if let ty::Adt(adt_def, args) = local_decl.ty.kind() &&
                                    self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
                                && args.len() > 0 {
                            let vec_inner_ty = args.type_at(0);
                            if vec_inner_ty.is_ref() {
                                let local_place = local.into();
                                if let Some(local_name) = self.describe_place(local_place) {
                                    err.span_label(local_decl.source_info.span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("variable `{0}` declared here",
                                                        local_name))
                                            }));
                                    err.note(::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("`{0}` is a collection that stores borrowed references, but {1} does not live long enough to be stored in it",
                                                        local_name, name))
                                            }));
                                    err.help("buffer reuse with borrowed references requires unsafe code or restructuring");
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            err
        }
    }
}#[tracing::instrument(level = "debug", skip(self, explanation))]
3136    fn report_local_value_does_not_live_long_enough(
3137        &self,
3138        location: Location,
3139        name: &str,
3140        borrow: &BorrowData<'tcx>,
3141        drop_span: Span,
3142        borrow_spans: UseSpans<'tcx>,
3143        explanation: BorrowExplanation<'tcx>,
3144    ) -> Diag<'infcx> {
3145        let borrow_span = borrow_spans.var_or_use_path_span();
3146        if let BorrowExplanation::MustBeValidFor {
3147            category,
3148            span,
3149            ref opt_place_desc,
3150            from_closure: false,
3151            ..
3152        } = explanation
3153            && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3154                borrow,
3155                borrow_span,
3156                span,
3157                category,
3158                opt_place_desc.as_ref(),
3159            )
3160        {
3161            return diag;
3162        }
3163
3164        let name = format!("`{name}`");
3165
3166        let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3167
3168        if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3169            let region_name = annotation.emit(self, &mut err);
3170
3171            err.span_label(
3172                borrow_span,
3173                format!("{name} would have to be valid for `{region_name}`..."),
3174            );
3175
3176            err.span_label(
3177                drop_span,
3178                format!(
3179                    "...but {name} will be dropped here, when the {} returns",
3180                    self.infcx
3181                        .tcx
3182                        .opt_item_name(self.mir_def_id().to_def_id())
3183                        .map(|name| format!("function `{name}`"))
3184                        .unwrap_or_else(|| {
3185                            match &self.infcx.tcx.def_kind(self.mir_def_id()) {
3186                                DefKind::Closure
3187                                    if self
3188                                        .infcx
3189                                        .tcx
3190                                        .is_coroutine(self.mir_def_id().to_def_id()) =>
3191                                {
3192                                    "enclosing coroutine"
3193                                }
3194                                DefKind::Closure => "enclosing closure",
3195                                kind => bug!("expected closure or coroutine, found {:?}", kind),
3196                            }
3197                            .to_string()
3198                        })
3199                ),
3200            );
3201
3202            err.note(
3203                "functions cannot return a borrow to data owned within the function's scope, \
3204                    functions can only return borrows to data passed as arguments",
3205            );
3206            err.note(
3207                "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3208                    references-and-borrowing.html#dangling-references>",
3209            );
3210
3211            if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3212            } else {
3213                explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3214            }
3215        } else {
3216            err.span_label(borrow_span, "borrowed value does not live long enough");
3217            err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3218
3219            borrow_spans.args_subdiag(&mut err, |args_span| {
3220                crate::session_diagnostics::CaptureArgLabel::Capture {
3221                    is_within: borrow_spans.for_coroutine(),
3222                    args_span,
3223                }
3224            });
3225
3226            explanation.add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
3227
3228            // Detect buffer reuse pattern
3229            if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) = explanation {
3230                // Check all locals at the borrow location to find Vec<&T> types
3231                for (local, local_decl) in self.body.local_decls.iter_enumerated() {
3232                    if let ty::Adt(adt_def, args) = local_decl.ty.kind()
3233                        && self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
3234                        && args.len() > 0
3235                    {
3236                        let vec_inner_ty = args.type_at(0);
3237                        // Check if Vec contains references
3238                        if vec_inner_ty.is_ref() {
3239                            let local_place = local.into();
3240                            if let Some(local_name) = self.describe_place(local_place) {
3241                                err.span_label(
3242                                    local_decl.source_info.span,
3243                                    format!("variable `{local_name}` declared here"),
3244                                );
3245                                err.note(
3246                                    format!(
3247                                        "`{local_name}` is a collection that stores borrowed references, \
3248                                         but {name} does not live long enough to be stored in it"
3249                                    )
3250                                );
3251                                err.help(
3252                                    "buffer reuse with borrowed references requires unsafe code or restructuring"
3253                                );
3254                                break;
3255                            }
3256                        }
3257                    }
3258                }
3259            }
3260        }
3261
3262        err
3263    }
3264
3265    fn report_borrow_conflicts_with_destructor(
3266        &mut self,
3267        location: Location,
3268        borrow: &BorrowData<'tcx>,
3269        (place, drop_span): (Place<'tcx>, Span),
3270        kind: Option<WriteKind>,
3271        dropped_ty: Ty<'tcx>,
3272    ) {
3273        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3273",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(3273u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_borrow_conflicts_with_destructor({0:?}, {1:?}, ({2:?}, {3:?}), {4:?})",
                                                    location, borrow, place, drop_span, kind) as &dyn Value))])
            });
    } else { ; }
};debug!(
3274            "report_borrow_conflicts_with_destructor(\
3275             {:?}, {:?}, ({:?}, {:?}), {:?}\
3276             )",
3277            location, borrow, place, drop_span, kind,
3278        );
3279
3280        let borrow_spans = self.retrieve_borrow_spans(borrow);
3281        let borrow_span = borrow_spans.var_or_use();
3282
3283        let mut err = self.cannot_borrow_across_destructor(borrow_span);
3284
3285        let what_was_dropped = match self.describe_place(place.as_ref()) {
3286            Some(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"),
3287            None => String::from("temporary value"),
3288        };
3289
3290        let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3291            Some(borrowed) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("here, drop of {0} needs exclusive access to `{1}`, because the type `{2}` implements the `Drop` trait",
                what_was_dropped, borrowed, dropped_ty))
    })format!(
3292                "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3293                 because the type `{dropped_ty}` implements the `Drop` trait"
3294            ),
3295            None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("here is drop of {0}; whose type `{1}` implements the `Drop` trait",
                what_was_dropped, dropped_ty))
    })format!(
3296                "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3297            ),
3298        };
3299        err.span_label(drop_span, label);
3300
3301        // Only give this note and suggestion if they could be relevant.
3302        let explanation =
3303            self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3304        match explanation {
3305            BorrowExplanation::UsedLater { .. }
3306            | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3307                err.note("consider using a `let` binding to create a longer lived value");
3308            }
3309            _ => {}
3310        }
3311
3312        explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3313
3314        self.buffer_error(err);
3315    }
3316
3317    fn report_thread_local_value_does_not_live_long_enough(
3318        &self,
3319        drop_span: Span,
3320        borrow_span: Span,
3321    ) -> Diag<'infcx> {
3322        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3322",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(3322u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_thread_local_value_does_not_live_long_enough({0:?}, {1:?})",
                                                    drop_span, borrow_span) as &dyn Value))])
            });
    } else { ; }
};debug!(
3323            "report_thread_local_value_does_not_live_long_enough(\
3324             {:?}, {:?}\
3325             )",
3326            drop_span, borrow_span
3327        );
3328
3329        // `TerminatorKind::Return`'s span (the `drop_span` here) `lo` can be subtly wrong and point
3330        // at a single character after the end of the function. This is somehow relied upon in
3331        // existing diagnostics, and changing this in `rustc_mir_build` makes diagnostics worse in
3332        // general. We fix these here.
3333        let sm = self.infcx.tcx.sess.source_map();
3334        let end_of_function = if drop_span.is_empty()
3335            && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3336        {
3337            adjusted_span
3338        } else {
3339            drop_span
3340        };
3341        self.thread_local_value_does_not_live_long_enough(borrow_span)
3342            .with_span_label(
3343                borrow_span,
3344                "thread-local variables cannot be borrowed beyond the end of the function",
3345            )
3346            .with_span_label(end_of_function, "end of enclosing function is here")
3347    }
3348
3349    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("report_temporary_value_does_not_live_long_enough",
                                    "rustc_borrowck::diagnostics::conflict_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3349u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["location", "borrow",
                                                    "drop_span", "borrow_spans", "proper_span", "explanation"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&drop_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow_spans)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&proper_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&explanation)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Diag<'infcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let BorrowExplanation::MustBeValidFor {
                    category, span, from_closure: false, .. } = explanation {
                if let Err(diag) =
                        self.try_report_cannot_return_reference_to_local(borrow,
                            proper_span, span, category, None) {
                    return diag;
                }
            }
            let mut err =
                self.temporary_value_borrowed_for_too_long(proper_span);
            err.span_label(proper_span,
                "creates a temporary value which is freed while still in use");
            err.span_label(drop_span,
                "temporary value is freed at the end of this statement");
            match explanation {
                BorrowExplanation::UsedLater(..) |
                    BorrowExplanation::UsedLaterInLoop(..) |
                    BorrowExplanation::UsedLaterWhenDropped { .. } => {
                    let sm = self.infcx.tcx.sess.source_map();
                    let mut suggested = false;
                    let msg =
                        "consider using a `let` binding to create a longer lived value";
                    #[doc =
                    " We check that there\'s a single level of block nesting to ensure always correct"]
                    #[doc =
                    " suggestions. If we don\'t, then we only provide a free-form message to avoid"]
                    #[doc =
                    " misleading users in cases like `tests/ui/nll/borrowed-temporary-error.rs`."]
                    #[doc =
                    " We could expand the analysis to suggest hoising all of the relevant parts of"]
                    #[doc =
                    " the users\' code to make the code compile, but that could be too much."]
                    #[doc =
                    " We found the `prop_expr` by the way to check whether the expression is a"]
                    #[doc =
                    " `FormatArguments`, which is a special case since it\'s generated by the"]
                    #[doc = " compiler."]
                    struct NestedStatementVisitor<'tcx> {
                        span: Span,
                        current: usize,
                        found: usize,
                        prop_expr: Option<&'tcx hir::Expr<'tcx>>,
                        call: Option<&'tcx hir::Expr<'tcx>>,
                    }
                    impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
                        fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
                            self.current += 1;
                            walk_block(self, block);
                            self.current -= 1;
                        }
                        fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
                            if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind
                                {
                                if self.span == rcvr.span.source_callsite() {
                                    self.call = Some(expr);
                                }
                            }
                            if self.span == expr.span.source_callsite() {
                                self.found = self.current;
                                if self.prop_expr.is_none() { self.prop_expr = Some(expr); }
                            }
                            walk_expr(self, expr);
                        }
                    }
                    let source_info = self.body.source_info(location);
                    let proper_span = proper_span.source_callsite();
                    if let Some(scope) =
                                        self.body.source_scopes.get(source_info.scope) &&
                                    let ClearCrossCrate::Set(scope_data) = &scope.local_data &&
                                let Some(id) =
                                    self.infcx.tcx.hir_node(scope_data.lint_root).body_id() &&
                            let hir::ExprKind::Block(block, _) =
                                self.infcx.tcx.hir_body(id).value.kind {
                        for stmt in block.stmts {
                            let mut visitor =
                                NestedStatementVisitor {
                                    span: proper_span,
                                    current: 0,
                                    found: 0,
                                    prop_expr: None,
                                    call: None,
                                };
                            visitor.visit_stmt(stmt);
                            let typeck_results =
                                self.infcx.tcx.typeck(self.mir_def_id());
                            let expr_ty: Option<Ty<'_>> =
                                visitor.prop_expr.map(|expr|
                                        typeck_results.expr_ty(expr).peel_refs());
                            if visitor.found == 0 && stmt.span.contains(proper_span) &&
                                        let Some(p) = sm.span_to_margin(stmt.span) &&
                                    let Ok(s) = sm.span_to_snippet(proper_span) {
                                if let Some(call) = visitor.call &&
                                                let hir::ExprKind::MethodCall(path, _, [], _) = call.kind &&
                                            path.ident.name == sym::iter && let Some(ty) = expr_ty {
                                    err.span_suggestion_verbose(path.ident.span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("consider consuming the `{0}` when turning it into an `Iterator`",
                                                        ty))
                                            }), "into_iter", Applicability::MaybeIncorrect);
                                }
                                let mutability =
                                    if #[allow(non_exhaustive_omitted_patterns)] match borrow.kind()
                                            {
                                            BorrowKind::Mut { .. } => true,
                                            _ => false,
                                        } {
                                        "mut "
                                    } else { "" };
                                let addition =
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("let {0}binding = {1};\n{2}",
                                                    mutability, s, " ".repeat(p)))
                                        });
                                err.multipart_suggestion(msg,
                                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                            [(stmt.span.shrink_to_lo(), addition),
                                                    (proper_span, "binding".to_string())])),
                                    Applicability::MaybeIncorrect);
                                suggested = true;
                                break;
                            }
                        }
                    }
                    if !suggested { err.note(msg); }
                }
                _ => {}
            }
            explanation.add_explanation_to_diagnostic(&self, &mut err, "",
                None, None);
            borrow_spans.args_subdiag(&mut err,
                |args_span|
                    {
                        crate::session_diagnostics::CaptureArgLabel::Capture {
                            is_within: borrow_spans.for_coroutine(),
                            args_span,
                        }
                    });
            err
        }
    }
}#[instrument(level = "debug", skip(self))]
3350    fn report_temporary_value_does_not_live_long_enough(
3351        &self,
3352        location: Location,
3353        borrow: &BorrowData<'tcx>,
3354        drop_span: Span,
3355        borrow_spans: UseSpans<'tcx>,
3356        proper_span: Span,
3357        explanation: BorrowExplanation<'tcx>,
3358    ) -> Diag<'infcx> {
3359        if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
3360            explanation
3361        {
3362            if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3363                borrow,
3364                proper_span,
3365                span,
3366                category,
3367                None,
3368            ) {
3369                return diag;
3370            }
3371        }
3372
3373        let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3374        err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3375        err.span_label(drop_span, "temporary value is freed at the end of this statement");
3376
3377        match explanation {
3378            BorrowExplanation::UsedLater(..)
3379            | BorrowExplanation::UsedLaterInLoop(..)
3380            | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3381                // Only give this note and suggestion if it could be relevant.
3382                let sm = self.infcx.tcx.sess.source_map();
3383                let mut suggested = false;
3384                let msg = "consider using a `let` binding to create a longer lived value";
3385
3386                /// We check that there's a single level of block nesting to ensure always correct
3387                /// suggestions. If we don't, then we only provide a free-form message to avoid
3388                /// misleading users in cases like `tests/ui/nll/borrowed-temporary-error.rs`.
3389                /// We could expand the analysis to suggest hoising all of the relevant parts of
3390                /// the users' code to make the code compile, but that could be too much.
3391                /// We found the `prop_expr` by the way to check whether the expression is a
3392                /// `FormatArguments`, which is a special case since it's generated by the
3393                /// compiler.
3394                struct NestedStatementVisitor<'tcx> {
3395                    span: Span,
3396                    current: usize,
3397                    found: usize,
3398                    prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3399                    call: Option<&'tcx hir::Expr<'tcx>>,
3400                }
3401
3402                impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3403                    fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3404                        self.current += 1;
3405                        walk_block(self, block);
3406                        self.current -= 1;
3407                    }
3408                    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3409                        if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3410                            if self.span == rcvr.span.source_callsite() {
3411                                self.call = Some(expr);
3412                            }
3413                        }
3414                        if self.span == expr.span.source_callsite() {
3415                            self.found = self.current;
3416                            if self.prop_expr.is_none() {
3417                                self.prop_expr = Some(expr);
3418                            }
3419                        }
3420                        walk_expr(self, expr);
3421                    }
3422                }
3423                let source_info = self.body.source_info(location);
3424                let proper_span = proper_span.source_callsite();
3425                if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3426                    && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3427                    && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3428                    && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3429                {
3430                    for stmt in block.stmts {
3431                        let mut visitor = NestedStatementVisitor {
3432                            span: proper_span,
3433                            current: 0,
3434                            found: 0,
3435                            prop_expr: None,
3436                            call: None,
3437                        };
3438                        visitor.visit_stmt(stmt);
3439
3440                        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3441                        let expr_ty: Option<Ty<'_>> =
3442                            visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3443
3444                        if visitor.found == 0
3445                            && stmt.span.contains(proper_span)
3446                            && let Some(p) = sm.span_to_margin(stmt.span)
3447                            && let Ok(s) = sm.span_to_snippet(proper_span)
3448                        {
3449                            if let Some(call) = visitor.call
3450                                && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3451                                && path.ident.name == sym::iter
3452                                && let Some(ty) = expr_ty
3453                            {
3454                                err.span_suggestion_verbose(
3455                                    path.ident.span,
3456                                    format!(
3457                                        "consider consuming the `{ty}` when turning it into an \
3458                                         `Iterator`",
3459                                    ),
3460                                    "into_iter",
3461                                    Applicability::MaybeIncorrect,
3462                                );
3463                            }
3464
3465                            let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3466                                "mut "
3467                            } else {
3468                                ""
3469                            };
3470
3471                            let addition =
3472                                format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3473                            err.multipart_suggestion(
3474                                msg,
3475                                vec![
3476                                    (stmt.span.shrink_to_lo(), addition),
3477                                    (proper_span, "binding".to_string()),
3478                                ],
3479                                Applicability::MaybeIncorrect,
3480                            );
3481
3482                            suggested = true;
3483                            break;
3484                        }
3485                    }
3486                }
3487                if !suggested {
3488                    err.note(msg);
3489                }
3490            }
3491            _ => {}
3492        }
3493        explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3494
3495        borrow_spans.args_subdiag(&mut err, |args_span| {
3496            crate::session_diagnostics::CaptureArgLabel::Capture {
3497                is_within: borrow_spans.for_coroutine(),
3498                args_span,
3499            }
3500        });
3501
3502        err
3503    }
3504
3505    fn try_report_cannot_return_reference_to_local(
3506        &self,
3507        borrow: &BorrowData<'tcx>,
3508        borrow_span: Span,
3509        return_span: Span,
3510        category: ConstraintCategory<'tcx>,
3511        opt_place_desc: Option<&String>,
3512    ) -> Result<(), Diag<'infcx>> {
3513        let return_kind = match category {
3514            ConstraintCategory::Return(_) => "return",
3515            ConstraintCategory::Yield => "yield",
3516            _ => return Ok(()),
3517        };
3518
3519        // FIXME use a better heuristic than Spans
3520        let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3521            "reference to"
3522        } else {
3523            "value referencing"
3524        };
3525
3526        let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3527            let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3528                match self.body.local_kind(local) {
3529                    LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3530                        "local variable "
3531                    }
3532                    LocalKind::Arg
3533                        if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3534                    {
3535                        "variable captured by `move` "
3536                    }
3537                    LocalKind::Arg => "function parameter ",
3538                    LocalKind::ReturnPointer | LocalKind::Temp => {
3539                        ::rustc_middle::util::bug::bug_fmt(format_args!("temporary or return pointer with a name"))bug!("temporary or return pointer with a name")
3540                    }
3541                }
3542            } else {
3543                "local data "
3544            };
3545            (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}`{1}`", local_kind, place_desc))
    })format!("{local_kind}`{place_desc}`"), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is borrowed here",
                place_desc))
    })format!("`{place_desc}` is borrowed here"))
3546        } else {
3547            let local = borrow.borrowed_place.local;
3548            match self.body.local_kind(local) {
3549                LocalKind::Arg => (
3550                    "function parameter".to_string(),
3551                    "function parameter borrowed here".to_string(),
3552                ),
3553                LocalKind::Temp
3554                    if self.body.local_decls[local].is_user_variable()
3555                        && !self.body.local_decls[local]
3556                            .source_info
3557                            .span
3558                            .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3559                {
3560                    ("local binding".to_string(), "local binding introduced here".to_string())
3561                }
3562                LocalKind::ReturnPointer | LocalKind::Temp => {
3563                    ("temporary value".to_string(), "temporary value created here".to_string())
3564                }
3565            }
3566        };
3567
3568        let mut err = self.cannot_return_reference_to_local(
3569            return_span,
3570            return_kind,
3571            reference_desc,
3572            &place_desc,
3573        );
3574
3575        if return_span != borrow_span {
3576            err.span_label(borrow_span, note);
3577
3578            let tcx = self.infcx.tcx;
3579
3580            let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3581
3582            // to avoid panics
3583            if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3584                && self
3585                    .infcx
3586                    .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3587                    .must_apply_modulo_regions()
3588            {
3589                err.span_suggestion_hidden(
3590                    return_span.shrink_to_hi(),
3591                    "use `.collect()` to allocate the iterator",
3592                    ".collect::<Vec<_>>()",
3593                    Applicability::MaybeIncorrect,
3594                );
3595            }
3596
3597            if let Some(cow_did) = tcx.get_diagnostic_item(sym::Cow)
3598                && let ty::Adt(adt_def, _) = return_ty.kind()
3599                && adt_def.did() == cow_did
3600            {
3601                let typeck = tcx.typeck(self.mir_def_id());
3602                if let Some(expr) = self.find_expr(return_span)
3603                    && let Some(def_id) = typeck.type_dependent_def_id(expr.hir_id)
3604                    && tcx.is_diagnostic_item(sym::to_owned_method, def_id)
3605                    && let Some(to_owned_ident) = expr.method_ident()
3606                {
3607                    err.span_suggestion_short(
3608                        to_owned_ident.span.shrink_to_lo(),
3609                        "try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`",
3610                        "in",
3611                        Applicability::MaybeIncorrect,
3612                    );
3613                }
3614            }
3615        }
3616
3617        Err(err)
3618    }
3619
3620    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("report_escaping_closure_capture",
                                    "rustc_borrowck::diagnostics::conflict_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3620u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["use_span",
                                                    "var_span", "fr_name", "category", "constraint_span",
                                                    "captured_var", "scope"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr_name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&category)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&captured_var as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&scope as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Diag<'infcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.infcx.tcx;
            let args_span = use_span.args_or_use();
            let (sugg_span, suggestion) =
                match tcx.sess.source_map().span_to_snippet(args_span) {
                    Ok(string) => {
                        let coro_prefix =
                            if let Some(sub) = string.strip_prefix("async") {
                                let trimmed_sub = sub.trim_end();
                                if trimmed_sub.ends_with("gen") {
                                    Some((trimmed_sub.len() + 5) as _)
                                } else { Some(5) }
                            } else if string.starts_with("gen") {
                                Some(3)
                            } else if string.starts_with("static") {
                                Some(6)
                            } else { None };
                        if let Some(n) = coro_prefix {
                            let pos = args_span.lo() + BytePos(n);
                            (args_span.with_lo(pos).with_hi(pos), " move")
                        } else { (args_span.shrink_to_lo(), "move ") }
                    }
                    Err(_) => (args_span, "move |<args>| <body>"),
                };
            let kind =
                match use_span.coroutine_kind() {
                    Some(coroutine_kind) =>
                        match coroutine_kind {
                            CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) =>
                                match kind {
                                    CoroutineSource::Block => "gen block",
                                    CoroutineSource::Closure => "gen closure",
                                    CoroutineSource::Fn => {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("gen block/closure expected, but gen function found."))
                                    }
                                },
                            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
                                kind) =>
                                match kind {
                                    CoroutineSource::Block => "async gen block",
                                    CoroutineSource::Closure => "async gen closure",
                                    CoroutineSource::Fn => {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("gen block/closure expected, but gen function found."))
                                    }
                                },
                            CoroutineKind::Desugared(CoroutineDesugaring::Async,
                                async_kind) => {
                                match async_kind {
                                    CoroutineSource::Block => "async block",
                                    CoroutineSource::Closure => "async closure",
                                    CoroutineSource::Fn => {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("async block/closure expected, but async function found."))
                                    }
                                }
                            }
                            CoroutineKind::Coroutine(_) => "coroutine",
                        },
                    None => "closure",
                };
            let mut err =
                self.cannot_capture_in_long_lived_closure(args_span, kind,
                    captured_var, var_span, scope);
            err.span_suggestion_verbose(sugg_span,
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("to force the {0} to take ownership of {1} (and any other referenced variables), use the `move` keyword",
                                kind, captured_var))
                    }), suggestion, Applicability::MachineApplicable);
            match category {
                ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType
                    => {
                    let msg =
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0} is returned here",
                                        kind))
                            });
                    err.span_note(constraint_span, msg);
                }
                ConstraintCategory::CallArgument(_) => {
                    fr_name.highlight_region_name(&mut err);
                    if #[allow(non_exhaustive_omitted_patterns)] match use_span.coroutine_kind()
                            {
                            Some(CoroutineKind::Desugared(CoroutineDesugaring::Async,
                                _)) => true,
                            _ => false,
                        } {
                        err.note("async blocks are not executed immediately and must either take a \
                         reference or ownership of outside variables they use");
                    } else {
                        let msg =
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0} requires argument type to outlive `{1}`",
                                            scope, fr_name))
                                });
                        err.span_note(constraint_span, msg);
                    }
                }
                _ =>
                    ::rustc_middle::util::bug::bug_fmt(format_args!("report_escaping_closure_capture called with unexpected constraint category: `{0:?}`",
                            category)),
            }
            err
        }
    }
}#[instrument(level = "debug", skip(self))]
3621    fn report_escaping_closure_capture(
3622        &self,
3623        use_span: UseSpans<'tcx>,
3624        var_span: Span,
3625        fr_name: &RegionName,
3626        category: ConstraintCategory<'tcx>,
3627        constraint_span: Span,
3628        captured_var: &str,
3629        scope: &str,
3630    ) -> Diag<'infcx> {
3631        let tcx = self.infcx.tcx;
3632        let args_span = use_span.args_or_use();
3633
3634        let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3635            Ok(string) => {
3636                let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3637                    let trimmed_sub = sub.trim_end();
3638                    if trimmed_sub.ends_with("gen") {
3639                        // `async` is 5 chars long.
3640                        Some((trimmed_sub.len() + 5) as _)
3641                    } else {
3642                        // `async` is 5 chars long.
3643                        Some(5)
3644                    }
3645                } else if string.starts_with("gen") {
3646                    // `gen` is 3 chars long
3647                    Some(3)
3648                } else if string.starts_with("static") {
3649                    // `static` is 6 chars long
3650                    // This is used for `!Unpin` coroutines
3651                    Some(6)
3652                } else {
3653                    None
3654                };
3655                if let Some(n) = coro_prefix {
3656                    let pos = args_span.lo() + BytePos(n);
3657                    (args_span.with_lo(pos).with_hi(pos), " move")
3658                } else {
3659                    (args_span.shrink_to_lo(), "move ")
3660                }
3661            }
3662            Err(_) => (args_span, "move |<args>| <body>"),
3663        };
3664        let kind = match use_span.coroutine_kind() {
3665            Some(coroutine_kind) => match coroutine_kind {
3666                CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3667                    CoroutineSource::Block => "gen block",
3668                    CoroutineSource::Closure => "gen closure",
3669                    CoroutineSource::Fn => {
3670                        bug!("gen block/closure expected, but gen function found.")
3671                    }
3672                },
3673                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3674                    CoroutineSource::Block => "async gen block",
3675                    CoroutineSource::Closure => "async gen closure",
3676                    CoroutineSource::Fn => {
3677                        bug!("gen block/closure expected, but gen function found.")
3678                    }
3679                },
3680                CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3681                    match async_kind {
3682                        CoroutineSource::Block => "async block",
3683                        CoroutineSource::Closure => "async closure",
3684                        CoroutineSource::Fn => {
3685                            bug!("async block/closure expected, but async function found.")
3686                        }
3687                    }
3688                }
3689                CoroutineKind::Coroutine(_) => "coroutine",
3690            },
3691            None => "closure",
3692        };
3693
3694        let mut err = self.cannot_capture_in_long_lived_closure(
3695            args_span,
3696            kind,
3697            captured_var,
3698            var_span,
3699            scope,
3700        );
3701        err.span_suggestion_verbose(
3702            sugg_span,
3703            format!(
3704                "to force the {kind} to take ownership of {captured_var} (and any \
3705                 other referenced variables), use the `move` keyword"
3706            ),
3707            suggestion,
3708            Applicability::MachineApplicable,
3709        );
3710
3711        match category {
3712            ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3713                let msg = format!("{kind} is returned here");
3714                err.span_note(constraint_span, msg);
3715            }
3716            ConstraintCategory::CallArgument(_) => {
3717                fr_name.highlight_region_name(&mut err);
3718                if matches!(
3719                    use_span.coroutine_kind(),
3720                    Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3721                ) {
3722                    err.note(
3723                        "async blocks are not executed immediately and must either take a \
3724                         reference or ownership of outside variables they use",
3725                    );
3726                } else {
3727                    let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3728                    err.span_note(constraint_span, msg);
3729                }
3730            }
3731            _ => bug!(
3732                "report_escaping_closure_capture called with unexpected constraint \
3733                 category: `{:?}`",
3734                category
3735            ),
3736        }
3737
3738        err
3739    }
3740
3741    fn report_escaping_data(
3742        &self,
3743        borrow_span: Span,
3744        name: &Option<String>,
3745        upvar_span: Span,
3746        upvar_name: Symbol,
3747        escape_span: Span,
3748    ) -> Diag<'infcx> {
3749        let tcx = self.infcx.tcx;
3750
3751        let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3752
3753        let mut err =
3754            borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
3755
3756        err.span_label(
3757            upvar_span,
3758            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` declared here, outside of the {1} body",
                upvar_name, escapes_from))
    })format!("`{upvar_name}` declared here, outside of the {escapes_from} body"),
3759        );
3760
3761        err.span_label(borrow_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("borrow is only valid in the {0} body",
                escapes_from))
    })format!("borrow is only valid in the {escapes_from} body"));
3762
3763        if let Some(name) = name {
3764            err.span_label(
3765                escape_span,
3766                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("reference to `{0}` escapes the {1} body here",
                name, escapes_from))
    })format!("reference to `{name}` escapes the {escapes_from} body here"),
3767            );
3768        } else {
3769            err.span_label(escape_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("reference escapes the {0} body here",
                escapes_from))
    })format!("reference escapes the {escapes_from} body here"));
3770        }
3771
3772        err
3773    }
3774
3775    fn get_moved_indexes(
3776        &self,
3777        location: Location,
3778        mpi: MovePathIndex,
3779    ) -> (Vec<MoveSite>, Vec<Location>) {
3780        fn predecessor_locations<'tcx>(
3781            body: &mir::Body<'tcx>,
3782            location: Location,
3783        ) -> impl Iterator<Item = Location> {
3784            if location.statement_index == 0 {
3785                let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3786                Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3787            } else {
3788                Either::Right(std::iter::once(Location {
3789                    statement_index: location.statement_index - 1,
3790                    ..location
3791                }))
3792            }
3793        }
3794
3795        let mut mpis = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [mpi]))vec![mpi];
3796        let move_paths = &self.move_data.move_paths;
3797        mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3798
3799        let mut stack = Vec::new();
3800        let mut back_edge_stack = Vec::new();
3801
3802        predecessor_locations(self.body, location).for_each(|predecessor| {
3803            if location.dominates(predecessor, self.dominators()) {
3804                back_edge_stack.push(predecessor)
3805            } else {
3806                stack.push(predecessor);
3807            }
3808        });
3809
3810        let mut reached_start = false;
3811
3812        /* Check if the mpi is initialized as an argument */
3813        let mut is_argument = false;
3814        for arg in self.body.args_iter() {
3815            if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3816                if mpis.contains(&path) {
3817                    is_argument = true;
3818                }
3819            }
3820        }
3821
3822        let mut visited = FxIndexSet::default();
3823        let mut move_locations = FxIndexSet::default();
3824        let mut reinits = ::alloc::vec::Vec::new()vec![];
3825        let mut result = ::alloc::vec::Vec::new()vec![];
3826
3827        let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3828            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3828",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(3828u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: (current_location={0:?}, back_edge={1})",
                                                    location, is_back_edge) as &dyn Value))])
            });
    } else { ; }
};debug!(
3829                "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3830                location, is_back_edge
3831            );
3832
3833            if !visited.insert(location) {
3834                return true;
3835            }
3836
3837            // check for moves
3838            let stmt_kind =
3839                self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3840            if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3841                // This analysis only tries to find moves explicitly written by the user, so we
3842                // ignore the move-outs created by `StorageDead` and at the beginning of a
3843                // function.
3844            } else {
3845                // If we are found a use of a.b.c which was in error, then we want to look for
3846                // moves not only of a.b.c but also a.b and a.
3847                //
3848                // Note that the moves data already includes "parent" paths, so we don't have to
3849                // worry about the other case: that is, if there is a move of a.b.c, it is already
3850                // marked as a move of a.b and a as well, so we will generate the correct errors
3851                // there.
3852                for moi in &self.move_data.loc_map[location] {
3853                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3853",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(3853u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: moi={0:?}",
                                                    moi) as &dyn Value))])
            });
    } else { ; }
};debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
3854                    let path = self.move_data.moves[*moi].path;
3855                    if mpis.contains(&path) {
3856                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3856",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(3856u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_use_of_moved_or_uninitialized: found {0:?}",
                                                    move_paths[path].place) as &dyn Value))])
            });
    } else { ; }
};debug!(
3857                            "report_use_of_moved_or_uninitialized: found {:?}",
3858                            move_paths[path].place
3859                        );
3860                        result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3861                        move_locations.insert(location);
3862
3863                        // Strictly speaking, we could continue our DFS here. There may be
3864                        // other moves that can reach the point of error. But it is kind of
3865                        // confusing to highlight them.
3866                        //
3867                        // Example:
3868                        //
3869                        // ```
3870                        // let a = vec![];
3871                        // let b = a;
3872                        // let c = a;
3873                        // drop(a); // <-- current point of error
3874                        // ```
3875                        //
3876                        // Because we stop the DFS here, we only highlight `let c = a`,
3877                        // and not `let b = a`. We will of course also report an error at
3878                        // `let c = a` which highlights `let b = a` as the move.
3879                        return true;
3880                    }
3881                }
3882            }
3883
3884            // check for inits
3885            let mut any_match = false;
3886            for ii in &self.move_data.init_loc_map[location] {
3887                let init = self.move_data.inits[*ii];
3888                match init.kind {
3889                    InitKind::Deep | InitKind::NonPanicPathOnly => {
3890                        if mpis.contains(&init.path) {
3891                            any_match = true;
3892                        }
3893                    }
3894                    InitKind::Shallow => {
3895                        if mpi == init.path {
3896                            any_match = true;
3897                        }
3898                    }
3899                }
3900            }
3901            if any_match {
3902                reinits.push(location);
3903                return true;
3904            }
3905            false
3906        };
3907
3908        while let Some(location) = stack.pop() {
3909            if dfs_iter(&mut result, location, false) {
3910                continue;
3911            }
3912
3913            let mut has_predecessor = false;
3914            predecessor_locations(self.body, location).for_each(|predecessor| {
3915                if location.dominates(predecessor, self.dominators()) {
3916                    back_edge_stack.push(predecessor)
3917                } else {
3918                    stack.push(predecessor);
3919                }
3920                has_predecessor = true;
3921            });
3922
3923            if !has_predecessor {
3924                reached_start = true;
3925            }
3926        }
3927        if (is_argument || !reached_start) && result.is_empty() {
3928            // Process back edges (moves in future loop iterations) only if
3929            // the move path is definitely initialized upon loop entry,
3930            // to avoid spurious "in previous iteration" errors.
3931            // During DFS, if there's a path from the error back to the start
3932            // of the function with no intervening init or move, then the
3933            // move path may be uninitialized at loop entry.
3934            while let Some(location) = back_edge_stack.pop() {
3935                if dfs_iter(&mut result, location, true) {
3936                    continue;
3937                }
3938
3939                predecessor_locations(self.body, location)
3940                    .for_each(|predecessor| back_edge_stack.push(predecessor));
3941            }
3942        }
3943
3944        // Check if we can reach these reinits from a move location.
3945        let reinits_reachable = reinits
3946            .into_iter()
3947            .filter(|reinit| {
3948                let mut visited = FxIndexSet::default();
3949                let mut stack = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [*reinit]))vec![*reinit];
3950                while let Some(location) = stack.pop() {
3951                    if !visited.insert(location) {
3952                        continue;
3953                    }
3954                    if move_locations.contains(&location) {
3955                        return true;
3956                    }
3957                    stack.extend(predecessor_locations(self.body, location));
3958                }
3959                false
3960            })
3961            .collect::<Vec<Location>>();
3962        (result, reinits_reachable)
3963    }
3964
3965    pub(crate) fn report_illegal_mutation_of_borrowed(
3966        &mut self,
3967        location: Location,
3968        (place, span): (Place<'tcx>, Span),
3969        loan: &BorrowData<'tcx>,
3970    ) {
3971        let loan_spans = self.retrieve_borrow_spans(loan);
3972        let loan_span = loan_spans.args_or_use();
3973
3974        let descr_place = self.describe_any_place(place.as_ref());
3975        if let BorrowKind::Fake(_) = loan.kind
3976            && let Some(section) = self.classify_immutable_section(loan.assigned_place)
3977        {
3978            let mut err = self.cannot_mutate_in_immutable_section(
3979                span,
3980                loan_span,
3981                &descr_place,
3982                section,
3983                "assign",
3984            );
3985
3986            loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3987                use crate::session_diagnostics::CaptureVarCause::*;
3988                match kind {
3989                    hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3990                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3991                        BorrowUseInClosure { var_span }
3992                    }
3993                }
3994            });
3995
3996            self.buffer_error(err);
3997
3998            return;
3999        }
4000
4001        let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
4002        self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
4003
4004        loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
4005            use crate::session_diagnostics::CaptureVarCause::*;
4006            match kind {
4007                hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
4008                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
4009                    BorrowUseInClosure { var_span }
4010                }
4011            }
4012        });
4013
4014        self.explain_why_borrow_contains_point(location, loan, None)
4015            .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
4016
4017        self.explain_deref_coercion(loan, &mut err);
4018
4019        self.buffer_error(err);
4020    }
4021
4022    fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
4023        let tcx = self.infcx.tcx;
4024        if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
4025            &self.body[loan.reserve_location.block].terminator
4026            && let Some((method_did, method_args)) = mir::find_self_call(
4027                tcx,
4028                self.body,
4029                loan.assigned_place.local,
4030                loan.reserve_location.block,
4031            )
4032            && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
4033                self.infcx.tcx,
4034                self.infcx.typing_env(self.infcx.param_env),
4035                method_did,
4036                method_args,
4037                *fn_span,
4038                call_source.from_hir_call(),
4039                self.infcx.tcx.fn_arg_idents(method_did)[0],
4040            )
4041        {
4042            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("borrow occurs due to deref coercion to `{0}`",
                deref_target_ty))
    })format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
4043            if let Some(deref_target_span) = deref_target_span {
4044                err.span_note(deref_target_span, "deref defined here");
4045            }
4046        }
4047    }
4048
4049    /// Reports an illegal reassignment; for example, an assignment to
4050    /// (part of) a non-`mut` local that occurs potentially after that
4051    /// local has already been initialized. `place` is the path being
4052    /// assigned; `err_place` is a place providing a reason why
4053    /// `place` is not mutable (e.g., the non-`mut` local `x` in an
4054    /// assignment to `x.f`).
4055    pub(crate) fn report_illegal_reassignment(
4056        &mut self,
4057        (place, span): (Place<'tcx>, Span),
4058        assigned_span: Span,
4059        err_place: Place<'tcx>,
4060    ) {
4061        let (from_arg, local_decl) = match err_place.as_local() {
4062            Some(local) => {
4063                (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
4064            }
4065            None => (false, None),
4066        };
4067
4068        // If root local is initialized immediately (everything apart from let
4069        // PATTERN;) then make the error refer to that local, rather than the
4070        // place being assigned later.
4071        let (place_description, assigned_span) = match local_decl {
4072            Some(LocalDecl {
4073                local_info:
4074                    ClearCrossCrate::Set(
4075                        LocalInfo::User(BindingForm::Var(VarBindingForm {
4076                            opt_match_place: None,
4077                            ..
4078                        }))
4079                        | LocalInfo::StaticRef { .. }
4080                        | LocalInfo::Boring,
4081                    ),
4082                ..
4083            })
4084            | None => (self.describe_any_place(place.as_ref()), assigned_span),
4085            Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
4086        };
4087        let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
4088        let msg = if from_arg {
4089            "cannot assign to immutable argument"
4090        } else {
4091            "cannot assign twice to immutable variable"
4092        };
4093        if span != assigned_span && !from_arg {
4094            err.span_label(assigned_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("first assignment to {0}",
                place_description))
    })format!("first assignment to {place_description}"));
4095        }
4096        if let Some(decl) = local_decl
4097            && decl.can_be_made_mutable()
4098        {
4099            let mut is_for_loop = false;
4100            let mut is_immut_ref_pattern = false;
4101            if let LocalInfo::User(BindingForm::Var(VarBindingForm {
4102                opt_match_place: Some((_, match_span)),
4103                ..
4104            })) = *decl.local_info()
4105            {
4106                if #[allow(non_exhaustive_omitted_patterns)] match match_span.desugaring_kind() {
    Some(DesugaringKind::ForLoop) => true,
    _ => false,
}matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop)) {
4107                    is_for_loop = true;
4108                }
4109
4110                if let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
4111                    struct RefPatternFinder<'tcx> {
4112                        tcx: TyCtxt<'tcx>,
4113                        binding_span: Span,
4114                        is_immut_ref_pattern: bool,
4115                    }
4116
4117                    impl<'tcx> Visitor<'tcx> for RefPatternFinder<'tcx> {
4118                        type NestedFilter = OnlyBodies;
4119
4120                        fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
4121                            self.tcx
4122                        }
4123
4124                        fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
4125                            if !self.is_immut_ref_pattern
4126                                && let hir::PatKind::Binding(_, _, ident, _) = pat.kind
4127                                && ident.span == self.binding_span
4128                                && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(pat.hir_id)
    {
    hir::Node::Pat(hir::Pat {
        kind: hir::PatKind::Ref(_, _, hir::Mutability::Not), .. }) => true,
    _ => false,
}matches!(
4129                                    self.tcx.parent_hir_node(pat.hir_id),
4130                                    hir::Node::Pat(hir::Pat {
4131                                        kind: hir::PatKind::Ref(_, _, hir::Mutability::Not),
4132                                        ..
4133                                    })
4134                                )
4135                            {
4136                                self.is_immut_ref_pattern = true;
4137                            }
4138                            hir::intravisit::walk_pat(self, pat);
4139                        }
4140                    }
4141
4142                    let mut finder = RefPatternFinder {
4143                        tcx: self.infcx.tcx,
4144                        binding_span: decl.source_info.span,
4145                        is_immut_ref_pattern: false,
4146                    };
4147
4148                    finder.visit_body(body);
4149                    is_immut_ref_pattern = finder.is_immut_ref_pattern;
4150                }
4151            }
4152
4153            let (span, message) = if is_immut_ref_pattern
4154                && let Ok(binding_name) =
4155                    self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
4156            {
4157                (decl.source_info.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("(mut {0})", binding_name))
    })format!("(mut {})", binding_name))
4158            } else {
4159                (decl.source_info.span.shrink_to_lo(), "mut ".to_string())
4160            };
4161
4162            err.span_suggestion_verbose(
4163                span,
4164                "consider making this binding mutable",
4165                message,
4166                Applicability::MachineApplicable,
4167            );
4168
4169            if !from_arg
4170                && !is_for_loop
4171                && #[allow(non_exhaustive_omitted_patterns)] match decl.local_info() {
    LocalInfo::User(BindingForm::Var(VarBindingForm {
        opt_match_place: Some((Some(_), _)), .. })) => true,
    _ => false,
}matches!(
4172                    decl.local_info(),
4173                    LocalInfo::User(BindingForm::Var(VarBindingForm {
4174                        opt_match_place: Some((Some(_), _)),
4175                        ..
4176                    }))
4177                )
4178            {
4179                err.span_suggestion_verbose(
4180                    decl.source_info.span.shrink_to_lo(),
4181                    "to modify the original value, take a borrow instead",
4182                    "ref mut ".to_string(),
4183                    Applicability::MaybeIncorrect,
4184                );
4185            }
4186        }
4187        err.span_label(span, msg);
4188        self.buffer_error(err);
4189    }
4190
4191    fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
4192        let tcx = self.infcx.tcx;
4193        let (kind, _place_ty) = place.projection.iter().fold(
4194            (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
4195            |(kind, place_ty), &elem| {
4196                (
4197                    match elem {
4198                        ProjectionElem::Deref => match kind {
4199                            StorageDeadOrDrop::LocalStorageDead
4200                            | StorageDeadOrDrop::BoxedStorageDead => {
4201                                if !place_ty.ty.is_box() {
    {
        ::core::panicking::panic_fmt(format_args!("Drop of value behind a reference or raw pointer"));
    }
};assert!(
4202                                    place_ty.ty.is_box(),
4203                                    "Drop of value behind a reference or raw pointer"
4204                                );
4205                                StorageDeadOrDrop::BoxedStorageDead
4206                            }
4207                            StorageDeadOrDrop::Destructor(_) => kind,
4208                        },
4209                        ProjectionElem::OpaqueCast { .. }
4210                        | ProjectionElem::Field(..)
4211                        | ProjectionElem::Downcast(..) => {
4212                            match place_ty.ty.kind() {
4213                                ty::Adt(def, _) if def.has_dtor(tcx) => {
4214                                    // Report the outermost adt with a destructor
4215                                    match kind {
4216                                        StorageDeadOrDrop::Destructor(_) => kind,
4217                                        StorageDeadOrDrop::LocalStorageDead
4218                                        | StorageDeadOrDrop::BoxedStorageDead => {
4219                                            StorageDeadOrDrop::Destructor(place_ty.ty)
4220                                        }
4221                                    }
4222                                }
4223                                _ => kind,
4224                            }
4225                        }
4226                        ProjectionElem::ConstantIndex { .. }
4227                        | ProjectionElem::Subslice { .. }
4228                        | ProjectionElem::Index(_)
4229                        | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
4230                    },
4231                    place_ty.projection_ty(tcx, elem),
4232                )
4233            },
4234        );
4235        kind
4236    }
4237
4238    /// Describe the reason for the fake borrow that was assigned to `place`.
4239    fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
4240        use rustc_middle::mir::visit::Visitor;
4241        struct FakeReadCauseFinder<'tcx> {
4242            place: Place<'tcx>,
4243            cause: Option<FakeReadCause>,
4244        }
4245        impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
4246            fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
4247                match statement {
4248                    Statement { kind: StatementKind::FakeRead((cause, place)), .. }
4249                        if *place == self.place =>
4250                    {
4251                        self.cause = Some(*cause);
4252                    }
4253                    _ => (),
4254                }
4255            }
4256        }
4257        let mut visitor = FakeReadCauseFinder { place, cause: None };
4258        visitor.visit_body(self.body);
4259        match visitor.cause {
4260            Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
4261            Some(FakeReadCause::ForIndex) => Some("indexing expression"),
4262            _ => None,
4263        }
4264    }
4265
4266    /// Annotate argument and return type of function and closure with (synthesized) lifetime for
4267    /// borrow of local value that does not live long enough.
4268    fn annotate_argument_and_return_for_borrow(
4269        &self,
4270        borrow: &BorrowData<'tcx>,
4271    ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4272        // Define a fallback for when we can't match a closure.
4273        let fallback = || {
4274            let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
4275            if is_closure {
4276                None
4277            } else {
4278                let ty = self
4279                    .infcx
4280                    .tcx
4281                    .type_of(self.mir_def_id())
4282                    .instantiate_identity()
4283                    .skip_norm_wip();
4284                match ty.kind() {
4285                    ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
4286                        self.mir_def_id(),
4287                        self.infcx
4288                            .tcx
4289                            .fn_sig(self.mir_def_id())
4290                            .instantiate_identity()
4291                            .skip_norm_wip(),
4292                    ),
4293                    _ => None,
4294                }
4295            }
4296        };
4297
4298        // In order to determine whether we need to annotate, we need to check whether the reserve
4299        // place was an assignment into a temporary.
4300        //
4301        // If it was, we check whether or not that temporary is eventually assigned into the return
4302        // place. If it was, we can add annotations about the function's return type and arguments
4303        // and it'll make sense.
4304        let location = borrow.reserve_location;
4305        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4305",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4305u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: location={0:?}",
                                                    location) as &dyn Value))])
            });
    } else { ; }
};debug!("annotate_argument_and_return_for_borrow: location={:?}", location);
4306        if let Some(Statement { kind: StatementKind::Assign((reservation, _)), .. }) =
4307            &self.body[location.block].statements.get(location.statement_index)
4308        {
4309            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4309",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4309u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: reservation={0:?}",
                                                    reservation) as &dyn Value))])
            });
    } else { ; }
};debug!("annotate_argument_and_return_for_borrow: reservation={:?}", reservation);
4310            // Check that the initial assignment of the reserve location is into a temporary.
4311            let mut target = match reservation.as_local() {
4312                Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4313                _ => return None,
4314            };
4315
4316            // Next, look through the rest of the block, checking if we are assigning the
4317            // `target` (that is, the place that contains our borrow) to anything.
4318            let mut annotated_closure = None;
4319            for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4320                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4320",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4320u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: target={0:?} stmt={1:?}",
                                                    target, stmt) as &dyn Value))])
            });
    } else { ; }
};debug!(
4321                    "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4322                    target, stmt
4323                );
4324                if let StatementKind::Assign((place, rvalue)) = &stmt.kind
4325                    && let Some(assigned_to) = place.as_local()
4326                {
4327                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4327",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4327u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_to={0:?} rvalue={1:?}",
                                                    assigned_to, rvalue) as &dyn Value))])
            });
    } else { ; }
};debug!(
4328                        "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4329                             rvalue={:?}",
4330                        assigned_to, rvalue
4331                    );
4332                    // Check if our `target` was captured by a closure.
4333                    if let Rvalue::Aggregate(AggregateKind::Closure(def_id, args), operands) =
4334                        rvalue
4335                    {
4336                        let def_id = def_id.expect_local();
4337                        for operand in operands {
4338                            let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4339                                operand
4340                            else {
4341                                continue;
4342                            };
4343                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4343",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4343u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from={0:?}",
                                                    assigned_from) as &dyn Value))])
            });
    } else { ; }
};debug!(
4344                                "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4345                                assigned_from
4346                            );
4347
4348                            // Find the local from the operand.
4349                            let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4350                            else {
4351                                continue;
4352                            };
4353
4354                            if assigned_from_local != target {
4355                                continue;
4356                            }
4357
4358                            // If a closure captured our `target` and then assigned
4359                            // into a place then we should annotate the closure in
4360                            // case it ends up being assigned into the return place.
4361                            annotated_closure =
4362                                self.annotate_fn_sig(def_id, args.as_closure().sig());
4363                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4363",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4363u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: annotated_closure={0:?} assigned_from_local={1:?} assigned_to={2:?}",
                                                    annotated_closure, assigned_from_local, assigned_to) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
4364                                "annotate_argument_and_return_for_borrow: \
4365                                     annotated_closure={:?} assigned_from_local={:?} \
4366                                     assigned_to={:?}",
4367                                annotated_closure, assigned_from_local, assigned_to
4368                            );
4369
4370                            if assigned_to == mir::RETURN_PLACE {
4371                                // If it was assigned directly into the return place, then
4372                                // return now.
4373                                return annotated_closure;
4374                            } else {
4375                                // Otherwise, update the target.
4376                                target = assigned_to;
4377                            }
4378                        }
4379
4380                        // If none of our closure's operands matched, then skip to the next
4381                        // statement.
4382                        continue;
4383                    }
4384
4385                    // Otherwise, look at other types of assignment.
4386                    let assigned_from = match rvalue {
4387                        Rvalue::Ref(_, _, assigned_from) => assigned_from,
4388                        Rvalue::Use(operand, _) => match operand {
4389                            Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4390                                assigned_from
4391                            }
4392                            _ => continue,
4393                        },
4394                        _ => continue,
4395                    };
4396                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4396",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4396u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from={0:?}",
                                                    assigned_from) as &dyn Value))])
            });
    } else { ; }
};debug!(
4397                        "annotate_argument_and_return_for_borrow: \
4398                             assigned_from={:?}",
4399                        assigned_from,
4400                    );
4401
4402                    // Find the local from the rvalue.
4403                    let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4404                        continue;
4405                    };
4406                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4406",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4406u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from_local={0:?}",
                                                    assigned_from_local) as &dyn Value))])
            });
    } else { ; }
};debug!(
4407                        "annotate_argument_and_return_for_borrow: \
4408                             assigned_from_local={:?}",
4409                        assigned_from_local,
4410                    );
4411
4412                    // Check if our local matches the target - if so, we've assigned our
4413                    // borrow to a new place.
4414                    if assigned_from_local != target {
4415                        continue;
4416                    }
4417
4418                    // If we assigned our `target` into a new place, then we should
4419                    // check if it was the return place.
4420                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4420",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4420u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from_local={0:?} assigned_to={1:?}",
                                                    assigned_from_local, assigned_to) as &dyn Value))])
            });
    } else { ; }
};debug!(
4421                        "annotate_argument_and_return_for_borrow: \
4422                             assigned_from_local={:?} assigned_to={:?}",
4423                        assigned_from_local, assigned_to
4424                    );
4425                    if assigned_to == mir::RETURN_PLACE {
4426                        // If it was then return the annotated closure if there was one,
4427                        // else, annotate this function.
4428                        return annotated_closure.or_else(fallback);
4429                    }
4430
4431                    // If we didn't assign into the return place, then we just update
4432                    // the target.
4433                    target = assigned_to;
4434                }
4435            }
4436
4437            // Check the terminator if we didn't find anything in the statements.
4438            let terminator = &self.body[location.block].terminator();
4439            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4439",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4439u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: target={0:?} terminator={1:?}",
                                                    target, terminator) as &dyn Value))])
            });
    } else { ; }
};debug!(
4440                "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4441                target, terminator
4442            );
4443            if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4444                &terminator.kind
4445                && let Some(assigned_to) = destination.as_local()
4446            {
4447                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4447",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4447u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_to={0:?} args={1:?}",
                                                    assigned_to, args) as &dyn Value))])
            });
    } else { ; }
};debug!(
4448                    "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4449                    assigned_to, args
4450                );
4451                for operand in args {
4452                    let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4453                        &operand.node
4454                    else {
4455                        continue;
4456                    };
4457                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4457",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4457u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from={0:?}",
                                                    assigned_from) as &dyn Value))])
            });
    } else { ; }
};debug!(
4458                        "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4459                        assigned_from,
4460                    );
4461
4462                    if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4463                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4463",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4463u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: assigned_from_local={0:?}",
                                                    assigned_from_local) as &dyn Value))])
            });
    } else { ; }
};debug!(
4464                            "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4465                            assigned_from_local,
4466                        );
4467
4468                        if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4469                            return annotated_closure.or_else(fallback);
4470                        }
4471                    }
4472                }
4473            }
4474        }
4475
4476        // If we haven't found an assignment into the return place, then we need not add
4477        // any annotations.
4478        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4478",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4478u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_argument_and_return_for_borrow: none found")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("annotate_argument_and_return_for_borrow: none found");
4479        None
4480    }
4481
4482    /// Annotate the first argument and return type of a function signature if they are
4483    /// references.
4484    fn annotate_fn_sig(
4485        &self,
4486        did: LocalDefId,
4487        sig: ty::PolyFnSig<'tcx>,
4488    ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4489        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:4489",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(4489u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("annotate_fn_sig: did={0:?} sig={1:?}",
                                                    did, sig) as &dyn Value))])
            });
    } else { ; }
};debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
4490        let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4491        let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4492        let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4493
4494        // We need to work out which arguments to highlight. We do this by looking
4495        // at the return type, where there are three cases:
4496        //
4497        // 1. If there are named arguments, then we should highlight the return type and
4498        //    highlight any of the arguments that are also references with that lifetime.
4499        //    If there are no arguments that have the same lifetime as the return type,
4500        //    then don't highlight anything.
4501        // 2. The return type is a reference with an anonymous lifetime. If this is
4502        //    the case, then we can take advantage of (and teach) the lifetime elision
4503        //    rules.
4504        //
4505        //    We know that an error is being reported. So the arguments and return type
4506        //    must satisfy the elision rules. Therefore, if there is a single argument
4507        //    then that means the return type and first (and only) argument have the same
4508        //    lifetime and the borrow isn't meeting that, we can highlight the argument
4509        //    and return type.
4510        //
4511        //    If there are multiple arguments then the first argument must be self (else
4512        //    it would not satisfy the elision rules), so we can highlight self and the
4513        //    return type.
4514        // 3. The return type is not a reference. In this case, we don't highlight
4515        //    anything.
4516        let return_ty = sig.output();
4517        match return_ty.skip_binder().kind() {
4518            ty::Ref(return_region, _, _)
4519                if return_region.is_named(self.infcx.tcx) && !is_closure =>
4520            {
4521                // This is case 1 from above, return type is a named reference so we need to
4522                // search for relevant arguments.
4523                let mut arguments = Vec::new();
4524                for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4525                    if let ty::Ref(argument_region, _, _) = argument.kind()
4526                        && argument_region == return_region
4527                    {
4528                        // Need to use the `rustc_middle::ty` types to compare against the
4529                        // `return_region`. Then use the `rustc_hir` type to get only
4530                        // the lifetime span.
4531                        match &fn_decl.inputs[index].kind {
4532                            hir::TyKind::Ref(lifetime, _) => {
4533                                // With access to the lifetime, we can get
4534                                // the span of it.
4535                                arguments.push((*argument, lifetime.ident.span));
4536                            }
4537                            // Resolve `self` whose self type is `&T`.
4538                            hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4539                                if let Res::SelfTyAlias { alias_to, .. } = path.res
4540                                    && let Some(alias_to) = alias_to.as_local()
4541                                    && let hir::Impl { self_ty, .. } = self
4542                                        .infcx
4543                                        .tcx
4544                                        .hir_node_by_def_id(alias_to)
4545                                        .expect_item()
4546                                        .expect_impl()
4547                                    && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4548                                {
4549                                    arguments.push((*argument, lifetime.ident.span));
4550                                }
4551                            }
4552                            _ => {
4553                                // Don't ICE though. It might be a type alias.
4554                            }
4555                        }
4556                    }
4557                }
4558
4559                // We need to have arguments. This shouldn't happen, but it's worth checking.
4560                if arguments.is_empty() {
4561                    return None;
4562                }
4563
4564                // We use a mix of the HIR and the Ty types to get information
4565                // as the HIR doesn't have full types for closure arguments.
4566                let return_ty = sig.output().skip_binder();
4567                let mut return_span = fn_decl.output.span();
4568                if let hir::FnRetTy::Return(ty) = &fn_decl.output
4569                    && let hir::TyKind::Ref(lifetime, _) = ty.kind
4570                {
4571                    return_span = lifetime.ident.span;
4572                }
4573
4574                Some(AnnotatedBorrowFnSignature::NamedFunction {
4575                    arguments,
4576                    return_ty,
4577                    return_span,
4578                })
4579            }
4580            ty::Ref(_, _, _) if is_closure => {
4581                // This is case 2 from above but only for closures, return type is anonymous
4582                // reference so we select
4583                // the first argument.
4584                let argument_span = fn_decl.inputs.first()?.span;
4585                let argument_ty = sig.inputs().skip_binder().first()?;
4586
4587                // Closure arguments are wrapped in a tuple, so we need to get the first
4588                // from that.
4589                if let ty::Tuple(elems) = argument_ty.kind() {
4590                    let &argument_ty = elems.first()?;
4591                    if let ty::Ref(_, _, _) = argument_ty.kind() {
4592                        return Some(AnnotatedBorrowFnSignature::Closure {
4593                            argument_ty,
4594                            argument_span,
4595                        });
4596                    }
4597                }
4598
4599                None
4600            }
4601            ty::Ref(_, _, _) => {
4602                // This is also case 2 from above but for functions, return type is still an
4603                // anonymous reference so we select the first argument.
4604                let argument_span = fn_decl.inputs.first()?.span;
4605                let argument_ty = *sig.inputs().skip_binder().first()?;
4606
4607                let return_span = fn_decl.output.span();
4608                let return_ty = sig.output().skip_binder();
4609
4610                // We expect the first argument to be a reference.
4611                match argument_ty.kind() {
4612                    ty::Ref(_, _, _) => {}
4613                    _ => return None,
4614                }
4615
4616                Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4617                    argument_ty,
4618                    argument_span,
4619                    return_ty,
4620                    return_span,
4621                })
4622            }
4623            _ => {
4624                // This is case 3 from above, return type is not a reference so don't highlight
4625                // anything.
4626                None
4627            }
4628        }
4629    }
4630}
4631
4632#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for AnnotatedBorrowFnSignature<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            AnnotatedBorrowFnSignature::NamedFunction {
                arguments: __self_0,
                return_ty: __self_1,
                return_span: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "NamedFunction", "arguments", __self_0, "return_ty",
                    __self_1, "return_span", &__self_2),
            AnnotatedBorrowFnSignature::AnonymousFunction {
                argument_ty: __self_0,
                argument_span: __self_1,
                return_ty: __self_2,
                return_span: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "AnonymousFunction", "argument_ty", __self_0,
                    "argument_span", __self_1, "return_ty", __self_2,
                    "return_span", &__self_3),
            AnnotatedBorrowFnSignature::Closure {
                argument_ty: __self_0, argument_span: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Closure", "argument_ty", __self_0, "argument_span",
                    &__self_1),
        }
    }
}Debug)]
4633enum AnnotatedBorrowFnSignature<'tcx> {
4634    NamedFunction {
4635        arguments: Vec<(Ty<'tcx>, Span)>,
4636        return_ty: Ty<'tcx>,
4637        return_span: Span,
4638    },
4639    AnonymousFunction {
4640        argument_ty: Ty<'tcx>,
4641        argument_span: Span,
4642        return_ty: Ty<'tcx>,
4643        return_span: Span,
4644    },
4645    Closure {
4646        argument_ty: Ty<'tcx>,
4647        argument_span: Span,
4648    },
4649}
4650
4651impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4652    /// Annotate the provided diagnostic with information about borrow from the fn signature that
4653    /// helps explain.
4654    pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4655        match self {
4656            &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4657                diag.span_label(
4658                    argument_span,
4659                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("has type `{0}`",
                cx.get_name_for_ty(argument_ty, 0)))
    })format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
4660                );
4661
4662                cx.get_region_name_for_ty(argument_ty, 0)
4663            }
4664            &AnnotatedBorrowFnSignature::AnonymousFunction {
4665                argument_ty,
4666                argument_span,
4667                return_ty,
4668                return_span,
4669            } => {
4670                let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4671                diag.span_label(argument_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("has type `{0}`", argument_ty_name))
    })format!("has type `{argument_ty_name}`"));
4672
4673                let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4674                let types_equal = return_ty_name == argument_ty_name;
4675                diag.span_label(
4676                    return_span,
4677                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}has type `{1}`",
                if types_equal { "also " } else { "" }, return_ty_name))
    })format!(
4678                        "{}has type `{}`",
4679                        if types_equal { "also " } else { "" },
4680                        return_ty_name,
4681                    ),
4682                );
4683
4684                diag.note(
4685                    "argument and return type have the same lifetime due to lifetime elision rules",
4686                );
4687                diag.note(
4688                    "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4689                     lifetime-syntax.html#lifetime-elision>",
4690                );
4691
4692                cx.get_region_name_for_ty(return_ty, 0)
4693            }
4694            AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4695                // Region of return type and arguments checked to be the same earlier.
4696                let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4697                for (_, argument_span) in arguments {
4698                    diag.span_label(*argument_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("has lifetime `{0}`", region_name))
    })format!("has lifetime `{region_name}`"));
4699                }
4700
4701                diag.span_label(*return_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("also has lifetime `{0}`",
                region_name))
    })format!("also has lifetime `{region_name}`",));
4702
4703                diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use data from the highlighted arguments which match the `{0}` lifetime of the return type",
                region_name))
    })format!(
4704                    "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4705                     the return type",
4706                ));
4707
4708                region_name
4709            }
4710        }
4711    }
4712}
4713
4714/// Detect whether one of the provided spans is a statement nested within the top-most visited expr
4715struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4716
4717impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4718    type Result = ControlFlow<()>;
4719    fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4720        match s.kind {
4721            hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4722            _ => ControlFlow::Continue(()),
4723        }
4724    }
4725}
4726
4727/// Look for `break` expressions within any arbitrary expressions. We'll do this to infer
4728/// whether this is a case where the moved value would affect the exit of a loop, making it
4729/// unsuitable for a `.clone()` suggestion.
4730struct BreakFinder {
4731    found_breaks: Vec<(hir::Destination, Span)>,
4732    found_continues: Vec<(hir::Destination, Span)>,
4733}
4734impl<'hir> Visitor<'hir> for BreakFinder {
4735    fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4736        match ex.kind {
4737            hir::ExprKind::Break(destination, _)
4738                if !ex.span.is_desugaring(DesugaringKind::ForLoop) =>
4739            {
4740                self.found_breaks.push((destination, ex.span));
4741            }
4742            hir::ExprKind::Continue(destination) => {
4743                self.found_continues.push((destination, ex.span));
4744            }
4745            _ => {}
4746        }
4747        hir::intravisit::walk_expr(self, ex);
4748    }
4749}
4750
4751/// Given a set of spans representing statements initializing the relevant binding, visit all the
4752/// function expressions looking for branching code paths that *do not* initialize the binding.
4753struct ConditionVisitor<'tcx> {
4754    tcx: TyCtxt<'tcx>,
4755    spans: Vec<Span>,
4756    name: String,
4757    errors: Vec<ConditionError>,
4758}
4759
4760struct ConditionError {
4761    span: Span,
4762    label: String,
4763    kind: ConditionErrorKind,
4764}
4765
4766impl ConditionError {
4767    fn new(span: Span, kind: ConditionErrorKind, label: String) -> Self {
4768        Self { span, label, kind }
4769    }
4770}
4771
4772#[derive(#[automatically_derived]
impl ::core::clone::Clone for ConditionErrorKind {
    #[inline]
    fn clone(&self) -> ConditionErrorKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ConditionErrorKind { }Copy)]
4773enum ConditionErrorKind {
4774    ConditionValue,
4775    Other,
4776}
4777
4778impl ConditionErrorKind {
4779    fn describes_condition_value(self) -> bool {
4780        #[allow(non_exhaustive_omitted_patterns)] match self {
    Self::ConditionValue => true,
    _ => false,
}matches!(self, Self::ConditionValue)
4781    }
4782}
4783
4784impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4785    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4786        match ex.kind {
4787            hir::ExprKind::If(cond, body, None) => {
4788                // `if` expressions with no `else` that initialize the binding might be missing an
4789                // `else` arm.
4790                if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4791                    self.errors.push(ConditionError::new(
4792                        cond.span,
4793                        ConditionErrorKind::ConditionValue,
4794                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this `if` condition is `false`, {0} is not initialized",
                self.name))
    })format!(
4795                            "if this `if` condition is `false`, {} is not initialized",
4796                            self.name,
4797                        ),
4798                    ));
4799                    self.errors.push(ConditionError::new(
4800                        ex.span.shrink_to_hi(),
4801                        ConditionErrorKind::Other,
4802                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an `else` arm might be missing here, initializing {0}",
                self.name))
    })format!("an `else` arm might be missing here, initializing {}", self.name),
4803                    ));
4804                }
4805            }
4806            hir::ExprKind::If(cond, body, Some(other)) => {
4807                // `if` expressions where the binding is only initialized in one of the two arms
4808                // might be missing a binding initialization.
4809                let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4810                let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4811                match (a, b) {
4812                    (true, true) | (false, false) => {}
4813                    (true, false) => {
4814                        if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4815                            self.errors.push(ConditionError::new(
4816                                cond.span,
4817                                ConditionErrorKind::ConditionValue,
4818                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this condition isn\'t met and the `while` loop runs 0 times, {0} is not initialized",
                self.name))
    })format!(
4819                                    "if this condition isn't met and the `while` loop runs 0 \
4820                                     times, {} is not initialized",
4821                                    self.name
4822                                ),
4823                            ));
4824                        } else {
4825                            self.errors.push(ConditionError::new(
4826                                body.span.shrink_to_hi().until(other.span),
4827                                ConditionErrorKind::ConditionValue,
4828                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if the `if` condition is `false` and this `else` arm is executed, {0} is not initialized",
                self.name))
    })format!(
4829                                    "if the `if` condition is `false` and this `else` arm is \
4830                                     executed, {} is not initialized",
4831                                    self.name
4832                                ),
4833                            ));
4834                        }
4835                    }
4836                    (false, true) => {
4837                        self.errors.push(ConditionError::new(
4838                            cond.span,
4839                            ConditionErrorKind::ConditionValue,
4840                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this condition is `true`, {0} is not initialized",
                self.name))
    })format!(
4841                                "if this condition is `true`, {} is not initialized",
4842                                self.name
4843                            ),
4844                        ));
4845                    }
4846                }
4847            }
4848            hir::ExprKind::Match(e, arms, loop_desugar) => {
4849                // If the binding is initialized in one of the match arms, then the other match
4850                // arms might be missing an initialization.
4851                let results: Vec<bool> = arms
4852                    .iter()
4853                    .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4854                    .collect();
4855                if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4856                    for (arm, seen) in arms.iter().zip(results) {
4857                        if !seen {
4858                            if loop_desugar == hir::MatchSource::ForLoopDesugar {
4859                                self.errors.push(ConditionError::new(
4860                                    e.span,
4861                                    ConditionErrorKind::Other,
4862                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if the `for` loop runs 0 times, {0} is not initialized",
                self.name))
    })format!(
4863                                        "if the `for` loop runs 0 times, {} is not initialized",
4864                                        self.name
4865                                    ),
4866                                ));
4867                            } else if let Some(guard) = &arm.guard {
4868                                if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_node(arm.body.hir_id)
    {
    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. }) => true,
    _ => false,
}matches!(
4869                                    self.tcx.hir_node(arm.body.hir_id),
4870                                    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4871                                ) {
4872                                    continue;
4873                                }
4874                                self.errors.push(ConditionError::new(
4875                                    arm.pat.span.to(guard.span),
4876                                    ConditionErrorKind::ConditionValue,
4877                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this pattern and condition are matched, {0} is not initialized",
                self.name))
    })format!(
4878                                        "if this pattern and condition are matched, {} is not \
4879                                         initialized",
4880                                        self.name
4881                                    ),
4882                                ));
4883                            } else {
4884                                if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_node(arm.body.hir_id)
    {
    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. }) => true,
    _ => false,
}matches!(
4885                                    self.tcx.hir_node(arm.body.hir_id),
4886                                    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4887                                ) {
4888                                    continue;
4889                                }
4890                                self.errors.push(ConditionError::new(
4891                                    arm.pat.span,
4892                                    ConditionErrorKind::Other,
4893                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this pattern is matched, {0} is not initialized",
                self.name))
    })format!(
4894                                        "if this pattern is matched, {} is not initialized",
4895                                        self.name
4896                                    ),
4897                                ));
4898                            }
4899                        }
4900                    }
4901                }
4902            }
4903            // FIXME: should we also account for binops, particularly `&&` and `||`? `try` should
4904            // also be accounted for. For now it is fine, as if we don't find *any* relevant
4905            // branching code paths, we point at the places where the binding *is* initialized for
4906            // *some* context.
4907            _ => {}
4908        }
4909        walk_expr(self, ex);
4910    }
4911}