]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/diagnostics/move_errors.rs
Rollup merge of #67055 - lqd:const_qualif, r=oli-obk
[rust.git] / src / librustc_mir / borrow_check / diagnostics / move_errors.rs
1 use rustc::mir::*;
2 use rustc::ty;
3 use rustc_errors::{DiagnosticBuilder,Applicability};
4 use syntax_pos::Span;
5
6 use crate::borrow_check::MirBorrowckCtxt;
7 use crate::borrow_check::prefixes::PrefixSet;
8 use crate::borrow_check::diagnostics::UseSpans;
9 use crate::dataflow::move_paths::{
10     IllegalMoveOrigin, IllegalMoveOriginKind,
11     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 {
85                 cannot_move_out_of: IllegalMoveOrigin { location, kind },
86             } => {
87                 // Note: that the only time we assign a place isn't a temporary
88                 // to a user variable is when initializing it.
89                 // If that ever stops being the case, then the ever initialized
90                 // flow could be used.
91                 if let Some(StatementKind::Assign(
92                     box(place, Rvalue::Use(Operand::Move(move_from)))
93                 )) = self.body.basic_blocks()[location.block]
94                     .statements
95                     .get(location.statement_index)
96                     .map(|stmt| &stmt.kind)
97                 {
98                     if let Some(local) = place.as_local() {
99                         let local_decl = &self.body.local_decls[local];
100                         // opt_match_place is the
101                         // match_span is the span of the expression being matched on
102                         // match *x.y { ... }        match_place is Some(*x.y)
103                         //       ^^^^                match_span is the span of *x.y
104                         //
105                         // opt_match_place is None for let [mut] x = ... statements,
106                         // whether or not the right-hand side is a place expression
107                         if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
108                             VarBindingForm {
109                                 opt_match_place: Some((ref opt_match_place, match_span)),
110                                 binding_mode: _,
111                                 opt_ty_info: _,
112                                 pat_span: _,
113                             },
114                         ))) = local_decl.local_info {
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!(
153             "append_binding_error(match_place={:?}, match_span={:?})",
154             match_place, match_span
155         );
156
157         let from_simple_let = match_place.is_none();
158         let match_place = match_place.as_ref().unwrap_or(move_from);
159
160         match self.move_data.rev_lookup.find(match_place.as_ref()) {
161             // Error with the match place
162             LookupResult::Parent(_) => {
163                 for ge in &mut *grouped_errors {
164                     if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
165                         if match_span == *span {
166                             debug!("appending local({:?}) to list", bind_to);
167                             if !binds_to.is_empty() {
168                                 binds_to.push(bind_to);
169                             }
170                             return;
171                         }
172                     }
173                 }
174                 debug!("found a new move error location");
175
176                 // Don't need to point to x in let x = ... .
177                 let (binds_to, span) = if from_simple_let {
178                     (vec![], statement_span)
179                 } else {
180                     (vec![bind_to], match_span)
181                 };
182                 grouped_errors.push(GroupedMoveError::MovesFromPlace {
183                     span,
184                     move_from: match_place.clone(),
185                     original_path,
186                     kind,
187                     binds_to,
188                 });
189             }
190             // Error with the pattern
191             LookupResult::Exact(_) => {
192                 let mpi = match self.move_data.rev_lookup.find(move_from.as_ref()) {
193                     LookupResult::Parent(Some(mpi)) => mpi,
194                     // move_from should be a projection from match_place.
195                     _ => unreachable!("Probably not unreachable..."),
196                 };
197                 for ge in &mut *grouped_errors {
198                     if let GroupedMoveError::MovesFromValue {
199                         span,
200                         move_from: other_mpi,
201                         binds_to,
202                         ..
203                     } = ge
204                     {
205                         if match_span == *span && mpi == *other_mpi {
206                             debug!("appending local({:?}) to list", bind_to);
207                             binds_to.push(bind_to);
208                             return;
209                         }
210                     }
211                 }
212                 debug!("found a new move error location");
213                 grouped_errors.push(GroupedMoveError::MovesFromValue {
214                     span: match_span,
215                     move_from: mpi,
216                     original_path,
217                     kind,
218                     binds_to: vec![bind_to],
219                 });
220             }
221         };
222     }
223
224     fn report(&mut self, error: GroupedMoveError<'tcx>) {
225         let (mut err, err_span) = {
226             let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind<'_>) =
227                 match error {
228                     GroupedMoveError::MovesFromPlace { span, ref original_path, ref kind, .. } |
229                     GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } => {
230                         (span, original_path, kind)
231                     }
232                     GroupedMoveError::OtherIllegalMove {
233                         use_spans,
234                         ref original_path,
235                         ref kind
236                     } => {
237                         (use_spans.args_or_use(), original_path, kind)
238                     },
239                 };
240             debug!("report: original_path={:?} span={:?}, kind={:?} \
241                    original_path.is_upvar_field_projection={:?}", original_path, span, kind,
242                    self.is_upvar_field_projection(original_path.as_ref()));
243             (
244                 match kind {
245                     IllegalMoveOriginKind::Static => {
246                         unreachable!();
247                     }
248                     IllegalMoveOriginKind::BorrowedContent { target_place } => {
249                         self.report_cannot_move_from_borrowed_content(
250                             original_path,
251                             target_place,
252                             span,
253                         )
254                     }
255                     IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
256                         self.cannot_move_out_of_interior_of_drop(span, ty)
257                     }
258                     IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } =>
259                         self.cannot_move_out_of_interior_noncopy(
260                             span, ty, Some(*is_index),
261                         ),
262                 },
263                 span,
264             )
265         };
266
267         self.add_move_hints(error, &mut err, err_span);
268         err.buffer(&mut self.errors_buffer);
269     }
270
271     fn report_cannot_move_from_static(
272         &mut self,
273         place: &Place<'tcx>,
274         span: Span
275     ) -> DiagnosticBuilder<'a> {
276         let description = if place.projection.len() == 1 {
277             format!("static item `{}`", self.describe_place(place.as_ref()).unwrap())
278         } else {
279             let base_static = PlaceRef {
280                 base: &place.base,
281                 projection: &[ProjectionElem::Deref],
282             };
283
284             format!(
285                 "`{:?}` as `{:?}` is a static item",
286                 self.describe_place(place.as_ref()).unwrap(),
287                 self.describe_place(base_static).unwrap(),
288             )
289         };
290
291         self.cannot_move_out_of(span, &description)
292     }
293
294     fn report_cannot_move_from_borrowed_content(
295         &mut self,
296         move_place: &Place<'tcx>,
297         deref_target_place: &Place<'tcx>,
298         span: Span,
299     ) -> DiagnosticBuilder<'a> {
300         // Inspect the type of the content behind the
301         // borrow to provide feedback about why this
302         // was a move rather than a copy.
303         let ty = deref_target_place.ty(*self.body, self.infcx.tcx).ty;
304         let upvar_field = self.prefixes(move_place.as_ref(), PrefixSet::All)
305             .find_map(|p| self.is_upvar_field_projection(p));
306
307         let deref_base = match deref_target_place.projection.as_ref() {
308             &[ref proj_base @ .., ProjectionElem::Deref] => {
309                 PlaceRef {
310                     base: &deref_target_place.base,
311                     projection: &proj_base,
312                 }
313             }
314             _ => bug!("deref_target_place is not a deref projection"),
315         };
316
317         if let PlaceRef {
318             base: PlaceBase::Local(local),
319             projection: [],
320         } = deref_base {
321             let decl = &self.body.local_decls[*local];
322             if decl.is_ref_for_guard() {
323                 let mut err = self.cannot_move_out_of(
324                     span,
325                     &format!("`{}` in pattern guard", self.local_names[*local].unwrap()),
326                 );
327                 err.note(
328                     "variables bound in patterns cannot be moved from \
329                      until after the end of the pattern guard");
330                 return err;
331             } else if decl.is_ref_to_static() {
332                 return self.report_cannot_move_from_static(move_place, span);
333             }
334         }
335
336         debug!("report: ty={:?}", ty);
337         let mut err = match ty.kind {
338             ty::Array(..) | ty::Slice(..) =>
339                 self.cannot_move_out_of_interior_noncopy(span, ty, None),
340             ty::Closure(def_id, closure_substs)
341                 if def_id == self.mir_def_id && upvar_field.is_some()
342             => {
343                 let closure_kind_ty = closure_substs
344                     .as_closure().kind_ty(def_id, self.infcx.tcx);
345                 let closure_kind = closure_kind_ty.to_opt_closure_kind();
346                 let capture_description = match closure_kind {
347                     Some(ty::ClosureKind::Fn) => {
348                         "captured variable in an `Fn` closure"
349                     }
350                     Some(ty::ClosureKind::FnMut) => {
351                         "captured variable in an `FnMut` closure"
352                     }
353                     Some(ty::ClosureKind::FnOnce) => {
354                         bug!("closure kind does not match first argument type")
355                     }
356                     None => bug!("closure kind not inferred by borrowck"),
357                 };
358
359                 let upvar = &self.upvars[upvar_field.unwrap().index()];
360                 let upvar_hir_id = upvar.var_hir_id;
361                 let upvar_name = upvar.name;
362                 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
363
364                 let place_name = self.describe_place(move_place.as_ref()).unwrap();
365
366                 let place_description = if self
367                     .is_upvar_field_projection(move_place.as_ref())
368                     .is_some()
369                 {
370                     format!("`{}`, a {}", place_name, capture_description)
371                 } else {
372                     format!(
373                         "`{}`, as `{}` is a {}",
374                         place_name,
375                         upvar_name,
376                         capture_description,
377                     )
378                 };
379
380                 debug!(
381                     "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
382                     closure_kind_ty, closure_kind, place_description,
383                 );
384
385                 let mut diag = self.cannot_move_out_of(span, &place_description);
386
387                 diag.span_label(upvar_span, "captured outer variable");
388
389                 diag
390             }
391             _ => {
392                 let source = self.borrowed_content_source(deref_base);
393                 match (
394                     self.describe_place(move_place.as_ref()),
395                     source.describe_for_named_place(),
396                 ) {
397                     (Some(place_desc), Some(source_desc)) => {
398                         self.cannot_move_out_of(
399                             span,
400                             &format!("`{}` which is behind a {}", place_desc, source_desc),
401                         )
402                     }
403                     (_, _) => {
404                         self.cannot_move_out_of(
405                             span,
406                             &source.describe_for_unnamed_place(),
407                         )
408                     }
409                 }
410             },
411         };
412         let move_ty = format!(
413             "{:?}",
414             move_place.ty(*self.body, self.infcx.tcx).ty,
415         );
416         if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
417             let is_option = move_ty.starts_with("std::option::Option");
418             let is_result = move_ty.starts_with("std::result::Result");
419             if is_option || is_result {
420                 err.span_suggestion(
421                     span,
422                     &format!("consider borrowing the `{}`'s content", if is_option {
423                         "Option"
424                     } else {
425                         "Result"
426                     }),
427                     format!("{}.as_ref()", snippet),
428                     Applicability::MaybeIncorrect,
429                 );
430             }
431         }
432         err
433     }
434
435     fn add_move_hints(
436         &self,
437         error: GroupedMoveError<'tcx>,
438         err: &mut DiagnosticBuilder<'a>,
439         span: Span,
440     ) {
441         match error {
442             GroupedMoveError::MovesFromPlace {
443                 mut binds_to,
444                 move_from,
445                 ..
446             } => {
447                 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
448                     err.span_suggestion(
449                         span,
450                         "consider borrowing here",
451                         format!("&{}", snippet),
452                         Applicability::Unspecified,
453                     );
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 LocalInfo::User(
515                 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
516                     pat_span,
517                     ..
518                 }))
519             ) = bind_to.local_info {
520                 if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
521                 {
522                     if pat_snippet.starts_with('&') {
523                         let pat_snippet = pat_snippet[1..].trim_start();
524                         let suggestion;
525                         let to_remove;
526                         if pat_snippet.starts_with("mut")
527                             && pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
528                         {
529                             suggestion = pat_snippet["mut".len()..].trim_start();
530                             to_remove = "&mut";
531                         } else {
532                             suggestion = pat_snippet;
533                             to_remove = "&";
534                         }
535                         suggestions.push((
536                             pat_span,
537                             to_remove,
538                             suggestion.to_owned(),
539                         ));
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         for (j, local) in binds_to.into_iter().enumerate() {
562             let bind_to = &self.body.local_decls[*local];
563             let binding_span = bind_to.source_info.span;
564
565             if j == 0 {
566                 err.span_label(binding_span, "data moved here");
567             } else {
568                 err.span_label(binding_span, "...and here");
569             }
570
571             if binds_to.len() == 1 {
572                 self.note_type_does_not_implement_copy(
573                     err,
574                     &format!("`{}`", self.local_names[*local].unwrap()),
575                     bind_to.ty,
576                     Some(binding_span)
577                 );
578             }
579         }
580
581         if binds_to.len() > 1 {
582             err.note("move occurs because these variables have types that \
583                       don't implement the `Copy` trait",
584             );
585         }
586     }
587 }