Skip to main content

rustc_borrowck/diagnostics/
conflict_errors.rs

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