]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/move_errors.rs
2dcdf1d9e456da3cbce23c0dae5dd550a3c1dcc9
[rust.git] / src / librustc_mir / borrow_check / move_errors.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use core::unicode::property::Pattern_White_Space;
12 use rustc::mir::*;
13 use rustc::ty;
14 use rustc_errors::DiagnosticBuilder;
15 use rustc_data_structures::indexed_vec::Idx;
16 use syntax_pos::Span;
17
18 use borrow_check::MirBorrowckCtxt;
19 use borrow_check::prefixes::PrefixSet;
20 use dataflow::move_paths::{IllegalMoveOrigin, IllegalMoveOriginKind};
21 use dataflow::move_paths::{LookupResult, MoveError, MovePathIndex};
22 use util::borrowck_errors::{BorrowckErrors, Origin};
23
24 // Often when desugaring a pattern match we may have many individual moves in
25 // MIR that are all part of one operation from the user's point-of-view. For
26 // example:
27 //
28 // let (x, y) = foo()
29 //
30 // would move x from the 0 field of some temporary, and y from the 1 field. We
31 // group such errors together for cleaner error reporting.
32 //
33 // Errors are kept separate if they are from places with different parent move
34 // paths. For example, this generates two errors:
35 //
36 // let (&x, &y) = (&String::new(), &String::new());
37 #[derive(Debug)]
38 enum GroupedMoveError<'tcx> {
39     // Place expression can't be moved from,
40     // e.g. match x[0] { s => (), } where x: &[String]
41     MovesFromPlace {
42         original_path: Place<'tcx>,
43         span: Span,
44         move_from: Place<'tcx>,
45         kind: IllegalMoveOriginKind<'tcx>,
46         binds_to: Vec<Local>,
47     },
48     // Part of a value expression can't be moved from,
49     // e.g. match &String::new() { &x => (), }
50     MovesFromValue {
51         original_path: Place<'tcx>,
52         span: Span,
53         move_from: MovePathIndex,
54         kind: IllegalMoveOriginKind<'tcx>,
55         binds_to: Vec<Local>,
56     },
57     // Everything that isn't from pattern matching.
58     OtherIllegalMove {
59         original_path: Place<'tcx>,
60         span: Span,
61         kind: IllegalMoveOriginKind<'tcx>,
62     },
63 }
64
65 impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
66     pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
67         let grouped_errors = self.group_move_errors(move_errors);
68         for error in grouped_errors {
69             self.report(error);
70         }
71     }
72
73     fn group_move_errors(
74         &self,
75         errors: Vec<(Place<'tcx>, MoveError<'tcx>)>
76     ) -> Vec<GroupedMoveError<'tcx>> {
77         let mut grouped_errors = Vec::new();
78         for (original_path, error) in errors {
79             self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
80         }
81         grouped_errors
82     }
83
84     fn append_to_grouped_errors(
85         &self,
86         grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
87         original_path: Place<'tcx>,
88         error: MoveError<'tcx>,
89     ) {
90         match error {
91             MoveError::UnionMove { .. } => {
92                 unimplemented!("don't know how to report union move errors yet.")
93             }
94             MoveError::IllegalMove {
95                 cannot_move_out_of: IllegalMoveOrigin { location, kind },
96             } => {
97                 let stmt_source_info = self.mir.source_info(location);
98                 // Note: that the only time we assign a place isn't a temporary
99                 // to a user variable is when initializing it.
100                 // If that ever stops being the case, then the ever initialized
101                 // flow could be used.
102                 if let Some(StatementKind::Assign(
103                     Place::Local(local),
104                     Rvalue::Use(Operand::Move(move_from)),
105                 )) = self.mir.basic_blocks()[location.block]
106                     .statements
107                     .get(location.statement_index)
108                     .map(|stmt| &stmt.kind)
109                 {
110                     let local_decl = &self.mir.local_decls[*local];
111                     // opt_match_place is the
112                     // match_span is the span of the expression being matched on
113                     // match *x.y { ... }        match_place is Some(*x.y)
114                     //       ^^^^                match_span is the span of *x.y
115                     //
116                     // opt_match_place is None for let [mut] x = ... statements,
117                     // whether or not the right-hand side is a place expression
118                     if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
119                         opt_match_place: Some((ref opt_match_place, match_span)),
120                         binding_mode: _,
121                         opt_ty_info: _,
122                         pat_span: _,
123                     }))) = local_decl.is_user_variable
124                     {
125                         self.append_binding_error(
126                             grouped_errors,
127                             kind,
128                             original_path,
129                             move_from,
130                             *local,
131                             opt_match_place,
132                             match_span,
133                             stmt_source_info.span,
134                         );
135                         return;
136                     }
137                 }
138                 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
139                     span: stmt_source_info.span,
140                     original_path,
141                     kind,
142                 });
143             }
144         }
145     }
146
147     fn append_binding_error(
148         &self,
149         grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
150         kind: IllegalMoveOriginKind<'tcx>,
151         original_path: Place<'tcx>,
152         move_from: &Place<'tcx>,
153         bind_to: Local,
154         match_place: &Option<Place<'tcx>>,
155         match_span: Span,
156         statement_span: Span,
157     ) {
158         debug!(
159             "append_binding_error(match_place={:?}, match_span={:?})",
160             match_place, match_span
161         );
162
163         let from_simple_let = match_place.is_none();
164         let match_place = match_place.as_ref().unwrap_or(move_from);
165
166         match self.move_data.rev_lookup.find(match_place) {
167             // Error with the match place
168             LookupResult::Parent(_) => {
169                 for ge in &mut *grouped_errors {
170                     if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
171                         if match_span == *span {
172                             debug!("appending local({:?}) to list", bind_to);
173                             if !binds_to.is_empty() {
174                                 binds_to.push(bind_to);
175                             }
176                             return;
177                         }
178                     }
179                 }
180                 debug!("found a new move error location");
181
182                 // Don't need to point to x in let x = ... .
183                 let (binds_to, span) = if from_simple_let {
184                     (vec![], statement_span)
185                 } else {
186                     (vec![bind_to], match_span)
187                 };
188                 grouped_errors.push(GroupedMoveError::MovesFromPlace {
189                     span,
190                     move_from: match_place.clone(),
191                     original_path,
192                     kind,
193                     binds_to,
194                 });
195             }
196             // Error with the pattern
197             LookupResult::Exact(_) => {
198                 let mpi = match self.move_data.rev_lookup.find(move_from) {
199                     LookupResult::Parent(Some(mpi)) => mpi,
200                     // move_from should be a projection from match_place.
201                     _ => unreachable!("Probably not unreachable..."),
202                 };
203                 for ge in &mut *grouped_errors {
204                     if let GroupedMoveError::MovesFromValue {
205                         span,
206                         move_from: other_mpi,
207                         binds_to,
208                         ..
209                     } = ge
210                     {
211                         if match_span == *span && mpi == *other_mpi {
212                             debug!("appending local({:?}) to list", bind_to);
213                             binds_to.push(bind_to);
214                             return;
215                         }
216                     }
217                 }
218                 debug!("found a new move error location");
219                 grouped_errors.push(GroupedMoveError::MovesFromValue {
220                     span: match_span,
221                     move_from: mpi,
222                     original_path,
223                     kind,
224                     binds_to: vec![bind_to],
225                 });
226             }
227         };
228     }
229
230     fn report(&mut self, error: GroupedMoveError<'tcx>) {
231         let (mut err, err_span) = {
232             let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind) =
233                 match error {
234                     GroupedMoveError::MovesFromPlace {
235                         span,
236                         ref original_path,
237                         ref kind,
238                         ..
239                     } |
240                     GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } |
241                     GroupedMoveError::OtherIllegalMove { span, ref original_path, ref kind } => {
242                         (span, original_path, kind)
243                     },
244                 };
245             let origin = Origin::Mir;
246             debug!("report: original_path={:?} span={:?}, kind={:?} \
247                    original_path.is_upvar_field_projection={:?}", original_path, span, kind,
248                    original_path.is_upvar_field_projection(self.mir, &self.tcx));
249             (
250                 match kind {
251                     IllegalMoveOriginKind::Static => {
252                         self.tcx.cannot_move_out_of(span, "static item", origin)
253                     }
254                     IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
255                         // Inspect the type of the content behind the
256                         // borrow to provide feedback about why this
257                         // was a move rather than a copy.
258                         let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
259                         let is_upvar_field_projection =
260                             self.prefixes(&original_path, PrefixSet::All)
261                             .any(|p| p.is_upvar_field_projection(self.mir, &self.tcx)
262                                  .is_some());
263                         match ty.sty {
264                             ty::TyArray(..) | ty::TySlice(..) => self
265                                 .tcx
266                                 .cannot_move_out_of_interior_noncopy(span, ty, None, origin),
267                             ty::TyClosure(def_id, closure_substs)
268                                 if !self.mir.upvar_decls.is_empty() && is_upvar_field_projection
269                             => {
270                                 let closure_kind_ty =
271                                     closure_substs.closure_kind_ty(def_id, self.tcx);
272                                 let closure_kind = closure_kind_ty.to_opt_closure_kind();
273                                 let place_description = match closure_kind {
274                                     Some(ty::ClosureKind::Fn) => {
275                                         "captured variable in an `Fn` closure"
276                                     }
277                                     Some(ty::ClosureKind::FnMut) => {
278                                         "captured variable in an `FnMut` closure"
279                                     }
280                                     Some(ty::ClosureKind::FnOnce) => {
281                                         bug!("closure kind does not match first argument type")
282                                     }
283                                     None => bug!("closure kind not inferred by borrowck"),
284                                 };
285                                 debug!("report: closure_kind_ty={:?} closure_kind={:?} \
286                                        place_description={:?}", closure_kind_ty, closure_kind,
287                                        place_description);
288
289                                 let mut diag = self.tcx.cannot_move_out_of(
290                                     span, place_description, origin);
291
292                                 for prefix in self.prefixes(&original_path, PrefixSet::All) {
293                                     if let Some(field) = prefix.is_upvar_field_projection(
294                                             self.mir, &self.tcx) {
295                                         let upvar_decl = &self.mir.upvar_decls[field.index()];
296                                         let upvar_hir_id =
297                                             upvar_decl.var_hir_id.assert_crate_local();
298                                         let upvar_node_id =
299                                             self.tcx.hir.hir_to_node_id(upvar_hir_id);
300                                         let upvar_span = self.tcx.hir.span(upvar_node_id);
301                                         diag.span_label(upvar_span, "captured outer variable");
302                                         break;
303                                     }
304                                 }
305
306                                 diag
307                             }
308                             _ => self
309                                 .tcx
310                                 .cannot_move_out_of(span, "borrowed content", origin),
311                         }
312                     }
313                     IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
314                         self.tcx
315                             .cannot_move_out_of_interior_of_drop(span, ty, origin)
316                     }
317                     IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self
318                         .tcx
319                         .cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index), origin),
320                 },
321                 span,
322             )
323         };
324
325         self.add_move_hints(error, &mut err, err_span);
326         err.buffer(&mut self.errors_buffer);
327     }
328
329     fn add_move_hints(
330         &self,
331         error: GroupedMoveError<'tcx>,
332         err: &mut DiagnosticBuilder<'a>,
333         span: Span,
334     ) {
335         let snippet = self.tcx.sess.codemap().span_to_snippet(span).unwrap();
336         match error {
337             GroupedMoveError::MovesFromPlace {
338                 mut binds_to,
339                 move_from,
340                 ..
341             } => {
342                 let try_remove_deref = match move_from {
343                     Place::Projection(box PlaceProjection {
344                         elem: ProjectionElem::Deref,
345                         ..
346                     }) => true,
347                     _ => false,
348                 };
349                 if try_remove_deref && snippet.starts_with('*') {
350                     // This is false for (e.g.) index expressions `a[b]`,
351                     // which roughly desugar to `*Index::index(&a, b)` or
352                     // `*IndexMut::index_mut(&mut a, b)`.
353                     err.span_suggestion(
354                         span,
355                         "consider removing the `*`",
356                         snippet[1..].to_owned(),
357                     );
358                 } else {
359                     err.span_suggestion(
360                         span,
361                         "consider borrowing here",
362                         format!("&{}", snippet),
363                     );
364                 }
365
366                 binds_to.sort();
367                 binds_to.dedup();
368                 self.add_move_error_labels(err, &binds_to);
369             }
370             GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
371                 binds_to.sort();
372                 binds_to.dedup();
373                 self.add_move_error_suggestions(err, &binds_to);
374                 self.add_move_error_labels(err, &binds_to);
375             }
376             // No binding. Nothing to suggest.
377             GroupedMoveError::OtherIllegalMove { .. } => (),
378         }
379     }
380
381     fn add_move_error_suggestions(
382         &self,
383         err: &mut DiagnosticBuilder<'a>,
384         binds_to: &[Local],
385     ) {
386         let mut suggestions: Vec<(Span, String, String)> = Vec::new();
387         for local in binds_to {
388             let bind_to = &self.mir.local_decls[*local];
389             if let Some(
390                 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
391                     pat_span,
392                     ..
393                 }))
394             ) = bind_to.is_user_variable {
395                 let pat_snippet = self
396                     .tcx.sess.codemap()
397                     .span_to_snippet(pat_span)
398                     .unwrap();
399                 if pat_snippet.starts_with('&') {
400                     let pat_snippet = pat_snippet[1..].trim_left();
401                     let suggestion;
402                     let to_remove;
403                     if pat_snippet.starts_with("mut")
404                         && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
405                     {
406                         suggestion = pat_snippet["mut".len()..].trim_left();
407                         to_remove = "&mut";
408                     } else {
409                         suggestion = pat_snippet;
410                         to_remove = "&";
411                     }
412                     suggestions.push((
413                         pat_span,
414                         format!("consider removing the `{}`", to_remove),
415                         suggestion.to_owned(),
416                     ));
417                 }
418             }
419         }
420         suggestions.sort_unstable_by_key(|&(span, _, _)| span);
421         suggestions.dedup_by_key(|&mut (span, _, _)| span);
422         for (span, msg, suggestion) in suggestions {
423             err.span_suggestion(span, &msg, suggestion);
424         }
425     }
426
427     fn add_move_error_labels(
428         &self,
429         err: &mut DiagnosticBuilder<'a>,
430         binds_to: &[Local],
431     ) {
432         let mut noncopy_var_spans = Vec::new();
433         for (j, local) in binds_to.into_iter().enumerate() {
434             let bind_to = &self.mir.local_decls[*local];
435             let binding_span = bind_to.source_info.span;
436
437             if j == 0 {
438                 err.span_label(binding_span, format!("data moved here"));
439             } else {
440                 err.span_label(binding_span, format!("... and here"));
441             }
442
443             if binds_to.len() == 1 {
444                 err.span_note(
445                     binding_span,
446                     &format!(
447                         "move occurs because `{}` has type `{}`, \
448                             which does not implement the `Copy` trait",
449                         bind_to.name.unwrap(),
450                         bind_to.ty
451                     ),
452                 );
453             } else {
454                 noncopy_var_spans.push(binding_span);
455             }
456         }
457
458         if binds_to.len() > 1 {
459             err.span_note(
460                 noncopy_var_spans,
461                 "move occurs because these variables have types that \
462                     don't implement the `Copy` trait",
463             );
464         }
465     }
466 }