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 dataflow::move_paths::InitLocation;
12 use borrow_check::MirBorrowckCtxt;
13 use util::borrowck_errors::{BorrowckErrors, Origin};
14 use util::collect_writes::FindAssignments;
15 use 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),
234 err.span_suggestion_with_applicability(
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));
288 err.span_suggestion_with_applicability(
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,
319 err.span_suggestion_with_applicability(
321 "consider changing this to be mutable",
322 format!("mut {}", upvar_ident.name),
323 Applicability::MachineApplicable,
329 // complete hack to approximate old AST-borrowck
330 // diagnostic: if the span starts with a mutable borrow of
331 // a local variable, then just suggest the user remove it.
334 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
335 snippet.starts_with("&mut ")
341 err.span_label(span, format!("cannot {ACT}", ACT = act));
342 err.span_label(span, "try removing `&mut` here");
345 Place::Projection(box Projection {
346 base: Place::Local(local),
347 elem: ProjectionElem::Deref,
349 if let Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) =
350 self.mir.local_decls[*local].is_user_variable
358 err.span_label(span, format!("cannot {ACT}", ACT = act));
360 "variables bound in patterns are immutable until the end of the pattern guard",
364 // We want to point out when a `&` can be readily replaced
367 // FIXME: can this case be generalized to work for an
368 // arbitrary base for the projection?
369 Place::Projection(box Projection {
370 base: Place::Local(local),
371 elem: ProjectionElem::Deref,
372 }) if self.mir.local_decls[*local].is_user_variable.is_some() =>
374 let local_decl = &self.mir.local_decls[*local];
375 let suggestion = match local_decl.is_user_variable.as_ref().unwrap() {
376 ClearCrossCrate::Set(mir::BindingForm::ImplicitSelf(_)) => {
377 Some(suggest_ampmut_self(self.infcx.tcx, local_decl))
380 ClearCrossCrate::Set(mir::BindingForm::Var(mir::VarBindingForm {
381 binding_mode: ty::BindingMode::BindByValue(_),
384 })) => Some(suggest_ampmut(
392 ClearCrossCrate::Set(mir::BindingForm::Var(mir::VarBindingForm {
393 binding_mode: ty::BindingMode::BindByReference(_),
396 let pattern_span = local_decl.source_info.span;
397 suggest_ref_mut(self.infcx.tcx, pattern_span)
398 .map(|replacement| (pattern_span, replacement))
401 ClearCrossCrate::Set(mir::BindingForm::RefForGuard) => unreachable!(),
403 ClearCrossCrate::Clear => bug!("saw cleared local state"),
406 let (pointer_sigil, pointer_desc) = if local_decl.ty.is_region_ptr() {
409 ("*const", "pointer")
412 if let Some((err_help_span, suggested_code)) = suggestion {
413 err.span_suggestion_with_applicability(
415 &format!("consider changing this to be a mutable {}", pointer_desc),
417 Applicability::MachineApplicable,
421 if let Some(name) = local_decl.name {
425 "`{NAME}` is a `{SIGIL}` {DESC}, \
426 so the data it refers to cannot be {ACTED_ON}",
428 SIGIL = pointer_sigil,
437 "cannot {ACT} through `{SIGIL}` {DESC}",
439 SIGIL = pointer_sigil,
446 Place::Projection(box Projection {
448 elem: ProjectionElem::Deref,
449 }) if *base == Place::Local(Local::new(1)) && !self.mir.upvar_decls.is_empty() =>
451 err.span_label(span, format!("cannot {ACT}", ACT = act));
454 "consider changing this to accept closures that implement `FnMut`"
458 Place::Projection(box Projection {
459 base: Place::Local(local),
460 elem: ProjectionElem::Deref,
461 }) if error_access == AccessKind::MutableBorrow => {
462 err.span_label(span, format!("cannot {ACT}", ACT = act));
464 let mpi = self.move_data.rev_lookup.find_local(*local);
465 for i in self.move_data.init_path_map[mpi].iter() {
466 if let InitLocation::Statement(location) = self.move_data.inits[*i].location {
469 kind: TerminatorKind::Call {
470 func: Operand::Constant(box Constant {
471 literal: ty::LazyConst::Evaluated(Const {
473 sty: TyKind::FnDef(id, substs),
484 ) = &self.mir.basic_blocks()[location.block].terminator {
485 let index_trait = self.infcx.tcx.lang_items().index_trait();
486 if self.infcx.tcx.parent(id) == index_trait {
487 let mut found = false;
488 self.infcx.tcx.for_each_relevant_impl(
489 self.infcx.tcx.lang_items().index_mut_trait().unwrap(),
496 let extra = if found {
499 format!(", but it is not implemented for `{}`",
505 "trait `IndexMut` is required to modify indexed content{}",
516 err.span_label(span, format!("cannot {ACT}", ACT = act));
520 err.buffer(&mut self.errors_buffer);
524 fn suggest_ampmut_self<'cx, 'gcx, 'tcx>(
525 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
526 local_decl: &mir::LocalDecl<'tcx>,
527 ) -> (Span, String) {
528 let sp = local_decl.source_info.span;
529 (sp, match tcx.sess.source_map().span_to_snippet(sp) {
531 let lt_pos = snippet.find('\'');
532 if let Some(lt_pos) = lt_pos {
533 format!("&{}mut self", &snippet[lt_pos..snippet.len() - 4])
535 "&mut self".to_string()
538 _ => "&mut self".to_string()
542 // When we want to suggest a user change a local variable to be a `&mut`, there
543 // are three potential "obvious" things to highlight:
545 // let ident [: Type] [= RightHandSideExpression];
546 // ^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
549 // We can always fallback on highlighting the first. But chances are good that
550 // the user experience will be better if we highlight one of the others if possible;
551 // for example, if the RHS is present and the Type is not, then the type is going to
552 // be inferred *from* the RHS, which means we should highlight that (and suggest
553 // that they borrow the RHS mutably).
555 // This implementation attempts to emulate AST-borrowck prioritization
556 // by trying (3.), then (2.) and finally falling back on (1.).
557 fn suggest_ampmut<'cx, 'gcx, 'tcx>(
558 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
561 local_decl: &mir::LocalDecl<'tcx>,
562 opt_ty_info: Option<Span>,
563 ) -> (Span, String) {
564 let locations = mir.find_assignments(local);
565 if !locations.is_empty() {
566 let assignment_rhs_span = mir.source_info(locations[0]).span;
567 if let Ok(src) = tcx.sess.source_map().span_to_snippet(assignment_rhs_span) {
568 if let (true, Some(ws_pos)) = (
569 src.starts_with("&'"),
570 src.find(|c: char| -> bool { c.is_whitespace() }),
572 let lt_name = &src[1..ws_pos];
573 let ty = &src[ws_pos..];
574 return (assignment_rhs_span, format!("&{} mut {}", lt_name, ty));
575 } else if src.starts_with('&') {
576 let borrowed_expr = &src[1..];
577 return (assignment_rhs_span, format!("&mut {}", borrowed_expr));
582 let highlight_span = match opt_ty_info {
583 // if this is a variable binding with an explicit type,
584 // try to highlight that for the suggestion.
585 Some(ty_span) => ty_span,
587 // otherwise, just highlight the span associated with
588 // the (MIR) LocalDecl.
589 None => local_decl.source_info.span,
592 if let Ok(src) = tcx.sess.source_map().span_to_snippet(highlight_span) {
593 if let (true, Some(ws_pos)) = (
594 src.starts_with("&'"),
595 src.find(|c: char| -> bool { c.is_whitespace() }),
597 let lt_name = &src[1..ws_pos];
598 let ty = &src[ws_pos..];
599 return (highlight_span, format!("&{} mut{}", lt_name, ty));
603 let ty_mut = local_decl.ty.builtin_deref(true).unwrap();
604 assert_eq!(ty_mut.mutbl, hir::MutImmutable);
606 if local_decl.ty.is_region_ptr() {
607 format!("&mut {}", ty_mut.ty)
609 format!("*mut {}", ty_mut.ty)
613 fn is_closure_or_generator(ty: ty::Ty) -> bool {
614 ty.is_closure() || ty.is_generator()
617 /// Add a suggestion to a struct definition given a field access to a local.
618 /// This function expects the local to be a reference to a struct in order to produce a suggestion.
621 /// LL | s: &'a String
622 /// | ---------- use `&'a mut String` here to make mutable
624 fn annotate_struct_field(
625 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
628 ) -> Option<(Span, String)> {
629 // Expect our local to be a reference to a struct of some kind.
630 if let ty::TyKind::Ref(_, ty, _) = ty.sty {
631 if let ty::TyKind::Adt(def, _) = ty.sty {
632 let field = def.all_fields().nth(field.index())?;
633 // Use the HIR types to construct the diagnostic message.
634 let node_id = tcx.hir().as_local_node_id(field.did)?;
635 let node = tcx.hir().find(node_id)?;
636 // Now we're dealing with the actual struct that we're going to suggest a change to,
637 // we can expect a field that is an immutable reference to a type.
638 if let hir::Node::Field(field) = node {
639 if let hir::TyKind::Rptr(lifetime, hir::MutTy {
640 mutbl: hir::Mutability::MutImmutable,
643 // Get the snippets in two parts - the named lifetime (if there is one) and
644 // type being referenced, that way we can reconstruct the snippet without loss
646 let type_snippet = tcx.sess.source_map().span_to_snippet(ty.span).ok()?;
647 let lifetime_snippet = if !lifetime.is_elided() {
648 format!("{} ", tcx.sess.source_map().span_to_snippet(lifetime.span).ok()?)
657 lifetime_snippet, &*type_snippet,