rustc_borrowck/diagnostics/
move_errors.rs

1#![allow(rustc::diagnostic_outside_of_impl)]
2#![allow(rustc::untranslatable_diagnostic)]
3
4use rustc_data_structures::fx::FxHashSet;
5use rustc_errors::{Applicability, Diag};
6use rustc_hir::intravisit::Visitor;
7use rustc_hir::{self as hir, CaptureBy, ExprKind, HirId, Node};
8use rustc_middle::bug;
9use rustc_middle::mir::*;
10use rustc_middle::ty::{self, Ty, TyCtxt};
11use rustc_mir_dataflow::move_paths::{LookupResult, MovePathIndex};
12use rustc_span::def_id::DefId;
13use rustc_span::{BytePos, DUMMY_SP, ExpnKind, MacroKind, Span};
14use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
15use rustc_trait_selection::infer::InferCtxtExt;
16use tracing::debug;
17
18use crate::MirBorrowckCtxt;
19use crate::diagnostics::{CapturedMessageOpt, DescribePlaceOpt, UseSpans};
20use crate::prefixes::PrefixSet;
21
22#[derive(Debug)]
23pub(crate) enum IllegalMoveOriginKind<'tcx> {
24    /// Illegal move due to attempt to move from behind a reference.
25    BorrowedContent {
26        /// The place the reference refers to: if erroneous code was trying to
27        /// move from `(*x).f` this will be `*x`.
28        target_place: Place<'tcx>,
29    },
30
31    /// Illegal move due to attempt to move from field of an ADT that
32    /// implements `Drop`. Rust maintains invariant that all `Drop`
33    /// ADT's remain fully-initialized so that user-defined destructor
34    /// can safely read from all of the ADT's fields.
35    InteriorOfTypeWithDestructor { container_ty: Ty<'tcx> },
36
37    /// Illegal move due to attempt to move out of a slice or array.
38    InteriorOfSliceOrArray { ty: Ty<'tcx>, is_index: bool },
39}
40
41#[derive(Debug)]
42pub(crate) struct MoveError<'tcx> {
43    place: Place<'tcx>,
44    location: Location,
45    kind: IllegalMoveOriginKind<'tcx>,
46}
47
48impl<'tcx> MoveError<'tcx> {
49    pub(crate) fn new(
50        place: Place<'tcx>,
51        location: Location,
52        kind: IllegalMoveOriginKind<'tcx>,
53    ) -> Self {
54        MoveError { place, location, kind }
55    }
56}
57
58// Often when desugaring a pattern match we may have many individual moves in
59// MIR that are all part of one operation from the user's point-of-view. For
60// example:
61//
62// let (x, y) = foo()
63//
64// would move x from the 0 field of some temporary, and y from the 1 field. We
65// group such errors together for cleaner error reporting.
66//
67// Errors are kept separate if they are from places with different parent move
68// paths. For example, this generates two errors:
69//
70// let (&x, &y) = (&String::new(), &String::new());
71#[derive(Debug)]
72enum GroupedMoveError<'tcx> {
73    // Place expression can't be moved from,
74    // e.g., match x[0] { s => (), } where x: &[String]
75    MovesFromPlace {
76        original_path: Place<'tcx>,
77        span: Span,
78        move_from: Place<'tcx>,
79        kind: IllegalMoveOriginKind<'tcx>,
80        binds_to: Vec<Local>,
81    },
82    // Part of a value expression can't be moved from,
83    // e.g., match &String::new() { &x => (), }
84    MovesFromValue {
85        original_path: Place<'tcx>,
86        span: Span,
87        move_from: MovePathIndex,
88        kind: IllegalMoveOriginKind<'tcx>,
89        binds_to: Vec<Local>,
90    },
91    // Everything that isn't from pattern matching.
92    OtherIllegalMove {
93        original_path: Place<'tcx>,
94        use_spans: UseSpans<'tcx>,
95        kind: IllegalMoveOriginKind<'tcx>,
96    },
97}
98
99impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
100    pub(crate) fn report_move_errors(&mut self) {
101        let grouped_errors = self.group_move_errors();
102        for error in grouped_errors {
103            self.report(error);
104        }
105    }
106
107    fn group_move_errors(&mut self) -> Vec<GroupedMoveError<'tcx>> {
108        let mut grouped_errors = Vec::new();
109        let errors = std::mem::take(&mut self.move_errors);
110        for error in errors {
111            self.append_to_grouped_errors(&mut grouped_errors, error);
112        }
113        grouped_errors
114    }
115
116    fn append_to_grouped_errors(
117        &self,
118        grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
119        MoveError { place: original_path, location, kind }: MoveError<'tcx>,
120    ) {
121        // Note: that the only time we assign a place isn't a temporary
122        // to a user variable is when initializing it.
123        // If that ever stops being the case, then the ever initialized
124        // flow could be used.
125        if let Some(StatementKind::Assign(box (place, Rvalue::Use(Operand::Move(move_from))))) =
126            self.body.basic_blocks[location.block]
127                .statements
128                .get(location.statement_index)
129                .map(|stmt| &stmt.kind)
130            && let Some(local) = place.as_local()
131        {
132            let local_decl = &self.body.local_decls[local];
133            // opt_match_place is the
134            // match_span is the span of the expression being matched on
135            // match *x.y { ... }        match_place is Some(*x.y)
136            //       ^^^^                match_span is the span of *x.y
137            //
138            // opt_match_place is None for let [mut] x = ... statements,
139            // whether or not the right-hand side is a place expression
140            if let LocalInfo::User(BindingForm::Var(VarBindingForm {
141                opt_match_place: Some((opt_match_place, match_span)),
142                ..
143            })) = *local_decl.local_info()
144            {
145                let stmt_source_info = self.body.source_info(location);
146                self.append_binding_error(
147                    grouped_errors,
148                    kind,
149                    original_path,
150                    *move_from,
151                    local,
152                    opt_match_place,
153                    match_span,
154                    stmt_source_info.span,
155                );
156                return;
157            }
158        }
159
160        let move_spans = self.move_spans(original_path.as_ref(), location);
161        grouped_errors.push(GroupedMoveError::OtherIllegalMove {
162            use_spans: move_spans,
163            original_path,
164            kind,
165        });
166    }
167
168    fn append_binding_error(
169        &self,
170        grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
171        kind: IllegalMoveOriginKind<'tcx>,
172        original_path: Place<'tcx>,
173        move_from: Place<'tcx>,
174        bind_to: Local,
175        match_place: Option<Place<'tcx>>,
176        match_span: Span,
177        statement_span: Span,
178    ) {
179        debug!(?match_place, ?match_span, "append_binding_error");
180
181        let from_simple_let = match_place.is_none();
182        let match_place = match_place.unwrap_or(move_from);
183
184        match self.move_data.rev_lookup.find(match_place.as_ref()) {
185            // Error with the match place
186            LookupResult::Parent(_) => {
187                for ge in &mut *grouped_errors {
188                    if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge
189                        && match_span == *span
190                    {
191                        debug!("appending local({bind_to:?}) to list");
192                        if !binds_to.is_empty() {
193                            binds_to.push(bind_to);
194                        }
195                        return;
196                    }
197                }
198                debug!("found a new move error location");
199
200                // Don't need to point to x in let x = ... .
201                let (binds_to, span) = if from_simple_let {
202                    (vec![], statement_span)
203                } else {
204                    (vec![bind_to], match_span)
205                };
206                grouped_errors.push(GroupedMoveError::MovesFromPlace {
207                    span,
208                    move_from,
209                    original_path,
210                    kind,
211                    binds_to,
212                });
213            }
214            // Error with the pattern
215            LookupResult::Exact(_) => {
216                let LookupResult::Parent(Some(mpi)) =
217                    self.move_data.rev_lookup.find(move_from.as_ref())
218                else {
219                    // move_from should be a projection from match_place.
220                    unreachable!("Probably not unreachable...");
221                };
222                for ge in &mut *grouped_errors {
223                    if let GroupedMoveError::MovesFromValue {
224                        span,
225                        move_from: other_mpi,
226                        binds_to,
227                        ..
228                    } = ge
229                    {
230                        if match_span == *span && mpi == *other_mpi {
231                            debug!("appending local({bind_to:?}) to list");
232                            binds_to.push(bind_to);
233                            return;
234                        }
235                    }
236                }
237                debug!("found a new move error location");
238                grouped_errors.push(GroupedMoveError::MovesFromValue {
239                    span: match_span,
240                    move_from: mpi,
241                    original_path,
242                    kind,
243                    binds_to: vec![bind_to],
244                });
245            }
246        };
247    }
248
249    fn report(&mut self, error: GroupedMoveError<'tcx>) {
250        let (span, use_spans, original_path, kind) = match error {
251            GroupedMoveError::MovesFromPlace { span, original_path, ref kind, .. }
252            | GroupedMoveError::MovesFromValue { span, original_path, ref kind, .. } => {
253                (span, None, original_path, kind)
254            }
255            GroupedMoveError::OtherIllegalMove { use_spans, original_path, ref kind } => {
256                (use_spans.args_or_use(), Some(use_spans), original_path, kind)
257            }
258        };
259        debug!(
260            "report: original_path={:?} span={:?}, kind={:?} \
261             original_path.is_upvar_field_projection={:?}",
262            original_path,
263            span,
264            kind,
265            self.is_upvar_field_projection(original_path.as_ref())
266        );
267        if self.has_ambiguous_copy(original_path.ty(self.body, self.infcx.tcx).ty) {
268            // If the type may implement Copy, skip the error.
269            // It's an error with the Copy implementation (e.g. duplicate Copy) rather than borrow check
270            self.dcx()
271                .span_delayed_bug(span, "Type may implement copy, but there is no other error.");
272            return;
273        }
274        let mut err = match kind {
275            &IllegalMoveOriginKind::BorrowedContent { target_place } => self
276                .report_cannot_move_from_borrowed_content(
277                    original_path,
278                    target_place,
279                    span,
280                    use_spans,
281                ),
282            &IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
283                self.cannot_move_out_of_interior_of_drop(span, ty)
284            }
285            &IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => {
286                self.cannot_move_out_of_interior_noncopy(span, ty, Some(is_index))
287            }
288        };
289
290        self.add_move_hints(error, &mut err, span);
291        self.buffer_error(err);
292    }
293
294    fn has_ambiguous_copy(&mut self, ty: Ty<'tcx>) -> bool {
295        let Some(copy_def_id) = self.infcx.tcx.lang_items().copy_trait() else { return false };
296
297        // Avoid bogus move errors because of an incoherent `Copy` impl.
298        self.infcx.type_implements_trait(copy_def_id, [ty], self.infcx.param_env).may_apply()
299            && self.infcx.tcx.coherent_trait(copy_def_id).is_err()
300    }
301
302    fn report_cannot_move_from_static(&mut self, place: Place<'tcx>, span: Span) -> Diag<'infcx> {
303        let description = if place.projection.len() == 1 {
304            format!("static item {}", self.describe_any_place(place.as_ref()))
305        } else {
306            let base_static = PlaceRef { local: place.local, projection: &[ProjectionElem::Deref] };
307
308            format!(
309                "{} as {} is a static item",
310                self.describe_any_place(place.as_ref()),
311                self.describe_any_place(base_static),
312            )
313        };
314
315        self.cannot_move_out_of(span, &description)
316    }
317
318    pub(in crate::diagnostics) fn suggest_clone_of_captured_var_in_move_closure(
319        &self,
320        err: &mut Diag<'_>,
321        upvar_name: &str,
322        use_spans: Option<UseSpans<'tcx>>,
323    ) {
324        let tcx = self.infcx.tcx;
325        let Some(use_spans) = use_spans else { return };
326        // We only care about the case where a closure captured a binding.
327        let UseSpans::ClosureUse { args_span, .. } = use_spans else { return };
328        let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
329        // Find the closure that captured the binding.
330        let mut expr_finder = FindExprBySpan::new(args_span, tcx);
331        expr_finder.include_closures = true;
332        expr_finder.visit_expr(tcx.hir_body(body_id).value);
333        let Some(closure_expr) = expr_finder.result else { return };
334        let ExprKind::Closure(closure) = closure_expr.kind else { return };
335        // We'll only suggest cloning the binding if it's a `move` closure.
336        let CaptureBy::Value { .. } = closure.capture_clause else { return };
337        // Find the expression within the closure where the binding is consumed.
338        let mut suggested = false;
339        let use_span = use_spans.var_or_use();
340        let mut expr_finder = FindExprBySpan::new(use_span, tcx);
341        expr_finder.include_closures = true;
342        expr_finder.visit_expr(tcx.hir_body(body_id).value);
343        let Some(use_expr) = expr_finder.result else { return };
344        let parent = tcx.parent_hir_node(use_expr.hir_id);
345        if let Node::Expr(expr) = parent
346            && let ExprKind::Assign(lhs, ..) = expr.kind
347            && lhs.hir_id == use_expr.hir_id
348        {
349            // Cloning the value being assigned makes no sense:
350            //
351            // error[E0507]: cannot move out of `var`, a captured variable in an `FnMut` closure
352            //   --> $DIR/option-content-move2.rs:11:9
353            //    |
354            // LL |     let mut var = None;
355            //    |         ------- captured outer variable
356            // LL |     func(|| {
357            //    |          -- captured by this `FnMut` closure
358            // LL |         // Shouldn't suggest `move ||.as_ref()` here
359            // LL |         move || {
360            //    |         ^^^^^^^ `var` is moved here
361            // LL |
362            // LL |             var = Some(NotCopyable);
363            //    |             ---
364            //    |             |
365            //    |             variable moved due to use in closure
366            //    |             move occurs because `var` has type `Option<NotCopyable>`, which does not implement the `Copy` trait
367            //    |
368            return;
369        }
370
371        // Search for an appropriate place for the structured `.clone()` suggestion to be applied.
372        // If we encounter a statement before the borrow error, we insert a statement there.
373        for (_, node) in tcx.hir_parent_iter(closure_expr.hir_id) {
374            if let Node::Stmt(stmt) = node {
375                let padding = tcx
376                    .sess
377                    .source_map()
378                    .indentation_before(stmt.span)
379                    .unwrap_or_else(|| "    ".to_string());
380                err.multipart_suggestion_verbose(
381                    "consider cloning the value before moving it into the closure",
382                    vec![
383                        (
384                            stmt.span.shrink_to_lo(),
385                            format!("let value = {upvar_name}.clone();\n{padding}"),
386                        ),
387                        (use_span, "value".to_string()),
388                    ],
389                    Applicability::MachineApplicable,
390                );
391                suggested = true;
392                break;
393            } else if let Node::Expr(expr) = node
394                && let ExprKind::Closure(_) = expr.kind
395            {
396                // We want to suggest cloning only on the first closure, not
397                // subsequent ones (like `ui/suggestions/option-content-move2.rs`).
398                break;
399            }
400        }
401        if !suggested {
402            // If we couldn't find a statement for us to insert a new `.clone()` statement before,
403            // we have a bare expression, so we suggest the creation of a new block inline to go
404            // from `move || val` to `{ let value = val.clone(); move || value }`.
405            let padding = tcx
406                .sess
407                .source_map()
408                .indentation_before(closure_expr.span)
409                .unwrap_or_else(|| "    ".to_string());
410            err.multipart_suggestion_verbose(
411                "consider cloning the value before moving it into the closure",
412                vec![
413                    (
414                        closure_expr.span.shrink_to_lo(),
415                        format!("{{\n{padding}let value = {upvar_name}.clone();\n{padding}"),
416                    ),
417                    (use_spans.var_or_use(), "value".to_string()),
418                    (closure_expr.span.shrink_to_hi(), format!("\n{padding}}}")),
419                ],
420                Applicability::MachineApplicable,
421            );
422        }
423    }
424
425    fn report_cannot_move_from_borrowed_content(
426        &mut self,
427        move_place: Place<'tcx>,
428        deref_target_place: Place<'tcx>,
429        span: Span,
430        use_spans: Option<UseSpans<'tcx>>,
431    ) -> Diag<'infcx> {
432        let tcx = self.infcx.tcx;
433        // Inspect the type of the content behind the
434        // borrow to provide feedback about why this
435        // was a move rather than a copy.
436        let ty = deref_target_place.ty(self.body, tcx).ty;
437        let upvar_field = self
438            .prefixes(move_place.as_ref(), PrefixSet::All)
439            .find_map(|p| self.is_upvar_field_projection(p));
440
441        let deref_base = match deref_target_place.projection.as_ref() {
442            [proj_base @ .., ProjectionElem::Deref] => {
443                PlaceRef { local: deref_target_place.local, projection: proj_base }
444            }
445            _ => bug!("deref_target_place is not a deref projection"),
446        };
447
448        if let PlaceRef { local, projection: [] } = deref_base {
449            let decl = &self.body.local_decls[local];
450            let local_name = self.local_name(local).map(|sym| format!("`{sym}`"));
451            if decl.is_ref_for_guard() {
452                return self
453                    .cannot_move_out_of(
454                        span,
455                        &format!(
456                            "{} in pattern guard",
457                            local_name.as_deref().unwrap_or("the place")
458                        ),
459                    )
460                    .with_note(
461                        "variables bound in patterns cannot be moved from \
462                         until after the end of the pattern guard",
463                    );
464            } else if decl.is_ref_to_static() {
465                return self.report_cannot_move_from_static(move_place, span);
466            }
467        }
468
469        debug!("report: ty={:?}", ty);
470        let mut err = match ty.kind() {
471            ty::Array(..) | ty::Slice(..) => {
472                self.cannot_move_out_of_interior_noncopy(span, ty, None)
473            }
474            ty::Closure(def_id, closure_args)
475                if def_id.as_local() == Some(self.mir_def_id())
476                    && let Some(upvar_field) = upvar_field =>
477            {
478                let closure_kind_ty = closure_args.as_closure().kind_ty();
479                let closure_kind = match closure_kind_ty.to_opt_closure_kind() {
480                    Some(kind @ (ty::ClosureKind::Fn | ty::ClosureKind::FnMut)) => kind,
481                    Some(ty::ClosureKind::FnOnce) => {
482                        bug!("closure kind does not match first argument type")
483                    }
484                    None => bug!("closure kind not inferred by borrowck"),
485                };
486                let capture_description =
487                    format!("captured variable in an `{closure_kind}` closure");
488
489                let upvar = &self.upvars[upvar_field.index()];
490                let upvar_hir_id = upvar.get_root_variable();
491                let upvar_name = upvar.to_string(tcx);
492                let upvar_span = tcx.hir_span(upvar_hir_id);
493
494                let place_name = self.describe_any_place(move_place.as_ref());
495
496                let place_description =
497                    if self.is_upvar_field_projection(move_place.as_ref()).is_some() {
498                        format!("{place_name}, a {capture_description}")
499                    } else {
500                        format!("{place_name}, as `{upvar_name}` is a {capture_description}")
501                    };
502
503                debug!(
504                    "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
505                    closure_kind_ty, closure_kind, place_description,
506                );
507
508                let closure_span = tcx.def_span(def_id);
509
510                self.cannot_move_out_of(span, &place_description)
511                    .with_span_label(upvar_span, "captured outer variable")
512                    .with_span_label(
513                        closure_span,
514                        format!("captured by this `{closure_kind}` closure"),
515                    )
516                    .with_span_help(
517                        self.get_closure_bound_clause_span(*def_id),
518                        "`Fn` and `FnMut` closures require captured values to be able to be \
519                         consumed multiple times, but `FnOnce` closures may consume them only once",
520                    )
521            }
522            _ => {
523                let source = self.borrowed_content_source(deref_base);
524                let move_place_ref = move_place.as_ref();
525                match (
526                    self.describe_place_with_options(
527                        move_place_ref,
528                        DescribePlaceOpt {
529                            including_downcast: false,
530                            including_tuple_field: false,
531                        },
532                    ),
533                    self.describe_name(move_place_ref),
534                    source.describe_for_named_place(),
535                ) {
536                    (Some(place_desc), Some(name), Some(source_desc)) => self.cannot_move_out_of(
537                        span,
538                        &format!("`{place_desc}` as enum variant `{name}` which is behind a {source_desc}"),
539                    ),
540                    (Some(place_desc), Some(name), None) => self.cannot_move_out_of(
541                        span,
542                        &format!("`{place_desc}` as enum variant `{name}`"),
543                    ),
544                    (Some(place_desc), _, Some(source_desc)) => self.cannot_move_out_of(
545                        span,
546                        &format!("`{place_desc}` which is behind a {source_desc}"),
547                    ),
548                    (_, _, _) => self.cannot_move_out_of(
549                        span,
550                        &source.describe_for_unnamed_place(tcx),
551                    ),
552                }
553            }
554        };
555        let msg_opt = CapturedMessageOpt {
556            is_partial_move: false,
557            is_loop_message: false,
558            is_move_msg: false,
559            is_loop_move: false,
560            has_suggest_reborrow: false,
561            maybe_reinitialized_locations_is_empty: true,
562        };
563        if let Some(use_spans) = use_spans {
564            self.explain_captures(&mut err, span, span, use_spans, move_place, msg_opt);
565        }
566        err
567    }
568
569    fn get_closure_bound_clause_span(&self, def_id: DefId) -> Span {
570        let tcx = self.infcx.tcx;
571        let typeck_result = tcx.typeck(self.mir_def_id());
572        // Check whether the closure is an argument to a call, if so,
573        // get the instantiated where-bounds of that call.
574        let closure_hir_id = tcx.local_def_id_to_hir_id(def_id.expect_local());
575        let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_hir_id) else { return DUMMY_SP };
576
577        let predicates = match parent.kind {
578            hir::ExprKind::Call(callee, _) => {
579                let Some(ty) = typeck_result.node_type_opt(callee.hir_id) else { return DUMMY_SP };
580                let ty::FnDef(fn_def_id, args) = ty.kind() else { return DUMMY_SP };
581                tcx.predicates_of(fn_def_id).instantiate(tcx, args)
582            }
583            hir::ExprKind::MethodCall(..) => {
584                let Some((_, method)) = typeck_result.type_dependent_def(parent.hir_id) else {
585                    return DUMMY_SP;
586                };
587                let args = typeck_result.node_args(parent.hir_id);
588                tcx.predicates_of(method).instantiate(tcx, args)
589            }
590            _ => return DUMMY_SP,
591        };
592
593        // Check whether one of the where-bounds requires the closure to impl `Fn[Mut]`.
594        for (pred, span) in predicates.predicates.iter().zip(predicates.spans.iter()) {
595            if let Some(clause) = pred.as_trait_clause()
596                && let ty::Closure(clause_closure_def_id, _) = clause.self_ty().skip_binder().kind()
597                && *clause_closure_def_id == def_id
598                && (tcx.lang_items().fn_mut_trait() == Some(clause.def_id())
599                    || tcx.lang_items().fn_trait() == Some(clause.def_id()))
600            {
601                // Found `<TyOfCapturingClosure as FnMut>`
602                // We point at the `Fn()` or `FnMut()` bound that coerced the closure, which
603                // could be changed to `FnOnce()` to avoid the move error.
604                return *span;
605            }
606        }
607        DUMMY_SP
608    }
609
610    fn add_move_hints(&self, error: GroupedMoveError<'tcx>, err: &mut Diag<'_>, span: Span) {
611        match error {
612            GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
613                self.add_borrow_suggestions(err, span);
614                if binds_to.is_empty() {
615                    let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
616                    let place_desc = match self.describe_place(move_from.as_ref()) {
617                        Some(desc) => format!("`{desc}`"),
618                        None => "value".to_string(),
619                    };
620
621                    if let Some(expr) = self.find_expr(span) {
622                        self.suggest_cloning(err, move_from.as_ref(), place_ty, expr, None);
623                    }
624
625                    err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
626                        is_partial_move: false,
627                        ty: place_ty,
628                        place: &place_desc,
629                        span,
630                    });
631                } else {
632                    binds_to.sort();
633                    binds_to.dedup();
634
635                    self.add_move_error_details(err, &binds_to);
636                }
637            }
638            GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
639                binds_to.sort();
640                binds_to.dedup();
641                self.add_move_error_suggestions(err, &binds_to);
642                self.add_move_error_details(err, &binds_to);
643            }
644            // No binding. Nothing to suggest.
645            GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
646                let mut use_span = use_spans.var_or_use();
647                let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
648                let place_desc = match self.describe_place(original_path.as_ref()) {
649                    Some(desc) => format!("`{desc}`"),
650                    None => "value".to_string(),
651                };
652
653                if let Some(expr) = self.find_expr(use_span) {
654                    self.suggest_cloning(
655                        err,
656                        original_path.as_ref(),
657                        place_ty,
658                        expr,
659                        Some(use_spans),
660                    );
661                }
662
663                if let Some(upvar_field) = self
664                    .prefixes(original_path.as_ref(), PrefixSet::All)
665                    .find_map(|p| self.is_upvar_field_projection(p))
666                {
667                    // Look for the introduction of the original binding being moved.
668                    let upvar = &self.upvars[upvar_field.index()];
669                    let upvar_hir_id = upvar.get_root_variable();
670                    use_span = match self.infcx.tcx.parent_hir_node(upvar_hir_id) {
671                        hir::Node::Param(param) => {
672                            // Instead of pointing at the path where we access the value within a
673                            // closure, we point at the type of the outer `fn` argument.
674                            param.ty_span
675                        }
676                        hir::Node::LetStmt(stmt) => match (stmt.ty, stmt.init) {
677                            // We point at the type of the outer let-binding.
678                            (Some(ty), _) => ty.span,
679                            // We point at the initializer of the outer let-binding, but only if it
680                            // isn't something that spans multiple lines, like a closure, as the
681                            // ASCII art gets messy.
682                            (None, Some(init))
683                                if !self.infcx.tcx.sess.source_map().is_multiline(init.span) =>
684                            {
685                                init.span
686                            }
687                            _ => use_span,
688                        },
689                        _ => use_span,
690                    };
691                }
692
693                err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
694                    is_partial_move: false,
695                    ty: place_ty,
696                    place: &place_desc,
697                    span: use_span,
698                });
699
700                let mut pointed_at_span = false;
701                use_spans.args_subdiag(err, |args_span| {
702                    if args_span == span || args_span == use_span {
703                        pointed_at_span = true;
704                    }
705                    crate::session_diagnostics::CaptureArgLabel::MoveOutPlace {
706                        place: place_desc.clone(),
707                        args_span,
708                    }
709                });
710                if !pointed_at_span && use_span != span {
711                    err.subdiagnostic(crate::session_diagnostics::CaptureArgLabel::MoveOutPlace {
712                        place: place_desc,
713                        args_span: span,
714                    });
715                }
716
717                self.add_note_for_packed_struct_derive(err, original_path.local);
718            }
719        }
720    }
721
722    fn add_borrow_suggestions(&self, err: &mut Diag<'_>, span: Span) {
723        match self.infcx.tcx.sess.source_map().span_to_snippet(span) {
724            Ok(snippet) if snippet.starts_with('*') => {
725                let sp = span.with_lo(span.lo() + BytePos(1));
726                let inner = self.find_expr(sp);
727                let mut is_raw_ptr = false;
728                if let Some(inner) = inner {
729                    let typck_result = self.infcx.tcx.typeck(self.mir_def_id());
730                    if let Some(inner_type) = typck_result.node_type_opt(inner.hir_id) {
731                        if matches!(inner_type.kind(), ty::RawPtr(..)) {
732                            is_raw_ptr = true;
733                        }
734                    }
735                }
736                // If the `inner` is a raw pointer, do not suggest removing the "*", see #126863
737                // FIXME: need to check whether the assigned object can be a raw pointer, see `tests/ui/borrowck/issue-20801.rs`.
738                if !is_raw_ptr {
739                    err.span_suggestion_verbose(
740                        span.with_hi(span.lo() + BytePos(1)),
741                        "consider removing the dereference here",
742                        String::new(),
743                        Applicability::MaybeIncorrect,
744                    );
745                }
746            }
747            _ => {
748                err.span_suggestion_verbose(
749                    span.shrink_to_lo(),
750                    "consider borrowing here",
751                    '&',
752                    Applicability::MaybeIncorrect,
753                );
754            }
755        }
756    }
757
758    fn add_move_error_suggestions(&self, err: &mut Diag<'_>, binds_to: &[Local]) {
759        /// A HIR visitor to associate each binding with a `&` or `&mut` that could be removed to
760        /// make it bind by reference instead (if possible)
761        struct BindingFinder<'tcx> {
762            typeck_results: &'tcx ty::TypeckResults<'tcx>,
763            tcx: TyCtxt<'tcx>,
764            /// Input: the span of the pattern we're finding bindings in
765            pat_span: Span,
766            /// Input: the spans of the bindings we're providing suggestions for
767            binding_spans: Vec<Span>,
768            /// Internal state: have we reached the pattern we're finding bindings in?
769            found_pat: bool,
770            /// Internal state: the innermost `&` or `&mut` "above" the visitor
771            ref_pat: Option<&'tcx hir::Pat<'tcx>>,
772            /// Internal state: could removing a `&` give bindings unexpected types?
773            has_adjustments: bool,
774            /// Output: for each input binding, the `&` or `&mut` to remove to make it by-ref
775            ref_pat_for_binding: Vec<(Span, Option<&'tcx hir::Pat<'tcx>>)>,
776            /// Output: ref patterns that can't be removed straightforwardly
777            cannot_remove: FxHashSet<HirId>,
778        }
779        impl<'tcx> Visitor<'tcx> for BindingFinder<'tcx> {
780            type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
781
782            fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
783                self.tcx
784            }
785
786            fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
787                // Don't walk into const patterns or anything else that might confuse this
788                if !self.found_pat {
789                    hir::intravisit::walk_expr(self, ex)
790                }
791            }
792
793            fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
794                if p.span == self.pat_span {
795                    self.found_pat = true;
796                }
797
798                let parent_has_adjustments = self.has_adjustments;
799                self.has_adjustments |=
800                    self.typeck_results.pat_adjustments().contains_key(p.hir_id);
801
802                // Track the innermost `&` or `&mut` enclosing bindings, to suggest removing it.
803                let parent_ref_pat = self.ref_pat;
804                if let hir::PatKind::Ref(..) = p.kind {
805                    self.ref_pat = Some(p);
806                    // To avoid edition-dependent logic to figure out how many refs this `&` can
807                    // peel off, simply don't remove the "parent" `&`.
808                    self.cannot_remove.extend(parent_ref_pat.map(|r| r.hir_id));
809                    if self.has_adjustments {
810                        // Removing this `&` could give child bindings unexpected types, so don't.
811                        self.cannot_remove.insert(p.hir_id);
812                        // As long the `&` stays, child patterns' types should be as expected.
813                        self.has_adjustments = false;
814                    }
815                }
816
817                if let hir::PatKind::Binding(_, _, ident, _) = p.kind {
818                    // the spans in `binding_spans` encompass both the ident and binding mode
819                    if let Some(&bind_sp) =
820                        self.binding_spans.iter().find(|bind_sp| bind_sp.contains(ident.span))
821                    {
822                        self.ref_pat_for_binding.push((bind_sp, self.ref_pat));
823                    } else {
824                        // we've encountered a binding that we're not reporting a move error for.
825                        // we don't want to change its type, so don't remove the surrounding `&`.
826                        if let Some(ref_pat) = self.ref_pat {
827                            self.cannot_remove.insert(ref_pat.hir_id);
828                        }
829                    }
830                }
831
832                hir::intravisit::walk_pat(self, p);
833                self.ref_pat = parent_ref_pat;
834                self.has_adjustments = parent_has_adjustments;
835            }
836        }
837        let mut pat_span = None;
838        let mut binding_spans = Vec::new();
839        for local in binds_to {
840            let bind_to = &self.body.local_decls[*local];
841            if let LocalInfo::User(BindingForm::Var(VarBindingForm { pat_span: pat_sp, .. })) =
842                *bind_to.local_info()
843            {
844                pat_span = Some(pat_sp);
845                binding_spans.push(bind_to.source_info.span);
846            }
847        }
848        let Some(pat_span) = pat_span else { return };
849
850        let tcx = self.infcx.tcx;
851        let Some(body) = tcx.hir_maybe_body_owned_by(self.mir_def_id()) else { return };
852        let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
853        let mut finder = BindingFinder {
854            typeck_results,
855            tcx,
856            pat_span,
857            binding_spans,
858            found_pat: false,
859            ref_pat: None,
860            has_adjustments: false,
861            ref_pat_for_binding: Vec::new(),
862            cannot_remove: FxHashSet::default(),
863        };
864        finder.visit_body(body);
865
866        let mut suggestions = Vec::new();
867        for (binding_span, opt_ref_pat) in finder.ref_pat_for_binding {
868            if let Some(ref_pat) = opt_ref_pat
869                && !finder.cannot_remove.contains(&ref_pat.hir_id)
870                && let hir::PatKind::Ref(subpat, mutbl) = ref_pat.kind
871                && let Some(ref_span) = ref_pat.span.trim_end(subpat.span)
872            {
873                let mutable_str = if mutbl.is_mut() { "mutable " } else { "" };
874                let msg = format!("consider removing the {mutable_str}borrow");
875                suggestions.push((ref_span, msg, "".to_string()));
876            } else {
877                let msg = "consider borrowing the pattern binding".to_string();
878                suggestions.push((binding_span.shrink_to_lo(), msg, "ref ".to_string()));
879            }
880        }
881        suggestions.sort_unstable_by_key(|&(span, _, _)| span);
882        suggestions.dedup_by_key(|&mut (span, _, _)| span);
883        for (span, msg, suggestion) in suggestions {
884            err.span_suggestion_verbose(span, msg, suggestion, Applicability::MachineApplicable);
885        }
886    }
887
888    fn add_move_error_details(&self, err: &mut Diag<'_>, binds_to: &[Local]) {
889        for (j, local) in binds_to.iter().enumerate() {
890            let bind_to = &self.body.local_decls[*local];
891            let binding_span = bind_to.source_info.span;
892
893            if j == 0 {
894                err.span_label(binding_span, "data moved here");
895            } else {
896                err.span_label(binding_span, "...and here");
897            }
898
899            if binds_to.len() == 1 {
900                let place_desc = self.local_name(*local).map(|sym| format!("`{sym}`"));
901
902                if let Some(expr) = self.find_expr(binding_span) {
903                    let local_place: PlaceRef<'tcx> = (*local).into();
904                    self.suggest_cloning(err, local_place, bind_to.ty, expr, None);
905                }
906
907                err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
908                    is_partial_move: false,
909                    ty: bind_to.ty,
910                    place: place_desc.as_deref().unwrap_or("the place"),
911                    span: binding_span,
912                });
913            }
914        }
915
916        if binds_to.len() > 1 {
917            err.note(
918                "move occurs because these variables have types that don't implement the `Copy` \
919                 trait",
920            );
921        }
922    }
923
924    /// Adds an explanatory note if the move error occurs in a derive macro
925    /// expansion of a packed struct.
926    /// Such errors happen because derive macro expansions shy away from taking
927    /// references to the struct's fields since doing so would be undefined behaviour
928    fn add_note_for_packed_struct_derive(&self, err: &mut Diag<'_>, local: Local) {
929        let local_place: PlaceRef<'tcx> = local.into();
930        let local_ty = local_place.ty(self.body.local_decls(), self.infcx.tcx).ty.peel_refs();
931
932        if let Some(adt) = local_ty.ty_adt_def()
933            && adt.repr().packed()
934            && let ExpnKind::Macro(MacroKind::Derive, name) =
935                self.body.span.ctxt().outer_expn_data().kind
936        {
937            err.note(format!("`#[derive({name})]` triggers a move because taking references to the fields of a packed struct is undefined behaviour"));
938        }
939    }
940}