]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/diagnostics/move_errors.rs
ceb97a98f1f7e157abc41bf772f94f6f14929a11
[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::Span;
5
6 use crate::borrow_check::diagnostics::UseSpans;
7 use crate::borrow_check::prefixes::PrefixSet;
8 use crate::borrow_check::MirBorrowckCtxt;
9 use crate::dataflow::move_paths::{
10     IllegalMoveOrigin, IllegalMoveOriginKind, LookupResult, MoveError, MovePathIndex,
11 };
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,
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 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
106                             VarBindingForm {
107                                 opt_match_place: Some((ref 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!("append_binding_error(match_place={:?}, match_span={:?})", match_place, match_span);
152
153         let from_simple_let = match_place.is_none();
154         let match_place = match_place.as_ref().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                         if match_span == *span {
162                             debug!("appending local({:?}) to list", bind_to);
163                             if !binds_to.is_empty() {
164                                 binds_to.push(bind_to);
165                             }
166                             return;
167                         }
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: match_place.clone(),
181                     original_path,
182                     kind,
183                     binds_to,
184                 });
185             }
186             // Error with the pattern
187             LookupResult::Exact(_) => {
188                 let mpi = match self.move_data.rev_lookup.find(move_from.as_ref()) {
189                     LookupResult::Parent(Some(mpi)) => mpi,
190                     // move_from should be a projection from match_place.
191                     _ => unreachable!("Probably not unreachable..."),
192                 };
193                 for ge in &mut *grouped_errors {
194                     if let GroupedMoveError::MovesFromValue {
195                         span,
196                         move_from: other_mpi,
197                         binds_to,
198                         ..
199                     } = ge
200                     {
201                         if match_span == *span && mpi == *other_mpi {
202                             debug!("appending local({:?}) to list", bind_to);
203                             binds_to.push(bind_to);
204                             return;
205                         }
206                     }
207                 }
208                 debug!("found a new move error location");
209                 grouped_errors.push(GroupedMoveError::MovesFromValue {
210                     span: match_span,
211                     move_from: mpi,
212                     original_path,
213                     kind,
214                     binds_to: vec![bind_to],
215                 });
216             }
217         };
218     }
219
220     fn report(&mut self, error: GroupedMoveError<'tcx>) {
221         let (mut err, err_span) = {
222             let (span, use_spans, original_path, kind): (
223                 Span,
224                 Option<UseSpans>,
225                 &Place<'tcx>,
226                 &IllegalMoveOriginKind<'_>,
227             ) = match error {
228                 GroupedMoveError::MovesFromPlace { span, ref original_path, ref kind, .. }
229                 | GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } => {
230                     (span, None, original_path, kind)
231                 }
232                 GroupedMoveError::OtherIllegalMove { use_spans, ref original_path, ref kind } => {
233                     (use_spans.args_or_use(), Some(use_spans), original_path, kind)
234                 }
235             };
236             debug!(
237                 "report: original_path={:?} span={:?}, kind={:?} \
238                    original_path.is_upvar_field_projection={:?}",
239                 original_path,
240                 span,
241                 kind,
242                 self.is_upvar_field_projection(original_path.as_ref())
243             );
244             (
245                 match kind {
246                     IllegalMoveOriginKind::BorrowedContent { target_place } => self
247                         .report_cannot_move_from_borrowed_content(
248                             original_path,
249                             target_place,
250                             span,
251                             use_spans,
252                         ),
253                     IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
254                         self.cannot_move_out_of_interior_of_drop(span, ty)
255                     }
256                     IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => {
257                         self.cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index))
258                     }
259                 },
260                 span,
261             )
262         };
263
264         self.add_move_hints(error, &mut err, err_span);
265         err.buffer(&mut self.errors_buffer);
266     }
267
268     fn report_cannot_move_from_static(
269         &mut self,
270         place: &Place<'tcx>,
271         span: Span,
272     ) -> DiagnosticBuilder<'a> {
273         let description = if place.projection.len() == 1 {
274             format!("static item `{}`", self.describe_place(place.as_ref()).unwrap())
275         } else {
276             let base_static = PlaceRef { base: &place.base, projection: &[ProjectionElem::Deref] };
277
278             format!(
279                 "`{:?}` as `{:?}` is a static item",
280                 self.describe_place(place.as_ref()).unwrap(),
281                 self.describe_place(base_static).unwrap(),
282             )
283         };
284
285         self.cannot_move_out_of(span, &description)
286     }
287
288     fn report_cannot_move_from_borrowed_content(
289         &mut self,
290         move_place: &Place<'tcx>,
291         deref_target_place: &Place<'tcx>,
292         span: Span,
293         use_spans: Option<UseSpans>,
294     ) -> DiagnosticBuilder<'a> {
295         // Inspect the type of the content behind the
296         // borrow to provide feedback about why this
297         // was a move rather than a copy.
298         let ty = deref_target_place.ty(*self.body, self.infcx.tcx).ty;
299         let upvar_field = self
300             .prefixes(move_place.as_ref(), PrefixSet::All)
301             .find_map(|p| self.is_upvar_field_projection(p));
302
303         let deref_base = match deref_target_place.projection.as_ref() {
304             &[ref proj_base @ .., ProjectionElem::Deref] => {
305                 PlaceRef { base: &deref_target_place.base, projection: &proj_base }
306             }
307             _ => bug!("deref_target_place is not a deref projection"),
308         };
309
310         if let PlaceRef { base: PlaceBase::Local(local), projection: [] } = deref_base {
311             let decl = &self.body.local_decls[*local];
312             if decl.is_ref_for_guard() {
313                 let mut err = self.cannot_move_out_of(
314                     span,
315                     &format!("`{}` in pattern guard", self.local_names[*local].unwrap()),
316                 );
317                 err.note(
318                     "variables bound in patterns cannot be moved from \
319                      until after the end of the pattern guard",
320                 );
321                 return err;
322             } else if decl.is_ref_to_static() {
323                 return self.report_cannot_move_from_static(move_place, span);
324             }
325         }
326
327         debug!("report: ty={:?}", ty);
328         let mut err = match ty.kind {
329             ty::Array(..) | ty::Slice(..) => {
330                 self.cannot_move_out_of_interior_noncopy(span, ty, None)
331             }
332             ty::Closure(def_id, closure_substs)
333                 if def_id == self.mir_def_id && upvar_field.is_some() =>
334             {
335                 let closure_kind_ty = closure_substs.as_closure().kind_ty(def_id, self.infcx.tcx);
336                 let closure_kind = closure_kind_ty.to_opt_closure_kind();
337                 let capture_description = match closure_kind {
338                     Some(ty::ClosureKind::Fn) => "captured variable in an `Fn` closure",
339                     Some(ty::ClosureKind::FnMut) => "captured variable in an `FnMut` closure",
340                     Some(ty::ClosureKind::FnOnce) => {
341                         bug!("closure kind does not match first argument type")
342                     }
343                     None => bug!("closure kind not inferred by borrowck"),
344                 };
345
346                 let upvar = &self.upvars[upvar_field.unwrap().index()];
347                 let upvar_hir_id = upvar.var_hir_id;
348                 let upvar_name = upvar.name;
349                 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
350
351                 let place_name = self.describe_place(move_place.as_ref()).unwrap();
352
353                 let place_description = if self
354                     .is_upvar_field_projection(move_place.as_ref())
355                     .is_some()
356                 {
357                     format!("`{}`, a {}", place_name, capture_description)
358                 } else {
359                     format!("`{}`, as `{}` is a {}", place_name, upvar_name, capture_description,)
360                 };
361
362                 debug!(
363                     "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
364                     closure_kind_ty, closure_kind, place_description,
365                 );
366
367                 let mut diag = self.cannot_move_out_of(span, &place_description);
368
369                 diag.span_label(upvar_span, "captured outer variable");
370
371                 diag
372             }
373             _ => {
374                 let source = self.borrowed_content_source(deref_base);
375                 match (self.describe_place(move_place.as_ref()), source.describe_for_named_place())
376                 {
377                     (Some(place_desc), Some(source_desc)) => self.cannot_move_out_of(
378                         span,
379                         &format!("`{}` which is behind a {}", place_desc, source_desc),
380                     ),
381                     (_, _) => self.cannot_move_out_of(span, &source.describe_for_unnamed_place()),
382                 }
383             }
384         };
385         let move_ty = format!("{:?}", move_place.ty(*self.body, self.infcx.tcx).ty,);
386         if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
387             let is_option = move_ty.starts_with("std::option::Option");
388             let is_result = move_ty.starts_with("std::result::Result");
389             if (is_option || is_result) && use_spans.map_or(true, |v| !v.for_closure()) {
390                 err.span_suggestion(
391                     span,
392                     &format!(
393                         "consider borrowing the `{}`'s content",
394                         if is_option { "Option" } else { "Result" }
395                     ),
396                     format!("{}.as_ref()", snippet),
397                     Applicability::MaybeIncorrect,
398                 );
399             }
400         }
401         err
402     }
403
404     fn add_move_hints(
405         &self,
406         error: GroupedMoveError<'tcx>,
407         err: &mut DiagnosticBuilder<'a>,
408         span: Span,
409     ) {
410         match error {
411             GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
412                 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
413                     err.span_suggestion(
414                         span,
415                         "consider borrowing here",
416                         format!("&{}", snippet),
417                         Applicability::Unspecified,
418                     );
419                 }
420
421                 if binds_to.is_empty() {
422                     let place_ty = move_from.ty(*self.body, self.infcx.tcx).ty;
423                     let place_desc = match self.describe_place(move_from.as_ref()) {
424                         Some(desc) => format!("`{}`", desc),
425                         None => format!("value"),
426                     };
427
428                     self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span));
429                 } else {
430                     binds_to.sort();
431                     binds_to.dedup();
432
433                     self.add_move_error_details(err, &binds_to);
434                 }
435             }
436             GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
437                 binds_to.sort();
438                 binds_to.dedup();
439                 self.add_move_error_suggestions(err, &binds_to);
440                 self.add_move_error_details(err, &binds_to);
441             }
442             // No binding. Nothing to suggest.
443             GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
444                 let span = use_spans.var_or_use();
445                 let place_ty = original_path.ty(*self.body, self.infcx.tcx).ty;
446                 let place_desc = match self.describe_place(original_path.as_ref()) {
447                     Some(desc) => format!("`{}`", desc),
448                     None => format!("value"),
449                 };
450                 self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span));
451
452                 use_spans.args_span_label(err, format!("move out of {} occurs here", place_desc));
453                 use_spans
454                     .var_span_label(err, format!("move occurs due to use{}", use_spans.describe()));
455             }
456         }
457     }
458
459     fn add_move_error_suggestions(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
460         let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
461         for local in binds_to {
462             let bind_to = &self.body.local_decls[*local];
463             if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
464                 pat_span,
465                 ..
466             }))) = bind_to.local_info
467             {
468                 if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
469                 {
470                     if pat_snippet.starts_with('&') {
471                         let pat_snippet = pat_snippet[1..].trim_start();
472                         let suggestion;
473                         let to_remove;
474                         if pat_snippet.starts_with("mut")
475                             && pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
476                         {
477                             suggestion = pat_snippet["mut".len()..].trim_start();
478                             to_remove = "&mut";
479                         } else {
480                             suggestion = pat_snippet;
481                             to_remove = "&";
482                         }
483                         suggestions.push((pat_span, to_remove, suggestion.to_owned()));
484                     }
485                 }
486             }
487         }
488         suggestions.sort_unstable_by_key(|&(span, _, _)| span);
489         suggestions.dedup_by_key(|&mut (span, _, _)| span);
490         for (span, to_remove, suggestion) in suggestions {
491             err.span_suggestion(
492                 span,
493                 &format!("consider removing the `{}`", to_remove),
494                 suggestion,
495                 Applicability::MachineApplicable,
496             );
497         }
498     }
499
500     fn add_move_error_details(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
501         for (j, local) in binds_to.into_iter().enumerate() {
502             let bind_to = &self.body.local_decls[*local];
503             let binding_span = bind_to.source_info.span;
504
505             if j == 0 {
506                 err.span_label(binding_span, "data moved here");
507             } else {
508                 err.span_label(binding_span, "...and here");
509             }
510
511             if binds_to.len() == 1 {
512                 self.note_type_does_not_implement_copy(
513                     err,
514                     &format!("`{}`", self.local_names[*local].unwrap()),
515                     bind_to.ty,
516                     Some(binding_span),
517                 );
518             }
519         }
520
521         if binds_to.len() > 1 {
522             err.note(
523                 "move occurs because these variables have types that \
524                       don't implement the `Copy` trait",
525             );
526         }
527     }
528 }