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