]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
Use verbose suggestions for mutability errors
[rust.git] / compiler / rustc_borrowck / src / diagnostics / mutability_errors.rs
1 use rustc_errors::{Applicability, Diagnostic};
2 use rustc_hir as hir;
3 use rustc_hir::intravisit::Visitor;
4 use rustc_hir::Node;
5 use rustc_middle::hir::map::Map;
6 use rustc_middle::mir::{Mutability, Place, PlaceRef, ProjectionElem};
7 use rustc_middle::ty::{self, Ty, TyCtxt};
8 use rustc_middle::{
9     hir::place::PlaceBase,
10     mir::{self, BindingForm, ClearCrossCrate, Local, LocalDecl, LocalInfo, LocalKind, Location},
11 };
12 use rustc_span::source_map::DesugaringKind;
13 use rustc_span::symbol::{kw, Symbol};
14 use rustc_span::{sym, BytePos, Span};
15
16 use crate::diagnostics::BorrowedContentSource;
17 use crate::MirBorrowckCtxt;
18 use rustc_const_eval::util::collect_writes::FindAssignments;
19
20 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
21 pub(crate) enum AccessKind {
22     MutableBorrow,
23     Mutate,
24 }
25
26 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
27     pub(crate) fn report_mutability_error(
28         &mut self,
29         access_place: Place<'tcx>,
30         span: Span,
31         the_place_err: PlaceRef<'tcx>,
32         error_access: AccessKind,
33         location: Location,
34     ) {
35         debug!(
36             "report_mutability_error(\
37                 access_place={:?}, span={:?}, the_place_err={:?}, error_access={:?}, location={:?},\
38             )",
39             access_place, span, the_place_err, error_access, location,
40         );
41
42         let mut err;
43         let item_msg;
44         let reason;
45         let mut opt_source = None;
46         let access_place_desc = self.describe_any_place(access_place.as_ref());
47         debug!("report_mutability_error: access_place_desc={:?}", access_place_desc);
48
49         match the_place_err {
50             PlaceRef { local, projection: [] } => {
51                 item_msg = access_place_desc;
52                 if access_place.as_local().is_some() {
53                     reason = ", as it is not declared as mutable".to_string();
54                 } else {
55                     let name = self.local_names[local].expect("immutable unnamed local");
56                     reason = format!(", as `{name}` is not declared as mutable");
57                 }
58             }
59
60             PlaceRef {
61                 local,
62                 projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)],
63             } => {
64                 debug_assert!(is_closure_or_generator(
65                     Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty
66                 ));
67
68                 let imm_borrow_derefed = self.upvars[upvar_index.index()]
69                     .place
70                     .place
71                     .deref_tys()
72                     .any(|ty| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not)));
73
74                 // If the place is immutable then:
75                 //
76                 // - Either we deref an immutable ref to get to our final place.
77                 //    - We don't capture derefs of raw ptrs
78                 // - Or the final place is immut because the root variable of the capture
79                 //   isn't marked mut and we should suggest that to the user.
80                 if imm_borrow_derefed {
81                     // If we deref an immutable ref then the suggestion here doesn't help.
82                     return;
83                 } else {
84                     item_msg = access_place_desc;
85                     if self.is_upvar_field_projection(access_place.as_ref()).is_some() {
86                         reason = ", as it is not declared as mutable".to_string();
87                     } else {
88                         let name = self.upvars[upvar_index.index()].place.to_string(self.infcx.tcx);
89                         reason = format!(", as `{name}` is not declared as mutable");
90                     }
91                 }
92             }
93
94             PlaceRef { local, projection: [ProjectionElem::Deref] }
95                 if self.body.local_decls[local].is_ref_for_guard() =>
96             {
97                 item_msg = access_place_desc;
98                 reason = ", as it is immutable for the pattern guard".to_string();
99             }
100             PlaceRef { local, projection: [ProjectionElem::Deref] }
101                 if self.body.local_decls[local].is_ref_to_static() =>
102             {
103                 if access_place.projection.len() == 1 {
104                     item_msg = format!("immutable static item {access_place_desc}");
105                     reason = String::new();
106                 } else {
107                     item_msg = access_place_desc;
108                     let local_info = &self.body.local_decls[local].local_info;
109                     if let Some(box LocalInfo::StaticRef { def_id, .. }) = *local_info {
110                         let static_name = &self.infcx.tcx.item_name(def_id);
111                         reason = format!(", as `{static_name}` is an immutable static item");
112                     } else {
113                         bug!("is_ref_to_static return true, but not ref to static?");
114                     }
115                 }
116             }
117             PlaceRef { local: _, projection: [proj_base @ .., ProjectionElem::Deref] } => {
118                 if the_place_err.local == ty::CAPTURE_STRUCT_LOCAL
119                     && proj_base.is_empty()
120                     && !self.upvars.is_empty()
121                 {
122                     item_msg = access_place_desc;
123                     debug_assert!(
124                         self.body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty.is_region_ptr()
125                     );
126                     debug_assert!(is_closure_or_generator(
127                         Place::ty_from(
128                             the_place_err.local,
129                             the_place_err.projection,
130                             self.body,
131                             self.infcx.tcx
132                         )
133                         .ty
134                     ));
135
136                     reason = if self.is_upvar_field_projection(access_place.as_ref()).is_some() {
137                         ", as it is a captured variable in a `Fn` closure".to_string()
138                     } else {
139                         ", as `Fn` closures cannot mutate their captured variables".to_string()
140                     }
141                 } else {
142                     let source = self.borrowed_content_source(PlaceRef {
143                         local: the_place_err.local,
144                         projection: proj_base,
145                     });
146                     let pointer_type = source.describe_for_immutable_place(self.infcx.tcx);
147                     opt_source = Some(source);
148                     if let Some(desc) = self.describe_place(access_place.as_ref()) {
149                         item_msg = format!("`{desc}`");
150                         reason = match error_access {
151                             AccessKind::Mutate => format!(", which is behind {pointer_type}"),
152                             AccessKind::MutableBorrow => {
153                                 format!(", as it is behind {pointer_type}")
154                             }
155                         }
156                     } else {
157                         item_msg = format!("data in {pointer_type}");
158                         reason = String::new();
159                     }
160                 }
161             }
162
163             PlaceRef {
164                 local: _,
165                 projection:
166                     [
167                         ..,
168                         ProjectionElem::Index(_)
169                         | ProjectionElem::ConstantIndex { .. }
170                         | ProjectionElem::OpaqueCast { .. }
171                         | ProjectionElem::Subslice { .. }
172                         | ProjectionElem::Downcast(..),
173                     ],
174             } => bug!("Unexpected immutable place."),
175         }
176
177         debug!("report_mutability_error: item_msg={:?}, reason={:?}", item_msg, reason);
178
179         // `act` and `acted_on` are strings that let us abstract over
180         // the verbs used in some diagnostic messages.
181         let act;
182         let acted_on;
183
184         let span = match error_access {
185             AccessKind::Mutate => {
186                 err = self.cannot_assign(span, &(item_msg + &reason));
187                 act = "assign";
188                 acted_on = "written";
189                 span
190             }
191             AccessKind::MutableBorrow => {
192                 act = "borrow as mutable";
193                 acted_on = "borrowed as mutable";
194
195                 let borrow_spans = self.borrow_spans(span, location);
196                 let borrow_span = borrow_spans.args_or_use();
197                 err = self.cannot_borrow_path_as_mutable_because(borrow_span, &item_msg, &reason);
198                 borrow_spans.var_span_label(
199                     &mut err,
200                     format!(
201                         "mutable borrow occurs due to use of {} in closure",
202                         self.describe_any_place(access_place.as_ref()),
203                     ),
204                     "mutable",
205                 );
206                 borrow_span
207             }
208         };
209
210         debug!("report_mutability_error: act={:?}, acted_on={:?}", act, acted_on);
211
212         match the_place_err {
213             // Suggest making an existing shared borrow in a struct definition a mutable borrow.
214             //
215             // This is applicable when we have a deref of a field access to a deref of a local -
216             // something like `*((*_1).0`. The local that we get will be a reference to the
217             // struct we've got a field access of (it must be a reference since there's a deref
218             // after the field access).
219             PlaceRef {
220                 local,
221                 projection:
222                     [
223                         proj_base @ ..,
224                         ProjectionElem::Deref,
225                         ProjectionElem::Field(field, _),
226                         ProjectionElem::Deref,
227                     ],
228             } => {
229                 err.span_label(span, format!("cannot {ACT}", ACT = act));
230
231                 if let Some(span) = get_mut_span_in_struct_field(
232                     self.infcx.tcx,
233                     Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty,
234                     *field,
235                 ) {
236                     err.span_suggestion_verbose(
237                         span,
238                         "consider changing this to be mutable",
239                         " mut ",
240                         Applicability::MaybeIncorrect,
241                     );
242                 }
243             }
244
245             // Suggest removing a `&mut` from the use of a mutable reference.
246             PlaceRef { local, projection: [] }
247                 if self
248                     .body
249                     .local_decls
250                     .get(local)
251                     .map(|l| mut_borrow_of_mutable_ref(l, self.local_names[local]))
252                     .unwrap_or(false) =>
253             {
254                 let decl = &self.body.local_decls[local];
255                 err.span_label(span, format!("cannot {ACT}", ACT = act));
256                 if let Some(mir::Statement {
257                     source_info,
258                     kind:
259                         mir::StatementKind::Assign(box (
260                             _,
261                             mir::Rvalue::Ref(
262                                 _,
263                                 mir::BorrowKind::Mut { allow_two_phase_borrow: false },
264                                 _,
265                             ),
266                         )),
267                     ..
268                 }) = &self.body[location.block].statements.get(location.statement_index)
269                 {
270                     match decl.local_info {
271                         Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
272                             mir::VarBindingForm {
273                                 binding_mode: ty::BindingMode::BindByValue(Mutability::Not),
274                                 opt_ty_info: Some(sp),
275                                 opt_match_place: _,
276                                 pat_span: _,
277                             },
278                         )))) => {
279                             err.span_note(sp, "the binding is already a mutable borrow");
280                         }
281                         _ => {
282                             err.span_note(
283                                 decl.source_info.span,
284                                 "the binding is already a mutable borrow",
285                             );
286                         }
287                     }
288                     if let Ok(snippet) =
289                         self.infcx.tcx.sess.source_map().span_to_snippet(source_info.span)
290                     {
291                         if snippet.starts_with("&mut ") {
292                             // We don't have access to the HIR to get accurate spans, but we can
293                             // give a best effort structured suggestion.
294                             err.span_suggestion_verbose(
295                                 source_info.span.with_hi(source_info.span.lo() + BytePos(5)),
296                                 "try removing `&mut` here",
297                                 "",
298                                 Applicability::MachineApplicable,
299                             );
300                         } else {
301                             // This can occur with things like `(&mut self).foo()`.
302                             err.span_help(source_info.span, "try removing `&mut` here");
303                         }
304                     } else {
305                         err.span_help(source_info.span, "try removing `&mut` here");
306                     }
307                 } else if decl.mutability == Mutability::Not
308                     && !matches!(
309                         decl.local_info,
310                         Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
311                             hir::ImplicitSelfKind::MutRef
312                         ))))
313                     )
314                 {
315                     err.span_suggestion_verbose(
316                         decl.source_info.span.shrink_to_lo(),
317                         "consider making the binding mutable",
318                         "mut ",
319                         Applicability::MachineApplicable,
320                     );
321                 }
322             }
323
324             // We want to suggest users use `let mut` for local (user
325             // variable) mutations...
326             PlaceRef { local, projection: [] }
327                 if self.body.local_decls[local].can_be_made_mutable() =>
328             {
329                 // ... but it doesn't make sense to suggest it on
330                 // variables that are `ref x`, `ref mut x`, `&self`,
331                 // or `&mut self` (such variables are simply not
332                 // mutable).
333                 let local_decl = &self.body.local_decls[local];
334                 assert_eq!(local_decl.mutability, Mutability::Not);
335
336                 err.span_label(span, format!("cannot {act}"));
337                 err.span_suggestion(
338                     local_decl.source_info.span,
339                     "consider changing this to be mutable",
340                     format!("mut {}", self.local_names[local].unwrap()),
341                     Applicability::MachineApplicable,
342                 );
343                 let tcx = self.infcx.tcx;
344                 if let ty::Closure(id, _) = *the_place_err.ty(self.body, tcx).ty.kind() {
345                     self.show_mutating_upvar(tcx, id.expect_local(), the_place_err, &mut err);
346                 }
347             }
348
349             // Also suggest adding mut for upvars
350             PlaceRef {
351                 local,
352                 projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)],
353             } => {
354                 debug_assert!(is_closure_or_generator(
355                     Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty
356                 ));
357
358                 let captured_place = &self.upvars[upvar_index.index()].place;
359
360                 err.span_label(span, format!("cannot {act}"));
361
362                 let upvar_hir_id = captured_place.get_root_variable();
363
364                 if let Some(Node::Pat(pat)) = self.infcx.tcx.hir().find(upvar_hir_id)
365                     && let hir::PatKind::Binding(
366                         hir::BindingAnnotation::NONE,
367                         _,
368                         upvar_ident,
369                         _,
370                     ) = pat.kind
371                 {
372                     err.span_suggestion(
373                         upvar_ident.span,
374                         "consider changing this to be mutable",
375                         format!("mut {}", upvar_ident.name),
376                         Applicability::MachineApplicable,
377                     );
378                 }
379
380                 let tcx = self.infcx.tcx;
381                 if let ty::Ref(_, ty, Mutability::Mut) = the_place_err.ty(self.body, tcx).ty.kind()
382                     && let ty::Closure(id, _) = *ty.kind()
383                 {
384                     self.show_mutating_upvar(tcx, id.expect_local(), the_place_err, &mut err);
385                 }
386             }
387
388             // complete hack to approximate old AST-borrowck
389             // diagnostic: if the span starts with a mutable borrow of
390             // a local variable, then just suggest the user remove it.
391             PlaceRef { local: _, projection: [] }
392                 if self
393                     .infcx
394                     .tcx
395                     .sess
396                     .source_map()
397                     .span_to_snippet(span)
398                     .map_or(false, |snippet| snippet.starts_with("&mut ")) =>
399             {
400                 err.span_label(span, format!("cannot {act}"));
401                 err.span_suggestion(
402                     span,
403                     "try removing `&mut` here",
404                     "",
405                     Applicability::MaybeIncorrect,
406                 );
407             }
408
409             PlaceRef { local, projection: [ProjectionElem::Deref] }
410                 if self.body.local_decls[local].is_ref_for_guard() =>
411             {
412                 err.span_label(span, format!("cannot {act}"));
413                 err.note(
414                     "variables bound in patterns are immutable until the end of the pattern guard",
415                 );
416             }
417
418             // We want to point out when a `&` can be readily replaced
419             // with an `&mut`.
420             //
421             // FIXME: can this case be generalized to work for an
422             // arbitrary base for the projection?
423             PlaceRef { local, projection: [ProjectionElem::Deref] }
424                 if self.body.local_decls[local].is_user_variable() =>
425             {
426                 let local_decl = &self.body.local_decls[local];
427
428                 let (pointer_sigil, pointer_desc) = if local_decl.ty.is_region_ptr() {
429                     ("&", "reference")
430                 } else {
431                     ("*const", "pointer")
432                 };
433
434                 match self.local_names[local] {
435                     Some(name) if !local_decl.from_compiler_desugaring() => {
436                         let label = match local_decl.local_info.as_deref().unwrap() {
437                             LocalInfo::User(ClearCrossCrate::Set(
438                                 mir::BindingForm::ImplicitSelf(_),
439                             )) => {
440                                 let (span, suggestion) =
441                                     suggest_ampmut_self(self.infcx.tcx, local_decl);
442                                 Some((true, span, suggestion))
443                             }
444
445                             LocalInfo::User(ClearCrossCrate::Set(mir::BindingForm::Var(
446                                 mir::VarBindingForm {
447                                     binding_mode: ty::BindingMode::BindByValue(_),
448                                     opt_ty_info,
449                                     ..
450                                 },
451                             ))) => {
452                                 // check if the RHS is from desugaring
453                                 let opt_assignment_rhs_span =
454                                     self.body.find_assignments(local).first().map(|&location| {
455                                         if let Some(mir::Statement {
456                                             source_info: _,
457                                             kind:
458                                                 mir::StatementKind::Assign(box (
459                                                     _,
460                                                     mir::Rvalue::Use(mir::Operand::Copy(place)),
461                                                 )),
462                                         }) = self.body[location.block]
463                                             .statements
464                                             .get(location.statement_index)
465                                         {
466                                             self.body.local_decls[place.local].source_info.span
467                                         } else {
468                                             self.body.source_info(location).span
469                                         }
470                                     });
471                                 match opt_assignment_rhs_span.and_then(|s| s.desugaring_kind()) {
472                                     // on for loops, RHS points to the iterator part
473                                     Some(DesugaringKind::ForLoop) => {
474                                         self.suggest_similar_mut_method_for_for_loop(&mut err);
475                                         err.span_label(opt_assignment_rhs_span.unwrap(), format!(
476                                             "this iterator yields `{pointer_sigil}` {pointer_desc}s",
477                                         ));
478                                         None
479                                     }
480                                     // don't create labels for compiler-generated spans
481                                     Some(_) => None,
482                                     None => {
483                                         let label = if name != kw::SelfLower {
484                                             suggest_ampmut(
485                                                 self.infcx.tcx,
486                                                 local_decl,
487                                                 opt_assignment_rhs_span,
488                                                 *opt_ty_info,
489                                             )
490                                         } else {
491                                             match local_decl.local_info.as_deref() {
492                                                 Some(LocalInfo::User(ClearCrossCrate::Set(
493                                                     mir::BindingForm::Var(mir::VarBindingForm {
494                                                         opt_ty_info: None,
495                                                         ..
496                                                     }),
497                                                 ))) => {
498                                                     let (span, sugg) = suggest_ampmut_self(
499                                                         self.infcx.tcx,
500                                                         local_decl,
501                                                     );
502                                                     (true, span, sugg)
503                                                 }
504                                                 // explicit self (eg `self: &'a Self`)
505                                                 _ => suggest_ampmut(
506                                                     self.infcx.tcx,
507                                                     local_decl,
508                                                     opt_assignment_rhs_span,
509                                                     *opt_ty_info,
510                                                 ),
511                                             }
512                                         };
513                                         Some(label)
514                                     }
515                                 }
516                             }
517
518                             LocalInfo::User(ClearCrossCrate::Set(mir::BindingForm::Var(
519                                 mir::VarBindingForm {
520                                     binding_mode: ty::BindingMode::BindByReference(_),
521                                     ..
522                                 },
523                             ))) => {
524                                 let pattern_span = local_decl.source_info.span;
525                                 suggest_ref_mut(self.infcx.tcx, pattern_span)
526                                     .map(|replacement| (true, pattern_span, replacement))
527                             }
528
529                             LocalInfo::User(ClearCrossCrate::Clear) => {
530                                 bug!("saw cleared local state")
531                             }
532
533                             _ => unreachable!(),
534                         };
535
536                         match label {
537                             Some((true, err_help_span, suggested_code)) => {
538                                 let (is_trait_sig, local_trait) = self.is_error_in_trait(local);
539                                 if !is_trait_sig {
540                                     err.span_suggestion_verbose(
541                                         err_help_span,
542                                         &format!(
543                                             "consider changing this to be a mutable {pointer_desc}"
544                                         ),
545                                         suggested_code,
546                                         Applicability::MachineApplicable,
547                                     );
548                                 } else if let Some(x) = local_trait {
549                                     err.span_suggestion_verbose(
550                                         x,
551                                         &format!(
552                                             "consider changing that to be a mutable {pointer_desc}"
553                                         ),
554                                         suggested_code,
555                                         Applicability::MachineApplicable,
556                                     );
557                                 }
558                             }
559                             Some((false, err_label_span, message)) => {
560                                 err.span_label(
561                                     err_label_span,
562                                     &format!(
563                                         "consider changing this binding's type to be: `{message}`"
564                                     ),
565                                 );
566                             }
567                             None => {}
568                         }
569                         err.span_label(
570                             span,
571                             format!(
572                                 "`{name}` is a `{pointer_sigil}` {pointer_desc}, \
573                                  so the data it refers to cannot be {acted_on}",
574                             ),
575                         );
576                     }
577                     _ => {
578                         err.span_label(
579                             span,
580                             format!("cannot {act} through `{pointer_sigil}` {pointer_desc}"),
581                         );
582                     }
583                 }
584             }
585
586             PlaceRef { local, projection: [ProjectionElem::Deref] }
587                 if local == ty::CAPTURE_STRUCT_LOCAL && !self.upvars.is_empty() =>
588             {
589                 self.expected_fn_found_fn_mut_call(&mut err, span, act);
590             }
591
592             PlaceRef { local: _, projection: [.., ProjectionElem::Deref] } => {
593                 err.span_label(span, format!("cannot {ACT}", ACT = act));
594
595                 match opt_source {
596                     Some(BorrowedContentSource::OverloadedDeref(ty)) => {
597                         err.help(&format!(
598                             "trait `DerefMut` is required to modify through a dereference, \
599                              but it is not implemented for `{ty}`",
600                         ));
601                     }
602                     Some(BorrowedContentSource::OverloadedIndex(ty)) => {
603                         err.help(&format!(
604                             "trait `IndexMut` is required to modify indexed content, \
605                              but it is not implemented for `{ty}`",
606                         ));
607                         self.suggest_map_index_mut_alternatives(ty, &mut err, span);
608                     }
609                     _ => (),
610                 }
611             }
612
613             _ => {
614                 err.span_label(span, format!("cannot {act}"));
615             }
616         }
617
618         self.buffer_error(err);
619     }
620
621     fn suggest_map_index_mut_alternatives(&self, ty: Ty<'tcx>, err: &mut Diagnostic, span: Span) {
622         let Some(adt) = ty.ty_adt_def() else { return };
623         let did = adt.did();
624         if self.infcx.tcx.is_diagnostic_item(sym::HashMap, did)
625             || self.infcx.tcx.is_diagnostic_item(sym::BTreeMap, did)
626         {
627             struct V<'a, 'tcx> {
628                 assign_span: Span,
629                 err: &'a mut Diagnostic,
630                 ty: Ty<'tcx>,
631                 suggested: bool,
632             }
633             impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
634                 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
635                     hir::intravisit::walk_stmt(self, stmt);
636                     let expr = match stmt.kind {
637                         hir::StmtKind::Semi(expr) | hir::StmtKind::Expr(expr) => expr,
638                         hir::StmtKind::Local(hir::Local { init: Some(expr), .. }) => expr,
639                         _ => {
640                             return;
641                         }
642                     };
643                     if let hir::ExprKind::Assign(place, rv, _sp) = expr.kind
644                         && let hir::ExprKind::Index(val, index) = place.kind
645                         && (expr.span == self.assign_span || place.span == self.assign_span)
646                     {
647                         // val[index] = rv;
648                         // ---------- place
649                         self.err.multipart_suggestions(
650                             &format!(
651                                 "to modify a `{}`, use `.get_mut()`, `.insert()` or the entry API",
652                                 self.ty,
653                             ),
654                             vec![
655                                 vec![ // val.insert(index, rv);
656                                     (
657                                         val.span.shrink_to_hi().with_hi(index.span.lo()),
658                                         ".insert(".to_string(),
659                                     ),
660                                     (
661                                         index.span.shrink_to_hi().with_hi(rv.span.lo()),
662                                         ", ".to_string(),
663                                     ),
664                                     (rv.span.shrink_to_hi(), ")".to_string()),
665                                 ],
666                                 vec![ // val.get_mut(index).map(|v| { *v = rv; });
667                                     (
668                                         val.span.shrink_to_hi().with_hi(index.span.lo()),
669                                         ".get_mut(".to_string(),
670                                     ),
671                                     (
672                                         index.span.shrink_to_hi().with_hi(place.span.hi()),
673                                         ").map(|val| { *val".to_string(),
674                                     ),
675                                     (
676                                         rv.span.shrink_to_hi(),
677                                         "; })".to_string(),
678                                     ),
679                                 ],
680                                 vec![ // let x = val.entry(index).or_insert(rv);
681                                     (val.span.shrink_to_lo(), "let val = ".to_string()),
682                                     (
683                                         val.span.shrink_to_hi().with_hi(index.span.lo()),
684                                         ".entry(".to_string(),
685                                     ),
686                                     (
687                                         index.span.shrink_to_hi().with_hi(rv.span.lo()),
688                                         ").or_insert(".to_string(),
689                                     ),
690                                     (rv.span.shrink_to_hi(), ")".to_string()),
691                                 ],
692                             ],
693                             Applicability::MachineApplicable,
694                         );
695                         self.suggested = true;
696                     } else if let hir::ExprKind::MethodCall(_path, receiver, _, sp) = expr.kind
697                         && let hir::ExprKind::Index(val, index) = receiver.kind
698                         && expr.span == self.assign_span
699                     {
700                         // val[index].path(args..);
701                         self.err.multipart_suggestion(
702                             &format!("to modify a `{}` use `.get_mut()`", self.ty),
703                             vec![
704                                 (
705                                     val.span.shrink_to_hi().with_hi(index.span.lo()),
706                                     ".get_mut(".to_string(),
707                                 ),
708                                 (
709                                     index.span.shrink_to_hi().with_hi(receiver.span.hi()),
710                                     ").map(|val| val".to_string(),
711                                 ),
712                                 (sp.shrink_to_hi(), ")".to_string()),
713                             ],
714                             Applicability::MachineApplicable,
715                         );
716                         self.suggested = true;
717                     }
718                 }
719             }
720             let hir_map = self.infcx.tcx.hir();
721             let def_id = self.body.source.def_id();
722             let hir_id = hir_map.local_def_id_to_hir_id(def_id.as_local().unwrap());
723             let node = hir_map.find(hir_id);
724             let Some(hir::Node::Item(item)) = node else { return; };
725             let hir::ItemKind::Fn(.., body_id) = item.kind else { return; };
726             let body = self.infcx.tcx.hir().body(body_id);
727             let mut v = V { assign_span: span, err, ty, suggested: false };
728             v.visit_body(body);
729             if !v.suggested {
730                 err.help(&format!(
731                     "to modify a `{ty}`, use `.get_mut()`, `.insert()` or the entry API",
732                 ));
733             }
734         }
735     }
736
737     /// User cannot make signature of a trait mutable without changing the
738     /// trait. So we find if this error belongs to a trait and if so we move
739     /// suggestion to the trait or disable it if it is out of scope of this crate
740     fn is_error_in_trait(&self, local: Local) -> (bool, Option<Span>) {
741         if self.body.local_kind(local) != LocalKind::Arg {
742             return (false, None);
743         }
744         let hir_map = self.infcx.tcx.hir();
745         let my_def = self.body.source.def_id();
746         let my_hir = hir_map.local_def_id_to_hir_id(my_def.as_local().unwrap());
747         let Some(td) =
748             self.infcx.tcx.impl_of_method(my_def).and_then(|x| self.infcx.tcx.trait_id_of_impl(x))
749         else {
750             return (false, None);
751         };
752         (
753             true,
754             td.as_local().and_then(|tld| match hir_map.find_by_def_id(tld) {
755                 Some(Node::Item(hir::Item {
756                     kind: hir::ItemKind::Trait(_, _, _, _, items),
757                     ..
758                 })) => {
759                     let mut f_in_trait_opt = None;
760                     for hir::TraitItemRef { id: fi, kind: k, .. } in *items {
761                         let hi = fi.hir_id();
762                         if !matches!(k, hir::AssocItemKind::Fn { .. }) {
763                             continue;
764                         }
765                         if hir_map.name(hi) != hir_map.name(my_hir) {
766                             continue;
767                         }
768                         f_in_trait_opt = Some(hi);
769                         break;
770                     }
771                     f_in_trait_opt.and_then(|f_in_trait| match hir_map.find(f_in_trait) {
772                         Some(Node::TraitItem(hir::TraitItem {
773                             kind:
774                                 hir::TraitItemKind::Fn(
775                                     hir::FnSig { decl: hir::FnDecl { inputs, .. }, .. },
776                                     _,
777                                 ),
778                             ..
779                         })) => {
780                             let hir::Ty { span, .. } = inputs[local.index() - 1];
781                             Some(span)
782                         }
783                         _ => None,
784                     })
785                 }
786                 _ => None,
787             }),
788         )
789     }
790
791     // point to span of upvar making closure call require mutable borrow
792     fn show_mutating_upvar(
793         &self,
794         tcx: TyCtxt<'_>,
795         closure_local_def_id: hir::def_id::LocalDefId,
796         the_place_err: PlaceRef<'tcx>,
797         err: &mut Diagnostic,
798     ) {
799         let tables = tcx.typeck(closure_local_def_id);
800         let closure_hir_id = tcx.hir().local_def_id_to_hir_id(closure_local_def_id);
801         if let Some((span, closure_kind_origin)) =
802             &tables.closure_kind_origins().get(closure_hir_id)
803         {
804             let reason = if let PlaceBase::Upvar(upvar_id) = closure_kind_origin.base {
805                 let upvar = ty::place_to_string_for_capture(tcx, closure_kind_origin);
806                 let root_hir_id = upvar_id.var_path.hir_id;
807                 // we have an origin for this closure kind starting at this root variable so it's safe to unwrap here
808                 let captured_places =
809                     tables.closure_min_captures[&closure_local_def_id].get(&root_hir_id).unwrap();
810
811                 let origin_projection = closure_kind_origin
812                     .projections
813                     .iter()
814                     .map(|proj| proj.kind)
815                     .collect::<Vec<_>>();
816                 let mut capture_reason = String::new();
817                 for captured_place in captured_places {
818                     let captured_place_kinds = captured_place
819                         .place
820                         .projections
821                         .iter()
822                         .map(|proj| proj.kind)
823                         .collect::<Vec<_>>();
824                     if rustc_middle::ty::is_ancestor_or_same_capture(
825                         &captured_place_kinds,
826                         &origin_projection,
827                     ) {
828                         match captured_place.info.capture_kind {
829                             ty::UpvarCapture::ByRef(
830                                 ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow,
831                             ) => {
832                                 capture_reason = format!("mutable borrow of `{upvar}`");
833                             }
834                             ty::UpvarCapture::ByValue => {
835                                 capture_reason = format!("possible mutation of `{upvar}`");
836                             }
837                             _ => bug!("upvar `{upvar}` borrowed, but not mutably"),
838                         }
839                         break;
840                     }
841                 }
842                 if capture_reason.is_empty() {
843                     bug!("upvar `{upvar}` borrowed, but cannot find reason");
844                 }
845                 capture_reason
846             } else {
847                 bug!("not an upvar")
848             };
849             err.span_label(
850                 *span,
851                 format!(
852                     "calling `{}` requires mutable binding due to {}",
853                     self.describe_place(the_place_err).unwrap(),
854                     reason
855                 ),
856             );
857         }
858     }
859
860     // Attempt to search similar mutable associated items for suggestion.
861     // In the future, attempt in all path but initially for RHS of for_loop
862     fn suggest_similar_mut_method_for_for_loop(&self, err: &mut Diagnostic) {
863         use hir::{
864             BodyId, Expr,
865             ExprKind::{Block, Call, DropTemps, Match, MethodCall},
866             HirId, ImplItem, ImplItemKind, Item, ItemKind,
867         };
868
869         fn maybe_body_id_of_fn(hir_map: Map<'_>, id: HirId) -> Option<BodyId> {
870             match hir_map.find(id) {
871                 Some(Node::Item(Item { kind: ItemKind::Fn(_, _, body_id), .. }))
872                 | Some(Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })) => {
873                     Some(*body_id)
874                 }
875                 _ => None,
876             }
877         }
878         let hir_map = self.infcx.tcx.hir();
879         let mir_body_hir_id = self.mir_hir_id();
880         if let Some(fn_body_id) = maybe_body_id_of_fn(hir_map, mir_body_hir_id) {
881             if let Block(
882                 hir::Block {
883                     expr:
884                         Some(Expr {
885                             kind:
886                                 DropTemps(Expr {
887                                     kind:
888                                         Match(
889                                             Expr {
890                                                 kind:
891                                                     Call(
892                                                         _,
893                                                         [
894                                                             Expr {
895                                                                 kind:
896                                                                     MethodCall(path_segment, _, _, span),
897                                                                 hir_id,
898                                                                 ..
899                                                             },
900                                                             ..,
901                                                         ],
902                                                     ),
903                                                 ..
904                                             },
905                                             ..,
906                                         ),
907                                     ..
908                                 }),
909                             ..
910                         }),
911                     ..
912                 },
913                 _,
914             ) = hir_map.body(fn_body_id).value.kind
915             {
916                 let opt_suggestions = self
917                     .infcx
918                     .tcx
919                     .typeck(path_segment.hir_id.owner.def_id)
920                     .type_dependent_def_id(*hir_id)
921                     .and_then(|def_id| self.infcx.tcx.impl_of_method(def_id))
922                     .map(|def_id| self.infcx.tcx.associated_items(def_id))
923                     .map(|assoc_items| {
924                         assoc_items
925                             .in_definition_order()
926                             .map(|assoc_item_def| assoc_item_def.ident(self.infcx.tcx))
927                             .filter(|&ident| {
928                                 let original_method_ident = path_segment.ident;
929                                 original_method_ident != ident
930                                     && ident
931                                         .as_str()
932                                         .starts_with(&original_method_ident.name.to_string())
933                             })
934                             .map(|ident| format!("{ident}()"))
935                             .peekable()
936                     });
937
938                 if let Some(mut suggestions) = opt_suggestions
939                     && suggestions.peek().is_some()
940                 {
941                     err.span_suggestions(
942                         *span,
943                         "use mutable method",
944                         suggestions,
945                         Applicability::MaybeIncorrect,
946                     );
947                 }
948             }
949         };
950     }
951
952     /// Targeted error when encountering an `FnMut` closure where an `Fn` closure was expected.
953     fn expected_fn_found_fn_mut_call(&self, err: &mut Diagnostic, sp: Span, act: &str) {
954         err.span_label(sp, format!("cannot {act}"));
955
956         let hir = self.infcx.tcx.hir();
957         let closure_id = self.mir_hir_id();
958         let closure_span = self.infcx.tcx.def_span(self.mir_def_id());
959         let fn_call_id = hir.get_parent_node(closure_id);
960         let node = hir.get(fn_call_id);
961         let def_id = hir.enclosing_body_owner(fn_call_id);
962         let mut look_at_return = true;
963         // If we can detect the expression to be an `fn` call where the closure was an argument,
964         // we point at the `fn` definition argument...
965         if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Call(func, args), .. }) = node {
966             let arg_pos = args
967                 .iter()
968                 .enumerate()
969                 .filter(|(_, arg)| arg.hir_id == closure_id)
970                 .map(|(pos, _)| pos)
971                 .next();
972             let tables = self.infcx.tcx.typeck(def_id);
973             if let Some(ty::FnDef(def_id, _)) =
974                 tables.node_type_opt(func.hir_id).as_ref().map(|ty| ty.kind())
975             {
976                 let arg = match hir.get_if_local(*def_id) {
977                     Some(
978                         hir::Node::Item(hir::Item {
979                             ident, kind: hir::ItemKind::Fn(sig, ..), ..
980                         })
981                         | hir::Node::TraitItem(hir::TraitItem {
982                             ident,
983                             kind: hir::TraitItemKind::Fn(sig, _),
984                             ..
985                         })
986                         | hir::Node::ImplItem(hir::ImplItem {
987                             ident,
988                             kind: hir::ImplItemKind::Fn(sig, _),
989                             ..
990                         }),
991                     ) => Some(
992                         arg_pos
993                             .and_then(|pos| {
994                                 sig.decl.inputs.get(
995                                     pos + if sig.decl.implicit_self.has_implicit_self() {
996                                         1
997                                     } else {
998                                         0
999                                     },
1000                                 )
1001                             })
1002                             .map(|arg| arg.span)
1003                             .unwrap_or(ident.span),
1004                     ),
1005                     _ => None,
1006                 };
1007                 if let Some(span) = arg {
1008                     err.span_label(span, "change this to accept `FnMut` instead of `Fn`");
1009                     err.span_label(func.span, "expects `Fn` instead of `FnMut`");
1010                     err.span_label(closure_span, "in this closure");
1011                     look_at_return = false;
1012                 }
1013             }
1014         }
1015
1016         if look_at_return && hir.get_return_block(closure_id).is_some() {
1017             // ...otherwise we are probably in the tail expression of the function, point at the
1018             // return type.
1019             match hir.get_by_def_id(hir.get_parent_item(fn_call_id).def_id) {
1020                 hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(sig, ..), .. })
1021                 | hir::Node::TraitItem(hir::TraitItem {
1022                     ident,
1023                     kind: hir::TraitItemKind::Fn(sig, _),
1024                     ..
1025                 })
1026                 | hir::Node::ImplItem(hir::ImplItem {
1027                     ident,
1028                     kind: hir::ImplItemKind::Fn(sig, _),
1029                     ..
1030                 }) => {
1031                     err.span_label(ident.span, "");
1032                     err.span_label(
1033                         sig.decl.output.span(),
1034                         "change this to return `FnMut` instead of `Fn`",
1035                     );
1036                     err.span_label(closure_span, "in this closure");
1037                 }
1038                 _ => {}
1039             }
1040         }
1041     }
1042 }
1043
1044 fn mut_borrow_of_mutable_ref(local_decl: &LocalDecl<'_>, local_name: Option<Symbol>) -> bool {
1045     debug!("local_info: {:?}, ty.kind(): {:?}", local_decl.local_info, local_decl.ty.kind());
1046
1047     match local_decl.local_info.as_deref() {
1048         // Check if mutably borrowing a mutable reference.
1049         Some(LocalInfo::User(ClearCrossCrate::Set(mir::BindingForm::Var(
1050             mir::VarBindingForm {
1051                 binding_mode: ty::BindingMode::BindByValue(Mutability::Not), ..
1052             },
1053         )))) => matches!(local_decl.ty.kind(), ty::Ref(_, _, hir::Mutability::Mut)),
1054         Some(LocalInfo::User(ClearCrossCrate::Set(mir::BindingForm::ImplicitSelf(kind)))) => {
1055             // Check if the user variable is a `&mut self` and we can therefore
1056             // suggest removing the `&mut`.
1057             //
1058             // Deliberately fall into this case for all implicit self types,
1059             // so that we don't fall in to the next case with them.
1060             *kind == hir::ImplicitSelfKind::MutRef
1061         }
1062         _ if Some(kw::SelfLower) == local_name => {
1063             // Otherwise, check if the name is the `self` keyword - in which case
1064             // we have an explicit self. Do the same thing in this case and check
1065             // for a `self: &mut Self` to suggest removing the `&mut`.
1066             matches!(local_decl.ty.kind(), ty::Ref(_, _, hir::Mutability::Mut))
1067         }
1068         _ => false,
1069     }
1070 }
1071
1072 fn suggest_ampmut_self<'tcx>(
1073     tcx: TyCtxt<'tcx>,
1074     local_decl: &mir::LocalDecl<'tcx>,
1075 ) -> (Span, String) {
1076     let sp = local_decl.source_info.span;
1077     (
1078         sp,
1079         match tcx.sess.source_map().span_to_snippet(sp) {
1080             Ok(snippet) => {
1081                 let lt_pos = snippet.find('\'');
1082                 if let Some(lt_pos) = lt_pos {
1083                     format!("&{}mut self", &snippet[lt_pos..snippet.len() - 4])
1084                 } else {
1085                     "&mut self".to_string()
1086                 }
1087             }
1088             _ => "&mut self".to_string(),
1089         },
1090     )
1091 }
1092
1093 // When we want to suggest a user change a local variable to be a `&mut`, there
1094 // are three potential "obvious" things to highlight:
1095 //
1096 // let ident [: Type] [= RightHandSideExpression];
1097 //     ^^^^^    ^^^^     ^^^^^^^^^^^^^^^^^^^^^^^
1098 //     (1.)     (2.)              (3.)
1099 //
1100 // We can always fallback on highlighting the first. But chances are good that
1101 // the user experience will be better if we highlight one of the others if possible;
1102 // for example, if the RHS is present and the Type is not, then the type is going to
1103 // be inferred *from* the RHS, which means we should highlight that (and suggest
1104 // that they borrow the RHS mutably).
1105 //
1106 // This implementation attempts to emulate AST-borrowck prioritization
1107 // by trying (3.), then (2.) and finally falling back on (1.).
1108 fn suggest_ampmut<'tcx>(
1109     tcx: TyCtxt<'tcx>,
1110     local_decl: &mir::LocalDecl<'tcx>,
1111     opt_assignment_rhs_span: Option<Span>,
1112     opt_ty_info: Option<Span>,
1113 ) -> (bool, Span, String) {
1114     if let Some(assignment_rhs_span) = opt_assignment_rhs_span
1115         && let Ok(src) = tcx.sess.source_map().span_to_snippet(assignment_rhs_span)
1116     {
1117         let is_mutbl = |ty: &str| -> bool {
1118             if let Some(rest) = ty.strip_prefix("mut") {
1119                 match rest.chars().next() {
1120                     // e.g. `&mut x`
1121                     Some(c) if c.is_whitespace() => true,
1122                     // e.g. `&mut(x)`
1123                     Some('(') => true,
1124                     // e.g. `&mut{x}`
1125                     Some('{') => true,
1126                     // e.g. `&mutablevar`
1127                     _ => false,
1128                 }
1129             } else {
1130                 false
1131             }
1132         };
1133         if let (true, Some(ws_pos)) = (src.starts_with("&'"), src.find(char::is_whitespace)) {
1134             let lt_name = &src[1..ws_pos];
1135             let ty = src[ws_pos..].trim_start();
1136             if !is_mutbl(ty) {
1137                 return (true, assignment_rhs_span, format!("&{lt_name} mut {ty}"));
1138             }
1139         } else if let Some(stripped) = src.strip_prefix('&') {
1140             let stripped = stripped.trim_start();
1141             if !is_mutbl(stripped) {
1142                 return (true, assignment_rhs_span, format!("&mut {stripped}"));
1143             }
1144         }
1145     }
1146
1147     let (suggestability, highlight_span) = match opt_ty_info {
1148         // if this is a variable binding with an explicit type,
1149         // try to highlight that for the suggestion.
1150         Some(ty_span) => (true, ty_span),
1151
1152         // otherwise, just highlight the span associated with
1153         // the (MIR) LocalDecl.
1154         None => (false, local_decl.source_info.span),
1155     };
1156
1157     if let Ok(src) = tcx.sess.source_map().span_to_snippet(highlight_span)
1158         && let (true, Some(ws_pos)) = (src.starts_with("&'"), src.find(char::is_whitespace))
1159     {
1160         let lt_name = &src[1..ws_pos];
1161         let ty = &src[ws_pos..];
1162         return (true, highlight_span, format!("&{} mut{}", lt_name, ty));
1163     }
1164
1165     let ty_mut = local_decl.ty.builtin_deref(true).unwrap();
1166     assert_eq!(ty_mut.mutbl, hir::Mutability::Not);
1167     (
1168         suggestability,
1169         highlight_span,
1170         if local_decl.ty.is_region_ptr() {
1171             format!("&mut {}", ty_mut.ty)
1172         } else {
1173             format!("*mut {}", ty_mut.ty)
1174         },
1175     )
1176 }
1177
1178 fn is_closure_or_generator(ty: Ty<'_>) -> bool {
1179     ty.is_closure() || ty.is_generator()
1180 }
1181
1182 /// Given a field that needs to be mutable, returns a span where the " mut " could go.
1183 /// This function expects the local to be a reference to a struct in order to produce a span.
1184 ///
1185 /// ```text
1186 /// LL |     s: &'a   String
1187 ///    |           ^^^ returns a span taking up the space here
1188 /// ```
1189 fn get_mut_span_in_struct_field<'tcx>(
1190     tcx: TyCtxt<'tcx>,
1191     ty: Ty<'tcx>,
1192     field: mir::Field,
1193 ) -> Option<Span> {
1194     // Expect our local to be a reference to a struct of some kind.
1195     if let ty::Ref(_, ty, _) = ty.kind()
1196         && let ty::Adt(def, _) = ty.kind()
1197         && let field = def.all_fields().nth(field.index())?
1198         // Use the HIR types to construct the diagnostic message.
1199         && let node = tcx.hir().find_by_def_id(field.did.as_local()?)?
1200         // Now we're dealing with the actual struct that we're going to suggest a change to,
1201         // we can expect a field that is an immutable reference to a type.
1202         && let hir::Node::Field(field) = node
1203         && let hir::TyKind::Rptr(lt, hir::MutTy { mutbl: hir::Mutability::Not, ty }) = field.ty.kind
1204     {
1205         return Some(lt.ident.span.between(ty.span));
1206     }
1207
1208     None
1209 }
1210
1211 /// If possible, suggest replacing `ref` with `ref mut`.
1212 fn suggest_ref_mut(tcx: TyCtxt<'_>, binding_span: Span) -> Option<String> {
1213     let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).ok()?;
1214     if hi_src.starts_with("ref") && hi_src["ref".len()..].starts_with(rustc_lexer::is_whitespace) {
1215         let replacement = format!("ref mut{}", &hi_src["ref".len()..]);
1216         Some(replacement)
1217     } else {
1218         None
1219     }
1220 }