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,
15 use crate::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 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
59 pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
60 let grouped_errors = self.group_move_errors(move_errors);
61 for error in grouped_errors {
68 errors: Vec<(Place<'tcx>, MoveError<'tcx>)>
69 ) -> Vec<GroupedMoveError<'tcx>> {
70 let mut grouped_errors = Vec::new();
71 for (original_path, error) in errors {
72 self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
77 fn append_to_grouped_errors(
79 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
80 original_path: Place<'tcx>,
81 error: MoveError<'tcx>,
84 MoveError::UnionMove { .. } => {
85 unimplemented!("don't know how to report union move errors yet.")
87 MoveError::IllegalMove {
88 cannot_move_out_of: IllegalMoveOrigin { location, kind },
90 // Note: that the only time we assign a place isn't a temporary
91 // to a user variable is when initializing it.
92 // If that ever stops being the case, then the ever initialized
93 // flow could be used.
94 if let Some(StatementKind::Assign(
95 Place::Base(PlaceBase::Local(local)),
96 box Rvalue::Use(Operand::Move(move_from)),
97 )) = self.body.basic_blocks()[location.block]
99 .get(location.statement_index)
100 .map(|stmt| &stmt.kind)
102 let local_decl = &self.body.local_decls[*local];
103 // opt_match_place is the
104 // match_span is the span of the expression being matched on
105 // match *x.y { ... } match_place is Some(*x.y)
106 // ^^^^ match_span is the span of *x.y
108 // opt_match_place is None for let [mut] x = ... statements,
109 // whether or not the right-hand side is a place expression
110 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
111 opt_match_place: Some((ref opt_match_place, match_span)),
115 }))) = local_decl.is_user_variable
117 let stmt_source_info = self.body.source_info(location);
118 self.append_binding_error(
126 stmt_source_info.span,
132 let move_spans = self.move_spans(&original_path, location);
133 grouped_errors.push(GroupedMoveError::OtherIllegalMove {
134 use_spans: move_spans,
142 fn append_binding_error(
144 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
145 kind: IllegalMoveOriginKind<'tcx>,
146 original_path: Place<'tcx>,
147 move_from: &Place<'tcx>,
149 match_place: &Option<Place<'tcx>>,
151 statement_span: Span,
154 "append_binding_error(match_place={:?}, match_span={:?})",
155 match_place, match_span
158 let from_simple_let = match_place.is_none();
159 let match_place = match_place.as_ref().unwrap_or(move_from);
161 match self.move_data.rev_lookup.find(match_place) {
162 // Error with the match place
163 LookupResult::Parent(_) => {
164 for ge in &mut *grouped_errors {
165 if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
166 if match_span == *span {
167 debug!("appending local({:?}) to list", bind_to);
168 if !binds_to.is_empty() {
169 binds_to.push(bind_to);
175 debug!("found a new move error location");
177 // Don't need to point to x in let x = ... .
178 let (binds_to, span) = if from_simple_let {
179 (vec![], statement_span)
181 (vec![bind_to], match_span)
183 grouped_errors.push(GroupedMoveError::MovesFromPlace {
185 move_from: match_place.clone(),
191 // Error with the pattern
192 LookupResult::Exact(_) => {
193 let mpi = match self.move_data.rev_lookup.find(move_from) {
194 LookupResult::Parent(Some(mpi)) => mpi,
195 // move_from should be a projection from match_place.
196 _ => unreachable!("Probably not unreachable..."),
198 for ge in &mut *grouped_errors {
199 if let GroupedMoveError::MovesFromValue {
201 move_from: other_mpi,
206 if match_span == *span && mpi == *other_mpi {
207 debug!("appending local({:?}) to list", bind_to);
208 binds_to.push(bind_to);
213 debug!("found a new move error location");
214 grouped_errors.push(GroupedMoveError::MovesFromValue {
219 binds_to: vec![bind_to],
225 fn report(&mut self, error: GroupedMoveError<'tcx>) {
226 let (mut err, err_span) = {
227 let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind<'_>) =
229 GroupedMoveError::MovesFromPlace { span, ref original_path, ref kind, .. } |
230 GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } => {
231 (span, original_path, kind)
233 GroupedMoveError::OtherIllegalMove {
238 (use_spans.args_or_use(), original_path, kind)
241 debug!("report: original_path={:?} span={:?}, kind={:?} \
242 original_path.is_upvar_field_projection={:?}", original_path, span, kind,
243 self.is_upvar_field_projection(original_path));
246 IllegalMoveOriginKind::Static => {
247 self.report_cannot_move_from_static(original_path, span)
249 IllegalMoveOriginKind::BorrowedContent { target_place } => {
250 self.report_cannot_move_from_borrowed_content(
256 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
258 .cannot_move_out_of_interior_of_drop(span, ty, Origin::Mir)
260 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } =>
261 self.infcx.tcx.cannot_move_out_of_interior_noncopy(
262 span, ty, Some(*is_index), Origin::Mir
269 self.add_move_hints(error, &mut err, err_span);
270 err.buffer(&mut self.errors_buffer);
273 fn report_cannot_move_from_static(
277 ) -> DiagnosticBuilder<'a> {
278 let mut base_static = place;
281 Place::Base(_) => break,
282 Place::Projection(box Projection { base, .. }) => base_static = base,
286 let description = if let Place::Base(_) = place {
287 format!("static item `{}`", self.describe_place(place).unwrap())
290 "`{:?}` as `{:?}` is a static item",
291 self.describe_place(place).unwrap(),
292 self.describe_place(base_static).unwrap(),
296 self.infcx.tcx.cannot_move_out_of(span, &description, Origin::Mir)
299 fn report_cannot_move_from_borrowed_content(
301 move_place: &Place<'tcx>,
302 deref_target_place: &Place<'tcx>,
304 ) -> DiagnosticBuilder<'a> {
305 let origin = Origin::Mir;
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, PrefixSet::All)
312 .find_map(|p| self.is_upvar_field_projection(p));
314 let deref_base = match deref_target_place {
315 Place::Projection(box Projection { base, elem: ProjectionElem::Deref }) => base,
316 _ => bug!("deref_target_place is not a deref projection"),
319 if let Place::Base(PlaceBase::Local(local)) = *deref_base {
320 let decl = &self.body.local_decls[local];
321 if decl.is_ref_for_guard() {
322 let mut err = self.infcx.tcx.cannot_move_out_of(
324 &format!("`{}` in pattern guard", decl.name.unwrap()),
328 "variables bound in patterns cannot be moved from \
329 until after the end of the pattern guard");
334 debug!("report: ty={:?}", ty);
335 let mut err = match ty.sty {
336 ty::Array(..) | ty::Slice(..) =>
337 self.infcx.tcx.cannot_move_out_of_interior_noncopy(
338 span, ty, None, origin
340 ty::Closure(def_id, closure_substs)
341 if def_id == self.mir_def_id && upvar_field.is_some()
343 let closure_kind_ty = closure_substs.closure_kind_ty(def_id, self.infcx.tcx);
344 let closure_kind = closure_kind_ty.to_opt_closure_kind();
345 let capture_description = match closure_kind {
346 Some(ty::ClosureKind::Fn) => {
347 "captured variable in an `Fn` closure"
349 Some(ty::ClosureKind::FnMut) => {
350 "captured variable in an `FnMut` closure"
352 Some(ty::ClosureKind::FnOnce) => {
353 bug!("closure kind does not match first argument type")
355 None => bug!("closure kind not inferred by borrowck"),
358 let upvar = &self.upvars[upvar_field.unwrap().index()];
359 let upvar_hir_id = upvar.var_hir_id;
360 let upvar_name = upvar.name;
361 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
363 let place_name = self.describe_place(move_place).unwrap();
365 let place_description = if self.is_upvar_field_projection(move_place).is_some() {
366 format!("`{}`, a {}", place_name, capture_description)
369 "`{}`, as `{}` is a {}",
377 "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
378 closure_kind_ty, closure_kind, place_description,
381 let mut diag = self.infcx.tcx.cannot_move_out_of(span, &place_description, origin);
383 diag.span_label(upvar_span, "captured outer variable");
388 let source = self.borrowed_content_source(deref_base);
389 match (self.describe_place(move_place), source.describe_for_named_place()) {
390 (Some(place_desc), Some(source_desc)) => {
391 self.infcx.tcx.cannot_move_out_of(
393 &format!("`{}` which is behind a {}", place_desc, source_desc),
398 self.infcx.tcx.cannot_move_out_of(
400 &source.describe_for_unnamed_place(),
407 let move_ty = format!(
409 move_place.ty(self.body, self.infcx.tcx).ty,
411 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
412 let is_option = move_ty.starts_with("std::option::Option");
413 let is_result = move_ty.starts_with("std::result::Result");
414 if is_option || is_result {
417 &format!("consider borrowing the `{}`'s content", if is_option {
422 format!("{}.as_ref()", snippet),
423 Applicability::MaybeIncorrect,
431 error: GroupedMoveError<'tcx>,
432 err: &mut DiagnosticBuilder<'a>,
435 let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap();
437 GroupedMoveError::MovesFromPlace {
444 "consider borrowing here",
445 format!("&{}", snippet),
446 Applicability::Unspecified,
449 if binds_to.is_empty() {
450 let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
451 let place_desc = match self.describe_place(&move_from) {
452 Some(desc) => format!("`{}`", desc),
453 None => format!("value"),
456 self.note_type_does_not_implement_copy(
466 self.add_move_error_details(err, &binds_to);
469 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
472 self.add_move_error_suggestions(err, &binds_to);
473 self.add_move_error_details(err, &binds_to);
475 // No binding. Nothing to suggest.
476 GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
477 let span = use_spans.var_or_use();
478 let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
479 let place_desc = match self.describe_place(original_path) {
480 Some(desc) => format!("`{}`", desc),
481 None => format!("value"),
483 self.note_type_does_not_implement_copy(
490 use_spans.args_span_label(err, format!("move out of {} occurs here", place_desc));
491 use_spans.var_span_label(
493 format!("move occurs due to use{}", use_spans.describe()),
499 fn add_move_error_suggestions(
501 err: &mut DiagnosticBuilder<'a>,
504 let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
505 for local in binds_to {
506 let bind_to = &self.body.local_decls[*local];
508 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
512 ) = bind_to.is_user_variable {
513 let pat_snippet = self.infcx.tcx.sess.source_map()
514 .span_to_snippet(pat_span)
516 if pat_snippet.starts_with('&') {
517 let pat_snippet = pat_snippet[1..].trim_start();
520 if pat_snippet.starts_with("mut")
521 && pat_snippet["mut".len()..].starts_with(Pattern_White_Space)
523 suggestion = pat_snippet["mut".len()..].trim_start();
526 suggestion = pat_snippet;
532 suggestion.to_owned(),
537 suggestions.sort_unstable_by_key(|&(span, _, _)| span);
538 suggestions.dedup_by_key(|&mut (span, _, _)| span);
539 for (span, to_remove, suggestion) in suggestions {
542 &format!("consider removing the `{}`", to_remove),
544 Applicability::MachineApplicable,
549 fn add_move_error_details(
551 err: &mut DiagnosticBuilder<'a>,
554 let mut noncopy_var_spans = Vec::new();
555 for (j, local) in binds_to.into_iter().enumerate() {
556 let bind_to = &self.body.local_decls[*local];
557 let binding_span = bind_to.source_info.span;
560 err.span_label(binding_span, "data moved here");
562 err.span_label(binding_span, "...and here");
565 if binds_to.len() == 1 {
566 self.note_type_does_not_implement_copy(
568 &format!("`{}`", bind_to.name.unwrap()),
573 noncopy_var_spans.push(binding_span);
577 if binds_to.len() > 1 {
580 "move occurs because these variables have types that \
581 don't implement the `Copy` trait",