1 use rustc_errors::{Applicability, DiagnosticBuilder};
2 use rustc_infer::infer::TyCtxtInferExt;
3 use rustc_middle::mir::*;
5 use rustc_mir_dataflow::move_paths::{
6 IllegalMoveOrigin, IllegalMoveOriginKind, LookupResult, MoveError, MovePathIndex,
8 use rustc_span::{sym, Span, DUMMY_SP};
9 use rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions;
11 use crate::diagnostics::{FnSelfUseKind, UseSpans};
12 use crate::prefixes::PrefixSet;
13 use crate::MirBorrowckCtxt;
15 // Often when desugaring a pattern match we may have many individual moves in
16 // MIR that are all part of one operation from the user's point-of-view. For
21 // would move x from the 0 field of some temporary, and y from the 1 field. We
22 // group such errors together for cleaner error reporting.
24 // Errors are kept separate if they are from places with different parent move
25 // paths. For example, this generates two errors:
27 // let (&x, &y) = (&String::new(), &String::new());
29 enum GroupedMoveError<'tcx> {
30 // Place expression can't be moved from,
31 // e.g., match x[0] { s => (), } where x: &[String]
33 original_path: Place<'tcx>,
35 move_from: Place<'tcx>,
36 kind: IllegalMoveOriginKind<'tcx>,
39 // Part of a value expression can't be moved from,
40 // e.g., match &String::new() { &x => (), }
42 original_path: Place<'tcx>,
44 move_from: MovePathIndex,
45 kind: IllegalMoveOriginKind<'tcx>,
48 // Everything that isn't from pattern matching.
50 original_path: Place<'tcx>,
51 use_spans: UseSpans<'tcx>,
52 kind: IllegalMoveOriginKind<'tcx>,
56 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
57 pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
58 let grouped_errors = self.group_move_errors(move_errors);
59 for error in grouped_errors {
66 errors: Vec<(Place<'tcx>, MoveError<'tcx>)>,
67 ) -> Vec<GroupedMoveError<'tcx>> {
68 let mut grouped_errors = Vec::new();
69 for (original_path, error) in errors {
70 self.append_to_grouped_errors(&mut grouped_errors, original_path, error);
75 fn append_to_grouped_errors(
77 grouped_errors: &mut Vec<GroupedMoveError<'tcx>>,
78 original_path: Place<'tcx>,
79 error: MoveError<'tcx>,
82 MoveError::UnionMove { .. } => {
83 unimplemented!("don't know how to report union move errors yet.")
85 MoveError::IllegalMove { cannot_move_out_of: IllegalMoveOrigin { location, kind } } => {
86 // Note: that the only time we assign a place isn't a temporary
87 // to a user variable is when initializing it.
88 // If that ever stops being the case, then the ever initialized
89 // flow could be used.
90 if let Some(StatementKind::Assign(box (
92 Rvalue::Use(Operand::Move(move_from)),
93 ))) = self.body.basic_blocks()[location.block]
95 .get(location.statement_index)
96 .map(|stmt| &stmt.kind)
98 if let Some(local) = place.as_local() {
99 let local_decl = &self.body.local_decls[local];
100 // opt_match_place is the
101 // match_span is the span of the expression being matched on
102 // match *x.y { ... } match_place is Some(*x.y)
103 // ^^^^ match_span is the span of *x.y
105 // opt_match_place is None for let [mut] x = ... statements,
106 // whether or not the right-hand side is a place expression
107 if let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
109 opt_match_place: Some((opt_match_place, match_span)),
114 )))) = local_decl.local_info
116 let stmt_source_info = self.body.source_info(location);
117 self.append_binding_error(
125 stmt_source_info.span,
132 let move_spans = self.move_spans(original_path.as_ref(), 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,
153 debug!("append_binding_error(match_place={:?}, match_span={:?})", match_place, match_span);
155 let from_simple_let = match_place.is_none();
156 let match_place = match_place.unwrap_or(move_from);
158 match self.move_data.rev_lookup.find(match_place.as_ref()) {
159 // Error with the match place
160 LookupResult::Parent(_) => {
161 for ge in &mut *grouped_errors {
162 if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge {
163 if match_span == *span {
164 debug!("appending local({:?}) to list", bind_to);
165 if !binds_to.is_empty() {
166 binds_to.push(bind_to);
172 debug!("found a new move error location");
174 // Don't need to point to x in let x = ... .
175 let (binds_to, span) = if from_simple_let {
176 (vec![], statement_span)
178 (vec![bind_to], match_span)
180 grouped_errors.push(GroupedMoveError::MovesFromPlace {
188 // Error with the pattern
189 LookupResult::Exact(_) => {
190 let mpi = match self.move_data.rev_lookup.find(move_from.as_ref()) {
191 LookupResult::Parent(Some(mpi)) => mpi,
192 // move_from should be a projection from match_place.
193 _ => unreachable!("Probably not unreachable..."),
195 for ge in &mut *grouped_errors {
196 if let GroupedMoveError::MovesFromValue {
198 move_from: other_mpi,
203 if match_span == *span && mpi == *other_mpi {
204 debug!("appending local({:?}) to list", bind_to);
205 binds_to.push(bind_to);
210 debug!("found a new move error location");
211 grouped_errors.push(GroupedMoveError::MovesFromValue {
216 binds_to: vec![bind_to],
222 fn report(&mut self, error: GroupedMoveError<'tcx>) {
223 let (mut err, err_span) = {
224 let (span, use_spans, original_path, kind): (
226 Option<UseSpans<'tcx>>,
228 &IllegalMoveOriginKind<'_>,
230 GroupedMoveError::MovesFromPlace { span, original_path, ref kind, .. }
231 | GroupedMoveError::MovesFromValue { span, original_path, ref kind, .. } => {
232 (span, None, original_path, kind)
234 GroupedMoveError::OtherIllegalMove { use_spans, original_path, ref kind } => {
235 (use_spans.args_or_use(), Some(use_spans), original_path, kind)
239 "report: original_path={:?} span={:?}, kind={:?} \
240 original_path.is_upvar_field_projection={:?}",
244 self.is_upvar_field_projection(original_path.as_ref())
248 IllegalMoveOriginKind::BorrowedContent { target_place } => self
249 .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(span, ty, Some(*is_index))
266 self.add_move_hints(error, &mut err, err_span);
267 self.buffer_error(err);
270 fn report_cannot_move_from_static(
274 ) -> DiagnosticBuilder<'a> {
275 let description = if place.projection.len() == 1 {
276 format!("static item {}", self.describe_any_place(place.as_ref()))
278 let base_static = PlaceRef { local: place.local, projection: &[ProjectionElem::Deref] };
281 "{} as {} is a static item",
282 self.describe_any_place(place.as_ref()),
283 self.describe_any_place(base_static),
287 self.cannot_move_out_of(span, &description)
290 fn report_cannot_move_from_borrowed_content(
292 move_place: Place<'tcx>,
293 deref_target_place: Place<'tcx>,
295 use_spans: Option<UseSpans<'tcx>>,
296 ) -> DiagnosticBuilder<'a> {
297 // Inspect the type of the content behind the
298 // borrow to provide feedback about why this
299 // was a move rather than a copy.
300 let ty = deref_target_place.ty(self.body, self.infcx.tcx).ty;
301 let upvar_field = self
302 .prefixes(move_place.as_ref(), PrefixSet::All)
303 .find_map(|p| self.is_upvar_field_projection(p));
305 let deref_base = match deref_target_place.projection.as_ref() {
306 [proj_base @ .., ProjectionElem::Deref] => {
307 PlaceRef { local: deref_target_place.local, projection: &proj_base }
309 _ => bug!("deref_target_place is not a deref projection"),
312 if let PlaceRef { local, projection: [] } = deref_base {
313 let decl = &self.body.local_decls[local];
314 if decl.is_ref_for_guard() {
315 let mut err = self.cannot_move_out_of(
317 &format!("`{}` in pattern guard", self.local_names[local].unwrap()),
320 "variables bound in patterns cannot be moved from \
321 until after the end of the pattern guard",
324 } else if decl.is_ref_to_static() {
325 return self.report_cannot_move_from_static(move_place, span);
329 debug!("report: ty={:?}", ty);
330 let mut err = match ty.kind() {
331 ty::Array(..) | ty::Slice(..) => {
332 self.cannot_move_out_of_interior_noncopy(span, ty, None)
334 ty::Closure(def_id, closure_substs)
335 if def_id.as_local() == Some(self.mir_def_id()) && upvar_field.is_some() =>
337 let closure_kind_ty = closure_substs.as_closure().kind_ty();
338 let closure_kind = match closure_kind_ty.to_opt_closure_kind() {
339 Some(kind @ (ty::ClosureKind::Fn | ty::ClosureKind::FnMut)) => kind,
340 Some(ty::ClosureKind::FnOnce) => {
341 bug!("closure kind does not match first argument type")
343 None => bug!("closure kind not inferred by borrowck"),
345 let capture_description =
346 format!("captured variable in an `{}` closure", closure_kind);
348 let upvar = &self.upvars[upvar_field.unwrap().index()];
349 let upvar_hir_id = upvar.place.get_root_variable();
350 let upvar_name = upvar.place.to_string(self.infcx.tcx);
351 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
353 let place_name = self.describe_any_place(move_place.as_ref());
355 let place_description =
356 if self.is_upvar_field_projection(move_place.as_ref()).is_some() {
357 format!("{}, a {}", place_name, capture_description)
359 format!("{}, as `{}` is a {}", place_name, upvar_name, capture_description)
363 "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
364 closure_kind_ty, closure_kind, place_description,
367 let mut diag = self.cannot_move_out_of(span, &place_description);
369 diag.span_label(upvar_span, "captured outer variable");
372 format!("captured by this `{}` closure", closure_kind),
378 let source = self.borrowed_content_source(deref_base);
379 match (self.describe_place(move_place.as_ref()), source.describe_for_named_place())
381 (Some(place_desc), Some(source_desc)) => self.cannot_move_out_of(
383 &format!("`{}` which is behind a {}", place_desc, source_desc),
385 (_, _) => self.cannot_move_out_of(
387 &source.describe_for_unnamed_place(self.infcx.tcx),
392 let ty = move_place.ty(self.body, self.infcx.tcx).ty;
393 let def_id = match *ty.kind() {
394 ty::Adt(self_def, _) => self_def.did,
396 | ty::FnDef(def_id, _)
397 | ty::Closure(def_id, _)
398 | ty::Generator(def_id, ..)
399 | ty::Opaque(def_id, _) => def_id,
402 let diag_name = self.infcx.tcx.get_diagnostic_name(def_id);
403 if matches!(diag_name, Some(sym::Option | sym::Result))
404 && use_spans.map_or(true, |v| !v.for_closure())
406 err.span_suggestion_verbose(
408 &format!("consider borrowing the `{}`'s content", diag_name.unwrap()),
409 ".as_ref()".to_string(),
410 Applicability::MaybeIncorrect,
412 } else if let Some(UseSpans::FnSelfUse {
413 kind: FnSelfUseKind::Normal { implicit_into_iter: true, .. },
417 let suggest = match self.infcx.tcx.get_diagnostic_item(sym::IntoIterator) {
418 Some(def_id) => self.infcx.tcx.infer_ctxt().enter(|infcx| {
419 type_known_to_meet_bound_modulo_regions(
424 .mk_imm_ref(infcx.tcx.lifetimes.re_erased, infcx.tcx.erase_regions(ty)),
432 err.span_suggestion_verbose(
434 &format!("consider iterating over a slice of the `{}`'s content", ty),
436 Applicability::MaybeIncorrect,
445 error: GroupedMoveError<'tcx>,
446 err: &mut DiagnosticBuilder<'a>,
450 GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
451 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
454 "consider borrowing here",
455 format!("&{}", snippet),
456 Applicability::Unspecified,
460 if binds_to.is_empty() {
461 let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
462 let place_desc = match self.describe_place(move_from.as_ref()) {
463 Some(desc) => format!("`{}`", desc),
464 None => "value".to_string(),
467 self.note_type_does_not_implement_copy(
478 self.add_move_error_details(err, &binds_to);
481 GroupedMoveError::MovesFromValue { mut binds_to, .. } => {
484 self.add_move_error_suggestions(err, &binds_to);
485 self.add_move_error_details(err, &binds_to);
487 // No binding. Nothing to suggest.
488 GroupedMoveError::OtherIllegalMove { ref original_path, use_spans, .. } => {
489 let span = use_spans.var_or_use();
490 let place_ty = original_path.ty(self.body, self.infcx.tcx).ty;
491 let place_desc = match self.describe_place(original_path.as_ref()) {
492 Some(desc) => format!("`{}`", desc),
493 None => "value".to_string(),
495 self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span), "");
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()),
507 fn add_move_error_suggestions(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
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];
511 if let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
512 VarBindingForm { pat_span, .. },
513 )))) = bind_to.local_info
515 if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
517 if let Some(stripped) = pat_snippet.strip_prefix('&') {
518 let pat_snippet = stripped.trim_start();
519 let (suggestion, to_remove) = if pat_snippet.starts_with("mut")
520 && pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
522 (pat_snippet["mut".len()..].trim_start(), "&mut")
526 suggestions.push((pat_span, to_remove, suggestion.to_owned()));
531 suggestions.sort_unstable_by_key(|&(span, _, _)| span);
532 suggestions.dedup_by_key(|&mut (span, _, _)| span);
533 for (span, to_remove, suggestion) in suggestions {
536 &format!("consider removing the `{}`", to_remove),
538 Applicability::MachineApplicable,
543 fn add_move_error_details(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
544 for (j, local) in binds_to.iter().enumerate() {
545 let bind_to = &self.body.local_decls[*local];
546 let binding_span = bind_to.source_info.span;
549 err.span_label(binding_span, "data moved here");
551 err.span_label(binding_span, "...and here");
554 if binds_to.len() == 1 {
555 self.note_type_does_not_implement_copy(
557 &format!("`{}`", self.local_names[*local].unwrap()),
565 if binds_to.len() > 1 {
567 "move occurs because these variables have types that \
568 don't implement the `Copy` trait",