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.as_place_ref(), 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.as_place_ref()) {
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.as_place_ref()) {
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.as_place_ref()));
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.as_place_ref()).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.as_place_ref()).unwrap(),
294 self.describe_place(base_static.as_place_ref()).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.as_place_ref(), PrefixSet::All)
312 .find_map(|p| self.is_upvar_field_projection(p));
314 let deref_base = match deref_target_place.projection {
315 Some(box Projection { ref base, elem: ProjectionElem::Deref }) => Place {
316 base: deref_target_place.base.clone(),
317 projection: base.clone(),
319 _ => bug!("deref_target_place is not a deref projection"),
323 base: PlaceBase::Local(local),
326 let decl = &self.body.local_decls[local];
327 if decl.is_ref_for_guard() {
328 let mut err = self.cannot_move_out_of(
330 &format!("`{}` in pattern guard", decl.name.unwrap()),
333 "variables bound in patterns cannot be moved from \
334 until after the end of the pattern guard");
339 debug!("report: ty={:?}", ty);
340 let mut err = match ty.sty {
341 ty::Array(..) | ty::Slice(..) =>
342 self.cannot_move_out_of_interior_noncopy(span, ty, None),
343 ty::Closure(def_id, closure_substs)
344 if def_id == self.mir_def_id && upvar_field.is_some()
346 let closure_kind_ty = closure_substs.closure_kind_ty(def_id, self.infcx.tcx);
347 let closure_kind = closure_kind_ty.to_opt_closure_kind();
348 let capture_description = match closure_kind {
349 Some(ty::ClosureKind::Fn) => {
350 "captured variable in an `Fn` closure"
352 Some(ty::ClosureKind::FnMut) => {
353 "captured variable in an `FnMut` closure"
355 Some(ty::ClosureKind::FnOnce) => {
356 bug!("closure kind does not match first argument type")
358 None => bug!("closure kind not inferred by borrowck"),
361 let upvar = &self.upvars[upvar_field.unwrap().index()];
362 let upvar_hir_id = upvar.var_hir_id;
363 let upvar_name = upvar.name;
364 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
366 let place_name = self.describe_place(move_place.as_place_ref()).unwrap();
368 let place_description = if self
369 .is_upvar_field_projection(move_place.as_place_ref())
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);
396 self.describe_place(move_place.as_place_ref()),
397 source.describe_for_named_place(),
399 (Some(place_desc), Some(source_desc)) => {
400 self.cannot_move_out_of(
402 &format!("`{}` which is behind a {}", place_desc, source_desc),
406 self.cannot_move_out_of(
408 &source.describe_for_unnamed_place(),
414 let move_ty = format!(
416 move_place.ty(self.body, self.infcx.tcx).ty,
418 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
419 let is_option = move_ty.starts_with("std::option::Option");
420 let is_result = move_ty.starts_with("std::result::Result");
421 if is_option || is_result {
424 &format!("consider borrowing the `{}`'s content", if is_option {
429 format!("{}.as_ref()", snippet),
430 Applicability::MaybeIncorrect,
438 error: GroupedMoveError<'tcx>,
439 err: &mut DiagnosticBuilder<'a>,
442 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
444 GroupedMoveError::MovesFromPlace {
451 "consider borrowing here",
452 format!("&{}", snippet),
453 Applicability::Unspecified,
456 if binds_to.is_empty() {
457 let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
458 let place_desc = match self.describe_place(move_from.as_place_ref()) {
459 Some(desc) => format!("`{}`", desc),
460 None => format!("value"),
463 self.note_type_does_not_implement_copy(
473 self.add_move_error_details(err, &binds_to);
476 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
479 self.add_move_error_suggestions(err, &binds_to);
480 self.add_move_error_details(err, &binds_to);
482 // No binding. Nothing to suggest.
483 GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
484 let span = use_spans.var_or_use();
485 let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
486 let place_desc = match self.describe_place(original_path.as_place_ref()) {
487 Some(desc) => format!("`{}`", desc),
488 None => format!("value"),
490 self.note_type_does_not_implement_copy(
497 use_spans.args_span_label(err, format!("move out of {} occurs here", place_desc));
498 use_spans.var_span_label(
500 format!("move occurs due to use{}", use_spans.describe()),
506 fn add_move_error_suggestions(
508 err: &mut DiagnosticBuilder<'a>,
511 let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
512 for local in binds_to {
513 let bind_to = &self.body.local_decls[*local];
515 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
519 ) = bind_to.is_user_variable {
520 let pat_snippet = self.infcx.tcx.sess.source_map()
521 .span_to_snippet(pat_span)
523 if pat_snippet.starts_with('&') {
524 let pat_snippet = pat_snippet[1..].trim_start();
527 if pat_snippet.starts_with("mut")
528 && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
530 suggestion = pat_snippet["mut".len()..].trim_start();
533 suggestion = pat_snippet;
539 suggestion.to_owned(),
544 suggestions.sort_unstable_by_key(|&(span, _, _)| span);
545 suggestions.dedup_by_key(|&mut (span, _, _)| span);
546 for (span, to_remove, suggestion) in suggestions {
549 &format!("consider removing the `{}`", to_remove),
551 Applicability::MachineApplicable,
556 fn add_move_error_details(
558 err: &mut DiagnosticBuilder<'a>,
561 let mut noncopy_var_spans = Vec::new();
562 for (j, local) in binds_to.into_iter().enumerate() {
563 let bind_to = &self.body.local_decls[*local];
564 let binding_span = bind_to.source_info.span;
567 err.span_label(binding_span, "data moved here");
569 err.span_label(binding_span, "...and here");
572 if binds_to.len() == 1 {
573 self.note_type_does_not_implement_copy(
575 &format!("`{}`", bind_to.name.unwrap()),
580 noncopy_var_spans.push(binding_span);
584 if binds_to.len() > 1 {
587 "move occurs because these variables have types that \
588 don't implement the `Copy` trait",