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_middle::bug;
19use rustc_middle::hir::nested_filter::OnlyBodies;
20use rustc_middle::mir::{
21    self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
22    FakeBorrowKind, FakeReadCause, LocalDecl, LocalInfo, LocalKind, Location, MutBorrowKind,
23    Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement, StatementKind,
24    Terminator, TerminatorKind, VarBindingForm, VarDebugInfoContents,
25};
26use rustc_middle::ty::print::PrintTraitRefExt as _;
27use rustc_middle::ty::{
28    self, PredicateKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, Upcast,
29    suggest_constraining_type_params,
30};
31use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex};
32use rustc_span::def_id::{DefId, LocalDefId};
33use rustc_span::hygiene::DesugaringKind;
34use rustc_span::{BytePos, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym};
35use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
36use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
37use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
38use rustc_trait_selection::infer::InferCtxtExt;
39use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
40use rustc_trait_selection::traits::{
41    Obligation, ObligationCause, ObligationCtxt, supertrait_def_ids,
42};
43use tracing::{debug, instrument};
44
45use super::explain_borrow::{BorrowExplanation, LaterUseKind};
46use super::{DescribePlaceOpt, RegionName, RegionNameSource, UseSpans};
47use crate::borrow_set::{BorrowData, TwoPhaseActivation};
48use crate::diagnostics::conflict_errors::StorageDeadOrDrop::LocalStorageDead;
49use crate::diagnostics::{CapturedMessageOpt, call_kind, find_all_local_uses};
50use crate::{InitializationRequiringAction, MirBorrowckCtxt, WriteKind, borrowck_errors};
51
52#[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)]
53struct MoveSite {
54    /// Index of the "move out" that we found. The `MoveData` can
55    /// then tell us where the move occurred.
56    moi: MoveOutIndex,
57
58    /// `true` if we traversed a back edge while walking from the point
59    /// of error to the move site.
60    traversed_back_edge: bool,
61}
62
63/// Which case a StorageDeadOrDrop is for.
64#[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)]
65enum StorageDeadOrDrop<'tcx> {
66    LocalStorageDead,
67    BoxedStorageDead,
68    Destructor(Ty<'tcx>),
69}
70
71impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
72    pub(crate) fn report_use_of_moved_or_uninitialized(
73        &mut self,
74        location: Location,
75        desired_action: InitializationRequiringAction,
76        (moved_place, used_place, span): (PlaceRef<'tcx>, PlaceRef<'tcx>, Span),
77        mpi: MovePathIndex,
78    ) {
79        {
    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:79",
                        "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(79u32),
                        ::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!(
80            "report_use_of_moved_or_uninitialized: location={:?} desired_action={:?} \
81             moved_place={:?} used_place={:?} span={:?} mpi={:?}",
82            location, desired_action, moved_place, used_place, span, mpi
83        );
84
85        let use_spans =
86            self.move_spans(moved_place, location).or_else(|| self.borrow_spans(span, location));
87        let span = use_spans.args_or_use();
88
89        let (move_site_vec, maybe_reinitialized_locations) = self.get_moved_indexes(location, mpi);
90        {
    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:90",
                        "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(90u32),
                        ::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!(
91            "report_use_of_moved_or_uninitialized: move_site_vec={:?} use_spans={:?}",
92            move_site_vec, use_spans
93        );
94        let move_out_indices: Vec<_> =
95            move_site_vec.iter().map(|move_site| move_site.moi).collect();
96
97        if move_out_indices.is_empty() {
98            let root_local = used_place.local;
99
100            if !self.uninitialized_error_reported.insert(root_local) {
101                {
    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:101",
                        "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(101u32),
                        ::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!(
102                    "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
103                    root_local
104                );
105                return;
106            }
107
108            let err = self.report_use_of_uninitialized(
109                mpi,
110                used_place,
111                moved_place,
112                desired_action,
113                span,
114                use_spans,
115            );
116            self.buffer_error(err);
117        } else {
118            if let Some((reported_place, _)) = self.has_move_error(&move_out_indices) {
119                if used_place.is_prefix_of(*reported_place) {
120                    {
    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:120",
                        "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(120u32),
                        ::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!(
121                        "report_use_of_moved_or_uninitialized place: error suppressed mois={:?}",
122                        move_out_indices
123                    );
124                    return;
125                }
126            }
127
128            let is_partial_move = move_site_vec.iter().any(|move_site| {
129                let move_out = self.move_data.moves[(*move_site).moi];
130                let moved_place = &self.move_data.move_paths[move_out.path].place;
131                // `*(_1)` where `_1` is a `Box` is actually a move out.
132                let is_box_move = moved_place.as_ref().projection == [ProjectionElem::Deref]
133                    && self.body.local_decls[moved_place.local].ty.is_box();
134
135                !is_box_move
136                    && used_place != moved_place.as_ref()
137                    && used_place.is_prefix_of(moved_place.as_ref())
138            });
139
140            let partial_str = if is_partial_move { "partial " } else { "" };
141            let partially_str = if is_partial_move { "partially " } else { "" };
142
143            let (on_move_message, on_move_label, on_move_notes) = if let ty::Adt(item_def, args) =
144                self.body.local_decls[moved_place.local].ty.kind()
145                && 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)
146            {
147                let this = self.infcx.tcx.item_name(item_def.did()).to_string();
148                let mut generic_args: Vec<_> = self
149                    .infcx
150                    .tcx
151                    .generics_of(item_def.did())
152                    .own_params
153                    .iter()
154                    .filter_map(|param| Some((param.name, args[param.index as usize].to_string())))
155                    .collect();
156                generic_args.push((kw::SelfUpper, this.clone()));
157
158                let args = FormatArgs { this, generic_args, .. };
159                let CustomDiagnostic { message, label, notes, parent_label: _ } =
160                    directive.eval(None, &args);
161
162                (message, label, notes)
163            } else {
164                (None, None, Vec::new())
165            };
166
167            let mut err = self.cannot_act_on_moved_value(
168                span,
169                desired_action.as_noun(),
170                partially_str,
171                self.describe_place_with_options(
172                    moved_place,
173                    DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
174                ),
175                on_move_message,
176            );
177
178            for note in on_move_notes {
179                err.note(note);
180            }
181
182            let reinit_spans = maybe_reinitialized_locations
183                .iter()
184                .take(3)
185                .map(|loc| {
186                    self.move_spans(self.move_data.move_paths[mpi].place.as_ref(), *loc)
187                        .args_or_use()
188                })
189                .collect::<Vec<Span>>();
190
191            let reinits = maybe_reinitialized_locations.len();
192            if reinits == 1 {
193                err.span_label(reinit_spans[0], "this reinitialization might get skipped");
194            } else if reinits > 1 {
195                err.span_note(
196                    MultiSpan::from_spans(reinit_spans),
197                    if reinits <= 3 {
198                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("these {0} reinitializations might get skipped",
                reinits))
    })format!("these {reinits} reinitializations might get skipped")
199                    } else {
200                        ::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!(
201                            "these 3 reinitializations and {} other{} might get skipped",
202                            reinits - 3,
203                            if reinits == 4 { "" } else { "s" }
204                        )
205                    },
206                );
207            }
208
209            let closure = self.add_moved_or_invoked_closure_note(location, used_place, &mut err);
210
211            let mut is_loop_move = false;
212            let mut seen_spans = FxIndexSet::default();
213
214            for move_site in &move_site_vec {
215                let move_out = self.move_data.moves[(*move_site).moi];
216                let moved_place = &self.move_data.move_paths[move_out.path].place;
217
218                let move_spans = self.move_spans(moved_place.as_ref(), move_out.source);
219                let move_span = move_spans.args_or_use();
220
221                let is_move_msg = move_spans.for_closure();
222
223                let is_loop_message = location == move_out.source || move_site.traversed_back_edge;
224
225                if location == move_out.source {
226                    is_loop_move = true;
227                }
228
229                let mut has_suggest_reborrow = false;
230                if !seen_spans.contains(&move_span) {
231                    self.suggest_ref_or_clone(
232                        mpi,
233                        &mut err,
234                        move_spans,
235                        moved_place.as_ref(),
236                        &mut has_suggest_reborrow,
237                        closure,
238                    );
239
240                    let msg_opt = CapturedMessageOpt {
241                        is_partial_move,
242                        is_loop_message,
243                        is_move_msg,
244                        is_loop_move,
245                        has_suggest_reborrow,
246                        maybe_reinitialized_locations_is_empty: maybe_reinitialized_locations
247                            .is_empty(),
248                    };
249                    self.explain_captures(
250                        &mut err,
251                        span,
252                        move_span,
253                        move_spans,
254                        *moved_place,
255                        msg_opt,
256                    );
257                }
258                seen_spans.insert(move_span);
259            }
260
261            use_spans.var_path_only_subdiag(&mut err, desired_action);
262
263            if !is_loop_move {
264                err.span_label(
265                    span,
266                    ::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!(
267                        "value {} here after {partial_str}move",
268                        desired_action.as_verb_in_past_tense(),
269                    ),
270                );
271            }
272
273            let ty = used_place.ty(self.body, self.infcx.tcx).ty;
274            let needs_note = match ty.kind() {
275                ty::Closure(id, _) => {
276                    self.infcx.tcx.closure_kind_origin(id.expect_local()).is_none()
277                }
278                _ => true,
279            };
280
281            let mpi = self.move_data.moves[move_out_indices[0]].path;
282            let place = &self.move_data.move_paths[mpi].place;
283            let ty = place.ty(self.body, self.infcx.tcx).ty;
284
285            if self.infcx.param_env.caller_bounds().iter().any(|c| {
286                c.as_trait_clause().is_some_and(|pred| {
287                    pred.skip_binder().self_ty() == ty && self.infcx.tcx.is_fn_trait(pred.def_id())
288                })
289            }) {
290                // Suppress the next suggestion since we don't want to put more bounds onto
291                // something that already has `Fn`-like bounds (or is a closure), so we can't
292                // restrict anyways.
293            } else {
294                let copy_did = self.infcx.tcx.require_lang_item(LangItem::Copy, span);
295                self.suggest_adding_bounds(&mut err, ty, copy_did, span);
296            }
297
298            let opt_name = self.describe_place_with_options(
299                place.as_ref(),
300                DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
301            );
302            let note_msg = match opt_name {
303                Some(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"),
304                None => "value".to_owned(),
305            };
306            if needs_note {
307                if let Some(local) = place.as_local() {
308                    let span = self.body.local_decls[local].source_info.span;
309                    if let Some(on_move_label) = on_move_label {
310                        err.span_label(span, on_move_label);
311                    } else {
312                        err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
313                            is_partial_move,
314                            ty,
315                            place: &note_msg,
316                            span,
317                        });
318                    }
319                } else {
320                    err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Note {
321                        is_partial_move,
322                        ty,
323                        place: &note_msg,
324                    });
325                };
326            }
327
328            if let UseSpans::FnSelfUse {
329                kind: CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. },
330                ..
331            } = use_spans
332            {
333                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!(
334                    "{} occurs due to deref coercion to `{deref_target_ty}`",
335                    desired_action.as_noun(),
336                ));
337
338                // Check first whether the source is accessible (issue #87060)
339                if let Some(deref_target_span) = deref_target_span
340                    && self.infcx.tcx.sess.source_map().is_span_accessible(deref_target_span)
341                {
342                    err.span_note(deref_target_span, "deref defined here");
343                }
344            }
345
346            self.buffer_move_error(move_out_indices, (used_place, err));
347        }
348    }
349
350    fn suggest_ref_or_clone(
351        &self,
352        mpi: MovePathIndex,
353        err: &mut Diag<'infcx>,
354        move_spans: UseSpans<'tcx>,
355        moved_place: PlaceRef<'tcx>,
356        has_suggest_reborrow: &mut bool,
357        moved_or_invoked_closure: bool,
358    ) {
359        let move_span = match move_spans {
360            UseSpans::ClosureUse { capture_kind_span, .. } => capture_kind_span,
361            _ => move_spans.args_or_use(),
362        };
363        struct ExpressionFinder<'hir> {
364            expr_span: Span,
365            expr: Option<&'hir hir::Expr<'hir>>,
366            pat: Option<&'hir hir::Pat<'hir>>,
367            parent_pat: Option<&'hir hir::Pat<'hir>>,
368            tcx: TyCtxt<'hir>,
369        }
370        impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
371            type NestedFilter = OnlyBodies;
372
373            fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
374                self.tcx
375            }
376
377            fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
378                if e.span == self.expr_span {
379                    self.expr = Some(e);
380                }
381                hir::intravisit::walk_expr(self, e);
382            }
383            fn visit_pat(&mut self, p: &'hir hir::Pat<'hir>) {
384                if p.span == self.expr_span {
385                    self.pat = Some(p);
386                }
387                if let hir::PatKind::Binding(hir::BindingMode::NONE, _, i, sub) = p.kind {
388                    if i.span == self.expr_span || p.span == self.expr_span {
389                        self.pat = Some(p);
390                    }
391                    // Check if we are in a situation of `ident @ ident` where we want to suggest
392                    // `ref ident @ ref ident` or `ref ident @ Struct { ref ident }`.
393                    if let Some(subpat) = sub
394                        && self.pat.is_none()
395                    {
396                        self.visit_pat(subpat);
397                        if self.pat.is_some() {
398                            self.parent_pat = Some(p);
399                        }
400                        return;
401                    }
402                }
403                hir::intravisit::walk_pat(self, p);
404            }
405        }
406        let tcx = self.infcx.tcx;
407        if let Some(body) = tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
408            let expr = body.value;
409            let place = &self.move_data.move_paths[mpi].place;
410            let span = place.as_local().map(|local| self.body.local_decls[local].source_info.span);
411            let mut finder = ExpressionFinder {
412                expr_span: move_span,
413                expr: None,
414                pat: None,
415                parent_pat: None,
416                tcx,
417            };
418            finder.visit_expr(expr);
419            if let Some(span) = span
420                && let Some(expr) = finder.expr
421            {
422                for (_, expr) in tcx.hir_parent_iter(expr.hir_id) {
423                    if let hir::Node::Expr(expr) = expr {
424                        if expr.span.contains(span) {
425                            // If the let binding occurs within the same loop, then that
426                            // loop isn't relevant, like in the following, the outermost `loop`
427                            // doesn't play into `x` being moved.
428                            // ```
429                            // loop {
430                            //     let x = String::new();
431                            //     loop {
432                            //         foo(x);
433                            //     }
434                            // }
435                            // ```
436                            break;
437                        }
438                        if let hir::ExprKind::Loop(.., loop_span) = expr.kind {
439                            err.span_label(loop_span, "inside of this loop");
440                        }
441                    }
442                }
443                let typeck = self.infcx.tcx.typeck(self.mir_def_id());
444                let parent = self.infcx.tcx.parent_hir_node(expr.hir_id);
445                let (def_id, args, offset) = if let hir::Node::Expr(parent_expr) = parent
446                    && let hir::ExprKind::MethodCall(_, _, args, _) = parent_expr.kind
447                {
448                    let def_id = typeck.type_dependent_def_id(parent_expr.hir_id);
449                    (def_id, args, 1)
450                } else if let hir::Node::Expr(parent_expr) = parent
451                    && let hir::ExprKind::Call(call, args) = parent_expr.kind
452                    && let ty::FnDef(def_id, _) = typeck.node_type(call.hir_id).kind()
453                {
454                    (Some(*def_id), args, 0)
455                } else {
456                    (None, &[][..], 0)
457                };
458                let ty = place.ty(self.body, self.infcx.tcx).ty;
459
460                let mut can_suggest_clone = true;
461                if let Some(def_id) = def_id
462                    && let Some(pos) = args.iter().position(|arg| arg.hir_id == expr.hir_id)
463                {
464                    // The move occurred as one of the arguments to a function call. Is that
465                    // argument generic? `def_id` can't be a closure here, so using `fn_sig` is fine
466                    let arg_param = if self.infcx.tcx.def_kind(def_id).is_fn_like()
467                        && let sig =
468                            self.infcx.tcx.fn_sig(def_id).instantiate_identity().skip_binder()
469                        && let Some(arg_ty) = sig.inputs().get(pos + offset)
470                        && let ty::Param(arg_param) = arg_ty.kind()
471                    {
472                        Some(arg_param)
473                    } else {
474                        None
475                    };
476
477                    // If the moved value is a mut reference, it is used in a
478                    // generic function and it's type is a generic param, it can be
479                    // reborrowed to avoid moving.
480                    // for example:
481                    // struct Y(u32);
482                    // x's type is '& mut Y' and it is used in `fn generic<T>(x: T) {}`.
483                    if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind()
484                        && arg_param.is_some()
485                    {
486                        *has_suggest_reborrow = true;
487                        self.suggest_reborrow(err, expr.span, moved_place);
488                        return;
489                    }
490
491                    // If the moved place is used generically by the callee and a reference to it
492                    // would still satisfy any bounds on its type, suggest borrowing.
493                    if let Some(&param) = arg_param
494                        && let hir::Node::Expr(call_expr) = parent
495                        && let Some(ref_mutability) = self.suggest_borrow_generic_arg(
496                            err,
497                            typeck,
498                            call_expr,
499                            def_id,
500                            param,
501                            moved_place,
502                            pos + offset,
503                            ty,
504                            expr.span,
505                        )
506                    {
507                        can_suggest_clone = ref_mutability.is_mut();
508                    } else if let Some(local_def_id) = def_id.as_local()
509                        && let node = self.infcx.tcx.hir_node_by_def_id(local_def_id)
510                        && let Some(fn_decl) = node.fn_decl()
511                        && let Some(ident) = node.ident()
512                        && let Some(arg) = fn_decl.inputs.get(pos + offset)
513                    {
514                        // If we can't suggest borrowing in the call, but the function definition
515                        // is local, instead offer changing the function to borrow that argument.
516                        let mut span: MultiSpan = arg.span.into();
517                        span.push_span_label(
518                            arg.span,
519                            "this parameter takes ownership of the value".to_string(),
520                        );
521                        let descr = match node.fn_kind() {
522                            Some(hir::intravisit::FnKind::ItemFn(..)) | None => "function",
523                            Some(hir::intravisit::FnKind::Method(..)) => "method",
524                            Some(hir::intravisit::FnKind::Closure) => "closure",
525                        };
526                        span.push_span_label(ident.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in this {0}", descr))
    })format!("in this {descr}"));
527                        err.span_note(
528                            span,
529                            ::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!(
530                                "consider changing this parameter type in {descr} `{ident}` to \
531                                 borrow instead if owning the value isn't necessary",
532                            ),
533                        );
534                    }
535                }
536                if let hir::Node::Expr(parent_expr) = parent
537                    && let hir::ExprKind::Call(call_expr, _) = parent_expr.kind
538                    && let hir::ExprKind::Path(qpath) = call_expr.kind
539                    && tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
540                {
541                    // Do not suggest `.clone()` in a `for` loop, we already suggest borrowing.
542                } else if let UseSpans::FnSelfUse { kind: CallKind::Normal { .. }, .. } = move_spans
543                {
544                    // We already suggest cloning for these cases in `explain_captures`.
545                } else if moved_or_invoked_closure {
546                    // Do not suggest `closure.clone()()`.
547                } else if let UseSpans::ClosureUse {
548                    closure_kind:
549                        ClosureKind::Coroutine(CoroutineKind::Desugared(_, CoroutineSource::Block)),
550                    ..
551                } = move_spans
552                    && can_suggest_clone
553                {
554                    self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans));
555                } else if self.suggest_hoisting_call_outside_loop(err, expr) && can_suggest_clone {
556                    // The place where the type moves would be misleading to suggest clone.
557                    // #121466
558                    self.suggest_cloning(err, place.as_ref(), ty, expr, Some(move_spans));
559                }
560            }
561
562            self.suggest_ref_for_dbg_args(expr, place, move_span, err);
563
564            // it's useless to suggest inserting `ref` when the span don't comes from local code
565            if let Some(pat) = finder.pat
566                && !move_span.is_dummy()
567                && !self.infcx.tcx.sess.source_map().is_imported(move_span)
568            {
569                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())];
570                if let Some(pat) = finder.parent_pat {
571                    sugg.insert(0, (pat.span.shrink_to_lo(), "ref ".to_string()));
572                }
573                err.multipart_suggestion(
574                    "borrow this binding in the pattern to avoid moving the value",
575                    sugg,
576                    Applicability::MachineApplicable,
577                );
578            }
579        }
580    }
581
582    // for dbg!(x) which may take ownership, suggest dbg!(&x) instead
583    fn suggest_ref_for_dbg_args(
584        &self,
585        body: &hir::Expr<'_>,
586        place: &Place<'tcx>,
587        move_span: Span,
588        err: &mut Diag<'infcx>,
589    ) {
590        let var_info = self.body.var_debug_info.iter().find(|info| match info.value {
591            VarDebugInfoContents::Place(ref p) => p == place,
592            _ => false,
593        });
594        let Some(var_info) = var_info else { return };
595        let arg_name = var_info.name;
596        struct MatchArgFinder<'tcx> {
597            tcx: TyCtxt<'tcx>,
598            move_span: Span,
599            arg_name: Symbol,
600            match_arg_span: Option<Span> = None,
601        }
602        impl Visitor<'_> for MatchArgFinder<'_> {
603            fn visit_expr(&mut self, e: &hir::Expr<'_>) {
604                // dbg! is expanded into a match pattern, we need to find the right argument span
605                if let hir::ExprKind::Match(scrutinee, ..) = &e.kind
606                    && let hir::ExprKind::Tup(args) = scrutinee.kind
607                    && e.span.macro_backtrace().any(|expn| {
608                        expn.macro_def_id.is_some_and(|macro_def_id| {
609                            self.tcx.is_diagnostic_item(sym::dbg_macro, macro_def_id)
610                        })
611                    })
612                {
613                    for arg in args {
614                        if let hir::ExprKind::Path(hir::QPath::Resolved(
615                            _,
616                            path @ Path { segments: [seg], .. },
617                        )) = &arg.kind
618                            && seg.ident.name == self.arg_name
619                            && self.move_span.source_equal(arg.span)
620                        {
621                            self.match_arg_span = Some(path.span);
622                            return;
623                        }
624                    }
625                }
626                hir::intravisit::walk_expr(self, e);
627            }
628        }
629
630        let mut finder = MatchArgFinder { tcx: self.infcx.tcx, move_span, arg_name, .. };
631        finder.visit_expr(body);
632        if let Some(macro_arg_span) = finder.match_arg_span {
633            err.span_suggestion_verbose(
634                macro_arg_span.shrink_to_lo(),
635                "consider borrowing instead of transferring ownership",
636                "&",
637                Applicability::MachineApplicable,
638            );
639        }
640    }
641
642    pub(crate) fn suggest_reborrow(
643        &self,
644        err: &mut Diag<'infcx>,
645        span: Span,
646        moved_place: PlaceRef<'tcx>,
647    ) {
648        err.span_suggestion_verbose(
649            span.shrink_to_lo(),
650            ::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!(
651                "consider creating a fresh reborrow of {} here",
652                self.describe_place(moved_place)
653                    .map(|n| format!("`{n}`"))
654                    .unwrap_or_else(|| "the mutable reference".to_string()),
655            ),
656            "&mut *",
657            Applicability::MachineApplicable,
658        );
659    }
660
661    /// If a place is used after being moved as an argument to a function, the function is generic
662    /// in that argument, and a reference to the argument's type would still satisfy the function's
663    /// bounds, suggest borrowing. This covers, e.g., borrowing an `impl Fn()` argument being passed
664    /// in an `impl FnOnce()` position.
665    /// Returns `Some(mutability)` when suggesting to borrow with mutability `mutability`, or `None`
666    /// if no suggestion is made.
667    fn suggest_borrow_generic_arg(
668        &self,
669        err: &mut Diag<'_>,
670        typeck: &ty::TypeckResults<'tcx>,
671        call_expr: &hir::Expr<'tcx>,
672        callee_did: DefId,
673        param: ty::ParamTy,
674        moved_place: PlaceRef<'tcx>,
675        moved_arg_pos: usize,
676        moved_arg_ty: Ty<'tcx>,
677        place_span: Span,
678    ) -> Option<ty::Mutability> {
679        let tcx = self.infcx.tcx;
680        let sig = tcx.fn_sig(callee_did).instantiate_identity().skip_binder();
681        let clauses = tcx.predicates_of(callee_did);
682
683        let generic_args = match call_expr.kind {
684            // For method calls, generic arguments are attached to the call node.
685            hir::ExprKind::MethodCall(..) => typeck.node_args_opt(call_expr.hir_id)?,
686            // For normal calls, generic arguments are in the callee's type.
687            // This diagnostic is only run for `FnDef` callees.
688            hir::ExprKind::Call(callee, _)
689                if let &ty::FnDef(_, args) = typeck.node_type(callee.hir_id).kind() =>
690            {
691                args
692            }
693            _ => return None,
694        };
695
696        // First, is there at least one method on one of `param`'s trait bounds?
697        // This keeps us from suggesting borrowing the argument to `mem::drop`, e.g.
698        if !clauses.instantiate_identity(tcx).predicates.iter().any(|clause| {
699            clause.as_trait_clause().is_some_and(|tc| {
700                tc.self_ty().skip_binder().is_param(param.index)
701                    && tc.polarity() == ty::PredicatePolarity::Positive
702                    && supertrait_def_ids(tcx, tc.def_id())
703                        .flat_map(|trait_did| tcx.associated_items(trait_did).in_definition_order())
704                        .any(|item| item.is_method())
705            })
706        }) {
707            return None;
708        }
709
710        // Try borrowing a shared reference first, then mutably.
711        if let Some(mutbl) = [ty::Mutability::Not, ty::Mutability::Mut].into_iter().find(|&mutbl| {
712            let re = self.infcx.tcx.lifetimes.re_erased;
713            let ref_ty = Ty::new_ref(self.infcx.tcx, re, moved_arg_ty, mutbl);
714
715            // Ensure that substituting `ref_ty` in the callee's signature doesn't break
716            // other inputs or the return type.
717            let new_args = tcx.mk_args_from_iter(generic_args.iter().enumerate().map(
718                |(i, arg)| {
719                    if i == param.index as usize { ref_ty.into() } else { arg }
720                },
721            ));
722            let can_subst = |ty: Ty<'tcx>| {
723                // Normalize before comparing to see through type aliases and projections.
724                let old_ty = ty::EarlyBinder::bind(ty).instantiate(tcx, generic_args);
725                let new_ty = ty::EarlyBinder::bind(ty).instantiate(tcx, new_args);
726                if let Ok(old_ty) = tcx.try_normalize_erasing_regions(
727                    self.infcx.typing_env(self.infcx.param_env),
728                    old_ty,
729                ) && let Ok(new_ty) = tcx.try_normalize_erasing_regions(
730                    self.infcx.typing_env(self.infcx.param_env),
731                    new_ty,
732                ) {
733                    old_ty == new_ty
734                } else {
735                    false
736                }
737            };
738            if !can_subst(sig.output())
739                || sig
740                    .inputs()
741                    .iter()
742                    .enumerate()
743                    .any(|(i, &input_ty)| i != moved_arg_pos && !can_subst(input_ty))
744            {
745                return false;
746            }
747
748            // Test the callee's predicates, substituting in `ref_ty` for the moved argument type.
749            clauses.instantiate(tcx, new_args).predicates.iter().all(|clause| {
750                // Normalize before testing to see through type aliases and projections.
751                let normalized = tcx
752                    .try_normalize_erasing_regions(
753                        self.infcx.typing_env(self.infcx.param_env),
754                        *clause,
755                    )
756                    .unwrap_or_else(|_| clause.skip_norm_wip());
757                self.infcx.predicate_must_hold_modulo_regions(&Obligation::new(
758                    tcx,
759                    ObligationCause::dummy(),
760                    self.infcx.param_env,
761                    normalized,
762                ))
763            })
764        }) {
765            let place_desc = if let Some(desc) = self.describe_place(moved_place) {
766                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", desc))
    })format!("`{desc}`")
767            } else {
768                "here".to_owned()
769            };
770            err.span_suggestion_verbose(
771                place_span.shrink_to_lo(),
772                ::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()),
773                mutbl.ref_prefix_str(),
774                Applicability::MaybeIncorrect,
775            );
776            Some(mutbl)
777        } else {
778            None
779        }
780    }
781
782    fn report_use_of_uninitialized(
783        &self,
784        mpi: MovePathIndex,
785        used_place: PlaceRef<'tcx>,
786        moved_place: PlaceRef<'tcx>,
787        desired_action: InitializationRequiringAction,
788        span: Span,
789        use_spans: UseSpans<'tcx>,
790    ) -> Diag<'infcx> {
791        // We need all statements in the body where the binding was assigned to later find all
792        // the branching code paths where the binding *wasn't* assigned to.
793        let inits = &self.move_data.init_path_map[mpi];
794        let move_path = &self.move_data.move_paths[mpi];
795        let decl_span = self.body.local_decls[move_path.place.local].source_info.span;
796        let mut spans_set = FxIndexSet::default();
797        for init_idx in inits {
798            let init = &self.move_data.inits[*init_idx];
799            let span = init.span(self.body);
800            if !span.is_dummy() {
801                spans_set.insert(span);
802            }
803        }
804        let spans: Vec<_> = spans_set.into_iter().collect();
805
806        let (name, desc) = match self.describe_place_with_options(
807            moved_place,
808            DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
809        ) {
810            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}` ")),
811            None => ("the variable".to_string(), String::new()),
812        };
813        let path = match self.describe_place_with_options(
814            used_place,
815            DescribePlaceOpt { including_downcast: true, including_tuple_field: true },
816        ) {
817            Some(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"),
818            None => "value".to_string(),
819        };
820
821        // We use the statements were the binding was initialized, and inspect the HIR to look
822        // for the branching codepaths that aren't covered, to point at them.
823        let tcx = self.infcx.tcx;
824        let body = tcx.hir_body_owned_by(self.mir_def_id());
825        let mut visitor = ConditionVisitor { tcx, spans, name, errors: ::alloc::vec::Vec::new()vec![] };
826        visitor.visit_body(&body);
827        let spans = visitor.spans;
828
829        let mut show_assign_sugg = false;
830        let isnt_initialized = if let InitializationRequiringAction::PartialAssignment
831        | InitializationRequiringAction::Assignment = desired_action
832        {
833            // The same error is emitted for bindings that are *sometimes* initialized and the ones
834            // that are *partially* initialized by assigning to a field of an uninitialized
835            // binding. We differentiate between them for more accurate wording here.
836            "isn't fully initialized"
837        } else if !spans.iter().any(|i| {
838            // We filter these to avoid misleading wording in cases like the following,
839            // where `x` has an `init`, but it is in the same place we're looking at:
840            // ```
841            // let x;
842            // x += 1;
843            // ```
844            !i.contains(span)
845            // We filter these to avoid incorrect main message on `match-cfg-fake-edges.rs`
846            && !visitor
847                .errors
848                .iter()
849                .map(|(sp, _)| *sp)
850                .any(|sp| span < sp && !sp.contains(span))
851        }) {
852            show_assign_sugg = true;
853            "isn't initialized"
854        } else {
855            "is possibly-uninitialized"
856        };
857
858        let used = desired_action.as_general_verb_in_past_tense();
859        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!(
860            self.dcx(),
861            span,
862            E0381,
863            "{used} binding {desc}{isnt_initialized}"
864        );
865        use_spans.var_path_only_subdiag(&mut err, desired_action);
866
867        if let InitializationRequiringAction::PartialAssignment
868        | InitializationRequiringAction::Assignment = desired_action
869        {
870            err.help(
871                "partial initialization isn't supported, fully initialize the binding with a \
872                 default value and mutate it, or use `std::mem::MaybeUninit`",
873            );
874        }
875        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}"));
876
877        let mut shown = false;
878        for (sp, label) in visitor.errors {
879            if sp < span && !sp.overlaps(span) {
880                // When we have a case like `match-cfg-fake-edges.rs`, we don't want to mention
881                // match arms coming after the primary span because they aren't relevant:
882                // ```
883                // let x;
884                // match y {
885                //     _ if { x = 2; true } => {}
886                //     _ if {
887                //         x; //~ ERROR
888                //         false
889                //     } => {}
890                //     _ => {} // We don't want to point to this.
891                // };
892                // ```
893                err.span_label(sp, label);
894                shown = true;
895            }
896        }
897        if !shown {
898            for sp in &spans {
899                if *sp < span && !sp.overlaps(span) {
900                    err.span_label(*sp, "binding initialized here in some conditions");
901                }
902            }
903        }
904
905        err.span_label(decl_span, "binding declared here but left uninitialized");
906        if show_assign_sugg {
907            struct LetVisitor {
908                decl_span: Span,
909                sugg: Option<(Span, bool)>,
910            }
911
912            impl<'v> Visitor<'v> for LetVisitor {
913                fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) {
914                    if self.sugg.is_some() {
915                        return;
916                    }
917
918                    // FIXME: We make sure that this is a normal top-level binding,
919                    // but we could suggest `todo!()` for all uninitialized bindings in the pattern
920                    if let hir::StmtKind::Let(hir::LetStmt { span, ty, init: None, pat, .. }) =
921                        &ex.kind
922                        && let hir::PatKind::Binding(binding_mode, ..) = pat.kind
923                        && span.contains(self.decl_span)
924                    {
925                        // Insert after the whole binding pattern so suggestions stay valid for
926                        // bindings with `@` subpatterns like `ref mut x @ v`.
927                        let strip_ref = #[allow(non_exhaustive_omitted_patterns)] match binding_mode.0 {
    hir::ByRef::Yes(..) => true,
    _ => false,
}matches!(binding_mode.0, hir::ByRef::Yes(..));
928                        self.sugg =
929                            ty.map_or(Some((pat.span, strip_ref)), |ty| Some((ty.span, strip_ref)));
930                    }
931                    hir::intravisit::walk_stmt(self, ex);
932                }
933            }
934
935            let mut visitor = LetVisitor { decl_span, sugg: None };
936            visitor.visit_body(&body);
937            if let Some((span, strip_ref)) = visitor.sugg {
938                self.suggest_assign_value(&mut err, moved_place, span, strip_ref);
939            }
940        }
941        err
942    }
943
944    fn suggest_assign_value(
945        &self,
946        err: &mut Diag<'_>,
947        moved_place: PlaceRef<'tcx>,
948        sugg_span: Span,
949        strip_ref: bool,
950    ) {
951        let mut ty = moved_place.ty(self.body, self.infcx.tcx).ty;
952        if strip_ref && let ty::Ref(_, inner, _) = ty.kind() {
953            ty = *inner;
954        }
955        {
    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:955",
                        "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(955u32),
                        ::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());
956
957        let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.infcx.param_env, ty)
958        else {
959            return;
960        };
961
962        err.span_suggestion_verbose(
963            sugg_span.shrink_to_hi(),
964            "consider assigning a value",
965            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" = {0}", assign_value))
    })format!(" = {assign_value}"),
966            Applicability::MaybeIncorrect,
967        );
968    }
969
970    /// In a move error that occurs on a call within a loop, we try to identify cases where cloning
971    /// the value would lead to a logic error. We infer these cases by seeing if the moved value is
972    /// part of the logic to break the loop, either through an explicit `break` or if the expression
973    /// is part of a `while let`.
974    fn suggest_hoisting_call_outside_loop(&self, err: &mut Diag<'_>, expr: &hir::Expr<'_>) -> bool {
975        let tcx = self.infcx.tcx;
976        let mut can_suggest_clone = true;
977
978        // If the moved value is a locally declared binding, we'll look upwards on the expression
979        // tree until the scope where it is defined, and no further, as suggesting to move the
980        // expression beyond that point would be illogical.
981        let local_hir_id = if let hir::ExprKind::Path(hir::QPath::Resolved(
982            _,
983            hir::Path { res: hir::def::Res::Local(local_hir_id), .. },
984        )) = expr.kind
985        {
986            Some(local_hir_id)
987        } else {
988            // This case would be if the moved value comes from an argument binding, we'll just
989            // look within the entire item, that's fine.
990            None
991        };
992
993        /// This will allow us to look for a specific `HirId`, in our case `local_hir_id` where the
994        /// binding was declared, within any other expression. We'll use it to search for the
995        /// binding declaration within every scope we inspect.
996        struct Finder {
997            hir_id: hir::HirId,
998        }
999        impl<'hir> Visitor<'hir> for Finder {
1000            type Result = ControlFlow<()>;
1001            fn visit_pat(&mut self, pat: &'hir hir::Pat<'hir>) -> Self::Result {
1002                if pat.hir_id == self.hir_id {
1003                    return ControlFlow::Break(());
1004                }
1005                hir::intravisit::walk_pat(self, pat)
1006            }
1007            fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) -> Self::Result {
1008                if ex.hir_id == self.hir_id {
1009                    return ControlFlow::Break(());
1010                }
1011                hir::intravisit::walk_expr(self, ex)
1012            }
1013        }
1014        // The immediate HIR parent of the moved expression. We'll look for it to be a call.
1015        let mut parent = None;
1016        // The top-most loop where the moved expression could be moved to a new binding.
1017        let mut outer_most_loop: Option<&hir::Expr<'_>> = None;
1018        for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
1019            let e = match node {
1020                hir::Node::Expr(e) => e,
1021                hir::Node::LetStmt(hir::LetStmt { els: Some(els), .. }) => {
1022                    let mut finder = BreakFinder { found_breaks: ::alloc::vec::Vec::new()vec![], found_continues: ::alloc::vec::Vec::new()vec![] };
1023                    finder.visit_block(els);
1024                    if !finder.found_breaks.is_empty() {
1025                        // Don't suggest clone as it could be will likely end in an infinite
1026                        // loop.
1027                        // let Some(_) = foo(non_copy.clone()) else { break; }
1028                        // ---                       ^^^^^^^^         -----
1029                        can_suggest_clone = false;
1030                    }
1031                    continue;
1032                }
1033                _ => continue,
1034            };
1035            if let Some(&hir_id) = local_hir_id {
1036                if (Finder { hir_id }).visit_expr(e).is_break() {
1037                    // The current scope includes the declaration of the binding we're accessing, we
1038                    // can't look up any further for loops.
1039                    break;
1040                }
1041            }
1042            if parent.is_none() {
1043                parent = Some(e);
1044            }
1045            match e.kind {
1046                hir::ExprKind::Let(_) => {
1047                    match tcx.parent_hir_node(e.hir_id) {
1048                        hir::Node::Expr(hir::Expr {
1049                            kind: hir::ExprKind::If(cond, ..), ..
1050                        }) => {
1051                            if (Finder { hir_id: expr.hir_id }).visit_expr(cond).is_break() {
1052                                // The expression where the move error happened is in a `while let`
1053                                // condition Don't suggest clone as it will likely end in an
1054                                // infinite loop.
1055                                // while let Some(_) = foo(non_copy.clone()) { }
1056                                // ---------                       ^^^^^^^^
1057                                can_suggest_clone = false;
1058                            }
1059                        }
1060                        _ => {}
1061                    }
1062                }
1063                hir::ExprKind::Loop(..) => {
1064                    outer_most_loop = Some(e);
1065                }
1066                _ => {}
1067            }
1068        }
1069        let loop_count: usize = tcx
1070            .hir_parent_iter(expr.hir_id)
1071            .map(|(_, node)| match node {
1072                hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Loop(..), .. }) => 1,
1073                _ => 0,
1074            })
1075            .sum();
1076
1077        let sm = tcx.sess.source_map();
1078        if let Some(in_loop) = outer_most_loop {
1079            let mut finder = BreakFinder { found_breaks: ::alloc::vec::Vec::new()vec![], found_continues: ::alloc::vec::Vec::new()vec![] };
1080            finder.visit_expr(in_loop);
1081            // All of the spans for `break` and `continue` expressions.
1082            let spans = finder
1083                .found_breaks
1084                .iter()
1085                .chain(finder.found_continues.iter())
1086                .map(|(_, span)| *span)
1087                .filter(|span| {
1088                    !#[allow(non_exhaustive_omitted_patterns)] match span.desugaring_kind() {
    Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => true,
    _ => false,
}matches!(
1089                        span.desugaring_kind(),
1090                        Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1091                    )
1092                })
1093                .collect::<Vec<Span>>();
1094            // All of the spans for the loops above the expression with the move error.
1095            let loop_spans: Vec<_> = tcx
1096                .hir_parent_iter(expr.hir_id)
1097                .filter_map(|(_, node)| match node {
1098                    hir::Node::Expr(hir::Expr { span, kind: hir::ExprKind::Loop(..), .. }) => {
1099                        Some(*span)
1100                    }
1101                    _ => None,
1102                })
1103                .collect();
1104            // It is possible that a user written `break` or `continue` is in the wrong place. We
1105            // point them out at the user for them to make a determination. (#92531)
1106            if !spans.is_empty() && loop_count > 1 {
1107                // Getting fancy: if the spans of the loops *do not* overlap, we only use the line
1108                // number when referring to them. If there *are* overlaps (multiple loops on the
1109                // same line) then we use the more verbose span output (`file.rs:col:ll`).
1110                let mut lines: Vec<_> =
1111                    loop_spans.iter().map(|sp| sm.lookup_char_pos(sp.lo()).line).collect();
1112                lines.sort();
1113                lines.dedup();
1114                let fmt_span = |span: Span| {
1115                    if lines.len() == loop_spans.len() {
1116                        ::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)
1117                    } else {
1118                        sm.span_to_diagnostic_string(span)
1119                    }
1120                };
1121                let mut spans: MultiSpan = spans.into();
1122                // Point at all the `continue`s and explicit `break`s in the relevant loops.
1123                for (desc, elements) in [
1124                    ("`break` exits", &finder.found_breaks),
1125                    ("`continue` advances", &finder.found_continues),
1126                ] {
1127                    for (destination, sp) in elements {
1128                        if let Ok(hir_id) = destination.target_id
1129                            && let hir::Node::Expr(expr) = tcx.hir_node(hir_id)
1130                            && !#[allow(non_exhaustive_omitted_patterns)] match sp.desugaring_kind() {
    Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => true,
    _ => false,
}matches!(
1131                                sp.desugaring_kind(),
1132                                Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
1133                            )
1134                        {
1135                            spans.push_span_label(
1136                                *sp,
1137                                ::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)),
1138                            );
1139                        }
1140                    }
1141                }
1142                // Point at all the loops that are between this move and the parent item.
1143                for span in loop_spans {
1144                    spans.push_span_label(sm.guess_head_span(span), "");
1145                }
1146
1147                // note: verify that your loop breaking logic is correct
1148                //   --> $DIR/nested-loop-moved-value-wrong-continue.rs:41:17
1149                //    |
1150                // 28 |     for foo in foos {
1151                //    |     ---------------
1152                // ...
1153                // 33 |         for bar in &bars {
1154                //    |         ----------------
1155                // ...
1156                // 41 |                 continue;
1157                //    |                 ^^^^^^^^ this `continue` advances the loop at line 33
1158                err.span_note(spans, "verify that your loop breaking logic is correct");
1159            }
1160            if let Some(parent) = parent
1161                && let hir::ExprKind::MethodCall(..) | hir::ExprKind::Call(..) = parent.kind
1162            {
1163                // FIXME: We could check that the call's *parent* takes `&mut val` to make the
1164                // suggestion more targeted to the `mk_iter(val).next()` case. Maybe do that only to
1165                // check for whether to suggest `let value` or `let mut value`.
1166
1167                let span = in_loop.span;
1168                if !finder.found_breaks.is_empty()
1169                    && let Ok(value) = sm.span_to_snippet(parent.span)
1170                {
1171                    // We know with high certainty that this move would affect the early return of a
1172                    // loop, so we suggest moving the expression with the move out of the loop.
1173                    let indent = if let Some(indent) = sm.indentation_before(span) {
1174                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}", indent))
    })format!("\n{indent}")
1175                    } else {
1176                        " ".to_string()
1177                    };
1178                    err.multipart_suggestion(
1179                        "consider moving the expression out of the loop so it is only moved once",
1180                        ::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![
1181                            (span.shrink_to_lo(), format!("let mut value = {value};{indent}")),
1182                            (parent.span, "value".to_string()),
1183                        ],
1184                        Applicability::MaybeIncorrect,
1185                    );
1186                }
1187            }
1188        }
1189        can_suggest_clone
1190    }
1191
1192    /// We have `S { foo: val, ..base }`, and we suggest instead writing
1193    /// `S { foo: val, bar: base.bar.clone(), .. }` when valid.
1194    fn suggest_cloning_on_functional_record_update(
1195        &self,
1196        err: &mut Diag<'_>,
1197        ty: Ty<'tcx>,
1198        expr: &hir::Expr<'_>,
1199    ) {
1200        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1201        let hir::ExprKind::Struct(struct_qpath, fields, hir::StructTailExpr::Base(base)) =
1202            expr.kind
1203        else {
1204            return;
1205        };
1206        let hir::QPath::Resolved(_, path) = struct_qpath else { return };
1207        let hir::def::Res::Def(_, def_id) = path.res else { return };
1208        let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return };
1209        let ty::Adt(def, args) = expr_ty.kind() else { return };
1210        let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = base.kind else { return };
1211        let (hir::def::Res::Local(_)
1212        | hir::def::Res::Def(
1213            DefKind::Const { .. }
1214            | DefKind::ConstParam
1215            | DefKind::Static { .. }
1216            | DefKind::AssocConst { .. },
1217            _,
1218        )) = path.res
1219        else {
1220            return;
1221        };
1222        let Ok(base_str) = self.infcx.tcx.sess.source_map().span_to_snippet(base.span) else {
1223            return;
1224        };
1225
1226        // 1. look for the fields of type `ty`.
1227        // 2. check if they are clone and add them to suggestion
1228        // 3. check if there are any values left to `..` and remove it if not
1229        // 4. emit suggestion to clone the field directly as `bar: base.bar.clone()`
1230
1231        let mut final_field_count = fields.len();
1232        let Some(variant) = def.variants().iter().find(|variant| variant.def_id == def_id) else {
1233            // When we have an enum, look for the variant that corresponds to the variant the user
1234            // wrote.
1235            return;
1236        };
1237        let mut sugg = ::alloc::vec::Vec::new()vec![];
1238        for field in &variant.fields {
1239            // In practice unless there are more than one field with the same type, we'll be
1240            // suggesting a single field at a type, because we don't aggregate multiple borrow
1241            // checker errors involving the functional record update syntax into a single one.
1242            let field_ty = field.ty(self.infcx.tcx, args);
1243            let ident = field.ident(self.infcx.tcx);
1244            if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) {
1245                // Suggest adding field and cloning it.
1246                sugg.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}.{0}.clone()", ident,
                base_str))
    })format!("{ident}: {base_str}.{ident}.clone()"));
1247                final_field_count += 1;
1248            }
1249        }
1250        let (span, sugg) = match fields {
1251            [.., last] => (
1252                if final_field_count == variant.fields.len() {
1253                    // We'll remove the `..base` as there aren't any fields left.
1254                    last.span.shrink_to_hi().with_hi(base.span.hi())
1255                } else {
1256                    last.span.shrink_to_hi()
1257                },
1258                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", sugg.join(", ")))
    })format!(", {}", sugg.join(", ")),
1259            ),
1260            // Account for no fields in suggestion span.
1261            [] => (
1262                expr.span.with_lo(struct_qpath.span().hi()),
1263                if final_field_count == variant.fields.len() {
1264                    // We'll remove the `..base` as there aren't any fields left.
1265                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0} }}", sugg.join(", ")))
    })format!(" {{ {} }}", sugg.join(", "))
1266                } else {
1267                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0}, ..{1} }}",
                sugg.join(", "), base_str))
    })format!(" {{ {}, ..{base_str} }}", sugg.join(", "))
1268                },
1269            ),
1270        };
1271        let prefix = if !self.implements_clone(ty) {
1272            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`");
1273            if let ty::Adt(def, _) = ty.kind() {
1274                err.span_note(self.infcx.tcx.def_span(def.did()), msg);
1275            } else {
1276                err.note(msg);
1277            }
1278            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if `{0}` implemented `Clone`, you could ",
                ty))
    })format!("if `{ty}` implemented `Clone`, you could ")
1279        } else {
1280            String::new()
1281        };
1282        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!(
1283            "{prefix}clone the value from the field instead of using the functional record update \
1284             syntax",
1285        );
1286        err.span_suggestion_verbose(span, msg, sugg, Applicability::MachineApplicable);
1287    }
1288
1289    pub(crate) fn suggest_cloning(
1290        &self,
1291        err: &mut Diag<'_>,
1292        place: PlaceRef<'tcx>,
1293        ty: Ty<'tcx>,
1294        expr: &'tcx hir::Expr<'tcx>,
1295        use_spans: Option<UseSpans<'tcx>>,
1296    ) {
1297        if let hir::ExprKind::Struct(_, _, hir::StructTailExpr::Base(_)) = expr.kind {
1298            // We have `S { foo: val, ..base }`. In `check_aggregate_rvalue` we have a single
1299            // `Location` that covers both the `S { ... }` literal, all of its fields and the
1300            // `base`. If the move happens because of `S { foo: val, bar: base.bar }` the `expr`
1301            //  will already be correct. Instead, we see if we can suggest writing.
1302            self.suggest_cloning_on_functional_record_update(err, ty, expr);
1303            return;
1304        }
1305
1306        if self.implements_clone(ty) {
1307            if self.in_move_closure(expr) {
1308                if let Some(name) = self.describe_place(place) {
1309                    self.suggest_clone_of_captured_var_in_move_closure(err, &name, use_spans);
1310                }
1311            } else {
1312                self.suggest_cloning_inner(err, ty, expr);
1313            }
1314        } else if let ty::Adt(def, args) = ty.kind()
1315            && let Some(local_did) = def.did().as_local()
1316            && def.variants().iter().all(|variant| {
1317                variant
1318                    .fields
1319                    .iter()
1320                    .all(|field| self.implements_clone(field.ty(self.infcx.tcx, args)))
1321            })
1322        {
1323            let ty_span = self.infcx.tcx.def_span(def.did());
1324            let mut span: MultiSpan = ty_span.into();
1325            let mut derive_clone = false;
1326            self.infcx.tcx.for_each_relevant_impl(
1327                self.infcx.tcx.lang_items().clone_trait().unwrap(),
1328                ty,
1329                |def_id| {
1330                    if self.infcx.tcx.is_automatically_derived(def_id) {
1331                        derive_clone = true;
1332                        span.push_span_label(
1333                            self.infcx.tcx.def_span(def_id),
1334                            "derived `Clone` adds implicit bounds on type parameters",
1335                        );
1336                        if let Some(generics) = self.infcx.tcx.hir_get_generics(local_did) {
1337                            for param in generics.params {
1338                                if let hir::GenericParamKind::Type { .. } = param.kind {
1339                                    span.push_span_label(
1340                                        param.span,
1341                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("introduces an implicit `{0}: Clone` bound",
                param.name.ident()))
    })format!(
1342                                            "introduces an implicit `{}: Clone` bound",
1343                                            param.name.ident()
1344                                        ),
1345                                    );
1346                                }
1347                            }
1348                        }
1349                    }
1350                },
1351            );
1352            let msg = if !derive_clone {
1353                span.push_span_label(
1354                    ty_span,
1355                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider {0}implementing `Clone` for this type",
                if derive_clone { "manually " } else { "" }))
    })format!(
1356                        "consider {}implementing `Clone` for this type",
1357                        if derive_clone { "manually " } else { "" }
1358                    ),
1359                );
1360                ::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")
1361            } else {
1362                ::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")
1363            };
1364            span.push_span_label(expr.span, "you could clone this value");
1365            err.span_note(span, msg);
1366            if derive_clone {
1367                err.help("consider manually implementing `Clone` to avoid undesired bounds");
1368            }
1369        } else if let ty::Param(param) = ty.kind()
1370            && let Some(_clone_trait_def) = self.infcx.tcx.lang_items().clone_trait()
1371            && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1372            && let generic_param = generics.type_param(*param, self.infcx.tcx)
1373            && let param_span = self.infcx.tcx.def_span(generic_param.def_id)
1374            && if let Some(UseSpans::FnSelfUse { kind, .. }) = use_spans
1375                && let CallKind::FnCall { fn_trait_id, self_ty } = kind
1376                && let ty::Param(_) = self_ty.kind()
1377                && ty == self_ty
1378                && self.infcx.tcx.fn_trait_kind_from_def_id(fn_trait_id).is_some()
1379            {
1380                // Do not suggest `F: FnOnce() + Clone`.
1381                false
1382            } else {
1383                true
1384            }
1385        {
1386            let mut span: MultiSpan = param_span.into();
1387            span.push_span_label(
1388                param_span,
1389                "consider constraining this type parameter with `Clone`",
1390            );
1391            span.push_span_label(expr.span, "you could clone this value");
1392            err.span_help(
1393                span,
1394                ::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"),
1395            );
1396        } else if let ty::Adt(_, _) = ty.kind()
1397            && let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1398        {
1399            // For cases like `Option<NonClone>`, where `Option<T>: Clone` if `T: Clone`, we point
1400            // at the types that should be `Clone`.
1401            let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1402            let cause = ObligationCause::misc(expr.span, self.mir_def_id());
1403            ocx.register_bound(cause, self.infcx.param_env, ty, clone_trait);
1404            let errors = ocx.evaluate_obligations_error_on_ambiguity();
1405            if errors.iter().all(|error| {
1406                match error.obligation.predicate.as_clause().and_then(|c| c.as_trait_clause()) {
1407                    Some(clause) => match clause.self_ty().skip_binder().kind() {
1408                        ty::Adt(def, _) => def.did().is_local() && clause.def_id() == clone_trait,
1409                        _ => false,
1410                    },
1411                    None => false,
1412                }
1413            }) {
1414                let mut type_spans = ::alloc::vec::Vec::new()vec![];
1415                let mut types = FxIndexSet::default();
1416                for clause in errors
1417                    .iter()
1418                    .filter_map(|e| e.obligation.predicate.as_clause())
1419                    .filter_map(|c| c.as_trait_clause())
1420                {
1421                    let ty::Adt(def, _) = clause.self_ty().skip_binder().kind() else { continue };
1422                    type_spans.push(self.infcx.tcx.def_span(def.did()));
1423                    types.insert(
1424                        self.infcx
1425                            .tcx
1426                            .short_string(clause.self_ty().skip_binder(), &mut err.long_ty_path()),
1427                    );
1428                }
1429                let mut span: MultiSpan = type_spans.clone().into();
1430                for sp in type_spans {
1431                    span.push_span_label(sp, "consider implementing `Clone` for this type");
1432                }
1433                span.push_span_label(expr.span, "you could clone this value");
1434                let types: Vec<_> = types.into_iter().collect();
1435                let msg = match &types[..] {
1436                    [only] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", only))
    })format!("`{only}`"),
1437                    [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!(
1438                        "{} and `{last}`",
1439                        head.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(", ")
1440                    ),
1441                    [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1442                };
1443                err.span_note(
1444                    span,
1445                    ::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"),
1446                );
1447            }
1448        }
1449    }
1450
1451    pub(crate) fn implements_clone(&self, ty: Ty<'tcx>) -> bool {
1452        let Some(clone_trait_def) = self.infcx.tcx.lang_items().clone_trait() else { return false };
1453        self.infcx
1454            .type_implements_trait(clone_trait_def, [ty], self.infcx.param_env)
1455            .must_apply_modulo_regions()
1456    }
1457
1458    /// Given an expression, check if it is a method call `foo.clone()`, where `foo` and
1459    /// `foo.clone()` both have the same type, returning the span for `.clone()` if so.
1460    pub(crate) fn clone_on_reference(&self, expr: &hir::Expr<'_>) -> Option<Span> {
1461        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1462        if let hir::ExprKind::MethodCall(segment, rcvr, args, span) = expr.kind
1463            && let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id)
1464            && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
1465            && rcvr_ty == expr_ty
1466            && segment.ident.name == sym::clone
1467            && args.is_empty()
1468        {
1469            Some(span)
1470        } else {
1471            None
1472        }
1473    }
1474
1475    fn in_move_closure(&self, expr: &hir::Expr<'_>) -> bool {
1476        for (_, node) in self.infcx.tcx.hir_parent_iter(expr.hir_id) {
1477            if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) = node
1478                && let hir::CaptureBy::Value { .. } = closure.capture_clause
1479            {
1480                // `move || x.clone()` will not work. FIXME: suggest `let y = x.clone(); move || y`
1481                return true;
1482            }
1483        }
1484        false
1485    }
1486
1487    fn suggest_cloning_inner(
1488        &self,
1489        err: &mut Diag<'_>,
1490        ty: Ty<'tcx>,
1491        expr: &hir::Expr<'_>,
1492    ) -> bool {
1493        let tcx = self.infcx.tcx;
1494
1495        // Don't suggest `.clone()` in a derive macro expansion.
1496        if let ExpnKind::Macro(MacroKind::Derive, _) = self.body.span.ctxt().outer_expn_data().kind
1497        {
1498            return false;
1499        }
1500        if let Some(_) = self.clone_on_reference(expr) {
1501            // Avoid redundant clone suggestion already suggested in `explain_captures`.
1502            // See `tests/ui/moves/needs-clone-through-deref.rs`
1503            return false;
1504        }
1505        // We don't want to suggest `.clone()` in a move closure, since the value has already been
1506        // captured.
1507        if self.in_move_closure(expr) {
1508            return false;
1509        }
1510        // We also don't want to suggest cloning a closure itself, since the value has already been
1511        // captured.
1512        if let hir::ExprKind::Closure(_) = expr.kind {
1513            return false;
1514        }
1515        // Try to find predicates on *generic params* that would allow copying `ty`
1516        let mut suggestion =
1517            if let Some(symbol) = tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1518                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}.clone()", symbol))
    })format!(": {symbol}.clone()")
1519            } else {
1520                ".clone()".to_owned()
1521            };
1522        let mut sugg = Vec::with_capacity(2);
1523        let mut inner_expr = expr;
1524        let mut is_raw_ptr = false;
1525        let typeck_result = self.infcx.tcx.typeck(self.mir_def_id());
1526        // Remove uses of `&` and `*` when suggesting `.clone()`.
1527        while let hir::ExprKind::AddrOf(.., inner) | hir::ExprKind::Unary(hir::UnOp::Deref, inner) =
1528            &inner_expr.kind
1529        {
1530            if let hir::ExprKind::AddrOf(_, hir::Mutability::Mut, _) = inner_expr.kind {
1531                // We assume that `&mut` refs are desired for their side-effects, so cloning the
1532                // value wouldn't do what the user wanted.
1533                return false;
1534            }
1535            inner_expr = inner;
1536            if let Some(inner_type) = typeck_result.node_type_opt(inner.hir_id) {
1537                if #[allow(non_exhaustive_omitted_patterns)] match inner_type.kind() {
    ty::RawPtr(..) => true,
    _ => false,
}matches!(inner_type.kind(), ty::RawPtr(..)) {
1538                    is_raw_ptr = true;
1539                    break;
1540                }
1541            }
1542        }
1543        // Cloning the raw pointer doesn't make sense in some cases and would cause a type mismatch
1544        // error. (see #126863)
1545        if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
1546            // Remove "(*" or "(&"
1547            sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
1548        }
1549        // Check whether `expr` is surrounded by parentheses or not.
1550        let span = if inner_expr.span.hi() != expr.span.hi() {
1551            // Account for `(*x)` to suggest `x.clone()`.
1552            if is_raw_ptr {
1553                expr.span.shrink_to_hi()
1554            } else {
1555                // Remove the close parenthesis ")"
1556                expr.span.with_lo(inner_expr.span.hi())
1557            }
1558        } else {
1559            if is_raw_ptr {
1560                sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1561                suggestion = ").clone()".to_string();
1562            }
1563            expr.span.shrink_to_hi()
1564        };
1565        sugg.push((span, suggestion));
1566        let msg = if let ty::Adt(def, _) = ty.kind()
1567            && [tcx.get_diagnostic_item(sym::Arc), tcx.get_diagnostic_item(sym::Rc)]
1568                .contains(&Some(def.did()))
1569        {
1570            "clone the value to increment its reference count"
1571        } else {
1572            "consider cloning the value if the performance cost is acceptable"
1573        };
1574        err.multipart_suggestion(msg, sugg, Applicability::MachineApplicable);
1575        true
1576    }
1577
1578    fn suggest_adding_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, def_id: DefId, span: Span) {
1579        let tcx = self.infcx.tcx;
1580        let generics = tcx.generics_of(self.mir_def_id());
1581
1582        let Some(hir_generics) =
1583            tcx.hir_get_generics(tcx.typeck_root_def_id_local(self.mir_def_id()))
1584        else {
1585            return;
1586        };
1587        // Try to find predicates on *generic params* that would allow copying `ty`
1588        let ocx = ObligationCtxt::new_with_diagnostics(self.infcx);
1589        let cause = ObligationCause::misc(span, self.mir_def_id());
1590
1591        ocx.register_bound(cause, self.infcx.param_env, ty, def_id);
1592        let errors = ocx.evaluate_obligations_error_on_ambiguity();
1593
1594        // Only emit suggestion if all required predicates are on generic
1595        let predicates: Result<Vec<_>, _> = errors
1596            .into_iter()
1597            .map(|err| match err.obligation.predicate.kind().skip_binder() {
1598                PredicateKind::Clause(ty::ClauseKind::Trait(predicate)) => {
1599                    match *predicate.self_ty().kind() {
1600                        ty::Param(param_ty) => Ok((
1601                            generics.type_param(param_ty, tcx),
1602                            predicate.trait_ref.print_trait_sugared().to_string(),
1603                            Some(predicate.trait_ref.def_id),
1604                        )),
1605                        _ => Err(()),
1606                    }
1607                }
1608                _ => Err(()),
1609            })
1610            .collect();
1611
1612        if let Ok(predicates) = predicates {
1613            suggest_constraining_type_params(
1614                tcx,
1615                hir_generics,
1616                err,
1617                predicates.iter().map(|(param, constraint, def_id)| {
1618                    (param.name.as_str(), &**constraint, *def_id)
1619                }),
1620                None,
1621            );
1622        }
1623    }
1624
1625    pub(crate) fn report_move_out_while_borrowed(
1626        &mut self,
1627        location: Location,
1628        (place, span): (Place<'tcx>, Span),
1629        borrow: &BorrowData<'tcx>,
1630    ) {
1631        {
    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:1631",
                        "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(1631u32),
                        ::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!(
1632            "report_move_out_while_borrowed: location={:?} place={:?} span={:?} borrow={:?}",
1633            location, place, span, borrow
1634        );
1635        let value_msg = self.describe_any_place(place.as_ref());
1636        let borrow_msg = self.describe_any_place(borrow.borrowed_place.as_ref());
1637
1638        let borrow_spans = self.retrieve_borrow_spans(borrow);
1639        let borrow_span = borrow_spans.args_or_use();
1640
1641        let move_spans = self.move_spans(place.as_ref(), location);
1642        let span = move_spans.args_or_use();
1643
1644        let mut err = self.cannot_move_when_borrowed(
1645            span,
1646            borrow_span,
1647            &self.describe_any_place(place.as_ref()),
1648            &borrow_msg,
1649            &value_msg,
1650        );
1651        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1652
1653        borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
1654
1655        move_spans.var_subdiag(&mut err, None, |kind, var_span| {
1656            use crate::session_diagnostics::CaptureVarCause::*;
1657            match kind {
1658                hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
1659                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1660                    MoveUseInClosure { var_span }
1661                }
1662            }
1663        });
1664
1665        self.explain_why_borrow_contains_point(location, borrow, None)
1666            .add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
1667        self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
1668        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1669        if let Some(expr) = self.find_expr(borrow_span) {
1670            // This is a borrow span, so we want to suggest cloning the referent.
1671            if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind
1672                && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr)
1673            {
1674                self.suggest_cloning(&mut err, place.as_ref(), ty, borrowed_expr, Some(move_spans));
1675            } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| {
1676                #[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!(
1677                    adj.kind,
1678                    ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref(
1679                        ty::adjustment::AutoBorrowMutability::Not
1680                            | ty::adjustment::AutoBorrowMutability::Mut {
1681                                allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No
1682                            }
1683                    ))
1684                )
1685            }) && let Some(ty) = typeck_results.expr_ty_opt(expr)
1686            {
1687                self.suggest_cloning(&mut err, place.as_ref(), ty, expr, Some(move_spans));
1688            }
1689        }
1690        self.buffer_error(err);
1691    }
1692
1693    pub(crate) fn report_use_while_mutably_borrowed(
1694        &self,
1695        location: Location,
1696        (place, _span): (Place<'tcx>, Span),
1697        borrow: &BorrowData<'tcx>,
1698    ) -> Diag<'infcx> {
1699        let borrow_spans = self.retrieve_borrow_spans(borrow);
1700        let borrow_span = borrow_spans.args_or_use();
1701
1702        // Conflicting borrows are reported separately, so only check for move
1703        // captures.
1704        let use_spans = self.move_spans(place.as_ref(), location);
1705        let span = use_spans.var_or_use();
1706
1707        // If the attempted use is in a closure then we do not care about the path span of the
1708        // place we are currently trying to use we call `var_span_label` on `borrow_spans` to
1709        // annotate if the existing borrow was in a closure.
1710        let mut err = self.cannot_use_when_mutably_borrowed(
1711            span,
1712            &self.describe_any_place(place.as_ref()),
1713            borrow_span,
1714            &self.describe_any_place(borrow.borrowed_place.as_ref()),
1715        );
1716        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
1717
1718        borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
1719            use crate::session_diagnostics::CaptureVarCause::*;
1720            let place = &borrow.borrowed_place;
1721            let desc_place = self.describe_any_place(place.as_ref());
1722            match kind {
1723                hir::ClosureKind::Coroutine(_) => {
1724                    BorrowUsePlaceCoroutine { place: desc_place, var_span, is_single_var: true }
1725                }
1726                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1727                    BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }
1728                }
1729            }
1730        });
1731
1732        self.explain_why_borrow_contains_point(location, borrow, None)
1733            .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
1734        err
1735    }
1736
1737    pub(crate) fn report_conflicting_borrow(
1738        &self,
1739        location: Location,
1740        (place, span): (Place<'tcx>, Span),
1741        gen_borrow_kind: BorrowKind,
1742        issued_borrow: &BorrowData<'tcx>,
1743    ) -> Diag<'infcx> {
1744        let issued_spans = self.retrieve_borrow_spans(issued_borrow);
1745        let issued_span = issued_spans.args_or_use();
1746
1747        let borrow_spans = self.borrow_spans(span, location);
1748        let span = borrow_spans.args_or_use();
1749
1750        let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() {
1751            "coroutine"
1752        } else {
1753            "closure"
1754        };
1755
1756        let (desc_place, msg_place, msg_borrow, union_type_name) =
1757            self.describe_place_for_conflicting_borrow(place, issued_borrow.borrowed_place);
1758
1759        let explanation = self.explain_why_borrow_contains_point(location, issued_borrow, None);
1760        let second_borrow_desc = if explanation.is_explained() { "second " } else { "" };
1761
1762        // FIXME: supply non-"" `opt_via` when appropriate
1763        let first_borrow_desc;
1764        let mut err = match (gen_borrow_kind, issued_borrow.kind) {
1765            (
1766                BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1767                BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1768            ) => {
1769                first_borrow_desc = "mutable ";
1770                let mut err = self.cannot_reborrow_already_borrowed(
1771                    span,
1772                    &desc_place,
1773                    &msg_place,
1774                    "immutable",
1775                    issued_span,
1776                    "it",
1777                    "mutable",
1778                    &msg_borrow,
1779                    None,
1780                );
1781                self.suggest_slice_method_if_applicable(
1782                    &mut err,
1783                    place,
1784                    issued_borrow.borrowed_place,
1785                    span,
1786                    issued_span,
1787                );
1788                err
1789            }
1790            (
1791                BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1792                BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1793            ) => {
1794                first_borrow_desc = "immutable ";
1795                let mut err = self.cannot_reborrow_already_borrowed(
1796                    span,
1797                    &desc_place,
1798                    &msg_place,
1799                    "mutable",
1800                    issued_span,
1801                    "it",
1802                    "immutable",
1803                    &msg_borrow,
1804                    None,
1805                );
1806                self.suggest_slice_method_if_applicable(
1807                    &mut err,
1808                    place,
1809                    issued_borrow.borrowed_place,
1810                    span,
1811                    issued_span,
1812                );
1813                self.suggest_binding_for_closure_capture_self(&mut err, &issued_spans);
1814                self.suggest_using_closure_argument_instead_of_capture(
1815                    &mut err,
1816                    issued_borrow.borrowed_place,
1817                    &issued_spans,
1818                );
1819                err
1820            }
1821
1822            (
1823                BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1824                BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow },
1825            ) => {
1826                first_borrow_desc = "first ";
1827                let mut err = self.cannot_mutably_borrow_multiply(
1828                    span,
1829                    &desc_place,
1830                    &msg_place,
1831                    issued_span,
1832                    &msg_borrow,
1833                    None,
1834                );
1835                self.suggest_slice_method_if_applicable(
1836                    &mut err,
1837                    place,
1838                    issued_borrow.borrowed_place,
1839                    span,
1840                    issued_span,
1841                );
1842                self.suggest_using_closure_argument_instead_of_capture(
1843                    &mut err,
1844                    issued_borrow.borrowed_place,
1845                    &issued_spans,
1846                );
1847                self.explain_iterator_advancement_in_for_loop_if_applicable(
1848                    &mut err,
1849                    span,
1850                    &issued_spans,
1851                );
1852                err
1853            }
1854
1855            (
1856                BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1857                BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1858            ) => {
1859                first_borrow_desc = "first ";
1860                self.cannot_uniquely_borrow_by_two_closures(span, &desc_place, issued_span, None)
1861            }
1862
1863            (BorrowKind::Mut { .. }, BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1864                if let Some(immutable_section_description) =
1865                    self.classify_immutable_section(issued_borrow.assigned_place)
1866                {
1867                    let mut err = self.cannot_mutate_in_immutable_section(
1868                        span,
1869                        issued_span,
1870                        &desc_place,
1871                        immutable_section_description,
1872                        "mutably borrow",
1873                    );
1874                    borrow_spans.var_subdiag(
1875                        &mut err,
1876                        Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
1877                        |kind, var_span| {
1878                            use crate::session_diagnostics::CaptureVarCause::*;
1879                            match kind {
1880                                hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1881                                    place: desc_place,
1882                                    var_span,
1883                                    is_single_var: true,
1884                                },
1885                                hir::ClosureKind::Closure
1886                                | hir::ClosureKind::CoroutineClosure(_) => BorrowUsePlaceClosure {
1887                                    place: desc_place,
1888                                    var_span,
1889                                    is_single_var: true,
1890                                },
1891                            }
1892                        },
1893                    );
1894                    return err;
1895                } else {
1896                    first_borrow_desc = "immutable ";
1897                    self.cannot_reborrow_already_borrowed(
1898                        span,
1899                        &desc_place,
1900                        &msg_place,
1901                        "mutable",
1902                        issued_span,
1903                        "it",
1904                        "immutable",
1905                        &msg_borrow,
1906                        None,
1907                    )
1908                }
1909            }
1910
1911            (BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }, _) => {
1912                first_borrow_desc = "first ";
1913                self.cannot_uniquely_borrow_by_one_closure(
1914                    span,
1915                    container_name,
1916                    &desc_place,
1917                    "",
1918                    issued_span,
1919                    "it",
1920                    "",
1921                    None,
1922                )
1923            }
1924
1925            (
1926                BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1927                BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
1928            ) => {
1929                first_borrow_desc = "first ";
1930                self.cannot_reborrow_already_uniquely_borrowed(
1931                    span,
1932                    container_name,
1933                    &desc_place,
1934                    "",
1935                    "immutable",
1936                    issued_span,
1937                    "",
1938                    None,
1939                    second_borrow_desc,
1940                )
1941            }
1942
1943            (BorrowKind::Mut { .. }, BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }) => {
1944                first_borrow_desc = "first ";
1945                self.cannot_reborrow_already_uniquely_borrowed(
1946                    span,
1947                    container_name,
1948                    &desc_place,
1949                    "",
1950                    "mutable",
1951                    issued_span,
1952                    "",
1953                    None,
1954                    second_borrow_desc,
1955                )
1956            }
1957
1958            (
1959                BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep),
1960                BorrowKind::Shared | BorrowKind::Fake(_),
1961            )
1962            | (
1963                BorrowKind::Fake(FakeBorrowKind::Shallow),
1964                BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_),
1965            ) => {
1966                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1967            }
1968        };
1969        self.note_due_to_edition_2024_opaque_capture_rules(issued_borrow, &mut err);
1970
1971        if issued_spans == borrow_spans {
1972            borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1973                use crate::session_diagnostics::CaptureVarCause::*;
1974                match kind {
1975                    hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1976                        place: desc_place,
1977                        var_span,
1978                        is_single_var: false,
1979                    },
1980                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1981                        BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
1982                    }
1983                }
1984            });
1985        } else {
1986            issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
1987                use crate::session_diagnostics::CaptureVarCause::*;
1988                let borrow_place = &issued_borrow.borrowed_place;
1989                let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
1990                match kind {
1991                    hir::ClosureKind::Coroutine(_) => {
1992                        FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
1993                    }
1994                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1995                        FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
1996                    }
1997                }
1998            });
1999
2000            borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
2001                use crate::session_diagnostics::CaptureVarCause::*;
2002                match kind {
2003                    hir::ClosureKind::Coroutine(_) => {
2004                        SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
2005                    }
2006                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
2007                        SecondBorrowUsePlaceClosure { place: desc_place, var_span }
2008                    }
2009                }
2010            });
2011        }
2012
2013        if union_type_name != "" {
2014            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!(
2015                "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
2016            ));
2017        }
2018
2019        explanation.add_explanation_to_diagnostic(
2020            &self,
2021            &mut err,
2022            first_borrow_desc,
2023            None,
2024            Some((issued_span, span)),
2025        );
2026
2027        self.suggest_using_local_if_applicable(&mut err, location, issued_borrow, explanation);
2028        self.suggest_copy_for_type_in_cloned_ref(&mut err, place);
2029
2030        err
2031    }
2032
2033    fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
2034        let tcx = self.infcx.tcx;
2035        let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2036
2037        struct FindUselessClone<'tcx> {
2038            tcx: TyCtxt<'tcx>,
2039            typeck_results: &'tcx ty::TypeckResults<'tcx>,
2040            clones: Vec<&'tcx hir::Expr<'tcx>>,
2041        }
2042        impl<'tcx> FindUselessClone<'tcx> {
2043            fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2044                Self { tcx, typeck_results: tcx.typeck(def_id), clones: ::alloc::vec::Vec::new()vec![] }
2045            }
2046        }
2047        impl<'tcx> Visitor<'tcx> for FindUselessClone<'tcx> {
2048            fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2049                if let hir::ExprKind::MethodCall(..) = ex.kind
2050                    && let Some(method_def_id) =
2051                        self.typeck_results.type_dependent_def_id(ex.hir_id)
2052                    && self.tcx.is_lang_item(self.tcx.parent(method_def_id), LangItem::Clone)
2053                {
2054                    self.clones.push(ex);
2055                }
2056                hir::intravisit::walk_expr(self, ex);
2057            }
2058        }
2059
2060        let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
2061
2062        let body = tcx.hir_body(body_id).value;
2063        expr_finder.visit_expr(body);
2064
2065        struct Holds<'tcx> {
2066            ty: Ty<'tcx>,
2067        }
2068
2069        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Holds<'tcx> {
2070            type Result = std::ops::ControlFlow<()>;
2071
2072            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
2073                if t == self.ty {
2074                    return ControlFlow::Break(());
2075                }
2076                t.super_visit_with(self)
2077            }
2078        }
2079
2080        let mut types_to_constrain = FxIndexSet::default();
2081
2082        let local_ty = self.body.local_decls[place.local].ty;
2083        let typeck_results = tcx.typeck(self.mir_def_id());
2084        let clone = tcx.require_lang_item(LangItem::Clone, body.span);
2085        for expr in expr_finder.clones {
2086            if let hir::ExprKind::MethodCall(_, rcvr, _, span) = expr.kind
2087                && let Some(rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id)
2088                && let Some(ty) = typeck_results.node_type_opt(expr.hir_id)
2089                && rcvr_ty == ty
2090                && let ty::Ref(_, inner, _) = rcvr_ty.kind()
2091                && let inner = inner.peel_refs()
2092                && (Holds { ty: inner }).visit_ty(local_ty).is_break()
2093                && let None =
2094                    self.infcx.type_implements_trait_shallow(clone, inner, self.infcx.param_env)
2095            {
2096                err.span_label(
2097                    span,
2098                    ::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!(
2099                        "this call doesn't do anything, the result is still `{rcvr_ty}` \
2100                             because `{inner}` doesn't implement `Clone`",
2101                    ),
2102                );
2103                types_to_constrain.insert(inner);
2104            }
2105        }
2106        for ty in types_to_constrain {
2107            self.suggest_adding_bounds_or_derive(err, ty, clone, body.span);
2108        }
2109    }
2110
2111    pub(crate) fn suggest_adding_bounds_or_derive(
2112        &self,
2113        err: &mut Diag<'_>,
2114        ty: Ty<'tcx>,
2115        trait_def_id: DefId,
2116        span: Span,
2117    ) {
2118        self.suggest_adding_bounds(err, ty, trait_def_id, span);
2119        if let ty::Adt(..) = ty.kind() {
2120            // The type doesn't implement the trait.
2121            let trait_ref =
2122                ty::Binder::dummy(ty::TraitRef::new(self.infcx.tcx, trait_def_id, [ty]));
2123            let obligation = Obligation::new(
2124                self.infcx.tcx,
2125                ObligationCause::dummy(),
2126                self.infcx.param_env,
2127                trait_ref,
2128            );
2129            self.infcx.err_ctxt().suggest_derive(
2130                &obligation,
2131                err,
2132                trait_ref.upcast(self.infcx.tcx),
2133            );
2134        }
2135    }
2136
2137    #[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(2137u32),
                                    ::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:2155",
                                        "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(2155u32),
                                        ::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:2184",
                                            "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(2184u32),
                                            ::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:2188",
                                            "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(2188u32),
                                            ::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:2198",
                                                            "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(2198u32),
                                                            ::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:2202",
                                                            "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(2202u32),
                                                            ::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:2205",
                                                    "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(2205u32),
                                                    ::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:2212",
                                            "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(2212u32),
                                            ::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:2215",
                                    "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(2215u32),
                                    ::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:2225",
                                        "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(2225u32),
                                        ::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))]
2138    fn suggest_using_local_if_applicable(
2139        &self,
2140        err: &mut Diag<'_>,
2141        location: Location,
2142        issued_borrow: &BorrowData<'tcx>,
2143        explanation: BorrowExplanation<'tcx>,
2144    ) {
2145        let used_in_call = matches!(
2146            explanation,
2147            BorrowExplanation::UsedLater(
2148                _,
2149                LaterUseKind::Call | LaterUseKind::Other,
2150                _call_span,
2151                _
2152            )
2153        );
2154        if !used_in_call {
2155            debug!("not later used in call");
2156            return;
2157        }
2158        if matches!(
2159            self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
2160            LocalInfo::IfThenRescopeTemp { .. }
2161        ) {
2162            // A better suggestion will be issued by the `if_let_rescope` lint
2163            return;
2164        }
2165
2166        let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
2167            explanation
2168        {
2169            Some(use_span)
2170        } else {
2171            None
2172        };
2173
2174        let outer_call_loc =
2175            if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
2176                loc
2177            } else {
2178                issued_borrow.reserve_location
2179            };
2180        let outer_call_stmt = self.body.stmt_at(outer_call_loc);
2181
2182        let inner_param_location = location;
2183        let Some(inner_param_stmt) = self.body.stmt_at(inner_param_location).left() else {
2184            debug!("`inner_param_location` {:?} is not for a statement", inner_param_location);
2185            return;
2186        };
2187        let Some(&inner_param) = inner_param_stmt.kind.as_assign().map(|(p, _)| p) else {
2188            debug!(
2189                "`inner_param_location` {:?} is not for an assignment: {:?}",
2190                inner_param_location, inner_param_stmt
2191            );
2192            return;
2193        };
2194        let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local);
2195        let Some((inner_call_loc, inner_call_term)) =
2196            inner_param_uses.into_iter().find_map(|loc| {
2197                let Either::Right(term) = self.body.stmt_at(loc) else {
2198                    debug!("{:?} is a statement, so it can't be a call", loc);
2199                    return None;
2200                };
2201                let TerminatorKind::Call { args, .. } = &term.kind else {
2202                    debug!("not a call: {:?}", term);
2203                    return None;
2204                };
2205                debug!("checking call args for uses of inner_param: {:?}", args);
2206                args.iter()
2207                    .map(|a| &a.node)
2208                    .any(|a| a == &Operand::Move(inner_param))
2209                    .then_some((loc, term))
2210            })
2211        else {
2212            debug!("no uses of inner_param found as a by-move call arg");
2213            return;
2214        };
2215        debug!("===> outer_call_loc = {:?}, inner_call_loc = {:?}", outer_call_loc, inner_call_loc);
2216
2217        let inner_call_span = inner_call_term.source_info.span;
2218        let outer_call_span = match use_span {
2219            Some(span) => span,
2220            None => outer_call_stmt.either(|s| s.source_info, |t| t.source_info).span,
2221        };
2222        if outer_call_span == inner_call_span || !outer_call_span.contains(inner_call_span) {
2223            // FIXME: This stops the suggestion in some cases where it should be emitted.
2224            //        Fix the spans for those cases so it's emitted correctly.
2225            debug!(
2226                "outer span {:?} does not strictly contain inner span {:?}",
2227                outer_call_span, inner_call_span
2228            );
2229            return;
2230        }
2231        err.span_help(
2232            inner_call_span,
2233            format!(
2234                "try adding a local storing this{}...",
2235                if use_span.is_some() { "" } else { " argument" }
2236            ),
2237        );
2238        err.span_help(
2239            outer_call_span,
2240            format!(
2241                "...and then using that local {}",
2242                if use_span.is_some() { "here" } else { "as the argument to this call" }
2243            ),
2244        );
2245    }
2246
2247    pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
2248        let tcx = self.infcx.tcx;
2249        let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
2250        let mut expr_finder = FindExprBySpan::new(span, tcx);
2251        expr_finder.visit_expr(tcx.hir_body(body_id).value);
2252        expr_finder.result
2253    }
2254
2255    fn suggest_slice_method_if_applicable(
2256        &self,
2257        err: &mut Diag<'_>,
2258        place: Place<'tcx>,
2259        borrowed_place: Place<'tcx>,
2260        span: Span,
2261        issued_span: Span,
2262    ) {
2263        let tcx = self.infcx.tcx;
2264
2265        let has_split_at_mut = |ty: Ty<'tcx>| {
2266            let ty = ty.peel_refs();
2267            match ty.kind() {
2268                ty::Array(..) | ty::Slice(..) => true,
2269                ty::Adt(def, _) if tcx.get_diagnostic_item(sym::Vec) == Some(def.did()) => true,
2270                _ if ty == tcx.types.str_ => true,
2271                _ => false,
2272            }
2273        };
2274        if let ([ProjectionElem::Index(index1)], [ProjectionElem::Index(index2)])
2275        | (
2276            [ProjectionElem::Deref, ProjectionElem::Index(index1)],
2277            [ProjectionElem::Deref, ProjectionElem::Index(index2)],
2278        ) = (&place.projection[..], &borrowed_place.projection[..])
2279        {
2280            let decl1 = &self.body.local_decls[*index1];
2281            let decl2 = &self.body.local_decls[*index2];
2282
2283            let mut note_default_suggestion = || {
2284                err.help(
2285                    "consider using `.split_at_mut(position)` or similar method to obtain two \
2286                     mutable non-overlapping sub-slices",
2287                )
2288                .help(
2289                    "consider using `.swap(index_1, index_2)` to swap elements at the specified \
2290                     indices",
2291                );
2292            };
2293
2294            let Some(index1) = self.find_expr(decl1.source_info.span) else {
2295                note_default_suggestion();
2296                return;
2297            };
2298
2299            let Some(index2) = self.find_expr(decl2.source_info.span) else {
2300                note_default_suggestion();
2301                return;
2302            };
2303
2304            let sm = tcx.sess.source_map();
2305
2306            let Ok(index1_str) = sm.span_to_snippet(index1.span) else {
2307                note_default_suggestion();
2308                return;
2309            };
2310
2311            let Ok(index2_str) = sm.span_to_snippet(index2.span) else {
2312                note_default_suggestion();
2313                return;
2314            };
2315
2316            let Some(object) = tcx.hir_parent_id_iter(index1.hir_id).find_map(|id| {
2317                if let hir::Node::Expr(expr) = tcx.hir_node(id)
2318                    && let hir::ExprKind::Index(obj, ..) = expr.kind
2319                {
2320                    Some(obj)
2321                } else {
2322                    None
2323                }
2324            }) else {
2325                note_default_suggestion();
2326                return;
2327            };
2328
2329            let Ok(obj_str) = sm.span_to_snippet(object.span) else {
2330                note_default_suggestion();
2331                return;
2332            };
2333
2334            let Some(swap_call) = tcx.hir_parent_id_iter(object.hir_id).find_map(|id| {
2335                if let hir::Node::Expr(call) = tcx.hir_node(id)
2336                    && let hir::ExprKind::Call(callee, ..) = call.kind
2337                    && let hir::ExprKind::Path(qpath) = callee.kind
2338                    && let hir::QPath::Resolved(None, res) = qpath
2339                    && let hir::def::Res::Def(_, did) = res.res
2340                    && tcx.is_diagnostic_item(sym::mem_swap, did)
2341                {
2342                    Some(call)
2343                } else {
2344                    None
2345                }
2346            }) else {
2347                let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2348                let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2349                let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2350                let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2351                if !idx1.equivalent_for_indexing(idx2) {
2352                    err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2353                }
2354                return;
2355            };
2356
2357            err.span_suggestion(
2358                swap_call.span,
2359                "use `.swap()` to swap elements at the specified indices instead",
2360                ::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})"),
2361                Applicability::MachineApplicable,
2362            );
2363            return;
2364        }
2365        let place_ty = PlaceRef::ty(&place.as_ref(), self.body, tcx).ty;
2366        let borrowed_place_ty = PlaceRef::ty(&borrowed_place.as_ref(), self.body, tcx).ty;
2367        if !has_split_at_mut(place_ty) && !has_split_at_mut(borrowed_place_ty) {
2368            // Only mention `split_at_mut` on `Vec`, array and slices.
2369            return;
2370        }
2371        let Some(index1) = self.find_expr(span) else { return };
2372        let hir::Node::Expr(parent) = tcx.parent_hir_node(index1.hir_id) else { return };
2373        let hir::ExprKind::Index(_, idx1, _) = parent.kind else { return };
2374        let Some(index2) = self.find_expr(issued_span) else { return };
2375        let hir::Node::Expr(parent) = tcx.parent_hir_node(index2.hir_id) else { return };
2376        let hir::ExprKind::Index(_, idx2, _) = parent.kind else { return };
2377        if idx1.equivalent_for_indexing(idx2) {
2378            // `let a = &mut foo[0]` and `let b = &mut foo[0]`? Don't mention `split_at_mut`
2379            return;
2380        }
2381        err.help("use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices");
2382    }
2383
2384    /// Suggest using `while let` for call `next` on an iterator in a for loop.
2385    ///
2386    /// For example:
2387    /// ```ignore (illustrative)
2388    ///
2389    /// for x in iter {
2390    ///     ...
2391    ///     iter.next()
2392    /// }
2393    /// ```
2394    pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
2395        &self,
2396        err: &mut Diag<'_>,
2397        span: Span,
2398        issued_spans: &UseSpans<'tcx>,
2399    ) {
2400        let issue_span = issued_spans.args_or_use();
2401        let tcx = self.infcx.tcx;
2402
2403        let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2404        let typeck_results = tcx.typeck(self.mir_def_id());
2405
2406        struct ExprFinder<'hir> {
2407            tcx: TyCtxt<'hir>,
2408            issue_span: Span,
2409            expr_span: Span,
2410            body_expr: Option<&'hir hir::Expr<'hir>> = None,
2411            loop_bind: Option<&'hir Ident> = None,
2412            loop_span: Option<Span> = None,
2413            head_span: Option<Span> = None,
2414            pat_span: Option<Span> = None,
2415            head: Option<&'hir hir::Expr<'hir>> = None,
2416        }
2417        impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2418            fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2419                // Try to find
2420                // let result = match IntoIterator::into_iter(<head>) {
2421                //     mut iter => {
2422                //         [opt_ident]: loop {
2423                //             match Iterator::next(&mut iter) {
2424                //                 None => break,
2425                //                 Some(<pat>) => <body>,
2426                //             };
2427                //         }
2428                //     }
2429                // };
2430                // corresponding to the desugaring of a for loop `for <pat> in <head> { <body> }`.
2431                if let hir::ExprKind::Call(path, [arg]) = ex.kind
2432                    && let hir::ExprKind::Path(qpath) = path.kind
2433                    && self.tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
2434                    && arg.span.contains(self.issue_span)
2435                    && ex.span.desugaring_kind() == Some(DesugaringKind::ForLoop)
2436                {
2437                    // Find `IntoIterator::into_iter(<head>)`
2438                    self.head = Some(arg);
2439                }
2440                if let hir::ExprKind::Loop(
2441                    hir::Block { stmts: [stmt, ..], .. },
2442                    _,
2443                    hir::LoopSource::ForLoop,
2444                    _,
2445                ) = ex.kind
2446                    && let hir::StmtKind::Expr(hir::Expr {
2447                        kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2448                        span: head_span,
2449                        ..
2450                    }) = stmt.kind
2451                    && let hir::ExprKind::Call(path, _args) = call.kind
2452                    && let hir::ExprKind::Path(qpath) = path.kind
2453                    && self.tcx.qpath_is_lang_item(qpath, LangItem::IteratorNext)
2454                    && let hir::PatKind::Struct(qpath, [field, ..], _) = bind.pat.kind
2455                    && self.tcx.qpath_is_lang_item(qpath, LangItem::OptionSome)
2456                    && call.span.contains(self.issue_span)
2457                {
2458                    // Find `<pat>` and the span for the whole `for` loop.
2459                    if let PatField {
2460                        pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2461                        ..
2462                    } = field
2463                    {
2464                        self.loop_bind = Some(ident);
2465                    }
2466                    self.head_span = Some(*head_span);
2467                    self.pat_span = Some(bind.pat.span);
2468                    self.loop_span = Some(stmt.span);
2469                }
2470
2471                if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2472                    && body_call.ident.name == sym::next
2473                    && recv.span.source_equal(self.expr_span)
2474                {
2475                    self.body_expr = Some(ex);
2476                }
2477
2478                hir::intravisit::walk_expr(self, ex);
2479            }
2480        }
2481        let mut finder = ExprFinder { tcx, expr_span: span, issue_span, .. };
2482        finder.visit_expr(tcx.hir_body(body_id).value);
2483
2484        if let Some(body_expr) = finder.body_expr
2485            && let Some(loop_span) = finder.loop_span
2486            && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id)
2487            && let Some(trait_did) = tcx.trait_of_assoc(def_id)
2488            && tcx.is_diagnostic_item(sym::Iterator, trait_did)
2489        {
2490            if let Some(loop_bind) = finder.loop_bind {
2491                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!(
2492                    "a for loop advances the iterator for you, the result is stored in `{}`",
2493                    loop_bind.name,
2494                ));
2495            } else {
2496                err.note(
2497                    "a for loop advances the iterator for you, the result is stored in its pattern",
2498                );
2499            }
2500            let msg = "if you want to call `next` on a iterator within the loop, consider using \
2501                       `while let`";
2502            if let Some(head) = finder.head
2503                && let Some(pat_span) = finder.pat_span
2504                && loop_span.contains(body_expr.span)
2505                && loop_span.contains(head.span)
2506            {
2507                let sm = self.infcx.tcx.sess.source_map();
2508
2509                let mut sugg = ::alloc::vec::Vec::new()vec![];
2510                if let hir::ExprKind::Path(hir::QPath::Resolved(None, _)) = head.kind {
2511                    // A bare path doesn't need a `let` assignment, it's already a simple
2512                    // binding access.
2513                    // As a new binding wasn't added, we don't need to modify the advancing call.
2514                    sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
2515                    sugg.push((
2516                        pat_span.shrink_to_hi().with_hi(head.span.lo()),
2517                        ") = ".to_string(),
2518                    ));
2519                    sugg.push((head.span.shrink_to_hi(), ".next()".to_string()));
2520                } else {
2521                    // Needs a new a `let` binding.
2522                    let indent = if let Some(indent) = sm.indentation_before(loop_span) {
2523                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}", indent))
    })format!("\n{indent}")
2524                    } else {
2525                        " ".to_string()
2526                    };
2527                    let Ok(head_str) = sm.span_to_snippet(head.span) else {
2528                        err.help(msg);
2529                        return;
2530                    };
2531                    sugg.push((
2532                        loop_span.with_hi(pat_span.lo()),
2533                        ::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("),
2534                    ));
2535                    sugg.push((
2536                        pat_span.shrink_to_hi().with_hi(head.span.hi()),
2537                        ") = iter.next()".to_string(),
2538                    ));
2539                    // As a new binding was added, we should change how the iterator is advanced to
2540                    // use the newly introduced binding.
2541                    if let hir::ExprKind::MethodCall(_, recv, ..) = body_expr.kind
2542                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, ..)) = recv.kind
2543                    {
2544                        // As we introduced a `let iter = <head>;`, we need to change where the
2545                        // already borrowed value was accessed from `<recv>.next()` to
2546                        // `iter.next()`.
2547                        sugg.push((recv.span, "iter".to_string()));
2548                    }
2549                }
2550                err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2551            } else {
2552                err.help(msg);
2553            }
2554        }
2555    }
2556
2557    /// Suggest using closure argument instead of capture.
2558    ///
2559    /// For example:
2560    /// ```ignore (illustrative)
2561    /// struct S;
2562    ///
2563    /// impl S {
2564    ///     fn call(&mut self, f: impl Fn(&mut Self)) { /* ... */ }
2565    ///     fn x(&self) {}
2566    /// }
2567    ///
2568    ///     let mut v = S;
2569    ///     v.call(|this: &mut S| v.x());
2570    /// //  ^\                    ^-- help: try using the closure argument: `this`
2571    /// //    *-- error: cannot borrow `v` as mutable because it is also borrowed as immutable
2572    /// ```
2573    fn suggest_using_closure_argument_instead_of_capture(
2574        &self,
2575        err: &mut Diag<'_>,
2576        borrowed_place: Place<'tcx>,
2577        issued_spans: &UseSpans<'tcx>,
2578    ) {
2579        let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2580        let tcx = self.infcx.tcx;
2581
2582        // Get the type of the local that we are trying to borrow
2583        let local = borrowed_place.local;
2584        let local_ty = self.body.local_decls[local].ty;
2585
2586        // Get the body the error happens in
2587        let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2588
2589        let body_expr = tcx.hir_body(body_id).value;
2590
2591        struct ClosureFinder<'hir> {
2592            tcx: TyCtxt<'hir>,
2593            borrow_span: Span,
2594            res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
2595            /// The path expression with the `borrow_span` span
2596            error_path: Option<(&'hir hir::Expr<'hir>, &'hir hir::QPath<'hir>)>,
2597        }
2598        impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
2599            type NestedFilter = OnlyBodies;
2600
2601            fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2602                self.tcx
2603            }
2604
2605            fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2606                if let hir::ExprKind::Path(qpath) = &ex.kind
2607                    && ex.span == self.borrow_span
2608                {
2609                    self.error_path = Some((ex, qpath));
2610                }
2611
2612                if let hir::ExprKind::Closure(closure) = ex.kind
2613                    && ex.span.contains(self.borrow_span)
2614                    // To support cases like `|| { v.call(|this| v.get()) }`
2615                    // FIXME: actually support such cases (need to figure out how to move from the
2616                    // capture place to original local).
2617                    && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span))
2618                {
2619                    self.res = Some((ex, closure));
2620                }
2621
2622                hir::intravisit::walk_expr(self, ex);
2623            }
2624        }
2625
2626        // Find the closure that most tightly wraps `capture_kind_span`
2627        let mut finder =
2628            ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
2629        finder.visit_expr(body_expr);
2630        let Some((closure_expr, closure)) = finder.res else { return };
2631
2632        let typeck_results = tcx.typeck(self.mir_def_id());
2633
2634        // Check that the parent of the closure is a method call,
2635        // with receiver matching with local's type (modulo refs)
2636        if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id)
2637            && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind
2638        {
2639            let recv_ty = typeck_results.expr_ty(recv);
2640
2641            if recv_ty.peel_refs() != local_ty {
2642                return;
2643            }
2644        }
2645
2646        // Get closure's arguments
2647        let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else {
2648            /* hir::Closure can be a coroutine too */
2649            return;
2650        };
2651        let sig = args.as_closure().sig();
2652        let tupled_params = tcx.instantiate_bound_regions_with_erased(
2653            sig.inputs().iter().next().unwrap().map_bound(|&b| b),
2654        );
2655        let ty::Tuple(params) = tupled_params.kind() else { return };
2656
2657        // Find the first argument with a matching type and get its identifier.
2658        let Some(this_name) = params.iter().zip(tcx.hir_body_param_idents(closure.body)).find_map(
2659            |(param_ty, ident)| {
2660                // FIXME: also support deref for stuff like `Rc` arguments
2661                if param_ty.peel_refs() == local_ty { ident } else { None }
2662            },
2663        ) else {
2664            return;
2665        };
2666
2667        let spans;
2668        if let Some((_path_expr, qpath)) = finder.error_path
2669            && let hir::QPath::Resolved(_, path) = qpath
2670            && let hir::def::Res::Local(local_id) = path.res
2671        {
2672            // Find all references to the problematic variable in this closure body
2673
2674            struct VariableUseFinder {
2675                local_id: hir::HirId,
2676                spans: Vec<Span>,
2677            }
2678            impl<'hir> Visitor<'hir> for VariableUseFinder {
2679                fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2680                    if let hir::ExprKind::Path(qpath) = &ex.kind
2681                        && let hir::QPath::Resolved(_, path) = qpath
2682                        && let hir::def::Res::Local(local_id) = path.res
2683                        && local_id == self.local_id
2684                    {
2685                        self.spans.push(ex.span);
2686                    }
2687
2688                    hir::intravisit::walk_expr(self, ex);
2689                }
2690            }
2691
2692            let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
2693            finder.visit_expr(tcx.hir_body(closure.body).value);
2694
2695            spans = finder.spans;
2696        } else {
2697            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];
2698        }
2699
2700        err.multipart_suggestion(
2701            "try using the closure argument",
2702            iter::zip(spans, iter::repeat(this_name.to_string())).collect(),
2703            Applicability::MaybeIncorrect,
2704        );
2705    }
2706
2707    fn suggest_binding_for_closure_capture_self(
2708        &self,
2709        err: &mut Diag<'_>,
2710        issued_spans: &UseSpans<'tcx>,
2711    ) {
2712        let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2713
2714        struct ExpressionFinder<'tcx> {
2715            capture_span: Span,
2716            closure_change_spans: Vec<Span> = ::alloc::vec::Vec::new()vec![],
2717            closure_arg_span: Option<Span> = None,
2718            in_closure: bool = false,
2719            suggest_arg: String = String::new(),
2720            tcx: TyCtxt<'tcx>,
2721            closure_local_id: Option<hir::HirId> = None,
2722            closure_call_changes: Vec<(Span, String)> = ::alloc::vec::Vec::new()vec![],
2723        }
2724        impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
2725            fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
2726                if e.span.contains(self.capture_span)
2727                    && let hir::ExprKind::Closure(&hir::Closure {
2728                        kind: hir::ClosureKind::Closure,
2729                        body,
2730                        fn_arg_span,
2731                        fn_decl: hir::FnDecl { inputs, .. },
2732                        ..
2733                    }) = e.kind
2734                    && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
2735                {
2736                    self.suggest_arg = "this: &Self".to_string();
2737                    if inputs.len() > 0 {
2738                        self.suggest_arg.push_str(", ");
2739                    }
2740                    self.in_closure = true;
2741                    self.closure_arg_span = fn_arg_span;
2742                    self.visit_expr(body);
2743                    self.in_closure = false;
2744                }
2745                if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
2746                    && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2747                    && seg.ident.name == kw::SelfLower
2748                    && self.in_closure
2749                {
2750                    self.closure_change_spans.push(e.span);
2751                }
2752                hir::intravisit::walk_expr(self, e);
2753            }
2754
2755            fn visit_local(&mut self, local: &'hir hir::LetStmt<'hir>) {
2756                if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
2757                    local.pat
2758                    && let Some(init) = local.init
2759                    && let &hir::Expr {
2760                        kind:
2761                            hir::ExprKind::Closure(&hir::Closure {
2762                                kind: hir::ClosureKind::Closure,
2763                                ..
2764                            }),
2765                        ..
2766                    } = init
2767                    && init.span.contains(self.capture_span)
2768                {
2769                    self.closure_local_id = Some(*hir_id);
2770                }
2771
2772                hir::intravisit::walk_local(self, local);
2773            }
2774
2775            fn visit_stmt(&mut self, s: &'hir hir::Stmt<'hir>) {
2776                if let hir::StmtKind::Semi(e) = s.kind
2777                    && let hir::ExprKind::Call(
2778                        hir::Expr { kind: hir::ExprKind::Path(path), .. },
2779                        args,
2780                    ) = e.kind
2781                    && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2782                    && let Res::Local(hir_id) = seg.res
2783                    && Some(hir_id) == self.closure_local_id
2784                {
2785                    let (span, arg_str) = if args.len() > 0 {
2786                        (args[0].span.shrink_to_lo(), "self, ".to_string())
2787                    } else {
2788                        let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
2789                        (span, "(self)".to_string())
2790                    };
2791                    self.closure_call_changes.push((span, arg_str));
2792                }
2793                hir::intravisit::walk_stmt(self, s);
2794            }
2795        }
2796
2797        if let hir::Node::ImplItem(hir::ImplItem {
2798            kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
2799            ..
2800        }) = self.infcx.tcx.hir_node(self.mir_hir_id())
2801            && let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
2802        {
2803            let mut finder =
2804                ExpressionFinder { capture_span: *capture_kind_span, tcx: self.infcx.tcx, .. };
2805            finder.visit_expr(expr);
2806
2807            if finder.closure_change_spans.is_empty() || finder.closure_call_changes.is_empty() {
2808                return;
2809            }
2810
2811            let sm = self.infcx.tcx.sess.source_map();
2812            let sugg = finder
2813                .closure_arg_span
2814                .map(|span| (sm.next_point(span.shrink_to_lo()).shrink_to_hi(), finder.suggest_arg))
2815                .into_iter()
2816                .chain(
2817                    finder.closure_change_spans.into_iter().map(|span| (span, "this".to_string())),
2818                )
2819                .chain(finder.closure_call_changes)
2820                .collect();
2821
2822            err.multipart_suggestion(
2823                "try explicitly passing `&Self` into the closure as an argument",
2824                sugg,
2825                Applicability::MachineApplicable,
2826            );
2827        }
2828    }
2829
2830    /// Returns the description of the root place for a conflicting borrow and the full
2831    /// descriptions of the places that caused the conflict.
2832    ///
2833    /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
2834    /// attempted while a shared borrow is live, then this function will return:
2835    /// ```
2836    /// ("x", "", "")
2837    /// # ;
2838    /// ```
2839    /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
2840    /// a shared borrow of another field `x.y`, then this function will return:
2841    /// ```
2842    /// ("x", "x.z", "x.y")
2843    /// # ;
2844    /// ```
2845    /// In the more complex union case, where the union is a field of a struct, then if a mutable
2846    /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
2847    /// another field `x.u.y`, then this function will return:
2848    /// ```
2849    /// ("x.u", "x.u.z", "x.u.y")
2850    /// # ;
2851    /// ```
2852    /// This is used when creating error messages like below:
2853    ///
2854    /// ```text
2855    /// cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
2856    /// mutable (via `a.u.s.b`) [E0502]
2857    /// ```
2858    fn describe_place_for_conflicting_borrow(
2859        &self,
2860        first_borrowed_place: Place<'tcx>,
2861        second_borrowed_place: Place<'tcx>,
2862    ) -> (String, String, String, String) {
2863        // Define a small closure that we can use to check if the type of a place
2864        // is a union.
2865        let union_ty = |place_base| {
2866            // Need to use fn call syntax `PlaceRef::ty` to determine the type of `place_base`;
2867            // using a type annotation in the closure argument instead leads to a lifetime error.
2868            let ty = PlaceRef::ty(&place_base, self.body, self.infcx.tcx).ty;
2869            ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
2870        };
2871
2872        // Start with an empty tuple, so we can use the functions on `Option` to reduce some
2873        // code duplication (particularly around returning an empty description in the failure
2874        // case).
2875        Some(())
2876            .filter(|_| {
2877                // If we have a conflicting borrow of the same place, then we don't want to add
2878                // an extraneous "via x.y" to our diagnostics, so filter out this case.
2879                first_borrowed_place != second_borrowed_place
2880            })
2881            .and_then(|_| {
2882                // We're going to want to traverse the first borrowed place to see if we can find
2883                // field access to a union. If we find that, then we will keep the place of the
2884                // union being accessed and the field that was being accessed so we can check the
2885                // second borrowed place for the same union and an access to a different field.
2886                for (place_base, elem) in first_borrowed_place.iter_projections().rev() {
2887                    match elem {
2888                        ProjectionElem::Field(field, _) if union_ty(place_base).is_some() => {
2889                            return Some((place_base, field));
2890                        }
2891                        _ => {}
2892                    }
2893                }
2894                None
2895            })
2896            .and_then(|(target_base, target_field)| {
2897                // With the place of a union and a field access into it, we traverse the second
2898                // borrowed place and look for an access to a different field of the same union.
2899                for (place_base, elem) in second_borrowed_place.iter_projections().rev() {
2900                    if let ProjectionElem::Field(field, _) = elem
2901                        && let Some(union_ty) = union_ty(place_base)
2902                    {
2903                        if field != target_field && place_base == target_base {
2904                            return Some((
2905                                self.describe_any_place(place_base),
2906                                self.describe_any_place(first_borrowed_place.as_ref()),
2907                                self.describe_any_place(second_borrowed_place.as_ref()),
2908                                union_ty.to_string(),
2909                            ));
2910                        }
2911                    }
2912                }
2913                None
2914            })
2915            .unwrap_or_else(|| {
2916                // If we didn't find a field access into a union, or both places match, then
2917                // only return the description of the first place.
2918                (
2919                    self.describe_any_place(first_borrowed_place.as_ref()),
2920                    "".to_string(),
2921                    "".to_string(),
2922                    "".to_string(),
2923                )
2924            })
2925    }
2926
2927    /// This means that some data referenced by `borrow` needs to live
2928    /// past the point where the StorageDeadOrDrop of `place` occurs.
2929    /// This is usually interpreted as meaning that `place` has too
2930    /// short a lifetime. (But sometimes it is more useful to report
2931    /// it as a more direct conflict between the execution of a
2932    /// `Drop::drop` with an aliasing borrow.)
2933    #[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(2933u32),
                                    ::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:2950",
                                        "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(2950u32),
                                        ::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:2986",
                                    "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(2986u32),
                                    ::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))]
2934    pub(crate) fn report_borrowed_value_does_not_live_long_enough(
2935        &mut self,
2936        location: Location,
2937        borrow: &BorrowData<'tcx>,
2938        place_span: (Place<'tcx>, Span),
2939        kind: Option<WriteKind>,
2940    ) {
2941        let drop_span = place_span.1;
2942        let borrowed_local = borrow.borrowed_place.local;
2943
2944        let borrow_spans = self.retrieve_borrow_spans(borrow);
2945        let borrow_span = borrow_spans.var_or_use_path_span();
2946
2947        let proper_span = self.body.local_decls[borrowed_local].source_info.span;
2948
2949        if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
2950            debug!(
2951                "suppressing access_place error when borrow doesn't live long enough for {:?}",
2952                borrow_span
2953            );
2954            return;
2955        }
2956
2957        self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
2958
2959        if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
2960            let err =
2961                self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
2962            self.buffer_error(err);
2963            return;
2964        }
2965
2966        if let StorageDeadOrDrop::Destructor(dropped_ty) =
2967            self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
2968        {
2969            // If a borrow of path `B` conflicts with drop of `D` (and
2970            // we're not in the uninteresting case where `B` is a
2971            // prefix of `D`), then report this as a more interesting
2972            // destructor conflict.
2973            if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
2974                self.report_borrow_conflicts_with_destructor(
2975                    location, borrow, place_span, kind, dropped_ty,
2976                );
2977                return;
2978            }
2979        }
2980
2981        let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
2982
2983        let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
2984        let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
2985
2986        debug!(?place_desc, ?explanation);
2987
2988        let mut err = match (place_desc, explanation) {
2989            // If the outlives constraint comes from inside the closure,
2990            // for example:
2991            //
2992            // let x = 0;
2993            // let y = &x;
2994            // Box::new(|| y) as Box<Fn() -> &'static i32>
2995            //
2996            // then just use the normal error. The closure isn't escaping
2997            // and `move` will not help here.
2998            (
2999                Some(name),
3000                BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
3001            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3002                .report_escaping_closure_capture(
3003                    borrow_spans,
3004                    borrow_span,
3005                    &RegionName {
3006                        name: self.synthesize_region_name(),
3007                        source: RegionNameSource::Static,
3008                    },
3009                    ConstraintCategory::CallArgument(None),
3010                    var_or_use_span,
3011                    &format!("`{name}`"),
3012                    "block",
3013                ),
3014            (
3015                Some(name),
3016                BorrowExplanation::MustBeValidFor {
3017                    category:
3018                        category @ (ConstraintCategory::Return(_)
3019                        | ConstraintCategory::CallArgument(_)
3020                        | ConstraintCategory::OpaqueType),
3021                    from_closure: false,
3022                    ref region_name,
3023                    span,
3024                    ..
3025                },
3026            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3027                .report_escaping_closure_capture(
3028                    borrow_spans,
3029                    borrow_span,
3030                    region_name,
3031                    category,
3032                    span,
3033                    &format!("`{name}`"),
3034                    "function",
3035                ),
3036            (
3037                name,
3038                BorrowExplanation::MustBeValidFor {
3039                    category: ConstraintCategory::Assignment,
3040                    from_closure: false,
3041                    region_name:
3042                        RegionName {
3043                            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
3044                            ..
3045                        },
3046                    span,
3047                    ..
3048                },
3049            ) => self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, span),
3050            (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
3051                location,
3052                &name,
3053                borrow,
3054                drop_span,
3055                borrow_spans,
3056                explanation,
3057            ),
3058            (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
3059                location,
3060                borrow,
3061                drop_span,
3062                borrow_spans,
3063                proper_span,
3064                explanation,
3065            ),
3066        };
3067        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
3068
3069        self.buffer_error(err);
3070    }
3071
3072    #[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(3072u32),
                                    ::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))]
3073    fn report_local_value_does_not_live_long_enough(
3074        &self,
3075        location: Location,
3076        name: &str,
3077        borrow: &BorrowData<'tcx>,
3078        drop_span: Span,
3079        borrow_spans: UseSpans<'tcx>,
3080        explanation: BorrowExplanation<'tcx>,
3081    ) -> Diag<'infcx> {
3082        let borrow_span = borrow_spans.var_or_use_path_span();
3083        if let BorrowExplanation::MustBeValidFor {
3084            category,
3085            span,
3086            ref opt_place_desc,
3087            from_closure: false,
3088            ..
3089        } = explanation
3090            && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3091                borrow,
3092                borrow_span,
3093                span,
3094                category,
3095                opt_place_desc.as_ref(),
3096            )
3097        {
3098            return diag;
3099        }
3100
3101        let name = format!("`{name}`");
3102
3103        let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3104
3105        if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3106            let region_name = annotation.emit(self, &mut err);
3107
3108            err.span_label(
3109                borrow_span,
3110                format!("{name} would have to be valid for `{region_name}`..."),
3111            );
3112
3113            err.span_label(
3114                drop_span,
3115                format!(
3116                    "...but {name} will be dropped here, when the {} returns",
3117                    self.infcx
3118                        .tcx
3119                        .opt_item_name(self.mir_def_id().to_def_id())
3120                        .map(|name| format!("function `{name}`"))
3121                        .unwrap_or_else(|| {
3122                            match &self.infcx.tcx.def_kind(self.mir_def_id()) {
3123                                DefKind::Closure
3124                                    if self
3125                                        .infcx
3126                                        .tcx
3127                                        .is_coroutine(self.mir_def_id().to_def_id()) =>
3128                                {
3129                                    "enclosing coroutine"
3130                                }
3131                                DefKind::Closure => "enclosing closure",
3132                                kind => bug!("expected closure or coroutine, found {:?}", kind),
3133                            }
3134                            .to_string()
3135                        })
3136                ),
3137            );
3138
3139            err.note(
3140                "functions cannot return a borrow to data owned within the function's scope, \
3141                    functions can only return borrows to data passed as arguments",
3142            );
3143            err.note(
3144                "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3145                    references-and-borrowing.html#dangling-references>",
3146            );
3147
3148            if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3149            } else {
3150                explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3151            }
3152        } else {
3153            err.span_label(borrow_span, "borrowed value does not live long enough");
3154            err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3155
3156            borrow_spans.args_subdiag(&mut err, |args_span| {
3157                crate::session_diagnostics::CaptureArgLabel::Capture {
3158                    is_within: borrow_spans.for_coroutine(),
3159                    args_span,
3160                }
3161            });
3162
3163            explanation.add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
3164
3165            // Detect buffer reuse pattern
3166            if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) = explanation {
3167                // Check all locals at the borrow location to find Vec<&T> types
3168                for (local, local_decl) in self.body.local_decls.iter_enumerated() {
3169                    if let ty::Adt(adt_def, args) = local_decl.ty.kind()
3170                        && self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
3171                        && args.len() > 0
3172                    {
3173                        let vec_inner_ty = args.type_at(0);
3174                        // Check if Vec contains references
3175                        if vec_inner_ty.is_ref() {
3176                            let local_place = local.into();
3177                            if let Some(local_name) = self.describe_place(local_place) {
3178                                err.span_label(
3179                                    local_decl.source_info.span,
3180                                    format!("variable `{local_name}` declared here"),
3181                                );
3182                                err.note(
3183                                    format!(
3184                                        "`{local_name}` is a collection that stores borrowed references, \
3185                                         but {name} does not live long enough to be stored in it"
3186                                    )
3187                                );
3188                                err.help(
3189                                    "buffer reuse with borrowed references requires unsafe code or restructuring"
3190                                );
3191                                break;
3192                            }
3193                        }
3194                    }
3195                }
3196            }
3197        }
3198
3199        err
3200    }
3201
3202    fn report_borrow_conflicts_with_destructor(
3203        &mut self,
3204        location: Location,
3205        borrow: &BorrowData<'tcx>,
3206        (place, drop_span): (Place<'tcx>, Span),
3207        kind: Option<WriteKind>,
3208        dropped_ty: Ty<'tcx>,
3209    ) {
3210        {
    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:3210",
                        "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(3210u32),
                        ::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!(
3211            "report_borrow_conflicts_with_destructor(\
3212             {:?}, {:?}, ({:?}, {:?}), {:?}\
3213             )",
3214            location, borrow, place, drop_span, kind,
3215        );
3216
3217        let borrow_spans = self.retrieve_borrow_spans(borrow);
3218        let borrow_span = borrow_spans.var_or_use();
3219
3220        let mut err = self.cannot_borrow_across_destructor(borrow_span);
3221
3222        let what_was_dropped = match self.describe_place(place.as_ref()) {
3223            Some(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"),
3224            None => String::from("temporary value"),
3225        };
3226
3227        let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3228            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!(
3229                "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3230                 because the type `{dropped_ty}` implements the `Drop` trait"
3231            ),
3232            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!(
3233                "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3234            ),
3235        };
3236        err.span_label(drop_span, label);
3237
3238        // Only give this note and suggestion if they could be relevant.
3239        let explanation =
3240            self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3241        match explanation {
3242            BorrowExplanation::UsedLater { .. }
3243            | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3244                err.note("consider using a `let` binding to create a longer lived value");
3245            }
3246            _ => {}
3247        }
3248
3249        explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3250
3251        self.buffer_error(err);
3252    }
3253
3254    fn report_thread_local_value_does_not_live_long_enough(
3255        &self,
3256        drop_span: Span,
3257        borrow_span: Span,
3258    ) -> Diag<'infcx> {
3259        {
    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:3259",
                        "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(3259u32),
                        ::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!(
3260            "report_thread_local_value_does_not_live_long_enough(\
3261             {:?}, {:?}\
3262             )",
3263            drop_span, borrow_span
3264        );
3265
3266        // `TerminatorKind::Return`'s span (the `drop_span` here) `lo` can be subtly wrong and point
3267        // at a single character after the end of the function. This is somehow relied upon in
3268        // existing diagnostics, and changing this in `rustc_mir_build` makes diagnostics worse in
3269        // general. We fix these here.
3270        let sm = self.infcx.tcx.sess.source_map();
3271        let end_of_function = if drop_span.is_empty()
3272            && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3273        {
3274            adjusted_span
3275        } else {
3276            drop_span
3277        };
3278        self.thread_local_value_does_not_live_long_enough(borrow_span)
3279            .with_span_label(
3280                borrow_span,
3281                "thread-local variables cannot be borrowed beyond the end of the function",
3282            )
3283            .with_span_label(end_of_function, "end of enclosing function is here")
3284    }
3285
3286    #[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(3286u32),
                                    ::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))]
3287    fn report_temporary_value_does_not_live_long_enough(
3288        &self,
3289        location: Location,
3290        borrow: &BorrowData<'tcx>,
3291        drop_span: Span,
3292        borrow_spans: UseSpans<'tcx>,
3293        proper_span: Span,
3294        explanation: BorrowExplanation<'tcx>,
3295    ) -> Diag<'infcx> {
3296        if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
3297            explanation
3298        {
3299            if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3300                borrow,
3301                proper_span,
3302                span,
3303                category,
3304                None,
3305            ) {
3306                return diag;
3307            }
3308        }
3309
3310        let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3311        err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3312        err.span_label(drop_span, "temporary value is freed at the end of this statement");
3313
3314        match explanation {
3315            BorrowExplanation::UsedLater(..)
3316            | BorrowExplanation::UsedLaterInLoop(..)
3317            | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3318                // Only give this note and suggestion if it could be relevant.
3319                let sm = self.infcx.tcx.sess.source_map();
3320                let mut suggested = false;
3321                let msg = "consider using a `let` binding to create a longer lived value";
3322
3323                /// We check that there's a single level of block nesting to ensure always correct
3324                /// suggestions. If we don't, then we only provide a free-form message to avoid
3325                /// misleading users in cases like `tests/ui/nll/borrowed-temporary-error.rs`.
3326                /// We could expand the analysis to suggest hoising all of the relevant parts of
3327                /// the users' code to make the code compile, but that could be too much.
3328                /// We found the `prop_expr` by the way to check whether the expression is a
3329                /// `FormatArguments`, which is a special case since it's generated by the
3330                /// compiler.
3331                struct NestedStatementVisitor<'tcx> {
3332                    span: Span,
3333                    current: usize,
3334                    found: usize,
3335                    prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3336                    call: Option<&'tcx hir::Expr<'tcx>>,
3337                }
3338
3339                impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3340                    fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3341                        self.current += 1;
3342                        walk_block(self, block);
3343                        self.current -= 1;
3344                    }
3345                    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3346                        if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3347                            if self.span == rcvr.span.source_callsite() {
3348                                self.call = Some(expr);
3349                            }
3350                        }
3351                        if self.span == expr.span.source_callsite() {
3352                            self.found = self.current;
3353                            if self.prop_expr.is_none() {
3354                                self.prop_expr = Some(expr);
3355                            }
3356                        }
3357                        walk_expr(self, expr);
3358                    }
3359                }
3360                let source_info = self.body.source_info(location);
3361                let proper_span = proper_span.source_callsite();
3362                if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3363                    && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3364                    && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3365                    && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3366                {
3367                    for stmt in block.stmts {
3368                        let mut visitor = NestedStatementVisitor {
3369                            span: proper_span,
3370                            current: 0,
3371                            found: 0,
3372                            prop_expr: None,
3373                            call: None,
3374                        };
3375                        visitor.visit_stmt(stmt);
3376
3377                        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3378                        let expr_ty: Option<Ty<'_>> =
3379                            visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3380
3381                        if visitor.found == 0
3382                            && stmt.span.contains(proper_span)
3383                            && let Some(p) = sm.span_to_margin(stmt.span)
3384                            && let Ok(s) = sm.span_to_snippet(proper_span)
3385                        {
3386                            if let Some(call) = visitor.call
3387                                && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3388                                && path.ident.name == sym::iter
3389                                && let Some(ty) = expr_ty
3390                            {
3391                                err.span_suggestion_verbose(
3392                                    path.ident.span,
3393                                    format!(
3394                                        "consider consuming the `{ty}` when turning it into an \
3395                                         `Iterator`",
3396                                    ),
3397                                    "into_iter",
3398                                    Applicability::MaybeIncorrect,
3399                                );
3400                            }
3401
3402                            let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3403                                "mut "
3404                            } else {
3405                                ""
3406                            };
3407
3408                            let addition =
3409                                format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3410                            err.multipart_suggestion(
3411                                msg,
3412                                vec![
3413                                    (stmt.span.shrink_to_lo(), addition),
3414                                    (proper_span, "binding".to_string()),
3415                                ],
3416                                Applicability::MaybeIncorrect,
3417                            );
3418
3419                            suggested = true;
3420                            break;
3421                        }
3422                    }
3423                }
3424                if !suggested {
3425                    err.note(msg);
3426                }
3427            }
3428            _ => {}
3429        }
3430        explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3431
3432        borrow_spans.args_subdiag(&mut err, |args_span| {
3433            crate::session_diagnostics::CaptureArgLabel::Capture {
3434                is_within: borrow_spans.for_coroutine(),
3435                args_span,
3436            }
3437        });
3438
3439        err
3440    }
3441
3442    fn try_report_cannot_return_reference_to_local(
3443        &self,
3444        borrow: &BorrowData<'tcx>,
3445        borrow_span: Span,
3446        return_span: Span,
3447        category: ConstraintCategory<'tcx>,
3448        opt_place_desc: Option<&String>,
3449    ) -> Result<(), Diag<'infcx>> {
3450        let return_kind = match category {
3451            ConstraintCategory::Return(_) => "return",
3452            ConstraintCategory::Yield => "yield",
3453            _ => return Ok(()),
3454        };
3455
3456        // FIXME use a better heuristic than Spans
3457        let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3458            "reference to"
3459        } else {
3460            "value referencing"
3461        };
3462
3463        let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3464            let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3465                match self.body.local_kind(local) {
3466                    LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3467                        "local variable "
3468                    }
3469                    LocalKind::Arg
3470                        if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3471                    {
3472                        "variable captured by `move` "
3473                    }
3474                    LocalKind::Arg => "function parameter ",
3475                    LocalKind::ReturnPointer | LocalKind::Temp => {
3476                        ::rustc_middle::util::bug::bug_fmt(format_args!("temporary or return pointer with a name"))bug!("temporary or return pointer with a name")
3477                    }
3478                }
3479            } else {
3480                "local data "
3481            };
3482            (::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"))
3483        } else {
3484            let local = borrow.borrowed_place.local;
3485            match self.body.local_kind(local) {
3486                LocalKind::Arg => (
3487                    "function parameter".to_string(),
3488                    "function parameter borrowed here".to_string(),
3489                ),
3490                LocalKind::Temp
3491                    if self.body.local_decls[local].is_user_variable()
3492                        && !self.body.local_decls[local]
3493                            .source_info
3494                            .span
3495                            .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3496                {
3497                    ("local binding".to_string(), "local binding introduced here".to_string())
3498                }
3499                LocalKind::ReturnPointer | LocalKind::Temp => {
3500                    ("temporary value".to_string(), "temporary value created here".to_string())
3501                }
3502            }
3503        };
3504
3505        let mut err = self.cannot_return_reference_to_local(
3506            return_span,
3507            return_kind,
3508            reference_desc,
3509            &place_desc,
3510        );
3511
3512        if return_span != borrow_span {
3513            err.span_label(borrow_span, note);
3514
3515            let tcx = self.infcx.tcx;
3516
3517            let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3518
3519            // to avoid panics
3520            if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3521                && self
3522                    .infcx
3523                    .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3524                    .must_apply_modulo_regions()
3525            {
3526                err.span_suggestion_hidden(
3527                    return_span.shrink_to_hi(),
3528                    "use `.collect()` to allocate the iterator",
3529                    ".collect::<Vec<_>>()",
3530                    Applicability::MaybeIncorrect,
3531                );
3532            }
3533
3534            if let Some(cow_did) = tcx.get_diagnostic_item(sym::Cow)
3535                && let ty::Adt(adt_def, _) = return_ty.kind()
3536                && adt_def.did() == cow_did
3537            {
3538                let typeck = tcx.typeck(self.mir_def_id());
3539                if let Some(expr) = self.find_expr(return_span)
3540                    && let Some(def_id) = typeck.type_dependent_def_id(expr.hir_id)
3541                    && tcx.is_diagnostic_item(sym::to_owned_method, def_id)
3542                    && let Some(to_owned_ident) = expr.method_ident()
3543                {
3544                    err.span_suggestion_short(
3545                        to_owned_ident.span.shrink_to_lo(),
3546                        "try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`",
3547                        "in",
3548                        Applicability::MaybeIncorrect,
3549                    );
3550                }
3551            }
3552        }
3553
3554        Err(err)
3555    }
3556
3557    #[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(3557u32),
                                    ::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))]
3558    fn report_escaping_closure_capture(
3559        &self,
3560        use_span: UseSpans<'tcx>,
3561        var_span: Span,
3562        fr_name: &RegionName,
3563        category: ConstraintCategory<'tcx>,
3564        constraint_span: Span,
3565        captured_var: &str,
3566        scope: &str,
3567    ) -> Diag<'infcx> {
3568        let tcx = self.infcx.tcx;
3569        let args_span = use_span.args_or_use();
3570
3571        let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3572            Ok(string) => {
3573                let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3574                    let trimmed_sub = sub.trim_end();
3575                    if trimmed_sub.ends_with("gen") {
3576                        // `async` is 5 chars long.
3577                        Some((trimmed_sub.len() + 5) as _)
3578                    } else {
3579                        // `async` is 5 chars long.
3580                        Some(5)
3581                    }
3582                } else if string.starts_with("gen") {
3583                    // `gen` is 3 chars long
3584                    Some(3)
3585                } else if string.starts_with("static") {
3586                    // `static` is 6 chars long
3587                    // This is used for `!Unpin` coroutines
3588                    Some(6)
3589                } else {
3590                    None
3591                };
3592                if let Some(n) = coro_prefix {
3593                    let pos = args_span.lo() + BytePos(n);
3594                    (args_span.with_lo(pos).with_hi(pos), " move")
3595                } else {
3596                    (args_span.shrink_to_lo(), "move ")
3597                }
3598            }
3599            Err(_) => (args_span, "move |<args>| <body>"),
3600        };
3601        let kind = match use_span.coroutine_kind() {
3602            Some(coroutine_kind) => match coroutine_kind {
3603                CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3604                    CoroutineSource::Block => "gen block",
3605                    CoroutineSource::Closure => "gen closure",
3606                    CoroutineSource::Fn => {
3607                        bug!("gen block/closure expected, but gen function found.")
3608                    }
3609                },
3610                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3611                    CoroutineSource::Block => "async gen block",
3612                    CoroutineSource::Closure => "async gen closure",
3613                    CoroutineSource::Fn => {
3614                        bug!("gen block/closure expected, but gen function found.")
3615                    }
3616                },
3617                CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3618                    match async_kind {
3619                        CoroutineSource::Block => "async block",
3620                        CoroutineSource::Closure => "async closure",
3621                        CoroutineSource::Fn => {
3622                            bug!("async block/closure expected, but async function found.")
3623                        }
3624                    }
3625                }
3626                CoroutineKind::Coroutine(_) => "coroutine",
3627            },
3628            None => "closure",
3629        };
3630
3631        let mut err = self.cannot_capture_in_long_lived_closure(
3632            args_span,
3633            kind,
3634            captured_var,
3635            var_span,
3636            scope,
3637        );
3638        err.span_suggestion_verbose(
3639            sugg_span,
3640            format!(
3641                "to force the {kind} to take ownership of {captured_var} (and any \
3642                 other referenced variables), use the `move` keyword"
3643            ),
3644            suggestion,
3645            Applicability::MachineApplicable,
3646        );
3647
3648        match category {
3649            ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3650                let msg = format!("{kind} is returned here");
3651                err.span_note(constraint_span, msg);
3652            }
3653            ConstraintCategory::CallArgument(_) => {
3654                fr_name.highlight_region_name(&mut err);
3655                if matches!(
3656                    use_span.coroutine_kind(),
3657                    Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3658                ) {
3659                    err.note(
3660                        "async blocks are not executed immediately and must either take a \
3661                         reference or ownership of outside variables they use",
3662                    );
3663                } else {
3664                    let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3665                    err.span_note(constraint_span, msg);
3666                }
3667            }
3668            _ => bug!(
3669                "report_escaping_closure_capture called with unexpected constraint \
3670                 category: `{:?}`",
3671                category
3672            ),
3673        }
3674
3675        err
3676    }
3677
3678    fn report_escaping_data(
3679        &self,
3680        borrow_span: Span,
3681        name: &Option<String>,
3682        upvar_span: Span,
3683        upvar_name: Symbol,
3684        escape_span: Span,
3685    ) -> Diag<'infcx> {
3686        let tcx = self.infcx.tcx;
3687
3688        let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3689
3690        let mut err =
3691            borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
3692
3693        err.span_label(
3694            upvar_span,
3695            ::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"),
3696        );
3697
3698        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"));
3699
3700        if let Some(name) = name {
3701            err.span_label(
3702                escape_span,
3703                ::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"),
3704            );
3705        } else {
3706            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"));
3707        }
3708
3709        err
3710    }
3711
3712    fn get_moved_indexes(
3713        &self,
3714        location: Location,
3715        mpi: MovePathIndex,
3716    ) -> (Vec<MoveSite>, Vec<Location>) {
3717        fn predecessor_locations<'tcx>(
3718            body: &mir::Body<'tcx>,
3719            location: Location,
3720        ) -> impl Iterator<Item = Location> {
3721            if location.statement_index == 0 {
3722                let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3723                Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3724            } else {
3725                Either::Right(std::iter::once(Location {
3726                    statement_index: location.statement_index - 1,
3727                    ..location
3728                }))
3729            }
3730        }
3731
3732        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];
3733        let move_paths = &self.move_data.move_paths;
3734        mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3735
3736        let mut stack = Vec::new();
3737        let mut back_edge_stack = Vec::new();
3738
3739        predecessor_locations(self.body, location).for_each(|predecessor| {
3740            if location.dominates(predecessor, self.dominators()) {
3741                back_edge_stack.push(predecessor)
3742            } else {
3743                stack.push(predecessor);
3744            }
3745        });
3746
3747        let mut reached_start = false;
3748
3749        /* Check if the mpi is initialized as an argument */
3750        let mut is_argument = false;
3751        for arg in self.body.args_iter() {
3752            if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3753                if mpis.contains(&path) {
3754                    is_argument = true;
3755                }
3756            }
3757        }
3758
3759        let mut visited = FxIndexSet::default();
3760        let mut move_locations = FxIndexSet::default();
3761        let mut reinits = ::alloc::vec::Vec::new()vec![];
3762        let mut result = ::alloc::vec::Vec::new()vec![];
3763
3764        let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3765            {
    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:3765",
                        "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(3765u32),
                        ::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!(
3766                "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3767                location, is_back_edge
3768            );
3769
3770            if !visited.insert(location) {
3771                return true;
3772            }
3773
3774            // check for moves
3775            let stmt_kind =
3776                self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3777            if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3778                // This analysis only tries to find moves explicitly written by the user, so we
3779                // ignore the move-outs created by `StorageDead` and at the beginning of a
3780                // function.
3781            } else {
3782                // If we are found a use of a.b.c which was in error, then we want to look for
3783                // moves not only of a.b.c but also a.b and a.
3784                //
3785                // Note that the moves data already includes "parent" paths, so we don't have to
3786                // worry about the other case: that is, if there is a move of a.b.c, it is already
3787                // marked as a move of a.b and a as well, so we will generate the correct errors
3788                // there.
3789                for moi in &self.move_data.loc_map[location] {
3790                    {
    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:3790",
                        "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(3790u32),
                        ::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);
3791                    let path = self.move_data.moves[*moi].path;
3792                    if mpis.contains(&path) {
3793                        {
    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:3793",
                        "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(3793u32),
                        ::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!(
3794                            "report_use_of_moved_or_uninitialized: found {:?}",
3795                            move_paths[path].place
3796                        );
3797                        result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3798                        move_locations.insert(location);
3799
3800                        // Strictly speaking, we could continue our DFS here. There may be
3801                        // other moves that can reach the point of error. But it is kind of
3802                        // confusing to highlight them.
3803                        //
3804                        // Example:
3805                        //
3806                        // ```
3807                        // let a = vec![];
3808                        // let b = a;
3809                        // let c = a;
3810                        // drop(a); // <-- current point of error
3811                        // ```
3812                        //
3813                        // Because we stop the DFS here, we only highlight `let c = a`,
3814                        // and not `let b = a`. We will of course also report an error at
3815                        // `let c = a` which highlights `let b = a` as the move.
3816                        return true;
3817                    }
3818                }
3819            }
3820
3821            // check for inits
3822            let mut any_match = false;
3823            for ii in &self.move_data.init_loc_map[location] {
3824                let init = self.move_data.inits[*ii];
3825                match init.kind {
3826                    InitKind::Deep | InitKind::NonPanicPathOnly => {
3827                        if mpis.contains(&init.path) {
3828                            any_match = true;
3829                        }
3830                    }
3831                    InitKind::Shallow => {
3832                        if mpi == init.path {
3833                            any_match = true;
3834                        }
3835                    }
3836                }
3837            }
3838            if any_match {
3839                reinits.push(location);
3840                return true;
3841            }
3842            false
3843        };
3844
3845        while let Some(location) = stack.pop() {
3846            if dfs_iter(&mut result, location, false) {
3847                continue;
3848            }
3849
3850            let mut has_predecessor = false;
3851            predecessor_locations(self.body, location).for_each(|predecessor| {
3852                if location.dominates(predecessor, self.dominators()) {
3853                    back_edge_stack.push(predecessor)
3854                } else {
3855                    stack.push(predecessor);
3856                }
3857                has_predecessor = true;
3858            });
3859
3860            if !has_predecessor {
3861                reached_start = true;
3862            }
3863        }
3864        if (is_argument || !reached_start) && result.is_empty() {
3865            // Process back edges (moves in future loop iterations) only if
3866            // the move path is definitely initialized upon loop entry,
3867            // to avoid spurious "in previous iteration" errors.
3868            // During DFS, if there's a path from the error back to the start
3869            // of the function with no intervening init or move, then the
3870            // move path may be uninitialized at loop entry.
3871            while let Some(location) = back_edge_stack.pop() {
3872                if dfs_iter(&mut result, location, true) {
3873                    continue;
3874                }
3875
3876                predecessor_locations(self.body, location)
3877                    .for_each(|predecessor| back_edge_stack.push(predecessor));
3878            }
3879        }
3880
3881        // Check if we can reach these reinits from a move location.
3882        let reinits_reachable = reinits
3883            .into_iter()
3884            .filter(|reinit| {
3885                let mut visited = FxIndexSet::default();
3886                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];
3887                while let Some(location) = stack.pop() {
3888                    if !visited.insert(location) {
3889                        continue;
3890                    }
3891                    if move_locations.contains(&location) {
3892                        return true;
3893                    }
3894                    stack.extend(predecessor_locations(self.body, location));
3895                }
3896                false
3897            })
3898            .collect::<Vec<Location>>();
3899        (result, reinits_reachable)
3900    }
3901
3902    pub(crate) fn report_illegal_mutation_of_borrowed(
3903        &mut self,
3904        location: Location,
3905        (place, span): (Place<'tcx>, Span),
3906        loan: &BorrowData<'tcx>,
3907    ) {
3908        let loan_spans = self.retrieve_borrow_spans(loan);
3909        let loan_span = loan_spans.args_or_use();
3910
3911        let descr_place = self.describe_any_place(place.as_ref());
3912        if let BorrowKind::Fake(_) = loan.kind
3913            && let Some(section) = self.classify_immutable_section(loan.assigned_place)
3914        {
3915            let mut err = self.cannot_mutate_in_immutable_section(
3916                span,
3917                loan_span,
3918                &descr_place,
3919                section,
3920                "assign",
3921            );
3922
3923            loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3924                use crate::session_diagnostics::CaptureVarCause::*;
3925                match kind {
3926                    hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3927                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3928                        BorrowUseInClosure { var_span }
3929                    }
3930                }
3931            });
3932
3933            self.buffer_error(err);
3934
3935            return;
3936        }
3937
3938        let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
3939        self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
3940
3941        loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3942            use crate::session_diagnostics::CaptureVarCause::*;
3943            match kind {
3944                hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3945                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3946                    BorrowUseInClosure { var_span }
3947                }
3948            }
3949        });
3950
3951        self.explain_why_borrow_contains_point(location, loan, None)
3952            .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3953
3954        self.explain_deref_coercion(loan, &mut err);
3955
3956        self.buffer_error(err);
3957    }
3958
3959    fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
3960        let tcx = self.infcx.tcx;
3961        if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
3962            &self.body[loan.reserve_location.block].terminator
3963            && let Some((method_did, method_args)) = mir::find_self_call(
3964                tcx,
3965                self.body,
3966                loan.assigned_place.local,
3967                loan.reserve_location.block,
3968            )
3969            && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
3970                self.infcx.tcx,
3971                self.infcx.typing_env(self.infcx.param_env),
3972                method_did,
3973                method_args,
3974                *fn_span,
3975                call_source.from_hir_call(),
3976                self.infcx.tcx.fn_arg_idents(method_did)[0],
3977            )
3978        {
3979            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}`"));
3980            if let Some(deref_target_span) = deref_target_span {
3981                err.span_note(deref_target_span, "deref defined here");
3982            }
3983        }
3984    }
3985
3986    /// Reports an illegal reassignment; for example, an assignment to
3987    /// (part of) a non-`mut` local that occurs potentially after that
3988    /// local has already been initialized. `place` is the path being
3989    /// assigned; `err_place` is a place providing a reason why
3990    /// `place` is not mutable (e.g., the non-`mut` local `x` in an
3991    /// assignment to `x.f`).
3992    pub(crate) fn report_illegal_reassignment(
3993        &mut self,
3994        (place, span): (Place<'tcx>, Span),
3995        assigned_span: Span,
3996        err_place: Place<'tcx>,
3997    ) {
3998        let (from_arg, local_decl) = match err_place.as_local() {
3999            Some(local) => {
4000                (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
4001            }
4002            None => (false, None),
4003        };
4004
4005        // If root local is initialized immediately (everything apart from let
4006        // PATTERN;) then make the error refer to that local, rather than the
4007        // place being assigned later.
4008        let (place_description, assigned_span) = match local_decl {
4009            Some(LocalDecl {
4010                local_info:
4011                    ClearCrossCrate::Set(
4012                        box LocalInfo::User(BindingForm::Var(VarBindingForm {
4013                            opt_match_place: None,
4014                            ..
4015                        }))
4016                        | box LocalInfo::StaticRef { .. }
4017                        | box LocalInfo::Boring,
4018                    ),
4019                ..
4020            })
4021            | None => (self.describe_any_place(place.as_ref()), assigned_span),
4022            Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
4023        };
4024        let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
4025        let msg = if from_arg {
4026            "cannot assign to immutable argument"
4027        } else {
4028            "cannot assign twice to immutable variable"
4029        };
4030        if span != assigned_span && !from_arg {
4031            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}"));
4032        }
4033        if let Some(decl) = local_decl
4034            && decl.can_be_made_mutable()
4035        {
4036            let mut is_for_loop = false;
4037            let mut is_ref_pattern = false;
4038            if let LocalInfo::User(BindingForm::Var(VarBindingForm {
4039                opt_match_place: Some((_, match_span)),
4040                ..
4041            })) = *decl.local_info()
4042            {
4043                if #[allow(non_exhaustive_omitted_patterns)] match match_span.desugaring_kind() {
    Some(DesugaringKind::ForLoop) => true,
    _ => false,
}matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop)) {
4044                    is_for_loop = true;
4045
4046                    if let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
4047                        struct RefPatternFinder<'tcx> {
4048                            tcx: TyCtxt<'tcx>,
4049                            binding_span: Span,
4050                            is_ref_pattern: bool,
4051                        }
4052
4053                        impl<'tcx> Visitor<'tcx> for RefPatternFinder<'tcx> {
4054                            type NestedFilter = OnlyBodies;
4055
4056                            fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
4057                                self.tcx
4058                            }
4059
4060                            fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
4061                                if !self.is_ref_pattern
4062                                    && let hir::PatKind::Binding(_, _, ident, _) = pat.kind
4063                                    && ident.span == self.binding_span
4064                                {
4065                                    self.is_ref_pattern =
4066                                        self.tcx.hir_parent_iter(pat.hir_id).any(|(_, node)| {
4067                                            #[allow(non_exhaustive_omitted_patterns)] match node {
    hir::Node::Pat(hir::Pat { kind: hir::PatKind::Ref(..), .. }) => true,
    _ => false,
}matches!(
4068                                                node,
4069                                                hir::Node::Pat(hir::Pat {
4070                                                    kind: hir::PatKind::Ref(..),
4071                                                    ..
4072                                                })
4073                                            )
4074                                        });
4075                                }
4076                                hir::intravisit::walk_pat(self, pat);
4077                            }
4078                        }
4079
4080                        let mut finder = RefPatternFinder {
4081                            tcx: self.infcx.tcx,
4082                            binding_span: decl.source_info.span,
4083                            is_ref_pattern: false,
4084                        };
4085
4086                        finder.visit_body(body);
4087                        is_ref_pattern = finder.is_ref_pattern;
4088                    }
4089                }
4090            }
4091
4092            let (span, message) = if is_for_loop
4093                && is_ref_pattern
4094                && let Ok(binding_name) =
4095                    self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
4096            {
4097                (decl.source_info.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("(mut {0})", binding_name))
    })format!("(mut {})", binding_name))
4098            } else {
4099                (decl.source_info.span.shrink_to_lo(), "mut ".to_string())
4100            };
4101
4102            err.span_suggestion_verbose(
4103                span,
4104                "consider making this binding mutable",
4105                message,
4106                Applicability::MachineApplicable,
4107            );
4108
4109            if !from_arg
4110                && !is_for_loop
4111                && #[allow(non_exhaustive_omitted_patterns)] match decl.local_info() {
    LocalInfo::User(BindingForm::Var(VarBindingForm {
        opt_match_place: Some((Some(_), _)), .. })) => true,
    _ => false,
}matches!(
4112                    decl.local_info(),
4113                    LocalInfo::User(BindingForm::Var(VarBindingForm {
4114                        opt_match_place: Some((Some(_), _)),
4115                        ..
4116                    }))
4117                )
4118            {
4119                err.span_suggestion_verbose(
4120                    decl.source_info.span.shrink_to_lo(),
4121                    "to modify the original value, take a borrow instead",
4122                    "ref mut ".to_string(),
4123                    Applicability::MaybeIncorrect,
4124                );
4125            }
4126        }
4127        err.span_label(span, msg);
4128        self.buffer_error(err);
4129    }
4130
4131    fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
4132        let tcx = self.infcx.tcx;
4133        let (kind, _place_ty) = place.projection.iter().fold(
4134            (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
4135            |(kind, place_ty), &elem| {
4136                (
4137                    match elem {
4138                        ProjectionElem::Deref => match kind {
4139                            StorageDeadOrDrop::LocalStorageDead
4140                            | StorageDeadOrDrop::BoxedStorageDead => {
4141                                if !place_ty.ty.is_box() {
    {
        ::core::panicking::panic_fmt(format_args!("Drop of value behind a reference or raw pointer"));
    }
};assert!(
4142                                    place_ty.ty.is_box(),
4143                                    "Drop of value behind a reference or raw pointer"
4144                                );
4145                                StorageDeadOrDrop::BoxedStorageDead
4146                            }
4147                            StorageDeadOrDrop::Destructor(_) => kind,
4148                        },
4149                        ProjectionElem::OpaqueCast { .. }
4150                        | ProjectionElem::Field(..)
4151                        | ProjectionElem::Downcast(..) => {
4152                            match place_ty.ty.kind() {
4153                                ty::Adt(def, _) if def.has_dtor(tcx) => {
4154                                    // Report the outermost adt with a destructor
4155                                    match kind {
4156                                        StorageDeadOrDrop::Destructor(_) => kind,
4157                                        StorageDeadOrDrop::LocalStorageDead
4158                                        | StorageDeadOrDrop::BoxedStorageDead => {
4159                                            StorageDeadOrDrop::Destructor(place_ty.ty)
4160                                        }
4161                                    }
4162                                }
4163                                _ => kind,
4164                            }
4165                        }
4166                        ProjectionElem::ConstantIndex { .. }
4167                        | ProjectionElem::Subslice { .. }
4168                        | ProjectionElem::Index(_)
4169                        | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
4170                    },
4171                    place_ty.projection_ty(tcx, elem),
4172                )
4173            },
4174        );
4175        kind
4176    }
4177
4178    /// Describe the reason for the fake borrow that was assigned to `place`.
4179    fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
4180        use rustc_middle::mir::visit::Visitor;
4181        struct FakeReadCauseFinder<'tcx> {
4182            place: Place<'tcx>,
4183            cause: Option<FakeReadCause>,
4184        }
4185        impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
4186            fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
4187                match statement {
4188                    Statement { kind: StatementKind::FakeRead(box (cause, place)), .. }
4189                        if *place == self.place =>
4190                    {
4191                        self.cause = Some(*cause);
4192                    }
4193                    _ => (),
4194                }
4195            }
4196        }
4197        let mut visitor = FakeReadCauseFinder { place, cause: None };
4198        visitor.visit_body(self.body);
4199        match visitor.cause {
4200            Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
4201            Some(FakeReadCause::ForIndex) => Some("indexing expression"),
4202            _ => None,
4203        }
4204    }
4205
4206    /// Annotate argument and return type of function and closure with (synthesized) lifetime for
4207    /// borrow of local value that does not live long enough.
4208    fn annotate_argument_and_return_for_borrow(
4209        &self,
4210        borrow: &BorrowData<'tcx>,
4211    ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4212        // Define a fallback for when we can't match a closure.
4213        let fallback = || {
4214            let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
4215            if is_closure {
4216                None
4217            } else {
4218                let ty = self
4219                    .infcx
4220                    .tcx
4221                    .type_of(self.mir_def_id())
4222                    .instantiate_identity()
4223                    .skip_norm_wip();
4224                match ty.kind() {
4225                    ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
4226                        self.mir_def_id(),
4227                        self.infcx
4228                            .tcx
4229                            .fn_sig(self.mir_def_id())
4230                            .instantiate_identity()
4231                            .skip_norm_wip(),
4232                    ),
4233                    _ => None,
4234                }
4235            }
4236        };
4237
4238        // In order to determine whether we need to annotate, we need to check whether the reserve
4239        // place was an assignment into a temporary.
4240        //
4241        // If it was, we check whether or not that temporary is eventually assigned into the return
4242        // place. If it was, we can add annotations about the function's return type and arguments
4243        // and it'll make sense.
4244        let location = borrow.reserve_location;
4245        {
    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:4245",
                        "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(4245u32),
                        ::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);
4246        if let Some(Statement { kind: StatementKind::Assign(box (reservation, _)), .. }) =
4247            &self.body[location.block].statements.get(location.statement_index)
4248        {
4249            {
    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:4249",
                        "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(4249u32),
                        ::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);
4250            // Check that the initial assignment of the reserve location is into a temporary.
4251            let mut target = match reservation.as_local() {
4252                Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4253                _ => return None,
4254            };
4255
4256            // Next, look through the rest of the block, checking if we are assigning the
4257            // `target` (that is, the place that contains our borrow) to anything.
4258            let mut annotated_closure = None;
4259            for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4260                {
    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:4260",
                        "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(4260u32),
                        ::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!(
4261                    "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4262                    target, stmt
4263                );
4264                if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind
4265                    && let Some(assigned_to) = place.as_local()
4266                {
4267                    {
    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:4267",
                        "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(4267u32),
                        ::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!(
4268                        "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4269                             rvalue={:?}",
4270                        assigned_to, rvalue
4271                    );
4272                    // Check if our `target` was captured by a closure.
4273                    if let Rvalue::Aggregate(box AggregateKind::Closure(def_id, args), operands) =
4274                        rvalue
4275                    {
4276                        let def_id = def_id.expect_local();
4277                        for operand in operands {
4278                            let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4279                                operand
4280                            else {
4281                                continue;
4282                            };
4283                            {
    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:4283",
                        "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(4283u32),
                        ::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!(
4284                                "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4285                                assigned_from
4286                            );
4287
4288                            // Find the local from the operand.
4289                            let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4290                            else {
4291                                continue;
4292                            };
4293
4294                            if assigned_from_local != target {
4295                                continue;
4296                            }
4297
4298                            // If a closure captured our `target` and then assigned
4299                            // into a place then we should annotate the closure in
4300                            // case it ends up being assigned into the return place.
4301                            annotated_closure =
4302                                self.annotate_fn_sig(def_id, args.as_closure().sig());
4303                            {
    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:4303",
                        "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(4303u32),
                        ::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!(
4304                                "annotate_argument_and_return_for_borrow: \
4305                                     annotated_closure={:?} assigned_from_local={:?} \
4306                                     assigned_to={:?}",
4307                                annotated_closure, assigned_from_local, assigned_to
4308                            );
4309
4310                            if assigned_to == mir::RETURN_PLACE {
4311                                // If it was assigned directly into the return place, then
4312                                // return now.
4313                                return annotated_closure;
4314                            } else {
4315                                // Otherwise, update the target.
4316                                target = assigned_to;
4317                            }
4318                        }
4319
4320                        // If none of our closure's operands matched, then skip to the next
4321                        // statement.
4322                        continue;
4323                    }
4324
4325                    // Otherwise, look at other types of assignment.
4326                    let assigned_from = match rvalue {
4327                        Rvalue::Ref(_, _, assigned_from) => assigned_from,
4328                        Rvalue::Use(operand, _) => match operand {
4329                            Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4330                                assigned_from
4331                            }
4332                            _ => continue,
4333                        },
4334                        _ => continue,
4335                    };
4336                    {
    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:4336",
                        "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(4336u32),
                        ::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!(
4337                        "annotate_argument_and_return_for_borrow: \
4338                             assigned_from={:?}",
4339                        assigned_from,
4340                    );
4341
4342                    // Find the local from the rvalue.
4343                    let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4344                        continue;
4345                    };
4346                    {
    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:4346",
                        "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(4346u32),
                        ::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!(
4347                        "annotate_argument_and_return_for_borrow: \
4348                             assigned_from_local={:?}",
4349                        assigned_from_local,
4350                    );
4351
4352                    // Check if our local matches the target - if so, we've assigned our
4353                    // borrow to a new place.
4354                    if assigned_from_local != target {
4355                        continue;
4356                    }
4357
4358                    // If we assigned our `target` into a new place, then we should
4359                    // check if it was the return place.
4360                    {
    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:4360",
                        "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(4360u32),
                        ::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!(
4361                        "annotate_argument_and_return_for_borrow: \
4362                             assigned_from_local={:?} assigned_to={:?}",
4363                        assigned_from_local, assigned_to
4364                    );
4365                    if assigned_to == mir::RETURN_PLACE {
4366                        // If it was then return the annotated closure if there was one,
4367                        // else, annotate this function.
4368                        return annotated_closure.or_else(fallback);
4369                    }
4370
4371                    // If we didn't assign into the return place, then we just update
4372                    // the target.
4373                    target = assigned_to;
4374                }
4375            }
4376
4377            // Check the terminator if we didn't find anything in the statements.
4378            let terminator = &self.body[location.block].terminator();
4379            {
    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:4379",
                        "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(4379u32),
                        ::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!(
4380                "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4381                target, terminator
4382            );
4383            if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4384                &terminator.kind
4385                && let Some(assigned_to) = destination.as_local()
4386            {
4387                {
    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:4387",
                        "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(4387u32),
                        ::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!(
4388                    "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4389                    assigned_to, args
4390                );
4391                for operand in args {
4392                    let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4393                        &operand.node
4394                    else {
4395                        continue;
4396                    };
4397                    {
    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:4397",
                        "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(4397u32),
                        ::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!(
4398                        "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4399                        assigned_from,
4400                    );
4401
4402                    if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4403                        {
    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:4403",
                        "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(4403u32),
                        ::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!(
4404                            "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4405                            assigned_from_local,
4406                        );
4407
4408                        if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4409                            return annotated_closure.or_else(fallback);
4410                        }
4411                    }
4412                }
4413            }
4414        }
4415
4416        // If we haven't found an assignment into the return place, then we need not add
4417        // any annotations.
4418        {
    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:4418",
                        "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(4418u32),
                        ::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");
4419        None
4420    }
4421
4422    /// Annotate the first argument and return type of a function signature if they are
4423    /// references.
4424    fn annotate_fn_sig(
4425        &self,
4426        did: LocalDefId,
4427        sig: ty::PolyFnSig<'tcx>,
4428    ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4429        {
    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:4429",
                        "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(4429u32),
                        ::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);
4430        let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4431        let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4432        let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4433
4434        // We need to work out which arguments to highlight. We do this by looking
4435        // at the return type, where there are three cases:
4436        //
4437        // 1. If there are named arguments, then we should highlight the return type and
4438        //    highlight any of the arguments that are also references with that lifetime.
4439        //    If there are no arguments that have the same lifetime as the return type,
4440        //    then don't highlight anything.
4441        // 2. The return type is a reference with an anonymous lifetime. If this is
4442        //    the case, then we can take advantage of (and teach) the lifetime elision
4443        //    rules.
4444        //
4445        //    We know that an error is being reported. So the arguments and return type
4446        //    must satisfy the elision rules. Therefore, if there is a single argument
4447        //    then that means the return type and first (and only) argument have the same
4448        //    lifetime and the borrow isn't meeting that, we can highlight the argument
4449        //    and return type.
4450        //
4451        //    If there are multiple arguments then the first argument must be self (else
4452        //    it would not satisfy the elision rules), so we can highlight self and the
4453        //    return type.
4454        // 3. The return type is not a reference. In this case, we don't highlight
4455        //    anything.
4456        let return_ty = sig.output();
4457        match return_ty.skip_binder().kind() {
4458            ty::Ref(return_region, _, _)
4459                if return_region.is_named(self.infcx.tcx) && !is_closure =>
4460            {
4461                // This is case 1 from above, return type is a named reference so we need to
4462                // search for relevant arguments.
4463                let mut arguments = Vec::new();
4464                for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4465                    if let ty::Ref(argument_region, _, _) = argument.kind()
4466                        && argument_region == return_region
4467                    {
4468                        // Need to use the `rustc_middle::ty` types to compare against the
4469                        // `return_region`. Then use the `rustc_hir` type to get only
4470                        // the lifetime span.
4471                        match &fn_decl.inputs[index].kind {
4472                            hir::TyKind::Ref(lifetime, _) => {
4473                                // With access to the lifetime, we can get
4474                                // the span of it.
4475                                arguments.push((*argument, lifetime.ident.span));
4476                            }
4477                            // Resolve `self` whose self type is `&T`.
4478                            hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4479                                if let Res::SelfTyAlias { alias_to, .. } = path.res
4480                                    && let Some(alias_to) = alias_to.as_local()
4481                                    && let hir::Impl { self_ty, .. } = self
4482                                        .infcx
4483                                        .tcx
4484                                        .hir_node_by_def_id(alias_to)
4485                                        .expect_item()
4486                                        .expect_impl()
4487                                    && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4488                                {
4489                                    arguments.push((*argument, lifetime.ident.span));
4490                                }
4491                            }
4492                            _ => {
4493                                // Don't ICE though. It might be a type alias.
4494                            }
4495                        }
4496                    }
4497                }
4498
4499                // We need to have arguments. This shouldn't happen, but it's worth checking.
4500                if arguments.is_empty() {
4501                    return None;
4502                }
4503
4504                // We use a mix of the HIR and the Ty types to get information
4505                // as the HIR doesn't have full types for closure arguments.
4506                let return_ty = sig.output().skip_binder();
4507                let mut return_span = fn_decl.output.span();
4508                if let hir::FnRetTy::Return(ty) = &fn_decl.output
4509                    && let hir::TyKind::Ref(lifetime, _) = ty.kind
4510                {
4511                    return_span = lifetime.ident.span;
4512                }
4513
4514                Some(AnnotatedBorrowFnSignature::NamedFunction {
4515                    arguments,
4516                    return_ty,
4517                    return_span,
4518                })
4519            }
4520            ty::Ref(_, _, _) if is_closure => {
4521                // This is case 2 from above but only for closures, return type is anonymous
4522                // reference so we select
4523                // the first argument.
4524                let argument_span = fn_decl.inputs.first()?.span;
4525                let argument_ty = sig.inputs().skip_binder().first()?;
4526
4527                // Closure arguments are wrapped in a tuple, so we need to get the first
4528                // from that.
4529                if let ty::Tuple(elems) = argument_ty.kind() {
4530                    let &argument_ty = elems.first()?;
4531                    if let ty::Ref(_, _, _) = argument_ty.kind() {
4532                        return Some(AnnotatedBorrowFnSignature::Closure {
4533                            argument_ty,
4534                            argument_span,
4535                        });
4536                    }
4537                }
4538
4539                None
4540            }
4541            ty::Ref(_, _, _) => {
4542                // This is also case 2 from above but for functions, return type is still an
4543                // anonymous reference so we select the first argument.
4544                let argument_span = fn_decl.inputs.first()?.span;
4545                let argument_ty = *sig.inputs().skip_binder().first()?;
4546
4547                let return_span = fn_decl.output.span();
4548                let return_ty = sig.output().skip_binder();
4549
4550                // We expect the first argument to be a reference.
4551                match argument_ty.kind() {
4552                    ty::Ref(_, _, _) => {}
4553                    _ => return None,
4554                }
4555
4556                Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4557                    argument_ty,
4558                    argument_span,
4559                    return_ty,
4560                    return_span,
4561                })
4562            }
4563            _ => {
4564                // This is case 3 from above, return type is not a reference so don't highlight
4565                // anything.
4566                None
4567            }
4568        }
4569    }
4570}
4571
4572#[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)]
4573enum AnnotatedBorrowFnSignature<'tcx> {
4574    NamedFunction {
4575        arguments: Vec<(Ty<'tcx>, Span)>,
4576        return_ty: Ty<'tcx>,
4577        return_span: Span,
4578    },
4579    AnonymousFunction {
4580        argument_ty: Ty<'tcx>,
4581        argument_span: Span,
4582        return_ty: Ty<'tcx>,
4583        return_span: Span,
4584    },
4585    Closure {
4586        argument_ty: Ty<'tcx>,
4587        argument_span: Span,
4588    },
4589}
4590
4591impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4592    /// Annotate the provided diagnostic with information about borrow from the fn signature that
4593    /// helps explain.
4594    pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4595        match self {
4596            &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4597                diag.span_label(
4598                    argument_span,
4599                    ::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)),
4600                );
4601
4602                cx.get_region_name_for_ty(argument_ty, 0)
4603            }
4604            &AnnotatedBorrowFnSignature::AnonymousFunction {
4605                argument_ty,
4606                argument_span,
4607                return_ty,
4608                return_span,
4609            } => {
4610                let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4611                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}`"));
4612
4613                let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4614                let types_equal = return_ty_name == argument_ty_name;
4615                diag.span_label(
4616                    return_span,
4617                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}has type `{1}`",
                if types_equal { "also " } else { "" }, return_ty_name))
    })format!(
4618                        "{}has type `{}`",
4619                        if types_equal { "also " } else { "" },
4620                        return_ty_name,
4621                    ),
4622                );
4623
4624                diag.note(
4625                    "argument and return type have the same lifetime due to lifetime elision rules",
4626                );
4627                diag.note(
4628                    "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4629                     lifetime-syntax.html#lifetime-elision>",
4630                );
4631
4632                cx.get_region_name_for_ty(return_ty, 0)
4633            }
4634            AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4635                // Region of return type and arguments checked to be the same earlier.
4636                let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4637                for (_, argument_span) in arguments {
4638                    diag.span_label(*argument_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("has lifetime `{0}`", region_name))
    })format!("has lifetime `{region_name}`"));
4639                }
4640
4641                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}`",));
4642
4643                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!(
4644                    "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4645                     the return type",
4646                ));
4647
4648                region_name
4649            }
4650        }
4651    }
4652}
4653
4654/// Detect whether one of the provided spans is a statement nested within the top-most visited expr
4655struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4656
4657impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4658    type Result = ControlFlow<()>;
4659    fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4660        match s.kind {
4661            hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4662            _ => ControlFlow::Continue(()),
4663        }
4664    }
4665}
4666
4667/// Look for `break` expressions within any arbitrary expressions. We'll do this to infer
4668/// whether this is a case where the moved value would affect the exit of a loop, making it
4669/// unsuitable for a `.clone()` suggestion.
4670struct BreakFinder {
4671    found_breaks: Vec<(hir::Destination, Span)>,
4672    found_continues: Vec<(hir::Destination, Span)>,
4673}
4674impl<'hir> Visitor<'hir> for BreakFinder {
4675    fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4676        match ex.kind {
4677            hir::ExprKind::Break(destination, _)
4678                if !ex.span.is_desugaring(DesugaringKind::ForLoop) =>
4679            {
4680                self.found_breaks.push((destination, ex.span));
4681            }
4682            hir::ExprKind::Continue(destination) => {
4683                self.found_continues.push((destination, ex.span));
4684            }
4685            _ => {}
4686        }
4687        hir::intravisit::walk_expr(self, ex);
4688    }
4689}
4690
4691/// Given a set of spans representing statements initializing the relevant binding, visit all the
4692/// function expressions looking for branching code paths that *do not* initialize the binding.
4693struct ConditionVisitor<'tcx> {
4694    tcx: TyCtxt<'tcx>,
4695    spans: Vec<Span>,
4696    name: String,
4697    errors: Vec<(Span, String)>,
4698}
4699
4700impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4701    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4702        match ex.kind {
4703            hir::ExprKind::If(cond, body, None) => {
4704                // `if` expressions with no `else` that initialize the binding might be missing an
4705                // `else` arm.
4706                if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4707                    self.errors.push((
4708                        cond.span,
4709                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this `if` condition is `false`, {0} is not initialized",
                self.name))
    })format!(
4710                            "if this `if` condition is `false`, {} is not initialized",
4711                            self.name,
4712                        ),
4713                    ));
4714                    self.errors.push((
4715                        ex.span.shrink_to_hi(),
4716                        ::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),
4717                    ));
4718                }
4719            }
4720            hir::ExprKind::If(cond, body, Some(other)) => {
4721                // `if` expressions where the binding is only initialized in one of the two arms
4722                // might be missing a binding initialization.
4723                let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4724                let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4725                match (a, b) {
4726                    (true, true) | (false, false) => {}
4727                    (true, false) => {
4728                        if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4729                            self.errors.push((
4730                                cond.span,
4731                                ::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!(
4732                                    "if this condition isn't met and the `while` loop runs 0 \
4733                                     times, {} is not initialized",
4734                                    self.name
4735                                ),
4736                            ));
4737                        } else {
4738                            self.errors.push((
4739                                body.span.shrink_to_hi().until(other.span),
4740                                ::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!(
4741                                    "if the `if` condition is `false` and this `else` arm is \
4742                                     executed, {} is not initialized",
4743                                    self.name
4744                                ),
4745                            ));
4746                        }
4747                    }
4748                    (false, true) => {
4749                        self.errors.push((
4750                            cond.span,
4751                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this condition is `true`, {0} is not initialized",
                self.name))
    })format!(
4752                                "if this condition is `true`, {} is not initialized",
4753                                self.name
4754                            ),
4755                        ));
4756                    }
4757                }
4758            }
4759            hir::ExprKind::Match(e, arms, loop_desugar) => {
4760                // If the binding is initialized in one of the match arms, then the other match
4761                // arms might be missing an initialization.
4762                let results: Vec<bool> = arms
4763                    .iter()
4764                    .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4765                    .collect();
4766                if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4767                    for (arm, seen) in arms.iter().zip(results) {
4768                        if !seen {
4769                            if loop_desugar == hir::MatchSource::ForLoopDesugar {
4770                                self.errors.push((
4771                                    e.span,
4772                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if the `for` loop runs 0 times, {0} is not initialized",
                self.name))
    })format!(
4773                                        "if the `for` loop runs 0 times, {} is not initialized",
4774                                        self.name
4775                                    ),
4776                                ));
4777                            } else if let Some(guard) = &arm.guard {
4778                                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!(
4779                                    self.tcx.hir_node(arm.body.hir_id),
4780                                    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4781                                ) {
4782                                    continue;
4783                                }
4784                                self.errors.push((
4785                                    arm.pat.span.to(guard.span),
4786                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this pattern and condition are matched, {0} is not initialized",
                self.name))
    })format!(
4787                                        "if this pattern and condition are matched, {} is not \
4788                                         initialized",
4789                                        self.name
4790                                    ),
4791                                ));
4792                            } else {
4793                                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!(
4794                                    self.tcx.hir_node(arm.body.hir_id),
4795                                    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4796                                ) {
4797                                    continue;
4798                                }
4799                                self.errors.push((
4800                                    arm.pat.span,
4801                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if this pattern is matched, {0} is not initialized",
                self.name))
    })format!(
4802                                        "if this pattern is matched, {} is not initialized",
4803                                        self.name
4804                                    ),
4805                                ));
4806                            }
4807                        }
4808                    }
4809                }
4810            }
4811            // FIXME: should we also account for binops, particularly `&&` and `||`? `try` should
4812            // also be accounted for. For now it is fine, as if we don't find *any* relevant
4813            // branching code paths, we point at the places where the binding *is* initialized for
4814            // *some* context.
4815            _ => {}
4816        }
4817        walk_expr(self, ex);
4818    }
4819}