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