]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/diagnostics/move_errors.rs
c016cc90b1b8679b0369aacf43dc5c44ca2501b3
[rust.git] / src / librustc_mir / borrow_check / diagnostics / move_errors.rs
1 use rustc::mir::*;
2 use rustc::ty;
3 use rustc_errors::{Applicability, DiagnosticBuilder};
4 use rustc_span::source_map::DesugaringKind;
5 use rustc_span::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,
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 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
107                             VarBindingForm {
108                                 opt_match_place: Some((ref 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.as_ref().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: match_place.clone(),
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>,
226                 &Place<'tcx>,
227                 &IllegalMoveOriginKind<'_>,
228             ) = match error {
229                 GroupedMoveError::MovesFromPlace { span, ref original_path, ref kind, .. }
230                 | GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } => {
231                     (span, None, original_path, kind)
232                 }
233                 GroupedMoveError::OtherIllegalMove { use_spans, ref 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_place(place.as_ref()).unwrap())
276         } else {
277             let base_static =
278                 PlaceRef { local: &place.local, projection: &[ProjectionElem::Deref] };
279
280             format!(
281                 "`{:?}` as `{:?}` is a static item",
282                 self.describe_place(place.as_ref()).unwrap(),
283                 self.describe_place(base_static).unwrap(),
284             )
285         };
286
287         self.cannot_move_out_of(span, &description)
288     }
289
290     fn report_cannot_move_from_borrowed_content(
291         &mut self,
292         move_place: &Place<'tcx>,
293         deref_target_place: &Place<'tcx>,
294         span: Span,
295         use_spans: Option<UseSpans>,
296     ) -> DiagnosticBuilder<'a> {
297         // Inspect the type of the content behind the
298         // borrow to provide feedback about why this
299         // was a move rather than a copy.
300         let ty = deref_target_place.ty(*self.body, self.infcx.tcx).ty;
301         let upvar_field = self
302             .prefixes(move_place.as_ref(), PrefixSet::All)
303             .find_map(|p| self.is_upvar_field_projection(p));
304
305         let deref_base = match deref_target_place.projection.as_ref() {
306             &[ref proj_base @ .., ProjectionElem::Deref] => {
307                 PlaceRef { local: &deref_target_place.local, projection: &proj_base }
308             }
309             _ => bug!("deref_target_place is not a deref projection"),
310         };
311
312         if let PlaceRef { local, projection: [] } = deref_base {
313             let decl = &self.body.local_decls[*local];
314             if decl.is_ref_for_guard() {
315                 let mut err = self.cannot_move_out_of(
316                     span,
317                     &format!("`{}` in pattern guard", self.local_names[*local].unwrap()),
318                 );
319                 err.note(
320                     "variables bound in patterns cannot be moved from \
321                      until after the end of the pattern guard",
322                 );
323                 return err;
324             } else if decl.is_ref_to_static() {
325                 return self.report_cannot_move_from_static(move_place, span);
326             }
327         }
328
329         debug!("report: ty={:?}", ty);
330         let mut err = match ty.kind {
331             ty::Array(..) | ty::Slice(..) => {
332                 self.cannot_move_out_of_interior_noncopy(span, ty, None)
333             }
334             ty::Closure(def_id, closure_substs)
335                 if def_id == self.mir_def_id && upvar_field.is_some() =>
336             {
337                 let closure_kind_ty = closure_substs.as_closure().kind_ty(def_id, self.infcx.tcx);
338                 let closure_kind = closure_kind_ty.to_opt_closure_kind();
339                 let capture_description = match closure_kind {
340                     Some(ty::ClosureKind::Fn) => "captured variable in an `Fn` closure",
341                     Some(ty::ClosureKind::FnMut) => "captured variable in an `FnMut` closure",
342                     Some(ty::ClosureKind::FnOnce) => {
343                         bug!("closure kind does not match first argument type")
344                     }
345                     None => bug!("closure kind not inferred by borrowck"),
346                 };
347
348                 let upvar = &self.upvars[upvar_field.unwrap().index()];
349                 let upvar_hir_id = upvar.var_hir_id;
350                 let upvar_name = upvar.name;
351                 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
352
353                 let place_name = self.describe_place(move_place.as_ref()).unwrap();
354
355                 let place_description = if self
356                     .is_upvar_field_projection(move_place.as_ref())
357                     .is_some()
358                 {
359                     format!("`{}`, a {}", place_name, capture_description)
360                 } else {
361                     format!("`{}`, as `{}` is a {}", place_name, upvar_name, capture_description,)
362                 };
363
364                 debug!(
365                     "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
366                     closure_kind_ty, closure_kind, place_description,
367                 );
368
369                 let mut diag = self.cannot_move_out_of(span, &place_description);
370
371                 diag.span_label(upvar_span, "captured outer variable");
372
373                 diag
374             }
375             _ => {
376                 let source = self.borrowed_content_source(deref_base);
377                 match (self.describe_place(move_place.as_ref()), source.describe_for_named_place())
378                 {
379                     (Some(place_desc), Some(source_desc)) => self.cannot_move_out_of(
380                         span,
381                         &format!("`{}` which is behind a {}", place_desc, source_desc),
382                     ),
383                     (_, _) => self.cannot_move_out_of(span, &source.describe_for_unnamed_place()),
384                 }
385             }
386         };
387         let move_ty = format!("{:?}", move_place.ty(*self.body, self.infcx.tcx).ty,);
388         if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
389             let is_option = move_ty.starts_with("std::option::Option");
390             let is_result = move_ty.starts_with("std::result::Result");
391             if (is_option || is_result) && use_spans.map_or(true, |v| !v.for_closure()) {
392                 err.span_suggestion(
393                     span,
394                     &format!(
395                         "consider borrowing the `{}`'s content",
396                         if is_option { "Option" } else { "Result" }
397                     ),
398                     format!("{}.as_ref()", snippet),
399                     Applicability::MaybeIncorrect,
400                 );
401             } else if span.is_desugaring(DesugaringKind::ForLoop)
402                 && move_ty.starts_with("std::vec::Vec")
403             {
404                 // FIXME: suggest for anything that implements `IntoIterator`.
405                 err.span_suggestion(
406                     span,
407                     "consider iterating over a slice of the `Vec`'s content",
408                     format!("&{}", snippet),
409                     Applicability::MaybeIncorrect,
410                 );
411             }
412         }
413         err
414     }
415
416     fn add_move_hints(
417         &self,
418         error: GroupedMoveError<'tcx>,
419         err: &mut DiagnosticBuilder<'a>,
420         span: Span,
421     ) {
422         match error {
423             GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
424                 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
425                     err.span_suggestion(
426                         span,
427                         "consider borrowing here",
428                         format!("&{}", snippet),
429                         Applicability::Unspecified,
430                     );
431                 }
432
433                 if binds_to.is_empty() {
434                     let place_ty = move_from.ty(*self.body, self.infcx.tcx).ty;
435                     let place_desc = match self.describe_place(move_from.as_ref()) {
436                         Some(desc) => format!("`{}`", desc),
437                         None => format!("value"),
438                     };
439
440                     self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span));
441                 } else {
442                     binds_to.sort();
443                     binds_to.dedup();
444
445                     self.add_move_error_details(err, &binds_to);
446                 }
447             }
448             GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
449                 binds_to.sort();
450                 binds_to.dedup();
451                 self.add_move_error_suggestions(err, &binds_to);
452                 self.add_move_error_details(err, &binds_to);
453             }
454             // No binding. Nothing to suggest.
455             GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
456                 let span = use_spans.var_or_use();
457                 let place_ty = original_path.ty(*self.body, self.infcx.tcx).ty;
458                 let place_desc = match self.describe_place(original_path.as_ref()) {
459                     Some(desc) => format!("`{}`", desc),
460                     None => format!("value"),
461                 };
462                 self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span));
463
464                 use_spans.args_span_label(err, format!("move out of {} occurs here", place_desc));
465                 use_spans
466                     .var_span_label(err, format!("move occurs due to use{}", use_spans.describe()));
467             }
468         }
469     }
470
471     fn add_move_error_suggestions(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
472         let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
473         for local in binds_to {
474             let bind_to = &self.body.local_decls[*local];
475             if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
476                 pat_span,
477                 ..
478             }))) = bind_to.local_info
479             {
480                 if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
481                 {
482                     if pat_snippet.starts_with('&') {
483                         let pat_snippet = pat_snippet[1..].trim_start();
484                         let suggestion;
485                         let to_remove;
486                         if pat_snippet.starts_with("mut")
487                             && pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
488                         {
489                             suggestion = pat_snippet["mut".len()..].trim_start();
490                             to_remove = "&mut";
491                         } else {
492                             suggestion = pat_snippet;
493                             to_remove = "&";
494                         }
495                         suggestions.push((pat_span, to_remove, suggestion.to_owned()));
496                     }
497                 }
498             }
499         }
500         suggestions.sort_unstable_by_key(|&(span, _, _)| span);
501         suggestions.dedup_by_key(|&mut (span, _, _)| span);
502         for (span, to_remove, suggestion) in suggestions {
503             err.span_suggestion(
504                 span,
505                 &format!("consider removing the `{}`", to_remove),
506                 suggestion,
507                 Applicability::MachineApplicable,
508             );
509         }
510     }
511
512     fn add_move_error_details(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
513         for (j, local) in binds_to.into_iter().enumerate() {
514             let bind_to = &self.body.local_decls[*local];
515             let binding_span = bind_to.source_info.span;
516
517             if j == 0 {
518                 err.span_label(binding_span, "data moved here");
519             } else {
520                 err.span_label(binding_span, "...and here");
521             }
522
523             if binds_to.len() == 1 {
524                 self.note_type_does_not_implement_copy(
525                     err,
526                     &format!("`{}`", self.local_names[*local].unwrap()),
527                     bind_to.ty,
528                     Some(binding_span),
529                 );
530             }
531         }
532
533         if binds_to.len() > 1 {
534             err.note(
535                 "move occurs because these variables have types that \
536                       don't implement the `Copy` trait",
537             );
538         }
539     }
540 }