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