rustc_borrowck/diagnostics/
mod.rs

1//! Borrow checker diagnostics.
2
3use std::collections::BTreeMap;
4
5use rustc_abi::{FieldIdx, VariantIdx};
6use rustc_data_structures::fx::FxIndexMap;
7use rustc_errors::{Applicability, Diag, EmissionGuarantee, MultiSpan, listify};
8use rustc_hir::def::{CtorKind, Namespace};
9use rustc_hir::{
10    self as hir, CoroutineKind, GenericBound, LangItem, WhereBoundPredicate, WherePredicateKind,
11};
12use rustc_index::{IndexSlice, IndexVec};
13use rustc_infer::infer::{BoundRegionConversionTime, NllRegionVariableOrigin};
14use rustc_infer::traits::SelectionError;
15use rustc_middle::mir::{
16    AggregateKind, CallSource, ConstOperand, ConstraintCategory, FakeReadCause, Local, LocalInfo,
17    LocalKind, Location, Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement,
18    StatementKind, Terminator, TerminatorKind, VarDebugInfoContents, find_self_call,
19};
20use rustc_middle::ty::print::Print;
21use rustc_middle::ty::{self, Ty, TyCtxt};
22use rustc_middle::{bug, span_bug};
23use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveOutIndex};
24use rustc_span::def_id::LocalDefId;
25use rustc_span::source_map::Spanned;
26use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
27use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
28use rustc_trait_selection::error_reporting::traits::call_kind::{CallDesugaringKind, call_kind};
29use rustc_trait_selection::infer::InferCtxtExt;
30use rustc_trait_selection::traits::{
31    FulfillmentError, FulfillmentErrorCode, type_known_to_meet_bound_modulo_regions,
32};
33use tracing::debug;
34
35use super::MirBorrowckCtxt;
36use super::borrow_set::BorrowData;
37use crate::constraints::OutlivesConstraint;
38use crate::fluent_generated as fluent;
39use crate::nll::ConstraintDescription;
40use crate::session_diagnostics::{
41    CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause,
42    CaptureVarKind, CaptureVarPathUseCause, OnClosureNote,
43};
44
45mod find_all_local_uses;
46mod find_use;
47mod outlives_suggestion;
48mod region_name;
49mod var_name;
50
51mod bound_region_errors;
52mod conflict_errors;
53mod explain_borrow;
54mod move_errors;
55mod mutability_errors;
56mod opaque_types;
57mod region_errors;
58
59pub(crate) use bound_region_errors::{ToUniverseInfo, UniverseInfo};
60pub(crate) use move_errors::{IllegalMoveOriginKind, MoveError};
61pub(crate) use mutability_errors::AccessKind;
62pub(crate) use outlives_suggestion::OutlivesSuggestionBuilder;
63pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};
64pub(crate) use region_name::{RegionName, RegionNameSource};
65pub(crate) use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;
66
67pub(super) struct DescribePlaceOpt {
68    including_downcast: bool,
69
70    /// Enable/Disable tuple fields.
71    /// For example `x` tuple. if it's `true` `x.0`. Otherwise `x`
72    including_tuple_field: bool,
73}
74
75pub(super) struct IncludingTupleField(pub(super) bool);
76
77enum BufferedDiag<'infcx> {
78    Error(Diag<'infcx>),
79    NonError(Diag<'infcx, ()>),
80}
81
82impl<'infcx> BufferedDiag<'infcx> {
83    fn sort_span(&self) -> Span {
84        match self {
85            BufferedDiag::Error(diag) => diag.sort_span,
86            BufferedDiag::NonError(diag) => diag.sort_span,
87        }
88    }
89}
90
91#[derive(Default)]
92pub(crate) struct BorrowckDiagnosticsBuffer<'infcx, 'tcx> {
93    /// This field keeps track of move errors that are to be reported for given move indices.
94    ///
95    /// There are situations where many errors can be reported for a single move out (see
96    /// #53807) and we want only the best of those errors.
97    ///
98    /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
99    /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of
100    /// the `Place` of the previous most diagnostic. This happens instead of buffering the
101    /// error. Once all move errors have been reported, any diagnostics in this map are added
102    /// to the buffer to be emitted.
103    ///
104    /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
105    /// when errors in the map are being re-added to the error buffer so that errors with the
106    /// same primary span come out in a consistent order.
107    buffered_move_errors: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, Diag<'infcx>)>,
108
109    buffered_mut_errors: FxIndexMap<Span, (Diag<'infcx>, usize)>,
110
111    /// Buffer of diagnostics to be reported. A mixture of error and non-error diagnostics.
112    buffered_diags: Vec<BufferedDiag<'infcx>>,
113}
114
115impl<'infcx, 'tcx> BorrowckDiagnosticsBuffer<'infcx, 'tcx> {
116    pub(crate) fn buffer_non_error(&mut self, diag: Diag<'infcx, ()>) {
117        self.buffered_diags.push(BufferedDiag::NonError(diag));
118    }
119}
120
121impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
122    pub(crate) fn buffer_error(&mut self, diag: Diag<'infcx>) {
123        self.diags_buffer.buffered_diags.push(BufferedDiag::Error(diag));
124    }
125
126    pub(crate) fn buffer_non_error(&mut self, diag: Diag<'infcx, ()>) {
127        self.diags_buffer.buffer_non_error(diag);
128    }
129
130    pub(crate) fn buffer_move_error(
131        &mut self,
132        move_out_indices: Vec<MoveOutIndex>,
133        place_and_err: (PlaceRef<'tcx>, Diag<'infcx>),
134    ) -> bool {
135        if let Some((_, diag)) =
136            self.diags_buffer.buffered_move_errors.insert(move_out_indices, place_and_err)
137        {
138            // Cancel the old diagnostic so we don't ICE
139            diag.cancel();
140            false
141        } else {
142            true
143        }
144    }
145
146    pub(crate) fn get_buffered_mut_error(&mut self, span: Span) -> Option<(Diag<'infcx>, usize)> {
147        // FIXME(#120456) - is `swap_remove` correct?
148        self.diags_buffer.buffered_mut_errors.swap_remove(&span)
149    }
150
151    pub(crate) fn buffer_mut_error(&mut self, span: Span, diag: Diag<'infcx>, count: usize) {
152        self.diags_buffer.buffered_mut_errors.insert(span, (diag, count));
153    }
154
155    pub(crate) fn emit_errors(&mut self) -> Option<ErrorGuaranteed> {
156        let mut res = self.infcx.tainted_by_errors();
157
158        // Buffer any move errors that we collected and de-duplicated.
159        for (_, (_, diag)) in std::mem::take(&mut self.diags_buffer.buffered_move_errors) {
160            // We have already set tainted for this error, so just buffer it.
161            self.buffer_error(diag);
162        }
163        for (_, (mut diag, count)) in std::mem::take(&mut self.diags_buffer.buffered_mut_errors) {
164            if count > 10 {
165                #[allow(rustc::diagnostic_outside_of_impl)]
166                #[allow(rustc::untranslatable_diagnostic)]
167                diag.note(format!("...and {} other attempted mutable borrows", count - 10));
168            }
169            self.buffer_error(diag);
170        }
171
172        if !self.diags_buffer.buffered_diags.is_empty() {
173            self.diags_buffer.buffered_diags.sort_by_key(|buffered_diag| buffered_diag.sort_span());
174            for buffered_diag in self.diags_buffer.buffered_diags.drain(..) {
175                match buffered_diag {
176                    BufferedDiag::Error(diag) => res = Some(diag.emit()),
177                    BufferedDiag::NonError(diag) => diag.emit(),
178                }
179            }
180        }
181
182        res
183    }
184
185    pub(crate) fn has_buffered_diags(&self) -> bool {
186        self.diags_buffer.buffered_diags.is_empty()
187    }
188
189    pub(crate) fn has_move_error(
190        &self,
191        move_out_indices: &[MoveOutIndex],
192    ) -> Option<&(PlaceRef<'tcx>, Diag<'infcx>)> {
193        self.diags_buffer.buffered_move_errors.get(move_out_indices)
194    }
195
196    /// Uses `body.var_debug_info` to find the symbol
197    fn local_name(&self, index: Local) -> Option<Symbol> {
198        *self.local_names().get(index)?
199    }
200
201    fn local_names(&self) -> &IndexSlice<Local, Option<Symbol>> {
202        self.local_names.get_or_init(|| {
203            let mut local_names = IndexVec::from_elem(None, &self.body.local_decls);
204            for var_debug_info in &self.body.var_debug_info {
205                if let VarDebugInfoContents::Place(place) = var_debug_info.value {
206                    if let Some(local) = place.as_local() {
207                        if let Some(prev_name) = local_names[local]
208                            && var_debug_info.name != prev_name
209                        {
210                            span_bug!(
211                                var_debug_info.source_info.span,
212                                "local {:?} has many names (`{}` vs `{}`)",
213                                local,
214                                prev_name,
215                                var_debug_info.name
216                            );
217                        }
218                        local_names[local] = Some(var_debug_info.name);
219                    }
220                }
221            }
222            local_names
223        })
224    }
225}
226
227impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
228    /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
229    /// is moved after being invoked.
230    ///
231    /// ```text
232    /// note: closure cannot be invoked more than once because it moves the variable `dict` out of
233    ///       its environment
234    ///   --> $DIR/issue-42065.rs:16:29
235    ///    |
236    /// LL |         for (key, value) in dict {
237    ///    |                             ^^^^
238    /// ```
239    #[allow(rustc::diagnostic_outside_of_impl)] // FIXME
240    pub(super) fn add_moved_or_invoked_closure_note(
241        &self,
242        location: Location,
243        place: PlaceRef<'tcx>,
244        diag: &mut Diag<'infcx>,
245    ) -> bool {
246        debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
247        let mut target = place.local_or_deref_local();
248        for stmt in &self.body[location.block].statements[location.statement_index..] {
249            debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);
250            if let StatementKind::Assign(box (into, Rvalue::Use(from))) = &stmt.kind {
251                debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);
252                match from {
253                    Operand::Copy(place) | Operand::Move(place)
254                        if target == place.local_or_deref_local() =>
255                    {
256                        target = into.local_or_deref_local()
257                    }
258                    _ => {}
259                }
260            }
261        }
262
263        // Check if we are attempting to call a closure after it has been invoked.
264        let terminator = self.body[location.block].terminator();
265        debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);
266        if let TerminatorKind::Call {
267            func: Operand::Constant(box ConstOperand { const_, .. }),
268            args,
269            ..
270        } = &terminator.kind
271            && let ty::FnDef(id, _) = *const_.ty().kind()
272        {
273            debug!("add_moved_or_invoked_closure_note: id={:?}", id);
274            if self.infcx.tcx.is_lang_item(self.infcx.tcx.parent(id), LangItem::FnOnce) {
275                let closure = match args.first() {
276                    Some(Spanned { node: Operand::Copy(place) | Operand::Move(place), .. })
277                        if target == place.local_or_deref_local() =>
278                    {
279                        place.local_or_deref_local().unwrap()
280                    }
281                    _ => return false,
282                };
283
284                debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
285                if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {
286                    let did = did.expect_local();
287                    if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
288                        diag.subdiagnostic(OnClosureNote::InvokedTwice {
289                            place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
290                            span: *span,
291                        });
292                        return true;
293                    }
294                }
295            }
296        }
297
298        // Check if we are just moving a closure after it has been invoked.
299        if let Some(target) = target
300            && let ty::Closure(did, _) = self.body.local_decls[target].ty.kind()
301        {
302            let did = did.expect_local();
303            if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
304                diag.subdiagnostic(OnClosureNote::MovedTwice {
305                    place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
306                    span: *span,
307                });
308                return true;
309            }
310        }
311        false
312    }
313
314    /// End-user visible description of `place` if one can be found.
315    /// If the place is a temporary for instance, `"value"` will be returned.
316    pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {
317        match self.describe_place(place_ref) {
318            Some(mut descr) => {
319                // Surround descr with `backticks`.
320                descr.reserve(2);
321                descr.insert(0, '`');
322                descr.push('`');
323                descr
324            }
325            None => "value".to_string(),
326        }
327    }
328
329    /// End-user visible description of `place` if one can be found.
330    /// If the place is a temporary for instance, `None` will be returned.
331    pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {
332        self.describe_place_with_options(
333            place_ref,
334            DescribePlaceOpt { including_downcast: false, including_tuple_field: true },
335        )
336    }
337
338    /// End-user visible description of `place` if one can be found. If the place is a temporary
339    /// for instance, `None` will be returned.
340    /// `IncludingDowncast` parameter makes the function return `None` if `ProjectionElem` is
341    /// `Downcast` and `IncludingDowncast` is true
342    pub(super) fn describe_place_with_options(
343        &self,
344        place: PlaceRef<'tcx>,
345        opt: DescribePlaceOpt,
346    ) -> Option<String> {
347        let local = place.local;
348        if self.body.local_decls[local]
349            .source_info
350            .span
351            .in_external_macro(self.infcx.tcx.sess.source_map())
352        {
353            return None;
354        }
355
356        let mut autoderef_index = None;
357        let mut buf = String::new();
358        let mut ok = self.append_local_to_string(local, &mut buf);
359
360        for (index, elem) in place.projection.into_iter().enumerate() {
361            match elem {
362                ProjectionElem::Deref => {
363                    if index == 0 {
364                        if self.body.local_decls[local].is_ref_for_guard() {
365                            continue;
366                        }
367                        if let LocalInfo::StaticRef { def_id, .. } =
368                            *self.body.local_decls[local].local_info()
369                        {
370                            buf.push_str(self.infcx.tcx.item_name(def_id).as_str());
371                            ok = Ok(());
372                            continue;
373                        }
374                    }
375                    if let Some(field) = self.is_upvar_field_projection(PlaceRef {
376                        local,
377                        projection: place.projection.split_at(index + 1).0,
378                    }) {
379                        let var_index = field.index();
380                        buf = self.upvars[var_index].to_string(self.infcx.tcx);
381                        ok = Ok(());
382                        if !self.upvars[var_index].is_by_ref() {
383                            buf.insert(0, '*');
384                        }
385                    } else {
386                        if autoderef_index.is_none() {
387                            autoderef_index = match place.projection.iter().rposition(|elem| {
388                                !matches!(
389                                    elem,
390                                    ProjectionElem::Deref | ProjectionElem::Downcast(..)
391                                )
392                            }) {
393                                Some(index) => Some(index + 1),
394                                None => Some(0),
395                            };
396                        }
397                        if index >= autoderef_index.unwrap() {
398                            buf.insert(0, '*');
399                        }
400                    }
401                }
402                ProjectionElem::Downcast(..) if opt.including_downcast => return None,
403                ProjectionElem::Downcast(..) => (),
404                ProjectionElem::OpaqueCast(..) => (),
405                ProjectionElem::UnwrapUnsafeBinder(_) => (),
406                ProjectionElem::Field(field, _ty) => {
407                    // FIXME(project-rfc_2229#36): print capture precisely here.
408                    if let Some(field) = self.is_upvar_field_projection(PlaceRef {
409                        local,
410                        projection: place.projection.split_at(index + 1).0,
411                    }) {
412                        buf = self.upvars[field.index()].to_string(self.infcx.tcx);
413                        ok = Ok(());
414                    } else {
415                        let field_name = self.describe_field(
416                            PlaceRef { local, projection: place.projection.split_at(index).0 },
417                            *field,
418                            IncludingTupleField(opt.including_tuple_field),
419                        );
420                        if let Some(field_name_str) = field_name {
421                            buf.push('.');
422                            buf.push_str(&field_name_str);
423                        }
424                    }
425                }
426                ProjectionElem::Index(index) => {
427                    buf.push('[');
428                    if self.append_local_to_string(*index, &mut buf).is_err() {
429                        buf.push('_');
430                    }
431                    buf.push(']');
432                }
433                ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
434                    // Since it isn't possible to borrow an element on a particular index and
435                    // then use another while the borrow is held, don't output indices details
436                    // to avoid confusing the end-user
437                    buf.push_str("[..]");
438                }
439            }
440        }
441        ok.ok().map(|_| buf)
442    }
443
444    fn describe_name(&self, place: PlaceRef<'tcx>) -> Option<Symbol> {
445        for elem in place.projection.into_iter() {
446            match elem {
447                ProjectionElem::Downcast(Some(name), _) => {
448                    return Some(*name);
449                }
450                _ => {}
451            }
452        }
453        None
454    }
455
456    /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have
457    /// a name, or its name was generated by the compiler, then `Err` is returned
458    fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {
459        let decl = &self.body.local_decls[local];
460        match self.local_name(local) {
461            Some(name) if !decl.from_compiler_desugaring() => {
462                buf.push_str(name.as_str());
463                Ok(())
464            }
465            _ => Err(()),
466        }
467    }
468
469    /// End-user visible description of the `field`nth field of `base`
470    fn describe_field(
471        &self,
472        place: PlaceRef<'tcx>,
473        field: FieldIdx,
474        including_tuple_field: IncludingTupleField,
475    ) -> Option<String> {
476        let place_ty = match place {
477            PlaceRef { local, projection: [] } => PlaceTy::from_ty(self.body.local_decls[local].ty),
478            PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {
479                ProjectionElem::Deref
480                | ProjectionElem::Index(..)
481                | ProjectionElem::ConstantIndex { .. }
482                | ProjectionElem::Subslice { .. } => {
483                    PlaceRef { local, projection: proj_base }.ty(self.body, self.infcx.tcx)
484                }
485                ProjectionElem::Downcast(..) => place.ty(self.body, self.infcx.tcx),
486                ProjectionElem::OpaqueCast(ty) | ProjectionElem::UnwrapUnsafeBinder(ty) => {
487                    PlaceTy::from_ty(*ty)
488                }
489                ProjectionElem::Field(_, field_type) => PlaceTy::from_ty(*field_type),
490            },
491        };
492        self.describe_field_from_ty(
493            place_ty.ty,
494            field,
495            place_ty.variant_index,
496            including_tuple_field,
497        )
498    }
499
500    /// End-user visible description of the `field_index`nth field of `ty`
501    fn describe_field_from_ty(
502        &self,
503        ty: Ty<'_>,
504        field: FieldIdx,
505        variant_index: Option<VariantIdx>,
506        including_tuple_field: IncludingTupleField,
507    ) -> Option<String> {
508        if let Some(boxed_ty) = ty.boxed_ty() {
509            // If the type is a box, the field is described from the boxed type
510            self.describe_field_from_ty(boxed_ty, field, variant_index, including_tuple_field)
511        } else {
512            match *ty.kind() {
513                ty::Adt(def, _) => {
514                    let variant = if let Some(idx) = variant_index {
515                        assert!(def.is_enum());
516                        def.variant(idx)
517                    } else {
518                        def.non_enum_variant()
519                    };
520                    if !including_tuple_field.0 && variant.ctor_kind() == Some(CtorKind::Fn) {
521                        return None;
522                    }
523                    Some(variant.fields[field].name.to_string())
524                }
525                ty::Tuple(_) => Some(field.index().to_string()),
526                ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
527                    self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
528                }
529                ty::Array(ty, _) | ty::Slice(ty) => {
530                    self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)
531                }
532                ty::Closure(def_id, _) | ty::Coroutine(def_id, _) => {
533                    // We won't be borrowck'ing here if the closure came from another crate,
534                    // so it's safe to call `expect_local`.
535                    //
536                    // We know the field exists so it's safe to call operator[] and `unwrap` here.
537                    let def_id = def_id.expect_local();
538                    let var_id =
539                        self.infcx.tcx.closure_captures(def_id)[field.index()].get_root_variable();
540
541                    Some(self.infcx.tcx.hir_name(var_id).to_string())
542                }
543                _ => {
544                    // Might need a revision when the fields in trait RFC is implemented
545                    // (https://github.com/rust-lang/rfcs/pull/1546)
546                    bug!("End-user description not implemented for field access on `{:?}`", ty);
547                }
548            }
549        }
550    }
551
552    pub(super) fn borrowed_content_source(
553        &self,
554        deref_base: PlaceRef<'tcx>,
555    ) -> BorrowedContentSource<'tcx> {
556        let tcx = self.infcx.tcx;
557
558        // Look up the provided place and work out the move path index for it,
559        // we'll use this to check whether it was originally from an overloaded
560        // operator.
561        match self.move_data.rev_lookup.find(deref_base) {
562            LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {
563                debug!("borrowed_content_source: mpi={:?}", mpi);
564
565                for i in &self.move_data.init_path_map[mpi] {
566                    let init = &self.move_data.inits[*i];
567                    debug!("borrowed_content_source: init={:?}", init);
568                    // We're only interested in statements that initialized a value, not the
569                    // initializations from arguments.
570                    let InitLocation::Statement(loc) = init.location else { continue };
571
572                    let bbd = &self.body[loc.block];
573                    let is_terminator = bbd.statements.len() == loc.statement_index;
574                    debug!(
575                        "borrowed_content_source: loc={:?} is_terminator={:?}",
576                        loc, is_terminator,
577                    );
578                    if !is_terminator {
579                        continue;
580                    } else if let Some(Terminator {
581                        kind:
582                            TerminatorKind::Call {
583                                func,
584                                call_source: CallSource::OverloadedOperator,
585                                ..
586                            },
587                        ..
588                    }) = &bbd.terminator
589                    {
590                        if let Some(source) =
591                            BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)
592                        {
593                            return source;
594                        }
595                    }
596                }
597            }
598            // Base is a `static` so won't be from an overloaded operator
599            _ => (),
600        };
601
602        // If we didn't find an overloaded deref or index, then assume it's a
603        // built in deref and check the type of the base.
604        let base_ty = deref_base.ty(self.body, tcx).ty;
605        if base_ty.is_raw_ptr() {
606            BorrowedContentSource::DerefRawPointer
607        } else if base_ty.is_mutable_ptr() {
608            BorrowedContentSource::DerefMutableRef
609        } else {
610            BorrowedContentSource::DerefSharedRef
611        }
612    }
613
614    /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
615    /// name where required.
616    pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
617        let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
618
619        // We need to add synthesized lifetimes where appropriate. We do
620        // this by hooking into the pretty printer and telling it to label the
621        // lifetimes without names with the value `'0`.
622        if let ty::Ref(region, ..) = ty.kind() {
623            match region.kind() {
624                ty::ReBound(_, ty::BoundRegion { kind: br, .. })
625                | ty::RePlaceholder(ty::PlaceholderRegion {
626                    bound: ty::BoundRegion { kind: br, .. },
627                    ..
628                }) => p.region_highlight_mode.highlighting_bound_region(br, counter),
629                _ => {}
630            }
631        }
632
633        ty.print(&mut p).unwrap();
634        p.into_buffer()
635    }
636
637    /// Returns the name of the provided `Ty` (that must be a reference)'s region with a
638    /// synthesized lifetime name where required.
639    pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
640        let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
641
642        let region = if let ty::Ref(region, ..) = ty.kind() {
643            match region.kind() {
644                ty::ReBound(_, ty::BoundRegion { kind: br, .. })
645                | ty::RePlaceholder(ty::PlaceholderRegion {
646                    bound: ty::BoundRegion { kind: br, .. },
647                    ..
648                }) => p.region_highlight_mode.highlighting_bound_region(br, counter),
649                _ => {}
650            }
651            region
652        } else {
653            bug!("ty for annotation of borrow region is not a reference");
654        };
655
656        region.print(&mut p).unwrap();
657        p.into_buffer()
658    }
659
660    /// Add a note to region errors and borrow explanations when higher-ranked regions in predicates
661    /// implicitly introduce an "outlives `'static`" constraint.
662    ///
663    /// This is very similar to `fn suggest_static_lifetime_for_gat_from_hrtb` which handles this
664    /// note for failed type tests instead of outlives errors.
665    fn add_placeholder_from_predicate_note<G: EmissionGuarantee>(
666        &self,
667        diag: &mut Diag<'_, G>,
668        path: &[OutlivesConstraint<'tcx>],
669    ) {
670        let tcx = self.infcx.tcx;
671        let Some((gat_hir_id, generics)) = path.iter().find_map(|constraint| {
672            let outlived = constraint.sub;
673            if let Some(origin) = self.regioncx.definitions.get(outlived)
674                && let NllRegionVariableOrigin::Placeholder(placeholder) = origin.origin
675                && let Some(id) = placeholder.bound.kind.get_id()
676                && let Some(placeholder_id) = id.as_local()
677                && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
678                && let Some(generics_impl) =
679                    tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
680            {
681                Some((gat_hir_id, generics_impl))
682            } else {
683                None
684            }
685        }) else {
686            return;
687        };
688
689        // Look for the where-bound which introduces the placeholder.
690        // As we're using the HIR, we need to handle both `for<'a> T: Trait<'a>`
691        // and `T: for<'a> Trait`<'a>.
692        for pred in generics.predicates {
693            let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
694                bound_generic_params,
695                bounds,
696                ..
697            }) = pred.kind
698            else {
699                continue;
700            };
701            if bound_generic_params
702                .iter()
703                .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
704                .is_some()
705            {
706                diag.span_note(pred.span, fluent::borrowck_limitations_implies_static);
707                return;
708            }
709            for bound in bounds.iter() {
710                if let GenericBound::Trait(bound) = bound {
711                    if bound
712                        .bound_generic_params
713                        .iter()
714                        .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
715                        .is_some()
716                    {
717                        diag.span_note(bound.span, fluent::borrowck_limitations_implies_static);
718                        return;
719                    }
720                }
721            }
722        }
723    }
724
725    /// Add a label to region errors and borrow explanations when outlives constraints arise from
726    /// proving a type implements `Sized` or `Copy`.
727    fn add_sized_or_copy_bound_info<G: EmissionGuarantee>(
728        &self,
729        err: &mut Diag<'_, G>,
730        blamed_category: ConstraintCategory<'tcx>,
731        path: &[OutlivesConstraint<'tcx>],
732    ) {
733        for sought_category in [ConstraintCategory::SizedBound, ConstraintCategory::CopyBound] {
734            if sought_category != blamed_category
735                && let Some(sought_constraint) = path.iter().find(|c| c.category == sought_category)
736            {
737                let label = format!(
738                    "requirement occurs due to {}",
739                    sought_category.description().trim_end()
740                );
741                err.span_label(sought_constraint.span, label);
742            }
743        }
744    }
745}
746
747/// The span(s) associated to a use of a place.
748#[derive(Copy, Clone, PartialEq, Eq, Debug)]
749pub(super) enum UseSpans<'tcx> {
750    /// The access is caused by capturing a variable for a closure.
751    ClosureUse {
752        /// This is true if the captured variable was from a coroutine.
753        closure_kind: hir::ClosureKind,
754        /// The span of the args of the closure, including the `move` keyword if
755        /// it's present.
756        args_span: Span,
757        /// The span of the use resulting in capture kind
758        /// Check `ty::CaptureInfo` for more details
759        capture_kind_span: Span,
760        /// The span of the use resulting in the captured path
761        /// Check `ty::CaptureInfo` for more details
762        path_span: Span,
763    },
764    /// The access is caused by using a variable as the receiver of a method
765    /// that takes 'self'
766    FnSelfUse {
767        /// The span of the variable being moved
768        var_span: Span,
769        /// The span of the method call on the variable
770        fn_call_span: Span,
771        /// The definition span of the method being called
772        fn_span: Span,
773        kind: CallKind<'tcx>,
774    },
775    /// This access is caused by a `match` or `if let` pattern.
776    PatUse(Span),
777    /// This access has a single span associated to it: common case.
778    OtherUse(Span),
779}
780
781impl UseSpans<'_> {
782    pub(super) fn args_or_use(self) -> Span {
783        match self {
784            UseSpans::ClosureUse { args_span: span, .. }
785            | UseSpans::PatUse(span)
786            | UseSpans::OtherUse(span) => span,
787            UseSpans::FnSelfUse { var_span, .. } => var_span,
788        }
789    }
790
791    /// Returns the span of `self`, in the case of a `ClosureUse` returns the `path_span`
792    pub(super) fn var_or_use_path_span(self) -> Span {
793        match self {
794            UseSpans::ClosureUse { path_span: span, .. }
795            | UseSpans::PatUse(span)
796            | UseSpans::OtherUse(span) => span,
797            UseSpans::FnSelfUse { var_span, .. } => var_span,
798        }
799    }
800
801    /// Returns the span of `self`, in the case of a `ClosureUse` returns the `capture_kind_span`
802    pub(super) fn var_or_use(self) -> Span {
803        match self {
804            UseSpans::ClosureUse { capture_kind_span: span, .. }
805            | UseSpans::PatUse(span)
806            | UseSpans::OtherUse(span) => span,
807            UseSpans::FnSelfUse { var_span, .. } => var_span,
808        }
809    }
810
811    // FIXME(coroutines): Make this just return the `ClosureKind` directly?
812    pub(super) fn coroutine_kind(self) -> Option<CoroutineKind> {
813        match self {
814            UseSpans::ClosureUse {
815                closure_kind: hir::ClosureKind::Coroutine(coroutine_kind),
816                ..
817            } => Some(coroutine_kind),
818            _ => None,
819        }
820    }
821
822    /// Add a span label to the arguments of the closure, if it exists.
823    #[allow(rustc::diagnostic_outside_of_impl)]
824    pub(super) fn args_subdiag(self, err: &mut Diag<'_>, f: impl FnOnce(Span) -> CaptureArgLabel) {
825        if let UseSpans::ClosureUse { args_span, .. } = self {
826            err.subdiagnostic(f(args_span));
827        }
828    }
829
830    /// Add a span label to the use of the captured variable, if it exists.
831    /// only adds label to the `path_span`
832    #[allow(rustc::diagnostic_outside_of_impl)]
833    pub(super) fn var_path_only_subdiag(
834        self,
835        err: &mut Diag<'_>,
836        action: crate::InitializationRequiringAction,
837    ) {
838        use CaptureVarPathUseCause::*;
839
840        use crate::InitializationRequiringAction::*;
841        if let UseSpans::ClosureUse { closure_kind, path_span, .. } = self {
842            match closure_kind {
843                hir::ClosureKind::Coroutine(_) => {
844                    err.subdiagnostic(match action {
845                        Borrow => BorrowInCoroutine { path_span },
846                        MatchOn | Use => UseInCoroutine { path_span },
847                        Assignment => AssignInCoroutine { path_span },
848                        PartialAssignment => AssignPartInCoroutine { path_span },
849                    });
850                }
851                hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
852                    err.subdiagnostic(match action {
853                        Borrow => BorrowInClosure { path_span },
854                        MatchOn | Use => UseInClosure { path_span },
855                        Assignment => AssignInClosure { path_span },
856                        PartialAssignment => AssignPartInClosure { path_span },
857                    });
858                }
859            }
860        }
861    }
862
863    /// Add a subdiagnostic to the use of the captured variable, if it exists.
864    #[allow(rustc::diagnostic_outside_of_impl)]
865    pub(super) fn var_subdiag(
866        self,
867        err: &mut Diag<'_>,
868        kind: Option<rustc_middle::mir::BorrowKind>,
869        f: impl FnOnce(hir::ClosureKind, Span) -> CaptureVarCause,
870    ) {
871        if let UseSpans::ClosureUse { closure_kind, capture_kind_span, path_span, .. } = self {
872            if capture_kind_span != path_span {
873                err.subdiagnostic(match kind {
874                    Some(kd) => match kd {
875                        rustc_middle::mir::BorrowKind::Shared
876                        | rustc_middle::mir::BorrowKind::Fake(_) => {
877                            CaptureVarKind::Immut { kind_span: capture_kind_span }
878                        }
879
880                        rustc_middle::mir::BorrowKind::Mut { .. } => {
881                            CaptureVarKind::Mut { kind_span: capture_kind_span }
882                        }
883                    },
884                    None => CaptureVarKind::Move { kind_span: capture_kind_span },
885                });
886            };
887            let diag = f(closure_kind, path_span);
888            err.subdiagnostic(diag);
889        }
890    }
891
892    /// Returns `false` if this place is not used in a closure.
893    pub(super) fn for_closure(&self) -> bool {
894        match *self {
895            UseSpans::ClosureUse { closure_kind, .. } => {
896                matches!(closure_kind, hir::ClosureKind::Closure)
897            }
898            _ => false,
899        }
900    }
901
902    /// Returns `false` if this place is not used in a coroutine.
903    pub(super) fn for_coroutine(&self) -> bool {
904        match *self {
905            // FIXME(coroutines): Do we want this to apply to synthetic coroutines?
906            UseSpans::ClosureUse { closure_kind, .. } => {
907                matches!(closure_kind, hir::ClosureKind::Coroutine(..))
908            }
909            _ => false,
910        }
911    }
912
913    pub(super) fn or_else<F>(self, if_other: F) -> Self
914    where
915        F: FnOnce() -> Self,
916    {
917        match self {
918            closure @ UseSpans::ClosureUse { .. } => closure,
919            UseSpans::PatUse(_) | UseSpans::OtherUse(_) => if_other(),
920            fn_self @ UseSpans::FnSelfUse { .. } => fn_self,
921        }
922    }
923}
924
925pub(super) enum BorrowedContentSource<'tcx> {
926    DerefRawPointer,
927    DerefMutableRef,
928    DerefSharedRef,
929    OverloadedDeref(Ty<'tcx>),
930    OverloadedIndex(Ty<'tcx>),
931}
932
933impl<'tcx> BorrowedContentSource<'tcx> {
934    pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {
935        match *self {
936            BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),
937            BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),
938            BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),
939            BorrowedContentSource::OverloadedDeref(ty) => ty
940                .ty_adt_def()
941                .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
942                    name @ (sym::Rc | sym::Arc) => Some(format!("an `{name}`")),
943                    _ => None,
944                })
945                .unwrap_or_else(|| format!("dereference of `{ty}`")),
946            BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{ty}`"),
947        }
948    }
949
950    pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {
951        match *self {
952            BorrowedContentSource::DerefRawPointer => Some("raw pointer"),
953            BorrowedContentSource::DerefSharedRef => Some("shared reference"),
954            BorrowedContentSource::DerefMutableRef => Some("mutable reference"),
955            // Overloaded deref and index operators should be evaluated into a
956            // temporary. So we don't need a description here.
957            BorrowedContentSource::OverloadedDeref(_)
958            | BorrowedContentSource::OverloadedIndex(_) => None,
959        }
960    }
961
962    pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {
963        match *self {
964            BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),
965            BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),
966            BorrowedContentSource::DerefMutableRef => {
967                bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")
968            }
969            BorrowedContentSource::OverloadedDeref(ty) => ty
970                .ty_adt_def()
971                .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {
972                    name @ (sym::Rc | sym::Arc) => Some(format!("an `{name}`")),
973                    _ => None,
974                })
975                .unwrap_or_else(|| format!("dereference of `{ty}`")),
976            BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{ty}`"),
977        }
978    }
979
980    fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {
981        match *func.kind() {
982            ty::FnDef(def_id, args) => {
983                let trait_id = tcx.trait_of_assoc(def_id)?;
984
985                if tcx.is_lang_item(trait_id, LangItem::Deref)
986                    || tcx.is_lang_item(trait_id, LangItem::DerefMut)
987                {
988                    Some(BorrowedContentSource::OverloadedDeref(args.type_at(0)))
989                } else if tcx.is_lang_item(trait_id, LangItem::Index)
990                    || tcx.is_lang_item(trait_id, LangItem::IndexMut)
991                {
992                    Some(BorrowedContentSource::OverloadedIndex(args.type_at(0)))
993                } else {
994                    None
995                }
996            }
997            _ => None,
998        }
999    }
1000}
1001
1002/// Helper struct for `explain_captures`.
1003struct CapturedMessageOpt {
1004    is_partial_move: bool,
1005    is_loop_message: bool,
1006    is_move_msg: bool,
1007    is_loop_move: bool,
1008    has_suggest_reborrow: bool,
1009    maybe_reinitialized_locations_is_empty: bool,
1010}
1011
1012impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
1013    /// Finds the spans associated to a move or copy of move_place at location.
1014    pub(super) fn move_spans(
1015        &self,
1016        moved_place: PlaceRef<'tcx>, // Could also be an upvar.
1017        location: Location,
1018    ) -> UseSpans<'tcx> {
1019        use self::UseSpans::*;
1020
1021        let Some(stmt) = self.body[location.block].statements.get(location.statement_index) else {
1022            return OtherUse(self.body.source_info(location).span);
1023        };
1024
1025        debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);
1026        if let StatementKind::Assign(box (_, Rvalue::Aggregate(kind, places))) = &stmt.kind
1027            && let AggregateKind::Closure(def_id, _) | AggregateKind::Coroutine(def_id, _) = **kind
1028        {
1029            debug!("move_spans: def_id={:?} places={:?}", def_id, places);
1030            let def_id = def_id.expect_local();
1031            if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1032                self.closure_span(def_id, moved_place, places)
1033            {
1034                return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };
1035            }
1036        }
1037
1038        // StatementKind::FakeRead only contains a def_id if they are introduced as a result
1039        // of pattern matching within a closure.
1040        if let StatementKind::FakeRead(box (cause, place)) = stmt.kind {
1041            match cause {
1042                FakeReadCause::ForMatchedPlace(Some(closure_def_id))
1043                | FakeReadCause::ForLet(Some(closure_def_id)) => {
1044                    debug!("move_spans: def_id={:?} place={:?}", closure_def_id, place);
1045                    let places = &[Operand::Move(place)];
1046                    if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1047                        self.closure_span(closure_def_id, moved_place, IndexSlice::from_raw(places))
1048                    {
1049                        return ClosureUse {
1050                            closure_kind,
1051                            args_span,
1052                            capture_kind_span,
1053                            path_span,
1054                        };
1055                    }
1056                }
1057                _ => {}
1058            }
1059        }
1060
1061        let normal_ret =
1062            if moved_place.projection.iter().any(|p| matches!(p, ProjectionElem::Downcast(..))) {
1063                PatUse(stmt.source_info.span)
1064            } else {
1065                OtherUse(stmt.source_info.span)
1066            };
1067
1068        // We are trying to find MIR of the form:
1069        // ```
1070        // _temp = _moved_val;
1071        // ...
1072        // FnSelfCall(_temp, ...)
1073        // ```
1074        //
1075        // where `_moved_val` is the place we generated the move error for,
1076        // `_temp` is some other local, and `FnSelfCall` is a function
1077        // that has a `self` parameter.
1078
1079        let target_temp = match stmt.kind {
1080            StatementKind::Assign(box (temp, _)) if temp.as_local().is_some() => {
1081                temp.as_local().unwrap()
1082            }
1083            _ => return normal_ret,
1084        };
1085
1086        debug!("move_spans: target_temp = {:?}", target_temp);
1087
1088        if let Some(Terminator {
1089            kind: TerminatorKind::Call { fn_span, call_source, .. }, ..
1090        }) = &self.body[location.block].terminator
1091        {
1092            let Some((method_did, method_args)) =
1093                find_self_call(self.infcx.tcx, self.body, target_temp, location.block)
1094            else {
1095                return normal_ret;
1096            };
1097
1098            let kind = call_kind(
1099                self.infcx.tcx,
1100                self.infcx.typing_env(self.infcx.param_env),
1101                method_did,
1102                method_args,
1103                *fn_span,
1104                call_source.from_hir_call(),
1105                self.infcx.tcx.fn_arg_idents(method_did)[0],
1106            );
1107
1108            return FnSelfUse {
1109                var_span: stmt.source_info.span,
1110                fn_call_span: *fn_span,
1111                fn_span: self.infcx.tcx.def_span(method_did),
1112                kind,
1113            };
1114        }
1115
1116        normal_ret
1117    }
1118
1119    /// Finds the span of arguments of a closure (within `maybe_closure_span`)
1120    /// and its usage of the local assigned at `location`.
1121    /// This is done by searching in statements succeeding `location`
1122    /// and originating from `maybe_closure_span`.
1123    pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans<'tcx> {
1124        use self::UseSpans::*;
1125        debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);
1126
1127        let target = match self.body[location.block].statements.get(location.statement_index) {
1128            Some(Statement { kind: StatementKind::Assign(box (place, _)), .. }) => {
1129                if let Some(local) = place.as_local() {
1130                    local
1131                } else {
1132                    return OtherUse(use_span);
1133                }
1134            }
1135            _ => return OtherUse(use_span),
1136        };
1137
1138        if self.body.local_kind(target) != LocalKind::Temp {
1139            // operands are always temporaries.
1140            return OtherUse(use_span);
1141        }
1142
1143        // drop and replace might have moved the assignment to the next block
1144        let maybe_additional_statement =
1145            if let TerminatorKind::Drop { target: drop_target, .. } =
1146                self.body[location.block].terminator().kind
1147            {
1148                self.body[drop_target].statements.first()
1149            } else {
1150                None
1151            };
1152
1153        let statements =
1154            self.body[location.block].statements[location.statement_index + 1..].iter();
1155
1156        for stmt in statements.chain(maybe_additional_statement) {
1157            if let StatementKind::Assign(box (_, Rvalue::Aggregate(kind, places))) = &stmt.kind {
1158                let (&def_id, is_coroutine) = match kind {
1159                    box AggregateKind::Closure(def_id, _) => (def_id, false),
1160                    box AggregateKind::Coroutine(def_id, _) => (def_id, true),
1161                    _ => continue,
1162                };
1163                let def_id = def_id.expect_local();
1164
1165                debug!(
1166                    "borrow_spans: def_id={:?} is_coroutine={:?} places={:?}",
1167                    def_id, is_coroutine, places
1168                );
1169                if let Some((args_span, closure_kind, capture_kind_span, path_span)) =
1170                    self.closure_span(def_id, Place::from(target).as_ref(), places)
1171                {
1172                    return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };
1173                } else {
1174                    return OtherUse(use_span);
1175                }
1176            }
1177
1178            if use_span != stmt.source_info.span {
1179                break;
1180            }
1181        }
1182
1183        OtherUse(use_span)
1184    }
1185
1186    /// Finds the spans of a captured place within a closure or coroutine.
1187    /// The first span is the location of the use resulting in the capture kind of the capture
1188    /// The second span is the location the use resulting in the captured path of the capture
1189    fn closure_span(
1190        &self,
1191        def_id: LocalDefId,
1192        target_place: PlaceRef<'tcx>,
1193        places: &IndexSlice<FieldIdx, Operand<'tcx>>,
1194    ) -> Option<(Span, hir::ClosureKind, Span, Span)> {
1195        debug!(
1196            "closure_span: def_id={:?} target_place={:?} places={:?}",
1197            def_id, target_place, places
1198        );
1199        let hir_id = self.infcx.tcx.local_def_id_to_hir_id(def_id);
1200        let expr = &self.infcx.tcx.hir_expect_expr(hir_id).kind;
1201        debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
1202        if let &hir::ExprKind::Closure(&hir::Closure { kind, fn_decl_span, .. }) = expr {
1203            for (captured_place, place) in
1204                self.infcx.tcx.closure_captures(def_id).iter().zip(places)
1205            {
1206                match place {
1207                    Operand::Copy(place) | Operand::Move(place)
1208                        if target_place == place.as_ref() =>
1209                    {
1210                        debug!("closure_span: found captured local {:?}", place);
1211                        return Some((
1212                            fn_decl_span,
1213                            kind,
1214                            captured_place.get_capture_kind_span(self.infcx.tcx),
1215                            captured_place.get_path_span(self.infcx.tcx),
1216                        ));
1217                    }
1218                    _ => {}
1219                }
1220            }
1221        }
1222        None
1223    }
1224
1225    /// Helper to retrieve span(s) of given borrow from the current MIR
1226    /// representation
1227    pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans<'tcx> {
1228        let span = self.body.source_info(borrow.reserve_location).span;
1229        self.borrow_spans(span, borrow.reserve_location)
1230    }
1231
1232    #[allow(rustc::diagnostic_outside_of_impl)]
1233    #[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
1234    fn explain_captures(
1235        &mut self,
1236        err: &mut Diag<'infcx>,
1237        span: Span,
1238        move_span: Span,
1239        move_spans: UseSpans<'tcx>,
1240        moved_place: Place<'tcx>,
1241        msg_opt: CapturedMessageOpt,
1242    ) {
1243        let CapturedMessageOpt {
1244            is_partial_move: is_partial,
1245            is_loop_message,
1246            is_move_msg,
1247            is_loop_move,
1248            has_suggest_reborrow,
1249            maybe_reinitialized_locations_is_empty,
1250        } = msg_opt;
1251        if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } = move_spans {
1252            let place_name = self
1253                .describe_place(moved_place.as_ref())
1254                .map(|n| format!("`{n}`"))
1255                .unwrap_or_else(|| "value".to_owned());
1256            match kind {
1257                CallKind::FnCall { fn_trait_id, self_ty }
1258                    if self.infcx.tcx.is_lang_item(fn_trait_id, LangItem::FnOnce) =>
1259                {
1260                    err.subdiagnostic(CaptureReasonLabel::Call {
1261                        fn_call_span,
1262                        place_name: &place_name,
1263                        is_partial,
1264                        is_loop_message,
1265                    });
1266                    // Check if the move occurs on a value because of a call on a closure that comes
1267                    // from a type parameter `F: FnOnce()`. If so, we provide a targeted `note`:
1268                    // ```
1269                    // error[E0382]: use of moved value: `blk`
1270                    //   --> $DIR/once-cant-call-twice-on-heap.rs:8:5
1271                    //    |
1272                    // LL | fn foo<F:FnOnce()>(blk: F) {
1273                    //    |                    --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
1274                    // LL | blk();
1275                    //    | ----- `blk` moved due to this call
1276                    // LL | blk();
1277                    //    | ^^^ value used here after move
1278                    //    |
1279                    // note: `FnOnce` closures can only be called once
1280                    //   --> $DIR/once-cant-call-twice-on-heap.rs:6:10
1281                    //    |
1282                    // LL | fn foo<F:FnOnce()>(blk: F) {
1283                    //    |        ^^^^^^^^ `F` is made to be an `FnOnce` closure here
1284                    // LL | blk();
1285                    //    | ----- this value implements `FnOnce`, which causes it to be moved when called
1286                    // ```
1287                    if let ty::Param(param_ty) = *self_ty.kind()
1288                        && let generics = self.infcx.tcx.generics_of(self.mir_def_id())
1289                        && let param = generics.type_param(param_ty, self.infcx.tcx)
1290                        && let Some(hir_generics) = self
1291                            .infcx
1292                            .tcx
1293                            .typeck_root_def_id(self.mir_def_id().to_def_id())
1294                            .as_local()
1295                            .and_then(|def_id| self.infcx.tcx.hir_get_generics(def_id))
1296                        && let spans = hir_generics
1297                            .predicates
1298                            .iter()
1299                            .filter_map(|pred| match pred.kind {
1300                                hir::WherePredicateKind::BoundPredicate(pred) => Some(pred),
1301                                _ => None,
1302                            })
1303                            .filter(|pred| {
1304                                if let Some((id, _)) = pred.bounded_ty.as_generic_param() {
1305                                    id == param.def_id
1306                                } else {
1307                                    false
1308                                }
1309                            })
1310                            .flat_map(|pred| pred.bounds)
1311                            .filter_map(|bound| {
1312                                if let Some(trait_ref) = bound.trait_ref()
1313                                    && let Some(trait_def_id) = trait_ref.trait_def_id()
1314                                    && trait_def_id == fn_trait_id
1315                                {
1316                                    Some(bound.span())
1317                                } else {
1318                                    None
1319                                }
1320                            })
1321                            .collect::<Vec<Span>>()
1322                        && !spans.is_empty()
1323                    {
1324                        let mut span: MultiSpan = spans.clone().into();
1325                        err.arg("ty", param_ty.to_string());
1326                        let msg = err.dcx.eagerly_translate_to_string(
1327                            fluent::borrowck_moved_a_fn_once_in_call_def,
1328                            err.args.iter(),
1329                        );
1330                        err.remove_arg("ty");
1331                        for sp in spans {
1332                            span.push_span_label(sp, msg.clone());
1333                        }
1334                        span.push_span_label(
1335                            fn_call_span,
1336                            fluent::borrowck_moved_a_fn_once_in_call,
1337                        );
1338                        err.span_note(span, fluent::borrowck_moved_a_fn_once_in_call_call);
1339                    } else {
1340                        err.subdiagnostic(CaptureReasonNote::FnOnceMoveInCall { var_span });
1341                    }
1342                }
1343                CallKind::Operator { self_arg, trait_id, .. } => {
1344                    let self_arg = self_arg.unwrap();
1345                    err.subdiagnostic(CaptureReasonLabel::OperatorUse {
1346                        fn_call_span,
1347                        place_name: &place_name,
1348                        is_partial,
1349                        is_loop_message,
1350                    });
1351                    if self.fn_self_span_reported.insert(fn_span) {
1352                        let lang = self.infcx.tcx.lang_items();
1353                        err.subdiagnostic(
1354                            if [lang.not_trait(), lang.deref_trait(), lang.neg_trait()]
1355                                .contains(&Some(trait_id))
1356                            {
1357                                CaptureReasonNote::UnOpMoveByOperator { span: self_arg.span }
1358                            } else {
1359                                CaptureReasonNote::LhsMoveByOperator { span: self_arg.span }
1360                            },
1361                        );
1362                    }
1363                }
1364                CallKind::Normal { self_arg, desugaring, method_did, method_args } => {
1365                    let self_arg = self_arg.unwrap();
1366                    let mut has_sugg = false;
1367                    let tcx = self.infcx.tcx;
1368                    // Avoid pointing to the same function in multiple different
1369                    // error messages.
1370                    if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) {
1371                        self.explain_iterator_advancement_in_for_loop_if_applicable(
1372                            err,
1373                            span,
1374                            &move_spans,
1375                        );
1376
1377                        let func = tcx.def_path_str(method_did);
1378                        err.subdiagnostic(CaptureReasonNote::FuncTakeSelf {
1379                            func,
1380                            place_name: place_name.clone(),
1381                            span: self_arg.span,
1382                        });
1383                    }
1384                    let parent_did = tcx.parent(method_did);
1385                    let parent_self_ty =
1386                        matches!(tcx.def_kind(parent_did), rustc_hir::def::DefKind::Impl { .. })
1387                            .then_some(parent_did)
1388                            .and_then(|did| match tcx.type_of(did).instantiate_identity().kind() {
1389                                ty::Adt(def, ..) => Some(def.did()),
1390                                _ => None,
1391                            });
1392                    let is_option_or_result = parent_self_ty.is_some_and(|def_id| {
1393                        matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
1394                    });
1395                    if is_option_or_result && maybe_reinitialized_locations_is_empty {
1396                        err.subdiagnostic(CaptureReasonLabel::BorrowContent { var_span });
1397                    }
1398                    if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {
1399                        let ty = moved_place.ty(self.body, tcx).ty;
1400                        let suggest = match tcx.get_diagnostic_item(sym::IntoIterator) {
1401                            Some(def_id) => type_known_to_meet_bound_modulo_regions(
1402                                self.infcx,
1403                                self.infcx.param_env,
1404                                Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty),
1405                                def_id,
1406                            ),
1407                            _ => false,
1408                        };
1409                        if suggest {
1410                            err.subdiagnostic(CaptureReasonSuggest::IterateSlice {
1411                                ty,
1412                                span: move_span.shrink_to_lo(),
1413                            });
1414                        }
1415
1416                        err.subdiagnostic(CaptureReasonLabel::ImplicitCall {
1417                            fn_call_span,
1418                            place_name: &place_name,
1419                            is_partial,
1420                            is_loop_message,
1421                        });
1422                        // If the moved place was a `&mut` ref, then we can
1423                        // suggest to reborrow it where it was moved, so it
1424                        // will still be valid by the time we get to the usage.
1425                        if let ty::Ref(_, _, hir::Mutability::Mut) =
1426                            moved_place.ty(self.body, self.infcx.tcx).ty.kind()
1427                        {
1428                            // Suggest `reborrow` in other place for following situations:
1429                            // 1. If we are in a loop this will be suggested later.
1430                            // 2. If the moved value is a mut reference, it is used in a
1431                            // generic function and the corresponding arg's type is generic param.
1432                            if !is_loop_move && !has_suggest_reborrow {
1433                                self.suggest_reborrow(
1434                                    err,
1435                                    move_span.shrink_to_lo(),
1436                                    moved_place.as_ref(),
1437                                );
1438                            }
1439                        }
1440                    } else {
1441                        if let Some((CallDesugaringKind::Await, _)) = desugaring {
1442                            err.subdiagnostic(CaptureReasonLabel::Await {
1443                                fn_call_span,
1444                                place_name: &place_name,
1445                                is_partial,
1446                                is_loop_message,
1447                            });
1448                        } else {
1449                            err.subdiagnostic(CaptureReasonLabel::MethodCall {
1450                                fn_call_span,
1451                                place_name: &place_name,
1452                                is_partial,
1453                                is_loop_message,
1454                            });
1455                        }
1456                        // Erase and shadow everything that could be passed to the new infcx.
1457                        let ty = moved_place.ty(self.body, tcx).ty;
1458
1459                        if let ty::Adt(def, args) = ty.peel_refs().kind()
1460                            && tcx.is_lang_item(def.did(), LangItem::Pin)
1461                            && let ty::Ref(_, _, hir::Mutability::Mut) = args.type_at(0).kind()
1462                            && let self_ty = self.infcx.instantiate_binder_with_fresh_vars(
1463                                fn_call_span,
1464                                BoundRegionConversionTime::FnCall,
1465                                tcx.fn_sig(method_did).instantiate(tcx, method_args).input(0),
1466                            )
1467                            && self.infcx.can_eq(self.infcx.param_env, ty, self_ty)
1468                        {
1469                            err.subdiagnostic(CaptureReasonSuggest::FreshReborrow {
1470                                span: move_span.shrink_to_hi(),
1471                            });
1472                            has_sugg = true;
1473                        }
1474                        if let Some(clone_trait) = tcx.lang_items().clone_trait() {
1475                            let sugg = if moved_place
1476                                .iter_projections()
1477                                .any(|(_, elem)| matches!(elem, ProjectionElem::Deref))
1478                            {
1479                                let (start, end) = if let Some(expr) = self.find_expr(move_span)
1480                                    && let Some(_) = self.clone_on_reference(expr)
1481                                    && let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind
1482                                {
1483                                    (move_span.shrink_to_lo(), move_span.with_lo(rcvr.span.hi()))
1484                                } else {
1485                                    (move_span.shrink_to_lo(), move_span.shrink_to_hi())
1486                                };
1487                                vec![
1488                                    // We use the fully-qualified path because `.clone()` can
1489                                    // sometimes choose `<&T as Clone>` instead of `<T as Clone>`
1490                                    // when going through auto-deref, so this ensures that doesn't
1491                                    // happen, causing suggestions for `.clone().clone()`.
1492                                    (start, format!("<{ty} as Clone>::clone(&")),
1493                                    (end, ")".to_string()),
1494                                ]
1495                            } else {
1496                                vec![(move_span.shrink_to_hi(), ".clone()".to_string())]
1497                            };
1498                            if let Some(errors) = self.infcx.type_implements_trait_shallow(
1499                                clone_trait,
1500                                ty,
1501                                self.infcx.param_env,
1502                            ) && !has_sugg
1503                            {
1504                                let msg = match &errors[..] {
1505                                    [] => "you can `clone` the value and consume it, but this \
1506                                           might not be your desired behavior"
1507                                        .to_string(),
1508                                    [error] => {
1509                                        format!(
1510                                            "you could `clone` the value and consume it, if the \
1511                                             `{}` trait bound could be satisfied",
1512                                            error.obligation.predicate,
1513                                        )
1514                                    }
1515                                    _ => {
1516                                        format!(
1517                                            "you could `clone` the value and consume it, if the \
1518                                             following trait bounds could be satisfied: {}",
1519                                            listify(&errors, |e: &FulfillmentError<'tcx>| format!(
1520                                                "`{}`",
1521                                                e.obligation.predicate
1522                                            ))
1523                                            .unwrap(),
1524                                        )
1525                                    }
1526                                };
1527                                err.multipart_suggestion_verbose(
1528                                    msg,
1529                                    sugg,
1530                                    Applicability::MaybeIncorrect,
1531                                );
1532                                for error in errors {
1533                                    if let FulfillmentErrorCode::Select(
1534                                        SelectionError::Unimplemented,
1535                                    ) = error.code
1536                                        && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(
1537                                            pred,
1538                                        )) = error.obligation.predicate.kind().skip_binder()
1539                                    {
1540                                        self.infcx.err_ctxt().suggest_derive(
1541                                            &error.obligation,
1542                                            err,
1543                                            error.obligation.predicate.kind().rebind(pred),
1544                                        );
1545                                    }
1546                                }
1547                            }
1548                        }
1549                    }
1550                }
1551                // Other desugarings takes &self, which cannot cause a move
1552                _ => {}
1553            }
1554        } else {
1555            if move_span != span || is_loop_message {
1556                err.subdiagnostic(CaptureReasonLabel::MovedHere {
1557                    move_span,
1558                    is_partial,
1559                    is_move_msg,
1560                    is_loop_message,
1561                });
1562            }
1563            // If the move error occurs due to a loop, don't show
1564            // another message for the same span
1565            if !is_loop_message {
1566                move_spans.var_subdiag(err, None, |kind, var_span| match kind {
1567                    hir::ClosureKind::Coroutine(_) => {
1568                        CaptureVarCause::PartialMoveUseInCoroutine { var_span, is_partial }
1569                    }
1570                    hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1571                        CaptureVarCause::PartialMoveUseInClosure { var_span, is_partial }
1572                    }
1573                })
1574            }
1575        }
1576    }
1577
1578    /// Skip over locals that begin with an underscore or have no name
1579    pub(crate) fn local_excluded_from_unused_mut_lint(&self, index: Local) -> bool {
1580        self.local_name(index).is_none_or(|name| name.as_str().starts_with('_'))
1581    }
1582}