3 use rustc::mir::{self, BindingForm, Constant, ClearCrossCrate, Local, Location, Mir};
4 use rustc::mir::{Mutability, Operand, Place, PlaceBase, Projection, ProjectionElem, Static};
5 use rustc::mir::{Terminator, TerminatorKind};
6 use rustc::ty::{self, Const, DefIdTree, TyS, TyKind, TyCtxt};
7 use rustc_data_structures::indexed_vec::Idx;
9 use syntax_pos::symbol::keywords;
11 use crate::dataflow::move_paths::InitLocation;
12 use crate::borrow_check::MirBorrowckCtxt;
13 use crate::util::borrowck_errors::{BorrowckErrors, Origin};
14 use crate::util::collect_writes::FindAssignments;
15 use crate::util::suggest_ref_mut;
16 use rustc_errors::Applicability;
18 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
19 pub(super) enum AccessKind {
25 impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
26 pub(super) fn report_mutability_error(
28 access_place: &Place<'tcx>,
30 the_place_err: &Place<'tcx>,
31 error_access: AccessKind,
35 "report_mutability_error(\
36 access_place={:?}, span={:?}, the_place_err={:?}, error_access={:?}, location={:?},\
38 access_place, span, the_place_err, error_access, location,
44 let access_place_desc = self.describe_place(access_place);
45 debug!("report_mutability_error: access_place_desc={:?}", access_place_desc);
48 Place::Base(PlaceBase::Local(local)) => {
49 item_msg = format!("`{}`", access_place_desc.unwrap());
50 if let Place::Base(PlaceBase::Local(_)) = access_place {
51 reason = ", as it is not declared as mutable".to_string();
53 let name = self.mir.local_decls[*local]
55 .expect("immutable unnamed local");
56 reason = format!(", as `{}` is not declared as mutable", name);
60 Place::Projection(box Projection {
62 elem: ProjectionElem::Field(upvar_index, _),
64 debug_assert!(is_closure_or_generator(
65 base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx)
68 item_msg = format!("`{}`", access_place_desc.unwrap());
69 if access_place.is_upvar_field_projection(self.mir, &self.infcx.tcx).is_some() {
70 reason = ", as it is not declared as mutable".to_string();
72 let name = self.mir.upvar_decls[upvar_index.index()].debug_name;
73 reason = format!(", as `{}` is not declared as mutable", name);
77 Place::Projection(box Projection {
79 elem: ProjectionElem::Deref,
81 if *base == Place::Base(PlaceBase::Local(Local::new(1))) &&
82 !self.mir.upvar_decls.is_empty() {
83 item_msg = format!("`{}`", access_place_desc.unwrap());
84 debug_assert!(self.mir.local_decls[Local::new(1)].ty.is_region_ptr());
85 debug_assert!(is_closure_or_generator(
86 the_place_err.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx)
89 reason = if access_place.is_upvar_field_projection(self.mir,
90 &self.infcx.tcx).is_some() {
91 ", as it is a captured variable in a `Fn` closure".to_string()
93 ", as `Fn` closures cannot mutate their captured variables".to_string()
96 if let Place::Base(PlaceBase::Local(local)) = *base {
97 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard))
98 = self.mir.local_decls[local].is_user_variable {
107 item_msg = format!("`{}`", access_place_desc.unwrap());
108 reason = ", as it is immutable for the pattern guard".to_string();
111 if base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx).is_region_ptr() {
116 if let Some(desc) = access_place_desc {
117 item_msg = format!("`{}`", desc);
118 reason = match error_access {
120 AccessKind::Mutate => format!(" which is behind a {}", pointer_type),
121 AccessKind::MutableBorrow => {
122 format!(", as it is behind a {}", pointer_type)
126 item_msg = format!("data in a {}", pointer_type);
127 reason = String::new();
132 Place::Base(PlaceBase::Promoted(_)) => unreachable!(),
134 Place::Base(PlaceBase::Static(box Static { def_id, ty: _ })) => {
135 if let Place::Base(PlaceBase::Static(_)) = access_place {
136 item_msg = format!("immutable static item `{}`", access_place_desc.unwrap());
137 reason = String::new();
139 item_msg = format!("`{}`", access_place_desc.unwrap());
140 let static_name = &self.infcx.tcx.item_name(*def_id);
141 reason = format!(", as `{}` is an immutable static item", static_name);
145 Place::Projection(box Projection {
147 elem: ProjectionElem::Index(_),
149 | Place::Projection(box Projection {
151 elem: ProjectionElem::ConstantIndex { .. },
153 | Place::Projection(box Projection {
155 elem: ProjectionElem::Subslice { .. },
157 | Place::Projection(box Projection {
159 elem: ProjectionElem::Downcast(..),
160 }) => bug!("Unexpected immutable place."),
163 debug!("report_mutability_error: item_msg={:?}, reason={:?}", item_msg, reason);
165 // `act` and `acted_on` are strings that let us abstract over
166 // the verbs used in some diagnostic messages.
170 let span = match error_access {
171 AccessKind::Move => {
173 .cannot_move_out_of(span, &(item_msg + &reason), Origin::Mir);
174 err.span_label(span, "cannot move");
175 err.buffer(&mut self.errors_buffer);
178 AccessKind::Mutate => {
180 .cannot_assign(span, &(item_msg + &reason), Origin::Mir);
182 acted_on = "written";
185 AccessKind::MutableBorrow => {
186 act = "borrow as mutable";
187 acted_on = "borrowed as mutable";
189 let borrow_spans = self.borrow_spans(span, location);
190 let borrow_span = borrow_spans.args_or_use();
191 err = self.infcx.tcx.cannot_borrow_path_as_mutable_because(
197 borrow_spans.var_span_label(
200 "mutable borrow occurs due to use of `{}` in closure",
201 // always Some() if the message is printed.
202 self.describe_place(access_place).unwrap_or_default(),
209 debug!("report_mutability_error: act={:?}, acted_on={:?}", act, acted_on);
211 match the_place_err {
212 // Suggest making an existing shared borrow in a struct definition a mutable borrow.
214 // This is applicable when we have a deref of a field access to a deref of a local -
215 // something like `*((*_1).0`. The local that we get will be a reference to the
216 // struct we've got a field access of (it must be a reference since there's a deref
217 // after the field access).
218 Place::Projection(box Projection {
219 base: Place::Projection(box Projection {
220 base: Place::Projection(box Projection {
222 elem: ProjectionElem::Deref,
224 elem: ProjectionElem::Field(field, _),
226 elem: ProjectionElem::Deref,
228 err.span_label(span, format!("cannot {ACT}", ACT = act));
230 if let Some((span, message)) = annotate_struct_field(
232 base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx),
237 "consider changing this to be mutable",
239 Applicability::MaybeIncorrect,
244 // Suggest removing a `&mut` from the use of a mutable reference.
245 Place::Base(PlaceBase::Local(local))
247 self.mir.local_decls.get(*local).map(|local_decl| {
248 if let ClearCrossCrate::Set(
249 mir::BindingForm::ImplicitSelf(kind)
250 ) = local_decl.is_user_variable.as_ref().unwrap() {
251 // Check if the user variable is a `&mut self` and we can therefore
252 // suggest removing the `&mut`.
254 // Deliberately fall into this case for all implicit self types,
255 // so that we don't fall in to the next case with them.
256 *kind == mir::ImplicitSelfKind::MutRef
257 } else if Some(keywords::SelfLower.name()) == local_decl.name {
258 // Otherwise, check if the name is the self kewyord - in which case
259 // we have an explicit self. Do the same thing in this case and check
260 // for a `self: &mut Self` to suggest removing the `&mut`.
261 if let ty::TyKind::Ref(
262 _, _, hir::Mutability::MutMutable
263 ) = local_decl.ty.sty {
274 err.span_label(span, format!("cannot {ACT}", ACT = act));
275 err.span_label(span, "try removing `&mut` here");
278 // We want to suggest users use `let mut` for local (user
279 // variable) mutations...
280 Place::Base(PlaceBase::Local(local))
281 if self.mir.local_decls[*local].can_be_made_mutable() => {
282 // ... but it doesn't make sense to suggest it on
283 // variables that are `ref x`, `ref mut x`, `&self`,
284 // or `&mut self` (such variables are simply not
286 let local_decl = &self.mir.local_decls[*local];
287 assert_eq!(local_decl.mutability, Mutability::Not);
289 err.span_label(span, format!("cannot {ACT}", ACT = act));
291 local_decl.source_info.span,
292 "consider changing this to be mutable",
293 format!("mut {}", local_decl.name.unwrap()),
294 Applicability::MachineApplicable,
298 // Also suggest adding mut for upvars
299 Place::Projection(box Projection {
301 elem: ProjectionElem::Field(upvar_index, _),
303 debug_assert!(is_closure_or_generator(
304 base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx)
307 err.span_label(span, format!("cannot {ACT}", ACT = act));
309 let upvar_hir_id = self.mir.upvar_decls[upvar_index.index()]
311 .assert_crate_local();
312 let upvar_node_id = self.infcx.tcx.hir().hir_to_node_id(upvar_hir_id);
313 if let Some(Node::Binding(pat)) = self.infcx.tcx.hir().find(upvar_node_id) {
314 if let hir::PatKind::Binding(
315 hir::BindingAnnotation::Unannotated,
323 "consider changing this to be mutable",
324 format!("mut {}", upvar_ident.name),
325 Applicability::MachineApplicable,
331 // complete hack to approximate old AST-borrowck
332 // diagnostic: if the span starts with a mutable borrow of
333 // a local variable, then just suggest the user remove it.
334 Place::Base(PlaceBase::Local(_))
336 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
337 snippet.starts_with("&mut ")
343 err.span_label(span, format!("cannot {ACT}", ACT = act));
344 err.span_label(span, "try removing `&mut` here");
347 Place::Projection(box Projection {
348 base: Place::Base(PlaceBase::Local(local)),
349 elem: ProjectionElem::Deref,
351 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
352 self.mir.local_decls[*local].is_user_variable
360 err.span_label(span, format!("cannot {ACT}", ACT = act));
362 "variables bound in patterns are immutable until the end of the pattern guard",
366 // We want to point out when a `&` can be readily replaced
369 // FIXME: can this case be generalized to work for an
370 // arbitrary base for the projection?
371 Place::Projection(box Projection {
372 base: Place::Base(PlaceBase::Local(local)),
373 elem: ProjectionElem::Deref,
374 }) if self.mir.local_decls[*local].is_user_variable.is_some() =>
376 let local_decl = &self.mir.local_decls[*local];
377 let suggestion = match local_decl.is_user_variable.as_ref().unwrap() {
378 ClearCrossCrate::Set(mir::BindingForm::ImplicitSelf(_)) => {
379 Some(suggest_ampmut_self(self.infcx.tcx, local_decl))
382 ClearCrossCrate::Set(mir::BindingForm::Var(mir::VarBindingForm {
383 binding_mode: ty::BindingMode::BindByValue(_),
386 })) => Some(suggest_ampmut(
394 ClearCrossCrate::Set(mir::BindingForm::Var(mir::VarBindingForm {
395 binding_mode: ty::BindingMode::BindByReference(_),
398 let pattern_span = local_decl.source_info.span;
399 suggest_ref_mut(self.infcx.tcx, pattern_span)
400 .map(|replacement| (pattern_span, replacement))
403 ClearCrossCrate::Set(mir::BindingForm::RefForGuard) => unreachable!(),
405 ClearCrossCrate::Clear => bug!("saw cleared local state"),
408 let (pointer_sigil, pointer_desc) = if local_decl.ty.is_region_ptr() {
411 ("*const", "pointer")
414 if let Some((err_help_span, suggested_code)) = suggestion {
417 &format!("consider changing this to be a mutable {}", pointer_desc),
419 Applicability::MachineApplicable,
423 if let Some(name) = local_decl.name {
427 "`{NAME}` is a `{SIGIL}` {DESC}, \
428 so the data it refers to cannot be {ACTED_ON}",
430 SIGIL = pointer_sigil,
439 "cannot {ACT} through `{SIGIL}` {DESC}",
441 SIGIL = pointer_sigil,
448 Place::Projection(box Projection {
450 elem: ProjectionElem::Deref,
451 }) if *base == Place::Base(PlaceBase::Local(Local::new(1))) &&
452 !self.mir.upvar_decls.is_empty() =>
454 err.span_label(span, format!("cannot {ACT}", ACT = act));
457 "consider changing this to accept closures that implement `FnMut`"
461 Place::Projection(box Projection {
462 base: Place::Base(PlaceBase::Local(local)),
463 elem: ProjectionElem::Deref,
464 }) if error_access == AccessKind::MutableBorrow => {
465 err.span_label(span, format!("cannot {ACT}", ACT = act));
467 let mpi = self.move_data.rev_lookup.find_local(*local);
468 for i in self.move_data.init_path_map[mpi].iter() {
469 if let InitLocation::Statement(location) = self.move_data.inits[*i].location {
472 kind: TerminatorKind::Call {
473 func: Operand::Constant(box Constant {
476 sty: TyKind::FnDef(id, substs),
487 ) = &self.mir.basic_blocks()[location.block].terminator {
488 let index_trait = self.infcx.tcx.lang_items().index_trait();
489 if self.infcx.tcx.parent(id) == index_trait {
490 let mut found = false;
491 self.infcx.tcx.for_each_relevant_impl(
492 self.infcx.tcx.lang_items().index_mut_trait().unwrap(),
499 let extra = if found {
502 format!(", but it is not implemented for `{}`",
508 "trait `IndexMut` is required to modify indexed content{}",
519 err.span_label(span, format!("cannot {ACT}", ACT = act));
523 err.buffer(&mut self.errors_buffer);
527 fn suggest_ampmut_self<'cx, 'gcx, 'tcx>(
528 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
529 local_decl: &mir::LocalDecl<'tcx>,
530 ) -> (Span, String) {
531 let sp = local_decl.source_info.span;
532 (sp, match tcx.sess.source_map().span_to_snippet(sp) {
534 let lt_pos = snippet.find('\'');
535 if let Some(lt_pos) = lt_pos {
536 format!("&{}mut self", &snippet[lt_pos..snippet.len() - 4])
538 "&mut self".to_string()
541 _ => "&mut self".to_string()
545 // When we want to suggest a user change a local variable to be a `&mut`, there
546 // are three potential "obvious" things to highlight:
548 // let ident [: Type] [= RightHandSideExpression];
549 // ^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
552 // We can always fallback on highlighting the first. But chances are good that
553 // the user experience will be better if we highlight one of the others if possible;
554 // for example, if the RHS is present and the Type is not, then the type is going to
555 // be inferred *from* the RHS, which means we should highlight that (and suggest
556 // that they borrow the RHS mutably).
558 // This implementation attempts to emulate AST-borrowck prioritization
559 // by trying (3.), then (2.) and finally falling back on (1.).
560 fn suggest_ampmut<'cx, 'gcx, 'tcx>(
561 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
564 local_decl: &mir::LocalDecl<'tcx>,
565 opt_ty_info: Option<Span>,
566 ) -> (Span, String) {
567 let locations = mir.find_assignments(local);
568 if !locations.is_empty() {
569 let assignment_rhs_span = mir.source_info(locations[0]).span;
570 if let Ok(src) = tcx.sess.source_map().span_to_snippet(assignment_rhs_span) {
571 if let (true, Some(ws_pos)) = (
572 src.starts_with("&'"),
573 src.find(|c: char| -> bool { c.is_whitespace() }),
575 let lt_name = &src[1..ws_pos];
576 let ty = &src[ws_pos..];
577 return (assignment_rhs_span, format!("&{} mut {}", lt_name, ty));
578 } else if src.starts_with('&') {
579 let borrowed_expr = &src[1..];
580 return (assignment_rhs_span, format!("&mut {}", borrowed_expr));
585 let highlight_span = match opt_ty_info {
586 // if this is a variable binding with an explicit type,
587 // try to highlight that for the suggestion.
588 Some(ty_span) => ty_span,
590 // otherwise, just highlight the span associated with
591 // the (MIR) LocalDecl.
592 None => local_decl.source_info.span,
595 if let Ok(src) = tcx.sess.source_map().span_to_snippet(highlight_span) {
596 if let (true, Some(ws_pos)) = (
597 src.starts_with("&'"),
598 src.find(|c: char| -> bool { c.is_whitespace() }),
600 let lt_name = &src[1..ws_pos];
601 let ty = &src[ws_pos..];
602 return (highlight_span, format!("&{} mut{}", lt_name, ty));
606 let ty_mut = local_decl.ty.builtin_deref(true).unwrap();
607 assert_eq!(ty_mut.mutbl, hir::MutImmutable);
609 if local_decl.ty.is_region_ptr() {
610 format!("&mut {}", ty_mut.ty)
612 format!("*mut {}", ty_mut.ty)
616 fn is_closure_or_generator(ty: ty::Ty<'_>) -> bool {
617 ty.is_closure() || ty.is_generator()
620 /// Adds a suggestion to a struct definition given a field access to a local.
621 /// This function expects the local to be a reference to a struct in order to produce a suggestion.
624 /// LL | s: &'a String
625 /// | ---------- use `&'a mut String` here to make mutable
627 fn annotate_struct_field(
628 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
631 ) -> Option<(Span, String)> {
632 // Expect our local to be a reference to a struct of some kind.
633 if let ty::TyKind::Ref(_, ty, _) = ty.sty {
634 if let ty::TyKind::Adt(def, _) = ty.sty {
635 let field = def.all_fields().nth(field.index())?;
636 // Use the HIR types to construct the diagnostic message.
637 let hir_id = tcx.hir().as_local_hir_id(field.did)?;
638 let node = tcx.hir().find_by_hir_id(hir_id)?;
639 // Now we're dealing with the actual struct that we're going to suggest a change to,
640 // we can expect a field that is an immutable reference to a type.
641 if let hir::Node::Field(field) = node {
642 if let hir::TyKind::Rptr(lifetime, hir::MutTy {
643 mutbl: hir::Mutability::MutImmutable,
646 // Get the snippets in two parts - the named lifetime (if there is one) and
647 // type being referenced, that way we can reconstruct the snippet without loss
649 let type_snippet = tcx.sess.source_map().span_to_snippet(ty.span).ok()?;
650 let lifetime_snippet = if !lifetime.is_elided() {
651 format!("{} ", tcx.sess.source_map().span_to_snippet(lifetime.span).ok()?)
660 lifetime_snippet, &*type_snippet,