]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/move_errors.rs
Rollup merge of #61220 - imbrem:error_explanations, r=estebank
[rust.git] / src / librustc_mir / borrow_check / move_errors.rs
1 use core::unicode::property::Pattern_White_Space;
2 use std::fmt::{self, Display};
3
4 use rustc::mir::*;
5 use rustc::ty;
6 use rustc_errors::{DiagnosticBuilder,Applicability};
7 use syntax_pos::Span;
8
9 use crate::borrow_check::MirBorrowckCtxt;
10 use crate::borrow_check::prefixes::PrefixSet;
11 use crate::dataflow::move_paths::{
12     IllegalMoveOrigin, IllegalMoveOriginKind, InitLocation,
13     LookupResult, MoveError, MovePathIndex,
14 };
15 use crate::util::borrowck_errors::{BorrowckErrors, Origin};
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         span: Span,
54         kind: IllegalMoveOriginKind<'tcx>,
55     },
56 }
57
58 enum BorrowedContentSource {
59     Arc,
60     Rc,
61     DerefRawPointer,
62     Other,
63 }
64
65 impl Display for BorrowedContentSource {
66     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67         match *self {
68             BorrowedContentSource::Arc => write!(f, "an `Arc`"),
69             BorrowedContentSource::Rc => write!(f, "an `Rc`"),
70             BorrowedContentSource::DerefRawPointer => write!(f, "dereference of raw pointer"),
71             BorrowedContentSource::Other => write!(f, "borrowed content"),
72         }
73     }
74 }
75
76 impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
77     pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
78         let grouped_errors = self.group_move_errors(move_errors);
79         for error in grouped_errors {
80             self.report(error);
81         }
82     }
83
84     fn group_move_errors(
85         &self,
86         errors: Vec<(Place<'tcx>, MoveError<'tcx>)>
87     ) -> Vec<GroupedMoveError<'tcx>> {
88         let mut grouped_errors = Vec::new();
89         for (original_path, error) in errors {
90             self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
91         }
92         grouped_errors
93     }
94
95     fn append_to_grouped_errors(
96         &self,
97         grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
98         original_path: Place<'tcx>,
99         error: MoveError<'tcx>,
100     ) {
101         match error {
102             MoveError::UnionMove { .. } => {
103                 unimplemented!("don't know how to report union move errors yet.")
104             }
105             MoveError::IllegalMove {
106                 cannot_move_out_of: IllegalMoveOrigin { location, kind },
107             } => {
108                 let stmt_source_info = self.mir.source_info(location);
109                 // Note: that the only time we assign a place isn't a temporary
110                 // to a user variable is when initializing it.
111                 // If that ever stops being the case, then the ever initialized
112                 // flow could be used.
113                 if let Some(StatementKind::Assign(
114                     Place::Base(PlaceBase::Local(local)),
115                     box Rvalue::Use(Operand::Move(move_from)),
116                 )) = self.mir.basic_blocks()[location.block]
117                     .statements
118                     .get(location.statement_index)
119                     .map(|stmt| &stmt.kind)
120                 {
121                     let local_decl = &self.mir.local_decls[*local];
122                     // opt_match_place is the
123                     // match_span is the span of the expression being matched on
124                     // match *x.y { ... }        match_place is Some(*x.y)
125                     //       ^^^^                match_span is the span of *x.y
126                     //
127                     // opt_match_place is None for let [mut] x = ... statements,
128                     // whether or not the right-hand side is a place expression
129                     if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
130                         opt_match_place: Some((ref opt_match_place, match_span)),
131                         binding_mode: _,
132                         opt_ty_info: _,
133                         pat_span: _,
134                     }))) = local_decl.is_user_variable
135                     {
136                         self.append_binding_error(
137                             grouped_errors,
138                             kind,
139                             original_path,
140                             move_from,
141                             *local,
142                             opt_match_place,
143                             match_span,
144                             stmt_source_info.span,
145                         );
146                         return;
147                     }
148                 }
149                 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
150                     span: stmt_source_info.span,
151                     original_path,
152                     kind,
153                 });
154             }
155         }
156     }
157
158     fn append_binding_error(
159         &self,
160         grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
161         kind: IllegalMoveOriginKind<'tcx>,
162         original_path: Place<'tcx>,
163         move_from: &Place<'tcx>,
164         bind_to: Local,
165         match_place: &Option<Place<'tcx>>,
166         match_span: Span,
167         statement_span: Span,
168     ) {
169         debug!(
170             "append_binding_error(match_place={:?}, match_span={:?})",
171             match_place, match_span
172         );
173
174         let from_simple_let = match_place.is_none();
175         let match_place = match_place.as_ref().unwrap_or(move_from);
176
177         match self.move_data.rev_lookup.find(match_place) {
178             // Error with the match place
179             LookupResult::Parent(_) => {
180                 for ge in &mut *grouped_errors {
181                     if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
182                         if match_span == *span {
183                             debug!("appending local({:?}) to list", bind_to);
184                             if !binds_to.is_empty() {
185                                 binds_to.push(bind_to);
186                             }
187                             return;
188                         }
189                     }
190                 }
191                 debug!("found a new move error location");
192
193                 // Don't need to point to x in let x = ... .
194                 let (binds_to, span) = if from_simple_let {
195                     (vec![], statement_span)
196                 } else {
197                     (vec![bind_to], match_span)
198                 };
199                 grouped_errors.push(GroupedMoveError::MovesFromPlace {
200                     span,
201                     move_from: match_place.clone(),
202                     original_path,
203                     kind,
204                     binds_to,
205                 });
206             }
207             // Error with the pattern
208             LookupResult::Exact(_) => {
209                 let mpi = match self.move_data.rev_lookup.find(move_from) {
210                     LookupResult::Parent(Some(mpi)) => mpi,
211                     // move_from should be a projection from match_place.
212                     _ => unreachable!("Probably not unreachable..."),
213                 };
214                 for ge in &mut *grouped_errors {
215                     if let GroupedMoveError::MovesFromValue {
216                         span,
217                         move_from: other_mpi,
218                         binds_to,
219                         ..
220                     } = ge
221                     {
222                         if match_span == *span && mpi == *other_mpi {
223                             debug!("appending local({:?}) to list", bind_to);
224                             binds_to.push(bind_to);
225                             return;
226                         }
227                     }
228                 }
229                 debug!("found a new move error location");
230                 grouped_errors.push(GroupedMoveError::MovesFromValue {
231                     span: match_span,
232                     move_from: mpi,
233                     original_path,
234                     kind,
235                     binds_to: vec![bind_to],
236                 });
237             }
238         };
239     }
240
241     fn report(&mut self, error: GroupedMoveError<'tcx>) {
242         let (mut err, err_span) = {
243             let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind<'_>) =
244                 match error {
245                     GroupedMoveError::MovesFromPlace { span, ref original_path, ref kind, .. } |
246                     GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } |
247                     GroupedMoveError::OtherIllegalMove { span, ref original_path, ref kind } => {
248                         (span, original_path, kind)
249                     },
250                 };
251             let origin = Origin::Mir;
252             debug!("report: original_path={:?} span={:?}, kind={:?} \
253                    original_path.is_upvar_field_projection={:?}", original_path, span, kind,
254                    self.is_upvar_field_projection(original_path));
255             let err = match kind {
256                 IllegalMoveOriginKind::Static => {
257                     self.infcx.tcx.cannot_move_out_of(span, "static item", origin)
258                 }
259                 IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
260                     // Inspect the type of the content behind the
261                     // borrow to provide feedback about why this
262                     // was a move rather than a copy.
263                     let ty = place.ty(self.mir, self.infcx.tcx).ty;
264                     let is_upvar_field_projection =
265                         self.prefixes(&original_path, PrefixSet::All)
266                         .any(|p| self.is_upvar_field_projection(p).is_some());
267                     debug!("report: ty={:?}", ty);
268                     let mut err = match ty.sty {
269                         ty::Array(..) | ty::Slice(..) =>
270                             self.infcx.tcx.cannot_move_out_of_interior_noncopy(
271                                 span, ty, None, origin
272                             ),
273                         ty::Closure(def_id, closure_substs)
274                             if def_id == self.mir_def_id && is_upvar_field_projection
275                         => {
276                             let closure_kind_ty =
277                                 closure_substs.closure_kind_ty(def_id, self.infcx.tcx);
278                             let closure_kind = closure_kind_ty.to_opt_closure_kind();
279                             let place_description = match closure_kind {
280                                 Some(ty::ClosureKind::Fn) => {
281                                     "captured variable in an `Fn` closure"
282                                 }
283                                 Some(ty::ClosureKind::FnMut) => {
284                                     "captured variable in an `FnMut` closure"
285                                 }
286                                 Some(ty::ClosureKind::FnOnce) => {
287                                     bug!("closure kind does not match first argument type")
288                                 }
289                                 None => bug!("closure kind not inferred by borrowck"),
290                             };
291                             debug!("report: closure_kind_ty={:?} closure_kind={:?} \
292                                     place_description={:?}", closure_kind_ty, closure_kind,
293                                     place_description);
294
295                             let mut diag = self.infcx.tcx.cannot_move_out_of(
296                                 span, place_description, origin);
297
298                             for prefix in self.prefixes(&original_path, PrefixSet::All) {
299                                 if let Some(field) = self.is_upvar_field_projection(prefix) {
300                                     let upvar_hir_id = self.upvars[field.index()].var_hir_id;
301                                     let upvar_span = self.infcx.tcx.hir().span_by_hir_id(
302                                         upvar_hir_id);
303                                     diag.span_label(upvar_span, "captured outer variable");
304                                     break;
305                                 }
306                             }
307
308                             diag
309                         }
310                         _ => {
311                             let source = self.borrowed_content_source(place);
312                             self.infcx.tcx.cannot_move_out_of(
313                                 span, &source.to_string(), origin
314                             )
315                         },
316                     };
317                     let orig_path_ty = format!(
318                         "{:?}",
319                         original_path.ty(self.mir, self.infcx.tcx).ty,
320                     );
321                     let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
322                     let is_option = orig_path_ty.starts_with("std::option::Option");
323                     let is_result = orig_path_ty.starts_with("std::result::Result");
324                     if  is_option || is_result {
325                         err.span_suggestion(
326                             span,
327                             &format!("consider borrowing the `{}`'s content", if is_option {
328                                 "Option"
329                             } else {
330                                 "Result"
331                             }),
332                             format!("{}.as_ref()", snippet),
333                             Applicability::MaybeIncorrect,
334                         );
335                     }
336                     err
337                 }
338                 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
339                     self.infcx.tcx
340                         .cannot_move_out_of_interior_of_drop(span, ty, origin)
341                 }
342                 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } =>
343                     self.infcx.tcx.cannot_move_out_of_interior_noncopy(
344                         span, ty, Some(*is_index), origin
345                     ),
346             };
347             (err, span)
348         };
349
350         self.add_move_hints(error, &mut err, err_span);
351         err.buffer(&mut self.errors_buffer);
352     }
353
354     fn add_move_hints(
355         &self,
356         error: GroupedMoveError<'tcx>,
357         err: &mut DiagnosticBuilder<'a>,
358         span: Span,
359     ) {
360         let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
361         match error {
362             GroupedMoveError::MovesFromPlace {
363                 mut binds_to,
364                 move_from,
365                 ..
366             } => {
367                 let try_remove_deref = match move_from {
368                     Place::Projection(box Projection {
369                         elem: ProjectionElem::Deref,
370                         ..
371                     }) => true,
372                     _ => false,
373                 };
374                 if try_remove_deref && snippet.starts_with('*') {
375                     // The snippet doesn't start with `*` in (e.g.) index
376                     // expressions `a[b]`, which roughly desugar to
377                     // `*Index::index(&a, b)` or
378                     // `*IndexMut::index_mut(&mut a, b)`.
379                     err.span_suggestion(
380                         span,
381                         "consider removing the `*`",
382                         snippet[1..].to_owned(),
383                         Applicability::Unspecified,
384                     );
385                 } else {
386                     err.span_suggestion(
387                         span,
388                         "consider borrowing here",
389                         format!("&{}", snippet),
390                         Applicability::Unspecified,
391                     );
392                 }
393
394                 binds_to.sort();
395                 binds_to.dedup();
396                 self.add_move_error_details(err, &binds_to);
397             }
398             GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
399                 binds_to.sort();
400                 binds_to.dedup();
401                 self.add_move_error_suggestions(err, &binds_to);
402                 self.add_move_error_details(err, &binds_to);
403             }
404             // No binding. Nothing to suggest.
405             GroupedMoveError::OtherIllegalMove { .. } => (),
406         }
407     }
408
409     fn add_move_error_suggestions(
410         &self,
411         err: &mut DiagnosticBuilder<'a>,
412         binds_to: &[Local],
413     ) {
414         let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
415         for local in binds_to {
416             let bind_to = &self.mir.local_decls[*local];
417             if let Some(
418                 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
419                     pat_span,
420                     ..
421                 }))
422             ) = bind_to.is_user_variable {
423                 let pat_snippet = self.infcx.tcx.sess.source_map()
424                     .span_to_snippet(pat_span)
425                     .unwrap();
426                 if pat_snippet.starts_with('&') {
427                     let pat_snippet = pat_snippet[1..].trim_start();
428                     let suggestion;
429                     let to_remove;
430                     if pat_snippet.starts_with("mut")
431                         && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
432                     {
433                         suggestion = pat_snippet["mut".len()..].trim_start();
434                         to_remove = "&mut";
435                     } else {
436                         suggestion = pat_snippet;
437                         to_remove = "&";
438                     }
439                     suggestions.push((
440                         pat_span,
441                         to_remove,
442                         suggestion.to_owned(),
443                     ));
444                 }
445             }
446         }
447         suggestions.sort_unstable_by_key(|&(span, _, _)| span);
448         suggestions.dedup_by_key(|&mut (span, _, _)| span);
449         for (span, to_remove, suggestion) in suggestions {
450             err.span_suggestion(
451                 span,
452                 &format!("consider removing the `{}`", to_remove),
453                 suggestion,
454                 Applicability::MachineApplicable,
455             );
456         }
457     }
458
459     fn add_move_error_details(
460         &self,
461         err: &mut DiagnosticBuilder<'a>,
462         binds_to: &[Local],
463     ) {
464         let mut noncopy_var_spans = Vec::new();
465         for (j, local) in binds_to.into_iter().enumerate() {
466             let bind_to = &self.mir.local_decls[*local];
467             let binding_span = bind_to.source_info.span;
468
469             if j == 0 {
470                 err.span_label(binding_span, "data moved here");
471             } else {
472                 err.span_label(binding_span, "...and here");
473             }
474
475             if binds_to.len() == 1 {
476                 err.span_note(
477                     binding_span,
478                     &format!(
479                         "move occurs because `{}` has type `{}`, \
480                             which does not implement the `Copy` trait",
481                         bind_to.name.unwrap(),
482                         bind_to.ty
483                     ),
484                 );
485             } else {
486                 noncopy_var_spans.push(binding_span);
487             }
488         }
489
490         if binds_to.len() > 1 {
491             err.span_note(
492                 noncopy_var_spans,
493                 "move occurs because these variables have types that \
494                     don't implement the `Copy` trait",
495             );
496         }
497     }
498
499     fn borrowed_content_source(&self, place: &Place<'tcx>) -> BorrowedContentSource {
500         // Look up the provided place and work out the move path index for it,
501         // we'll use this to work back through where this value came from and check whether it
502         // was originally part of an `Rc` or `Arc`.
503         let initial_mpi = match self.move_data.rev_lookup.find(place) {
504             LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => mpi,
505             _ => return BorrowedContentSource::Other,
506         };
507
508         let mut queue = vec![initial_mpi];
509         let mut visited = Vec::new();
510         debug!("borrowed_content_source: queue={:?}", queue);
511         while let Some(mpi) = queue.pop() {
512             debug!(
513                 "borrowed_content_source: mpi={:?} queue={:?} visited={:?}",
514                 mpi, queue, visited
515             );
516
517             // Don't visit the same path twice.
518             if visited.contains(&mpi) {
519                 continue;
520             }
521             visited.push(mpi);
522
523             for i in &self.move_data.init_path_map[mpi] {
524                 let init = &self.move_data.inits[*i];
525                 debug!("borrowed_content_source: init={:?}", init);
526                 // We're only interested in statements that initialized a value, not the
527                 // initializations from arguments.
528                 let loc = match init.location {
529                     InitLocation::Statement(stmt) => stmt,
530                     _ => continue,
531                 };
532
533                 let bbd = &self.mir[loc.block];
534                 let is_terminator = bbd.statements.len() == loc.statement_index;
535                 debug!("borrowed_content_source: loc={:?} is_terminator={:?}", loc, is_terminator);
536                 if !is_terminator {
537                     let stmt = &bbd.statements[loc.statement_index];
538                     debug!("borrowed_content_source: stmt={:?}", stmt);
539                     // We're only interested in assignments (in particular, where the
540                     // assignment came from - was it an `Rc` or `Arc`?).
541                     if let StatementKind::Assign(_, box Rvalue::Ref(_, _, source)) = &stmt.kind {
542                         let ty = source.ty(self.mir, self.infcx.tcx).ty;
543                         let ty = match ty.sty {
544                             ty::Ref(_, ty, _) => ty,
545                             _ => ty,
546                         };
547                         debug!("borrowed_content_source: ty={:?}", ty);
548
549                         if ty.is_arc() {
550                             return BorrowedContentSource::Arc;
551                         } else if ty.is_rc() {
552                             return BorrowedContentSource::Rc;
553                         } else {
554                             queue.push(init.path);
555                         }
556                     }
557                 } else if let Some(Terminator {
558                     kind: TerminatorKind::Call { args, .. },
559                     ..
560                 }) = &bbd.terminator {
561                     for arg in args {
562                         let source = match arg {
563                             Operand::Copy(place) | Operand::Move(place) => place,
564                             _ => continue,
565                         };
566
567                         let ty = source.ty(self.mir, self.infcx.tcx).ty;
568                         let ty = match ty.sty {
569                             ty::Ref(_, ty, _) => ty,
570                             _ => ty,
571                         };
572                         debug!("borrowed_content_source: ty={:?}", ty);
573
574                         if ty.is_arc() {
575                             return BorrowedContentSource::Arc;
576                         } else if ty.is_rc() {
577                             return BorrowedContentSource::Rc;
578                         } else {
579                             queue.push(init.path);
580                         }
581                     }
582                 }
583             }
584         }
585
586         // If we didn't find an `Arc` or an `Rc`, then check specifically for
587         // a dereference of a place that has the type of a raw pointer.
588         // We can't use `place.ty(..).to_ty(..)` here as that strips away the raw pointer.
589         if let Place::Projection(box Projection {
590             base,
591             elem: ProjectionElem::Deref,
592         }) = place {
593             if base.ty(self.mir, self.infcx.tcx).ty.is_unsafe_ptr() {
594                 return BorrowedContentSource::DerefRawPointer;
595             }
596         }
597
598         BorrowedContentSource::Other
599     }
600 }