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