]> git.proxmox.com Git - rustc.git/blob - src/librustc_mir/borrow_check/move_errors.rs
New upstream version 1.29.0+dfsg1
[rustc.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(&mut 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 // 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::Local(local),
96 Rvalue::Use(Operand::Move(move_from)),
97 )) = self.mir.basic_blocks()[location.block]
98 .statements
99 .get(location.statement_index)
100 .map(|stmt| &stmt.kind)
101 {
102 let local_decl = &self.mir.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 }))) = local_decl.is_user_variable
115 {
116 self.append_binding_error(
117 grouped_errors,
118 kind,
119 move_from,
120 *local,
121 opt_match_place,
122 match_span,
123 stmt_source_info.span,
124 );
125 return;
126 }
127 }
128 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
129 span: stmt_source_info.span,
130 kind,
131 });
132 }
133 }
134 }
135
136 fn append_binding_error(
137 &self,
138 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
139 kind: IllegalMoveOriginKind<'tcx>,
140 move_from: &Place<'tcx>,
141 bind_to: Local,
142 match_place: &Option<Place<'tcx>>,
143 match_span: Span,
144 statement_span: Span,
145 ) {
146 debug!(
147 "append_to_grouped_errors(match_place={:?}, match_span={:?})",
148 match_place, match_span
149 );
150
151 let from_simple_let = match_place.is_none();
152 let match_place = match_place.as_ref().unwrap_or(move_from);
153
154 match self.move_data.rev_lookup.find(match_place) {
155 // Error with the match place
156 LookupResult::Parent(_) => {
157 for ge in &mut *grouped_errors {
158 if let GroupedMoveError::MovesFromMatchPlace { span, binds_to, .. } = ge {
159 if match_span == *span {
160 debug!("appending local({:?}) to list", bind_to);
161 if !binds_to.is_empty() {
162 binds_to.push(bind_to);
163 }
164 return;
165 }
166 }
167 }
168 debug!("found a new move error location");
169
170 // Don't need to point to x in let x = ... .
171 let (binds_to, span) = if from_simple_let {
172 (vec![], statement_span)
173 } else {
174 (vec![bind_to], match_span)
175 };
176 grouped_errors.push(GroupedMoveError::MovesFromMatchPlace {
177 span,
178 move_from: match_place.clone(),
179 kind,
180 binds_to,
181 });
182 }
183 // Error with the pattern
184 LookupResult::Exact(_) => {
185 let mpi = match self.move_data.rev_lookup.find(move_from) {
186 LookupResult::Parent(Some(mpi)) => mpi,
187 // move_from should be a projection from match_place.
188 _ => unreachable!("Probably not unreachable..."),
189 };
190 for ge in &mut *grouped_errors {
191 if let GroupedMoveError::MovesFromPattern {
192 span,
193 move_from: other_mpi,
194 binds_to,
195 ..
196 } = ge
197 {
198 if match_span == *span && mpi == *other_mpi {
199 debug!("appending local({:?}) to list", bind_to);
200 binds_to.push(bind_to);
201 return;
202 }
203 }
204 }
205 debug!("found a new move error location");
206 grouped_errors.push(GroupedMoveError::MovesFromPattern {
207 span: match_span,
208 move_from: mpi,
209 kind,
210 binds_to: vec![bind_to],
211 });
212 }
213 };
214 }
215
216 fn report(&mut self, error: GroupedMoveError<'tcx>) {
217 let (mut err, err_span) = {
218 let (span, kind): (Span, &IllegalMoveOriginKind) = match error {
219 GroupedMoveError::MovesFromMatchPlace { span, ref kind, .. }
220 | GroupedMoveError::MovesFromPattern { span, ref kind, .. }
221 | GroupedMoveError::OtherIllegalMove { span, ref kind } => (span, kind),
222 };
223 let origin = Origin::Mir;
224 (
225 match kind {
226 IllegalMoveOriginKind::Static => {
227 self.tcx.cannot_move_out_of(span, "static item", origin)
228 }
229 IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
230 // Inspect the type of the content behind the
231 // borrow to provide feedback about why this
232 // was a move rather than a copy.
233 let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
234 match ty.sty {
235 ty::TyArray(..) | ty::TySlice(..) => self
236 .tcx
237 .cannot_move_out_of_interior_noncopy(span, ty, None, origin),
238 ty::TyClosure(def_id, closure_substs)
239 if !self.mir.upvar_decls.is_empty()
240 && {
241 match place {
242 Place::Projection(ref proj) => {
243 proj.base == Place::Local(Local::new(1))
244 }
245 Place::Promoted(_) |
246 Place::Local(_) | Place::Static(_) => unreachable!(),
247 }
248 } =>
249 {
250 let closure_kind_ty =
251 closure_substs.closure_kind_ty(def_id, self.tcx);
252 let closure_kind = closure_kind_ty.to_opt_closure_kind();
253 let place_description = match closure_kind {
254 Some(ty::ClosureKind::Fn) => {
255 "captured variable in an `Fn` closure"
256 }
257 Some(ty::ClosureKind::FnMut) => {
258 "captured variable in an `FnMut` closure"
259 }
260 Some(ty::ClosureKind::FnOnce) => {
261 bug!("closure kind does not match first argument type")
262 }
263 None => bug!("closure kind not inferred by borrowck"),
264 };
265 self.tcx.cannot_move_out_of(span, place_description, origin)
266 }
267 _ => self
268 .tcx
269 .cannot_move_out_of(span, "borrowed content", origin),
270 }
271 }
272 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
273 self.tcx
274 .cannot_move_out_of_interior_of_drop(span, ty, origin)
275 }
276 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self
277 .tcx
278 .cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index), origin),
279 },
280 span,
281 )
282 };
283
284 self.add_move_hints(error, &mut err, err_span);
285 err.buffer(&mut self.errors_buffer);
286 }
287
288 fn add_move_hints(
289 &self,
290 error: GroupedMoveError<'tcx>,
291 err: &mut DiagnosticBuilder<'a>,
292 span: Span,
293 ) {
294 match error {
295 GroupedMoveError::MovesFromMatchPlace {
296 mut binds_to,
297 move_from,
298 ..
299 } => {
300 // Ok to suggest a borrow, since the target can't be moved from
301 // anyway.
302 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
303 match move_from {
304 Place::Projection(ref proj)
305 if self.suitable_to_remove_deref(proj, &snippet) =>
306 {
307 err.span_suggestion(
308 span,
309 "consider removing this dereference operator",
310 (&snippet[1..]).to_owned(),
311 );
312 }
313 _ => {
314 err.span_suggestion(
315 span,
316 "consider using a reference instead",
317 format!("&{}", snippet),
318 );
319 }
320 }
321
322 binds_to.sort();
323 binds_to.dedup();
324 for local in binds_to {
325 let bind_to = &self.mir.local_decls[local];
326 let binding_span = bind_to.source_info.span;
327 err.span_label(
328 binding_span,
329 format!(
330 "move occurs because {} has type `{}`, \
331 which does not implement the `Copy` trait",
332 bind_to.name.unwrap(),
333 bind_to.ty
334 ),
335 );
336 }
337 }
338 }
339 GroupedMoveError::MovesFromPattern { mut binds_to, .. } => {
340 // Suggest ref, since there might be a move in
341 // another match arm
342 binds_to.sort();
343 binds_to.dedup();
344 for local in binds_to {
345 let bind_to = &self.mir.local_decls[local];
346 let binding_span = bind_to.source_info.span;
347
348 // Suggest ref mut when the user has already written mut.
349 let ref_kind = match bind_to.mutability {
350 Mutability::Not => "ref",
351 Mutability::Mut => "ref mut",
352 };
353 match bind_to.name {
354 Some(name) => {
355 err.span_suggestion(
356 binding_span,
357 "to prevent move, use ref or ref mut",
358 format!("{} {:?}", ref_kind, name),
359 );
360 }
361 None => {
362 err.span_label(
363 span,
364 format!("Local {:?} is not suitable for ref", bind_to),
365 );
366 }
367 }
368 }
369 }
370 // Nothing to suggest.
371 GroupedMoveError::OtherIllegalMove { .. } => (),
372 }
373 }
374
375 fn suitable_to_remove_deref(&self, proj: &PlaceProjection<'tcx>, snippet: &str) -> bool {
376 let is_shared_ref = |ty: ty::Ty| match ty.sty {
377 ty::TypeVariants::TyRef(.., hir::Mutability::MutImmutable) => true,
378 _ => false,
379 };
380
381 proj.elem == ProjectionElem::Deref && snippet.starts_with('*') && match proj.base {
382 Place::Local(local) => {
383 let local_decl = &self.mir.local_decls[local];
384 // If this is a temporary, then this could be from an
385 // overloaded * operator.
386 local_decl.is_user_variable.is_some() && is_shared_ref(local_decl.ty)
387 }
388 Place::Promoted(_) => true,
389 Place::Static(ref st) => is_shared_ref(st.ty),
390 Place::Projection(ref proj) => match proj.elem {
391 ProjectionElem::Field(_, ty) => is_shared_ref(ty),
392 _ => false,
393 },
394 }
395 }
396 }