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(
94 Place::Base(PlaceBase::Local(local)),
95 box Rvalue::Use(Operand::Move(move_from)),
96 )) = self.body.basic_blocks()[location.block]
98 .get(location.statement_index)
99 .map(|stmt| &stmt.kind)
101 let local_decl = &self.body.local_decls[*local];
102 // opt_match_place is the
103 // match_span is the span of the expression being matched on
104 // match *x.y { ... } match_place is Some(*x.y)
105 // ^^^^ match_span is the span of *x.y
107 // opt_match_place is None for let [mut] x = ... statements,
108 // whether or not the right-hand side is a place expression
109 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
110 opt_match_place: Some((ref opt_match_place, match_span)),
114 }))) = local_decl.is_user_variable
116 let stmt_source_info = self.body.source_info(location);
117 self.append_binding_error(
125 stmt_source_info.span,
131 let move_spans = self.move_spans(&original_path, location);
132 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
133 use_spans: move_spans,
141 fn append_binding_error(
143 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
144 kind: IllegalMoveOriginKind<'tcx>,
145 original_path: Place<'tcx>,
146 move_from: &Place<'tcx>,
148 match_place: &Option<Place<'tcx>>,
150 statement_span: Span,
153 "append_binding_error(match_place={:?}, match_span={:?})",
154 match_place, match_span
157 let from_simple_let = match_place.is_none();
158 let match_place = match_place.as_ref().unwrap_or(move_from);
160 match self.move_data.rev_lookup.find(match_place) {
161 // Error with the match place
162 LookupResult::Parent(_) => {
163 for ge in &mut *grouped_errors {
164 if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
165 if match_span == *span {
166 debug!("appending local({:?}) to list", bind_to);
167 if !binds_to.is_empty() {
168 binds_to.push(bind_to);
174 debug!("found a new move error location");
176 // Don't need to point to x in let x = ... .
177 let (binds_to, span) = if from_simple_let {
178 (vec![], statement_span)
180 (vec![bind_to], match_span)
182 grouped_errors.push(GroupedMoveError::MovesFromPlace {
184 move_from: match_place.clone(),
190 // Error with the pattern
191 LookupResult::Exact(_) => {
192 let mpi = match self.move_data.rev_lookup.find(move_from) {
193 LookupResult::Parent(Some(mpi)) => mpi,
194 // move_from should be a projection from match_place.
195 _ => unreachable!("Probably not unreachable..."),
197 for ge in &mut *grouped_errors {
198 if let GroupedMoveError::MovesFromValue {
200 move_from: other_mpi,
205 if match_span == *span && mpi == *other_mpi {
206 debug!("appending local({:?}) to list", bind_to);
207 binds_to.push(bind_to);
212 debug!("found a new move error location");
213 grouped_errors.push(GroupedMoveError::MovesFromValue {
218 binds_to: vec![bind_to],
224 fn report(&mut self, error: GroupedMoveError<'tcx>) {
225 let (mut err, err_span) = {
226 let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind<'_>) =
228 GroupedMoveError::MovesFromPlace { span, ref original_path, ref kind, .. } |
229 GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } => {
230 (span, original_path, kind)
232 GroupedMoveError::OtherIllegalMove {
237 (use_spans.args_or_use(), original_path, kind)
240 debug!("report: original_path={:?} span={:?}, kind={:?} \
241 original_path.is_upvar_field_projection={:?}", original_path, span, kind,
242 self.is_upvar_field_projection(original_path));
245 IllegalMoveOriginKind::Static => {
246 self.report_cannot_move_from_static(original_path, span)
248 IllegalMoveOriginKind::BorrowedContent { target_place } => {
249 self.report_cannot_move_from_borrowed_content(
255 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
256 self.cannot_move_out_of_interior_of_drop(span, ty)
258 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } =>
259 self.cannot_move_out_of_interior_noncopy(
260 span, ty, Some(*is_index),
267 self.add_move_hints(error, &mut err, err_span);
268 err.buffer(&mut self.errors_buffer);
271 fn report_cannot_move_from_static(
275 ) -> DiagnosticBuilder<'a> {
276 let mut base_static = place;
279 Place::Base(_) => break,
280 Place::Projection(box Projection { base, .. }) => base_static = base,
284 let description = if let Place::Base(_) = place {
285 format!("static item `{}`", self.describe_place(place).unwrap())
288 "`{:?}` as `{:?}` is a static item",
289 self.describe_place(place).unwrap(),
290 self.describe_place(base_static).unwrap(),
294 self.cannot_move_out_of(span, &description)
297 fn report_cannot_move_from_borrowed_content(
299 move_place: &Place<'tcx>,
300 deref_target_place: &Place<'tcx>,
302 ) -> DiagnosticBuilder<'a> {
303 // Inspect the type of the content behind the
304 // borrow to provide feedback about why this
305 // was a move rather than a copy.
306 let ty = deref_target_place.ty(self.body, self.infcx.tcx).ty;
307 let upvar_field = self.prefixes(&move_place, PrefixSet::All)
308 .find_map(|p| self.is_upvar_field_projection(p));
310 let deref_base = match deref_target_place {
311 Place::Projection(box Projection { base, elem: ProjectionElem::Deref }) => base,
312 _ => bug!("deref_target_place is not a deref projection"),
315 if let Place::Base(PlaceBase::Local(local)) = *deref_base {
316 let decl = &self.body.local_decls[local];
317 if decl.is_ref_for_guard() {
318 let mut err = self.cannot_move_out_of(
320 &format!("`{}` in pattern guard", decl.name.unwrap()),
323 "variables bound in patterns cannot be moved from \
324 until after the end of the pattern guard");
329 debug!("report: ty={:?}", ty);
330 let mut err = match ty.sty {
331 ty::Array(..) | ty::Slice(..) =>
332 self.cannot_move_out_of_interior_noncopy(span, ty, None),
333 ty::Closure(def_id, closure_substs)
334 if def_id == self.mir_def_id && upvar_field.is_some()
336 let closure_kind_ty = closure_substs.closure_kind_ty(def_id, self.infcx.tcx);
337 let closure_kind = closure_kind_ty.to_opt_closure_kind();
338 let capture_description = match closure_kind {
339 Some(ty::ClosureKind::Fn) => {
340 "captured variable in an `Fn` closure"
342 Some(ty::ClosureKind::FnMut) => {
343 "captured variable in an `FnMut` closure"
345 Some(ty::ClosureKind::FnOnce) => {
346 bug!("closure kind does not match first argument type")
348 None => bug!("closure kind not inferred by borrowck"),
351 let upvar = &self.upvars[upvar_field.unwrap().index()];
352 let upvar_hir_id = upvar.var_hir_id;
353 let upvar_name = upvar.name;
354 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
356 let place_name = self.describe_place(move_place).unwrap();
358 let place_description = if self.is_upvar_field_projection(move_place).is_some() {
359 format!("`{}`, a {}", place_name, capture_description)
362 "`{}`, as `{}` is a {}",
370 "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
371 closure_kind_ty, closure_kind, place_description,
374 let mut diag = self.cannot_move_out_of(span, &place_description);
376 diag.span_label(upvar_span, "captured outer variable");
381 let source = self.borrowed_content_source(deref_base);
382 match (self.describe_place(move_place), source.describe_for_named_place()) {
383 (Some(place_desc), Some(source_desc)) => {
384 self.cannot_move_out_of(
386 &format!("`{}` which is behind a {}", place_desc, source_desc),
390 self.cannot_move_out_of(
392 &source.describe_for_unnamed_place(),
398 let move_ty = format!(
400 move_place.ty(self.body, self.infcx.tcx).ty,
402 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
403 let is_option = move_ty.starts_with("std::option::Option");
404 let is_result = move_ty.starts_with("std::result::Result");
405 if is_option || is_result {
408 &format!("consider borrowing the `{}`'s content", if is_option {
413 format!("{}.as_ref()", snippet),
414 Applicability::MaybeIncorrect,
422 error: GroupedMoveError<'tcx>,
423 err: &mut DiagnosticBuilder<'a>,
426 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
428 GroupedMoveError::MovesFromPlace {
435 "consider borrowing here",
436 format!("&{}", snippet),
437 Applicability::Unspecified,
440 if binds_to.is_empty() {
441 let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
442 let place_desc = match self.describe_place(&move_from) {
443 Some(desc) => format!("`{}`", desc),
444 None => format!("value"),
447 self.note_type_does_not_implement_copy(
457 self.add_move_error_details(err, &binds_to);
460 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
463 self.add_move_error_suggestions(err, &binds_to);
464 self.add_move_error_details(err, &binds_to);
466 // No binding. Nothing to suggest.
467 GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
468 let span = use_spans.var_or_use();
469 let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
470 let place_desc = match self.describe_place(original_path) {
471 Some(desc) => format!("`{}`", desc),
472 None => format!("value"),
474 self.note_type_does_not_implement_copy(
481 use_spans.args_span_label(err, format!("move out of {} occurs here", place_desc));
482 use_spans.var_span_label(
484 format!("move occurs due to use{}", use_spans.describe()),
490 fn add_move_error_suggestions(
492 err: &mut DiagnosticBuilder<'a>,
495 let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
496 for local in binds_to {
497 let bind_to = &self.body.local_decls[*local];
499 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
503 ) = bind_to.is_user_variable {
504 let pat_snippet = self.infcx.tcx.sess.source_map()
505 .span_to_snippet(pat_span)
507 if pat_snippet.starts_with('&') {
508 let pat_snippet = pat_snippet[1..].trim_start();
511 if pat_snippet.starts_with("mut")
512 && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
514 suggestion = pat_snippet["mut".len()..].trim_start();
517 suggestion = pat_snippet;
523 suggestion.to_owned(),
528 suggestions.sort_unstable_by_key(|&(span, _, _)| span);
529 suggestions.dedup_by_key(|&mut (span, _, _)| span);
530 for (span, to_remove, suggestion) in suggestions {
533 &format!("consider removing the `{}`", to_remove),
535 Applicability::MachineApplicable,
540 fn add_move_error_details(
542 err: &mut DiagnosticBuilder<'a>,
545 let mut noncopy_var_spans = Vec::new();
546 for (j, local) in binds_to.into_iter().enumerate() {
547 let bind_to = &self.body.local_decls[*local];
548 let binding_span = bind_to.source_info.span;
551 err.span_label(binding_span, "data moved here");
553 err.span_label(binding_span, "...and here");
556 if binds_to.len() == 1 {
557 self.note_type_does_not_implement_copy(
559 &format!("`{}`", bind_to.name.unwrap()),
564 noncopy_var_spans.push(binding_span);
568 if binds_to.len() > 1 {
571 "move occurs because these variables have types that \
572 don't implement the `Copy` trait",