rustc_borrowck/diagnostics/
conflict_errors.rs

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