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