1 use core::unicode::property::Pattern_White_Space;
5 use rustc_errors::{DiagnosticBuilder,Applicability};
8 use crate::borrow_check::MirBorrowckCtxt;
9 use crate::borrow_check::prefixes::PrefixSet;
10 use crate::borrow_check::error_reporting::UseSpans;
11 use crate::dataflow::move_paths::{
12 IllegalMoveOrigin, IllegalMoveOriginKind,
13 LookupResult, MoveError, MovePathIndex,
16 // Often when desugaring a pattern match we may have many individual moves in
17 // MIR that are all part of one operation from the user's point-of-view. For
22 // would move x from the 0 field of some temporary, and y from the 1 field. We
23 // group such errors together for cleaner error reporting.
25 // Errors are kept separate if they are from places with different parent move
26 // paths. For example, this generates two errors:
28 // let (&x, &y) = (&String::new(), &String::new());
30 enum GroupedMoveError<'tcx> {
31 // Place expression can't be moved from,
32 // e.g., match x[0] { s => (), } where x: &[String]
34 original_path: Place<'tcx>,
36 move_from: Place<'tcx>,
37 kind: IllegalMoveOriginKind<'tcx>,
40 // Part of a value expression can't be moved from,
41 // e.g., match &String::new() { &x => (), }
43 original_path: Place<'tcx>,
45 move_from: MovePathIndex,
46 kind: IllegalMoveOriginKind<'tcx>,
49 // Everything that isn't from pattern matching.
51 original_path: Place<'tcx>,
53 kind: IllegalMoveOriginKind<'tcx>,
57 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
58 pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
59 let grouped_errors = self.group_move_errors(move_errors);
60 for error in grouped_errors {
67 errors: Vec<(Place<'tcx>, MoveError<'tcx>)>
68 ) -> Vec<GroupedMoveError<'tcx>> {
69 let mut grouped_errors = Vec::new();
70 for (original_path, error) in errors {
71 self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
76 fn append_to_grouped_errors(
78 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
79 original_path: Place<'tcx>,
80 error: MoveError<'tcx>,
83 MoveError::UnionMove { .. } => {
84 unimplemented!("don't know how to report union move errors yet.")
86 MoveError::IllegalMove {
87 cannot_move_out_of: IllegalMoveOrigin { location, kind },
89 // Note: that the only time we assign a place isn't a temporary
90 // to a user variable is when initializing it.
91 // If that ever stops being the case, then the ever initialized
92 // flow could be used.
93 if let Some(StatementKind::Assign(
95 base: PlaceBase::Local(local),
98 box Rvalue::Use(Operand::Move(move_from)),
99 )) = self.body.basic_blocks()[location.block]
101 .get(location.statement_index)
102 .map(|stmt| &stmt.kind)
104 let local_decl = &self.body.local_decls[*local];
105 // opt_match_place is the
106 // match_span is the span of the expression being matched on
107 // match *x.y { ... } match_place is Some(*x.y)
108 // ^^^^ match_span is the span of *x.y
110 // opt_match_place is None for let [mut] x = ... statements,
111 // whether or not the right-hand side is a place expression
112 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
113 opt_match_place: Some((ref opt_match_place, match_span)),
117 }))) = local_decl.is_user_variable
119 let stmt_source_info = self.body.source_info(location);
120 self.append_binding_error(
128 stmt_source_info.span,
134 let move_spans = self.move_spans(&original_path, location);
135 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
136 use_spans: move_spans,
144 fn append_binding_error(
146 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
147 kind: IllegalMoveOriginKind<'tcx>,
148 original_path: Place<'tcx>,
149 move_from: &Place<'tcx>,
151 match_place: &Option<Place<'tcx>>,
153 statement_span: Span,
156 "append_binding_error(match_place={:?}, match_span={:?})",
157 match_place, match_span
160 let from_simple_let = match_place.is_none();
161 let match_place = match_place.as_ref().unwrap_or(move_from);
163 match self.move_data.rev_lookup.find(match_place) {
164 // Error with the match place
165 LookupResult::Parent(_) => {
166 for ge in &mut *grouped_errors {
167 if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
168 if match_span == *span {
169 debug!("appending local({:?}) to list", bind_to);
170 if !binds_to.is_empty() {
171 binds_to.push(bind_to);
177 debug!("found a new move error location");
179 // Don't need to point to x in let x = ... .
180 let (binds_to, span) = if from_simple_let {
181 (vec![], statement_span)
183 (vec![bind_to], match_span)
185 grouped_errors.push(GroupedMoveError::MovesFromPlace {
187 move_from: match_place.clone(),
193 // Error with the pattern
194 LookupResult::Exact(_) => {
195 let mpi = match self.move_data.rev_lookup.find(move_from) {
196 LookupResult::Parent(Some(mpi)) => mpi,
197 // move_from should be a projection from match_place.
198 _ => unreachable!("Probably not unreachable..."),
200 for ge in &mut *grouped_errors {
201 if let GroupedMoveError::MovesFromValue {
203 move_from: other_mpi,
208 if match_span == *span && mpi == *other_mpi {
209 debug!("appending local({:?}) to list", bind_to);
210 binds_to.push(bind_to);
215 debug!("found a new move error location");
216 grouped_errors.push(GroupedMoveError::MovesFromValue {
221 binds_to: vec![bind_to],
227 fn report(&mut self, error: GroupedMoveError<'tcx>) {
228 let (mut err, err_span) = {
229 let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind<'_>) =
231 GroupedMoveError::MovesFromPlace { span, ref original_path, ref kind, .. } |
232 GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } => {
233 (span, original_path, kind)
235 GroupedMoveError::OtherIllegalMove {
240 (use_spans.args_or_use(), original_path, kind)
243 debug!("report: original_path={:?} span={:?}, kind={:?} \
244 original_path.is_upvar_field_projection={:?}", original_path, span, kind,
245 self.is_upvar_field_projection(original_path));
248 IllegalMoveOriginKind::Static => {
249 self.report_cannot_move_from_static(original_path, span)
251 IllegalMoveOriginKind::BorrowedContent { target_place } => {
252 self.report_cannot_move_from_borrowed_content(
258 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
259 self.cannot_move_out_of_interior_of_drop(span, ty)
261 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } =>
262 self.cannot_move_out_of_interior_noncopy(
263 span, ty, Some(*is_index),
270 self.add_move_hints(error, &mut err, err_span);
271 err.buffer(&mut self.errors_buffer);
274 fn report_cannot_move_from_static(
278 ) -> DiagnosticBuilder<'a> {
279 let description = if place.projection.is_none() {
280 format!("static item `{}`", self.describe_place(place).unwrap())
282 let mut base_static = &place.projection;
283 while let Some(box Projection { base: Some(ref proj), .. }) = base_static {
284 base_static = &proj.base;
286 let base_static = Place {
287 base: place.base.clone(),
288 projection: base_static.clone(),
292 "`{:?}` as `{:?}` is a static item",
293 self.describe_place(place).unwrap(),
294 self.describe_place(&base_static).unwrap(),
298 self.cannot_move_out_of(span, &description)
301 fn report_cannot_move_from_borrowed_content(
303 move_place: &Place<'tcx>,
304 deref_target_place: &Place<'tcx>,
306 ) -> DiagnosticBuilder<'a> {
307 // Inspect the type of the content behind the
308 // borrow to provide feedback about why this
309 // was a move rather than a copy.
310 let ty = deref_target_place.ty(self.body, self.infcx.tcx).ty;
311 let upvar_field = self.prefixes(&move_place.base, &move_place.projection, PrefixSet::All)
312 .find_map(|p| self.is_upvar_field_projection(&Place {
314 projection: p.1.clone(),
317 let deref_base = match deref_target_place.projection {
318 Some(box Projection { ref base, elem: ProjectionElem::Deref }) => Place {
319 base: deref_target_place.base.clone(),
320 projection: base.clone(),
322 _ => bug!("deref_target_place is not a deref projection"),
326 base: PlaceBase::Local(local),
329 let decl = &self.body.local_decls[local];
330 if decl.is_ref_for_guard() {
331 let mut err = self.cannot_move_out_of(
333 &format!("`{}` in pattern guard", decl.name.unwrap()),
336 "variables bound in patterns cannot be moved from \
337 until after the end of the pattern guard");
342 debug!("report: ty={:?}", ty);
343 let mut err = match ty.sty {
344 ty::Array(..) | ty::Slice(..) =>
345 self.cannot_move_out_of_interior_noncopy(span, ty, None),
346 ty::Closure(def_id, closure_substs)
347 if def_id == self.mir_def_id && upvar_field.is_some()
349 let closure_kind_ty = closure_substs.closure_kind_ty(def_id, self.infcx.tcx);
350 let closure_kind = closure_kind_ty.to_opt_closure_kind();
351 let capture_description = match closure_kind {
352 Some(ty::ClosureKind::Fn) => {
353 "captured variable in an `Fn` closure"
355 Some(ty::ClosureKind::FnMut) => {
356 "captured variable in an `FnMut` closure"
358 Some(ty::ClosureKind::FnOnce) => {
359 bug!("closure kind does not match first argument type")
361 None => bug!("closure kind not inferred by borrowck"),
364 let upvar = &self.upvars[upvar_field.unwrap().index()];
365 let upvar_hir_id = upvar.var_hir_id;
366 let upvar_name = upvar.name;
367 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
369 let place_name = self.describe_place(move_place).unwrap();
371 let place_description = if self.is_upvar_field_projection(move_place).is_some() {
372 format!("`{}`, a {}", place_name, capture_description)
375 "`{}`, as `{}` is a {}",
383 "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
384 closure_kind_ty, closure_kind, place_description,
387 let mut diag = self.cannot_move_out_of(span, &place_description);
389 diag.span_label(upvar_span, "captured outer variable");
394 let source = self.borrowed_content_source(&deref_base);
395 match (self.describe_place(move_place), source.describe_for_named_place()) {
396 (Some(place_desc), Some(source_desc)) => {
397 self.cannot_move_out_of(
399 &format!("`{}` which is behind a {}", place_desc, source_desc),
403 self.cannot_move_out_of(
405 &source.describe_for_unnamed_place(),
411 let move_ty = format!(
413 move_place.ty(self.body, self.infcx.tcx).ty,
415 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
416 let is_option = move_ty.starts_with("std::option::Option");
417 let is_result = move_ty.starts_with("std::result::Result");
418 if is_option || is_result {
421 &format!("consider borrowing the `{}`'s content", if is_option {
426 format!("{}.as_ref()", snippet),
427 Applicability::MaybeIncorrect,
435 error: GroupedMoveError<'tcx>,
436 err: &mut DiagnosticBuilder<'a>,
439 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
441 GroupedMoveError::MovesFromPlace {
448 "consider borrowing here",
449 format!("&{}", snippet),
450 Applicability::Unspecified,
453 if binds_to.is_empty() {
454 let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
455 let place_desc = match self.describe_place(&move_from) {
456 Some(desc) => format!("`{}`", desc),
457 None => format!("value"),
460 self.note_type_does_not_implement_copy(
470 self.add_move_error_details(err, &binds_to);
473 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
476 self.add_move_error_suggestions(err, &binds_to);
477 self.add_move_error_details(err, &binds_to);
479 // No binding. Nothing to suggest.
480 GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
481 let span = use_spans.var_or_use();
482 let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
483 let place_desc = match self.describe_place(original_path) {
484 Some(desc) => format!("`{}`", desc),
485 None => format!("value"),
487 self.note_type_does_not_implement_copy(
494 use_spans.args_span_label(err, format!("move out of {} occurs here", place_desc));
495 use_spans.var_span_label(
497 format!("move occurs due to use{}", use_spans.describe()),
503 fn add_move_error_suggestions(
505 err: &mut DiagnosticBuilder<'a>,
508 let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
509 for local in binds_to {
510 let bind_to = &self.body.local_decls[*local];
512 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
516 ) = bind_to.is_user_variable {
517 let pat_snippet = self.infcx.tcx.sess.source_map()
518 .span_to_snippet(pat_span)
520 if pat_snippet.starts_with('&') {
521 let pat_snippet = pat_snippet[1..].trim_start();
524 if pat_snippet.starts_with("mut")
525 && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
527 suggestion = pat_snippet["mut".len()..].trim_start();
530 suggestion = pat_snippet;
536 suggestion.to_owned(),
541 suggestions.sort_unstable_by_key(|&(span, _, _)| span);
542 suggestions.dedup_by_key(|&mut (span, _, _)| span);
543 for (span, to_remove, suggestion) in suggestions {
546 &format!("consider removing the `{}`", to_remove),
548 Applicability::MachineApplicable,
553 fn add_move_error_details(
555 err: &mut DiagnosticBuilder<'a>,
558 let mut noncopy_var_spans = Vec::new();
559 for (j, local) in binds_to.into_iter().enumerate() {
560 let bind_to = &self.body.local_decls[*local];
561 let binding_span = bind_to.source_info.span;
564 err.span_label(binding_span, "data moved here");
566 err.span_label(binding_span, "...and here");
569 if binds_to.len() == 1 {
570 self.note_type_does_not_implement_copy(
572 &format!("`{}`", bind_to.name.unwrap()),
577 noncopy_var_spans.push(binding_span);
581 if binds_to.len() > 1 {
584 "move occurs because these variables have types that \
585 don't implement the `Copy` trait",