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