]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/move_errors.rs
Rollup merge of #62685 - nathanwhit:as_ref_suggest_fix, r=estebank
[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::Base(PlaceBase::Local(local)),
95                     box Rvalue::Use(Operand::Move(move_from)),
96                 )) = self.body.basic_blocks()[location.block]
97                     .statements
98                     .get(location.statement_index)
99                     .map(|stmt| &stmt.kind)
100                 {
101                     let local_decl = &self.body.local_decls[*local];
102                     // opt_match_place is the
103                     // match_span is the span of the expression being matched on
104                     // match *x.y { ... }        match_place is Some(*x.y)
105                     //       ^^^^                match_span is the span of *x.y
106                     //
107                     // opt_match_place is None for let [mut] x = ... statements,
108                     // whether or not the right-hand side is a place expression
109                     if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
110                         opt_match_place: Some((ref opt_match_place, match_span)),
111                         binding_mode: _,
112                         opt_ty_info: _,
113                         pat_span: _,
114                     }))) = local_decl.is_user_variable
115                     {
116                         let stmt_source_info = self.body.source_info(location);
117                         self.append_binding_error(
118                             grouped_errors,
119                             kind,
120                             original_path,
121                             move_from,
122                             *local,
123                             opt_match_place,
124                             match_span,
125                             stmt_source_info.span,
126                         );
127                         return;
128                     }
129                 }
130
131                 let move_spans = self.move_spans(&original_path, 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) {
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) {
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));
243             (
244                 match kind {
245                     IllegalMoveOriginKind::Static => {
246                         self.report_cannot_move_from_static(original_path, span)
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 mut base_static = place;
277         loop {
278             match base_static {
279                 Place::Base(_) => break,
280                 Place::Projection(box Projection { base, .. }) => base_static = base,
281             }
282         }
283
284         let description = if let Place::Base(_) = place {
285             format!("static item `{}`", self.describe_place(place).unwrap())
286         } else {
287             format!(
288                 "`{:?}` as `{:?}` is a static item",
289                 self.describe_place(place).unwrap(),
290                 self.describe_place(base_static).unwrap(),
291             )
292         };
293
294         self.cannot_move_out_of(span, &description)
295     }
296
297     fn report_cannot_move_from_borrowed_content(
298         &mut self,
299         move_place: &Place<'tcx>,
300         deref_target_place: &Place<'tcx>,
301         span: Span,
302     ) -> DiagnosticBuilder<'a> {
303         // Inspect the type of the content behind the
304         // borrow to provide feedback about why this
305         // was a move rather than a copy.
306         let ty = deref_target_place.ty(self.body, self.infcx.tcx).ty;
307         let upvar_field = self.prefixes(&move_place, PrefixSet::All)
308             .find_map(|p| self.is_upvar_field_projection(p));
309
310         let deref_base = match deref_target_place {
311             Place::Projection(box Projection { base, elem: ProjectionElem::Deref }) => base,
312             _ => bug!("deref_target_place is not a deref projection"),
313         };
314
315         if let Place::Base(PlaceBase::Local(local)) = *deref_base {
316             let decl = &self.body.local_decls[local];
317             if decl.is_ref_for_guard() {
318                 let mut err = self.cannot_move_out_of(
319                     span,
320                     &format!("`{}` in pattern guard", decl.name.unwrap()),
321                 );
322                 err.note(
323                     "variables bound in patterns cannot be moved from \
324                      until after the end of the pattern guard");
325                 return err;
326             }
327         }
328
329         debug!("report: ty={:?}", ty);
330         let mut err = match ty.sty {
331             ty::Array(..) | ty::Slice(..) =>
332                 self.cannot_move_out_of_interior_noncopy(span, ty, None),
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.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) => {
340                         "captured variable in an `Fn` closure"
341                     }
342                     Some(ty::ClosureKind::FnMut) => {
343                         "captured variable in an `FnMut` closure"
344                     }
345                     Some(ty::ClosureKind::FnOnce) => {
346                         bug!("closure kind does not match first argument type")
347                     }
348                     None => bug!("closure kind not inferred by borrowck"),
349                 };
350
351                 let upvar = &self.upvars[upvar_field.unwrap().index()];
352                 let upvar_hir_id = upvar.var_hir_id;
353                 let upvar_name = upvar.name;
354                 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
355
356                 let place_name = self.describe_place(move_place).unwrap();
357
358                 let place_description = if self.is_upvar_field_projection(move_place).is_some() {
359                     format!("`{}`, a {}", place_name, capture_description)
360                 } else {
361                     format!(
362                         "`{}`, as `{}` is a {}",
363                         place_name,
364                         upvar_name,
365                         capture_description,
366                     )
367                 };
368
369                 debug!(
370                     "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
371                     closure_kind_ty, closure_kind, place_description,
372                 );
373
374                 let mut diag = self.cannot_move_out_of(span, &place_description);
375
376                 diag.span_label(upvar_span, "captured outer variable");
377
378                 diag
379             }
380             _ => {
381                 let source = self.borrowed_content_source(deref_base);
382                 match (self.describe_place(move_place), source.describe_for_named_place()) {
383                     (Some(place_desc), Some(source_desc)) => {
384                         self.cannot_move_out_of(
385                             span,
386                             &format!("`{}` which is behind a {}", place_desc, source_desc),
387                         )
388                     }
389                     (_, _) => {
390                         self.cannot_move_out_of(
391                             span,
392                             &source.describe_for_unnamed_place(),
393                         )
394                     }
395                 }
396             },
397         };
398         let move_ty = format!(
399             "{:?}",
400             move_place.ty(self.body, self.infcx.tcx).ty,
401         );
402         let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
403         let is_option = move_ty.starts_with("std::option::Option");
404         let is_result = move_ty.starts_with("std::result::Result");
405         if  is_option || is_result {
406             err.span_suggestion(
407                 span,
408                 &format!("consider borrowing the `{}`'s content", if is_option {
409                     "Option"
410                 } else {
411                     "Result"
412                 }),
413                 format!("{}.as_ref()", snippet),
414                 Applicability::MaybeIncorrect,
415             );
416         }
417         err
418     }
419
420     fn add_move_hints(
421         &self,
422         error: GroupedMoveError<'tcx>,
423         err: &mut DiagnosticBuilder<'a>,
424         span: Span,
425     ) {
426         let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
427         match error {
428             GroupedMoveError::MovesFromPlace {
429                 mut binds_to,
430                 move_from,
431                 ..
432             } => {
433                 err.span_suggestion(
434                     span,
435                     "consider borrowing here",
436                     format!("&{}", snippet),
437                     Applicability::Unspecified,
438                 );
439
440                 if binds_to.is_empty() {
441                     let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
442                     let place_desc = match self.describe_place(&move_from) {
443                         Some(desc) => format!("`{}`", desc),
444                         None => format!("value"),
445                     };
446
447                     self.note_type_does_not_implement_copy(
448                         err,
449                         &place_desc,
450                         place_ty,
451                         Some(span)
452                     );
453                 } else {
454                     binds_to.sort();
455                     binds_to.dedup();
456
457                     self.add_move_error_details(err, &binds_to);
458                 }
459             }
460             GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
461                 binds_to.sort();
462                 binds_to.dedup();
463                 self.add_move_error_suggestions(err, &binds_to);
464                 self.add_move_error_details(err, &binds_to);
465             }
466             // No binding. Nothing to suggest.
467             GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
468                 let span = use_spans.var_or_use();
469                 let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
470                 let place_desc = match self.describe_place(original_path) {
471                     Some(desc) => format!("`{}`", desc),
472                     None => format!("value"),
473                 };
474                 self.note_type_does_not_implement_copy(
475                     err,
476                     &place_desc,
477                     place_ty,
478                     Some(span),
479                 );
480
481                 use_spans.args_span_label(err, format!("move out of {} occurs here", place_desc));
482                 use_spans.var_span_label(
483                     err,
484                     format!("move occurs due to use{}", use_spans.describe()),
485                 );
486             },
487         }
488     }
489
490     fn add_move_error_suggestions(
491         &self,
492         err: &mut DiagnosticBuilder<'a>,
493         binds_to: &[Local],
494     ) {
495         let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
496         for local in binds_to {
497             let bind_to = &self.body.local_decls[*local];
498             if let Some(
499                 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
500                     pat_span,
501                     ..
502                 }))
503             ) = bind_to.is_user_variable {
504                 let pat_snippet = self.infcx.tcx.sess.source_map()
505                     .span_to_snippet(pat_span)
506                     .unwrap();
507                 if pat_snippet.starts_with('&') {
508                     let pat_snippet = pat_snippet[1..].trim_start();
509                     let suggestion;
510                     let to_remove;
511                     if pat_snippet.starts_with("mut")
512                         && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
513                     {
514                         suggestion = pat_snippet["mut".len()..].trim_start();
515                         to_remove = "&mut";
516                     } else {
517                         suggestion = pat_snippet;
518                         to_remove = "&";
519                     }
520                     suggestions.push((
521                         pat_span,
522                         to_remove,
523                         suggestion.to_owned(),
524                     ));
525                 }
526             }
527         }
528         suggestions.sort_unstable_by_key(|&(span, _, _)| span);
529         suggestions.dedup_by_key(|&mut (span, _, _)| span);
530         for (span, to_remove, suggestion) in suggestions {
531             err.span_suggestion(
532                 span,
533                 &format!("consider removing the `{}`", to_remove),
534                 suggestion,
535                 Applicability::MachineApplicable,
536             );
537         }
538     }
539
540     fn add_move_error_details(
541         &self,
542         err: &mut DiagnosticBuilder<'a>,
543         binds_to: &[Local],
544     ) {
545         let mut noncopy_var_spans = Vec::new();
546         for (j, local) in binds_to.into_iter().enumerate() {
547             let bind_to = &self.body.local_decls[*local];
548             let binding_span = bind_to.source_info.span;
549
550             if j == 0 {
551                 err.span_label(binding_span, "data moved here");
552             } else {
553                 err.span_label(binding_span, "...and here");
554             }
555
556             if binds_to.len() == 1 {
557                 self.note_type_does_not_implement_copy(
558                     err,
559                     &format!("`{}`", bind_to.name.unwrap()),
560                     bind_to.ty,
561                     Some(binding_span)
562                 );
563             } else {
564                 noncopy_var_spans.push(binding_span);
565             }
566         }
567
568         if binds_to.len() > 1 {
569             err.span_note(
570                 noncopy_var_spans,
571                 "move occurs because these variables have types that \
572                     don't implement the `Copy` trait",
573             );
574         }
575     }
576 }