]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/move_errors.rs
remove `_with_applicability` from suggestion fns
[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 borrow_check::MirBorrowckCtxt;
10 use borrow_check::prefixes::PrefixSet;
11 use dataflow::move_paths::{
12     IllegalMoveOrigin, IllegalMoveOriginKind, InitLocation,
13     LookupResult, MoveError, MovePathIndex,
14 };
15 use 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::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 {
246                         span,
247                         ref original_path,
248                         ref kind,
249                         ..
250                     } |
251                     GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } |
252                     GroupedMoveError::OtherIllegalMove { span, ref original_path, ref kind } => {
253                         (span, original_path, kind)
254                     },
255                 };
256             let origin = Origin::Mir;
257             debug!("report: original_path={:?} span={:?}, kind={:?} \
258                    original_path.is_upvar_field_projection={:?}", original_path, span, kind,
259                    original_path.is_upvar_field_projection(self.mir, &self.infcx.tcx));
260             (
261                 match kind {
262                     IllegalMoveOriginKind::Static => {
263                         self.infcx.tcx.cannot_move_out_of(span, "static item", origin)
264                     }
265                     IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
266                         // Inspect the type of the content behind the
267                         // borrow to provide feedback about why this
268                         // was a move rather than a copy.
269                         let ty = place.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
270                         let is_upvar_field_projection =
271                             self.prefixes(&original_path, PrefixSet::All)
272                             .any(|p| p.is_upvar_field_projection(self.mir, &self.infcx.tcx)
273                                  .is_some());
274                         debug!("report: ty={:?}", ty);
275                         match ty.sty {
276                             ty::Array(..) | ty::Slice(..) =>
277                                 self.infcx.tcx.cannot_move_out_of_interior_noncopy(
278                                     span, ty, None, origin
279                                 ),
280                             ty::Closure(def_id, closure_substs)
281                                 if !self.mir.upvar_decls.is_empty() && is_upvar_field_projection
282                             => {
283                                 let closure_kind_ty =
284                                     closure_substs.closure_kind_ty(def_id, self.infcx.tcx);
285                                 let closure_kind = closure_kind_ty.to_opt_closure_kind();
286                                 let place_description = match closure_kind {
287                                     Some(ty::ClosureKind::Fn) => {
288                                         "captured variable in an `Fn` closure"
289                                     }
290                                     Some(ty::ClosureKind::FnMut) => {
291                                         "captured variable in an `FnMut` closure"
292                                     }
293                                     Some(ty::ClosureKind::FnOnce) => {
294                                         bug!("closure kind does not match first argument type")
295                                     }
296                                     None => bug!("closure kind not inferred by borrowck"),
297                                 };
298                                 debug!("report: closure_kind_ty={:?} closure_kind={:?} \
299                                        place_description={:?}", closure_kind_ty, closure_kind,
300                                        place_description);
301
302                                 let mut diag = self.infcx.tcx.cannot_move_out_of(
303                                     span, place_description, origin);
304
305                                 for prefix in self.prefixes(&original_path, PrefixSet::All) {
306                                     if let Some(field) = prefix.is_upvar_field_projection(
307                                             self.mir, &self.infcx.tcx) {
308                                         let upvar_decl = &self.mir.upvar_decls[field.index()];
309                                         let upvar_hir_id =
310                                             upvar_decl.var_hir_id.assert_crate_local();
311                                         let upvar_node_id =
312                                             self.infcx.tcx.hir().hir_to_node_id(upvar_hir_id);
313                                         let upvar_span = self.infcx.tcx.hir().span(upvar_node_id);
314                                         diag.span_label(upvar_span, "captured outer variable");
315                                         break;
316                                     }
317                                 }
318
319                                 diag
320                             }
321                             _ => {
322                                 let source = self.borrowed_content_source(place);
323                                 self.infcx.tcx.cannot_move_out_of(
324                                     span, &source.to_string(), origin
325                                 )
326                             },
327                         }
328                     }
329                     IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
330                         self.infcx.tcx
331                             .cannot_move_out_of_interior_of_drop(span, ty, origin)
332                     }
333                     IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } =>
334                         self.infcx.tcx.cannot_move_out_of_interior_noncopy(
335                             span, ty, Some(*is_index), origin
336                         ),
337                 },
338                 span,
339             )
340         };
341
342         self.add_move_hints(error, &mut err, err_span);
343         err.buffer(&mut self.errors_buffer);
344     }
345
346     fn add_move_hints(
347         &self,
348         error: GroupedMoveError<'tcx>,
349         err: &mut DiagnosticBuilder<'a>,
350         span: Span,
351     ) {
352         let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
353         match error {
354             GroupedMoveError::MovesFromPlace {
355                 mut binds_to,
356                 move_from,
357                 ..
358             } => {
359                 let try_remove_deref = match move_from {
360                     Place::Projection(box PlaceProjection {
361                         elem: ProjectionElem::Deref,
362                         ..
363                     }) => true,
364                     _ => false,
365                 };
366                 if try_remove_deref && snippet.starts_with('*') {
367                     // The snippet doesn't start with `*` in (e.g.) index
368                     // expressions `a[b]`, which roughly desugar to
369                     // `*Index::index(&a, b)` or
370                     // `*IndexMut::index_mut(&mut a, b)`.
371                     err.span_suggestion(
372                         span,
373                         "consider removing the `*`",
374                         snippet[1..].to_owned(),
375                         Applicability::Unspecified,
376                     );
377                 } else {
378                     err.span_suggestion(
379                         span,
380                         "consider borrowing here",
381                         format!("&{}", snippet),
382                         Applicability::Unspecified,
383                     );
384                 }
385
386                 binds_to.sort();
387                 binds_to.dedup();
388                 self.add_move_error_details(err, &binds_to);
389             }
390             GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
391                 binds_to.sort();
392                 binds_to.dedup();
393                 self.add_move_error_suggestions(err, &binds_to);
394                 self.add_move_error_details(err, &binds_to);
395             }
396             // No binding. Nothing to suggest.
397             GroupedMoveError::OtherIllegalMove { .. } => (),
398         }
399     }
400
401     fn add_move_error_suggestions(
402         &self,
403         err: &mut DiagnosticBuilder<'a>,
404         binds_to: &[Local],
405     ) {
406         let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
407         for local in binds_to {
408             let bind_to = &self.mir.local_decls[*local];
409             if let Some(
410                 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
411                     pat_span,
412                     ..
413                 }))
414             ) = bind_to.is_user_variable {
415                 let pat_snippet = self.infcx.tcx.sess.source_map()
416                     .span_to_snippet(pat_span)
417                     .unwrap();
418                 if pat_snippet.starts_with('&') {
419                     let pat_snippet = pat_snippet[1..].trim_start();
420                     let suggestion;
421                     let to_remove;
422                     if pat_snippet.starts_with("mut")
423                         && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
424                     {
425                         suggestion = pat_snippet["mut".len()..].trim_start();
426                         to_remove = "&mut";
427                     } else {
428                         suggestion = pat_snippet;
429                         to_remove = "&";
430                     }
431                     suggestions.push((
432                         pat_span,
433                         to_remove,
434                         suggestion.to_owned(),
435                     ));
436                 }
437             }
438         }
439         suggestions.sort_unstable_by_key(|&(span, _, _)| span);
440         suggestions.dedup_by_key(|&mut (span, _, _)| span);
441         for (span, to_remove, suggestion) in suggestions {
442             err.span_suggestion(
443                 span,
444                 &format!("consider removing the `{}`", to_remove),
445                 suggestion,
446                 Applicability::MachineApplicable,
447             );
448         }
449     }
450
451     fn add_move_error_details(
452         &self,
453         err: &mut DiagnosticBuilder<'a>,
454         binds_to: &[Local],
455     ) {
456         let mut noncopy_var_spans = Vec::new();
457         for (j, local) in binds_to.into_iter().enumerate() {
458             let bind_to = &self.mir.local_decls[*local];
459             let binding_span = bind_to.source_info.span;
460
461             if j == 0 {
462                 err.span_label(binding_span, "data moved here");
463             } else {
464                 err.span_label(binding_span, "...and here");
465             }
466
467             if binds_to.len() == 1 {
468                 err.span_note(
469                     binding_span,
470                     &format!(
471                         "move occurs because `{}` has type `{}`, \
472                             which does not implement the `Copy` trait",
473                         bind_to.name.unwrap(),
474                         bind_to.ty
475                     ),
476                 );
477             } else {
478                 noncopy_var_spans.push(binding_span);
479             }
480         }
481
482         if binds_to.len() > 1 {
483             err.span_note(
484                 noncopy_var_spans,
485                 "move occurs because these variables have types that \
486                     don't implement the `Copy` trait",
487             );
488         }
489     }
490
491     fn borrowed_content_source(&self, place: &Place<'tcx>) -> BorrowedContentSource {
492         // Look up the provided place and work out the move path index for it,
493         // we'll use this to work back through where this value came from and check whether it
494         // was originally part of an `Rc` or `Arc`.
495         let initial_mpi = match self.move_data.rev_lookup.find(place) {
496             LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => mpi,
497             _ => return BorrowedContentSource::Other,
498         };
499
500         let mut queue = vec![initial_mpi];
501         let mut visited = Vec::new();
502         debug!("borrowed_content_source: queue={:?}", queue);
503         while let Some(mpi) = queue.pop() {
504             debug!(
505                 "borrowed_content_source: mpi={:?} queue={:?} visited={:?}",
506                 mpi, queue, visited
507             );
508
509             // Don't visit the same path twice.
510             if visited.contains(&mpi) {
511                 continue;
512             }
513             visited.push(mpi);
514
515             for i in &self.move_data.init_path_map[mpi] {
516                 let init = &self.move_data.inits[*i];
517                 debug!("borrowed_content_source: init={:?}", init);
518                 // We're only interested in statements that initialized a value, not the
519                 // initializations from arguments.
520                 let loc = match init.location {
521                     InitLocation::Statement(stmt) => stmt,
522                     _ => continue,
523                 };
524
525                 let bbd = &self.mir[loc.block];
526                 let is_terminator = bbd.statements.len() == loc.statement_index;
527                 debug!("borrowed_content_source: loc={:?} is_terminator={:?}", loc, is_terminator);
528                 if !is_terminator {
529                     let stmt = &bbd.statements[loc.statement_index];
530                     debug!("borrowed_content_source: stmt={:?}", stmt);
531                     // We're only interested in assignments (in particular, where the
532                     // assignment came from - was it an `Rc` or `Arc`?).
533                     if let StatementKind::Assign(_, box Rvalue::Ref(_, _, source)) = &stmt.kind {
534                         let ty = source.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
535                         let ty = match ty.sty {
536                             ty::TyKind::Ref(_, ty, _) => ty,
537                             _ => ty,
538                         };
539                         debug!("borrowed_content_source: ty={:?}", ty);
540
541                         if ty.is_arc() {
542                             return BorrowedContentSource::Arc;
543                         } else if ty.is_rc() {
544                             return BorrowedContentSource::Rc;
545                         } else {
546                             queue.push(init.path);
547                         }
548                     }
549                 } else if let Some(Terminator {
550                     kind: TerminatorKind::Call { args, .. },
551                     ..
552                 }) = &bbd.terminator {
553                     for arg in args {
554                         let source = match arg {
555                             Operand::Copy(place) | Operand::Move(place) => place,
556                             _ => continue,
557                         };
558
559                         let ty = source.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
560                         let ty = match ty.sty {
561                             ty::TyKind::Ref(_, ty, _) => ty,
562                             _ => ty,
563                         };
564                         debug!("borrowed_content_source: ty={:?}", ty);
565
566                         if ty.is_arc() {
567                             return BorrowedContentSource::Arc;
568                         } else if ty.is_rc() {
569                             return BorrowedContentSource::Rc;
570                         } else {
571                             queue.push(init.path);
572                         }
573                     }
574                 }
575             }
576         }
577
578         // If we didn't find an `Arc` or an `Rc`, then check specifically for
579         // a dereference of a place that has the type of a raw pointer.
580         // We can't use `place.ty(..).to_ty(..)` here as that strips away the raw pointer.
581         if let Place::Projection(box Projection {
582             base,
583             elem: ProjectionElem::Deref,
584         }) = place {
585             if base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx).is_unsafe_ptr() {
586                 return BorrowedContentSource::DerefRawPointer;
587             }
588         }
589
590         BorrowedContentSource::Other
591     }
592 }