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