3 use rustc_errors::{DiagnosticBuilder,Applicability};
6 use crate::borrow_check::MirBorrowckCtxt;
7 use crate::borrow_check::prefixes::PrefixSet;
8 use crate::borrow_check::error_reporting::UseSpans;
9 use crate::dataflow::move_paths::{
10 IllegalMoveOrigin, IllegalMoveOriginKind,
11 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 {
85 cannot_move_out_of: IllegalMoveOrigin { location, kind },
87 // Note: that the only time we assign a place isn't a temporary
88 // to a user variable is when initializing it.
89 // If that ever stops being the case, then the ever initialized
90 // flow could be used.
91 if let Some(StatementKind::Assign(
92 box(place, 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 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
109 opt_match_place: Some((ref opt_match_place, match_span)),
114 ))) = 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,
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.as_ref()) {
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.as_ref()) {
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.as_ref()));
245 IllegalMoveOriginKind::Static => {
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 description = if place.projection.len() == 1 {
277 format!("static item `{}`", self.describe_place(place.as_ref()).unwrap())
279 let base_static = PlaceRef {
281 projection: &[ProjectionElem::Deref],
285 "`{:?}` as `{:?}` is a static item",
286 self.describe_place(place.as_ref()).unwrap(),
287 self.describe_place(base_static).unwrap(),
291 self.cannot_move_out_of(span, &description)
294 fn report_cannot_move_from_borrowed_content(
296 move_place: &Place<'tcx>,
297 deref_target_place: &Place<'tcx>,
299 ) -> DiagnosticBuilder<'a> {
300 // Inspect the type of the content behind the
301 // borrow to provide feedback about why this
302 // was a move rather than a copy.
303 let ty = deref_target_place.ty(&*self.body, self.infcx.tcx).ty;
304 let upvar_field = self.prefixes(move_place.as_ref(), PrefixSet::All)
305 .find_map(|p| self.is_upvar_field_projection(p));
307 let deref_base = match deref_target_place.projection.as_ref() {
308 &[ref proj_base @ .., ProjectionElem::Deref] => {
310 base: &deref_target_place.base,
311 projection: &proj_base,
314 _ => bug!("deref_target_place is not a deref projection"),
318 base: PlaceBase::Local(local),
321 let decl = &self.body.local_decls[*local];
322 if decl.is_ref_for_guard() {
323 let mut err = self.cannot_move_out_of(
325 &format!("`{}` in pattern guard", self.local_names[*local].unwrap()),
328 "variables bound in patterns cannot be moved from \
329 until after the end of the pattern guard");
331 } else if decl.is_ref_to_static() {
332 return self.report_cannot_move_from_static(move_place, span);
336 debug!("report: ty={:?}", ty);
337 let mut err = match ty.kind {
338 ty::Array(..) | ty::Slice(..) =>
339 self.cannot_move_out_of_interior_noncopy(span, ty, None),
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
344 .as_closure().kind_ty(def_id, self.infcx.tcx);
345 let closure_kind = closure_kind_ty.to_opt_closure_kind();
346 let capture_description = match closure_kind {
347 Some(ty::ClosureKind::Fn) => {
348 "captured variable in an `Fn` closure"
350 Some(ty::ClosureKind::FnMut) => {
351 "captured variable in an `FnMut` closure"
353 Some(ty::ClosureKind::FnOnce) => {
354 bug!("closure kind does not match first argument type")
356 None => bug!("closure kind not inferred by borrowck"),
359 let upvar = &self.upvars[upvar_field.unwrap().index()];
360 let upvar_hir_id = upvar.var_hir_id;
361 let upvar_name = upvar.name;
362 let upvar_span = self.infcx.tcx.hir().span(upvar_hir_id);
364 let place_name = self.describe_place(move_place.as_ref()).unwrap();
366 let place_description = if self
367 .is_upvar_field_projection(move_place.as_ref())
370 format!("`{}`, a {}", place_name, capture_description)
373 "`{}`, as `{}` is a {}",
381 "report: closure_kind_ty={:?} closure_kind={:?} place_description={:?}",
382 closure_kind_ty, closure_kind, place_description,
385 let mut diag = self.cannot_move_out_of(span, &place_description);
387 diag.span_label(upvar_span, "captured outer variable");
392 let source = self.borrowed_content_source(deref_base);
394 self.describe_place(move_place.as_ref()),
395 source.describe_for_named_place(),
397 (Some(place_desc), Some(source_desc)) => {
398 self.cannot_move_out_of(
400 &format!("`{}` which is behind a {}", place_desc, source_desc),
404 self.cannot_move_out_of(
406 &source.describe_for_unnamed_place(),
412 let move_ty = format!(
414 move_place.ty(&*self.body, self.infcx.tcx).ty,
416 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
417 let is_option = move_ty.starts_with("std::option::Option");
418 let is_result = move_ty.starts_with("std::result::Result");
419 if is_option || is_result {
422 &format!("consider borrowing the `{}`'s content", if is_option {
427 format!("{}.as_ref()", snippet),
428 Applicability::MaybeIncorrect,
437 error: GroupedMoveError<'tcx>,
438 err: &mut DiagnosticBuilder<'a>,
442 GroupedMoveError::MovesFromPlace {
447 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
450 "consider borrowing here",
451 format!("&{}", snippet),
452 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_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_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];
514 if let LocalInfo::User(
515 ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
519 ) = bind_to.local_info {
520 if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
522 if pat_snippet.starts_with('&') {
523 let pat_snippet = pat_snippet[1..].trim_start();
526 if pat_snippet.starts_with("mut")
527 && pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
529 suggestion = pat_snippet["mut".len()..].trim_start();
532 suggestion = pat_snippet;
538 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 for (j, local) in binds_to.into_iter().enumerate() {
562 let bind_to = &self.body.local_decls[*local];
563 let binding_span = bind_to.source_info.span;
566 err.span_label(binding_span, "data moved here");
568 err.span_label(binding_span, "...and here");
571 if binds_to.len() == 1 {
572 self.note_type_does_not_implement_copy(
574 &format!("`{}`", self.local_names[*local].unwrap()),
581 if binds_to.len() > 1 {
582 err.note("move occurs because these variables have types that \
583 don't implement the `Copy` trait",