Skip to main content

rustc_hir_typeck/
place_op.rs

1use rustc_ast as ast;
2use rustc_errors::Applicability;
3use rustc_hir as hir;
4use rustc_hir_analysis::autoderef::Autoderef;
5use rustc_infer::infer::InferOk;
6use rustc_infer::traits::{Obligation, ObligationCauseCode};
7use rustc_middle::ty::adjustment::{
8    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
9    OverloadedDeref, PointerCoercion,
10};
11use rustc_middle::ty::{self, Ty};
12use rustc_span::{Span, kw, span_bug, sym};
13use tracing::debug;
14
15use crate::method::{MethodCallee, TreatNotYetDefinedOpaques};
16use crate::{FnCtxt, PlaceOp};
17
18impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
19    /// Type-check `*oprnd_expr` with `oprnd_expr` type-checked already.
20    pub(super) fn lookup_derefing(
21        &self,
22        expr: &hir::Expr<'_>,
23        oprnd_expr: &'tcx hir::Expr<'tcx>,
24        oprnd_ty: Ty<'tcx>,
25    ) -> Option<Ty<'tcx>> {
26        if let Some(ty) = oprnd_ty.builtin_deref(true) {
27            return Some(ty);
28        }
29
30        let ok = self.try_overloaded_deref(expr.span, oprnd_ty)?;
31        let method = self.register_infer_ok_obligations(ok);
32        if let ty::Ref(_, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() {
33            self.apply_adjustments(
34                oprnd_expr,
35                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Adjustment {
                    kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Not)),
                    target: method.sig.inputs()[0],
                }]))vec![Adjustment {
36                    kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Not)),
37                    target: method.sig.inputs()[0],
38                }],
39            );
40        } else {
41            ::rustc_span::macros::bug_impl(Some(expr.span),
    format_args!("input to deref is not a ref?"), Location::caller());span_bug!(expr.span, "input to deref is not a ref?");
42        }
43        let ty = self.make_overloaded_place_return_type(method);
44        self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
45        Some(ty)
46    }
47
48    /// Type-check `*base_expr[index_expr]` with `base_expr` and `index_expr` type-checked already.
49    pub(super) fn lookup_indexing(
50        &self,
51        expr: &hir::Expr<'_>,
52        base_expr: &'tcx hir::Expr<'tcx>,
53        base_ty: Ty<'tcx>,
54        index_expr: &'tcx hir::Expr<'tcx>,
55        idx_ty: Ty<'tcx>,
56    ) -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)> {
57        // FIXME(#18741) -- this is almost but not quite the same as the
58        // autoderef that normal method probing does. They could likely be
59        // consolidated.
60
61        let mut autoderef = self.autoderef(base_expr.span, base_ty);
62        let mut result = None;
63        while result.is_none() && autoderef.next().is_some() {
64            result = self.try_index_step(expr, base_expr, &autoderef, idx_ty, index_expr);
65        }
66        self.register_predicates(autoderef.into_obligations());
67        result
68    }
69
70    fn negative_index(
71        &self,
72        ty: Ty<'tcx>,
73        span: Span,
74        base_expr: &hir::Expr<'_>,
75    ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
76        let ty = self.deeply_resolve_ignoring_regions(ty);
77        let mut err = self.dcx().struct_span_err(
78            span,
79            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("negative integers cannot be used to index on a `{0}`",
                ty))
    })format!("negative integers cannot be used to index on a `{ty}`"),
80        );
81        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot use a negative integer for indexing on `{0}`",
                ty))
    })format!("cannot use a negative integer for indexing on `{ty}`"));
82        if let (hir::ExprKind::Path(..), Ok(snippet)) =
83            (&base_expr.kind, self.tcx.sess.source_map().span_to_snippet(base_expr.span))
84        {
85            // `foo[-1]` to `foo[foo.len() - 1]`
86            err.span_suggestion_verbose(
87                span.shrink_to_lo(),
88                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to access an element starting from the end of the `{0}`, compute the index",
                ty))
    })format!(
89                    "to access an element starting from the end of the `{ty}`, compute the index",
90                ),
91                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.len() ", snippet))
    })format!("{snippet}.len() "),
92                Applicability::MachineApplicable,
93            );
94        }
95        let guar = err.emit_err();
96        Some((Ty::new_error(self.tcx, guar), Ty::new_error(self.tcx, guar)))
97    }
98
99    /// To type-check `base_expr[index_expr]`, we progressively autoderef
100    /// (and otherwise adjust) `base_expr`, looking for a type which either
101    /// supports builtin indexing or overloaded indexing.
102    /// This loop implements one step in that search; the autoderef loop
103    /// is implemented by `lookup_indexing`.
104    fn try_index_step(
105        &self,
106        expr: &hir::Expr<'_>,
107        base_expr: &hir::Expr<'_>,
108        autoderef: &Autoderef<'a, 'tcx>,
109        index_ty: Ty<'tcx>,
110        index_expr: &hir::Expr<'_>,
111    ) -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)> {
112        let adjusted_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty());
113        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:113",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(113u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("try_index_step(expr={0:?}, base_expr={1:?}, adjusted_ty={2:?}, index_ty={3:?})",
                                                    expr, base_expr, adjusted_ty, index_ty) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
114            "try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \
115             index_ty={:?})",
116            expr, base_expr, adjusted_ty, index_ty
117        );
118
119        if let hir::ExprKind::Unary(
120            hir::UnOp::Neg,
121            hir::Expr {
122                kind: hir::ExprKind::Lit(hir::Lit { node: ast::LitKind::Int(..), .. }),
123                ..
124            },
125        ) = index_expr.kind
126        {
127            match adjusted_ty.kind() {
128                ty::Adt(def, _) if self.tcx.is_diagnostic_item(sym::Vec, def.did()) => {
129                    return self.negative_index(adjusted_ty, index_expr.span, base_expr);
130                }
131                ty::Slice(_) | ty::Array(_, _) => {
132                    return self.negative_index(adjusted_ty, index_expr.span, base_expr);
133                }
134                _ => {}
135            }
136        }
137
138        for unsize in [false, true] {
139            let mut self_ty = adjusted_ty;
140            if unsize {
141                // We only unsize arrays here.
142                if let ty::Array(element_ty, ct) = *adjusted_ty.kind() {
143                    self.register_predicate(Obligation::new(
144                        self.tcx,
145                        self.cause(
146                            base_expr.span,
147                            ObligationCauseCode::ArrayLen(adjusted_ty, base_expr.span),
148                        ),
149                        self.param_env,
150                        ty::ClauseKind::ConstArgHasType(ct, self.tcx.types.usize),
151                    ));
152                    self_ty = Ty::new_slice(self.tcx, element_ty);
153                } else {
154                    continue;
155                }
156            }
157
158            // If some lookup succeeds, write callee into table and extract index/element
159            // type from the method signature.
160            // If some lookup succeeded, install method in table
161            let input_ty = self.next_ty_var(base_expr.span);
162            let method =
163                self.try_overloaded_place_op(expr.span, self_ty, Some(input_ty), PlaceOp::Index);
164
165            if let Some(result) = method {
166                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:166",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(166u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("try_index_step: success, using overloaded indexing")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("try_index_step: success, using overloaded indexing");
167                let method = self.register_infer_ok_obligations(result);
168
169                let mut adjustments = self.adjust_steps(autoderef);
170                if let ty::Ref(region, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() {
171                    adjustments.push(Adjustment {
172                        kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Not)),
173                        target: Ty::new_imm_ref(self.tcx, *region, adjusted_ty),
174                    });
175                } else {
176                    ::rustc_span::macros::bug_impl(Some(expr.span),
    format_args!("input to index is not a ref?"), Location::caller());span_bug!(expr.span, "input to index is not a ref?");
177                }
178                if unsize {
179                    adjustments.push(Adjustment {
180                        kind: Adjust::Pointer(PointerCoercion::Unsize),
181                        target: method.sig.inputs()[0],
182                    });
183                }
184                self.apply_adjustments(base_expr, adjustments);
185
186                self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
187
188                return Some((input_ty, self.make_overloaded_place_return_type(method)));
189            }
190        }
191
192        None
193    }
194
195    /// Try to resolve an overloaded place op. We only deal with the immutable
196    /// variant here (Deref/Index). In some contexts we would need the mutable
197    /// variant (DerefMut/IndexMut); those would be later converted by
198    /// `convert_place_derefs_to_mutable`.
199    pub(super) fn try_overloaded_place_op(
200        &self,
201        span: Span,
202        base_ty: Ty<'tcx>,
203        opt_rhs_ty: Option<Ty<'tcx>>,
204        op: PlaceOp,
205    ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
206        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:206",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(206u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("try_overloaded_place_op({0:?},{1:?},{2:?})",
                                                    span, base_ty, op) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("try_overloaded_place_op({:?},{:?},{:?})", span, base_ty, op);
207
208        let (Some(imm_tr), imm_op) = (match op {
209            PlaceOp::Deref => (self.tcx.lang_items().deref_trait(), kw::Deref),
210            PlaceOp::Index => (self.tcx.lang_items().index_trait(), sym::index),
211        }) else {
212            // Bail if `Deref` or `Index` isn't defined.
213            return None;
214        };
215
216        // FIXME(trait-system-refactor-initiative#231): we may want to treat
217        // opaque types as rigid here to support `impl Deref<Target = impl Index<usize>>`.
218        let treat_opaques = TreatNotYetDefinedOpaques::AsInfer;
219        self.lookup_method_for_operator(
220            self.misc(span),
221            imm_op,
222            imm_tr,
223            base_ty,
224            opt_rhs_ty,
225            treat_opaques,
226        )
227    }
228
229    fn try_mutable_overloaded_place_op(
230        &self,
231        span: Span,
232        base_ty: Ty<'tcx>,
233        opt_rhs_ty: Option<Ty<'tcx>>,
234        op: PlaceOp,
235    ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
236        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:236",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(236u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("try_mutable_overloaded_place_op({0:?},{1:?},{2:?})",
                                                    span, base_ty, op) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("try_mutable_overloaded_place_op({:?},{:?},{:?})", span, base_ty, op);
237
238        let (Some(mut_tr), mut_op) = (match op {
239            PlaceOp::Deref => (self.tcx.lang_items().deref_mut_trait(), sym::deref_mut),
240            PlaceOp::Index => (self.tcx.lang_items().index_mut_trait(), sym::index_mut),
241        }) else {
242            // Bail if `DerefMut` or `IndexMut` isn't defined.
243            return None;
244        };
245
246        // We have to replace the operator with the mutable variant for the
247        // program to compile, so we don't really have a choice here and want
248        // to just try using `DerefMut` even if its not in the item bounds
249        // of the opaque.
250        let treat_opaques = TreatNotYetDefinedOpaques::AsInfer;
251        self.lookup_method_for_operator(
252            self.misc(span),
253            mut_op,
254            mut_tr,
255            base_ty,
256            opt_rhs_ty,
257            treat_opaques,
258        )
259    }
260
261    /// Convert auto-derefs, indices, etc of an expression from `Deref` and `Index`
262    /// into `DerefMut` and `IndexMut` respectively.
263    ///
264    /// This is a second pass of typechecking derefs/indices. We need this because we do not
265    /// always know whether a place needs to be mutable or not in the first pass.
266    /// This happens whether there is an implicit mutable reborrow, e.g. when the type
267    /// is used as the receiver of a method call.
268    pub(crate) fn convert_place_derefs_to_mutable(&self, expr: &hir::Expr<'_>) {
269        // Gather up expressions we want to munge.
270        let mut exprs = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [expr]))vec![expr];
271
272        while let hir::ExprKind::Field(expr, _)
273        | hir::ExprKind::Index(expr, _, _)
274        | hir::ExprKind::Unary(hir::UnOp::Deref, expr) = exprs.last().unwrap().kind
275        {
276            exprs.push(expr);
277        }
278
279        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:279",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(279u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("convert_place_derefs_to_mutable: exprs={0:?}",
                                                    exprs) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("convert_place_derefs_to_mutable: exprs={:?}", exprs);
280
281        // Fix up autoderefs and derefs.
282        let mut inside_union = false;
283        for (i, &expr) in exprs.iter().rev().enumerate() {
284            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:284",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(284u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("convert_place_derefs_to_mutable: i={0} expr={1:?}",
                                                    i, expr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("convert_place_derefs_to_mutable: i={} expr={:?}", i, expr);
285
286            let mut source = self.node_ty(expr.hir_id);
287            if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Unary(hir::UnOp::Deref, _) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Deref, _)) {
288                // Clear previous flag; after a pointer indirection it does not apply any more.
289                inside_union = false;
290            }
291            if source.is_union() {
292                inside_union = true;
293            }
294            // Fix up the autoderefs. Autorefs can only occur immediately preceding
295            // overloaded place ops, and will be fixed by them in order to get
296            // the correct region.
297            // Do not mutate adjustments in place, but rather take them,
298            // and replace them after mutating them, to avoid having the
299            // typeck results borrowed during (`deref_mut`) method resolution.
300            let previous_adjustments =
301                self.typeck_results.borrow_mut().adjustments_mut().remove(expr.hir_id);
302            if let Some(mut adjustments) = previous_adjustments {
303                for adjustment in &mut adjustments {
304                    if let Adjust::Deref(DerefAdjustKind::Overloaded(ref mut deref)) =
305                        adjustment.kind
306                        && let Some(ok) = self.try_mutable_overloaded_place_op(
307                            expr.span,
308                            source,
309                            None,
310                            PlaceOp::Deref,
311                        )
312                    {
313                        let method = self.register_infer_ok_obligations(ok);
314                        let ty::Ref(_, _, mutbl) = *method.sig.output().kind() else {
315                            ::rustc_span::macros::bug_impl(Some(self.tcx.def_span(method.def_id)),
    format_args!("expected DerefMut to return a &mut"), Location::caller());span_bug!(
316                                self.tcx.def_span(method.def_id),
317                                "expected DerefMut to return a &mut"
318                            );
319                        };
320                        *deref = OverloadedDeref { mutbl, span: deref.span };
321                        self.enforce_context_effects(None, expr.span, method.def_id, method.args);
322                        // If this is a union field, also throw an error for `DerefMut` of `ManuallyDrop` (see RFC 2514).
323                        // This helps avoid accidental drops.
324                        if inside_union
325                            && source.ty_adt_def().is_some_and(|adt| adt.is_manually_drop())
326                        {
327                            self.dcx().struct_span_err(
328                                expr.span,
329                                "not automatically applying `DerefMut` on `ManuallyDrop` union field",
330                            )
331                            .with_help(
332                                "writing to this reference calls the destructor for the old value",
333                            )
334                            .with_help("add an explicit `*` if that is desired, or call `ptr::write` to not run the destructor")
335                            .emit();
336                        }
337                    }
338                    source = adjustment.target;
339                }
340                self.typeck_results.borrow_mut().adjustments_mut().insert(expr.hir_id, adjustments);
341            }
342
343            match expr.kind {
344                hir::ExprKind::Index(base_expr, ..) => {
345                    self.convert_place_op_to_mutable(PlaceOp::Index, expr, base_expr);
346                }
347                hir::ExprKind::Unary(hir::UnOp::Deref, base_expr) => {
348                    self.convert_place_op_to_mutable(PlaceOp::Deref, expr, base_expr);
349                }
350                _ => {}
351            }
352        }
353    }
354
355    fn convert_place_op_to_mutable(
356        &self,
357        op: PlaceOp,
358        expr: &hir::Expr<'_>,
359        base_expr: &hir::Expr<'_>,
360    ) {
361        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:361",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(361u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("convert_place_op_to_mutable({0:?}, {1:?}, {2:?})",
                                                    op, expr, base_expr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("convert_place_op_to_mutable({:?}, {:?}, {:?})", op, expr, base_expr);
362        if !self.typeck_results.borrow().is_method_call(expr) {
363            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:363",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(363u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("convert_place_op_to_mutable - builtin, nothing to do")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("convert_place_op_to_mutable - builtin, nothing to do");
364            return;
365        }
366
367        // Need to deref because overloaded place ops take self by-reference.
368        let base_ty = self
369            .typeck_results
370            .borrow()
371            .expr_ty_adjusted(base_expr)
372            .builtin_deref(false)
373            .expect("place op takes something that is not a ref");
374
375        let arg_ty = match op {
376            PlaceOp::Deref => None,
377            PlaceOp::Index => {
378                // We would need to recover the `T` used when we resolve `<_ as Index<T>>::index`
379                // in try_index_step. This is the arg at index 1.
380                //
381                // Note: we should *not* use `expr_ty` of index_expr here because autoderef
382                // during coercions can cause type of index_expr to differ from `T` (#72002).
383                // We also could not use `expr_ty_adjusted` of index_expr because reborrowing
384                // during coercions can also cause type of index_expr to differ from `T`,
385                // which can potentially cause regionck failure (#74933).
386                Some(self.typeck_results.borrow().node_args(expr.hir_id).type_at(1))
387            }
388        };
389        let method = self.try_mutable_overloaded_place_op(expr.span, base_ty, arg_ty, op);
390        let method = match method {
391            Some(ok) => self.register_infer_ok_obligations(ok),
392            // Couldn't find the mutable variant of the place op, keep the
393            // current, immutable version.
394            None => return,
395        };
396        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:396",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(396u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("convert_place_op_to_mutable: method={0:?}",
                                                    method) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("convert_place_op_to_mutable: method={:?}", method);
397        self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
398
399        let ty::Ref(region, _, hir::Mutability::Mut) = method.sig.inputs()[0].kind() else {
400            ::rustc_span::macros::bug_impl(Some(expr.span),
    format_args!("input to mutable place op is not a mut ref?"),
    Location::caller());span_bug!(expr.span, "input to mutable place op is not a mut ref?");
401        };
402
403        // Convert the autoref in the base expr to mutable with the correct
404        // region and mutability.
405        let base_expr_ty = self.node_ty(base_expr.hir_id);
406        if let Some(adjustments) =
407            self.typeck_results.borrow_mut().adjustments_mut().get_mut(base_expr.hir_id)
408        {
409            let mut source = base_expr_ty;
410            for adjustment in &mut adjustments[..] {
411                if let Adjust::Borrow(AutoBorrow::Ref(..)) = adjustment.kind {
412                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs:412",
                        "rustc_hir_typeck::place_op", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/place_op.rs"),
                        ::tracing_core::__macro_support::Option::Some(412u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::place_op"),
                        ::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!("convert_place_op_to_mutable: converting autoref {0:?}",
                                                    adjustment) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("convert_place_op_to_mutable: converting autoref {:?}", adjustment);
413                    let mutbl = AutoBorrowMutability::Mut {
414                        // Deref/indexing can be desugared to a method call,
415                        // so maybe we could use two-phase here.
416                        // See the documentation of AllowTwoPhase for why that's
417                        // not the case today.
418                        allow_two_phase_borrow: AllowTwoPhase::No,
419                    };
420                    adjustment.kind = Adjust::Borrow(AutoBorrow::Ref(mutbl));
421                    adjustment.target = Ty::new_ref(self.tcx, *region, source, mutbl.into());
422                }
423                source = adjustment.target;
424            }
425
426            // If we have an autoref followed by unsizing at the end, fix the unsize target.
427            if let [
428                ..,
429                Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
430                Adjustment { kind: Adjust::Pointer(PointerCoercion::Unsize), ref mut target },
431            ] = adjustments[..]
432            {
433                *target = method.sig.inputs()[0];
434            }
435        }
436    }
437}