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(qpath) = call_expr.kind
507                    && tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
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.evaluate_obligations_error_on_ambiguity();
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.evaluate_obligations_error_on_ambiguity();
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            tcx: TyCtxt<'hir>,
2316            issue_span: Span,
2317            expr_span: Span,
2318            body_expr: Option<&'hir hir::Expr<'hir>>,
2319            loop_bind: Option<&'hir Ident>,
2320            loop_span: Option<Span>,
2321            head_span: Option<Span>,
2322            pat_span: Option<Span>,
2323            head: Option<&'hir hir::Expr<'hir>>,
2324        }
2325        impl<'hir> Visitor<'hir> for ExprFinder<'hir> {
2326            fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2327                // Try to find
2328                // let result = match IntoIterator::into_iter(<head>) {
2329                //     mut iter => {
2330                //         [opt_ident]: loop {
2331                //             match Iterator::next(&mut iter) {
2332                //                 None => break,
2333                //                 Some(<pat>) => <body>,
2334                //             };
2335                //         }
2336                //     }
2337                // };
2338                // corresponding to the desugaring of a for loop `for <pat> in <head> { <body> }`.
2339                if let hir::ExprKind::Call(path, [arg]) = ex.kind
2340                    && let hir::ExprKind::Path(qpath) = path.kind
2341                    && self.tcx.qpath_is_lang_item(qpath, LangItem::IntoIterIntoIter)
2342                    && arg.span.contains(self.issue_span)
2343                    && ex.span.desugaring_kind() == Some(DesugaringKind::ForLoop)
2344                {
2345                    // Find `IntoIterator::into_iter(<head>)`
2346                    self.head = Some(arg);
2347                }
2348                if let hir::ExprKind::Loop(
2349                    hir::Block { stmts: [stmt, ..], .. },
2350                    _,
2351                    hir::LoopSource::ForLoop,
2352                    _,
2353                ) = ex.kind
2354                    && let hir::StmtKind::Expr(hir::Expr {
2355                        kind: hir::ExprKind::Match(call, [_, bind, ..], _),
2356                        span: head_span,
2357                        ..
2358                    }) = stmt.kind
2359                    && let hir::ExprKind::Call(path, _args) = call.kind
2360                    && let hir::ExprKind::Path(qpath) = path.kind
2361                    && self.tcx.qpath_is_lang_item(qpath, LangItem::IteratorNext)
2362                    && let hir::PatKind::Struct(qpath, [field, ..], _) = bind.pat.kind
2363                    && self.tcx.qpath_is_lang_item(qpath, LangItem::OptionSome)
2364                    && call.span.contains(self.issue_span)
2365                {
2366                    // Find `<pat>` and the span for the whole `for` loop.
2367                    if let PatField {
2368                        pat: hir::Pat { kind: hir::PatKind::Binding(_, _, ident, ..), .. },
2369                        ..
2370                    } = field
2371                    {
2372                        self.loop_bind = Some(ident);
2373                    }
2374                    self.head_span = Some(*head_span);
2375                    self.pat_span = Some(bind.pat.span);
2376                    self.loop_span = Some(stmt.span);
2377                }
2378
2379                if let hir::ExprKind::MethodCall(body_call, recv, ..) = ex.kind
2380                    && body_call.ident.name == sym::next
2381                    && recv.span.source_equal(self.expr_span)
2382                {
2383                    self.body_expr = Some(ex);
2384                }
2385
2386                hir::intravisit::walk_expr(self, ex);
2387            }
2388        }
2389        let mut finder = ExprFinder {
2390            tcx,
2391            expr_span: span,
2392            issue_span,
2393            loop_bind: None,
2394            body_expr: None,
2395            head_span: None,
2396            loop_span: None,
2397            pat_span: None,
2398            head: None,
2399        };
2400        finder.visit_expr(tcx.hir_body(body_id).value);
2401
2402        if let Some(body_expr) = finder.body_expr
2403            && let Some(loop_span) = finder.loop_span
2404            && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id)
2405            && let Some(trait_did) = tcx.trait_of_assoc(def_id)
2406            && tcx.is_diagnostic_item(sym::Iterator, trait_did)
2407        {
2408            if let Some(loop_bind) = finder.loop_bind {
2409                err.note(format!(
2410                    "a for loop advances the iterator for you, the result is stored in `{}`",
2411                    loop_bind.name,
2412                ));
2413            } else {
2414                err.note(
2415                    "a for loop advances the iterator for you, the result is stored in its pattern",
2416                );
2417            }
2418            let msg = "if you want to call `next` on a iterator within the loop, consider using \
2419                       `while let`";
2420            if let Some(head) = finder.head
2421                && let Some(pat_span) = finder.pat_span
2422                && loop_span.contains(body_expr.span)
2423                && loop_span.contains(head.span)
2424            {
2425                let sm = self.infcx.tcx.sess.source_map();
2426
2427                let mut sugg = vec![];
2428                if let hir::ExprKind::Path(hir::QPath::Resolved(None, _)) = head.kind {
2429                    // A bare path doesn't need a `let` assignment, it's already a simple
2430                    // binding access.
2431                    // As a new binding wasn't added, we don't need to modify the advancing call.
2432                    sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
2433                    sugg.push((
2434                        pat_span.shrink_to_hi().with_hi(head.span.lo()),
2435                        ") = ".to_string(),
2436                    ));
2437                    sugg.push((head.span.shrink_to_hi(), ".next()".to_string()));
2438                } else {
2439                    // Needs a new a `let` binding.
2440                    let indent = if let Some(indent) = sm.indentation_before(loop_span) {
2441                        format!("\n{indent}")
2442                    } else {
2443                        " ".to_string()
2444                    };
2445                    let Ok(head_str) = sm.span_to_snippet(head.span) else {
2446                        err.help(msg);
2447                        return;
2448                    };
2449                    sugg.push((
2450                        loop_span.with_hi(pat_span.lo()),
2451                        format!("let iter = {head_str};{indent}while let Some("),
2452                    ));
2453                    sugg.push((
2454                        pat_span.shrink_to_hi().with_hi(head.span.hi()),
2455                        ") = iter.next()".to_string(),
2456                    ));
2457                    // As a new binding was added, we should change how the iterator is advanced to
2458                    // use the newly introduced binding.
2459                    if let hir::ExprKind::MethodCall(_, recv, ..) = body_expr.kind
2460                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, ..)) = recv.kind
2461                    {
2462                        // As we introduced a `let iter = <head>;`, we need to change where the
2463                        // already borrowed value was accessed from `<recv>.next()` to
2464                        // `iter.next()`.
2465                        sugg.push((recv.span, "iter".to_string()));
2466                    }
2467                }
2468                err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2469            } else {
2470                err.help(msg);
2471            }
2472        }
2473    }
2474
2475    /// Suggest using closure argument instead of capture.
2476    ///
2477    /// For example:
2478    /// ```ignore (illustrative)
2479    /// struct S;
2480    ///
2481    /// impl S {
2482    ///     fn call(&mut self, f: impl Fn(&mut Self)) { /* ... */ }
2483    ///     fn x(&self) {}
2484    /// }
2485    ///
2486    ///     let mut v = S;
2487    ///     v.call(|this: &mut S| v.x());
2488    /// //  ^\                    ^-- help: try using the closure argument: `this`
2489    /// //    *-- error: cannot borrow `v` as mutable because it is also borrowed as immutable
2490    /// ```
2491    fn suggest_using_closure_argument_instead_of_capture(
2492        &self,
2493        err: &mut Diag<'_>,
2494        borrowed_place: Place<'tcx>,
2495        issued_spans: &UseSpans<'tcx>,
2496    ) {
2497        let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2498        let tcx = self.infcx.tcx;
2499
2500        // Get the type of the local that we are trying to borrow
2501        let local = borrowed_place.local;
2502        let local_ty = self.body.local_decls[local].ty;
2503
2504        // Get the body the error happens in
2505        let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
2506
2507        let body_expr = tcx.hir_body(body_id).value;
2508
2509        struct ClosureFinder<'hir> {
2510            tcx: TyCtxt<'hir>,
2511            borrow_span: Span,
2512            res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
2513            /// The path expression with the `borrow_span` span
2514            error_path: Option<(&'hir hir::Expr<'hir>, &'hir hir::QPath<'hir>)>,
2515        }
2516        impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
2517            type NestedFilter = OnlyBodies;
2518
2519            fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2520                self.tcx
2521            }
2522
2523            fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2524                if let hir::ExprKind::Path(qpath) = &ex.kind
2525                    && ex.span == self.borrow_span
2526                {
2527                    self.error_path = Some((ex, qpath));
2528                }
2529
2530                if let hir::ExprKind::Closure(closure) = ex.kind
2531                    && ex.span.contains(self.borrow_span)
2532                    // To support cases like `|| { v.call(|this| v.get()) }`
2533                    // FIXME: actually support such cases (need to figure out how to move from the
2534                    // capture place to original local).
2535                    && self.res.as_ref().is_none_or(|(prev_res, _)| prev_res.span.contains(ex.span))
2536                {
2537                    self.res = Some((ex, closure));
2538                }
2539
2540                hir::intravisit::walk_expr(self, ex);
2541            }
2542        }
2543
2544        // Find the closure that most tightly wraps `capture_kind_span`
2545        let mut finder =
2546            ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
2547        finder.visit_expr(body_expr);
2548        let Some((closure_expr, closure)) = finder.res else { return };
2549
2550        let typeck_results = tcx.typeck(self.mir_def_id());
2551
2552        // Check that the parent of the closure is a method call,
2553        // with receiver matching with local's type (modulo refs)
2554        if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id)
2555            && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind
2556        {
2557            let recv_ty = typeck_results.expr_ty(recv);
2558
2559            if recv_ty.peel_refs() != local_ty {
2560                return;
2561            }
2562        }
2563
2564        // Get closure's arguments
2565        let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else {
2566            /* hir::Closure can be a coroutine too */
2567            return;
2568        };
2569        let sig = args.as_closure().sig();
2570        let tupled_params = tcx.instantiate_bound_regions_with_erased(
2571            sig.inputs().iter().next().unwrap().map_bound(|&b| b),
2572        );
2573        let ty::Tuple(params) = tupled_params.kind() else { return };
2574
2575        // Find the first argument with a matching type and get its identifier.
2576        let Some(this_name) = params.iter().zip(tcx.hir_body_param_idents(closure.body)).find_map(
2577            |(param_ty, ident)| {
2578                // FIXME: also support deref for stuff like `Rc` arguments
2579                if param_ty.peel_refs() == local_ty { ident } else { None }
2580            },
2581        ) else {
2582            return;
2583        };
2584
2585        let spans;
2586        if let Some((_path_expr, qpath)) = finder.error_path
2587            && let hir::QPath::Resolved(_, path) = qpath
2588            && let hir::def::Res::Local(local_id) = path.res
2589        {
2590            // Find all references to the problematic variable in this closure body
2591
2592            struct VariableUseFinder {
2593                local_id: hir::HirId,
2594                spans: Vec<Span>,
2595            }
2596            impl<'hir> Visitor<'hir> for VariableUseFinder {
2597                fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
2598                    if let hir::ExprKind::Path(qpath) = &ex.kind
2599                        && let hir::QPath::Resolved(_, path) = qpath
2600                        && let hir::def::Res::Local(local_id) = path.res
2601                        && local_id == self.local_id
2602                    {
2603                        self.spans.push(ex.span);
2604                    }
2605
2606                    hir::intravisit::walk_expr(self, ex);
2607                }
2608            }
2609
2610            let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
2611            finder.visit_expr(tcx.hir_body(closure.body).value);
2612
2613            spans = finder.spans;
2614        } else {
2615            spans = vec![capture_kind_span];
2616        }
2617
2618        err.multipart_suggestion(
2619            "try using the closure argument",
2620            iter::zip(spans, iter::repeat(this_name.to_string())).collect(),
2621            Applicability::MaybeIncorrect,
2622        );
2623    }
2624
2625    fn suggest_binding_for_closure_capture_self(
2626        &self,
2627        err: &mut Diag<'_>,
2628        issued_spans: &UseSpans<'tcx>,
2629    ) {
2630        let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
2631
2632        struct ExpressionFinder<'tcx> {
2633            capture_span: Span,
2634            closure_change_spans: Vec<Span>,
2635            closure_arg_span: Option<Span>,
2636            in_closure: bool,
2637            suggest_arg: String,
2638            tcx: TyCtxt<'tcx>,
2639            closure_local_id: Option<hir::HirId>,
2640            closure_call_changes: Vec<(Span, String)>,
2641        }
2642        impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
2643            fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
2644                if e.span.contains(self.capture_span)
2645                    && let hir::ExprKind::Closure(&hir::Closure {
2646                        kind: hir::ClosureKind::Closure,
2647                        body,
2648                        fn_arg_span,
2649                        fn_decl: hir::FnDecl { inputs, .. },
2650                        ..
2651                    }) = e.kind
2652                    && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
2653                {
2654                    self.suggest_arg = "this: &Self".to_string();
2655                    if inputs.len() > 0 {
2656                        self.suggest_arg.push_str(", ");
2657                    }
2658                    self.in_closure = true;
2659                    self.closure_arg_span = fn_arg_span;
2660                    self.visit_expr(body);
2661                    self.in_closure = false;
2662                }
2663                if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
2664                    && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2665                    && seg.ident.name == kw::SelfLower
2666                    && self.in_closure
2667                {
2668                    self.closure_change_spans.push(e.span);
2669                }
2670                hir::intravisit::walk_expr(self, e);
2671            }
2672
2673            fn visit_local(&mut self, local: &'hir hir::LetStmt<'hir>) {
2674                if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
2675                    local.pat
2676                    && let Some(init) = local.init
2677                    && let &hir::Expr {
2678                        kind:
2679                            hir::ExprKind::Closure(&hir::Closure {
2680                                kind: hir::ClosureKind::Closure,
2681                                ..
2682                            }),
2683                        ..
2684                    } = init
2685                    && init.span.contains(self.capture_span)
2686                {
2687                    self.closure_local_id = Some(*hir_id);
2688                }
2689
2690                hir::intravisit::walk_local(self, local);
2691            }
2692
2693            fn visit_stmt(&mut self, s: &'hir hir::Stmt<'hir>) {
2694                if let hir::StmtKind::Semi(e) = s.kind
2695                    && let hir::ExprKind::Call(
2696                        hir::Expr { kind: hir::ExprKind::Path(path), .. },
2697                        args,
2698                    ) = e.kind
2699                    && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
2700                    && let Res::Local(hir_id) = seg.res
2701                    && Some(hir_id) == self.closure_local_id
2702                {
2703                    let (span, arg_str) = if args.len() > 0 {
2704                        (args[0].span.shrink_to_lo(), "self, ".to_string())
2705                    } else {
2706                        let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
2707                        (span, "(self)".to_string())
2708                    };
2709                    self.closure_call_changes.push((span, arg_str));
2710                }
2711                hir::intravisit::walk_stmt(self, s);
2712            }
2713        }
2714
2715        if let hir::Node::ImplItem(hir::ImplItem {
2716            kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
2717            ..
2718        }) = self.infcx.tcx.hir_node(self.mir_hir_id())
2719            && let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
2720        {
2721            let mut finder = ExpressionFinder {
2722                capture_span: *capture_kind_span,
2723                closure_change_spans: vec![],
2724                closure_arg_span: None,
2725                in_closure: false,
2726                suggest_arg: String::new(),
2727                closure_local_id: None,
2728                closure_call_changes: vec![],
2729                tcx: self.infcx.tcx,
2730            };
2731            finder.visit_expr(expr);
2732
2733            if finder.closure_change_spans.is_empty() || finder.closure_call_changes.is_empty() {
2734                return;
2735            }
2736
2737            let sm = self.infcx.tcx.sess.source_map();
2738            let sugg = finder
2739                .closure_arg_span
2740                .map(|span| (sm.next_point(span.shrink_to_lo()).shrink_to_hi(), finder.suggest_arg))
2741                .into_iter()
2742                .chain(
2743                    finder.closure_change_spans.into_iter().map(|span| (span, "this".to_string())),
2744                )
2745                .chain(finder.closure_call_changes)
2746                .collect();
2747
2748            err.multipart_suggestion_verbose(
2749                "try explicitly passing `&Self` into the closure as an argument",
2750                sugg,
2751                Applicability::MachineApplicable,
2752            );
2753        }
2754    }
2755
2756    /// Returns the description of the root place for a conflicting borrow and the full
2757    /// descriptions of the places that caused the conflict.
2758    ///
2759    /// In the simplest case, where there are no unions involved, if a mutable borrow of `x` is
2760    /// attempted while a shared borrow is live, then this function will return:
2761    /// ```
2762    /// ("x", "", "")
2763    /// # ;
2764    /// ```
2765    /// In the simple union case, if a mutable borrow of a union field `x.z` is attempted while
2766    /// a shared borrow of another field `x.y`, then this function will return:
2767    /// ```
2768    /// ("x", "x.z", "x.y")
2769    /// # ;
2770    /// ```
2771    /// In the more complex union case, where the union is a field of a struct, then if a mutable
2772    /// borrow of a union field in a struct `x.u.z` is attempted while a shared borrow of
2773    /// another field `x.u.y`, then this function will return:
2774    /// ```
2775    /// ("x.u", "x.u.z", "x.u.y")
2776    /// # ;
2777    /// ```
2778    /// This is used when creating error messages like below:
2779    ///
2780    /// ```text
2781    /// cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
2782    /// mutable (via `a.u.s.b`) [E0502]
2783    /// ```
2784    fn describe_place_for_conflicting_borrow(
2785        &self,
2786        first_borrowed_place: Place<'tcx>,
2787        second_borrowed_place: Place<'tcx>,
2788    ) -> (String, String, String, String) {
2789        // Define a small closure that we can use to check if the type of a place
2790        // is a union.
2791        let union_ty = |place_base| {
2792            // Need to use fn call syntax `PlaceRef::ty` to determine the type of `place_base`;
2793            // using a type annotation in the closure argument instead leads to a lifetime error.
2794            let ty = PlaceRef::ty(&place_base, self.body, self.infcx.tcx).ty;
2795            ty.ty_adt_def().filter(|adt| adt.is_union()).map(|_| ty)
2796        };
2797
2798        // Start with an empty tuple, so we can use the functions on `Option` to reduce some
2799        // code duplication (particularly around returning an empty description in the failure
2800        // case).
2801        Some(())
2802            .filter(|_| {
2803                // If we have a conflicting borrow of the same place, then we don't want to add
2804                // an extraneous "via x.y" to our diagnostics, so filter out this case.
2805                first_borrowed_place != second_borrowed_place
2806            })
2807            .and_then(|_| {
2808                // We're going to want to traverse the first borrowed place to see if we can find
2809                // field access to a union. If we find that, then we will keep the place of the
2810                // union being accessed and the field that was being accessed so we can check the
2811                // second borrowed place for the same union and an access to a different field.
2812                for (place_base, elem) in first_borrowed_place.iter_projections().rev() {
2813                    match elem {
2814                        ProjectionElem::Field(field, _) if union_ty(place_base).is_some() => {
2815                            return Some((place_base, field));
2816                        }
2817                        _ => {}
2818                    }
2819                }
2820                None
2821            })
2822            .and_then(|(target_base, target_field)| {
2823                // With the place of a union and a field access into it, we traverse the second
2824                // borrowed place and look for an access to a different field of the same union.
2825                for (place_base, elem) in second_borrowed_place.iter_projections().rev() {
2826                    if let ProjectionElem::Field(field, _) = elem
2827                        && let Some(union_ty) = union_ty(place_base)
2828                    {
2829                        if field != target_field && place_base == target_base {
2830                            return Some((
2831                                self.describe_any_place(place_base),
2832                                self.describe_any_place(first_borrowed_place.as_ref()),
2833                                self.describe_any_place(second_borrowed_place.as_ref()),
2834                                union_ty.to_string(),
2835                            ));
2836                        }
2837                    }
2838                }
2839                None
2840            })
2841            .unwrap_or_else(|| {
2842                // If we didn't find a field access into a union, or both places match, then
2843                // only return the description of the first place.
2844                (
2845                    self.describe_any_place(first_borrowed_place.as_ref()),
2846                    "".to_string(),
2847                    "".to_string(),
2848                    "".to_string(),
2849                )
2850            })
2851    }
2852
2853    /// This means that some data referenced by `borrow` needs to live
2854    /// past the point where the StorageDeadOrDrop of `place` occurs.
2855    /// This is usually interpreted as meaning that `place` has too
2856    /// short a lifetime. (But sometimes it is more useful to report
2857    /// it as a more direct conflict between the execution of a
2858    /// `Drop::drop` with an aliasing borrow.)
2859    #[instrument(level = "debug", skip(self))]
2860    pub(crate) fn report_borrowed_value_does_not_live_long_enough(
2861        &mut self,
2862        location: Location,
2863        borrow: &BorrowData<'tcx>,
2864        place_span: (Place<'tcx>, Span),
2865        kind: Option<WriteKind>,
2866    ) {
2867        let drop_span = place_span.1;
2868        let borrowed_local = borrow.borrowed_place.local;
2869
2870        let borrow_spans = self.retrieve_borrow_spans(borrow);
2871        let borrow_span = borrow_spans.var_or_use_path_span();
2872
2873        let proper_span = self.body.local_decls[borrowed_local].source_info.span;
2874
2875        if self.access_place_error_reported.contains(&(Place::from(borrowed_local), borrow_span)) {
2876            debug!(
2877                "suppressing access_place error when borrow doesn't live long enough for {:?}",
2878                borrow_span
2879            );
2880            return;
2881        }
2882
2883        self.access_place_error_reported.insert((Place::from(borrowed_local), borrow_span));
2884
2885        if self.body.local_decls[borrowed_local].is_ref_to_thread_local() {
2886            let err =
2887                self.report_thread_local_value_does_not_live_long_enough(drop_span, borrow_span);
2888            self.buffer_error(err);
2889            return;
2890        }
2891
2892        if let StorageDeadOrDrop::Destructor(dropped_ty) =
2893            self.classify_drop_access_kind(borrow.borrowed_place.as_ref())
2894        {
2895            // If a borrow of path `B` conflicts with drop of `D` (and
2896            // we're not in the uninteresting case where `B` is a
2897            // prefix of `D`), then report this as a more interesting
2898            // destructor conflict.
2899            if !borrow.borrowed_place.as_ref().is_prefix_of(place_span.0.as_ref()) {
2900                self.report_borrow_conflicts_with_destructor(
2901                    location, borrow, place_span, kind, dropped_ty,
2902                );
2903                return;
2904            }
2905        }
2906
2907        let place_desc = self.describe_place(borrow.borrowed_place.as_ref());
2908
2909        let kind_place = kind.filter(|_| place_desc.is_some()).map(|k| (k, place_span.0));
2910        let explanation = self.explain_why_borrow_contains_point(location, borrow, kind_place);
2911
2912        debug!(?place_desc, ?explanation);
2913
2914        let mut err = match (place_desc, explanation) {
2915            // If the outlives constraint comes from inside the closure,
2916            // for example:
2917            //
2918            // let x = 0;
2919            // let y = &x;
2920            // Box::new(|| y) as Box<Fn() -> &'static i32>
2921            //
2922            // then just use the normal error. The closure isn't escaping
2923            // and `move` will not help here.
2924            (
2925                Some(name),
2926                BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
2927            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
2928                .report_escaping_closure_capture(
2929                    borrow_spans,
2930                    borrow_span,
2931                    &RegionName {
2932                        name: self.synthesize_region_name(),
2933                        source: RegionNameSource::Static,
2934                    },
2935                    ConstraintCategory::CallArgument(None),
2936                    var_or_use_span,
2937                    &format!("`{name}`"),
2938                    "block",
2939                ),
2940            (
2941                Some(name),
2942                BorrowExplanation::MustBeValidFor {
2943                    category:
2944                        category @ (ConstraintCategory::Return(_)
2945                        | ConstraintCategory::CallArgument(_)
2946                        | ConstraintCategory::OpaqueType),
2947                    from_closure: false,
2948                    ref region_name,
2949                    span,
2950                    ..
2951                },
2952            ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
2953                .report_escaping_closure_capture(
2954                    borrow_spans,
2955                    borrow_span,
2956                    region_name,
2957                    category,
2958                    span,
2959                    &format!("`{name}`"),
2960                    "function",
2961                ),
2962            (
2963                name,
2964                BorrowExplanation::MustBeValidFor {
2965                    category: ConstraintCategory::Assignment,
2966                    from_closure: false,
2967                    region_name:
2968                        RegionName {
2969                            source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name),
2970                            ..
2971                        },
2972                    span,
2973                    ..
2974                },
2975            ) => self.report_escaping_data(borrow_span, &name, upvar_span, upvar_name, span),
2976            (Some(name), explanation) => self.report_local_value_does_not_live_long_enough(
2977                location,
2978                &name,
2979                borrow,
2980                drop_span,
2981                borrow_spans,
2982                explanation,
2983            ),
2984            (None, explanation) => self.report_temporary_value_does_not_live_long_enough(
2985                location,
2986                borrow,
2987                drop_span,
2988                borrow_spans,
2989                proper_span,
2990                explanation,
2991            ),
2992        };
2993        self.note_due_to_edition_2024_opaque_capture_rules(borrow, &mut err);
2994
2995        self.buffer_error(err);
2996    }
2997
2998    #[tracing::instrument(level = "debug", skip(self, explanation))]
2999    fn report_local_value_does_not_live_long_enough(
3000        &self,
3001        location: Location,
3002        name: &str,
3003        borrow: &BorrowData<'tcx>,
3004        drop_span: Span,
3005        borrow_spans: UseSpans<'tcx>,
3006        explanation: BorrowExplanation<'tcx>,
3007    ) -> Diag<'infcx> {
3008        let borrow_span = borrow_spans.var_or_use_path_span();
3009        if let BorrowExplanation::MustBeValidFor {
3010            category,
3011            span,
3012            ref opt_place_desc,
3013            from_closure: false,
3014            ..
3015        } = explanation
3016            && let Err(diag) = self.try_report_cannot_return_reference_to_local(
3017                borrow,
3018                borrow_span,
3019                span,
3020                category,
3021                opt_place_desc.as_ref(),
3022            )
3023        {
3024            return diag;
3025        }
3026
3027        let name = format!("`{name}`");
3028
3029        let mut err = self.path_does_not_live_long_enough(borrow_span, &name);
3030
3031        if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
3032            let region_name = annotation.emit(self, &mut err);
3033
3034            err.span_label(
3035                borrow_span,
3036                format!("{name} would have to be valid for `{region_name}`..."),
3037            );
3038
3039            err.span_label(
3040                drop_span,
3041                format!(
3042                    "...but {name} will be dropped here, when the {} returns",
3043                    self.infcx
3044                        .tcx
3045                        .opt_item_name(self.mir_def_id().to_def_id())
3046                        .map(|name| format!("function `{name}`"))
3047                        .unwrap_or_else(|| {
3048                            match &self.infcx.tcx.def_kind(self.mir_def_id()) {
3049                                DefKind::Closure
3050                                    if self
3051                                        .infcx
3052                                        .tcx
3053                                        .is_coroutine(self.mir_def_id().to_def_id()) =>
3054                                {
3055                                    "enclosing coroutine"
3056                                }
3057                                DefKind::Closure => "enclosing closure",
3058                                kind => bug!("expected closure or coroutine, found {:?}", kind),
3059                            }
3060                            .to_string()
3061                        })
3062                ),
3063            );
3064
3065            err.note(
3066                "functions cannot return a borrow to data owned within the function's scope, \
3067                    functions can only return borrows to data passed as arguments",
3068            );
3069            err.note(
3070                "to learn more, visit <https://doc.rust-lang.org/book/ch04-02-\
3071                    references-and-borrowing.html#dangling-references>",
3072            );
3073
3074            if let BorrowExplanation::MustBeValidFor { .. } = explanation {
3075            } else {
3076                explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3077            }
3078        } else {
3079            err.span_label(borrow_span, "borrowed value does not live long enough");
3080            err.span_label(drop_span, format!("{name} dropped here while still borrowed"));
3081
3082            borrow_spans.args_subdiag(&mut err, |args_span| {
3083                crate::session_diagnostics::CaptureArgLabel::Capture {
3084                    is_within: borrow_spans.for_coroutine(),
3085                    args_span,
3086                }
3087            });
3088
3089            explanation.add_explanation_to_diagnostic(&self, &mut err, "", Some(borrow_span), None);
3090
3091            // Detect buffer reuse pattern
3092            if let BorrowExplanation::UsedLater(_dropped_local, _, _, _) = explanation {
3093                // Check all locals at the borrow location to find Vec<&T> types
3094                for (local, local_decl) in self.body.local_decls.iter_enumerated() {
3095                    if let ty::Adt(adt_def, args) = local_decl.ty.kind()
3096                        && self.infcx.tcx.is_diagnostic_item(sym::Vec, adt_def.did())
3097                        && args.len() > 0
3098                    {
3099                        let vec_inner_ty = args.type_at(0);
3100                        // Check if Vec contains references
3101                        if vec_inner_ty.is_ref() {
3102                            let local_place = local.into();
3103                            if let Some(local_name) = self.describe_place(local_place) {
3104                                err.span_label(
3105                                    local_decl.source_info.span,
3106                                    format!("variable `{local_name}` declared here"),
3107                                );
3108                                err.note(
3109                                    format!(
3110                                        "`{local_name}` is a collection that stores borrowed references, \
3111                                         but {name} does not live long enough to be stored in it"
3112                                    )
3113                                );
3114                                err.help(
3115                                    "buffer reuse with borrowed references requires unsafe code or restructuring"
3116                                );
3117                                break;
3118                            }
3119                        }
3120                    }
3121                }
3122            }
3123        }
3124
3125        err
3126    }
3127
3128    fn report_borrow_conflicts_with_destructor(
3129        &mut self,
3130        location: Location,
3131        borrow: &BorrowData<'tcx>,
3132        (place, drop_span): (Place<'tcx>, Span),
3133        kind: Option<WriteKind>,
3134        dropped_ty: Ty<'tcx>,
3135    ) {
3136        debug!(
3137            "report_borrow_conflicts_with_destructor(\
3138             {:?}, {:?}, ({:?}, {:?}), {:?}\
3139             )",
3140            location, borrow, place, drop_span, kind,
3141        );
3142
3143        let borrow_spans = self.retrieve_borrow_spans(borrow);
3144        let borrow_span = borrow_spans.var_or_use();
3145
3146        let mut err = self.cannot_borrow_across_destructor(borrow_span);
3147
3148        let what_was_dropped = match self.describe_place(place.as_ref()) {
3149            Some(name) => format!("`{name}`"),
3150            None => String::from("temporary value"),
3151        };
3152
3153        let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
3154            Some(borrowed) => format!(
3155                "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
3156                 because the type `{dropped_ty}` implements the `Drop` trait"
3157            ),
3158            None => format!(
3159                "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
3160            ),
3161        };
3162        err.span_label(drop_span, label);
3163
3164        // Only give this note and suggestion if they could be relevant.
3165        let explanation =
3166            self.explain_why_borrow_contains_point(location, borrow, kind.map(|k| (k, place)));
3167        match explanation {
3168            BorrowExplanation::UsedLater { .. }
3169            | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3170                err.note("consider using a `let` binding to create a longer lived value");
3171            }
3172            _ => {}
3173        }
3174
3175        explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3176
3177        self.buffer_error(err);
3178    }
3179
3180    fn report_thread_local_value_does_not_live_long_enough(
3181        &self,
3182        drop_span: Span,
3183        borrow_span: Span,
3184    ) -> Diag<'infcx> {
3185        debug!(
3186            "report_thread_local_value_does_not_live_long_enough(\
3187             {:?}, {:?}\
3188             )",
3189            drop_span, borrow_span
3190        );
3191
3192        // `TerminatorKind::Return`'s span (the `drop_span` here) `lo` can be subtly wrong and point
3193        // at a single character after the end of the function. This is somehow relied upon in
3194        // existing diagnostics, and changing this in `rustc_mir_build` makes diagnostics worse in
3195        // general. We fix these here.
3196        let sm = self.infcx.tcx.sess.source_map();
3197        let end_of_function = if drop_span.is_empty()
3198            && let Ok(adjusted_span) = sm.span_extend_prev_while(drop_span, |c| c == '}')
3199        {
3200            adjusted_span
3201        } else {
3202            drop_span
3203        };
3204        self.thread_local_value_does_not_live_long_enough(borrow_span)
3205            .with_span_label(
3206                borrow_span,
3207                "thread-local variables cannot be borrowed beyond the end of the function",
3208            )
3209            .with_span_label(end_of_function, "end of enclosing function is here")
3210    }
3211
3212    #[instrument(level = "debug", skip(self))]
3213    fn report_temporary_value_does_not_live_long_enough(
3214        &self,
3215        location: Location,
3216        borrow: &BorrowData<'tcx>,
3217        drop_span: Span,
3218        borrow_spans: UseSpans<'tcx>,
3219        proper_span: Span,
3220        explanation: BorrowExplanation<'tcx>,
3221    ) -> Diag<'infcx> {
3222        if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
3223            explanation
3224        {
3225            if let Err(diag) = self.try_report_cannot_return_reference_to_local(
3226                borrow,
3227                proper_span,
3228                span,
3229                category,
3230                None,
3231            ) {
3232                return diag;
3233            }
3234        }
3235
3236        let mut err = self.temporary_value_borrowed_for_too_long(proper_span);
3237        err.span_label(proper_span, "creates a temporary value which is freed while still in use");
3238        err.span_label(drop_span, "temporary value is freed at the end of this statement");
3239
3240        match explanation {
3241            BorrowExplanation::UsedLater(..)
3242            | BorrowExplanation::UsedLaterInLoop(..)
3243            | BorrowExplanation::UsedLaterWhenDropped { .. } => {
3244                // Only give this note and suggestion if it could be relevant.
3245                let sm = self.infcx.tcx.sess.source_map();
3246                let mut suggested = false;
3247                let msg = "consider using a `let` binding to create a longer lived value";
3248
3249                /// We check that there's a single level of block nesting to ensure always correct
3250                /// suggestions. If we don't, then we only provide a free-form message to avoid
3251                /// misleading users in cases like `tests/ui/nll/borrowed-temporary-error.rs`.
3252                /// We could expand the analysis to suggest hoising all of the relevant parts of
3253                /// the users' code to make the code compile, but that could be too much.
3254                /// We found the `prop_expr` by the way to check whether the expression is a
3255                /// `FormatArguments`, which is a special case since it's generated by the
3256                /// compiler.
3257                struct NestedStatementVisitor<'tcx> {
3258                    span: Span,
3259                    current: usize,
3260                    found: usize,
3261                    prop_expr: Option<&'tcx hir::Expr<'tcx>>,
3262                    call: Option<&'tcx hir::Expr<'tcx>>,
3263                }
3264
3265                impl<'tcx> Visitor<'tcx> for NestedStatementVisitor<'tcx> {
3266                    fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
3267                        self.current += 1;
3268                        walk_block(self, block);
3269                        self.current -= 1;
3270                    }
3271                    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3272                        if let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind {
3273                            if self.span == rcvr.span.source_callsite() {
3274                                self.call = Some(expr);
3275                            }
3276                        }
3277                        if self.span == expr.span.source_callsite() {
3278                            self.found = self.current;
3279                            if self.prop_expr.is_none() {
3280                                self.prop_expr = Some(expr);
3281                            }
3282                        }
3283                        walk_expr(self, expr);
3284                    }
3285                }
3286                let source_info = self.body.source_info(location);
3287                let proper_span = proper_span.source_callsite();
3288                if let Some(scope) = self.body.source_scopes.get(source_info.scope)
3289                    && let ClearCrossCrate::Set(scope_data) = &scope.local_data
3290                    && let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
3291                    && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
3292                {
3293                    for stmt in block.stmts {
3294                        let mut visitor = NestedStatementVisitor {
3295                            span: proper_span,
3296                            current: 0,
3297                            found: 0,
3298                            prop_expr: None,
3299                            call: None,
3300                        };
3301                        visitor.visit_stmt(stmt);
3302
3303                        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
3304                        let expr_ty: Option<Ty<'_>> =
3305                            visitor.prop_expr.map(|expr| typeck_results.expr_ty(expr).peel_refs());
3306
3307                        if visitor.found == 0
3308                            && stmt.span.contains(proper_span)
3309                            && let Some(p) = sm.span_to_margin(stmt.span)
3310                            && let Ok(s) = sm.span_to_snippet(proper_span)
3311                        {
3312                            if let Some(call) = visitor.call
3313                                && let hir::ExprKind::MethodCall(path, _, [], _) = call.kind
3314                                && path.ident.name == sym::iter
3315                                && let Some(ty) = expr_ty
3316                            {
3317                                err.span_suggestion_verbose(
3318                                    path.ident.span,
3319                                    format!(
3320                                        "consider consuming the `{ty}` when turning it into an \
3321                                         `Iterator`",
3322                                    ),
3323                                    "into_iter",
3324                                    Applicability::MaybeIncorrect,
3325                                );
3326                            }
3327
3328                            let mutability = if matches!(borrow.kind(), BorrowKind::Mut { .. }) {
3329                                "mut "
3330                            } else {
3331                                ""
3332                            };
3333
3334                            let addition =
3335                                format!("let {}binding = {};\n{}", mutability, s, " ".repeat(p));
3336                            err.multipart_suggestion_verbose(
3337                                msg,
3338                                vec![
3339                                    (stmt.span.shrink_to_lo(), addition),
3340                                    (proper_span, "binding".to_string()),
3341                                ],
3342                                Applicability::MaybeIncorrect,
3343                            );
3344
3345                            suggested = true;
3346                            break;
3347                        }
3348                    }
3349                }
3350                if !suggested {
3351                    err.note(msg);
3352                }
3353            }
3354            _ => {}
3355        }
3356        explanation.add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3357
3358        borrow_spans.args_subdiag(&mut err, |args_span| {
3359            crate::session_diagnostics::CaptureArgLabel::Capture {
3360                is_within: borrow_spans.for_coroutine(),
3361                args_span,
3362            }
3363        });
3364
3365        err
3366    }
3367
3368    fn try_report_cannot_return_reference_to_local(
3369        &self,
3370        borrow: &BorrowData<'tcx>,
3371        borrow_span: Span,
3372        return_span: Span,
3373        category: ConstraintCategory<'tcx>,
3374        opt_place_desc: Option<&String>,
3375    ) -> Result<(), Diag<'infcx>> {
3376        let return_kind = match category {
3377            ConstraintCategory::Return(_) => "return",
3378            ConstraintCategory::Yield => "yield",
3379            _ => return Ok(()),
3380        };
3381
3382        // FIXME use a better heuristic than Spans
3383        let reference_desc = if return_span == self.body.source_info(borrow.reserve_location).span {
3384            "reference to"
3385        } else {
3386            "value referencing"
3387        };
3388
3389        let (place_desc, note) = if let Some(place_desc) = opt_place_desc {
3390            let local_kind = if let Some(local) = borrow.borrowed_place.as_local() {
3391                match self.body.local_kind(local) {
3392                    LocalKind::Temp if self.body.local_decls[local].is_user_variable() => {
3393                        "local variable "
3394                    }
3395                    LocalKind::Arg
3396                        if !self.upvars.is_empty() && local == ty::CAPTURE_STRUCT_LOCAL =>
3397                    {
3398                        "variable captured by `move` "
3399                    }
3400                    LocalKind::Arg => "function parameter ",
3401                    LocalKind::ReturnPointer | LocalKind::Temp => {
3402                        bug!("temporary or return pointer with a name")
3403                    }
3404                }
3405            } else {
3406                "local data "
3407            };
3408            (format!("{local_kind}`{place_desc}`"), format!("`{place_desc}` is borrowed here"))
3409        } else {
3410            let local = borrow.borrowed_place.local;
3411            match self.body.local_kind(local) {
3412                LocalKind::Arg => (
3413                    "function parameter".to_string(),
3414                    "function parameter borrowed here".to_string(),
3415                ),
3416                LocalKind::Temp
3417                    if self.body.local_decls[local].is_user_variable()
3418                        && !self.body.local_decls[local]
3419                            .source_info
3420                            .span
3421                            .in_external_macro(self.infcx.tcx.sess.source_map()) =>
3422                {
3423                    ("local binding".to_string(), "local binding introduced here".to_string())
3424                }
3425                LocalKind::ReturnPointer | LocalKind::Temp => {
3426                    ("temporary value".to_string(), "temporary value created here".to_string())
3427                }
3428            }
3429        };
3430
3431        let mut err = self.cannot_return_reference_to_local(
3432            return_span,
3433            return_kind,
3434            reference_desc,
3435            &place_desc,
3436        );
3437
3438        if return_span != borrow_span {
3439            err.span_label(borrow_span, note);
3440
3441            let tcx = self.infcx.tcx;
3442
3443            let return_ty = self.regioncx.universal_regions().unnormalized_output_ty;
3444
3445            // to avoid panics
3446            if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator)
3447                && self
3448                    .infcx
3449                    .type_implements_trait(iter_trait, [return_ty], self.infcx.param_env)
3450                    .must_apply_modulo_regions()
3451            {
3452                err.span_suggestion_hidden(
3453                    return_span.shrink_to_hi(),
3454                    "use `.collect()` to allocate the iterator",
3455                    ".collect::<Vec<_>>()",
3456                    Applicability::MaybeIncorrect,
3457                );
3458            }
3459        }
3460
3461        Err(err)
3462    }
3463
3464    #[instrument(level = "debug", skip(self))]
3465    fn report_escaping_closure_capture(
3466        &self,
3467        use_span: UseSpans<'tcx>,
3468        var_span: Span,
3469        fr_name: &RegionName,
3470        category: ConstraintCategory<'tcx>,
3471        constraint_span: Span,
3472        captured_var: &str,
3473        scope: &str,
3474    ) -> Diag<'infcx> {
3475        let tcx = self.infcx.tcx;
3476        let args_span = use_span.args_or_use();
3477
3478        let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
3479            Ok(string) => {
3480                let coro_prefix = if let Some(sub) = string.strip_prefix("async") {
3481                    let trimmed_sub = sub.trim_end();
3482                    if trimmed_sub.ends_with("gen") {
3483                        // `async` is 5 chars long.
3484                        Some((trimmed_sub.len() + 5) as _)
3485                    } else {
3486                        // `async` is 5 chars long.
3487                        Some(5)
3488                    }
3489                } else if string.starts_with("gen") {
3490                    // `gen` is 3 chars long
3491                    Some(3)
3492                } else if string.starts_with("static") {
3493                    // `static` is 6 chars long
3494                    // This is used for `!Unpin` coroutines
3495                    Some(6)
3496                } else {
3497                    None
3498                };
3499                if let Some(n) = coro_prefix {
3500                    let pos = args_span.lo() + BytePos(n);
3501                    (args_span.with_lo(pos).with_hi(pos), " move")
3502                } else {
3503                    (args_span.shrink_to_lo(), "move ")
3504                }
3505            }
3506            Err(_) => (args_span, "move |<args>| <body>"),
3507        };
3508        let kind = match use_span.coroutine_kind() {
3509            Some(coroutine_kind) => match coroutine_kind {
3510                CoroutineKind::Desugared(CoroutineDesugaring::Gen, kind) => match kind {
3511                    CoroutineSource::Block => "gen block",
3512                    CoroutineSource::Closure => "gen closure",
3513                    CoroutineSource::Fn => {
3514                        bug!("gen block/closure expected, but gen function found.")
3515                    }
3516                },
3517                CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, kind) => match kind {
3518                    CoroutineSource::Block => "async gen block",
3519                    CoroutineSource::Closure => "async gen closure",
3520                    CoroutineSource::Fn => {
3521                        bug!("gen block/closure expected, but gen function found.")
3522                    }
3523                },
3524                CoroutineKind::Desugared(CoroutineDesugaring::Async, async_kind) => {
3525                    match async_kind {
3526                        CoroutineSource::Block => "async block",
3527                        CoroutineSource::Closure => "async closure",
3528                        CoroutineSource::Fn => {
3529                            bug!("async block/closure expected, but async function found.")
3530                        }
3531                    }
3532                }
3533                CoroutineKind::Coroutine(_) => "coroutine",
3534            },
3535            None => "closure",
3536        };
3537
3538        let mut err = self.cannot_capture_in_long_lived_closure(
3539            args_span,
3540            kind,
3541            captured_var,
3542            var_span,
3543            scope,
3544        );
3545        err.span_suggestion_verbose(
3546            sugg_span,
3547            format!(
3548                "to force the {kind} to take ownership of {captured_var} (and any \
3549                 other referenced variables), use the `move` keyword"
3550            ),
3551            suggestion,
3552            Applicability::MachineApplicable,
3553        );
3554
3555        match category {
3556            ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
3557                let msg = format!("{kind} is returned here");
3558                err.span_note(constraint_span, msg);
3559            }
3560            ConstraintCategory::CallArgument(_) => {
3561                fr_name.highlight_region_name(&mut err);
3562                if matches!(
3563                    use_span.coroutine_kind(),
3564                    Some(CoroutineKind::Desugared(CoroutineDesugaring::Async, _))
3565                ) {
3566                    err.note(
3567                        "async blocks are not executed immediately and must either take a \
3568                         reference or ownership of outside variables they use",
3569                    );
3570                } else {
3571                    let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
3572                    err.span_note(constraint_span, msg);
3573                }
3574            }
3575            _ => bug!(
3576                "report_escaping_closure_capture called with unexpected constraint \
3577                 category: `{:?}`",
3578                category
3579            ),
3580        }
3581
3582        err
3583    }
3584
3585    fn report_escaping_data(
3586        &self,
3587        borrow_span: Span,
3588        name: &Option<String>,
3589        upvar_span: Span,
3590        upvar_name: Symbol,
3591        escape_span: Span,
3592    ) -> Diag<'infcx> {
3593        let tcx = self.infcx.tcx;
3594
3595        let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
3596
3597        let mut err =
3598            borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
3599
3600        err.span_label(
3601            upvar_span,
3602            format!("`{upvar_name}` declared here, outside of the {escapes_from} body"),
3603        );
3604
3605        err.span_label(borrow_span, format!("borrow is only valid in the {escapes_from} body"));
3606
3607        if let Some(name) = name {
3608            err.span_label(
3609                escape_span,
3610                format!("reference to `{name}` escapes the {escapes_from} body here"),
3611            );
3612        } else {
3613            err.span_label(escape_span, format!("reference escapes the {escapes_from} body here"));
3614        }
3615
3616        err
3617    }
3618
3619    fn get_moved_indexes(
3620        &self,
3621        location: Location,
3622        mpi: MovePathIndex,
3623    ) -> (Vec<MoveSite>, Vec<Location>) {
3624        fn predecessor_locations<'tcx>(
3625            body: &mir::Body<'tcx>,
3626            location: Location,
3627        ) -> impl Iterator<Item = Location> {
3628            if location.statement_index == 0 {
3629                let predecessors = body.basic_blocks.predecessors()[location.block].to_vec();
3630                Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
3631            } else {
3632                Either::Right(std::iter::once(Location {
3633                    statement_index: location.statement_index - 1,
3634                    ..location
3635                }))
3636            }
3637        }
3638
3639        let mut mpis = vec![mpi];
3640        let move_paths = &self.move_data.move_paths;
3641        mpis.extend(move_paths[mpi].parents(move_paths).map(|(mpi, _)| mpi));
3642
3643        let mut stack = Vec::new();
3644        let mut back_edge_stack = Vec::new();
3645
3646        predecessor_locations(self.body, location).for_each(|predecessor| {
3647            if location.dominates(predecessor, self.dominators()) {
3648                back_edge_stack.push(predecessor)
3649            } else {
3650                stack.push(predecessor);
3651            }
3652        });
3653
3654        let mut reached_start = false;
3655
3656        /* Check if the mpi is initialized as an argument */
3657        let mut is_argument = false;
3658        for arg in self.body.args_iter() {
3659            if let Some(path) = self.move_data.rev_lookup.find_local(arg) {
3660                if mpis.contains(&path) {
3661                    is_argument = true;
3662                }
3663            }
3664        }
3665
3666        let mut visited = FxIndexSet::default();
3667        let mut move_locations = FxIndexSet::default();
3668        let mut reinits = vec![];
3669        let mut result = vec![];
3670
3671        let mut dfs_iter = |result: &mut Vec<MoveSite>, location: Location, is_back_edge: bool| {
3672            debug!(
3673                "report_use_of_moved_or_uninitialized: (current_location={:?}, back_edge={})",
3674                location, is_back_edge
3675            );
3676
3677            if !visited.insert(location) {
3678                return true;
3679            }
3680
3681            // check for moves
3682            let stmt_kind =
3683                self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
3684            if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3685                // This analysis only tries to find moves explicitly written by the user, so we
3686                // ignore the move-outs created by `StorageDead` and at the beginning of a
3687                // function.
3688            } else {
3689                // If we are found a use of a.b.c which was in error, then we want to look for
3690                // moves not only of a.b.c but also a.b and a.
3691                //
3692                // Note that the moves data already includes "parent" paths, so we don't have to
3693                // worry about the other case: that is, if there is a move of a.b.c, it is already
3694                // marked as a move of a.b and a as well, so we will generate the correct errors
3695                // there.
3696                for moi in &self.move_data.loc_map[location] {
3697                    debug!("report_use_of_moved_or_uninitialized: moi={:?}", moi);
3698                    let path = self.move_data.moves[*moi].path;
3699                    if mpis.contains(&path) {
3700                        debug!(
3701                            "report_use_of_moved_or_uninitialized: found {:?}",
3702                            move_paths[path].place
3703                        );
3704                        result.push(MoveSite { moi: *moi, traversed_back_edge: is_back_edge });
3705                        move_locations.insert(location);
3706
3707                        // Strictly speaking, we could continue our DFS here. There may be
3708                        // other moves that can reach the point of error. But it is kind of
3709                        // confusing to highlight them.
3710                        //
3711                        // Example:
3712                        //
3713                        // ```
3714                        // let a = vec![];
3715                        // let b = a;
3716                        // let c = a;
3717                        // drop(a); // <-- current point of error
3718                        // ```
3719                        //
3720                        // Because we stop the DFS here, we only highlight `let c = a`,
3721                        // and not `let b = a`. We will of course also report an error at
3722                        // `let c = a` which highlights `let b = a` as the move.
3723                        return true;
3724                    }
3725                }
3726            }
3727
3728            // check for inits
3729            let mut any_match = false;
3730            for ii in &self.move_data.init_loc_map[location] {
3731                let init = self.move_data.inits[*ii];
3732                match init.kind {
3733                    InitKind::Deep | InitKind::NonPanicPathOnly => {
3734                        if mpis.contains(&init.path) {
3735                            any_match = true;
3736                        }
3737                    }
3738                    InitKind::Shallow => {
3739                        if mpi == init.path {
3740                            any_match = true;
3741                        }
3742                    }
3743                }
3744            }
3745            if any_match {
3746                reinits.push(location);
3747                return true;
3748            }
3749            false
3750        };
3751
3752        while let Some(location) = stack.pop() {
3753            if dfs_iter(&mut result, location, false) {
3754                continue;
3755            }
3756
3757            let mut has_predecessor = false;
3758            predecessor_locations(self.body, location).for_each(|predecessor| {
3759                if location.dominates(predecessor, self.dominators()) {
3760                    back_edge_stack.push(predecessor)
3761                } else {
3762                    stack.push(predecessor);
3763                }
3764                has_predecessor = true;
3765            });
3766
3767            if !has_predecessor {
3768                reached_start = true;
3769            }
3770        }
3771        if (is_argument || !reached_start) && result.is_empty() {
3772            // Process back edges (moves in future loop iterations) only if
3773            // the move path is definitely initialized upon loop entry,
3774            // to avoid spurious "in previous iteration" errors.
3775            // During DFS, if there's a path from the error back to the start
3776            // of the function with no intervening init or move, then the
3777            // move path may be uninitialized at loop entry.
3778            while let Some(location) = back_edge_stack.pop() {
3779                if dfs_iter(&mut result, location, true) {
3780                    continue;
3781                }
3782
3783                predecessor_locations(self.body, location)
3784                    .for_each(|predecessor| back_edge_stack.push(predecessor));
3785            }
3786        }
3787
3788        // Check if we can reach these reinits from a move location.
3789        let reinits_reachable = reinits
3790            .into_iter()
3791            .filter(|reinit| {
3792                let mut visited = FxIndexSet::default();
3793                let mut stack = vec![*reinit];
3794                while let Some(location) = stack.pop() {
3795                    if !visited.insert(location) {
3796                        continue;
3797                    }
3798                    if move_locations.contains(&location) {
3799                        return true;
3800                    }
3801                    stack.extend(predecessor_locations(self.body, location));
3802                }
3803                false
3804            })
3805            .collect::<Vec<Location>>();
3806        (result, reinits_reachable)
3807    }
3808
3809    pub(crate) fn report_illegal_mutation_of_borrowed(
3810        &mut self,
3811        location: Location,
3812        (place, span): (Place<'tcx>, Span),
3813        loan: &BorrowData<'tcx>,
3814    ) {
3815        let loan_spans = self.retrieve_borrow_spans(loan);
3816        let loan_span = loan_spans.args_or_use();
3817
3818        let descr_place = self.describe_any_place(place.as_ref());
3819        if let BorrowKind::Fake(_) = loan.kind
3820            && let Some(section) = self.classify_immutable_section(loan.assigned_place)
3821        {
3822            let mut err = self.cannot_mutate_in_immutable_section(
3823                span,
3824                loan_span,
3825                &descr_place,
3826                section,
3827                "assign",
3828            );
3829
3830            loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3831                use crate::session_diagnostics::CaptureVarCause::*;
3832                match kind {
3833                    hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3834                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3835                        BorrowUseInClosure { var_span }
3836                    }
3837                }
3838            });
3839
3840            self.buffer_error(err);
3841
3842            return;
3843        }
3844
3845        let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
3846        self.note_due_to_edition_2024_opaque_capture_rules(loan, &mut err);
3847
3848        loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
3849            use crate::session_diagnostics::CaptureVarCause::*;
3850            match kind {
3851                hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
3852                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
3853                    BorrowUseInClosure { var_span }
3854                }
3855            }
3856        });
3857
3858        self.explain_why_borrow_contains_point(location, loan, None)
3859            .add_explanation_to_diagnostic(&self, &mut err, "", None, None);
3860
3861        self.explain_deref_coercion(loan, &mut err);
3862
3863        self.buffer_error(err);
3864    }
3865
3866    fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
3867        let tcx = self.infcx.tcx;
3868        if let Some(Terminator { kind: TerminatorKind::Call { call_source, fn_span, .. }, .. }) =
3869            &self.body[loan.reserve_location.block].terminator
3870            && let Some((method_did, method_args)) = mir::find_self_call(
3871                tcx,
3872                self.body,
3873                loan.assigned_place.local,
3874                loan.reserve_location.block,
3875            )
3876            && let CallKind::DerefCoercion { deref_target_span, deref_target_ty, .. } = call_kind(
3877                self.infcx.tcx,
3878                self.infcx.typing_env(self.infcx.param_env),
3879                method_did,
3880                method_args,
3881                *fn_span,
3882                call_source.from_hir_call(),
3883                self.infcx.tcx.fn_arg_idents(method_did)[0],
3884            )
3885        {
3886            err.note(format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
3887            if let Some(deref_target_span) = deref_target_span {
3888                err.span_note(deref_target_span, "deref defined here");
3889            }
3890        }
3891    }
3892
3893    /// Reports an illegal reassignment; for example, an assignment to
3894    /// (part of) a non-`mut` local that occurs potentially after that
3895    /// local has already been initialized. `place` is the path being
3896    /// assigned; `err_place` is a place providing a reason why
3897    /// `place` is not mutable (e.g., the non-`mut` local `x` in an
3898    /// assignment to `x.f`).
3899    pub(crate) fn report_illegal_reassignment(
3900        &mut self,
3901        (place, span): (Place<'tcx>, Span),
3902        assigned_span: Span,
3903        err_place: Place<'tcx>,
3904    ) {
3905        let (from_arg, local_decl) = match err_place.as_local() {
3906            Some(local) => {
3907                (self.body.local_kind(local) == LocalKind::Arg, Some(&self.body.local_decls[local]))
3908            }
3909            None => (false, None),
3910        };
3911
3912        // If root local is initialized immediately (everything apart from let
3913        // PATTERN;) then make the error refer to that local, rather than the
3914        // place being assigned later.
3915        let (place_description, assigned_span) = match local_decl {
3916            Some(LocalDecl {
3917                local_info:
3918                    ClearCrossCrate::Set(
3919                        box LocalInfo::User(BindingForm::Var(VarBindingForm {
3920                            opt_match_place: None,
3921                            ..
3922                        }))
3923                        | box LocalInfo::StaticRef { .. }
3924                        | box LocalInfo::Boring,
3925                    ),
3926                ..
3927            })
3928            | None => (self.describe_any_place(place.as_ref()), assigned_span),
3929            Some(decl) => (self.describe_any_place(err_place.as_ref()), decl.source_info.span),
3930        };
3931        let mut err = self.cannot_reassign_immutable(span, &place_description, from_arg);
3932        let msg = if from_arg {
3933            "cannot assign to immutable argument"
3934        } else {
3935            "cannot assign twice to immutable variable"
3936        };
3937        if span != assigned_span && !from_arg {
3938            err.span_label(assigned_span, format!("first assignment to {place_description}"));
3939        }
3940        if let Some(decl) = local_decl
3941            && decl.can_be_made_mutable()
3942        {
3943            err.span_suggestion_verbose(
3944                decl.source_info.span.shrink_to_lo(),
3945                "consider making this binding mutable",
3946                "mut ".to_string(),
3947                Applicability::MachineApplicable,
3948            );
3949            if !from_arg
3950                && matches!(
3951                    decl.local_info(),
3952                    LocalInfo::User(BindingForm::Var(VarBindingForm {
3953                        opt_match_place: Some((Some(_), _)),
3954                        ..
3955                    }))
3956                )
3957            {
3958                err.span_suggestion_verbose(
3959                    decl.source_info.span.shrink_to_lo(),
3960                    "to modify the original value, take a borrow instead",
3961                    "ref mut ".to_string(),
3962                    Applicability::MaybeIncorrect,
3963                );
3964            }
3965        }
3966        err.span_label(span, msg);
3967        self.buffer_error(err);
3968    }
3969
3970    fn classify_drop_access_kind(&self, place: PlaceRef<'tcx>) -> StorageDeadOrDrop<'tcx> {
3971        let tcx = self.infcx.tcx;
3972        let (kind, _place_ty) = place.projection.iter().fold(
3973            (LocalStorageDead, PlaceTy::from_ty(self.body.local_decls[place.local].ty)),
3974            |(kind, place_ty), &elem| {
3975                (
3976                    match elem {
3977                        ProjectionElem::Deref => match kind {
3978                            StorageDeadOrDrop::LocalStorageDead
3979                            | StorageDeadOrDrop::BoxedStorageDead => {
3980                                assert!(
3981                                    place_ty.ty.is_box(),
3982                                    "Drop of value behind a reference or raw pointer"
3983                                );
3984                                StorageDeadOrDrop::BoxedStorageDead
3985                            }
3986                            StorageDeadOrDrop::Destructor(_) => kind,
3987                        },
3988                        ProjectionElem::OpaqueCast { .. }
3989                        | ProjectionElem::Field(..)
3990                        | ProjectionElem::Downcast(..) => {
3991                            match place_ty.ty.kind() {
3992                                ty::Adt(def, _) if def.has_dtor(tcx) => {
3993                                    // Report the outermost adt with a destructor
3994                                    match kind {
3995                                        StorageDeadOrDrop::Destructor(_) => kind,
3996                                        StorageDeadOrDrop::LocalStorageDead
3997                                        | StorageDeadOrDrop::BoxedStorageDead => {
3998                                            StorageDeadOrDrop::Destructor(place_ty.ty)
3999                                        }
4000                                    }
4001                                }
4002                                _ => kind,
4003                            }
4004                        }
4005                        ProjectionElem::ConstantIndex { .. }
4006                        | ProjectionElem::Subslice { .. }
4007                        | ProjectionElem::Index(_)
4008                        | ProjectionElem::UnwrapUnsafeBinder(_) => kind,
4009                    },
4010                    place_ty.projection_ty(tcx, elem),
4011                )
4012            },
4013        );
4014        kind
4015    }
4016
4017    /// Describe the reason for the fake borrow that was assigned to `place`.
4018    fn classify_immutable_section(&self, place: Place<'tcx>) -> Option<&'static str> {
4019        use rustc_middle::mir::visit::Visitor;
4020        struct FakeReadCauseFinder<'tcx> {
4021            place: Place<'tcx>,
4022            cause: Option<FakeReadCause>,
4023        }
4024        impl<'tcx> Visitor<'tcx> for FakeReadCauseFinder<'tcx> {
4025            fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
4026                match statement {
4027                    Statement { kind: StatementKind::FakeRead(box (cause, place)), .. }
4028                        if *place == self.place =>
4029                    {
4030                        self.cause = Some(*cause);
4031                    }
4032                    _ => (),
4033                }
4034            }
4035        }
4036        let mut visitor = FakeReadCauseFinder { place, cause: None };
4037        visitor.visit_body(self.body);
4038        match visitor.cause {
4039            Some(FakeReadCause::ForMatchGuard) => Some("match guard"),
4040            Some(FakeReadCause::ForIndex) => Some("indexing expression"),
4041            _ => None,
4042        }
4043    }
4044
4045    /// Annotate argument and return type of function and closure with (synthesized) lifetime for
4046    /// borrow of local value that does not live long enough.
4047    fn annotate_argument_and_return_for_borrow(
4048        &self,
4049        borrow: &BorrowData<'tcx>,
4050    ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4051        // Define a fallback for when we can't match a closure.
4052        let fallback = || {
4053            let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
4054            if is_closure {
4055                None
4056            } else {
4057                let ty = self.infcx.tcx.type_of(self.mir_def_id()).instantiate_identity();
4058                match ty.kind() {
4059                    ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
4060                        self.mir_def_id(),
4061                        self.infcx.tcx.fn_sig(self.mir_def_id()).instantiate_identity(),
4062                    ),
4063                    _ => None,
4064                }
4065            }
4066        };
4067
4068        // In order to determine whether we need to annotate, we need to check whether the reserve
4069        // place was an assignment into a temporary.
4070        //
4071        // If it was, we check whether or not that temporary is eventually assigned into the return
4072        // place. If it was, we can add annotations about the function's return type and arguments
4073        // and it'll make sense.
4074        let location = borrow.reserve_location;
4075        debug!("annotate_argument_and_return_for_borrow: location={:?}", location);
4076        if let Some(Statement { kind: StatementKind::Assign(box (reservation, _)), .. }) =
4077            &self.body[location.block].statements.get(location.statement_index)
4078        {
4079            debug!("annotate_argument_and_return_for_borrow: reservation={:?}", reservation);
4080            // Check that the initial assignment of the reserve location is into a temporary.
4081            let mut target = match reservation.as_local() {
4082                Some(local) if self.body.local_kind(local) == LocalKind::Temp => local,
4083                _ => return None,
4084            };
4085
4086            // Next, look through the rest of the block, checking if we are assigning the
4087            // `target` (that is, the place that contains our borrow) to anything.
4088            let mut annotated_closure = None;
4089            for stmt in &self.body[location.block].statements[location.statement_index + 1..] {
4090                debug!(
4091                    "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}",
4092                    target, stmt
4093                );
4094                if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind
4095                    && let Some(assigned_to) = place.as_local()
4096                {
4097                    debug!(
4098                        "annotate_argument_and_return_for_borrow: assigned_to={:?} \
4099                             rvalue={:?}",
4100                        assigned_to, rvalue
4101                    );
4102                    // Check if our `target` was captured by a closure.
4103                    if let Rvalue::Aggregate(box AggregateKind::Closure(def_id, args), operands) =
4104                        rvalue
4105                    {
4106                        let def_id = def_id.expect_local();
4107                        for operand in operands {
4108                            let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4109                                operand
4110                            else {
4111                                continue;
4112                            };
4113                            debug!(
4114                                "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4115                                assigned_from
4116                            );
4117
4118                            // Find the local from the operand.
4119                            let Some(assigned_from_local) = assigned_from.local_or_deref_local()
4120                            else {
4121                                continue;
4122                            };
4123
4124                            if assigned_from_local != target {
4125                                continue;
4126                            }
4127
4128                            // If a closure captured our `target` and then assigned
4129                            // into a place then we should annotate the closure in
4130                            // case it ends up being assigned into the return place.
4131                            annotated_closure =
4132                                self.annotate_fn_sig(def_id, args.as_closure().sig());
4133                            debug!(
4134                                "annotate_argument_and_return_for_borrow: \
4135                                     annotated_closure={:?} assigned_from_local={:?} \
4136                                     assigned_to={:?}",
4137                                annotated_closure, assigned_from_local, assigned_to
4138                            );
4139
4140                            if assigned_to == mir::RETURN_PLACE {
4141                                // If it was assigned directly into the return place, then
4142                                // return now.
4143                                return annotated_closure;
4144                            } else {
4145                                // Otherwise, update the target.
4146                                target = assigned_to;
4147                            }
4148                        }
4149
4150                        // If none of our closure's operands matched, then skip to the next
4151                        // statement.
4152                        continue;
4153                    }
4154
4155                    // Otherwise, look at other types of assignment.
4156                    let assigned_from = match rvalue {
4157                        Rvalue::Ref(_, _, assigned_from) => assigned_from,
4158                        Rvalue::Use(operand) => match operand {
4159                            Operand::Copy(assigned_from) | Operand::Move(assigned_from) => {
4160                                assigned_from
4161                            }
4162                            _ => continue,
4163                        },
4164                        _ => continue,
4165                    };
4166                    debug!(
4167                        "annotate_argument_and_return_for_borrow: \
4168                             assigned_from={:?}",
4169                        assigned_from,
4170                    );
4171
4172                    // Find the local from the rvalue.
4173                    let Some(assigned_from_local) = assigned_from.local_or_deref_local() else {
4174                        continue;
4175                    };
4176                    debug!(
4177                        "annotate_argument_and_return_for_borrow: \
4178                             assigned_from_local={:?}",
4179                        assigned_from_local,
4180                    );
4181
4182                    // Check if our local matches the target - if so, we've assigned our
4183                    // borrow to a new place.
4184                    if assigned_from_local != target {
4185                        continue;
4186                    }
4187
4188                    // If we assigned our `target` into a new place, then we should
4189                    // check if it was the return place.
4190                    debug!(
4191                        "annotate_argument_and_return_for_borrow: \
4192                             assigned_from_local={:?} assigned_to={:?}",
4193                        assigned_from_local, assigned_to
4194                    );
4195                    if assigned_to == mir::RETURN_PLACE {
4196                        // If it was then return the annotated closure if there was one,
4197                        // else, annotate this function.
4198                        return annotated_closure.or_else(fallback);
4199                    }
4200
4201                    // If we didn't assign into the return place, then we just update
4202                    // the target.
4203                    target = assigned_to;
4204                }
4205            }
4206
4207            // Check the terminator if we didn't find anything in the statements.
4208            let terminator = &self.body[location.block].terminator();
4209            debug!(
4210                "annotate_argument_and_return_for_borrow: target={:?} terminator={:?}",
4211                target, terminator
4212            );
4213            if let TerminatorKind::Call { destination, target: Some(_), args, .. } =
4214                &terminator.kind
4215                && let Some(assigned_to) = destination.as_local()
4216            {
4217                debug!(
4218                    "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}",
4219                    assigned_to, args
4220                );
4221                for operand in args {
4222                    let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) =
4223                        &operand.node
4224                    else {
4225                        continue;
4226                    };
4227                    debug!(
4228                        "annotate_argument_and_return_for_borrow: assigned_from={:?}",
4229                        assigned_from,
4230                    );
4231
4232                    if let Some(assigned_from_local) = assigned_from.local_or_deref_local() {
4233                        debug!(
4234                            "annotate_argument_and_return_for_borrow: assigned_from_local={:?}",
4235                            assigned_from_local,
4236                        );
4237
4238                        if assigned_to == mir::RETURN_PLACE && assigned_from_local == target {
4239                            return annotated_closure.or_else(fallback);
4240                        }
4241                    }
4242                }
4243            }
4244        }
4245
4246        // If we haven't found an assignment into the return place, then we need not add
4247        // any annotations.
4248        debug!("annotate_argument_and_return_for_borrow: none found");
4249        None
4250    }
4251
4252    /// Annotate the first argument and return type of a function signature if they are
4253    /// references.
4254    fn annotate_fn_sig(
4255        &self,
4256        did: LocalDefId,
4257        sig: ty::PolyFnSig<'tcx>,
4258    ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
4259        debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
4260        let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
4261        let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
4262        let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
4263
4264        // We need to work out which arguments to highlight. We do this by looking
4265        // at the return type, where there are three cases:
4266        //
4267        // 1. If there are named arguments, then we should highlight the return type and
4268        //    highlight any of the arguments that are also references with that lifetime.
4269        //    If there are no arguments that have the same lifetime as the return type,
4270        //    then don't highlight anything.
4271        // 2. The return type is a reference with an anonymous lifetime. If this is
4272        //    the case, then we can take advantage of (and teach) the lifetime elision
4273        //    rules.
4274        //
4275        //    We know that an error is being reported. So the arguments and return type
4276        //    must satisfy the elision rules. Therefore, if there is a single argument
4277        //    then that means the return type and first (and only) argument have the same
4278        //    lifetime and the borrow isn't meeting that, we can highlight the argument
4279        //    and return type.
4280        //
4281        //    If there are multiple arguments then the first argument must be self (else
4282        //    it would not satisfy the elision rules), so we can highlight self and the
4283        //    return type.
4284        // 3. The return type is not a reference. In this case, we don't highlight
4285        //    anything.
4286        let return_ty = sig.output();
4287        match return_ty.skip_binder().kind() {
4288            ty::Ref(return_region, _, _)
4289                if return_region.is_named(self.infcx.tcx) && !is_closure =>
4290            {
4291                // This is case 1 from above, return type is a named reference so we need to
4292                // search for relevant arguments.
4293                let mut arguments = Vec::new();
4294                for (index, argument) in sig.inputs().skip_binder().iter().enumerate() {
4295                    if let ty::Ref(argument_region, _, _) = argument.kind()
4296                        && argument_region == return_region
4297                    {
4298                        // Need to use the `rustc_middle::ty` types to compare against the
4299                        // `return_region`. Then use the `rustc_hir` type to get only
4300                        // the lifetime span.
4301                        match &fn_decl.inputs[index].kind {
4302                            hir::TyKind::Ref(lifetime, _) => {
4303                                // With access to the lifetime, we can get
4304                                // the span of it.
4305                                arguments.push((*argument, lifetime.ident.span));
4306                            }
4307                            // Resolve `self` whose self type is `&T`.
4308                            hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
4309                                if let Res::SelfTyAlias { alias_to, .. } = path.res
4310                                    && let Some(alias_to) = alias_to.as_local()
4311                                    && let hir::Impl { self_ty, .. } = self
4312                                        .infcx
4313                                        .tcx
4314                                        .hir_node_by_def_id(alias_to)
4315                                        .expect_item()
4316                                        .expect_impl()
4317                                    && let hir::TyKind::Ref(lifetime, _) = self_ty.kind
4318                                {
4319                                    arguments.push((*argument, lifetime.ident.span));
4320                                }
4321                            }
4322                            _ => {
4323                                // Don't ICE though. It might be a type alias.
4324                            }
4325                        }
4326                    }
4327                }
4328
4329                // We need to have arguments. This shouldn't happen, but it's worth checking.
4330                if arguments.is_empty() {
4331                    return None;
4332                }
4333
4334                // We use a mix of the HIR and the Ty types to get information
4335                // as the HIR doesn't have full types for closure arguments.
4336                let return_ty = sig.output().skip_binder();
4337                let mut return_span = fn_decl.output.span();
4338                if let hir::FnRetTy::Return(ty) = &fn_decl.output
4339                    && let hir::TyKind::Ref(lifetime, _) = ty.kind
4340                {
4341                    return_span = lifetime.ident.span;
4342                }
4343
4344                Some(AnnotatedBorrowFnSignature::NamedFunction {
4345                    arguments,
4346                    return_ty,
4347                    return_span,
4348                })
4349            }
4350            ty::Ref(_, _, _) if is_closure => {
4351                // This is case 2 from above but only for closures, return type is anonymous
4352                // reference so we select
4353                // the first argument.
4354                let argument_span = fn_decl.inputs.first()?.span;
4355                let argument_ty = sig.inputs().skip_binder().first()?;
4356
4357                // Closure arguments are wrapped in a tuple, so we need to get the first
4358                // from that.
4359                if let ty::Tuple(elems) = argument_ty.kind() {
4360                    let &argument_ty = elems.first()?;
4361                    if let ty::Ref(_, _, _) = argument_ty.kind() {
4362                        return Some(AnnotatedBorrowFnSignature::Closure {
4363                            argument_ty,
4364                            argument_span,
4365                        });
4366                    }
4367                }
4368
4369                None
4370            }
4371            ty::Ref(_, _, _) => {
4372                // This is also case 2 from above but for functions, return type is still an
4373                // anonymous reference so we select the first argument.
4374                let argument_span = fn_decl.inputs.first()?.span;
4375                let argument_ty = *sig.inputs().skip_binder().first()?;
4376
4377                let return_span = fn_decl.output.span();
4378                let return_ty = sig.output().skip_binder();
4379
4380                // We expect the first argument to be a reference.
4381                match argument_ty.kind() {
4382                    ty::Ref(_, _, _) => {}
4383                    _ => return None,
4384                }
4385
4386                Some(AnnotatedBorrowFnSignature::AnonymousFunction {
4387                    argument_ty,
4388                    argument_span,
4389                    return_ty,
4390                    return_span,
4391                })
4392            }
4393            _ => {
4394                // This is case 3 from above, return type is not a reference so don't highlight
4395                // anything.
4396                None
4397            }
4398        }
4399    }
4400}
4401
4402#[derive(Debug)]
4403enum AnnotatedBorrowFnSignature<'tcx> {
4404    NamedFunction {
4405        arguments: Vec<(Ty<'tcx>, Span)>,
4406        return_ty: Ty<'tcx>,
4407        return_span: Span,
4408    },
4409    AnonymousFunction {
4410        argument_ty: Ty<'tcx>,
4411        argument_span: Span,
4412        return_ty: Ty<'tcx>,
4413        return_span: Span,
4414    },
4415    Closure {
4416        argument_ty: Ty<'tcx>,
4417        argument_span: Span,
4418    },
4419}
4420
4421impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
4422    /// Annotate the provided diagnostic with information about borrow from the fn signature that
4423    /// helps explain.
4424    pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
4425        match self {
4426            &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
4427                diag.span_label(
4428                    argument_span,
4429                    format!("has type `{}`", cx.get_name_for_ty(argument_ty, 0)),
4430                );
4431
4432                cx.get_region_name_for_ty(argument_ty, 0)
4433            }
4434            &AnnotatedBorrowFnSignature::AnonymousFunction {
4435                argument_ty,
4436                argument_span,
4437                return_ty,
4438                return_span,
4439            } => {
4440                let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
4441                diag.span_label(argument_span, format!("has type `{argument_ty_name}`"));
4442
4443                let return_ty_name = cx.get_name_for_ty(return_ty, 0);
4444                let types_equal = return_ty_name == argument_ty_name;
4445                diag.span_label(
4446                    return_span,
4447                    format!(
4448                        "{}has type `{}`",
4449                        if types_equal { "also " } else { "" },
4450                        return_ty_name,
4451                    ),
4452                );
4453
4454                diag.note(
4455                    "argument and return type have the same lifetime due to lifetime elision rules",
4456                );
4457                diag.note(
4458                    "to learn more, visit <https://doc.rust-lang.org/book/ch10-03-\
4459                     lifetime-syntax.html#lifetime-elision>",
4460                );
4461
4462                cx.get_region_name_for_ty(return_ty, 0)
4463            }
4464            AnnotatedBorrowFnSignature::NamedFunction { arguments, return_ty, return_span } => {
4465                // Region of return type and arguments checked to be the same earlier.
4466                let region_name = cx.get_region_name_for_ty(*return_ty, 0);
4467                for (_, argument_span) in arguments {
4468                    diag.span_label(*argument_span, format!("has lifetime `{region_name}`"));
4469                }
4470
4471                diag.span_label(*return_span, format!("also has lifetime `{region_name}`",));
4472
4473                diag.help(format!(
4474                    "use data from the highlighted arguments which match the `{region_name}` lifetime of \
4475                     the return type",
4476                ));
4477
4478                region_name
4479            }
4480        }
4481    }
4482}
4483
4484/// Detect whether one of the provided spans is a statement nested within the top-most visited expr
4485struct ReferencedStatementsVisitor<'a>(&'a [Span]);
4486
4487impl<'v> Visitor<'v> for ReferencedStatementsVisitor<'_> {
4488    type Result = ControlFlow<()>;
4489    fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
4490        match s.kind {
4491            hir::StmtKind::Semi(expr) if self.0.contains(&expr.span) => ControlFlow::Break(()),
4492            _ => ControlFlow::Continue(()),
4493        }
4494    }
4495}
4496
4497/// Look for `break` expressions within any arbitrary expressions. We'll do this to infer
4498/// whether this is a case where the moved value would affect the exit of a loop, making it
4499/// unsuitable for a `.clone()` suggestion.
4500struct BreakFinder {
4501    found_breaks: Vec<(hir::Destination, Span)>,
4502    found_continues: Vec<(hir::Destination, Span)>,
4503}
4504impl<'hir> Visitor<'hir> for BreakFinder {
4505    fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
4506        match ex.kind {
4507            hir::ExprKind::Break(destination, _) => {
4508                self.found_breaks.push((destination, ex.span));
4509            }
4510            hir::ExprKind::Continue(destination) => {
4511                self.found_continues.push((destination, ex.span));
4512            }
4513            _ => {}
4514        }
4515        hir::intravisit::walk_expr(self, ex);
4516    }
4517}
4518
4519/// Given a set of spans representing statements initializing the relevant binding, visit all the
4520/// function expressions looking for branching code paths that *do not* initialize the binding.
4521struct ConditionVisitor<'tcx> {
4522    tcx: TyCtxt<'tcx>,
4523    spans: Vec<Span>,
4524    name: String,
4525    errors: Vec<(Span, String)>,
4526}
4527
4528impl<'v, 'tcx> Visitor<'v> for ConditionVisitor<'tcx> {
4529    fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
4530        match ex.kind {
4531            hir::ExprKind::If(cond, body, None) => {
4532                // `if` expressions with no `else` that initialize the binding might be missing an
4533                // `else` arm.
4534                if ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break() {
4535                    self.errors.push((
4536                        cond.span,
4537                        format!(
4538                            "if this `if` condition is `false`, {} is not initialized",
4539                            self.name,
4540                        ),
4541                    ));
4542                    self.errors.push((
4543                        ex.span.shrink_to_hi(),
4544                        format!("an `else` arm might be missing here, initializing {}", self.name),
4545                    ));
4546                }
4547            }
4548            hir::ExprKind::If(cond, body, Some(other)) => {
4549                // `if` expressions where the binding is only initialized in one of the two arms
4550                // might be missing a binding initialization.
4551                let a = ReferencedStatementsVisitor(&self.spans).visit_expr(body).is_break();
4552                let b = ReferencedStatementsVisitor(&self.spans).visit_expr(other).is_break();
4553                match (a, b) {
4554                    (true, true) | (false, false) => {}
4555                    (true, false) => {
4556                        if other.span.is_desugaring(DesugaringKind::WhileLoop) {
4557                            self.errors.push((
4558                                cond.span,
4559                                format!(
4560                                    "if this condition isn't met and the `while` loop runs 0 \
4561                                     times, {} is not initialized",
4562                                    self.name
4563                                ),
4564                            ));
4565                        } else {
4566                            self.errors.push((
4567                                body.span.shrink_to_hi().until(other.span),
4568                                format!(
4569                                    "if the `if` condition is `false` and this `else` arm is \
4570                                     executed, {} is not initialized",
4571                                    self.name
4572                                ),
4573                            ));
4574                        }
4575                    }
4576                    (false, true) => {
4577                        self.errors.push((
4578                            cond.span,
4579                            format!(
4580                                "if this condition is `true`, {} is not initialized",
4581                                self.name
4582                            ),
4583                        ));
4584                    }
4585                }
4586            }
4587            hir::ExprKind::Match(e, arms, loop_desugar) => {
4588                // If the binding is initialized in one of the match arms, then the other match
4589                // arms might be missing an initialization.
4590                let results: Vec<bool> = arms
4591                    .iter()
4592                    .map(|arm| ReferencedStatementsVisitor(&self.spans).visit_arm(arm).is_break())
4593                    .collect();
4594                if results.iter().any(|x| *x) && !results.iter().all(|x| *x) {
4595                    for (arm, seen) in arms.iter().zip(results) {
4596                        if !seen {
4597                            if loop_desugar == hir::MatchSource::ForLoopDesugar {
4598                                self.errors.push((
4599                                    e.span,
4600                                    format!(
4601                                        "if the `for` loop runs 0 times, {} is not initialized",
4602                                        self.name
4603                                    ),
4604                                ));
4605                            } else if let Some(guard) = &arm.guard {
4606                                if matches!(
4607                                    self.tcx.hir_node(arm.body.hir_id),
4608                                    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4609                                ) {
4610                                    continue;
4611                                }
4612                                self.errors.push((
4613                                    arm.pat.span.to(guard.span),
4614                                    format!(
4615                                        "if this pattern and condition are matched, {} is not \
4616                                         initialized",
4617                                        self.name
4618                                    ),
4619                                ));
4620                            } else {
4621                                if matches!(
4622                                    self.tcx.hir_node(arm.body.hir_id),
4623                                    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
4624                                ) {
4625                                    continue;
4626                                }
4627                                self.errors.push((
4628                                    arm.pat.span,
4629                                    format!(
4630                                        "if this pattern is matched, {} is not initialized",
4631                                        self.name
4632                                    ),
4633                                ));
4634                            }
4635                        }
4636                    }
4637                }
4638            }
4639            // FIXME: should we also account for binops, particularly `&&` and `||`? `try` should
4640            // also be accounted for. For now it is fine, as if we don't find *any* relevant
4641            // branching code paths, we point at the places where the binding *is* initialized for
4642            // *some* context.
4643            _ => {}
4644        }
4645        walk_expr(self, ex);
4646    }
4647}