Skip to main content

rustc_borrowck/diagnostics/
mutability_errors.rs

1use core::ops::ControlFlow;
2
3use either::Either;
4use hir::{ExprKind, Param};
5use rustc_abi::FieldIdx;
6use rustc_errors::{Applicability, Diag};
7use rustc_hir::intravisit::Visitor;
8use rustc_hir::{self as hir, BindingMode, ByRef, Node};
9use rustc_middle::bug;
10use rustc_middle::hir::place::PlaceBase;
11use rustc_middle::mir::visit::PlaceContext;
12use rustc_middle::mir::{
13    self, BindingForm, Body, BorrowKind, Local, LocalDecl, LocalInfo, LocalKind, Location,
14    Mutability, Operand, Place, PlaceRef, ProjectionElem, RawPtrKind, Rvalue, Statement,
15    StatementKind, TerminatorKind,
16};
17use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt, Upcast};
18use rustc_span::{BytePos, DesugaringKind, Span, Symbol, kw, sym};
19use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
20use rustc_trait_selection::infer::InferCtxtExt;
21use rustc_trait_selection::traits;
22use tracing::{debug, trace};
23
24use crate::diagnostics::BorrowedContentSource;
25use crate::{MirBorrowckCtxt, session_diagnostics};
26
27#[derive(#[automatically_derived]
impl ::core::marker::Copy for AccessKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AccessKind {
    #[inline]
    fn clone(&self) -> AccessKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AccessKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AccessKind::MutableBorrow => "MutableBorrow",
                AccessKind::Mutate => "Mutate",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for AccessKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for AccessKind {
    #[inline]
    fn eq(&self, other: &AccessKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
28pub(crate) enum AccessKind {
29    MutableBorrow,
30    Mutate,
31}
32
33/// Finds all statements that assign directly to local (i.e., X = ...) and returns their
34/// locations.
35fn find_assignments(body: &Body<'_>, local: Local) -> Vec<Location> {
36    use rustc_middle::mir::visit::Visitor;
37
38    struct FindLocalAssignmentVisitor {
39        needle: Local,
40        locations: Vec<Location>,
41    }
42
43    impl<'tcx> Visitor<'tcx> for FindLocalAssignmentVisitor {
44        fn visit_local(&mut self, local: Local, place_context: PlaceContext, location: Location) {
45            if self.needle != local {
46                return;
47            }
48
49            if place_context.is_place_assignment() {
50                self.locations.push(location);
51            }
52        }
53    }
54
55    let mut visitor = FindLocalAssignmentVisitor { needle: local, locations: ::alloc::vec::Vec::new()vec![] };
56    visitor.visit_body(body);
57    visitor.locations
58}
59
60impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
61    pub(crate) fn report_mutability_error(
62        &mut self,
63        access_place: Place<'tcx>,
64        span: Span,
65        the_place_err: PlaceRef<'tcx>,
66        error_access: AccessKind,
67        location: Location,
68    ) {
69        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs:69",
                        "rustc_borrowck::diagnostics::mutability_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(69u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::mutability_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_mutability_error(access_place={0:?}, span={1:?}, the_place_err={2:?}, error_access={3:?}, location={4:?},)",
                                                    access_place, span, the_place_err, error_access, location)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(
70            "report_mutability_error(\
71                access_place={:?}, span={:?}, the_place_err={:?}, error_access={:?}, location={:?},\
72            )",
73            access_place, span, the_place_err, error_access, location,
74        );
75
76        let mut err;
77        let item_msg;
78        let reason;
79        let mut opt_source = None;
80        let access_place_desc = self.describe_any_place(access_place.as_ref());
81        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs:81",
                        "rustc_borrowck::diagnostics::mutability_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(81u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::mutability_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_mutability_error: access_place_desc={0:?}",
                                                    access_place_desc) as &dyn Value))])
            });
    } else { ; }
};debug!("report_mutability_error: access_place_desc={:?}", access_place_desc);
82
83        match the_place_err {
84            PlaceRef { local, projection: [] } => {
85                item_msg = access_place_desc;
86                if access_place.as_local().is_some() {
87                    reason = ", as it is not declared as mutable".to_string();
88                } else {
89                    let name = self.local_name(local).expect("immutable unnamed local");
90                    reason = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", as `{0}` is not declared as mutable",
                name))
    })format!(", as `{name}` is not declared as mutable");
91                }
92            }
93
94            PlaceRef {
95                local,
96                projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)],
97            } => {
98                if true {
    if !is_closure_like(Place::ty_from(local, proj_base, self.body,
                        self.infcx.tcx).ty) {
        ::core::panicking::panic("assertion failed: is_closure_like(Place::ty_from(local, proj_base, self.body,\n            self.infcx.tcx).ty)")
    };
};debug_assert!(is_closure_like(
99                    Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty
100                ));
101
102                let imm_borrow_derefed = self.upvars[upvar_index.index()]
103                    .place
104                    .deref_tys()
105                    .any(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Ref(.., hir::Mutability::Not) => true,
    _ => false,
}matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not)));
106
107                // If the place is immutable then:
108                //
109                // - Either we deref an immutable ref to get to our final place.
110                //    - We don't capture derefs of raw ptrs
111                // - Or the final place is immut because the root variable of the capture
112                //   isn't marked mut and we should suggest that to the user.
113                if imm_borrow_derefed {
114                    // If we deref an immutable ref then the suggestion here doesn't help.
115                    return;
116                } else {
117                    item_msg = access_place_desc;
118                    if self.is_upvar_field_projection(access_place.as_ref()).is_some() {
119                        reason = ", as it is not declared as mutable".to_string();
120                    } else {
121                        let name = self.upvars[upvar_index.index()].to_string(self.infcx.tcx);
122                        reason = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", as `{0}` is not declared as mutable",
                name))
    })format!(", as `{name}` is not declared as mutable");
123                    }
124                }
125            }
126
127            PlaceRef { local, projection: [ProjectionElem::Deref] }
128                if self.body.local_decls[local].is_ref_for_guard() =>
129            {
130                item_msg = access_place_desc;
131                reason = ", as it is immutable for the pattern guard".to_string();
132            }
133            PlaceRef { local, projection: [ProjectionElem::Deref] }
134                if self.body.local_decls[local].is_ref_to_static() =>
135            {
136                if access_place.projection.len() == 1 {
137                    item_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("immutable static item {0}",
                access_place_desc))
    })format!("immutable static item {access_place_desc}");
138                    reason = String::new();
139                } else {
140                    item_msg = access_place_desc;
141                    let local_info = self.body.local_decls[local].local_info();
142                    let LocalInfo::StaticRef { def_id, .. } = *local_info else {
143                        ::rustc_middle::util::bug::bug_fmt(format_args!("is_ref_to_static return true, but not ref to static?"));bug!("is_ref_to_static return true, but not ref to static?");
144                    };
145                    let static_name = &self.infcx.tcx.item_name(def_id);
146                    reason = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", as `{0}` is an immutable static item",
                static_name))
    })format!(", as `{static_name}` is an immutable static item");
147                }
148            }
149            PlaceRef { local, projection: [proj_base @ .., ProjectionElem::Deref] } => {
150                if local == ty::CAPTURE_STRUCT_LOCAL
151                    && proj_base.is_empty()
152                    && !self.upvars.is_empty()
153                {
154                    item_msg = access_place_desc;
155                    if true {
    if !self.body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty.is_ref() {
        ::core::panicking::panic("assertion failed: self.body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty.is_ref()")
    };
};debug_assert!(self.body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty.is_ref());
156                    if true {
    if !is_closure_like(the_place_err.ty(self.body, self.infcx.tcx).ty) {
        ::core::panicking::panic("assertion failed: is_closure_like(the_place_err.ty(self.body, self.infcx.tcx).ty)")
    };
};debug_assert!(is_closure_like(the_place_err.ty(self.body, self.infcx.tcx).ty));
157
158                    reason = if self.is_upvar_field_projection(access_place.as_ref()).is_some() {
159                        ", as it is a captured variable in a `Fn` closure".to_string()
160                    } else {
161                        ", as `Fn` closures cannot mutate their captured variables".to_string()
162                    }
163                } else {
164                    let source =
165                        self.borrowed_content_source(PlaceRef { local, projection: proj_base });
166                    let pointer_type = source.describe_for_immutable_place(self.infcx.tcx);
167                    opt_source = Some(source);
168                    if let Some(desc) = self.describe_place(access_place.as_ref()) {
169                        item_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", desc))
    })format!("`{desc}`");
170                        reason = match error_access {
171                            AccessKind::Mutate => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", which is behind {0}",
                pointer_type))
    })format!(", which is behind {pointer_type}"),
172                            AccessKind::MutableBorrow => {
173                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", as it is behind {0}",
                pointer_type))
    })format!(", as it is behind {pointer_type}")
174                            }
175                        }
176                    } else {
177                        item_msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("data in {0}", pointer_type))
    })format!("data in {pointer_type}");
178                        reason = String::new();
179                    }
180                }
181            }
182
183            PlaceRef {
184                local: _,
185                projection:
186                    [
187                        ..,
188                        ProjectionElem::Index(_)
189                        | ProjectionElem::ConstantIndex { .. }
190                        | ProjectionElem::OpaqueCast { .. }
191                        | ProjectionElem::Subslice { .. }
192                        | ProjectionElem::Downcast(..)
193                        | ProjectionElem::UnwrapUnsafeBinder(_),
194                    ],
195            } => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected immutable place."))bug!("Unexpected immutable place."),
196        }
197
198        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs:198",
                        "rustc_borrowck::diagnostics::mutability_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(198u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::mutability_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_mutability_error: item_msg={0:?}, reason={1:?}",
                                                    item_msg, reason) as &dyn Value))])
            });
    } else { ; }
};debug!("report_mutability_error: item_msg={:?}, reason={:?}", item_msg, reason);
199
200        // `act` and `acted_on` are strings that let us abstract over
201        // the verbs used in some diagnostic messages.
202        let act;
203        let acted_on;
204        let mut suggest = true;
205        let mut mut_error = None;
206        let mut count = 1;
207
208        let span = match error_access {
209            AccessKind::Mutate => {
210                err = self.cannot_assign(span, &(item_msg + &reason));
211                act = "assign";
212                acted_on = "written to";
213                span
214            }
215            AccessKind::MutableBorrow => {
216                act = "borrow as mutable";
217                acted_on = "borrowed as mutable";
218
219                let borrow_spans = self.borrow_spans(span, location);
220                let borrow_span = borrow_spans.args_or_use();
221                match the_place_err {
222                    PlaceRef { local, projection: [] }
223                        if self.body.local_decls[local].can_be_made_mutable() =>
224                    {
225                        let span = self.body.local_decls[local].source_info.span;
226                        mut_error = Some(span);
227                        if let Some((buffered_err, c)) = self.get_buffered_mut_error(span) {
228                            // We've encountered a second (or more) attempt to mutably borrow an
229                            // immutable binding, so the likely problem is with the binding
230                            // declaration, not the use. We collect these in a single diagnostic
231                            // and make the binding the primary span of the error.
232                            err = buffered_err;
233                            count = c + 1;
234                            if count == 2 {
235                                err.replace_span_with(span, false);
236                                err.span_label(span, "not mutable");
237                            }
238                            suggest = false;
239                        } else {
240                            err = self.cannot_borrow_path_as_mutable_because(
241                                borrow_span,
242                                &item_msg,
243                                &reason,
244                            );
245                        }
246                    }
247                    _ => {
248                        err = self.cannot_borrow_path_as_mutable_because(
249                            borrow_span,
250                            &item_msg,
251                            &reason,
252                        );
253                    }
254                }
255                if suggest {
256                    borrow_spans.var_subdiag(
257                        &mut err,
258                        Some(mir::BorrowKind::Mut { kind: mir::MutBorrowKind::Default }),
259                        |_kind, var_span| {
260                            let place = self.describe_any_place(access_place.as_ref());
261                            session_diagnostics::CaptureVarCause::MutableBorrowUsePlaceClosure {
262                                place,
263                                var_span,
264                            }
265                        },
266                    );
267                }
268                borrow_span
269            }
270        };
271
272        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs:272",
                        "rustc_borrowck::diagnostics::mutability_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(272u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::mutability_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_mutability_error: act={0:?}, acted_on={1:?}",
                                                    act, acted_on) as &dyn Value))])
            });
    } else { ; }
};debug!("report_mutability_error: act={:?}, acted_on={:?}", act, acted_on);
273
274        match the_place_err {
275            // Suggest making an existing shared borrow in a struct definition a mutable borrow.
276            //
277            // This is applicable when we have a deref of a field access to a deref of a local -
278            // something like `*((*_1).0`. The local that we get will be a reference to the
279            // struct we've got a field access of (it must be a reference since there's a deref
280            // after the field access).
281            PlaceRef {
282                local,
283                projection:
284                    [
285                        proj_base @ ..,
286                        ProjectionElem::Deref,
287                        ProjectionElem::Field(field, _),
288                        ProjectionElem::Deref,
289                    ],
290            } => {
291                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
292
293                let place = Place::ty_from(local, proj_base, self.body, self.infcx.tcx);
294                if let Some(span) = get_mut_span_in_struct_field(self.infcx.tcx, place.ty, *field) {
295                    err.span_suggestion_verbose(
296                        span,
297                        "consider changing this to be mutable",
298                        " mut ",
299                        Applicability::MaybeIncorrect,
300                    );
301                }
302            }
303
304            // Suggest removing a `&mut` from the use of a mutable reference.
305            PlaceRef { local, projection: [] }
306                if self
307                    .body
308                    .local_decls
309                    .get(local)
310                    .is_some_and(|l| mut_borrow_of_mutable_ref(l, self.local_name(local))) =>
311            {
312                let decl = &self.body.local_decls[local];
313                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
314                if let Some(mir::Statement {
315                    source_info,
316                    kind:
317                        mir::StatementKind::Assign(box (
318                            _,
319                            mir::Rvalue::Ref(
320                                _,
321                                mir::BorrowKind::Mut { kind: mir::MutBorrowKind::Default },
322                                _,
323                            ),
324                        )),
325                    ..
326                }) = &self.body[location.block].statements.get(location.statement_index)
327                {
328                    match *decl.local_info() {
329                        LocalInfo::User(BindingForm::Var(mir::VarBindingForm {
330                            binding_mode: BindingMode(ByRef::No, Mutability::Not),
331                            opt_ty_info: Some(sp),
332                            pat_span,
333                            ..
334                        })) => {
335                            if suggest {
336                                err.span_note(sp, "the binding is already a mutable borrow");
337                                err.span_suggestion_verbose(
338                                    pat_span.shrink_to_lo(),
339                                    "consider making the binding mutable if you need to reborrow \
340                                     multiple times",
341                                    "mut ".to_string(),
342                                    Applicability::MaybeIncorrect,
343                                );
344                            }
345                        }
346                        _ => {
347                            err.span_note(
348                                decl.source_info.span,
349                                "the binding is already a mutable borrow",
350                            );
351                        }
352                    }
353                    if let Ok(snippet) =
354                        self.infcx.tcx.sess.source_map().span_to_snippet(source_info.span)
355                    {
356                        if snippet.starts_with("&mut ") {
357                            // We don't have access to the HIR to get accurate spans, but we can
358                            // give a best effort structured suggestion.
359                            err.span_suggestion_verbose(
360                                source_info.span.with_hi(source_info.span.lo() + BytePos(5)),
361                                "if there is only one mutable reborrow, remove the `&mut`",
362                                "",
363                                Applicability::MaybeIncorrect,
364                            );
365                        } else {
366                            // This can occur with things like `(&mut self).foo()`.
367                            err.span_help(source_info.span, "try removing `&mut` here");
368                        }
369                    } else {
370                        err.span_help(source_info.span, "try removing `&mut` here");
371                    }
372                } else if decl.mutability.is_not() {
373                    if #[allow(non_exhaustive_omitted_patterns)] match decl.local_info() {
    LocalInfo::User(BindingForm::ImplicitSelf(hir::ImplicitSelfKind::RefMut))
        => true,
    _ => false,
}matches!(
374                        decl.local_info(),
375                        LocalInfo::User(BindingForm::ImplicitSelf(hir::ImplicitSelfKind::RefMut))
376                    ) {
377                        err.note(
378                            "as `Self` may be unsized, this call attempts to take `&mut &mut self`",
379                        );
380                        err.note("however, `&mut self` expands to `self: &mut Self`, therefore `self` cannot be borrowed mutably");
381                    } else {
382                        err.span_suggestion_verbose(
383                            decl.source_info.span.shrink_to_lo(),
384                            "consider making the binding mutable",
385                            "mut ",
386                            Applicability::MachineApplicable,
387                        );
388                    };
389                }
390            }
391
392            // We want to suggest users use `let mut` for local (user
393            // variable) mutations...
394            PlaceRef { local, projection: [] }
395                if self.body.local_decls[local].can_be_made_mutable() =>
396            {
397                // ... but it doesn't make sense to suggest it on
398                // variables that are `ref x`, `ref mut x`, `&self`,
399                // or `&mut self` (such variables are simply not
400                // mutable).
401                let local_decl = &self.body.local_decls[local];
402                match (&local_decl.mutability, &Mutability::Not) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(local_decl.mutability, Mutability::Not);
403
404                if count < 10 {
405                    err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
406                }
407                if suggest {
408                    self.construct_mut_suggestion_for_local_binding_patterns(&mut err, local);
409                    let tcx = self.infcx.tcx;
410                    if let ty::Closure(id, _) = *the_place_err.ty(self.body, tcx).ty.kind() {
411                        self.show_mutating_upvar(tcx, id.expect_local(), the_place_err, &mut err);
412                    }
413                }
414            }
415
416            // Also suggest adding mut for upvars.
417            PlaceRef {
418                local,
419                projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)],
420            } => {
421                if true {
    if !is_closure_like(Place::ty_from(local, proj_base, self.body,
                        self.infcx.tcx).ty) {
        ::core::panicking::panic("assertion failed: is_closure_like(Place::ty_from(local, proj_base, self.body,\n            self.infcx.tcx).ty)")
    };
};debug_assert!(is_closure_like(
422                    Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty
423                ));
424
425                let captured_place = self.upvars[upvar_index.index()];
426
427                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
428
429                let upvar_hir_id = captured_place.get_root_variable();
430
431                if let Node::Pat(pat) = self.infcx.tcx.hir_node(upvar_hir_id)
432                    && let hir::PatKind::Binding(hir::BindingMode::NONE, _, upvar_ident, _) =
433                        pat.kind
434                {
435                    if upvar_ident.name == kw::SelfLower {
436                        for (_, node) in self.infcx.tcx.hir_parent_iter(upvar_hir_id) {
437                            if let Some(fn_decl) = node.fn_decl() {
438                                if !#[allow(non_exhaustive_omitted_patterns)] match fn_decl.implicit_self {
    hir::ImplicitSelfKind::RefImm | hir::ImplicitSelfKind::RefMut => true,
    _ => false,
}matches!(
439                                    fn_decl.implicit_self,
440                                    hir::ImplicitSelfKind::RefImm | hir::ImplicitSelfKind::RefMut
441                                ) {
442                                    err.span_suggestion_verbose(
443                                        upvar_ident.span.shrink_to_lo(),
444                                        "consider changing this to be mutable",
445                                        "mut ",
446                                        Applicability::MachineApplicable,
447                                    );
448                                    break;
449                                }
450                            }
451                        }
452                    } else {
453                        err.span_suggestion_verbose(
454                            upvar_ident.span.shrink_to_lo(),
455                            "consider changing this to be mutable",
456                            "mut ",
457                            Applicability::MachineApplicable,
458                        );
459                    }
460                }
461
462                let tcx = self.infcx.tcx;
463                if let ty::Ref(_, ty, Mutability::Mut) = the_place_err.ty(self.body, tcx).ty.kind()
464                    && let ty::Closure(id, _) = *ty.kind()
465                {
466                    self.show_mutating_upvar(tcx, id.expect_local(), the_place_err, &mut err);
467                }
468            }
469
470            // Complete hack to approximate old AST-borrowck diagnostic: if the span starts
471            // with a mutable borrow of a local variable, then just suggest the user remove it.
472            PlaceRef { local: _, projection: [] }
473                if self
474                    .infcx
475                    .tcx
476                    .sess
477                    .source_map()
478                    .span_to_snippet(span)
479                    .is_ok_and(|snippet| snippet.starts_with("&mut ")) =>
480            {
481                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
482                err.span_suggestion_verbose(
483                    span.with_hi(span.lo() + BytePos(5)),
484                    "try removing `&mut` here",
485                    "",
486                    Applicability::MaybeIncorrect,
487                );
488            }
489
490            PlaceRef { local, projection: [ProjectionElem::Deref] }
491                if self.body.local_decls[local].is_ref_for_guard() =>
492            {
493                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
494                err.note(
495                    "variables bound in patterns are immutable until the end of the pattern guard",
496                );
497            }
498
499            // We want to point out when a `&` can be readily replaced
500            // with an `&mut`.
501            //
502            // FIXME: can this case be generalized to work for an
503            // arbitrary base for the projection?
504            PlaceRef { local, projection: [ProjectionElem::Deref] }
505                if self.body.local_decls[local].is_user_variable() =>
506            {
507                let local_decl = &self.body.local_decls[local];
508
509                let (pointer_sigil, pointer_desc) =
510                    if local_decl.ty.is_ref() { ("&", "reference") } else { ("*const", "pointer") };
511
512                match self.local_name(local) {
513                    Some(name) if !local_decl.from_compiler_desugaring() => {
514                        err.span_label(
515                            span,
516                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a `{1}` {2}, so it cannot be {3}",
                name, pointer_sigil, pointer_desc, acted_on))
    })format!(
517                                "`{name}` is a `{pointer_sigil}` {pointer_desc}, so it cannot be \
518                                 {acted_on}",
519                            ),
520                        );
521
522                        self.suggest_using_iter_mut(&mut err);
523                        self.suggest_make_local_mut(&mut err, local, name);
524                    }
525                    _ => {
526                        err.span_label(
527                            span,
528                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0} through `{1}` {2}", act,
                pointer_sigil, pointer_desc))
    })format!("cannot {act} through `{pointer_sigil}` {pointer_desc}"),
529                        );
530                    }
531                }
532            }
533
534            PlaceRef { local, projection: [ProjectionElem::Deref] }
535                if local == ty::CAPTURE_STRUCT_LOCAL && !self.upvars.is_empty() =>
536            {
537                self.point_at_binding_outside_closure(&mut err, local, access_place);
538                self.expected_fn_found_fn_mut_call(&mut err, span, act);
539            }
540
541            PlaceRef { local, projection: [.., ProjectionElem::Deref] } => {
542                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
543
544                match opt_source {
545                    Some(BorrowedContentSource::OverloadedDeref(ty)) => {
546                        err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait `DerefMut` is required to modify through a dereference, but it is not implemented for `{0}`",
                ty))
    })format!(
547                            "trait `DerefMut` is required to modify through a dereference, \
548                             but it is not implemented for `{ty}`",
549                        ));
550                    }
551                    Some(BorrowedContentSource::OverloadedIndex(ty)) => {
552                        err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("trait `IndexMut` is required to modify indexed content, but it is not implemented for `{0}`",
                ty))
    })format!(
553                            "trait `IndexMut` is required to modify indexed content, \
554                             but it is not implemented for `{ty}`",
555                        ));
556                        self.suggest_map_index_mut_alternatives(ty, &mut err, span);
557                    }
558                    _ => {
559                        let local = &self.body.local_decls[local];
560                        match local.local_info() {
561                            LocalInfo::StaticRef { def_id, .. } => {
562                                let span = self.infcx.tcx.def_span(def_id);
563                                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this `static` cannot be {0}",
                acted_on))
    })format!("this `static` cannot be {acted_on}"));
564                            }
565                            LocalInfo::ConstRef { def_id } => {
566                                let span = self.infcx.tcx.def_span(def_id);
567                                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this `const` cannot be {0}",
                acted_on))
    })format!("this `const` cannot be {acted_on}"));
568                            }
569                            LocalInfo::BlockTailTemp(_) | LocalInfo::Boring
570                                if !local.source_info.span.overlaps(span) =>
571                            {
572                                err.span_label(
573                                    local.source_info.span,
574                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this cannot be {0}", acted_on))
    })format!("this cannot be {acted_on}"),
575                                );
576                            }
577                            _ => {}
578                        }
579                    }
580                }
581            }
582
583            PlaceRef { local, .. } => {
584                let local = &self.body.local_decls[local];
585                if !local.source_info.span.overlaps(span) {
586                    err.span_label(local.source_info.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this cannot be {0}", acted_on))
    })format!("this cannot be {acted_on}"));
587                }
588                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
589            }
590        }
591
592        if let Some(span) = mut_error {
593            self.buffer_mut_error(span, err, count);
594        } else {
595            self.buffer_error(err);
596        }
597    }
598
599    /// Suggest `map[k] = v` => `map.insert(k, v)` and the like.
600    fn suggest_map_index_mut_alternatives(&self, ty: Ty<'tcx>, err: &mut Diag<'infcx>, span: Span) {
601        let Some(adt) = ty.ty_adt_def() else { return };
602        let did = adt.did();
603        if self.infcx.tcx.is_diagnostic_item(sym::HashMap, did)
604            || self.infcx.tcx.is_diagnostic_item(sym::BTreeMap, did)
605        {
606            /// Walks through the HIR, looking for the corresponding span for this error.
607            /// When it finds it, see if it corresponds to assignment operator whose LHS
608            /// is an index expr.
609            struct SuggestIndexOperatorAlternativeVisitor<'a, 'infcx, 'tcx> {
610                assign_span: Span,
611                err: &'a mut Diag<'infcx>,
612                ty: Ty<'tcx>,
613                suggested: bool,
614            }
615            impl<'a, 'infcx, 'tcx> Visitor<'tcx> for SuggestIndexOperatorAlternativeVisitor<'a, 'infcx, 'tcx> {
616                fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
617                    hir::intravisit::walk_stmt(self, stmt);
618                    let expr = match stmt.kind {
619                        hir::StmtKind::Semi(expr) | hir::StmtKind::Expr(expr) => expr,
620                        hir::StmtKind::Let(hir::LetStmt { init: Some(expr), .. }) => expr,
621                        _ => {
622                            return;
623                        }
624                    };
625                    if let hir::ExprKind::Assign(place, rv, _sp) = expr.kind
626                        && let hir::ExprKind::Index(val, index, _) = place.kind
627                        && (expr.span == self.assign_span || place.span == self.assign_span)
628                    {
629                        // val[index] = rv;
630                        // ---------- place
631                        self.err.multipart_suggestions(
632                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `.insert()` to insert a value into a `{0}`, `.get_mut()` to modify it, or the entry API for more flexibility",
                self.ty))
    })format!(
633                                "use `.insert()` to insert a value into a `{}`, `.get_mut()` \
634                                to modify it, or the entry API for more flexibility",
635                                self.ty,
636                            ),
637                            <[_]>::into_vec(::alloc::boxed::box_new([<[_]>::into_vec(::alloc::boxed::box_new([(val.span.shrink_to_hi().with_hi(index.span.lo()),
                                    ".insert(".to_string()),
                                (index.span.shrink_to_hi().with_hi(rv.span.lo()),
                                    ", ".to_string()),
                                (rv.span.shrink_to_hi(), ")".to_string())])),
                <[_]>::into_vec(::alloc::boxed::box_new([(val.span.shrink_to_lo(),
                                    "if let Some(val) = ".to_string()),
                                (val.span.shrink_to_hi().with_hi(index.span.lo()),
                                    ".get_mut(".to_string()),
                                (index.span.shrink_to_hi().with_hi(place.span.hi()),
                                    ") { *val".to_string()),
                                (rv.span.shrink_to_hi(), "; }".to_string())])),
                <[_]>::into_vec(::alloc::boxed::box_new([(val.span.shrink_to_lo(),
                                    "let val = ".to_string()),
                                (val.span.shrink_to_hi().with_hi(index.span.lo()),
                                    ".entry(".to_string()),
                                (index.span.shrink_to_hi().with_hi(rv.span.lo()),
                                    ").or_insert(".to_string()),
                                (rv.span.shrink_to_hi(), ")".to_string())]))]))vec![
638                                vec![
639                                    // val.insert(index, rv);
640                                    (
641                                        val.span.shrink_to_hi().with_hi(index.span.lo()),
642                                        ".insert(".to_string(),
643                                    ),
644                                    (
645                                        index.span.shrink_to_hi().with_hi(rv.span.lo()),
646                                        ", ".to_string(),
647                                    ),
648                                    (rv.span.shrink_to_hi(), ")".to_string()),
649                                ],
650                                vec![
651                                    // if let Some(v) = val.get_mut(index) { *v = rv; }
652                                    (val.span.shrink_to_lo(), "if let Some(val) = ".to_string()),
653                                    (
654                                        val.span.shrink_to_hi().with_hi(index.span.lo()),
655                                        ".get_mut(".to_string(),
656                                    ),
657                                    (
658                                        index.span.shrink_to_hi().with_hi(place.span.hi()),
659                                        ") { *val".to_string(),
660                                    ),
661                                    (rv.span.shrink_to_hi(), "; }".to_string()),
662                                ],
663                                vec![
664                                    // let x = val.entry(index).or_insert(rv);
665                                    (val.span.shrink_to_lo(), "let val = ".to_string()),
666                                    (
667                                        val.span.shrink_to_hi().with_hi(index.span.lo()),
668                                        ".entry(".to_string(),
669                                    ),
670                                    (
671                                        index.span.shrink_to_hi().with_hi(rv.span.lo()),
672                                        ").or_insert(".to_string(),
673                                    ),
674                                    (rv.span.shrink_to_hi(), ")".to_string()),
675                                ],
676                            ],
677                            Applicability::MachineApplicable,
678                        );
679                        self.suggested = true;
680                    } else if let hir::ExprKind::MethodCall(_path, receiver, _, sp) = expr.kind
681                        && let hir::ExprKind::Index(val, index, _) = receiver.kind
682                        && receiver.span == self.assign_span
683                    {
684                        // val[index].path(args..);
685                        self.err.multipart_suggestion(
686                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to modify a `{0}` use `.get_mut()`",
                self.ty))
    })format!("to modify a `{}` use `.get_mut()`", self.ty),
687                            <[_]>::into_vec(::alloc::boxed::box_new([(val.span.shrink_to_lo(),
                    "if let Some(val) = ".to_string()),
                (val.span.shrink_to_hi().with_hi(index.span.lo()),
                    ".get_mut(".to_string()),
                (index.span.shrink_to_hi().with_hi(receiver.span.hi()),
                    ") { val".to_string()),
                (sp.shrink_to_hi(), "; }".to_string())]))vec![
688                                (val.span.shrink_to_lo(), "if let Some(val) = ".to_string()),
689                                (
690                                    val.span.shrink_to_hi().with_hi(index.span.lo()),
691                                    ".get_mut(".to_string(),
692                                ),
693                                (
694                                    index.span.shrink_to_hi().with_hi(receiver.span.hi()),
695                                    ") { val".to_string(),
696                                ),
697                                (sp.shrink_to_hi(), "; }".to_string()),
698                            ],
699                            Applicability::MachineApplicable,
700                        );
701                        self.suggested = true;
702                    }
703                }
704            }
705            let def_id = self.body.source.def_id();
706            let Some(local_def_id) = def_id.as_local() else { return };
707            let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(local_def_id) else { return };
708
709            let mut v = SuggestIndexOperatorAlternativeVisitor {
710                assign_span: span,
711                err,
712                ty,
713                suggested: false,
714            };
715            v.visit_body(&body);
716            if !v.suggested {
717                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to modify a `{0}`, use `.get_mut()`, `.insert()` or the entry API",
                ty))
    })format!(
718                    "to modify a `{ty}`, use `.get_mut()`, `.insert()` or the entry API",
719                ));
720            }
721        }
722    }
723
724    /// User cannot make signature of a trait mutable without changing the
725    /// trait. So we find if this error belongs to a trait and if so we move
726    /// suggestion to the trait or disable it if it is out of scope of this crate
727    ///
728    /// The returned values are:
729    ///  - is the current item an assoc `fn` of an impl that corresponds to a trait def? if so, we
730    ///    have to suggest changing both the impl `fn` arg and the trait `fn` arg
731    ///  - is the trait from the local crate? If not, we can't suggest changing signatures
732    ///  - `Span` of the argument in the trait definition
733    fn is_error_in_trait(&self, local: Local) -> (bool, bool, Option<Span>) {
734        let tcx = self.infcx.tcx;
735        if self.body.local_kind(local) != LocalKind::Arg {
736            return (false, false, None);
737        }
738        let my_def = self.body.source.def_id();
739        let Some(td) = tcx.trait_impl_of_assoc(my_def).map(|id| self.infcx.tcx.impl_trait_id(id))
740        else {
741            return (false, false, None);
742        };
743
744        let implemented_trait_item = self.infcx.tcx.trait_item_of(my_def);
745
746        (
747            true,
748            td.is_local(),
749            implemented_trait_item.and_then(|f_in_trait| {
750                let f_in_trait = f_in_trait.as_local()?;
751                if let Node::TraitItem(ti) = self.infcx.tcx.hir_node_by_def_id(f_in_trait)
752                    && let hir::TraitItemKind::Fn(sig, _) = ti.kind
753                    && let Some(ty) = sig.decl.inputs.get(local.index() - 1)
754                    && let hir::TyKind::Ref(_, mut_ty) = ty.kind
755                    && let hir::Mutability::Not = mut_ty.mutbl
756                    && sig.decl.implicit_self.has_implicit_self()
757                {
758                    Some(ty.span)
759                } else {
760                    None
761                }
762            }),
763        )
764    }
765
766    fn construct_mut_suggestion_for_local_binding_patterns(
767        &self,
768        err: &mut Diag<'_>,
769        local: Local,
770    ) {
771        let local_decl = &self.body.local_decls[local];
772        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs:772",
                        "rustc_borrowck::diagnostics::mutability_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(772u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::mutability_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("local_decl: {0:?}",
                                                    local_decl) as &dyn Value))])
            });
    } else { ; }
};debug!("local_decl: {:?}", local_decl);
773        let pat_span = match *local_decl.local_info() {
774            LocalInfo::User(BindingForm::Var(mir::VarBindingForm {
775                binding_mode: BindingMode(ByRef::No, Mutability::Not),
776                opt_ty_info: _,
777                opt_match_place: _,
778                pat_span,
779                introductions: _,
780            })) => pat_span,
781            _ => local_decl.source_info.span,
782        };
783
784        // With ref-binding patterns, the mutability suggestion has to apply to
785        // the binding, not the reference (which would be a type error):
786        //
787        // `let &b = a;` -> `let &(mut b) = a;`
788        // or
789        // `fn foo(&x: &i32)` -> `fn foo(&(mut x): &i32)`
790        let def_id = self.body.source.def_id();
791        if let Some(local_def_id) = def_id.as_local()
792            && let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(local_def_id)
793            && let Some(hir_id) = (BindingFinder { span: pat_span }).visit_body(&body).break_value()
794            && let node = self.infcx.tcx.hir_node(hir_id)
795            && let hir::Node::LetStmt(hir::LetStmt {
796                pat: hir::Pat { kind: hir::PatKind::Ref(_, _, _), .. },
797                ..
798            })
799            | hir::Node::Param(Param {
800                pat: hir::Pat { kind: hir::PatKind::Ref(_, _, _), .. },
801                ..
802            }) = node
803        {
804            err.multipart_suggestion(
805                "consider changing this to be mutable",
806                <[_]>::into_vec(::alloc::boxed::box_new([(pat_span.until(local_decl.source_info.span),
                    "&(mut ".to_string()),
                (local_decl.source_info.span.shrink_to_hi().with_hi(pat_span.hi()),
                    ")".to_string())]))vec![
807                    (pat_span.until(local_decl.source_info.span), "&(mut ".to_string()),
808                    (
809                        local_decl.source_info.span.shrink_to_hi().with_hi(pat_span.hi()),
810                        ")".to_string(),
811                    ),
812                ],
813                Applicability::MachineApplicable,
814            );
815            return;
816        }
817
818        err.span_suggestion_verbose(
819            local_decl.source_info.span.shrink_to_lo(),
820            "consider changing this to be mutable",
821            "mut ",
822            Applicability::MachineApplicable,
823        );
824    }
825
826    // Point to span of upvar making closure call that requires a mutable borrow
827    fn show_mutating_upvar(
828        &self,
829        tcx: TyCtxt<'_>,
830        closure_local_def_id: hir::def_id::LocalDefId,
831        the_place_err: PlaceRef<'tcx>,
832        err: &mut Diag<'_>,
833    ) {
834        let tables = tcx.typeck(closure_local_def_id);
835        if let Some((span, closure_kind_origin)) = tcx.closure_kind_origin(closure_local_def_id) {
836            let reason = if let PlaceBase::Upvar(upvar_id) = closure_kind_origin.base {
837                let upvar = ty::place_to_string_for_capture(tcx, closure_kind_origin);
838                let root_hir_id = upvar_id.var_path.hir_id;
839                // We have an origin for this closure kind starting at this root variable so it's
840                // safe to unwrap here.
841                let captured_places =
842                    tables.closure_min_captures[&closure_local_def_id].get(&root_hir_id).unwrap();
843
844                let origin_projection = closure_kind_origin
845                    .projections
846                    .iter()
847                    .map(|proj| proj.kind)
848                    .collect::<Vec<_>>();
849                let mut capture_reason = String::new();
850                for captured_place in captured_places {
851                    let captured_place_kinds = captured_place
852                        .place
853                        .projections
854                        .iter()
855                        .map(|proj| proj.kind)
856                        .collect::<Vec<_>>();
857                    if rustc_middle::ty::is_ancestor_or_same_capture(
858                        &captured_place_kinds,
859                        &origin_projection,
860                    ) {
861                        match captured_place.info.capture_kind {
862                            ty::UpvarCapture::ByRef(
863                                ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
864                            ) => {
865                                capture_reason = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("mutable borrow of `{0}`", upvar))
    })format!("mutable borrow of `{upvar}`");
866                            }
867                            ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
868                                capture_reason = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("possible mutation of `{0}`",
                upvar))
    })format!("possible mutation of `{upvar}`");
869                            }
870                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("upvar `{0}` borrowed, but not mutably",
        upvar))bug!("upvar `{upvar}` borrowed, but not mutably"),
871                        }
872                        break;
873                    }
874                }
875                if capture_reason.is_empty() {
876                    ::rustc_middle::util::bug::bug_fmt(format_args!("upvar `{0}` borrowed, but cannot find reason",
        upvar));bug!("upvar `{upvar}` borrowed, but cannot find reason");
877                }
878                capture_reason
879            } else {
880                ::rustc_middle::util::bug::bug_fmt(format_args!("not an upvar"))bug!("not an upvar")
881            };
882            // Sometimes we deliberately don't store the name of a place when coming from a macro in
883            // another crate. We generally want to limit those diagnostics a little, to hide
884            // implementation details (such as those from pin!() or format!()). In that case show a
885            // slightly different error message, or none at all if something else happened. In other
886            // cases the message is likely not useful.
887            if let Some(place_name) = self.describe_place(the_place_err) {
888                err.span_label(
889                    *span,
890                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("calling `{0}` requires mutable binding due to {1}",
                place_name, reason))
    })format!("calling `{place_name}` requires mutable binding due to {reason}"),
891                );
892            } else if span.from_expansion() {
893                err.span_label(
894                    *span,
895                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a call in this macro requires a mutable binding due to {0}",
                reason))
    })format!("a call in this macro requires a mutable binding due to {reason}",),
896                );
897            }
898        }
899    }
900
901    // Attempt to search similar mutable associated items for suggestion.
902    // In the future, attempt in all path but initially for RHS of for_loop
903    fn suggest_similar_mut_method_for_for_loop(&self, err: &mut Diag<'_>, span: Span) {
904        use hir::ExprKind::{AddrOf, Block, Call, MethodCall};
905        use hir::{BorrowKind, Expr};
906
907        let tcx = self.infcx.tcx;
908        struct Finder {
909            span: Span,
910        }
911
912        impl<'tcx> Visitor<'tcx> for Finder {
913            type Result = ControlFlow<&'tcx Expr<'tcx>>;
914            fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) -> Self::Result {
915                if e.span == self.span {
916                    ControlFlow::Break(e)
917                } else {
918                    hir::intravisit::walk_expr(self, e)
919                }
920            }
921        }
922        if let Some(body) = tcx.hir_maybe_body_owned_by(self.mir_def_id())
923            && let Block(block, _) = body.value.kind
924        {
925            // `span` corresponds to the expression being iterated, find the `for`-loop desugared
926            // expression with that span in order to identify potential fixes when encountering a
927            // read-only iterator that should be mutable.
928            if let ControlFlow::Break(expr) = (Finder { span }).visit_block(block)
929                && let Call(_, [expr]) = expr.kind
930            {
931                match expr.kind {
932                    MethodCall(path_segment, _, _, span) => {
933                        // We have `for _ in iter.read_only_iter()`, try to
934                        // suggest `for _ in iter.mutable_iter()` instead.
935                        let opt_suggestions = tcx
936                            .typeck(path_segment.hir_id.owner.def_id)
937                            .type_dependent_def_id(expr.hir_id)
938                            .and_then(|def_id| tcx.impl_of_assoc(def_id))
939                            .map(|def_id| tcx.associated_items(def_id))
940                            .map(|assoc_items| {
941                                assoc_items
942                                    .in_definition_order()
943                                    .map(|assoc_item_def| assoc_item_def.ident(tcx))
944                                    .filter(|&ident| {
945                                        let original_method_ident = path_segment.ident;
946                                        original_method_ident != ident
947                                            && ident.as_str().starts_with(
948                                                &original_method_ident.name.to_string(),
949                                            )
950                                    })
951                                    .map(|ident| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}()", ident))
    })format!("{ident}()"))
952                                    .peekable()
953                            });
954
955                        if let Some(mut suggestions) = opt_suggestions
956                            && suggestions.peek().is_some()
957                        {
958                            err.span_suggestions(
959                                span,
960                                "use mutable method",
961                                suggestions,
962                                Applicability::MaybeIncorrect,
963                            );
964                        }
965                    }
966                    AddrOf(BorrowKind::Ref, Mutability::Not, expr) => {
967                        // We have `for _ in &i`, suggest `for _ in &mut i`.
968                        err.span_suggestion_verbose(
969                            expr.span.shrink_to_lo(),
970                            "use a mutable iterator instead",
971                            "mut ",
972                            Applicability::MachineApplicable,
973                        );
974                    }
975                    _ => {}
976                }
977            }
978        }
979    }
980
981    /// When modifying a binding from inside of an `Fn` closure, point at the binding definition.
982    fn point_at_binding_outside_closure(
983        &self,
984        err: &mut Diag<'_>,
985        local: Local,
986        access_place: Place<'tcx>,
987    ) {
988        let place = access_place.as_ref();
989        for (index, elem) in place.projection.into_iter().enumerate() {
990            if let ProjectionElem::Deref = elem {
991                if index == 0 {
992                    if self.body.local_decls[local].is_ref_for_guard() {
993                        continue;
994                    }
995                    if let LocalInfo::StaticRef { .. } = *self.body.local_decls[local].local_info()
996                    {
997                        continue;
998                    }
999                }
1000                if let Some(field) = self.is_upvar_field_projection(PlaceRef {
1001                    local,
1002                    projection: place.projection.split_at(index + 1).0,
1003                }) {
1004                    let var_index = field.index();
1005                    let upvar = self.upvars[var_index];
1006                    if let Some(hir_id) = upvar.info.capture_kind_expr_id {
1007                        let node = self.infcx.tcx.hir_node(hir_id);
1008                        if let hir::Node::Expr(expr) = node
1009                            && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1010                            && let hir::def::Res::Local(hir_id) = path.res
1011                            && let hir::Node::Pat(pat) = self.infcx.tcx.hir_node(hir_id)
1012                        {
1013                            let name = upvar.to_string(self.infcx.tcx);
1014                            err.span_label(
1015                                pat.span,
1016                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` declared here, outside the closure",
                name))
    })format!("`{name}` declared here, outside the closure"),
1017                            );
1018                            break;
1019                        }
1020                    }
1021                }
1022            }
1023        }
1024    }
1025    /// Targeted error when encountering an `FnMut` closure where an `Fn` closure was expected.
1026    fn expected_fn_found_fn_mut_call(&self, err: &mut Diag<'_>, sp: Span, act: &str) {
1027        err.span_label(sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot {0}", act))
    })format!("cannot {act}"));
1028
1029        let tcx = self.infcx.tcx;
1030        let closure_id = self.mir_hir_id();
1031        let closure_span = tcx.def_span(self.mir_def_id());
1032        let fn_call_id = tcx.parent_hir_id(closure_id);
1033        let node = tcx.hir_node(fn_call_id);
1034        let def_id = tcx.hir_enclosing_body_owner(fn_call_id);
1035        let mut look_at_return = true;
1036
1037        err.span_label(closure_span, "in this closure");
1038        // If the HIR node is a function or method call, get the DefId
1039        // of the callee function or method, the span, and args of the call expr
1040        let get_call_details = || {
1041            let hir::Node::Expr(hir::Expr { hir_id, kind, .. }) = node else {
1042                return None;
1043            };
1044
1045            let typeck_results = tcx.typeck(def_id);
1046
1047            match kind {
1048                hir::ExprKind::Call(expr, args) => {
1049                    if let Some(ty::FnDef(def_id, _)) =
1050                        typeck_results.node_type_opt(expr.hir_id).as_ref().map(|ty| ty.kind())
1051                    {
1052                        Some((*def_id, expr.span, *args))
1053                    } else {
1054                        None
1055                    }
1056                }
1057                hir::ExprKind::MethodCall(_, _, args, span) => typeck_results
1058                    .type_dependent_def_id(*hir_id)
1059                    .map(|def_id| (def_id, *span, *args)),
1060                _ => None,
1061            }
1062        };
1063
1064        // If we can detect the expression to be a function or method call where the closure was
1065        // an argument, we point at the function or method definition argument...
1066        if let Some((callee_def_id, call_span, call_args)) = get_call_details() {
1067            let arg_pos = call_args
1068                .iter()
1069                .enumerate()
1070                .filter(|(_, arg)| arg.hir_id == closure_id)
1071                .map(|(pos, _)| pos)
1072                .next();
1073
1074            let arg = match tcx.hir_get_if_local(callee_def_id) {
1075                Some(
1076                    hir::Node::Item(hir::Item {
1077                        kind: hir::ItemKind::Fn { ident, sig, .. }, ..
1078                    })
1079                    | hir::Node::TraitItem(hir::TraitItem {
1080                        ident,
1081                        kind: hir::TraitItemKind::Fn(sig, _),
1082                        ..
1083                    })
1084                    | hir::Node::ImplItem(hir::ImplItem {
1085                        ident,
1086                        kind: hir::ImplItemKind::Fn(sig, _),
1087                        ..
1088                    }),
1089                ) => Some(
1090                    arg_pos
1091                        .and_then(|pos| {
1092                            sig.decl.inputs.get(
1093                                pos + if sig.decl.implicit_self.has_implicit_self() {
1094                                    1
1095                                } else {
1096                                    0
1097                                },
1098                            )
1099                        })
1100                        .map(|arg| arg.span)
1101                        .unwrap_or(ident.span),
1102                ),
1103                _ => None,
1104            };
1105            if let Some(span) = arg {
1106                err.span_label(span, "change this to accept `FnMut` instead of `Fn`");
1107                err.span_label(call_span, "expects `Fn` instead of `FnMut`");
1108                look_at_return = false;
1109            }
1110        }
1111
1112        if look_at_return && tcx.hir_get_fn_id_for_return_block(closure_id).is_some() {
1113            // ...otherwise we are probably in the tail expression of the function, point at the
1114            // return type.
1115            match tcx.hir_node_by_def_id(tcx.hir_get_parent_item(fn_call_id).def_id) {
1116                hir::Node::Item(hir::Item {
1117                    kind: hir::ItemKind::Fn { ident, sig, .. }, ..
1118                })
1119                | hir::Node::TraitItem(hir::TraitItem {
1120                    ident,
1121                    kind: hir::TraitItemKind::Fn(sig, _),
1122                    ..
1123                })
1124                | hir::Node::ImplItem(hir::ImplItem {
1125                    ident,
1126                    kind: hir::ImplItemKind::Fn(sig, _),
1127                    ..
1128                }) => {
1129                    err.span_label(ident.span, "");
1130                    err.span_label(
1131                        sig.decl.output.span(),
1132                        "change this to return `FnMut` instead of `Fn`",
1133                    );
1134                }
1135                _ => {}
1136            }
1137        }
1138    }
1139
1140    fn suggest_using_iter_mut(&self, err: &mut Diag<'_>) {
1141        let source = self.body.source;
1142        if let InstanceKind::Item(def_id) = source.instance
1143            && let Some(Node::Expr(hir::Expr { hir_id, kind, .. })) =
1144                self.infcx.tcx.hir_get_if_local(def_id)
1145            && let ExprKind::Closure(hir::Closure { kind: hir::ClosureKind::Closure, .. }) = kind
1146            && let Node::Expr(expr) = self.infcx.tcx.parent_hir_node(*hir_id)
1147        {
1148            let mut cur_expr = expr;
1149            while let ExprKind::MethodCall(path_segment, recv, _, _) = cur_expr.kind {
1150                if path_segment.ident.name == sym::iter {
1151                    // Check that the type has an `iter_mut` method.
1152                    let res = self
1153                        .infcx
1154                        .tcx
1155                        .typeck(path_segment.hir_id.owner.def_id)
1156                        .type_dependent_def_id(cur_expr.hir_id)
1157                        .and_then(|def_id| self.infcx.tcx.impl_of_assoc(def_id))
1158                        .map(|def_id| self.infcx.tcx.associated_items(def_id))
1159                        .map(|assoc_items| {
1160                            assoc_items.filter_by_name_unhygienic(sym::iter_mut).peekable()
1161                        });
1162
1163                    if let Some(mut res) = res
1164                        && res.peek().is_some()
1165                    {
1166                        err.span_suggestion_verbose(
1167                            path_segment.ident.span,
1168                            "you may want to use `iter_mut` here",
1169                            "iter_mut",
1170                            Applicability::MaybeIncorrect,
1171                        );
1172                    }
1173                    break;
1174                } else {
1175                    cur_expr = recv;
1176                }
1177            }
1178        }
1179    }
1180
1181    fn suggest_make_local_mut(&self, err: &mut Diag<'_>, local: Local, name: Symbol) {
1182        let local_decl = &self.body.local_decls[local];
1183
1184        let (pointer_sigil, pointer_desc) =
1185            if local_decl.ty.is_ref() { ("&", "reference") } else { ("*const", "pointer") };
1186
1187        let (is_trait_sig, is_local, local_trait) = self.is_error_in_trait(local);
1188
1189        if is_trait_sig && !is_local {
1190            // Do not suggest changing the signature when the trait comes from another crate.
1191            err.span_label(
1192                local_decl.source_info.span,
1193                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this is an immutable {0}",
                pointer_desc))
    })format!("this is an immutable {pointer_desc}"),
1194            );
1195            return;
1196        }
1197
1198        // Do not suggest changing type if that is not under user control.
1199        if self.is_closure_arg_with_non_locally_decided_type(local) {
1200            return;
1201        }
1202
1203        let decl_span = local_decl.source_info.span;
1204
1205        let (amp_mut_sugg, local_var_ty_info) = match *local_decl.local_info() {
1206            LocalInfo::User(mir::BindingForm::ImplicitSelf(_)) => {
1207                let (span, suggestion) = suggest_ampmut_self(self.infcx.tcx, decl_span);
1208                let additional = local_trait.map(|span| suggest_ampmut_self(self.infcx.tcx, span));
1209                (AmpMutSugg::Type { span, suggestion, additional }, None)
1210            }
1211
1212            LocalInfo::User(mir::BindingForm::Var(mir::VarBindingForm {
1213                binding_mode: BindingMode(ByRef::No, _),
1214                opt_ty_info,
1215                ..
1216            })) => {
1217                // Check if the RHS is from desugaring.
1218                let first_assignment = find_assignments(&self.body, local).first().copied();
1219                let first_assignment_stmt = first_assignment
1220                    .and_then(|loc| self.body[loc.block].statements.get(loc.statement_index));
1221                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs:1221",
                        "rustc_borrowck::diagnostics::mutability_errors",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1221u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::mutability_errors"),
                        ::tracing_core::field::FieldSet::new(&["first_assignment_stmt"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&first_assignment_stmt)
                                            as &dyn Value))])
            });
    } else { ; }
};trace!(?first_assignment_stmt);
1222                let opt_assignment_rhs_span =
1223                    first_assignment.map(|loc| self.body.source_info(loc).span);
1224                let mut source_span = opt_assignment_rhs_span;
1225                if let Some(mir::Statement {
1226                    source_info: _,
1227                    kind:
1228                        mir::StatementKind::Assign(box (_, mir::Rvalue::Use(mir::Operand::Copy(place)))),
1229                    ..
1230                }) = first_assignment_stmt
1231                {
1232                    let local_span = self.body.local_decls[place.local].source_info.span;
1233                    // `&self` in async functions have a `desugaring_kind`, but the local we assign
1234                    // it with does not, so use the local_span for our checks later.
1235                    source_span = Some(local_span);
1236                    if let Some(DesugaringKind::ForLoop) = local_span.desugaring_kind() {
1237                        // On for loops, RHS points to the iterator part.
1238                        self.suggest_similar_mut_method_for_for_loop(err, local_span);
1239                        err.span_label(
1240                            local_span,
1241                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this iterator yields `{0}` {1}s",
                pointer_sigil, pointer_desc))
    })format!("this iterator yields `{pointer_sigil}` {pointer_desc}s",),
1242                        );
1243                        return;
1244                    }
1245                }
1246
1247                // Don't create labels for compiler-generated spans or spans not from users' code.
1248                if source_span.is_some_and(|s| {
1249                    s.desugaring_kind().is_some() || self.infcx.tcx.sess.source_map().is_imported(s)
1250                }) {
1251                    return;
1252                }
1253
1254                // This could be because we're in an `async fn`.
1255                if name == kw::SelfLower && opt_ty_info.is_none() {
1256                    let (span, suggestion) = suggest_ampmut_self(self.infcx.tcx, decl_span);
1257                    (AmpMutSugg::Type { span, suggestion, additional: None }, None)
1258                } else if let Some(sugg) =
1259                    suggest_ampmut(self.infcx, self.body(), first_assignment_stmt)
1260                {
1261                    (sugg, opt_ty_info)
1262                } else {
1263                    return;
1264                }
1265            }
1266
1267            LocalInfo::User(mir::BindingForm::Var(mir::VarBindingForm {
1268                binding_mode: BindingMode(ByRef::Yes(..), _),
1269                ..
1270            })) => {
1271                let pattern_span: Span = local_decl.source_info.span;
1272                let Some(span) = suggest_ref_mut(self.infcx.tcx, pattern_span) else {
1273                    return;
1274                };
1275                (AmpMutSugg::Type { span, suggestion: "mut ".to_owned(), additional: None }, None)
1276            }
1277
1278            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1279        };
1280
1281        let mut suggest = |suggs: Vec<_>, applicability, extra| {
1282            if suggs.iter().any(|(span, _)| self.infcx.tcx.sess.source_map().is_imported(*span)) {
1283                return;
1284            }
1285
1286            err.multipart_suggestion_verbose(
1287                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider changing this to be a mutable {1}{0}{2}",
                if is_trait_sig {
                    " in the `impl` method and the `trait` definition"
                } else { "" }, pointer_desc, extra))
    })format!(
1288                    "consider changing this to be a mutable {pointer_desc}{}{extra}",
1289                    if is_trait_sig {
1290                        " in the `impl` method and the `trait` definition"
1291                    } else {
1292                        ""
1293                    }
1294                ),
1295                suggs,
1296                applicability,
1297            );
1298        };
1299
1300        let (mut sugg, add_type_annotation_if_not_exists) = match amp_mut_sugg {
1301            AmpMutSugg::Type { span, suggestion, additional } => {
1302                let mut sugg = <[_]>::into_vec(::alloc::boxed::box_new([(span, suggestion)]))vec![(span, suggestion)];
1303                sugg.extend(additional);
1304                suggest(sugg, Applicability::MachineApplicable, "");
1305                return;
1306            }
1307            AmpMutSugg::MapGetMut { span, suggestion } => {
1308                if self.infcx.tcx.sess.source_map().is_imported(span) {
1309                    return;
1310                }
1311                err.multipart_suggestion_verbose(
1312                    "consider using `get_mut`",
1313                    <[_]>::into_vec(::alloc::boxed::box_new([(span, suggestion)]))vec![(span, suggestion)],
1314                    Applicability::MaybeIncorrect,
1315                );
1316                return;
1317            }
1318            AmpMutSugg::Expr { span, suggestion } => {
1319                // `Expr` suggestions should change type annotations if they already exist (probably immut),
1320                // but do not add new type annotations.
1321                (<[_]>::into_vec(::alloc::boxed::box_new([(span, suggestion)]))vec![(span, suggestion)], false)
1322            }
1323            AmpMutSugg::ChangeBinding => (::alloc::vec::Vec::new()vec![], true),
1324        };
1325
1326        // Find a binding's type to make mutable.
1327        let (binding_exists, span) = match local_var_ty_info {
1328            // If this is a variable binding with an explicit type,
1329            // then we will suggest changing it to be mutable.
1330            // This is `Applicability::MachineApplicable`.
1331            Some(ty_span) => (true, ty_span),
1332
1333            // Otherwise, we'll suggest *adding* an annotated type, we'll suggest
1334            // the RHS's type for that.
1335            // This is `Applicability::HasPlaceholders`.
1336            None => (false, decl_span),
1337        };
1338
1339        if !binding_exists && !add_type_annotation_if_not_exists {
1340            suggest(sugg, Applicability::MachineApplicable, "");
1341            return;
1342        }
1343
1344        // If the binding already exists and is a reference with an explicit
1345        // lifetime, then we can suggest adding ` mut`. This is special-cased from
1346        // the path without an explicit lifetime.
1347        let (sugg_span, sugg_str, suggest_now) = if let Ok(src) = self.infcx.tcx.sess.source_map().span_to_snippet(span)
1348            && src.starts_with("&'")
1349            // Note that `&' a T` is invalid so this is correct.
1350            && let Some(ws_pos) = src.find(char::is_whitespace)
1351        {
1352            let span = span.with_lo(span.lo() + BytePos(ws_pos as u32)).shrink_to_lo();
1353            (span, " mut".to_owned(), true)
1354        // If there is already a binding, we modify it to be `mut`.
1355        } else if binding_exists {
1356            // Shrink the span to just after the `&` in `&variable`.
1357            let span = span.with_lo(span.lo() + BytePos(1)).shrink_to_lo();
1358            (span, "mut ".to_owned(), true)
1359        } else {
1360            // Otherwise, suggest that the user annotates the binding; We provide the
1361            // type of the local.
1362            let ty = local_decl.ty.builtin_deref(true).unwrap();
1363
1364            (span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}mut {1}",
                if local_decl.ty.is_ref() { "&" } else { "*" }, ty))
    })format!("{}mut {}", if local_decl.ty.is_ref() { "&" } else { "*" }, ty), false)
1365        };
1366
1367        if suggest_now {
1368            // Suggest changing `&x` to `&mut x` and changing `&T` to `&mut T` at the same time.
1369            let has_change = !sugg.is_empty();
1370            sugg.push((sugg_span, sugg_str));
1371            suggest(
1372                sugg,
1373                Applicability::MachineApplicable,
1374                // FIXME(fee1-dead) this somehow doesn't fire
1375                if has_change { " and changing the binding's type" } else { "" },
1376            );
1377            return;
1378        } else if !sugg.is_empty() {
1379            suggest(sugg, Applicability::MachineApplicable, "");
1380            return;
1381        }
1382
1383        let def_id = self.body.source.def_id();
1384        let hir_id = if let Some(local_def_id) = def_id.as_local()
1385            && let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(local_def_id)
1386        {
1387            BindingFinder { span: sugg_span }.visit_body(&body).break_value()
1388        } else {
1389            None
1390        };
1391        let node = hir_id.map(|hir_id| self.infcx.tcx.hir_node(hir_id));
1392
1393        let Some(hir::Node::LetStmt(local)) = node else {
1394            err.span_label(
1395                sugg_span,
1396                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider changing this binding\'s type to be: `{0}`",
                sugg_str))
    })format!("consider changing this binding's type to be: `{sugg_str}`"),
1397            );
1398            return;
1399        };
1400
1401        let tables = self.infcx.tcx.typeck(def_id.as_local().unwrap());
1402        if let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()
1403            && let Some(expr) = local.init
1404            && let ty = tables.node_type_opt(expr.hir_id)
1405            && let Some(ty) = ty
1406            && let ty::Ref(..) = ty.kind()
1407        {
1408            match self
1409                .infcx
1410                .type_implements_trait_shallow(clone_trait, ty.peel_refs(), self.infcx.param_env)
1411                .as_deref()
1412            {
1413                Some([]) => {
1414                    // FIXME: This error message isn't useful, since we're just
1415                    // vaguely suggesting to clone a value that already
1416                    // implements `Clone`.
1417                    //
1418                    // A correct suggestion here would take into account the fact
1419                    // that inference may be affected by missing types on bindings,
1420                    // etc., to improve "tests/ui/borrowck/issue-91206.stderr", for
1421                    // example.
1422                }
1423                None => {
1424                    if let hir::ExprKind::MethodCall(segment, _rcvr, [], span) = expr.kind
1425                        && segment.ident.name == sym::clone
1426                    {
1427                        err.span_help(
1428                            span,
1429                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` doesn\'t implement `Clone`, so this call clones the reference `{1}`",
                ty.peel_refs(), ty))
    })format!(
1430                                "`{}` doesn't implement `Clone`, so this call clones \
1431                                             the reference `{ty}`",
1432                                ty.peel_refs(),
1433                            ),
1434                        );
1435                    }
1436                    // The type doesn't implement Clone.
1437                    let trait_ref = ty::Binder::dummy(ty::TraitRef::new(
1438                        self.infcx.tcx,
1439                        clone_trait,
1440                        [ty.peel_refs()],
1441                    ));
1442                    let obligation = traits::Obligation::new(
1443                        self.infcx.tcx,
1444                        traits::ObligationCause::dummy(),
1445                        self.infcx.param_env,
1446                        trait_ref,
1447                    );
1448                    self.infcx.err_ctxt().suggest_derive(
1449                        &obligation,
1450                        err,
1451                        trait_ref.upcast(self.infcx.tcx),
1452                    );
1453                }
1454                Some(errors) => {
1455                    if let hir::ExprKind::MethodCall(segment, _rcvr, [], span) = expr.kind
1456                        && segment.ident.name == sym::clone
1457                    {
1458                        err.span_help(
1459                            span,
1460                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` doesn\'t implement `Clone` because its implementations trait bounds could not be met, so this call clones the reference `{1}`",
                ty.peel_refs(), ty))
    })format!(
1461                                "`{}` doesn't implement `Clone` because its \
1462                                             implementations trait bounds could not be met, so \
1463                                             this call clones the reference `{ty}`",
1464                                ty.peel_refs(),
1465                            ),
1466                        );
1467                        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the following trait bounds weren\'t met: {0}",
                errors.iter().map(|e|
                                e.obligation.predicate.to_string()).collect::<Vec<_>>().join("\n")))
    })format!(
1468                            "the following trait bounds weren't met: {}",
1469                            errors
1470                                .iter()
1471                                .map(|e| e.obligation.predicate.to_string())
1472                                .collect::<Vec<_>>()
1473                                .join("\n"),
1474                        ));
1475                    }
1476                    // The type doesn't implement Clone because of unmet obligations.
1477                    for error in errors {
1478                        if let traits::FulfillmentErrorCode::Select(
1479                            traits::SelectionError::Unimplemented,
1480                        ) = error.code
1481                            && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1482                                error.obligation.predicate.kind().skip_binder()
1483                        {
1484                            self.infcx.err_ctxt().suggest_derive(
1485                                &error.obligation,
1486                                err,
1487                                error.obligation.predicate.kind().rebind(pred),
1488                            );
1489                        }
1490                    }
1491                }
1492            }
1493        }
1494        let (changing, span, sugg) = match local.ty {
1495            Some(ty) => ("changing", ty.span, sugg_str),
1496            None => ("specifying", local.pat.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}", sugg_str))
    })format!(": {sugg_str}")),
1497        };
1498        err.span_suggestion_verbose(
1499            span,
1500            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider {0} this binding\'s type",
                changing))
    })format!("consider {changing} this binding's type"),
1501            sugg,
1502            Applicability::HasPlaceholders,
1503        );
1504    }
1505
1506    /// Returns `true` if `local` is an argument in a closure passed to a
1507    /// function defined in another crate.
1508    ///
1509    /// For example, in the following code this function returns `true` for `x`
1510    /// since `Option::inspect()` is not defined in the current crate:
1511    ///
1512    /// ```text
1513    /// some_option.as_mut().inspect(|x| {
1514    /// ```
1515    fn is_closure_arg_with_non_locally_decided_type(&self, local: Local) -> bool {
1516        // We don't care about regular local variables, only args.
1517        if self.body.local_kind(local) != LocalKind::Arg {
1518            return false;
1519        }
1520
1521        // Make sure we are inside a closure.
1522        let InstanceKind::Item(body_def_id) = self.body.source.instance else {
1523            return false;
1524        };
1525        let Some(Node::Expr(hir::Expr { hir_id: body_hir_id, kind, .. })) =
1526            self.infcx.tcx.hir_get_if_local(body_def_id)
1527        else {
1528            return false;
1529        };
1530        let ExprKind::Closure(hir::Closure { kind: hir::ClosureKind::Closure, .. }) = kind else {
1531            return false;
1532        };
1533
1534        // Check if the method/function that our closure is passed to is defined
1535        // in another crate.
1536        let Node::Expr(closure_parent) = self.infcx.tcx.parent_hir_node(*body_hir_id) else {
1537            return false;
1538        };
1539        match closure_parent.kind {
1540            ExprKind::MethodCall(method, _, _, _) => self
1541                .infcx
1542                .tcx
1543                .typeck(method.hir_id.owner.def_id)
1544                .type_dependent_def_id(closure_parent.hir_id)
1545                .is_some_and(|def_id| !def_id.is_local()),
1546            ExprKind::Call(func, _) => self
1547                .infcx
1548                .tcx
1549                .typeck(func.hir_id.owner.def_id)
1550                .node_type_opt(func.hir_id)
1551                .and_then(|ty| match ty.kind() {
1552                    ty::FnDef(def_id, _) => Some(def_id),
1553                    _ => None,
1554                })
1555                .is_some_and(|def_id| !def_id.is_local()),
1556            _ => false,
1557        }
1558    }
1559}
1560
1561struct BindingFinder {
1562    span: Span,
1563}
1564
1565impl<'tcx> Visitor<'tcx> for BindingFinder {
1566    type Result = ControlFlow<hir::HirId>;
1567    fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) -> Self::Result {
1568        if let hir::StmtKind::Let(local) = s.kind
1569            && local.pat.span == self.span
1570        {
1571            ControlFlow::Break(local.hir_id)
1572        } else {
1573            hir::intravisit::walk_stmt(self, s)
1574        }
1575    }
1576
1577    fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) -> Self::Result {
1578        if let hir::Pat { kind: hir::PatKind::Ref(_, _, _), span, .. } = param.pat
1579            && *span == self.span
1580        {
1581            ControlFlow::Break(param.hir_id)
1582        } else {
1583            ControlFlow::Continue(())
1584        }
1585    }
1586}
1587
1588fn mut_borrow_of_mutable_ref(local_decl: &LocalDecl<'_>, local_name: Option<Symbol>) -> bool {
1589    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs:1589",
                        "rustc_borrowck::diagnostics::mutability_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1589u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::mutability_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("local_info: {0:?}, ty.kind(): {1:?}",
                                                    local_decl.local_info, local_decl.ty.kind()) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!("local_info: {:?}, ty.kind(): {:?}", local_decl.local_info, local_decl.ty.kind());
1590
1591    match *local_decl.local_info() {
1592        // Check if mutably borrowing a mutable reference.
1593        LocalInfo::User(mir::BindingForm::Var(mir::VarBindingForm {
1594            binding_mode: BindingMode(ByRef::No, Mutability::Not),
1595            ..
1596        })) => #[allow(non_exhaustive_omitted_patterns)] match local_decl.ty.kind() {
    ty::Ref(_, _, hir::Mutability::Mut) => true,
    _ => false,
}matches!(local_decl.ty.kind(), ty::Ref(_, _, hir::Mutability::Mut)),
1597        LocalInfo::User(mir::BindingForm::ImplicitSelf(kind)) => {
1598            // Check if the user variable is a `&mut self` and we can therefore
1599            // suggest removing the `&mut`.
1600            //
1601            // Deliberately fall into this case for all implicit self types,
1602            // so that we don't fall into the next case with them.
1603            kind == hir::ImplicitSelfKind::RefMut
1604        }
1605        _ if Some(kw::SelfLower) == local_name => {
1606            // Otherwise, check if the name is the `self` keyword - in which case
1607            // we have an explicit self. Do the same thing in this case and check
1608            // for a `self: &mut Self` to suggest removing the `&mut`.
1609            #[allow(non_exhaustive_omitted_patterns)] match local_decl.ty.kind() {
    ty::Ref(_, _, hir::Mutability::Mut) => true,
    _ => false,
}matches!(local_decl.ty.kind(), ty::Ref(_, _, hir::Mutability::Mut))
1610        }
1611        _ => false,
1612    }
1613}
1614
1615fn suggest_ampmut_self(tcx: TyCtxt<'_>, span: Span) -> (Span, String) {
1616    match tcx.sess.source_map().span_to_snippet(span) {
1617        Ok(snippet) if snippet.ends_with("self") => {
1618            (span.with_hi(span.hi() - BytePos(4)).shrink_to_hi(), "mut ".to_string())
1619        }
1620        _ => (span, "&mut self".to_string()),
1621    }
1622}
1623
1624enum AmpMutSugg {
1625    /// Type suggestion. Changes `&self` to `&mut self`, `x: &T` to `x: &mut T`,
1626    /// `ref x` to `ref mut x`, etc.
1627    Type {
1628        span: Span,
1629        suggestion: String,
1630        additional: Option<(Span, String)>,
1631    },
1632    /// Suggestion for expressions, `&x` to `&mut x`, `&x[i]` to `&mut x[i]`, etc.
1633    Expr {
1634        span: Span,
1635        suggestion: String,
1636    },
1637    /// Suggests `.get_mut` in the case of `&map[&key]` for Hash/BTreeMap.
1638    MapGetMut {
1639        span: Span,
1640        suggestion: String,
1641    },
1642    ChangeBinding,
1643}
1644
1645// When we want to suggest a user change a local variable to be a `&mut`, there
1646// are three potential "obvious" things to highlight:
1647//
1648// let ident [: Type] [= RightHandSideExpression];
1649//     ^^^^^    ^^^^     ^^^^^^^^^^^^^^^^^^^^^^^
1650//     (1.)     (2.)              (3.)
1651//
1652// We can always fallback on highlighting the first. But chances are good that
1653// the user experience will be better if we highlight one of the others if possible;
1654// for example, if the RHS is present and the Type is not, then the type is going to
1655// be inferred *from* the RHS, which means we should highlight that (and suggest
1656// that they borrow the RHS mutably).
1657//
1658// This implementation attempts to emulate AST-borrowck prioritization
1659// by trying (3.), then (2.) and finally falling back on (1.).
1660fn suggest_ampmut<'tcx>(
1661    infcx: &crate::BorrowckInferCtxt<'tcx>,
1662    body: &Body<'tcx>,
1663    opt_assignment_rhs_stmt: Option<&Statement<'tcx>>,
1664) -> Option<AmpMutSugg> {
1665    let tcx = infcx.tcx;
1666    // If there is a RHS and it starts with a `&` from it, then check if it is
1667    // mutable, and if not, put suggest putting `mut ` to make it mutable.
1668    // We don't have to worry about lifetime annotations here because they are
1669    // not valid when taking a reference. For example, the following is not valid Rust:
1670    //
1671    // let x: &i32 = &'a 5;
1672    //                ^^ lifetime annotation not allowed
1673    //
1674    if let Some(rhs_stmt) = opt_assignment_rhs_stmt
1675        && let StatementKind::Assign(box (lhs, rvalue)) = &rhs_stmt.kind
1676        && let mut rhs_span = rhs_stmt.source_info.span
1677        && let Ok(mut rhs_str) = tcx.sess.source_map().span_to_snippet(rhs_span)
1678    {
1679        let mut rvalue = rvalue;
1680
1681        // Take some special care when handling `let _x = &*_y`:
1682        // We want to know if this is part of an overloaded index, so `let x = &a[0]`,
1683        // or whether this is a usertype ascription (`let _x: &T = y`).
1684        if let Rvalue::Ref(_, BorrowKind::Shared, place) = rvalue
1685            && place.projection.len() == 1
1686            && place.projection[0] == ProjectionElem::Deref
1687            && let Some(assign) = find_assignments(&body, place.local).first()
1688        {
1689            // If this is a usertype ascription (`let _x: &T = _y`) then pierce through it as either we want
1690            // to suggest `&mut` on the expression (handled here) or we return `None` and let the caller
1691            // suggest `&mut` on the type if the expression seems fine (e.g. `let _x: &T = &mut _y`).
1692            if let Some(user_ty_projs) = body.local_decls[lhs.local].user_ty.as_ref()
1693                && let [user_ty_proj] = user_ty_projs.contents.as_slice()
1694                && user_ty_proj.projs.is_empty()
1695                && let Either::Left(rhs_stmt_new) = body.stmt_at(*assign)
1696                && let StatementKind::Assign(box (_, rvalue_new)) = &rhs_stmt_new.kind
1697                && let rhs_span_new = rhs_stmt_new.source_info.span
1698                && let Ok(rhs_str_new) = tcx.sess.source_map().span_to_snippet(rhs_span)
1699            {
1700                (rvalue, rhs_span, rhs_str) = (rvalue_new, rhs_span_new, rhs_str_new);
1701            }
1702
1703            if let Either::Right(call) = body.stmt_at(*assign)
1704                && let TerminatorKind::Call {
1705                    func: Operand::Constant(box const_operand), args, ..
1706                } = &call.kind
1707                && let ty::FnDef(method_def_id, method_args) = *const_operand.ty().kind()
1708                && let Some(trait_) = tcx.trait_of_assoc(method_def_id)
1709                && tcx.is_lang_item(trait_, hir::LangItem::Index)
1710            {
1711                let trait_ref = ty::TraitRef::from_assoc(
1712                    tcx,
1713                    tcx.require_lang_item(hir::LangItem::IndexMut, rhs_span),
1714                    method_args,
1715                );
1716                // The type only implements `Index` but not `IndexMut`, we must not suggest `&mut`.
1717                if !infcx
1718                    .type_implements_trait(trait_ref.def_id, trait_ref.args, infcx.param_env)
1719                    .must_apply_considering_regions()
1720                {
1721                    // Suggest `get_mut` if type is a `BTreeMap` or `HashMap`.
1722                    if let ty::Adt(def, _) = trait_ref.self_ty().kind()
1723                        && [sym::BTreeMap, sym::HashMap]
1724                            .into_iter()
1725                            .any(|s| tcx.is_diagnostic_item(s, def.did()))
1726                        && let [map, key] = &**args
1727                        && let Ok(map) = tcx.sess.source_map().span_to_snippet(map.span)
1728                        && let Ok(key) = tcx.sess.source_map().span_to_snippet(key.span)
1729                    {
1730                        let span = rhs_span;
1731                        let suggestion = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.get_mut({1}).unwrap()", map,
                key))
    })format!("{map}.get_mut({key}).unwrap()");
1732                        return Some(AmpMutSugg::MapGetMut { span, suggestion });
1733                    }
1734                    return None;
1735                }
1736            }
1737        }
1738
1739        let sugg = match rvalue {
1740            Rvalue::Ref(_, BorrowKind::Shared, _) if let Some(ref_idx) = rhs_str.find('&') => {
1741                // Shrink the span to just after the `&` in `&variable`.
1742                Some((
1743                    rhs_span.with_lo(rhs_span.lo() + BytePos(ref_idx as u32 + 1)).shrink_to_lo(),
1744                    "mut ".to_owned(),
1745                ))
1746            }
1747            Rvalue::RawPtr(RawPtrKind::Const, _) if let Some(const_idx) = rhs_str.find("const") => {
1748                // Suggest changing `&raw const` to `&raw mut` if applicable.
1749                let const_idx = const_idx as u32;
1750                Some((
1751                    rhs_span
1752                        .with_lo(rhs_span.lo() + BytePos(const_idx))
1753                        .with_hi(rhs_span.lo() + BytePos(const_idx + "const".len() as u32)),
1754                    "mut".to_owned(),
1755                ))
1756            }
1757            _ => None,
1758        };
1759
1760        if let Some((span, suggestion)) = sugg {
1761            return Some(AmpMutSugg::Expr { span, suggestion });
1762        }
1763    }
1764
1765    Some(AmpMutSugg::ChangeBinding)
1766}
1767
1768/// If the type is a `Coroutine`, `Closure`, or `CoroutineClosure`
1769fn is_closure_like(ty: Ty<'_>) -> bool {
1770    ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure()
1771}
1772
1773/// Given a field that needs to be mutable, returns a span where the " mut " could go.
1774/// This function expects the local to be a reference to a struct in order to produce a span.
1775///
1776/// ```text
1777/// LL |     s: &'a   String
1778///    |           ^^^ returns a span taking up the space here
1779/// ```
1780fn get_mut_span_in_struct_field<'tcx>(
1781    tcx: TyCtxt<'tcx>,
1782    ty: Ty<'tcx>,
1783    field: FieldIdx,
1784) -> Option<Span> {
1785    // Expect our local to be a reference to a struct of some kind.
1786    if let ty::Ref(_, ty, _) = ty.kind()
1787        && let ty::Adt(def, _) = ty.kind()
1788        && let field = def.all_fields().nth(field.index())?
1789        // Now we're dealing with the actual struct that we're going to suggest a change to,
1790        // we can expect a field that is an immutable reference to a type.
1791        && let hir::Node::Field(field) = tcx.hir_node_by_def_id(field.did.as_local()?)
1792        && let hir::TyKind::Ref(lt, hir::MutTy { mutbl: hir::Mutability::Not, ty }) = field.ty.kind
1793    {
1794        return Some(lt.ident.span.between(ty.span));
1795    }
1796
1797    None
1798}
1799
1800/// If possible, suggest replacing `ref` with `ref mut`.
1801fn suggest_ref_mut(tcx: TyCtxt<'_>, span: Span) -> Option<Span> {
1802    let pattern_str = tcx.sess.source_map().span_to_snippet(span).ok()?;
1803    if let Some(rest) = pattern_str.strip_prefix("ref")
1804        && rest.starts_with(rustc_lexer::is_whitespace)
1805    {
1806        let span = span.with_lo(span.lo() + BytePos(4)).shrink_to_lo();
1807        Some(span)
1808    } else {
1809        None
1810    }
1811}