1 use core::unicode::property::Pattern_White_Space;
2 use std::fmt::{self, Display};
6 use rustc_errors::{DiagnosticBuilder,Applicability};
9 use borrow_check::MirBorrowckCtxt;
10 use borrow_check::prefixes::PrefixSet;
11 use dataflow::move_paths::{
12 IllegalMoveOrigin, IllegalMoveOriginKind, InitLocation,
13 LookupResult, MoveError, MovePathIndex,
15 use util::borrowck_errors::{BorrowckErrors, Origin};
17 // Often when desugaring a pattern match we may have many individual moves in
18 // MIR that are all part of one operation from the user's point-of-view. For
23 // would move x from the 0 field of some temporary, and y from the 1 field. We
24 // group such errors together for cleaner error reporting.
26 // Errors are kept separate if they are from places with different parent move
27 // paths. For example, this generates two errors:
29 // let (&x, &y) = (&String::new(), &String::new());
31 enum GroupedMoveError<'tcx> {
32 // Place expression can't be moved from,
33 // e.g., match x[0] { s => (), } where x: &[String]
35 original_path: Place<'tcx>,
37 move_from: Place<'tcx>,
38 kind: IllegalMoveOriginKind<'tcx>,
41 // Part of a value expression can't be moved from,
42 // e.g., match &String::new() { &x => (), }
44 original_path: Place<'tcx>,
46 move_from: MovePathIndex,
47 kind: IllegalMoveOriginKind<'tcx>,
50 // Everything that isn't from pattern matching.
52 original_path: Place<'tcx>,
54 kind: IllegalMoveOriginKind<'tcx>,
58 enum BorrowedContentSource {
65 impl Display for BorrowedContentSource {
66 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 BorrowedContentSource::Arc => write!(f, "an `Arc`"),
69 BorrowedContentSource::Rc => write!(f, "an `Rc`"),
70 BorrowedContentSource::DerefRawPointer => write!(f, "dereference of raw pointer"),
71 BorrowedContentSource::Other => write!(f, "borrowed content"),
76 impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
77 pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
78 let grouped_errors = self.group_move_errors(move_errors);
79 for error in grouped_errors {
86 errors: Vec<(Place<'tcx>, MoveError<'tcx>)>
87 ) -> Vec<GroupedMoveError<'tcx>> {
88 let mut grouped_errors = Vec::new();
89 for (original_path, error) in errors {
90 self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
95 fn append_to_grouped_errors(
97 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
98 original_path: Place<'tcx>,
99 error: MoveError<'tcx>,
102 MoveError::UnionMove { .. } => {
103 unimplemented!("don't know how to report union move errors yet.")
105 MoveError::IllegalMove {
106 cannot_move_out_of: IllegalMoveOrigin { location, kind },
108 let stmt_source_info = self.mir.source_info(location);
109 // Note: that the only time we assign a place isn't a temporary
110 // to a user variable is when initializing it.
111 // If that ever stops being the case, then the ever initialized
112 // flow could be used.
113 if let Some(StatementKind::Assign(
115 box Rvalue::Use(Operand::Move(move_from)),
116 )) = self.mir.basic_blocks()[location.block]
118 .get(location.statement_index)
119 .map(|stmt| &stmt.kind)
121 let local_decl = &self.mir.local_decls[*local];
122 // opt_match_place is the
123 // match_span is the span of the expression being matched on
124 // match *x.y { ... } match_place is Some(*x.y)
125 // ^^^^ match_span is the span of *x.y
127 // opt_match_place is None for let [mut] x = ... statements,
128 // whether or not the right-hand side is a place expression
129 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
130 opt_match_place: Some((ref opt_match_place, match_span)),
134 }))) = local_decl.is_user_variable
136 self.append_binding_error(
144 stmt_source_info.span,
149 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
150 span: stmt_source_info.span,
158 fn append_binding_error(
160 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
161 kind: IllegalMoveOriginKind<'tcx>,
162 original_path: Place<'tcx>,
163 move_from: &Place<'tcx>,
165 match_place: &Option<Place<'tcx>>,
167 statement_span: Span,
170 "append_binding_error(match_place={:?}, match_span={:?})",
171 match_place, match_span
174 let from_simple_let = match_place.is_none();
175 let match_place = match_place.as_ref().unwrap_or(move_from);
177 match self.move_data.rev_lookup.find(match_place) {
178 // Error with the match place
179 LookupResult::Parent(_) => {
180 for ge in &mut *grouped_errors {
181 if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
182 if match_span == *span {
183 debug!("appending local({:?}) to list", bind_to);
184 if !binds_to.is_empty() {
185 binds_to.push(bind_to);
191 debug!("found a new move error location");
193 // Don't need to point to x in let x = ... .
194 let (binds_to, span) = if from_simple_let {
195 (vec![], statement_span)
197 (vec![bind_to], match_span)
199 grouped_errors.push(GroupedMoveError::MovesFromPlace {
201 move_from: match_place.clone(),
207 // Error with the pattern
208 LookupResult::Exact(_) => {
209 let mpi = match self.move_data.rev_lookup.find(move_from) {
210 LookupResult::Parent(Some(mpi)) => mpi,
211 // move_from should be a projection from match_place.
212 _ => unreachable!("Probably not unreachable..."),
214 for ge in &mut *grouped_errors {
215 if let GroupedMoveError::MovesFromValue {
217 move_from: other_mpi,
222 if match_span == *span && mpi == *other_mpi {
223 debug!("appending local({:?}) to list", bind_to);
224 binds_to.push(bind_to);
229 debug!("found a new move error location");
230 grouped_errors.push(GroupedMoveError::MovesFromValue {
235 binds_to: vec![bind_to],
241 fn report(&mut self, error: GroupedMoveError<'tcx>) {
242 let (mut err, err_span) = {
243 let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind) =
245 GroupedMoveError::MovesFromPlace {
251 GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } |
252 GroupedMoveError::OtherIllegalMove { span, ref original_path, ref kind } => {
253 (span, original_path, kind)
256 let origin = Origin::Mir;
257 debug!("report: original_path={:?} span={:?}, kind={:?} \
258 original_path.is_upvar_field_projection={:?}", original_path, span, kind,
259 original_path.is_upvar_field_projection(self.mir, &self.infcx.tcx));
262 IllegalMoveOriginKind::Static => {
263 self.infcx.tcx.cannot_move_out_of(span, "static item", origin)
265 IllegalMoveOriginKind::BorrowedContent { target_place: place } => {
266 // Inspect the type of the content behind the
267 // borrow to provide feedback about why this
268 // was a move rather than a copy.
269 let ty = place.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
270 let is_upvar_field_projection =
271 self.prefixes(&original_path, PrefixSet::All)
272 .any(|p| p.is_upvar_field_projection(self.mir, &self.infcx.tcx)
274 debug!("report: ty={:?}", ty);
276 ty::Array(..) | ty::Slice(..) =>
277 self.infcx.tcx.cannot_move_out_of_interior_noncopy(
278 span, ty, None, origin
280 ty::Closure(def_id, closure_substs)
281 if !self.mir.upvar_decls.is_empty() && is_upvar_field_projection
283 let closure_kind_ty =
284 closure_substs.closure_kind_ty(def_id, self.infcx.tcx);
285 let closure_kind = closure_kind_ty.to_opt_closure_kind();
286 let place_description = match closure_kind {
287 Some(ty::ClosureKind::Fn) => {
288 "captured variable in an `Fn` closure"
290 Some(ty::ClosureKind::FnMut) => {
291 "captured variable in an `FnMut` closure"
293 Some(ty::ClosureKind::FnOnce) => {
294 bug!("closure kind does not match first argument type")
296 None => bug!("closure kind not inferred by borrowck"),
298 debug!("report: closure_kind_ty={:?} closure_kind={:?} \
299 place_description={:?}", closure_kind_ty, closure_kind,
302 let mut diag = self.infcx.tcx.cannot_move_out_of(
303 span, place_description, origin);
305 for prefix in self.prefixes(&original_path, PrefixSet::All) {
306 if let Some(field) = prefix.is_upvar_field_projection(
307 self.mir, &self.infcx.tcx) {
308 let upvar_decl = &self.mir.upvar_decls[field.index()];
310 upvar_decl.var_hir_id.assert_crate_local();
312 self.infcx.tcx.hir().hir_to_node_id(upvar_hir_id);
313 let upvar_span = self.infcx.tcx.hir().span(upvar_node_id);
314 diag.span_label(upvar_span, "captured outer variable");
322 let source = self.borrowed_content_source(place);
323 self.infcx.tcx.cannot_move_out_of(
324 span, &source.to_string(), origin
329 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
331 .cannot_move_out_of_interior_of_drop(span, ty, origin)
333 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } =>
334 self.infcx.tcx.cannot_move_out_of_interior_noncopy(
335 span, ty, Some(*is_index), origin
342 self.add_move_hints(error, &mut err, err_span);
343 err.buffer(&mut self.errors_buffer);
348 error: GroupedMoveError<'tcx>,
349 err: &mut DiagnosticBuilder<'a>,
352 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
354 GroupedMoveError::MovesFromPlace {
359 let try_remove_deref = match move_from {
360 Place::Projection(box PlaceProjection {
361 elem: ProjectionElem::Deref,
366 if try_remove_deref && snippet.starts_with('*') {
367 // The snippet doesn't start with `*` in (e.g.) index
368 // expressions `a[b]`, which roughly desugar to
369 // `*Index::index(&a, b)` or
370 // `*IndexMut::index_mut(&mut a, b)`.
371 err.span_suggestion_with_applicability(
373 "consider removing the `*`",
374 snippet[1..].to_owned(),
375 Applicability::Unspecified,
378 err.span_suggestion_with_applicability(
380 "consider borrowing here",
381 format!("&{}", snippet),
382 Applicability::Unspecified,
388 self.add_move_error_details(err, &binds_to);
390 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
393 self.add_move_error_suggestions(err, &binds_to);
394 self.add_move_error_details(err, &binds_to);
396 // No binding. Nothing to suggest.
397 GroupedMoveError::OtherIllegalMove { .. } => (),
401 fn add_move_error_suggestions(
403 err: &mut DiagnosticBuilder<'a>,
406 let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
407 for local in binds_to {
408 let bind_to = &self.mir.local_decls[*local];
410 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
414 ) = bind_to.is_user_variable {
415 let pat_snippet = self.infcx.tcx.sess.source_map()
416 .span_to_snippet(pat_span)
418 if pat_snippet.starts_with('&') {
419 let pat_snippet = pat_snippet[1..].trim_start();
422 if pat_snippet.starts_with("mut")
423 && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
425 suggestion = pat_snippet["mut".len()..].trim_start();
428 suggestion = pat_snippet;
434 suggestion.to_owned(),
439 suggestions.sort_unstable_by_key(|&(span, _, _)| span);
440 suggestions.dedup_by_key(|&mut (span, _, _)| span);
441 for (span, to_remove, suggestion) in suggestions {
442 err.span_suggestion_with_applicability(
444 &format!("consider removing the `{}`", to_remove),
446 Applicability::MachineApplicable,
451 fn add_move_error_details(
453 err: &mut DiagnosticBuilder<'a>,
456 let mut noncopy_var_spans = Vec::new();
457 for (j, local) in binds_to.into_iter().enumerate() {
458 let bind_to = &self.mir.local_decls[*local];
459 let binding_span = bind_to.source_info.span;
462 err.span_label(binding_span, "data moved here");
464 err.span_label(binding_span, "...and here");
467 if binds_to.len() == 1 {
471 "move occurs because `{}` has type `{}`, \
472 which does not implement the `Copy` trait",
473 bind_to.name.unwrap(),
478 noncopy_var_spans.push(binding_span);
482 if binds_to.len() > 1 {
485 "move occurs because these variables have types that \
486 don't implement the `Copy` trait",
491 fn borrowed_content_source(&self, place: &Place<'tcx>) -> BorrowedContentSource {
492 // Look up the provided place and work out the move path index for it,
493 // we'll use this to work back through where this value came from and check whether it
494 // was originally part of an `Rc` or `Arc`.
495 let initial_mpi = match self.move_data.rev_lookup.find(place) {
496 LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => mpi,
497 _ => return BorrowedContentSource::Other,
500 let mut queue = vec![initial_mpi];
501 let mut visited = Vec::new();
502 debug!("borrowed_content_source: queue={:?}", queue);
503 while let Some(mpi) = queue.pop() {
505 "borrowed_content_source: mpi={:?} queue={:?} visited={:?}",
509 // Don't visit the same path twice.
510 if visited.contains(&mpi) {
515 for i in &self.move_data.init_path_map[mpi] {
516 let init = &self.move_data.inits[*i];
517 debug!("borrowed_content_source: init={:?}", init);
518 // We're only interested in statements that initialized a value, not the
519 // initializations from arguments.
520 let loc = match init.location {
521 InitLocation::Statement(stmt) => stmt,
525 let bbd = &self.mir[loc.block];
526 let is_terminator = bbd.statements.len() == loc.statement_index;
527 debug!("borrowed_content_source: loc={:?} is_terminator={:?}", loc, is_terminator);
529 let stmt = &bbd.statements[loc.statement_index];
530 debug!("borrowed_content_source: stmt={:?}", stmt);
531 // We're only interested in assignments (in particular, where the
532 // assignment came from - was it an `Rc` or `Arc`?).
533 if let StatementKind::Assign(_, box Rvalue::Ref(_, _, source)) = &stmt.kind {
534 let ty = source.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
535 let ty = match ty.sty {
536 ty::TyKind::Ref(_, ty, _) => ty,
539 debug!("borrowed_content_source: ty={:?}", ty);
542 return BorrowedContentSource::Arc;
543 } else if ty.is_rc() {
544 return BorrowedContentSource::Rc;
546 queue.push(init.path);
549 } else if let Some(Terminator {
550 kind: TerminatorKind::Call { args, .. },
552 }) = &bbd.terminator {
554 let source = match arg {
555 Operand::Copy(place) | Operand::Move(place) => place,
559 let ty = source.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
560 let ty = match ty.sty {
561 ty::TyKind::Ref(_, ty, _) => ty,
564 debug!("borrowed_content_source: ty={:?}", ty);
567 return BorrowedContentSource::Arc;
568 } else if ty.is_rc() {
569 return BorrowedContentSource::Rc;
571 queue.push(init.path);
578 // If we didn't find an `Arc` or an `Rc`, then check specifically for
579 // a dereference of a place that has the type of a raw pointer.
580 // We can't use `place.ty(..).to_ty(..)` here as that strips away the raw pointer.
581 if let Place::Projection(box Projection {
583 elem: ProjectionElem::Deref,
585 if base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx).is_unsafe_ptr() {
586 return BorrowedContentSource::DerefRawPointer;
590 BorrowedContentSource::Other