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