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