Skip to main content

rustc_borrowck/diagnostics/
conflict_errors.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let drop_span = place_span.1;
            let borrowed_local = borrow.borrowed_place.local;
            let borrow_spans = self.retrieve_borrow_spans(borrow);
            let borrow_span = borrow_spans.var_or_use_path_span();
            let proper_span =
                self.body.local_decls[borrowed_local].source_info.span;
            if self.access_place_error_reported.contains(&(Place::from(borrowed_local),
                            borrow_span)) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2958",
                                        "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(2958u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("suppressing access_place error when borrow doesn\'t live long enough for {0:?}",
                                                                    borrow_span) as &dyn Value))])
                            });
                    } else { ; }
                };
                return;
            }
            self.access_place_error_reported.insert((Place::from(borrowed_local),
                    borrow_span));
            if self.body.local_decls[borrowed_local].is_ref_to_thread_local()
                {
                let err =
                    self.report_thread_local_value_does_not_live_long_enough(drop_span,
                        borrow_span);
                self.buffer_error(err);
                return;
            }
            if let StorageDeadOrDrop::Destructor(dropped_ty) =
                    self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
                {
                if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref())
                    {
                    self.report_borrow_conflicts_with_destructor(location,
                        borrow, place_span, kind, dropped_ty);
                    return;
                }
            }
            let place_desc =
                self.describe_place(borrow.borrowed_place.as_ref());
            let kind_place =
                kind.filter(|_|
                            place_desc.is_some()).map(|k| (k, place_span.0));
            let explanation =
                self.explain_why_borrow_contains_point(location, borrow,
                    kind_place);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:2994",
                                    "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(2994u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["place_desc",
                                                    "explanation"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&place_desc)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&explanation)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let mut err =
                match (place_desc, explanation) {
                    (Some(name),
                        BorrowExplanation::UsedLater(_,
                        LaterUseKind::ClosureCapture, var_or_use_span, _)) if
                        borrow_spans.for_coroutine() || borrow_spans.for_closure()
                        =>
                        self.report_escaping_closure_capture(borrow_spans,
                            borrow_span,
                            &RegionName {
                                    name: self.synthesize_region_name(),
                                    source: RegionNameSource::Static,
                                }, ConstraintCategory::CallArgument(None), var_or_use_span,
                            &::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", name))
                                    }), "block"),
                    (Some(name), BorrowExplanation::MustBeValidFor {
                        category: category
                            @
                            (ConstraintCategory::Return(_) |
                            ConstraintCategory::CallArgument(_) |
                            ConstraintCategory::OpaqueType),
                        from_closure: false,
                        ref region_name,
                        span, .. }) if
                        borrow_spans.for_coroutine() || borrow_spans.for_closure()
                        =>
                        self.report_escaping_closure_capture(borrow_spans,
                            borrow_span, region_name, category, span,
                            &::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", name))
                                    }), "function"),
                    (name, BorrowExplanation::MustBeValidFor {
                        category: ConstraintCategory::Assignment,
                        from_closure: false,
                        region_name: RegionName {
                            source: RegionNameSource::AnonRegionFromUpvar(upvar_span,
                                upvar_name),
                            ..
                            },
                        span, .. }) =>
                        self.report_escaping_data(borrow_span, &name, upvar_span,
                            upvar_name, span),
                    (Some(name), explanation) =>
                        self.report_local_value_does_not_live_long_enough(location,
                            &name, borrow, drop_span, borrow_spans, explanation),
                    (None, explanation) =>
                        self.report_temporary_value_does_not_live_long_enough(location,
                            borrow, drop_span, borrow_spans, proper_span, explanation),
                };
            self.note_due_to_edition_2024_opaque_capture_rules(borrow,
                &mut err);
            self.buffer_error(err);
        }
    }
}#[instrument(level = "debug", skip(self))]
2942    pub(crate) fn report_borrowed_value_does_not_live_long_enough(
2943        &mut self,
2944        location: Location,
2945        borrow: &BorrowData<'tcx>,
2946        place_span: (Place<'tcx>, Span),
2947        kind: Option<WriteKind>,
2948    ) {
2949        let drop_span = place_span.1;
2950        let borrowed_local = borrow.borrowed_place.local;
2951
2952        let borrow_spans = self.retrieve_borrow_spans(borrow);
2953        let borrow_span = borrow_spans.var_or_use_path_span();
2954
2955        let proper_span = self.body.local_decls[borrowed_local].source_info.span;
2956
2957        if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
2958            debug!(
2959                "suppressing access_place error when borrow doesn't live long enough for {:?}",
2960                borrow_span
2961            );
2962            return;
2963        }
2964
2965        self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
2966
2967        if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
2968            let err =
2969                self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
2970            self.buffer_error(err);
2971            return;
2972        }
2973
2974        if let StorageDeadOrDrop::Destructor(dropped_ty) =
2975            self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
2976        {
2977            // If a borrow of path `B` conflicts with drop of `D` (and
2978            // we're not in the uninteresting case where `B` is a
2979            // prefix of `D`), then report this as a more interesting
2980            // destructor conflict.
2981            if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
2982                self.report_borrow_conflicts_with_destructor(
2983                    location, borrow, place_span, kind, dropped_ty,
2984                );
2985                return;
2986            }
2987        }
2988
2989        let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
2990
2991        let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
2992        let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
2993
2994        debug!(?place_desc, ?explanation);
2995
2996        let mut err = match (place_desc, explanation) {
2997            // If the outlives constraint comes from inside the closure,
2998            // for example:
2999            //
3000            // let x = 0;
3001            // let y = &x;
3002            // Box::new(|| y) as Box<Fn() -> &'static i32>
3003            //
3004            // then just use the normal error. The closure isn't escaping
3005            // and `move` will not help here.
3006            (
3007                Some(name),
3008                BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
3009            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3010                .report_escaping_closure_capture(
3011                    borrow_spans,
3012                    borrow_span,
3013                    &RegionName {
3014                        name: self.synthesize_region_name(),
3015                        source: RegionNameSource::Static,
3016                    },
3017                    ConstraintCategory::CallArgument(None),
3018                    var_or_use_span,
3019                    &format!("`{name}`"),
3020                    "block",
3021                ),
3022            (
3023                Some(name),
3024                BorrowExplanation::MustBeValidFor {
3025                    category:
3026                        category @ (ConstraintCategory::Return(_)
3027                        | ConstraintCategory::CallArgument(_)
3028                        | ConstraintCategory::OpaqueType),
3029                    from_closure: false,
3030                    ref region_name,
3031                    span,
3032                    ..
3033                },
3034            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3035                .report_escaping_closure_capture(
3036                    borrow_spans,
3037                    borrow_span,
3038                    region_name,
3039                    category,
3040                    span,
3041                    &format!("`{name}`"),
3042                    "function",
3043                ),
3044            (
3045                name,
3046                BorrowExplanation::MustBeValidFor {
3047                    category: ConstraintCategory::Assignment,
3048                    from_closure: false,
3049                    region_name:
3050                        RegionName {
3051                            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
3052                            ..
3053                        },
3054                    span,
3055                    ..
3056                },
3057            ) => self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, span),
3058            (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
3059                location,
3060                &name,
3061                borrow,
3062                drop_span,
3063                borrow_spans,
3064                explanation,
3065            ),
3066            (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
3067                location,
3068                borrow,
3069                drop_span,
3070                borrow_spans,
3071                proper_span,
3072                explanation,
3073            ),
3074        };
3075        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
3076
3077        self.buffer_error(err);
3078    }
3079
3080    #[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(3080u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&["location", "name",
                                                    "borrow", "drop_span", "borrow_spans"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&name as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&drop_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow_spans)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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