]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/move_errors.rs
Auto merge of #105145 - Ayush1325:sequential-remote-server, r=Mark-Simulacrum
[rust.git] / compiler / rustc_borrowck / src / diagnostics / move_errors.rs
1 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
2 use rustc_middle::mir::*;
3 use rustc_middle::ty;
4 use rustc_mir_dataflow::move_paths::{
5     IllegalMoveOrigin, IllegalMoveOriginKind, LookupResult, MoveError, MovePathIndex,
6 };
7 use rustc_span::{BytePos, Span};
8
9 use crate::diagnostics::{DescribePlaceOpt, UseSpans};
10 use crate::prefixes::PrefixSet;
11 use crate::MirBorrowckCtxt;
12
13 // Often when desugaring a pattern match we may have many individual moves in
14 // MIR that are all part of one operation from the user's point-of-view. For
15 // example:
16 //
17 // let (x, y) = foo()
18 //
19 // would move x from the 0 field of some temporary, and y from the 1 field. We
20 // group such errors together for cleaner error reporting.
21 //
22 // Errors are kept separate if they are from places with different parent move
23 // paths. For example, this generates two errors:
24 //
25 // let (&x, &y) = (&String::new(), &String::new());
26 #[derive(Debug)]
27 enum GroupedMoveError<'tcx> {
28     // Place expression can't be moved from,
29     // e.g., match x[0] { s => (), } where x: &[String]
30     MovesFromPlace {
31         original_path: Place<'tcx>,
32         span: Span,
33         move_from: Place<'tcx>,
34         kind: IllegalMoveOriginKind<'tcx>,
35         binds_to: Vec<Local>,
36     },
37     // Part of a value expression can't be moved from,
38     // e.g., match &String::new() { &x => (), }
39     MovesFromValue {
40         original_path: Place<'tcx>,
41         span: Span,
42         move_from: MovePathIndex,
43         kind: IllegalMoveOriginKind<'tcx>,
44         binds_to: Vec<Local>,
45     },
46     // Everything that isn't from pattern matching.
47     OtherIllegalMove {
48         original_path: Place<'tcx>,
49         use_spans: UseSpans<'tcx>,
50         kind: IllegalMoveOriginKind<'tcx>,
51     },
52 }
53
54 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
55     pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
56         let grouped_errors = self.group_move_errors(move_errors);
57         for error in grouped_errors {
58             self.report(error);
59         }
60     }
61
62     fn group_move_errors(
63         &self,
64         errors: Vec<(Place<'tcx>, MoveError<'tcx>)>,
65     ) -> Vec<GroupedMoveError<'tcx>> {
66         let mut grouped_errors = Vec::new();
67         for (original_path, error) in errors {
68             self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
69         }
70         grouped_errors
71     }
72
73     fn append_to_grouped_errors(
74         &self,
75         grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
76         original_path: Place<'tcx>,
77         error: MoveError<'tcx>,
78     ) {
79         match error {
80             MoveError::UnionMove { .. } => {
81                 unimplemented!("don't know how to report union move errors yet.")
82             }
83             MoveError::IllegalMove { cannot_move_out_of: IllegalMoveOrigin { location, kind } } => {
84                 // Note: that the only time we assign a place isn't a temporary
85                 // to a user variable is when initializing it.
86                 // If that ever stops being the case, then the ever initialized
87                 // flow could be used.
88                 if let Some(StatementKind::Assign(box (
89                     place,
90                     Rvalue::Use(Operand::Move(move_from)),
91                 ))) = self.body.basic_blocks[location.block]
92                     .statements
93                     .get(location.statement_index)
94                     .map(|stmt| &stmt.kind)
95                 {
96                     if let Some(local) = place.as_local() {
97                         let local_decl = &self.body.local_decls[local];
98                         // opt_match_place is the
99                         // match_span is the span of the expression being matched on
100                         // match *x.y { ... }        match_place is Some(*x.y)
101                         //       ^^^^                match_span is the span of *x.y
102                         //
103                         // opt_match_place is None for let [mut] x = ... statements,
104                         // whether or not the right-hand side is a place expression
105                         if let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
106                             VarBindingForm {
107                                 opt_match_place: Some((opt_match_place, match_span)),
108                                 binding_mode: _,
109                                 opt_ty_info: _,
110                                 pat_span: _,
111                             },
112                         )))) = local_decl.local_info
113                         {
114                             let stmt_source_info = self.body.source_info(location);
115                             self.append_binding_error(
116                                 grouped_errors,
117                                 kind,
118                                 original_path,
119                                 *move_from,
120                                 local,
121                                 opt_match_place,
122                                 match_span,
123                                 stmt_source_info.span,
124                             );
125                             return;
126                         }
127                     }
128                 }
129
130                 let move_spans = self.move_spans(original_path.as_ref(), location);
131                 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
132                     use_spans: move_spans,
133                     original_path,
134                     kind,
135                 });
136             }
137         }
138     }
139
140     fn append_binding_error(
141         &self,
142         grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
143         kind: IllegalMoveOriginKind<'tcx>,
144         original_path: Place<'tcx>,
145         move_from: Place<'tcx>,
146         bind_to: Local,
147         match_place: Option<Place<'tcx>>,
148         match_span: Span,
149         statement_span: Span,
150     ) {
151         debug!(?match_place, ?match_span, "append_binding_error");
152
153         let from_simple_let = match_place.is_none();
154         let match_place = match_place.unwrap_or(move_from);
155
156         match self.move_data.rev_lookup.find(match_place.as_ref()) {
157             // Error with the match place
158             LookupResult::Parent(_) => {
159                 for ge in &mut *grouped_errors {
160                     if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge
161                         && match_span == *span
162                     {
163                         debug!("appending local({bind_to:?}) to list");
164                         if !binds_to.is_empty() {
165                             binds_to.push(bind_to);
166                         }
167                         return;
168                     }
169                 }
170                 debug!("found a new move error location");
171
172                 // Don't need to point to x in let x = ... .
173                 let (binds_to, span) = if from_simple_let {
174                     (vec![], statement_span)
175                 } else {
176                     (vec![bind_to], match_span)
177                 };
178                 grouped_errors.push(GroupedMoveError::MovesFromPlace {
179                     span,
180                     move_from,
181                     original_path,
182                     kind,
183                     binds_to,
184                 });
185             }
186             // Error with the pattern
187             LookupResult::Exact(_) => {
188                 let LookupResult::Parent(Some(mpi)) = self.move_data.rev_lookup.find(move_from.as_ref()) else {
189                     // move_from should be a projection from match_place.
190                     unreachable!("Probably not unreachable...");
191                 };
192                 for ge in &mut *grouped_errors {
193                     if let GroupedMoveError::MovesFromValue {
194                         span,
195                         move_from: other_mpi,
196                         binds_to,
197                         ..
198                     } = ge
199                     {
200                         if match_span == *span && mpi == *other_mpi {
201                             debug!("appending local({bind_to:?}) to list");
202                             binds_to.push(bind_to);
203                             return;
204                         }
205                     }
206                 }
207                 debug!("found a new move error location");
208                 grouped_errors.push(GroupedMoveError::MovesFromValue {
209                     span: match_span,
210                     move_from: mpi,
211                     original_path,
212                     kind,
213                     binds_to: vec![bind_to],
214                 });
215             }
216         };
217     }
218
219     fn report(&mut self, error: GroupedMoveError<'tcx>) {
220         let (mut err, err_span) = {
221             let (span, use_spans, original_path, kind) = match error {
222                 GroupedMoveError::MovesFromPlace { span, original_path, ref kind, .. }
223                 | GroupedMoveError::MovesFromValue { span, original_path, ref kind, .. } => {
224                     (span, None, original_path, kind)
225                 }
226                 GroupedMoveError::OtherIllegalMove { use_spans, original_path, ref kind } => {
227                     (use_spans.args_or_use(), Some(use_spans), original_path, kind)
228                 }
229             };
230             debug!(
231                 "report: original_path={:?} span={:?}, kind={:?} \
232                    original_path.is_upvar_field_projection={:?}",
233                 original_path,
234                 span,
235                 kind,
236                 self.is_upvar_field_projection(original_path.as_ref())
237             );
238             (
239                 match kind {
240                     &IllegalMoveOriginKind::BorrowedContent { target_place } => self
241                         .report_cannot_move_from_borrowed_content(
242                             original_path,
243                             target_place,
244                             span,
245                             use_spans,
246                         ),
247                     &IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
248                         self.cannot_move_out_of_interior_of_drop(span, ty)
249                     }
250                     &IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => {
251                         self.cannot_move_out_of_interior_noncopy(span, ty, Some(is_index))
252                     }
253                 },
254                 span,
255             )
256         };
257
258         self.add_move_hints(error, &mut err, err_span);
259         self.buffer_error(err);
260     }
261
262     fn report_cannot_move_from_static(
263         &mut self,
264         place: Place<'tcx>,
265         span: Span,
266     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
267         let description = if place.projection.len() == 1 {
268             format!("static item {}", self.describe_any_place(place.as_ref()))
269         } else {
270             let base_static = PlaceRef { local: place.local, projection: &[ProjectionElem::Deref] };
271
272             format!(
273                 "{} as {} is a static item",
274                 self.describe_any_place(place.as_ref()),
275                 self.describe_any_place(base_static),
276             )
277         };
278
279         self.cannot_move_out_of(span, &description)
280     }
281
282     fn report_cannot_move_from_borrowed_content(
283         &mut self,
284         move_place: Place<'tcx>,
285         deref_target_place: Place<'tcx>,
286         span: Span,
287         use_spans: Option<UseSpans<'tcx>>,
288     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
289         // Inspect the type of the content behind the
290         // borrow to provide feedback about why this
291         // was a move rather than a copy.
292         let ty = deref_target_place.ty(self.body, self.infcx.tcx).ty;
293         let upvar_field = self
294             .prefixes(move_place.as_ref(), PrefixSet::All)
295             .find_map(|p| self.is_upvar_field_projection(p));
296
297         let deref_base = match deref_target_place.projection.as_ref() {
298             [proj_base @ .., ProjectionElem::Deref] => {
299                 PlaceRef { local: deref_target_place.local, projection: &proj_base }
300             }
301             _ => bug!("deref_target_place is not a deref projection"),
302         };
303
304         if let PlaceRef { local, projection: [] } = deref_base {
305             let decl = &self.body.local_decls[local];
306             if decl.is_ref_for_guard() {
307                 let mut err = self.cannot_move_out_of(
308                     span,
309                     &format!("`{}` in pattern guard", self.local_names[local].unwrap()),
310                 );
311                 err.note(
312                     "variables bound in patterns cannot be moved from \
313                      until after the end of the pattern guard",
314                 );
315                 return err;
316             } else if decl.is_ref_to_static() {
317                 return self.report_cannot_move_from_static(move_place, span);
318             }
319         }
320
321         debug!("report: ty={:?}", ty);
322         let mut err = match ty.kind() {
323             ty::Array(..) | ty::Slice(..) => {
324                 self.cannot_move_out_of_interior_noncopy(span, ty, None)
325             }
326             ty::Closure(def_id, closure_substs)
327                 if def_id.as_local() == Some(self.mir_def_id()) && upvar_field.is_some() =>
328             {
329                 let closure_kind_ty = closure_substs.as_closure().kind_ty();
330                 let closure_kind = match closure_kind_ty.to_opt_closure_kind() {
331                     Some(kind @ (ty::ClosureKind::Fn | ty::ClosureKind::FnMut)) => kind,
332                     Some(ty::ClosureKind::FnOnce) => {
333                         bug!("closure kind does not match first argument type")
334                     }
335                     None => bug!("closure kind not inferred by borrowck"),
336                 };
337                 let capture_description =
338                     format!("captured variable in an `{closure_kind}` closure");
339
340                 let upvar = &self.upvars[upvar_field.unwrap().index()];
341                 let upvar_hir_id = upvar.place.get_root_variable();
342                 let upvar_name = upvar.place.to_string(self.infcx.tcx);
343                 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
344
345                 let place_name = self.describe_any_place(move_place.as_ref());
346
347                 let place_description =
348                     if self.is_upvar_field_projection(move_place.as_ref()).is_some() {
349                         format!("{place_name}, a {capture_description}")
350                     } else {
351                         format!("{place_name}, as `{upvar_name}` is a {capture_description}")
352                     };
353
354                 debug!(
355                     "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
356                     closure_kind_ty, closure_kind, place_description,
357                 );
358
359                 let mut diag = self.cannot_move_out_of(span, &place_description);
360
361                 diag.span_label(upvar_span, "captured outer variable");
362                 diag.span_label(
363                     self.infcx.tcx.def_span(def_id),
364                     format!("captured by this `{closure_kind}` closure"),
365                 );
366
367                 diag
368             }
369             _ => {
370                 let source = self.borrowed_content_source(deref_base);
371                 let move_place_ref = move_place.as_ref();
372                 match (
373                     self.describe_place_with_options(
374                         move_place_ref,
375                         DescribePlaceOpt {
376                             including_downcast: false,
377                             including_tuple_field: false,
378                         },
379                     ),
380                     self.describe_name(move_place_ref),
381                     source.describe_for_named_place(),
382                 ) {
383                     (Some(place_desc), Some(name), Some(source_desc)) => self.cannot_move_out_of(
384                         span,
385                         &format!("`{place_desc}` as enum variant `{name}` which is behind a {source_desc}"),
386                     ),
387                     (Some(place_desc), Some(name), None) => self.cannot_move_out_of(
388                         span,
389                         &format!("`{place_desc}` as enum variant `{name}`"),
390                     ),
391                     (Some(place_desc), _, Some(source_desc)) => self.cannot_move_out_of(
392                         span,
393                         &format!("`{place_desc}` which is behind a {source_desc}"),
394                     ),
395                     (_, _, _) => self.cannot_move_out_of(
396                         span,
397                         &source.describe_for_unnamed_place(self.infcx.tcx),
398                     ),
399                 }
400             }
401         };
402         if let Some(use_spans) = use_spans {
403             self.explain_captures(
404                 &mut err, span, span, use_spans, move_place, "", "", "", false, true,
405             );
406         }
407         err
408     }
409
410     fn add_move_hints(&self, error: GroupedMoveError<'tcx>, err: &mut Diagnostic, span: Span) {
411         match error {
412             GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
413                 self.add_borrow_suggestions(err, span);
414                 if binds_to.is_empty() {
415                     let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
416                     let place_desc = match self.describe_place(move_from.as_ref()) {
417                         Some(desc) => format!("`{desc}`"),
418                         None => "value".to_string(),
419                     };
420
421                     self.note_type_does_not_implement_copy(
422                         err,
423                         &place_desc,
424                         place_ty,
425                         Some(span),
426                         "",
427                     );
428                 } else {
429                     binds_to.sort();
430                     binds_to.dedup();
431
432                     self.add_move_error_details(err, &binds_to);
433                 }
434             }
435             GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
436                 binds_to.sort();
437                 binds_to.dedup();
438                 self.add_move_error_suggestions(err, &binds_to);
439                 self.add_move_error_details(err, &binds_to);
440             }
441             // No binding. Nothing to suggest.
442             GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
443                 let span = use_spans.var_or_use();
444                 let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
445                 let place_desc = match self.describe_place(original_path.as_ref()) {
446                     Some(desc) => format!("`{desc}`"),
447                     None => "value".to_string(),
448                 };
449                 self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span), "");
450
451                 use_spans.args_span_label(err, format!("move out of {place_desc} occurs here"));
452             }
453         }
454     }
455
456     fn add_borrow_suggestions(&self, err: &mut Diagnostic, span: Span) {
457         match self.infcx.tcx.sess.source_map().span_to_snippet(span) {
458             Ok(snippet) if snippet.starts_with('*') => {
459                 err.span_suggestion_verbose(
460                     span.with_hi(span.lo() + BytePos(1)),
461                     "consider removing the dereference here",
462                     String::new(),
463                     Applicability::MaybeIncorrect,
464                 );
465             }
466             _ => {
467                 err.span_suggestion_verbose(
468                     span.shrink_to_lo(),
469                     "consider borrowing here",
470                     "&".to_string(),
471                     Applicability::MaybeIncorrect,
472                 );
473             }
474         }
475     }
476
477     fn add_move_error_suggestions(&self, err: &mut Diagnostic, binds_to: &[Local]) {
478         let mut suggestions: Vec<(Span, String, String)> = Vec::new();
479         for local in binds_to {
480             let bind_to = &self.body.local_decls[*local];
481             if let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
482                 VarBindingForm { pat_span, .. },
483             )))) = bind_to.local_info
484             {
485                 let Ok(pat_snippet) =
486                     self.infcx.tcx.sess.source_map().span_to_snippet(pat_span) else { continue; };
487                 let Some(stripped) = pat_snippet.strip_prefix('&') else {
488                     suggestions.push((
489                         bind_to.source_info.span.shrink_to_lo(),
490                         "consider borrowing the pattern binding".to_string(),
491                         "ref ".to_string(),
492                     ));
493                     continue;
494                 };
495                 let inner_pat_snippet = stripped.trim_start();
496                 let (pat_span, suggestion, to_remove) = if inner_pat_snippet.starts_with("mut")
497                     && inner_pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
498                 {
499                     let inner_pat_snippet = inner_pat_snippet["mut".len()..].trim_start();
500                     let pat_span = pat_span.with_hi(
501                         pat_span.lo()
502                             + BytePos((pat_snippet.len() - inner_pat_snippet.len()) as u32),
503                     );
504                     (pat_span, String::new(), "mutable borrow")
505                 } else {
506                     let pat_span = pat_span.with_hi(
507                         pat_span.lo()
508                             + BytePos(
509                                 (pat_snippet.len() - inner_pat_snippet.trim_start().len()) as u32,
510                             ),
511                     );
512                     (pat_span, String::new(), "borrow")
513                 };
514                 suggestions.push((
515                     pat_span,
516                     format!("consider removing the {to_remove}"),
517                     suggestion.to_string(),
518                 ));
519             }
520         }
521         suggestions.sort_unstable_by_key(|&(span, _, _)| span);
522         suggestions.dedup_by_key(|&mut (span, _, _)| span);
523         for (span, msg, suggestion) in suggestions {
524             err.span_suggestion_verbose(span, &msg, suggestion, Applicability::MachineApplicable);
525         }
526     }
527
528     fn add_move_error_details(&self, err: &mut Diagnostic, binds_to: &[Local]) {
529         for (j, local) in binds_to.iter().enumerate() {
530             let bind_to = &self.body.local_decls[*local];
531             let binding_span = bind_to.source_info.span;
532
533             if j == 0 {
534                 err.span_label(binding_span, "data moved here");
535             } else {
536                 err.span_label(binding_span, "...and here");
537             }
538
539             if binds_to.len() == 1 {
540                 self.note_type_does_not_implement_copy(
541                     err,
542                     &format!("`{}`", self.local_names[*local].unwrap()),
543                     bind_to.ty,
544                     Some(binding_span),
545                     "",
546                 );
547             }
548         }
549
550         if binds_to.len() > 1 {
551             err.note(
552                 "move occurs because these variables have types that don't implement the `Copy` \
553                  trait",
554             );
555         }
556     }
557 }