Skip to main content

rustc_borrowck/diagnostics/
conflict_errors.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let drop_span = place_span.1;
            let borrowed_local = borrow.borrowed_place.local;
            let borrow_spans = self.retrieve_borrow_spans(borrow);
            let borrow_span = borrow_spans.var_or_use_path_span();
            let proper_span =
                self.body.local_decls[borrowed_local].source_info.span;
            if self.access_place_error_reported.contains(&(Place::from(borrowed_local),
                            borrow_span)) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3062",
                                        "rustc_borrowck::diagnostics::conflict_errors",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                        ::tracing_core::__macro_support::Option::Some(3062u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("suppressing access_place error when borrow doesn\'t live long enough for {0:?}",
                                                                    borrow_span) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return;
            }
            self.access_place_error_reported.insert((Place::from(borrowed_local),
                    borrow_span));
            if self.body.local_decls[borrowed_local].is_ref_to_thread_local()
                {
                let err =
                    self.report_thread_local_value_does_not_live_long_enough(drop_span,
                        borrow_span);
                self.buffer_error(err);
                return;
            }
            if let StorageDeadOrDrop::Destructor(dropped_ty) =
                    self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
                {
                if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref())
                    {
                    self.report_borrow_conflicts_with_destructor(location,
                        borrow, place_span, kind, dropped_ty);
                    return;
                }
            }
            let place_desc =
                self.describe_place(borrow.borrowed_place.as_ref());
            let kind_place =
                kind.filter(|_|
                            place_desc.is_some()).map(|k| (k, place_span.0));
            let explanation =
                self.explain_why_borrow_contains_point(location, borrow,
                    kind_place);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3098",
                                    "rustc_borrowck::diagnostics::conflict_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3098u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place_desc")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place_desc");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("explanation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("explanation");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_desc)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&explanation)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let mut err =
                match (place_desc, explanation) {
                    (Some(name),
                        BorrowExplanation::UsedLater(_,
                        LaterUseKind::ClosureCapture, var_or_use_span, _)) if
                        borrow_spans.for_coroutine() || borrow_spans.for_closure()
                        =>
                        self.report_escaping_closure_capture(borrow_spans,
                            borrow_span,
                            &RegionName {
                                    name: self.synthesize_region_name(),
                                    source: RegionNameSource::Static,
                                }, ConstraintCategory::CallArgument(None), var_or_use_span,
                            &::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", name))
                                    }), "block"),
                    (Some(name), BorrowExplanation::MustBeValidFor {
                        ref best_blame, ref region_name, .. }) if
                        let OutlivesConstraint {
                                category: category
                                    @
                                    (ConstraintCategory::Return(_) |
                                    ConstraintCategory::CallArgument(_) |
                                    ConstraintCategory::OpaqueType),
                                from_closure: false,
                                span, .. } = best_blame.constraint() &&
                            (borrow_spans.for_coroutine() || borrow_spans.for_closure())
                        => {
                        self.report_escaping_closure_capture(borrow_spans,
                            borrow_span, region_name, *category, *span,
                            &::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("`{0}`", name))
                                    }), "function")
                    }
                    (name, BorrowExplanation::MustBeValidFor {
                        ref best_blame,
                        region_name: RegionName {
                            source: RegionNameSource::AnonRegionFromUpvar(upvar_span,
                                upvar_name),
                            ..
                            }, .. }) if
                        let OutlivesConstraint {
                            category: ConstraintCategory::Assignment,
                            from_closure: false,
                            span, .. } = best_blame.constraint() => {
                        self.report_escaping_data(borrow_span, &name, upvar_span,
                            upvar_name, *span)
                    }
                    (Some(name), explanation) =>
                        self.report_local_value_does_not_live_long_enough(location,
                            &name, borrow, drop_span, borrow_spans, explanation),
                    (None, explanation) =>
                        self.report_temporary_value_does_not_live_long_enough(location,
                            borrow, drop_span, borrow_spans, proper_span, explanation),
                };
            self.note_due_to_edition_2024_opaque_capture_rules(borrow,
                &mut err);
            self.buffer_error(err);
        }
    }
}#[instrument(level = "debug", skip(self))]
3046    pub(crate) fn report_borrowed_value_does_not_live_long_enough(
3047        &mut self,
3048        location: Location,
3049        borrow: &BorrowData<'tcx>,
3050        place_span: (Place<'tcx>, Span),
3051        kind: Option<WriteKind>,
3052    ) {
3053        let drop_span = place_span.1;
3054        let borrowed_local = borrow.borrowed_place.local;
3055
3056        let borrow_spans = self.retrieve_borrow_spans(borrow);
3057        let borrow_span = borrow_spans.var_or_use_path_span();
3058
3059        let proper_span = self.body.local_decls[borrowed_local].source_info.span;
3060
3061        if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
3062            debug!(
3063                "suppressing access_place error when borrow doesn't live long enough for {:?}",
3064                borrow_span
3065            );
3066            return;
3067        }
3068
3069        self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
3070
3071        if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
3072            let err =
3073                self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
3074            self.buffer_error(err);
3075            return;
3076        }
3077
3078        if let StorageDeadOrDrop::Destructor(dropped_ty) =
3079            self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
3080        {
3081            // If a borrow of path `B` conflicts with drop of `D` (and
3082            // we're not in the uninteresting case where `B` is a
3083            // prefix of `D`), then report this as a more interesting
3084            // destructor conflict.
3085            if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
3086                self.report_borrow_conflicts_with_destructor(
3087                    location, borrow, place_span, kind, dropped_ty,
3088                );
3089                return;
3090            }
3091        }
3092
3093        let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
3094
3095        let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
3096        let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
3097
3098        debug!(?place_desc, ?explanation);
3099
3100        let mut err = match (place_desc, explanation) {
3101            // If the outlives constraint comes from inside the closure,
3102            // for example:
3103            //
3104            // let x = 0;
3105            // let y = &x;
3106            // Box::new(|| y) as Box<Fn() -> &'static i32>
3107            //
3108            // then just use the normal error. The closure isn't escaping
3109            // and `move` will not help here.
3110            (
3111                Some(name),
3112                BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
3113            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
3114                .report_escaping_closure_capture(
3115                    borrow_spans,
3116                    borrow_span,
3117                    &RegionName {
3118                        name: self.synthesize_region_name(),
3119                        source: RegionNameSource::Static,
3120                    },
3121                    ConstraintCategory::CallArgument(None),
3122                    var_or_use_span,
3123                    &format!("`{name}`"),
3124                    "block",
3125                ),
3126            (
3127                Some(name),
3128                BorrowExplanation::MustBeValidFor { ref best_blame, ref region_name, .. },
3129            ) if let OutlivesConstraint {
3130                category:
3131                    category @ (ConstraintCategory::Return(_)
3132                    | ConstraintCategory::CallArgument(_)
3133                    | ConstraintCategory::OpaqueType),
3134                from_closure: false,
3135                span,
3136                ..
3137            } = best_blame.constraint()
3138                && (borrow_spans.for_coroutine() || borrow_spans.for_closure()) =>
3139            {
3140                self.report_escaping_closure_capture(
3141                    borrow_spans,
3142                    borrow_span,
3143                    region_name,
3144                    *category,
3145                    *span,
3146                    &format!("`{name}`"),
3147                    "function",
3148                )
3149            }
3150            (
3151                name,
3152                BorrowExplanation::MustBeValidFor {
3153                    ref best_blame,
3154                    region_name:
3155                        RegionName {
3156                            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
3157                            ..
3158                        },
3159                    ..
3160                },
3161            ) if let OutlivesConstraint {
3162                category: ConstraintCategory::Assignment,
3163                from_closure: false,
3164                span,
3165                ..
3166            } = best_blame.constraint() =>
3167            {
3168                self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, *span)
3169            }
3170            (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
3171                location,
3172                &name,
3173                borrow,
3174                drop_span,
3175                borrow_spans,
3176                explanation,
3177            ),
3178            (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
3179                location,
3180                borrow,
3181                drop_span,
3182                borrow_spans,
3183                proper_span,
3184                explanation,
3185            ),
3186        };
3187        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
3188
3189        self.buffer_error(err);
3190    }
3191
3192    {}
#[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("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3192u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("borrow")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("borrow");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("drop_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("drop_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("borrow_spans")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("borrow_spans");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&name as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&drop_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow_spans)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Diag<'diag> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let borrow_span = borrow_spans.var_or_use_path_span();
            if let BorrowExplanation::MustBeValidFor {
                            best_blame, opt_place_desc, .. } = &explanation &&
                        let OutlivesConstraint {
                            category, span, from_closure: false, .. } =
                            best_blame.constraint() &&
                    let Err(diag) =
                        self.try_report_cannot_return_reference_to_local(borrow,
                            borrow_span, *span, *category, opt_place_desc.as_ref()) {
                return diag;
            }
            let name =
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("`{0}`", name))
                    });
            let mut err =
                self.path_does_not_live_long_enough(borrow_span, &name);
            if let Some(annotation) =
                    self.annotate_argument_and_return_for_borrow(borrow) {
                let region_name = annotation.emit(self, &mut err);
                err.span_label(borrow_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0} would have to be valid for `{1}`...",
                                    name, region_name))
                        }));
                let tcx = self.infcx.tcx;
                let def_id = self.mir_def_id();
                let scope_end =
                    match tcx.opt_item_name(def_id.to_def_id()) {
                        Some(fn_name) =>
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("the function `{0}` returns",
                                            fn_name))
                                }),
                        None if
                            #[allow(non_exhaustive_omitted_patterns)] match tcx.hir_node_by_def_id(def_id)
                                {
                                hir::Node::ConstBlock(_) => true,
                                _ => false,
                            } => {
                            "the enclosing const block ends".to_string()
                        }
                        None =>
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("the enclosing {0} returns",
                                            tcx.def_descr(def_id.to_def_id())))
                                }),
                    };
                err.span_label(drop_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("...but {0} will be dropped here, when {1}",
                                    name, scope_end))
                        }));
                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))]
3193    fn report_local_value_does_not_live_long_enough(
3194        &self,
3195        location: Location,
3196        name: &str,
3197        borrow: &BorrowData<'tcx>,
3198        drop_span: Span,
3199        borrow_spans: UseSpans<'tcx>,
3200        explanation: BorrowExplanation<'tcx>,
3201    ) -> Diag<'diag> {
3202        let borrow_span = borrow_spans.var_or_use_path_span();
3203        if let BorrowExplanation::MustBeValidFor { best_blame, opt_place_desc, .. } = &explanation
3204            && let OutlivesConstraint { category, span, from_closure: false, .. } =
3205                best_blame.constraint()
3206            && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3207                borrow,
3208                borrow_span,
3209                *span,
3210                *category,
3211                opt_place_desc.as_ref(),
3212            )
3213        {
3214            return diag;
3215        }
3216
3217        let name = format!("`{name}`");
3218
3219        let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3220
3221        if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3222            let region_name = annotation.emit(self, &mut err);
3223
3224            err.span_label(
3225                borrow_span,
3226                format!("{name} would have to be valid for `{region_name}`..."),
3227            );
3228
3229            let tcx = self.infcx.tcx;
3230            let def_id = self.mir_def_id();
3231            let scope_end = match tcx.opt_item_name(def_id.to_def_id()) {
3232                Some(fn_name) => format!("the function `{fn_name}` returns"),
3233                None if matches!(tcx.hir_node_by_def_id(def_id), hir::Node::ConstBlock(_)) => {
3234                    "the enclosing const block ends".to_string()
3235                }
3236                None => format!("the enclosing {} returns", tcx.def_descr(def_id.to_def_id())),
3237            };
3238            err.span_label(
3239                drop_span,
3240                format!("...but {name} will be dropped here, when {scope_end}"),
3241            );
3242
3243            err.note(
3244                "functions cannot return a borrow to data owned within the function's scope, \
3245                    functions can only return borrows to data passed as arguments",
3246            );
3247            err.note(
3248                "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3249                    references-and-borrowing.html#dangling-references>",
3250            );
3251
3252            if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3253            } else {
3254                explanation.add_explanation_to_diagnostic(self, &mut err, "", None, None);
3255            }
3256        } else {
3257            err.span_label(borrow_span, "borrowed value does not live long enough");
3258            err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3259
3260            borrow_spans.args_subdiag(&mut err, |args_span| {
3261                crate::session_diagnostics::CaptureArgLabel::Capture {
3262                    is_within: borrow_spans.for_coroutine(),
3263                    args_span,
3264                }
3265            });
3266
3267            explanation.add_explanation_to_diagnostic(self, &mut err, "", Some(borrow_span), None);
3268
3269            // Detect buffer reuse pattern
3270            if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) = explanation {
3271                // Check all locals at the borrow location to find Vec<&T> types
3272                for (local, local_decl) in self.body.local_decls.iter_enumerated() {
3273                    if let ty::Adt(adt_def, args) = local_decl.ty.kind()
3274                        && self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
3275                        && args.len() > 0
3276                    {
3277                        let vec_inner_ty = args.type_at(0);
3278                        // Check if Vec contains references
3279                        if vec_inner_ty.is_ref() {
3280                            let local_place = local.into();
3281                            if let Some(local_name) = self.describe_place(local_place) {
3282                                err.span_label(
3283                                    local_decl.source_info.span,
3284                                    format!("variable `{local_name}` declared here"),
3285                                );
3286                                err.note(
3287                                    format!(
3288                                        "`{local_name}` is a collection that stores borrowed references, \
3289                                         but {name} does not live long enough to be stored in it"
3290                                    )
3291                                );
3292                                err.help(
3293                                    "buffer reuse with borrowed references requires unsafe code or restructuring"
3294                                );
3295                                break;
3296                            }
3297                        }
3298                    }
3299                }
3300            }
3301        }
3302
3303        err
3304    }
3305
3306    fn report_borrow_conflicts_with_destructor(
3307        &mut self,
3308        location: Location,
3309        borrow: &BorrowData<'tcx>,
3310        (place, drop_span): (Place<'tcx>, Span),
3311        kind: Option<WriteKind>,
3312        dropped_ty: Ty<'tcx>,
3313    ) {
3314        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3314",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(3314u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_borrow_conflicts_with_destructor({0:?}, {1:?}, ({2:?}, {3:?}), {4:?})",
                                                    location, borrow, place, drop_span, kind) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
3315            "report_borrow_conflicts_with_destructor(\
3316             {:?}, {:?}, ({:?}, {:?}), {:?}\
3317             )",
3318            location, borrow, place, drop_span, kind,
3319        );
3320
3321        let borrow_spans = self.retrieve_borrow_spans(borrow);
3322        let borrow_span = borrow_spans.var_or_use();
3323
3324        let mut err = self.cannot_borrow_across_destructor(borrow_span);
3325
3326        let what_was_dropped = match self.describe_place(place.as_ref()) {
3327            Some(name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"),
3328            None => String::from("temporary value"),
3329        };
3330
3331        let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3332            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!(
3333                "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3334                 because the type `{dropped_ty}` implements the `Drop` trait"
3335            ),
3336            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!(
3337                "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3338            ),
3339        };
3340        err.span_label(drop_span, label);
3341
3342        // Only give this note and suggestion if they could be relevant.
3343        let explanation =
3344            self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3345        match explanation {
3346            BorrowExplanation::UsedLater { .. }
3347            | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3348                err.note("consider using a `let` binding to create a longer lived value");
3349            }
3350            _ => {}
3351        }
3352
3353        explanation.add_explanation_to_diagnostic(self, &mut err, "", None, None);
3354
3355        self.buffer_error(err);
3356    }
3357
3358    fn report_thread_local_value_does_not_live_long_enough(
3359        &self,
3360        drop_span: Span,
3361        borrow_span: Span,
3362    ) -> Diag<'diag> {
3363        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs:3363",
                        "rustc_borrowck::diagnostics::conflict_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(3363u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_thread_local_value_does_not_live_long_enough({0:?}, {1:?})",
                                                    drop_span, borrow_span) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
3364            "report_thread_local_value_does_not_live_long_enough(\
3365             {:?}, {:?}\
3366             )",
3367            drop_span, borrow_span
3368        );
3369
3370        // `TerminatorKind::Return`'s span (the `drop_span` here) `lo` can be subtly wrong and point
3371        // at a single character after the end of the function. This is somehow relied upon in
3372        // existing diagnostics, and changing this in `rustc_mir_build` makes diagnostics worse in
3373        // general. We fix these here.
3374        let sm = self.infcx.tcx.sess.source_map();
3375        let end_of_function = if drop_span.is_empty()
3376            && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3377        {
3378            adjusted_span
3379        } else {
3380            drop_span
3381        };
3382        self.thread_local_value_does_not_live_long_enough(borrow_span)
3383            .with_span_label(
3384                borrow_span,
3385                "thread-local variables cannot be borrowed beyond the end of the function",
3386            )
3387            .with_span_label(end_of_function, "end of enclosing function is here")
3388    }
3389
3390    {}
#[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("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3390u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("borrow")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("borrow");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("drop_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("drop_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("borrow_spans")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("borrow_spans");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("proper_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("proper_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("explanation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("explanation");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&drop_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&borrow_spans)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&proper_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&explanation)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Diag<'diag> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let BorrowExplanation::MustBeValidFor { ref best_blame, .. } =
                        explanation &&
                    let OutlivesConstraint {
                        category, span, from_closure: false, .. } =
                        best_blame.constraint() {
                if let Err(diag) =
                        self.try_report_cannot_return_reference_to_local(borrow,
                            proper_span, *span, *category, None) {
                    return diag;
                }
            }
            let mut err =
                self.temporary_value_borrowed_for_too_long(proper_span);
            err.span_label(proper_span,
                "creates a temporary value which is freed while still in use");
            err.span_label(drop_span,
                "temporary value is freed at the end of this statement");
            match explanation {
                BorrowExplanation::UsedLater(..) |
                    BorrowExplanation::UsedLaterInLoop(..) |
                    BorrowExplanation::UsedLaterWhenDropped { .. } => {
                    let sm = self.infcx.tcx.sess.source_map();
                    let mut suggested = false;
                    let msg =
                        "consider using a `let` binding to create a longer lived value";
                    #[doc =
                    " We check that there\'s a single level of block nesting to ensure always correct"]
                    #[doc =
                    " suggestions. If we don\'t, then we only provide a free-form message to avoid"]
                    #[doc =
                    " misleading users in cases like `tests/ui/nll/borrowed-temporary-error.rs`."]
                    #[doc =
                    " We could expand the analysis to suggest hoising all of the relevant parts of"]
                    #[doc =
                    " the users\' code to make the code compile, but that could be too much."]
                    #[doc =
                    " We found the `prop_expr` by the way to check whether the expression is a"]
                    #[doc =
                    " `FormatArguments`, which is a special case since it\'s generated by the"]
                    #[doc = " compiler."]
                    struct NestedStatementVisitor<'tcx> {
                        span: Span,
                        current: usize,
                        found: usize,
                        prop_expr: Option<&'tcx hir::Expr<'tcx>>,
                        call: Option<&'tcx hir::Expr<'tcx>>,
                    }
                    impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
                        fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
                            self.current += 1;
                            walk_block(self, block);
                            self.current -= 1;
                        }
                        fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
                            if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind
                                {
                                if self.span == rcvr.span.source_callsite() {
                                    self.call = Some(expr);
                                }
                            }
                            if self.span == expr.span.source_callsite() {
                                self.found = self.current;
                                if self.prop_expr.is_none() { self.prop_expr = Some(expr); }
                            }
                            walk_expr(self, expr);
                        }
                    }
                    let source_info = self.body.source_info(location);
                    let proper_span = proper_span.source_callsite();
                    if let Some(scope) =
                                        self.body.source_scopes.get(source_info.scope) &&
                                    let ClearCrossCrate::Set(scope_data) = &scope.local_data &&
                                let Some(id) =
                                    self.infcx.tcx.hir_node(scope_data.lint_root).body_id() &&
                            let hir::ExprKind::Block(block, _) =
                                self.infcx.tcx.hir_body(id).value.kind {
                        for stmt in block.stmts {
                            let mut visitor =
                                NestedStatementVisitor {
                                    span: proper_span,
                                    current: 0,
                                    found: 0,
                                    prop_expr: None,
                                    call: None,
                                };
                            visitor.visit_stmt(stmt);
                            let typeck_results =
                                self.infcx.tcx.typeck(self.mir_def_id());
                            let expr_ty: Option<Ty<'_>> =
                                visitor.prop_expr.map(|expr|
                                        typeck_results.expr_ty(expr).peel_refs());
                            if visitor.found == 0 && stmt.span.contains(proper_span) &&
                                        let Some(p) = sm.span_to_margin(stmt.span) &&
                                    let Ok(s) = sm.span_to_snippet(proper_span) {
                                if let Some(call) = visitor.call &&
                                                let hir::ExprKind::MethodCall(path, _, [], _) = call.kind &&
                                            path.ident.name == sym::iter && let Some(ty) = expr_ty {
                                    err.span_suggestion_verbose(path.ident.span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("consider consuming the `{0}` when turning it into an `Iterator`",
                                                        ty))
                                            }), "into_iter", Applicability::MaybeIncorrect);
                                }
                                let mutability =
                                    if #[allow(non_exhaustive_omitted_patterns)] match borrow.kind()
                                            {
                                            BorrowKind::Mut { .. } => true,
                                            _ => false,
                                        } {
                                        "mut "
                                    } else { "" };
                                let addition =
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("let {0}binding = {1};\n{2}",
                                                    mutability, s, " ".repeat(p)))
                                        });
                                err.multipart_suggestion(msg,
                                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                            [(stmt.span.shrink_to_lo(), addition),
                                                    (proper_span, "binding".to_string())])),
                                    Applicability::MaybeIncorrect);
                                suggested = true;
                                break;
                            }
                        }
                    }
                    if !suggested { err.note(msg); }
                }
                _ => {}
            }
            explanation.add_explanation_to_diagnostic(self, &mut err, "",
                None, None);
            borrow_spans.args_subdiag(&mut err,
                |args_span|
                    {
                        crate::session_diagnostics::CaptureArgLabel::Capture {
                            is_within: borrow_spans.for_coroutine(),
                            args_span,
                        }
                    });
            err
        }
    }
}#[instrument(level = "debug", skip(self))]
3391    fn report_temporary_value_does_not_live_long_enough(
3392        &self,
3393        location: Location,
3394        borrow: &BorrowData<'tcx>,
3395        drop_span: Span,
3396        borrow_spans: UseSpans<'tcx>,
3397        proper_span: Span,
3398        explanation: BorrowExplanation<'tcx>,
3399    ) -> Diag<'diag> {
3400        if let BorrowExplanation::MustBeValidFor { ref best_blame, .. } = explanation
3401            && let OutlivesConstraint { category, span, from_closure: false, .. } =
3402                best_blame.constraint()
3403        {
3404            if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3405                borrow,
3406                proper_span,
3407                *span,
3408                *category,
3409                None,
3410            ) {
3411                return diag;
3412            }
3413        }
3414
3415        let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3416        err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3417        err.span_label(drop_span, "temporary value is freed at the end of this statement");
3418
3419        match explanation {
3420            BorrowExplanation::UsedLater(..)
3421            | BorrowExplanation::UsedLaterInLoop(..)
3422            | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3423                // Only give this note and suggestion if it could be relevant.
3424                let sm = self.infcx.tcx.sess.source_map();
3425                let mut suggested = false;
3426                let msg = "consider using a `let` binding to create a longer lived value";
3427
3428                /// We check that there's a single level of block nesting to ensure always correct
3429                /// suggestions. If we don't, then we only provide a free-form message to avoid
3430                /// misleading users in cases like `tests/ui/nll/borrowed-temporary-error.rs`.
3431                /// We could expand the analysis to suggest hoising all of the relevant parts of
3432                /// the users' code to make the code compile, but that could be too much.
3433                /// We found the `prop_expr` by the way to check whether the expression is a
3434                /// `FormatArguments`, which is a special case since it's generated by the
3435                /// compiler.
3436                struct NestedStatementVisitor<'tcx> {
3437                    span: Span,
3438                    current: usize,
3439                    found: usize,
3440                    prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3441                    call: Option<&'tcx hir::Expr<'tcx>>,
3442                }
3443
3444                impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3445                    fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3446                        self.current += 1;
3447                        walk_block(self, block);
3448                        self.current -= 1;
3449                    }
3450                    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3451                        if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3452                            if self.span == rcvr.span.source_callsite() {
3453                                self.call = Some(expr);
3454                            }
3455                        }
3456                        if self.span == expr.span.source_callsite() {
3457                            self.found = self.current;
3458                            if self.prop_expr.is_none() {
3459                                self.prop_expr = Some(expr);
3460                            }
3461                        }
3462                        walk_expr(self, expr);
3463                    }
3464                }
3465                let source_info = self.body.source_info(location);
3466                let proper_span = proper_span.source_callsite();
3467                if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3468                    && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3469                    && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3470                    && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3471                {
3472                    for stmt in block.stmts {
3473                        let mut visitor = NestedStatementVisitor {
3474                            span: proper_span,
3475                            current: 0,
3476                            found: 0,
3477                            prop_expr: None,
3478                            call: None,
3479                        };
3480                        visitor.visit_stmt(stmt);
3481
3482                        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3483                        let expr_ty: Option<Ty<'_>> =
3484                            visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3485
3486                        if visitor.found == 0
3487                            && stmt.span.contains(proper_span)
3488                            && let Some(p) = sm.span_to_margin(stmt.span)
3489                            && let Ok(s) = sm.span_to_snippet(proper_span)
3490                        {
3491                            if let Some(call) = visitor.call
3492                                && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3493                                && path.ident.name == sym::iter
3494                                && let Some(ty) = expr_ty
3495                            {
3496                                err.span_suggestion_verbose(
3497                                    path.ident.span,
3498                                    format!(
3499                                        "consider consuming the `{ty}` when turning it into an \
3500                                         `Iterator`",
3501                                    ),
3502                                    "into_iter",
3503                                    Applicability::MaybeIncorrect,
3504                                );
3505                            }
3506
3507                            let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3508                                "mut "
3509                            } else {
3510                                ""
3511                            };
3512
3513                            let addition =
3514                                format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3515                            err.multipart_suggestion(
3516                                msg,
3517                                vec![
3518                                    (stmt.span.shrink_to_lo(), addition),
3519                                    (proper_span, "binding".to_string()),
3520                                ],
3521                                Applicability::MaybeIncorrect,
3522                            );
3523
3524                            suggested = true;
3525                            break;
3526                        }
3527                    }
3528                }
3529                if !suggested {
3530                    err.note(msg);
3531                }
3532            }
3533            _ => {}
3534        }
3535        explanation.add_explanation_to_diagnostic(self, &mut err, "", None, None);
3536
3537        borrow_spans.args_subdiag(&mut err, |args_span| {
3538            crate::session_diagnostics::CaptureArgLabel::Capture {
3539                is_within: borrow_spans.for_coroutine(),
3540                args_span,
3541            }
3542        });
3543
3544        err
3545    }
3546
3547    fn try_report_cannot_return_reference_to_local(
3548        &self,
3549        borrow: &BorrowData<'tcx>,
3550        borrow_span: Span,
3551        return_span: Span,
3552        category: ConstraintCategory<'tcx>,
3553        opt_place_desc: Option<&String>,
3554    ) -> Result<(), Diag<'diag>> {
3555        let return_kind = match category {
3556            ConstraintCategory::Return(_) => "return",
3557            ConstraintCategory::Yield => "yield",
3558            _ => return Ok(()),
3559        };
3560
3561        // FIXME use a better heuristic than Spans
3562        let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3563            "reference to"
3564        } else {
3565            "value referencing"
3566        };
3567
3568        let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3569            let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3570                match self.body.local_kind(local) {
3571                    LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3572                        "local variable "
3573                    }
3574                    LocalKind::Arg
3575                        if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3576                    {
3577                        "variable captured by `move` "
3578                    }
3579                    LocalKind::Arg => "function parameter ",
3580                    LocalKind::ReturnPointer | LocalKind::Temp => {
3581                        ::rustc_span::macros::bug_impl(None,
    format_args!("temporary or return pointer with a name"),
    Location::caller())bug!("temporary or return pointer with a name")
3582                    }
3583                }
3584            } else {
3585                "local data "
3586            };
3587            (::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"))
3588        } else {
3589            let local = borrow.borrowed_place.local;
3590            match self.body.local_kind(local) {
3591                LocalKind::Arg => (
3592                    "function parameter".to_string(),
3593                    "function parameter borrowed here".to_string(),
3594                ),
3595                LocalKind::Temp
3596                    if self.body.local_decls[local].is_user_variable()
3597                        && !self.body.local_decls[local]
3598                            .source_info
3599                            .span
3600                            .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3601                {
3602                    ("local binding".to_string(), "local binding introduced here".to_string())
3603                }
3604                LocalKind::ReturnPointer | LocalKind::Temp => {
3605                    ("temporary value".to_string(), "temporary value created here".to_string())
3606                }
3607            }
3608        };
3609
3610        let mut err = self.cannot_return_reference_to_local(
3611            return_span,
3612            return_kind,
3613            reference_desc,
3614            &place_desc,
3615        );
3616
3617        if return_span != borrow_span {
3618            err.span_label(borrow_span, note);
3619
3620            let tcx = self.infcx.tcx;
3621
3622            let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3623
3624            // to avoid panics
3625            if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3626                && self
3627                    .infcx
3628                    .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3629                    .must_apply_modulo_regions()
3630            {
3631                err.span_suggestion_hidden(
3632                    return_span.shrink_to_hi(),
3633                    "use `.collect()` to allocate the iterator",
3634                    ".collect::<Vec<_>>()",
3635                    Applicability::MaybeIncorrect,
3636                );
3637            }
3638
3639            if let Some(cow_did) = tcx.get_diagnostic_item(sym::Cow)
3640                && let ty::Adt(adt_def, _) = return_ty.kind()
3641                && adt_def.did() == cow_did
3642            {
3643                let typeck = tcx.typeck(self.mir_def_id());
3644                if let Some(expr) = self.find_expr(return_span)
3645                    && let Some(def_id) = typeck.type_dependent_def_id(expr.hir_id)
3646                    && tcx.is_diagnostic_item(sym::to_owned_method, def_id)
3647                    && let Some(to_owned_ident) = expr.method_ident()
3648                {
3649                    err.span_suggestion_short(
3650                        to_owned_ident.span.shrink_to_lo(),
3651                        "try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`",
3652                        "in",
3653                        Applicability::MaybeIncorrect,
3654                    );
3655                }
3656            }
3657        }
3658
3659        Err(err)
3660    }
3661
3662    {}
#[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("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3662u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::conflict_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("use_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("use_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("var_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("var_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fr_name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fr_name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("category")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("category");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constraint_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constraint_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("captured_var")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("captured_var");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("scope");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fr_name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&category)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&captured_var as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&scope as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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