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.
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.
11 use core::unicode::property::Pattern_White_Space;
14 use rustc_errors::DiagnosticBuilder;
15 use rustc_data_structures::indexed_vec::Idx;
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};
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
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.
33 // Errors are kept separate if they are from places with different parent move
34 // paths. For example, this generates two errors:
36 // let (&x, &y) = (&String::new(), &String::new());
38 enum GroupedMoveError<'tcx> {
39 // Place expression can't be moved from,
40 // e.g. match x[0] { s => (), } where x: &[String]
42 original_path: Place<'tcx>,
44 move_from: Place<'tcx>,
45 kind: IllegalMoveOriginKind<'tcx>,
48 // Part of a value expression can't be moved from,
49 // e.g. match &String::new() { &x => (), }
51 original_path: Place<'tcx>,
53 move_from: MovePathIndex,
54 kind: IllegalMoveOriginKind<'tcx>,
57 // Everything that isn't from pattern matching.
59 original_path: Place<'tcx>,
61 kind: IllegalMoveOriginKind<'tcx>,
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 {
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);
84 fn append_to_grouped_errors(
86 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
87 original_path: Place<'tcx>,
88 error: MoveError<'tcx>,
91 MoveError::UnionMove { .. } => {
92 unimplemented!("don't know how to report union move errors yet.")
94 MoveError::IllegalMove {
95 cannot_move_out_of: IllegalMoveOrigin { location, kind },
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(
104 Rvalue::Use(Operand::Move(move_from)),
105 )) = self.mir.basic_blocks()[location.block]
107 .get(location.statement_index)
108 .map(|stmt| &stmt.kind)
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
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)),
123 }))) = local_decl.is_user_variable
125 self.append_binding_error(
133 stmt_source_info.span,
138 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
139 span: stmt_source_info.span,
147 fn append_binding_error(
149 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
150 kind: IllegalMoveOriginKind<'tcx>,
151 original_path: Place<'tcx>,
152 move_from: &Place<'tcx>,
154 match_place: &Option<Place<'tcx>>,
156 statement_span: Span,
159 "append_binding_error(match_place={:?}, match_span={:?})",
160 match_place, match_span
163 let from_simple_let = match_place.is_none();
164 let match_place = match_place.as_ref().unwrap_or(move_from);
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);
180 debug!("found a new move error location");
182 // Don't need to point to x in let x = ... .
183 let (binds_to, span) = if from_simple_let {
184 (vec![], statement_span)
186 (vec![bind_to], match_span)
188 grouped_errors.push(GroupedMoveError::MovesFromPlace {
190 move_from: match_place.clone(),
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..."),
203 for ge in &mut *grouped_errors {
204 if let GroupedMoveError::MovesFromValue {
206 move_from: other_mpi,
211 if match_span == *span && mpi == *other_mpi {
212 debug!("appending local({:?}) to list", bind_to);
213 binds_to.push(bind_to);
218 debug!("found a new move error location");
219 grouped_errors.push(GroupedMoveError::MovesFromValue {
224 binds_to: vec![bind_to],
230 fn report(&mut self, error: GroupedMoveError<'tcx>) {
231 let (mut err, err_span) = {
232 let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind) =
234 GroupedMoveError::MovesFromPlace {
240 GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } |
241 GroupedMoveError::OtherIllegalMove { span, ref original_path, ref kind } => {
242 (span, original_path, kind)
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));
251 IllegalMoveOriginKind::Static => {
252 self.tcx.cannot_move_out_of(span, "static item", origin)
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)
264 ty::TyArray(..) | ty::TySlice(..) => self
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
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"
277 Some(ty::ClosureKind::FnMut) => {
278 "captured variable in an `FnMut` closure"
280 Some(ty::ClosureKind::FnOnce) => {
281 bug!("closure kind does not match first argument type")
283 None => bug!("closure kind not inferred by borrowck"),
285 debug!("report: closure_kind_ty={:?} closure_kind={:?} \
286 place_description={:?}", closure_kind_ty, closure_kind,
289 let mut diag = self.tcx.cannot_move_out_of(
290 span, place_description, origin);
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()];
297 upvar_decl.var_hir_id.assert_crate_local();
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");
310 .cannot_move_out_of(span, "borrowed content", origin),
313 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
315 .cannot_move_out_of_interior_of_drop(span, ty, origin)
317 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self
319 .cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index), origin),
325 self.add_move_hints(error, &mut err, err_span);
326 err.buffer(&mut self.errors_buffer);
331 error: GroupedMoveError<'tcx>,
332 err: &mut DiagnosticBuilder<'a>,
335 let snippet = self.tcx.sess.codemap().span_to_snippet(span).unwrap();
337 GroupedMoveError::MovesFromPlace {
342 let try_remove_deref = match move_from {
343 Place::Projection(box PlaceProjection {
344 elem: ProjectionElem::Deref,
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)`.
355 "consider removing the `*`",
356 snippet[1..].to_owned(),
361 "consider borrowing here",
362 format!("&{}", snippet),
368 self.add_move_error_labels(err, &binds_to);
370 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
373 self.add_move_error_suggestions(err, &binds_to);
374 self.add_move_error_labels(err, &binds_to);
376 // No binding. Nothing to suggest.
377 GroupedMoveError::OtherIllegalMove { .. } => (),
381 fn add_move_error_suggestions(
383 err: &mut DiagnosticBuilder<'a>,
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];
390 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
394 ) = bind_to.is_user_variable {
395 let pat_snippet = self
397 .span_to_snippet(pat_span)
399 if pat_snippet.starts_with('&') {
400 let pat_snippet = pat_snippet[1..].trim_left();
403 if pat_snippet.starts_with("mut")
404 && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
406 suggestion = pat_snippet["mut".len()..].trim_left();
409 suggestion = pat_snippet;
414 format!("consider removing the `{}`", to_remove),
415 suggestion.to_owned(),
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);
427 fn add_move_error_labels(
429 err: &mut DiagnosticBuilder<'a>,
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;
438 err.span_label(binding_span, format!("data moved here"));
440 err.span_label(binding_span, format!("... and here"));
443 if binds_to.len() == 1 {
447 "move occurs because `{}` has type `{}`, \
448 which does not implement the `Copy` trait",
449 bind_to.name.unwrap(),
454 noncopy_var_spans.push(binding_span);
458 if binds_to.len() > 1 {
461 "move occurs because these variables have types that \
462 don't implement the `Copy` trait",