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;
12 use std::fmt::{self, Display};
16 use rustc_errors::{DiagnosticBuilder,Applicability};
19 use borrow_check::MirBorrowckCtxt;
20 use borrow_check::prefixes::PrefixSet;
21 use dataflow::move_paths::{
22 IllegalMoveOrigin, IllegalMoveOriginKind, InitLocation,
23 LookupResult, MoveError, MovePathIndex,
25 use util::borrowck_errors::{BorrowckErrors, Origin};
27 // Often when desugaring a pattern match we may have many individual moves in
28 // MIR that are all part of one operation from the user's point-of-view. For
33 // would move x from the 0 field of some temporary, and y from the 1 field. We
34 // group such errors together for cleaner error reporting.
36 // Errors are kept separate if they are from places with different parent move
37 // paths. For example, this generates two errors:
39 // let (&x, &y) = (&String::new(), &String::new());
41 enum GroupedMoveError<'tcx> {
42 // Place expression can't be moved from,
43 // e.g. match x[0] { s => (), } where x: &[String]
45 original_path: Place<'tcx>,
47 move_from: Place<'tcx>,
48 kind: IllegalMoveOriginKind<'tcx>,
51 // Part of a value expression can't be moved from,
52 // e.g. match &String::new() { &x => (), }
54 original_path: Place<'tcx>,
56 move_from: MovePathIndex,
57 kind: IllegalMoveOriginKind<'tcx>,
60 // Everything that isn't from pattern matching.
62 original_path: Place<'tcx>,
64 kind: IllegalMoveOriginKind<'tcx>,
68 enum BorrowedContentSource {
74 impl Display for BorrowedContentSource {
75 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77 BorrowedContentSource::Arc => write!(f, "an `Arc`"),
78 BorrowedContentSource::Rc => write!(f, "an `Rc`"),
79 BorrowedContentSource::Other => write!(f, "borrowed content"),
84 impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
85 pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
86 let grouped_errors = self.group_move_errors(move_errors);
87 for error in grouped_errors {
94 errors: Vec<(Place<'tcx>, MoveError<'tcx>)>
95 ) -> Vec<GroupedMoveError<'tcx>> {
96 let mut grouped_errors = Vec::new();
97 for (original_path, error) in errors {
98 self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
103 fn append_to_grouped_errors(
105 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
106 original_path: Place<'tcx>,
107 error: MoveError<'tcx>,
110 MoveError::UnionMove { .. } => {
111 unimplemented!("don't know how to report union move errors yet.")
113 MoveError::IllegalMove {
114 cannot_move_out_of: IllegalMoveOrigin { location, kind },
116 let stmt_source_info = self.mir.source_info(location);
117 // Note: that the only time we assign a place isn't a temporary
118 // to a user variable is when initializing it.
119 // If that ever stops being the case, then the ever initialized
120 // flow could be used.
121 if let Some(StatementKind::Assign(
123 box Rvalue::Use(Operand::Move(move_from)),
124 )) = self.mir.basic_blocks()[location.block]
126 .get(location.statement_index)
127 .map(|stmt| &stmt.kind)
129 let local_decl = &self.mir.local_decls[*local];
130 // opt_match_place is the
131 // match_span is the span of the expression being matched on
132 // match *x.y { ... } match_place is Some(*x.y)
133 // ^^^^ match_span is the span of *x.y
135 // opt_match_place is None for let [mut] x = ... statements,
136 // whether or not the right-hand side is a place expression
137 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
138 opt_match_place: Some((ref opt_match_place, match_span)),
142 }))) = local_decl.is_user_variable
144 self.append_binding_error(
152 stmt_source_info.span,
157 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
158 span: stmt_source_info.span,
166 fn append_binding_error(
168 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
169 kind: IllegalMoveOriginKind<'tcx>,
170 original_path: Place<'tcx>,
171 move_from: &Place<'tcx>,
173 match_place: &Option<Place<'tcx>>,
175 statement_span: Span,
178 "append_binding_error(match_place={:?}, match_span={:?})",
179 match_place, match_span
182 let from_simple_let = match_place.is_none();
183 let match_place = match_place.as_ref().unwrap_or(move_from);
185 match self.move_data.rev_lookup.find(match_place) {
186 // Error with the match place
187 LookupResult::Parent(_) => {
188 for ge in &mut *grouped_errors {
189 if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
190 if match_span == *span {
191 debug!("appending local({:?}) to list", bind_to);
192 if !binds_to.is_empty() {
193 binds_to.push(bind_to);
199 debug!("found a new move error location");
201 // Don't need to point to x in let x = ... .
202 let (binds_to, span) = if from_simple_let {
203 (vec![], statement_span)
205 (vec![bind_to], match_span)
207 grouped_errors.push(GroupedMoveError::MovesFromPlace {
209 move_from: match_place.clone(),
215 // Error with the pattern
216 LookupResult::Exact(_) => {
217 let mpi = match self.move_data.rev_lookup.find(move_from) {
218 LookupResult::Parent(Some(mpi)) => mpi,
219 // move_from should be a projection from match_place.
220 _ => unreachable!("Probably not unreachable..."),
222 for ge in &mut *grouped_errors {
223 if let GroupedMoveError::MovesFromValue {
225 move_from: other_mpi,
230 if match_span == *span && mpi == *other_mpi {
231 debug!("appending local({:?}) to list", bind_to);
232 binds_to.push(bind_to);
237 debug!("found a new move error location");
238 grouped_errors.push(GroupedMoveError::MovesFromValue {
243 binds_to: vec![bind_to],
249 fn report(&mut self, error: GroupedMoveError<'tcx>) {
250 let (mut err, err_span) = {
251 let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind) =
253 GroupedMoveError::MovesFromPlace {
259 GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } |
260 GroupedMoveError::OtherIllegalMove { span, ref original_path, ref kind } => {
261 (span, original_path, kind)
264 let origin = Origin::Mir;
265 debug!("report: original_path={:?} span={:?}, kind={:?} \
266 original_path.is_upvar_field_projection={:?}", original_path, span, kind,
267 original_path.is_upvar_field_projection(self.mir, &self.infcx.tcx));
270 IllegalMoveOriginKind::Static => {
271 self.infcx.tcx.cannot_move_out_of(span, "static item", origin)
273 IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
274 // Inspect the type of the content behind the
275 // borrow to provide feedback about why this
276 // was a move rather than a copy.
277 let ty = place.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
278 let is_upvar_field_projection =
279 self.prefixes(&original_path, PrefixSet::All)
280 .any(|p| p.is_upvar_field_projection(self.mir, &self.infcx.tcx)
283 ty::Array(..) | ty::Slice(..) =>
284 self.infcx.tcx.cannot_move_out_of_interior_noncopy(
285 span, ty, None, origin
287 ty::Closure(def_id, closure_substs)
288 if !self.mir.upvar_decls.is_empty() && is_upvar_field_projection
290 let closure_kind_ty =
291 closure_substs.closure_kind_ty(def_id, self.infcx.tcx);
292 let closure_kind = closure_kind_ty.to_opt_closure_kind();
293 let place_description = match closure_kind {
294 Some(ty::ClosureKind::Fn) => {
295 "captured variable in an `Fn` closure"
297 Some(ty::ClosureKind::FnMut) => {
298 "captured variable in an `FnMut` closure"
300 Some(ty::ClosureKind::FnOnce) => {
301 bug!("closure kind does not match first argument type")
303 None => bug!("closure kind not inferred by borrowck"),
305 debug!("report: closure_kind_ty={:?} closure_kind={:?} \
306 place_description={:?}", closure_kind_ty, closure_kind,
309 let mut diag = self.infcx.tcx.cannot_move_out_of(
310 span, place_description, origin);
312 for prefix in self.prefixes(&original_path, PrefixSet::All) {
313 if let Some(field) = prefix.is_upvar_field_projection(
314 self.mir, &self.infcx.tcx) {
315 let upvar_decl = &self.mir.upvar_decls[field.index()];
317 upvar_decl.var_hir_id.assert_crate_local();
319 self.infcx.tcx.hir.hir_to_node_id(upvar_hir_id);
320 let upvar_span = self.infcx.tcx.hir.span(upvar_node_id);
321 diag.span_label(upvar_span, "captured outer variable");
329 let source = self.borrowed_content_source(place);
330 self.infcx.tcx.cannot_move_out_of(
331 span, &format!("{}", source), origin
336 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
338 .cannot_move_out_of_interior_of_drop(span, ty, origin)
340 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } =>
341 self.infcx.tcx.cannot_move_out_of_interior_noncopy(
342 span, ty, Some(*is_index), origin
349 self.add_move_hints(error, &mut err, err_span);
350 err.buffer(&mut self.errors_buffer);
355 error: GroupedMoveError<'tcx>,
356 err: &mut DiagnosticBuilder<'a>,
359 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
361 GroupedMoveError::MovesFromPlace {
366 let try_remove_deref = match move_from {
367 Place::Projection(box PlaceProjection {
368 elem: ProjectionElem::Deref,
373 if try_remove_deref && snippet.starts_with('*') {
374 // The snippet doesn't start with `*` in (e.g.) index
375 // expressions `a[b]`, which roughly desugar to
376 // `*Index::index(&a, b)` or
377 // `*IndexMut::index_mut(&mut a, b)`.
378 err.span_suggestion_with_applicability(
380 "consider removing the `*`",
381 snippet[1..].to_owned(),
382 Applicability::Unspecified,
385 err.span_suggestion_with_applicability(
387 "consider borrowing here",
388 format!("&{}", snippet),
389 Applicability::Unspecified,
395 self.add_move_error_details(err, &binds_to);
397 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
400 self.add_move_error_suggestions(err, &binds_to);
401 self.add_move_error_details(err, &binds_to);
403 // No binding. Nothing to suggest.
404 GroupedMoveError::OtherIllegalMove { .. } => (),
408 fn add_move_error_suggestions(
410 err: &mut DiagnosticBuilder<'a>,
413 let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
414 for local in binds_to {
415 let bind_to = &self.mir.local_decls[*local];
417 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
421 ) = bind_to.is_user_variable {
422 let pat_snippet = self.infcx.tcx.sess.source_map()
423 .span_to_snippet(pat_span)
425 if pat_snippet.starts_with('&') {
426 let pat_snippet = pat_snippet[1..].trim_left();
429 if pat_snippet.starts_with("mut")
430 && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
432 suggestion = pat_snippet["mut".len()..].trim_left();
435 suggestion = pat_snippet;
441 suggestion.to_owned(),
446 suggestions.sort_unstable_by_key(|&(span, _, _)| span);
447 suggestions.dedup_by_key(|&mut (span, _, _)| span);
448 for (span, to_remove, suggestion) in suggestions {
449 err.span_suggestion_with_applicability(
451 &format!("consider removing the `{}`", to_remove),
453 Applicability::MachineApplicable,
458 fn add_move_error_details(
460 err: &mut DiagnosticBuilder<'a>,
463 let mut noncopy_var_spans = Vec::new();
464 for (j, local) in binds_to.into_iter().enumerate() {
465 let bind_to = &self.mir.local_decls[*local];
466 let binding_span = bind_to.source_info.span;
469 err.span_label(binding_span, format!("data moved here"));
471 err.span_label(binding_span, format!("...and here"));
474 if binds_to.len() == 1 {
478 "move occurs because `{}` has type `{}`, \
479 which does not implement the `Copy` trait",
480 bind_to.name.unwrap(),
485 noncopy_var_spans.push(binding_span);
489 if binds_to.len() > 1 {
492 "move occurs because these variables have types that \
493 don't implement the `Copy` trait",
498 fn borrowed_content_source(&self, place: &Place<'tcx>) -> BorrowedContentSource {
499 // Look up the provided place and work out the move path index for it,
500 // we'll use this to work back through where this value came from and check whether it
501 // was originally part of an `Rc` or `Arc`.
502 let initial_mpi = match self.move_data.rev_lookup.find(place) {
503 LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => mpi,
504 _ => return BorrowedContentSource::Other,
507 let mut queue = vec![initial_mpi];
508 let mut visited = Vec::new();
509 debug!("borrowed_content_source: queue={:?}", queue);
510 while let Some(mpi) = queue.pop() {
512 "borrowed_content_source: mpi={:?} queue={:?} visited={:?}",
516 // Don't visit the same path twice.
517 if visited.contains(&mpi) {
522 for i in &self.move_data.init_path_map[mpi] {
523 let init = &self.move_data.inits[*i];
524 debug!("borrowed_content_source: init={:?}", init);
525 // We're only interested in statements that initialized a value, not the
526 // initializations from arguments.
527 let loc = match init.location {
528 InitLocation::Statement(stmt) => stmt,
532 let bbd = &self.mir[loc.block];
533 let is_terminator = bbd.statements.len() == loc.statement_index;
534 debug!("borrowed_content_source: loc={:?} is_terminator={:?}", loc, is_terminator);
536 let stmt = &bbd.statements[loc.statement_index];
537 debug!("borrowed_content_source: stmt={:?}", stmt);
538 // We're only interested in assignments (in particular, where the
539 // assignment came from - was it an `Rc` or `Arc`?).
540 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, source)) = &stmt.kind {
541 let ty = source.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
542 let ty = match ty.sty {
543 ty::TyKind::Ref(_, ty, _) => ty,
546 debug!("borrowed_content_source: ty={:?}", ty);
549 return BorrowedContentSource::Arc;
550 } else if ty.is_rc() {
551 return BorrowedContentSource::Rc;
553 queue.push(init.path);
556 } else if let Some(Terminator {
557 kind: TerminatorKind::Call { args, .. },
559 }) = &bbd.terminator {
561 let source = match arg {
562 Operand::Copy(place) | Operand::Move(place) => place,
566 let ty = source.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
567 let ty = match ty.sty {
568 ty::TyKind::Ref(_, ty, _) => ty,
571 debug!("borrowed_content_source: ty={:?}", ty);
574 return BorrowedContentSource::Arc;
575 } else if ty.is_rc() {
576 return BorrowedContentSource::Rc;
578 queue.push(init.path);
585 BorrowedContentSource::Other