1 use rustc_errors::{Applicability, DiagnosticBuilder};
2 use rustc_middle::mir::*;
4 use rustc_span::source_map::DesugaringKind;
5 use rustc_span::{Span, Symbol};
7 use crate::borrow_check::diagnostics::UseSpans;
8 use crate::borrow_check::prefixes::PrefixSet;
9 use crate::borrow_check::MirBorrowckCtxt;
10 use crate::dataflow::move_paths::{
11 IllegalMoveOrigin, IllegalMoveOriginKind, LookupResult, MoveError, MovePathIndex,
14 // Often when desugaring a pattern match we may have many individual moves in
15 // MIR that are all part of one operation from the user's point-of-view. For
20 // would move x from the 0 field of some temporary, and y from the 1 field. We
21 // group such errors together for cleaner error reporting.
23 // Errors are kept separate if they are from places with different parent move
24 // paths. For example, this generates two errors:
26 // let (&x, &y) = (&String::new(), &String::new());
28 enum GroupedMoveError<'tcx> {
29 // Place expression can't be moved from,
30 // e.g., match x[0] { s => (), } where x: &[String]
32 original_path: Place<'tcx>,
34 move_from: Place<'tcx>,
35 kind: IllegalMoveOriginKind<'tcx>,
38 // Part of a value expression can't be moved from,
39 // e.g., match &String::new() { &x => (), }
41 original_path: Place<'tcx>,
43 move_from: MovePathIndex,
44 kind: IllegalMoveOriginKind<'tcx>,
47 // Everything that isn't from pattern matching.
49 original_path: Place<'tcx>,
51 kind: IllegalMoveOriginKind<'tcx>,
55 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
56 pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
57 let grouped_errors = self.group_move_errors(move_errors);
58 for error in grouped_errors {
65 errors: Vec<(Place<'tcx>, MoveError<'tcx>)>,
66 ) -> Vec<GroupedMoveError<'tcx>> {
67 let mut grouped_errors = Vec::new();
68 for (original_path, error) in errors {
69 self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
74 fn append_to_grouped_errors(
76 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
77 original_path: Place<'tcx>,
78 error: MoveError<'tcx>,
81 MoveError::UnionMove { .. } => {
82 unimplemented!("don't know how to report union move errors yet.")
84 MoveError::IllegalMove { cannot_move_out_of: IllegalMoveOrigin { location, kind } } => {
85 // Note: that the only time we assign a place isn't a temporary
86 // to a user variable is when initializing it.
87 // If that ever stops being the case, then the ever initialized
88 // flow could be used.
89 if let Some(StatementKind::Assign(box (
91 Rvalue::Use(Operand::Move(move_from)),
92 ))) = self.body.basic_blocks()[location.block]
94 .get(location.statement_index)
95 .map(|stmt| &stmt.kind)
97 if let Some(local) = place.as_local() {
98 let local_decl = &self.body.local_decls[local];
99 // opt_match_place is the
100 // match_span is the span of the expression being matched on
101 // match *x.y { ... } match_place is Some(*x.y)
102 // ^^^^ match_span is the span of *x.y
104 // opt_match_place is None for let [mut] x = ... statements,
105 // whether or not the right-hand side is a place expression
106 if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
108 opt_match_place: Some((opt_match_place, match_span)),
113 ))) = local_decl.local_info
115 let stmt_source_info = self.body.source_info(location);
116 self.append_binding_error(
124 stmt_source_info.span,
131 let move_spans = self.move_spans(original_path.as_ref(), 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,
152 debug!("append_binding_error(match_place={:?}, match_span={:?})", match_place, match_span);
154 let from_simple_let = match_place.is_none();
155 let match_place = match_place.unwrap_or(move_from);
157 match self.move_data.rev_lookup.find(match_place.as_ref()) {
158 // Error with the match place
159 LookupResult::Parent(_) => {
160 for ge in &mut *grouped_errors {
161 if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
162 if match_span == *span {
163 debug!("appending local({:?}) to list", bind_to);
164 if !binds_to.is_empty() {
165 binds_to.push(bind_to);
171 debug!("found a new move error location");
173 // Don't need to point to x in let x = ... .
174 let (binds_to, span) = if from_simple_let {
175 (vec![], statement_span)
177 (vec![bind_to], match_span)
179 grouped_errors.push(GroupedMoveError::MovesFromPlace {
187 // Error with the pattern
188 LookupResult::Exact(_) => {
189 let mpi = match self.move_data.rev_lookup.find(move_from.as_ref()) {
190 LookupResult::Parent(Some(mpi)) => mpi,
191 // move_from should be a projection from match_place.
192 _ => unreachable!("Probably not unreachable..."),
194 for ge in &mut *grouped_errors {
195 if let GroupedMoveError::MovesFromValue {
197 move_from: other_mpi,
202 if match_span == *span && mpi == *other_mpi {
203 debug!("appending local({:?}) to list", bind_to);
204 binds_to.push(bind_to);
209 debug!("found a new move error location");
210 grouped_errors.push(GroupedMoveError::MovesFromValue {
215 binds_to: vec![bind_to],
221 fn report(&mut self, error: GroupedMoveError<'tcx>) {
222 let (mut err, err_span) = {
223 let (span, use_spans, original_path, kind): (
227 &IllegalMoveOriginKind<'_>,
229 GroupedMoveError::MovesFromPlace { span, original_path, ref kind, .. }
230 | GroupedMoveError::MovesFromValue { span, original_path, ref kind, .. } => {
231 (span, None, original_path, kind)
233 GroupedMoveError::OtherIllegalMove { use_spans, original_path, ref kind } => {
234 (use_spans.args_or_use(), Some(use_spans), original_path, kind)
238 "report: original_path={:?} span={:?}, kind={:?} \
239 original_path.is_upvar_field_projection={:?}",
243 self.is_upvar_field_projection(original_path.as_ref())
247 IllegalMoveOriginKind::BorrowedContent { target_place } => self
248 .report_cannot_move_from_borrowed_content(
254 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
255 self.cannot_move_out_of_interior_of_drop(span, ty)
257 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => {
258 self.cannot_move_out_of_interior_noncopy(span, ty, Some(*is_index))
265 self.add_move_hints(error, &mut err, err_span);
266 err.buffer(&mut self.errors_buffer);
269 fn report_cannot_move_from_static(
273 ) -> DiagnosticBuilder<'a> {
274 let description = if place.projection.len() == 1 {
275 format!("static item {}", self.describe_any_place(place.as_ref()))
277 let base_static = PlaceRef { local: place.local, projection: &[ProjectionElem::Deref] };
280 "{} as {} is a static item",
281 self.describe_any_place(place.as_ref()),
282 self.describe_any_place(base_static),
286 self.cannot_move_out_of(span, &description)
289 fn report_cannot_move_from_borrowed_content(
291 move_place: Place<'tcx>,
292 deref_target_place: Place<'tcx>,
294 use_spans: Option<UseSpans>,
295 ) -> DiagnosticBuilder<'a> {
296 // Inspect the type of the content behind the
297 // borrow to provide feedback about why this
298 // was a move rather than a copy.
299 let ty = deref_target_place.ty(self.body, self.infcx.tcx).ty;
300 let upvar_field = self
301 .prefixes(move_place.as_ref(), PrefixSet::All)
302 .find_map(|p| self.is_upvar_field_projection(p));
304 let deref_base = match deref_target_place.projection.as_ref() {
305 &[ref proj_base @ .., ProjectionElem::Deref] => {
306 PlaceRef { local: deref_target_place.local, projection: &proj_base }
308 _ => bug!("deref_target_place is not a deref projection"),
311 if let PlaceRef { local, projection: [] } = deref_base {
312 let decl = &self.body.local_decls[local];
313 if decl.is_ref_for_guard() {
314 let mut err = self.cannot_move_out_of(
316 &format!("`{}` in pattern guard", self.local_names[local].unwrap()),
319 "variables bound in patterns cannot be moved from \
320 until after the end of the pattern guard",
323 } else if decl.is_ref_to_static() {
324 return self.report_cannot_move_from_static(move_place, span);
328 debug!("report: ty={:?}", ty);
329 let mut err = match ty.kind {
330 ty::Array(..) | ty::Slice(..) => {
331 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.as_closure().kind_ty();
337 let closure_kind = closure_kind_ty.to_opt_closure_kind();
338 let capture_description = match closure_kind {
339 Some(ty::ClosureKind::Fn) => "captured variable in an `Fn` closure",
340 Some(ty::ClosureKind::FnMut) => "captured variable in an `FnMut` closure",
341 Some(ty::ClosureKind::FnOnce) => {
342 bug!("closure kind does not match first argument type")
344 None => bug!("closure kind not inferred by borrowck"),
347 let upvar = &self.upvars[upvar_field.unwrap().index()];
348 let upvar_hir_id = upvar.var_hir_id;
349 let upvar_name = upvar.name;
350 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
352 let place_name = self.describe_any_place(move_place.as_ref());
354 let place_description =
355 if self.is_upvar_field_projection(move_place.as_ref()).is_some() {
356 format!("{}, a {}", place_name, capture_description)
358 format!("{}, as `{}` is a {}", place_name, upvar_name, capture_description)
362 "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
363 closure_kind_ty, closure_kind, place_description,
366 let mut diag = self.cannot_move_out_of(span, &place_description);
368 diag.span_label(upvar_span, "captured outer variable");
373 let source = self.borrowed_content_source(deref_base);
374 match (self.describe_place(move_place.as_ref()), source.describe_for_named_place())
376 (Some(place_desc), Some(source_desc)) => self.cannot_move_out_of(
378 &format!("`{}` which is behind a {}", place_desc, source_desc),
380 (_, _) => self.cannot_move_out_of(
382 &source.describe_for_unnamed_place(self.infcx.tcx),
387 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
388 let def_id = match move_place.ty(self.body, self.infcx.tcx).ty.kind {
389 ty::Adt(self_def, _) => self_def.did,
391 | ty::FnDef(def_id, _)
392 | ty::Closure(def_id, _)
393 | ty::Generator(def_id, ..)
394 | ty::Opaque(def_id, _) => def_id,
398 self.infcx.tcx.is_diagnostic_item(Symbol::intern("option_type"), def_id);
400 self.infcx.tcx.is_diagnostic_item(Symbol::intern("result_type"), def_id);
401 if (is_option || is_result) && use_spans.map_or(true, |v| !v.for_closure()) {
405 "consider borrowing the `{}`'s content",
406 if is_option { "Option" } else { "Result" }
408 format!("{}.as_ref()", snippet),
409 Applicability::MaybeIncorrect,
411 } else if span.is_desugaring(DesugaringKind::ForLoop)
412 && self.infcx.tcx.is_diagnostic_item(Symbol::intern("vec_type"), def_id)
414 // FIXME: suggest for anything that implements `IntoIterator`.
417 "consider iterating over a slice of the `Vec<_>`'s content",
418 format!("&{}", snippet),
419 Applicability::MaybeIncorrect,
428 error: GroupedMoveError<'tcx>,
429 err: &mut DiagnosticBuilder<'a>,
433 GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
434 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
437 "consider borrowing here",
438 format!("&{}", snippet),
439 Applicability::Unspecified,
443 if binds_to.is_empty() {
444 let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
445 let place_desc = match self.describe_place(move_from.as_ref()) {
446 Some(desc) => format!("`{}`", desc),
447 None => "value".to_string(),
450 self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span));
455 self.add_move_error_details(err, &binds_to);
458 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
461 self.add_move_error_suggestions(err, &binds_to);
462 self.add_move_error_details(err, &binds_to);
464 // No binding. Nothing to suggest.
465 GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
466 let span = use_spans.var_or_use();
467 let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
468 let place_desc = match self.describe_place(original_path.as_ref()) {
469 Some(desc) => format!("`{}`", desc),
470 None => "value".to_string(),
472 self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span));
474 use_spans.args_span_label(err, format!("move out of {} occurs here", place_desc));
476 .var_span_label(err, format!("move occurs due to use{}", use_spans.describe()));
481 fn add_move_error_suggestions(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
482 let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
483 for local in binds_to {
484 let bind_to = &self.body.local_decls[*local];
485 if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
488 }))) = bind_to.local_info
490 if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
492 if pat_snippet.starts_with('&') {
493 let pat_snippet = pat_snippet[1..].trim_start();
494 let (suggestion, to_remove) = if pat_snippet.starts_with("mut")
495 && pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
497 (pat_snippet["mut".len()..].trim_start(), "&mut")
501 suggestions.push((pat_span, to_remove, suggestion.to_owned()));
506 suggestions.sort_unstable_by_key(|&(span, _, _)| span);
507 suggestions.dedup_by_key(|&mut (span, _, _)| span);
508 for (span, to_remove, suggestion) in suggestions {
511 &format!("consider removing the `{}`", to_remove),
513 Applicability::MachineApplicable,
518 fn add_move_error_details(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
519 for (j, local) in binds_to.iter().enumerate() {
520 let bind_to = &self.body.local_decls[*local];
521 let binding_span = bind_to.source_info.span;
524 err.span_label(binding_span, "data moved here");
526 err.span_label(binding_span, "...and here");
529 if binds_to.len() == 1 {
530 self.note_type_does_not_implement_copy(
532 &format!("`{}`", self.local_names[*local].unwrap()),
539 if binds_to.len() > 1 {
541 "move occurs because these variables have types that \
542 don't implement the `Copy` trait",