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