3 use rustc::mir::{self, BindingForm, Constant, ClearCrossCrate, Local, Location, Mir};
4 use rustc::mir::{Mutability, Operand, Place, Projection, ProjectionElem, Static, Terminator};
5 use rustc::mir::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::Local(local) => {
49 item_msg = format!("`{}`", access_place_desc.unwrap());
50 if let Place::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::Local(Local::new(1)) && !self.mir.upvar_decls.is_empty() {
82 item_msg = format!("`{}`", access_place_desc.unwrap());
83 debug_assert!(self.mir.local_decls[Local::new(1)].ty.is_region_ptr());
84 debug_assert!(is_closure_or_generator(
85 the_place_err.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx)
88 reason = if access_place.is_upvar_field_projection(self.mir,
89 &self.infcx.tcx).is_some() {
90 ", as it is a captured variable in a `Fn` closure".to_string()
92 ", as `Fn` closures cannot mutate their captured variables".to_string()
95 if let Place::Local(local) = *base {
96 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard))
97 = self.mir.local_decls[local].is_user_variable {
106 item_msg = format!("`{}`", access_place_desc.unwrap());
107 reason = ", as it is immutable for the pattern guard".to_string();
110 if base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx).is_region_ptr() {
115 if let Some(desc) = access_place_desc {
116 item_msg = format!("`{}`", desc);
117 reason = match error_access {
119 AccessKind::Mutate => format!(" which is behind a {}", pointer_type),
120 AccessKind::MutableBorrow => {
121 format!(", as it is behind a {}", pointer_type)
125 item_msg = format!("data in a {}", pointer_type);
126 reason = String::new();
131 Place::Promoted(_) => unreachable!(),
133 Place::Static(box Static { def_id, ty: _ }) => {
134 if let Place::Static(_) = access_place {
135 item_msg = format!("immutable static item `{}`", access_place_desc.unwrap());
136 reason = String::new();
138 item_msg = format!("`{}`", access_place_desc.unwrap());
139 let static_name = &self.infcx.tcx.item_name(*def_id);
140 reason = format!(", as `{}` is an immutable static item", static_name);
144 Place::Projection(box Projection {
146 elem: ProjectionElem::Index(_),
148 | Place::Projection(box Projection {
150 elem: ProjectionElem::ConstantIndex { .. },
152 | Place::Projection(box Projection {
154 elem: ProjectionElem::Subslice { .. },
156 | Place::Projection(box Projection {
158 elem: ProjectionElem::Downcast(..),
159 }) => bug!("Unexpected immutable place."),
162 debug!("report_mutability_error: item_msg={:?}, reason={:?}", item_msg, reason);
164 // `act` and `acted_on` are strings that let us abstract over
165 // the verbs used in some diagnostic messages.
169 let span = match error_access {
170 AccessKind::Move => {
172 .cannot_move_out_of(span, &(item_msg + &reason), Origin::Mir);
173 err.span_label(span, "cannot move");
174 err.buffer(&mut self.errors_buffer);
177 AccessKind::Mutate => {
179 .cannot_assign(span, &(item_msg + &reason), Origin::Mir);
181 acted_on = "written";
184 AccessKind::MutableBorrow => {
185 act = "borrow as mutable";
186 acted_on = "borrowed as mutable";
188 let borrow_spans = self.borrow_spans(span, location);
189 let borrow_span = borrow_spans.args_or_use();
190 err = self.infcx.tcx.cannot_borrow_path_as_mutable_because(
196 borrow_spans.var_span_label(
199 "mutable borrow occurs due to use of `{}` in closure",
200 // always Some() if the message is printed.
201 self.describe_place(access_place).unwrap_or_default(),
208 debug!("report_mutability_error: act={:?}, acted_on={:?}", act, acted_on);
210 match the_place_err {
211 // Suggest making an existing shared borrow in a struct definition a mutable borrow.
213 // This is applicable when we have a deref of a field access to a deref of a local -
214 // something like `*((*_1).0`. The local that we get will be a reference to the
215 // struct we've got a field access of (it must be a reference since there's a deref
216 // after the field access).
217 Place::Projection(box Projection {
218 base: Place::Projection(box Projection {
219 base: Place::Projection(box Projection {
221 elem: ProjectionElem::Deref,
223 elem: ProjectionElem::Field(field, _),
225 elem: ProjectionElem::Deref,
227 err.span_label(span, format!("cannot {ACT}", ACT = act));
229 if let Some((span, message)) = annotate_struct_field(
231 base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx),
236 "consider changing this to be mutable",
238 Applicability::MaybeIncorrect,
243 // Suggest removing a `&mut` from the use of a mutable reference.
246 self.mir.local_decls.get(*local).map(|local_decl| {
247 if let ClearCrossCrate::Set(
248 mir::BindingForm::ImplicitSelf(kind)
249 ) = local_decl.is_user_variable.as_ref().unwrap() {
250 // Check if the user variable is a `&mut self` and we can therefore
251 // suggest removing the `&mut`.
253 // Deliberately fall into this case for all implicit self types,
254 // so that we don't fall in to the next case with them.
255 *kind == mir::ImplicitSelfKind::MutRef
256 } else if Some(keywords::SelfLower.name()) == local_decl.name {
257 // Otherwise, check if the name is the self kewyord - in which case
258 // we have an explicit self. Do the same thing in this case and check
259 // for a `self: &mut Self` to suggest removing the `&mut`.
260 if let ty::TyKind::Ref(
261 _, _, hir::Mutability::MutMutable
262 ) = local_decl.ty.sty {
273 err.span_label(span, format!("cannot {ACT}", ACT = act));
274 err.span_label(span, "try removing `&mut` here");
277 // We want to suggest users use `let mut` for local (user
278 // variable) mutations...
279 Place::Local(local) if self.mir.local_decls[*local].can_be_made_mutable() => {
280 // ... but it doesn't make sense to suggest it on
281 // variables that are `ref x`, `ref mut x`, `&self`,
282 // or `&mut self` (such variables are simply not
284 let local_decl = &self.mir.local_decls[*local];
285 assert_eq!(local_decl.mutability, Mutability::Not);
287 err.span_label(span, format!("cannot {ACT}", ACT = act));
289 local_decl.source_info.span,
290 "consider changing this to be mutable",
291 format!("mut {}", local_decl.name.unwrap()),
292 Applicability::MachineApplicable,
296 // Also suggest adding mut for upvars
297 Place::Projection(box Projection {
299 elem: ProjectionElem::Field(upvar_index, _),
301 debug_assert!(is_closure_or_generator(
302 base.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx)
305 err.span_label(span, format!("cannot {ACT}", ACT = act));
307 let upvar_hir_id = self.mir.upvar_decls[upvar_index.index()]
309 .assert_crate_local();
310 let upvar_node_id = self.infcx.tcx.hir().hir_to_node_id(upvar_hir_id);
311 if let Some(Node::Binding(pat)) = self.infcx.tcx.hir().find(upvar_node_id) {
312 if let hir::PatKind::Binding(
313 hir::BindingAnnotation::Unannotated,
322 "consider changing this to be mutable",
323 format!("mut {}", upvar_ident.name),
324 Applicability::MachineApplicable,
330 // complete hack to approximate old AST-borrowck
331 // diagnostic: if the span starts with a mutable borrow of
332 // a local variable, then just suggest the user remove it.
335 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
336 snippet.starts_with("&mut ")
342 err.span_label(span, format!("cannot {ACT}", ACT = act));
343 err.span_label(span, "try removing `&mut` here");
346 Place::Projection(box Projection {
347 base: Place::Local(local),
348 elem: ProjectionElem::Deref,
350 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
351 self.mir.local_decls[*local].is_user_variable
359 err.span_label(span, format!("cannot {ACT}", ACT = act));
361 "variables bound in patterns are immutable until the end of the pattern guard",
365 // We want to point out when a `&` can be readily replaced
368 // FIXME: can this case be generalized to work for an
369 // arbitrary base for the projection?
370 Place::Projection(box Projection {
371 base: Place::Local(local),
372 elem: ProjectionElem::Deref,
373 }) if self.mir.local_decls[*local].is_user_variable.is_some() =>
375 let local_decl = &self.mir.local_decls[*local];
376 let suggestion = match local_decl.is_user_variable.as_ref().unwrap() {
377 ClearCrossCrate::Set(mir::BindingForm::ImplicitSelf(_)) => {
378 Some(suggest_ampmut_self(self.infcx.tcx, local_decl))
381 ClearCrossCrate::Set(mir::BindingForm::Var(mir::VarBindingForm {
382 binding_mode: ty::BindingMode::BindByValue(_),
385 })) => Some(suggest_ampmut(
393 ClearCrossCrate::Set(mir::BindingForm::Var(mir::VarBindingForm {
394 binding_mode: ty::BindingMode::BindByReference(_),
397 let pattern_span = local_decl.source_info.span;
398 suggest_ref_mut(self.infcx.tcx, pattern_span)
399 .map(|replacement| (pattern_span, replacement))
402 ClearCrossCrate::Set(mir::BindingForm::RefForGuard) => unreachable!(),
404 ClearCrossCrate::Clear => bug!("saw cleared local state"),
407 let (pointer_sigil, pointer_desc) = if local_decl.ty.is_region_ptr() {
410 ("*const", "pointer")
413 if let Some((err_help_span, suggested_code)) = suggestion {
416 &format!("consider changing this to be a mutable {}", pointer_desc),
418 Applicability::MachineApplicable,
422 if let Some(name) = local_decl.name {
426 "`{NAME}` is a `{SIGIL}` {DESC}, \
427 so the data it refers to cannot be {ACTED_ON}",
429 SIGIL = pointer_sigil,
438 "cannot {ACT} through `{SIGIL}` {DESC}",
440 SIGIL = pointer_sigil,
447 Place::Projection(box Projection {
449 elem: ProjectionElem::Deref,
450 }) if *base == Place::Local(Local::new(1)) && !self.mir.upvar_decls.is_empty() =>
452 err.span_label(span, format!("cannot {ACT}", ACT = act));
455 "consider changing this to accept closures that implement `FnMut`"
459 Place::Projection(box Projection {
460 base: Place::Local(local),
461 elem: ProjectionElem::Deref,
462 }) if error_access == AccessKind::MutableBorrow => {
463 err.span_label(span, format!("cannot {ACT}", ACT = act));
465 let mpi = self.move_data.rev_lookup.find_local(*local);
466 for i in self.move_data.init_path_map[mpi].iter() {
467 if let InitLocation::Statement(location) = self.move_data.inits[*i].location {
470 kind: TerminatorKind::Call {
471 func: Operand::Constant(box Constant {
472 literal: ty::LazyConst::Evaluated(Const {
474 sty: TyKind::FnDef(id, substs),
485 ) = &self.mir.basic_blocks()[location.block].terminator {
486 let index_trait = self.infcx.tcx.lang_items().index_trait();
487 if self.infcx.tcx.parent(id) == index_trait {
488 let mut found = false;
489 self.infcx.tcx.for_each_relevant_impl(
490 self.infcx.tcx.lang_items().index_mut_trait().unwrap(),
497 let extra = if found {
500 format!(", but it is not implemented for `{}`",
506 "trait `IndexMut` is required to modify indexed content{}",
517 err.span_label(span, format!("cannot {ACT}", ACT = act));
521 err.buffer(&mut self.errors_buffer);
525 fn suggest_ampmut_self<'cx, 'gcx, 'tcx>(
526 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
527 local_decl: &mir::LocalDecl<'tcx>,
528 ) -> (Span, String) {
529 let sp = local_decl.source_info.span;
530 (sp, match tcx.sess.source_map().span_to_snippet(sp) {
532 let lt_pos = snippet.find('\'');
533 if let Some(lt_pos) = lt_pos {
534 format!("&{}mut self", &snippet[lt_pos..snippet.len() - 4])
536 "&mut self".to_string()
539 _ => "&mut self".to_string()
543 // When we want to suggest a user change a local variable to be a `&mut`, there
544 // are three potential "obvious" things to highlight:
546 // let ident [: Type] [= RightHandSideExpression];
547 // ^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
550 // We can always fallback on highlighting the first. But chances are good that
551 // the user experience will be better if we highlight one of the others if possible;
552 // for example, if the RHS is present and the Type is not, then the type is going to
553 // be inferred *from* the RHS, which means we should highlight that (and suggest
554 // that they borrow the RHS mutably).
556 // This implementation attempts to emulate AST-borrowck prioritization
557 // by trying (3.), then (2.) and finally falling back on (1.).
558 fn suggest_ampmut<'cx, 'gcx, 'tcx>(
559 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
562 local_decl: &mir::LocalDecl<'tcx>,
563 opt_ty_info: Option<Span>,
564 ) -> (Span, String) {
565 let locations = mir.find_assignments(local);
566 if !locations.is_empty() {
567 let assignment_rhs_span = mir.source_info(locations[0]).span;
568 if let Ok(src) = tcx.sess.source_map().span_to_snippet(assignment_rhs_span) {
569 if let (true, Some(ws_pos)) = (
570 src.starts_with("&'"),
571 src.find(|c: char| -> bool { c.is_whitespace() }),
573 let lt_name = &src[1..ws_pos];
574 let ty = &src[ws_pos..];
575 return (assignment_rhs_span, format!("&{} mut {}", lt_name, ty));
576 } else if src.starts_with('&') {
577 let borrowed_expr = &src[1..];
578 return (assignment_rhs_span, format!("&mut {}", borrowed_expr));
583 let highlight_span = match opt_ty_info {
584 // if this is a variable binding with an explicit type,
585 // try to highlight that for the suggestion.
586 Some(ty_span) => ty_span,
588 // otherwise, just highlight the span associated with
589 // the (MIR) LocalDecl.
590 None => local_decl.source_info.span,
593 if let Ok(src) = tcx.sess.source_map().span_to_snippet(highlight_span) {
594 if let (true, Some(ws_pos)) = (
595 src.starts_with("&'"),
596 src.find(|c: char| -> bool { c.is_whitespace() }),
598 let lt_name = &src[1..ws_pos];
599 let ty = &src[ws_pos..];
600 return (highlight_span, format!("&{} mut{}", lt_name, ty));
604 let ty_mut = local_decl.ty.builtin_deref(true).unwrap();
605 assert_eq!(ty_mut.mutbl, hir::MutImmutable);
607 if local_decl.ty.is_region_ptr() {
608 format!("&mut {}", ty_mut.ty)
610 format!("*mut {}", ty_mut.ty)
614 fn is_closure_or_generator(ty: ty::Ty<'_>) -> bool {
615 ty.is_closure() || ty.is_generator()
618 /// Adds a suggestion to a struct definition given a field access to a local.
619 /// This function expects the local to be a reference to a struct in order to produce a suggestion.
622 /// LL | s: &'a String
623 /// | ---------- use `&'a mut String` here to make mutable
625 fn annotate_struct_field(
626 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
629 ) -> Option<(Span, String)> {
630 // Expect our local to be a reference to a struct of some kind.
631 if let ty::TyKind::Ref(_, ty, _) = ty.sty {
632 if let ty::TyKind::Adt(def, _) = ty.sty {
633 let field = def.all_fields().nth(field.index())?;
634 // Use the HIR types to construct the diagnostic message.
635 let node_id = tcx.hir().as_local_node_id(field.did)?;
636 let node = tcx.hir().find(node_id)?;
637 // Now we're dealing with the actual struct that we're going to suggest a change to,
638 // we can expect a field that is an immutable reference to a type.
639 if let hir::Node::Field(field) = node {
640 if let hir::TyKind::Rptr(lifetime, hir::MutTy {
641 mutbl: hir::Mutability::MutImmutable,
644 // Get the snippets in two parts - the named lifetime (if there is one) and
645 // type being referenced, that way we can reconstruct the snippet without loss
647 let type_snippet = tcx.sess.source_map().span_to_snippet(ty.span).ok()?;
648 let lifetime_snippet = if !lifetime.is_elided() {
649 format!("{} ", tcx.sess.source_map().span_to_snippet(lifetime.span).ok()?)
658 lifetime_snippet, &*type_snippet,