]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/move_errors.rs
Promoteds are statics and statics have a place, not just a value
[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 rustc::hir;
12 use rustc::mir::*;
13 use rustc::ty;
14 use rustc_data_structures::indexed_vec::Idx;
15 use rustc_errors::DiagnosticBuilder;
16 use syntax_pos::Span;
17
18 use borrow_check::MirBorrowckCtxt;
19 use dataflow::move_paths::{IllegalMoveOrigin, IllegalMoveOriginKind};
20 use dataflow::move_paths::{LookupResult, MoveError, MovePathIndex};
21 use util::borrowck_errors::{BorrowckErrors, Origin};
22
23 // Often when desugaring a pattern match we may have many individual moves in
24 // MIR that are all part of one operation from the user's point-of-view. For
25 // example:
26 //
27 // let (x, y) = foo()
28 //
29 // would move x from the 0 field of some temporary, and y from the 1 field. We
30 // group such errors together for cleaner error reporting.
31 //
32 // Errors are kept separate if they are from places with different parent move
33 // paths. For example, this generates two errors:
34 //
35 // let (&x, &y) = (&String::new(), &String::new());
36 #[derive(Debug)]
37 enum GroupedMoveError<'tcx> {
38     // Match place can't be moved from
39     // e.g. match x[0] { s => (), } where x: &[String]
40     MovesFromMatchPlace {
41         span: Span,
42         move_from: Place<'tcx>,
43         kind: IllegalMoveOriginKind<'tcx>,
44         binds_to: Vec<Local>,
45     },
46     // Part of a pattern can't be moved from,
47     // e.g. match &String::new() { &x => (), }
48     MovesFromPattern {
49         span: Span,
50         move_from: MovePathIndex,
51         kind: IllegalMoveOriginKind<'tcx>,
52         binds_to: Vec<Local>,
53     },
54     // Everything that isn't from pattern matching.
55     OtherIllegalMove {
56         span: Span,
57         kind: IllegalMoveOriginKind<'tcx>,
58     },
59 }
60
61 impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
62     pub(crate) fn report_move_errors(&self, move_errors: Vec<MoveError<'tcx>>) {
63         let grouped_errors = self.group_move_errors(move_errors);
64         for error in grouped_errors {
65             self.report(error);
66         }
67     }
68
69     fn group_move_errors(&self, errors: Vec<MoveError<'tcx>>) -> Vec<GroupedMoveError<'tcx>> {
70         let mut grouped_errors = Vec::new();
71         for error in errors {
72             self.append_to_grouped_errors(&mut grouped_errors, error);
73         }
74         grouped_errors
75     }
76
77     fn append_to_grouped_errors(
78         &self,
79         grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
80         error: MoveError<'tcx>,
81     ) {
82         match error {
83             MoveError::UnionMove { .. } => {
84                 unimplemented!("don't know how to report union move errors yet.")
85             }
86             MoveError::IllegalMove {
87                 cannot_move_out_of: IllegalMoveOrigin { location, kind },
88             } => {
89                 let stmt_source_info = self.mir.source_info(location);
90                 if let Some(StatementKind::Assign(
91                     Place::Local(local),
92                     Rvalue::Use(Operand::Move(move_from)),
93                 )) = self.mir.basic_blocks()[location.block]
94                     .statements
95                     .get(location.statement_index)
96                     .map(|stmt| &stmt.kind)
97                 {
98                     let local_decl = &self.mir.local_decls[*local];
99                     // opt_match_place is the
100                     // match_span is the span of the expression being matched on
101                     // match *x.y { ... }        match_place is Some(*x.y)
102                     //       ^^^^                match_span is the span of *x.y
103                     //
104                     // opt_match_place is None for let [mut] x = ... statements,
105                     // whether or not the right-hand side is a place expression
106                     if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
107                         opt_match_place: Some((ref opt_match_place, match_span)),
108                         binding_mode: _,
109                         opt_ty_info: _,
110                     }))) = local_decl.is_user_variable
111                     {
112                         // HACK use scopes to determine if this assignment is
113                         // the initialization of a variable.
114                         // FIXME(matthewjasper) This would probably be more
115                         // reliable if it used the ever initialized dataflow
116                         // but move errors are currently reported before the
117                         // rest of borrowck has run.
118                         if self
119                             .mir
120                             .is_sub_scope(local_decl.source_info.scope, stmt_source_info.scope)
121                         {
122                             self.append_binding_error(
123                                 grouped_errors,
124                                 kind,
125                                 move_from,
126                                 *local,
127                                 opt_match_place,
128                                 match_span,
129                             );
130                             return;
131                         }
132                     }
133                 }
134                 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
135                     span: stmt_source_info.span,
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         move_from: &Place<'tcx>,
147         bind_to: Local,
148         match_place: &Option<Place<'tcx>>,
149         match_span: Span,
150     ) {
151         debug!(
152             "append_to_grouped_errors(match_place={:?}, match_span={:?})",
153             match_place, match_span
154         );
155
156         let from_simple_let = match_place.is_none();
157         let match_place = match_place.as_ref().unwrap_or(move_from);
158
159         match self.move_data.rev_lookup.find(match_place) {
160             // Error with the match place
161             LookupResult::Parent(_) => {
162                 for ge in &mut *grouped_errors {
163                     if let GroupedMoveError::MovesFromMatchPlace { span, binds_to, .. } = ge {
164                         if match_span == *span {
165                             debug!("appending local({:?}) to list", bind_to);
166                             if !binds_to.is_empty() {
167                                 binds_to.push(bind_to);
168                             }
169                             return;
170                         }
171                     }
172                 }
173                 debug!("found a new move error location");
174
175                 // Don't need to point to x in let x = ... .
176                 let binds_to = if from_simple_let {
177                     vec![]
178                 } else {
179                     vec![bind_to]
180                 };
181                 grouped_errors.push(GroupedMoveError::MovesFromMatchPlace {
182                     span: match_span,
183                     move_from: match_place.clone(),
184                     kind,
185                     binds_to,
186                 });
187             }
188             // Error with the pattern
189             LookupResult::Exact(_) => {
190                 let mpi = match self.move_data.rev_lookup.find(move_from) {
191                     LookupResult::Parent(Some(mpi)) => mpi,
192                     // move_from should be a projection from match_place.
193                     _ => unreachable!("Probably not unreachable..."),
194                 };
195                 for ge in &mut *grouped_errors {
196                     if let GroupedMoveError::MovesFromPattern {
197                         span,
198                         move_from: other_mpi,
199                         binds_to,
200                         ..
201                     } = ge
202                     {
203                         if match_span == *span && mpi == *other_mpi {
204                             debug!("appending local({:?}) to list", bind_to);
205                             binds_to.push(bind_to);
206                             return;
207                         }
208                     }
209                 }
210                 debug!("found a new move error location");
211                 grouped_errors.push(GroupedMoveError::MovesFromPattern {
212                     span: match_span,
213                     move_from: mpi,
214                     kind,
215                     binds_to: vec![bind_to],
216                 });
217             }
218         };
219     }
220
221     fn report(&self, error: GroupedMoveError<'tcx>) {
222         let (mut err, err_span) = {
223             let (span, kind): (Span, &IllegalMoveOriginKind) = match error {
224                 GroupedMoveError::MovesFromMatchPlace { span, ref kind, .. }
225                 | GroupedMoveError::MovesFromPattern { span, ref kind, .. }
226                 | GroupedMoveError::OtherIllegalMove { span, ref kind } => (span, kind),
227             };
228             let origin = Origin::Mir;
229             (
230                 match kind {
231                     IllegalMoveOriginKind::Static => {
232                         self.tcx.cannot_move_out_of(span, "static item", origin)
233                     }
234                     IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
235                         // Inspect the type of the content behind the
236                         // borrow to provide feedback about why this
237                         // was a move rather than a copy.
238                         let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
239                         match ty.sty {
240                             ty::TyArray(..) | ty::TySlice(..) => self
241                                 .tcx
242                                 .cannot_move_out_of_interior_noncopy(span, ty, None, origin),
243                             ty::TyClosure(def_id, closure_substs)
244                                 if !self.mir.upvar_decls.is_empty()
245                                     && {
246                                         match place {
247                                             Place::Projection(ref proj) => {
248                                                 proj.base == Place::Local(Local::new(1))
249                                             }
250                                             Place::Local(_) | Place::Static(_) => unreachable!(),
251                                         }
252                                     } =>
253                             {
254                                 let closure_kind_ty =
255                                     closure_substs.closure_kind_ty(def_id, self.tcx);
256                                 let closure_kind = closure_kind_ty.to_opt_closure_kind();
257                                 let place_description = match closure_kind {
258                                     Some(ty::ClosureKind::Fn) => {
259                                         "captured variable in an `Fn` closure"
260                                     }
261                                     Some(ty::ClosureKind::FnMut) => {
262                                         "captured variable in an `FnMut` closure"
263                                     }
264                                     Some(ty::ClosureKind::FnOnce) => {
265                                         bug!("closure kind does not match first argument type")
266                                     }
267                                     None => bug!("closure kind not inferred by borrowck"),
268                                 };
269                                 self.tcx.cannot_move_out_of(span, place_description, origin)
270                             }
271                             _ => self
272                                 .tcx
273                                 .cannot_move_out_of(span, "borrowed content", origin),
274                         }
275                     }
276                     IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
277                         self.tcx
278                             .cannot_move_out_of_interior_of_drop(span, ty, origin)
279                     }
280                     IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self
281                         .tcx
282                         .cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index), origin),
283                 },
284                 span,
285             )
286         };
287
288         self.add_move_hints(error, &mut err, err_span);
289         err.emit();
290     }
291
292     fn add_move_hints(
293         &self,
294         error: GroupedMoveError<'tcx>,
295         err: &mut DiagnosticBuilder<'a>,
296         span: Span,
297     ) {
298         match error {
299             GroupedMoveError::MovesFromMatchPlace {
300                 mut binds_to,
301                 move_from,
302                 ..
303             } => {
304                 // Ok to suggest a borrow, since the target can't be moved from
305                 // anyway.
306                 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
307                     match move_from {
308                         Place::Projection(ref proj)
309                             if self.suitable_to_remove_deref(proj, &snippet) =>
310                         {
311                             err.span_suggestion(
312                                 span,
313                                 "consider removing this dereference operator",
314                                 format!("{}", &snippet[1..]),
315                             );
316                         }
317                         _ => {
318                             err.span_suggestion(
319                                 span,
320                                 "consider using a reference instead",
321                                 format!("&{}", snippet),
322                             );
323                         }
324                     }
325
326                     binds_to.sort();
327                     binds_to.dedup();
328                     for local in binds_to {
329                         let bind_to = &self.mir.local_decls[local];
330                         let binding_span = bind_to.source_info.span;
331                         err.span_label(
332                             binding_span,
333                             format!(
334                                 "move occurs because {} has type `{}`, \
335                                  which does not implement the `Copy` trait",
336                                 bind_to.name.unwrap(),
337                                 bind_to.ty
338                             ),
339                         );
340                     }
341                 }
342             }
343             GroupedMoveError::MovesFromPattern { mut binds_to, .. } => {
344                 // Suggest ref, since there might be a move in
345                 // another match arm
346                 binds_to.sort();
347                 binds_to.dedup();
348                 for local in binds_to {
349                     let bind_to = &self.mir.local_decls[local];
350                     let binding_span = bind_to.source_info.span;
351
352                     // Suggest ref mut when the user has already written mut.
353                     let ref_kind = match bind_to.mutability {
354                         Mutability::Not => "ref",
355                         Mutability::Mut => "ref mut",
356                     };
357                     match bind_to.name {
358                         Some(name) => {
359                             err.span_suggestion(
360                                 binding_span,
361                                 "to prevent move, use ref or ref mut",
362                                 format!("{} {:?}", ref_kind, name),
363                             );
364                         }
365                         None => {
366                             err.span_label(
367                                 span,
368                                 format!("Local {:?} is not suitable for ref", bind_to),
369                             );
370                         }
371                     }
372                 }
373             }
374             // Nothing to suggest.
375             GroupedMoveError::OtherIllegalMove { .. } => (),
376         }
377     }
378
379     fn suitable_to_remove_deref(&self, proj: &PlaceProjection<'tcx>, snippet: &str) -> bool {
380         let is_shared_ref = |ty: ty::Ty| match ty.sty {
381             ty::TypeVariants::TyRef(.., hir::Mutability::MutImmutable) => true,
382             _ => false,
383         };
384
385         proj.elem == ProjectionElem::Deref && snippet.starts_with('*') && match proj.base {
386             Place::Local(local) => {
387                 let local_decl = &self.mir.local_decls[local];
388                 // If this is a temporary, then this could be from an
389                 // overloaded * operator.
390                 local_decl.is_user_variable.is_some() && is_shared_ref(local_decl.ty)
391             }
392             Place::Promoted(_) => true,
393             Place::Static(ref st) => is_shared_ref(st.ty),
394             Place::Projection(ref proj) => match proj.elem {
395                 ProjectionElem::Field(_, ty) => is_shared_ref(ty),
396                 _ => false,
397             },
398         }
399     }
400 }