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