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