Skip to main content

rustc_mir_build/thir/cx/
expr.rs

1use itertools::Itertools;
2use rustc_abi::{FIRST_VARIANT, FieldIdx, Size, VariantIdx};
3use rustc_ast::UnsafeBinderCastKind;
4use rustc_data_structures::stack::ensure_sufficient_stack;
5use rustc_hir as hir;
6use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
7use rustc_hir::{LangItem, find_attr};
8use rustc_index::Idx;
9use rustc_middle::hir::place::{
10    Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind,
11};
12use rustc_middle::middle::region;
13use rustc_middle::mir::{self, AssignOp, BinOp, BorrowKind, UnOp};
14use rustc_middle::thir::*;
15use rustc_middle::ty::adjustment::{
16    Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, DerefAdjustKind, PointerCoercion,
17};
18use rustc_middle::ty::{
19    self, AdtKind, GenericArgs, InlineConstArgs, InlineConstArgsParts, ScalarInt, Ty, UpvarArgs,
20};
21use rustc_middle::{bug, span_bug};
22use rustc_span::Span;
23use tracing::{debug, info, instrument, trace};
24
25use crate::errors::*;
26use crate::thir::cx::ThirBuildCx;
27
28impl<'tcx> ThirBuildCx<'tcx> {
29    /// Create a THIR expression for the given HIR expression. This expands all
30    /// adjustments and directly adds the type information from the
31    /// `typeck_results`. See the [dev-guide] for more details.
32    ///
33    /// (The term "mirror" in this case does not refer to "flipped" or
34    /// "reversed".)
35    ///
36    /// [dev-guide]: https://rustc-dev-guide.rust-lang.org/thir.html
37    pub(crate) fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId {
38        // `mirror_expr` is recursing very deep. Make sure the stack doesn't overflow.
39        ensure_sufficient_stack(|| self.mirror_expr_inner(expr))
40    }
41
42    pub(crate) fn mirror_exprs(&mut self, exprs: &'tcx [hir::Expr<'tcx>]) -> Box<[ExprId]> {
43        // `mirror_exprs` may also recurse deeply, so it needs protection from stack overflow.
44        // Note that we *could* forward to `mirror_expr` for that, but we can consolidate the
45        // overhead of stack growth by doing it outside the iteration.
46        ensure_sufficient_stack(|| exprs.iter().map(|expr| self.mirror_expr_inner(expr)).collect())
47    }
48
49    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("mirror_expr_inner",
                                    "rustc_mir_build::thir::cx::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(49u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ExprId = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let expr_scope =
                region::Scope {
                    local_id: hir_expr.hir_id.local_id,
                    data: region::ScopeData::Node,
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:54",
                                    "rustc_mir_build::thir::cx::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(54u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                    ::tracing_core::field::FieldSet::new(&["hir_expr.hir_id",
                                                    "hir_expr.span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&hir_expr.hir_id)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&hir_expr.span)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let mut expr = self.make_mirror_unadjusted(hir_expr);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:58",
                                    "rustc_mir_build::thir::cx::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(58u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                    ::tracing_core::field::FieldSet::new(&["expr.ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&expr.ty) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            if self.apply_adjustments {
                for adjustment in
                    self.typeck_results.expr_adjustments(hir_expr) {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:63",
                                            "rustc_mir_build::thir::cx::expr", ::tracing::Level::TRACE,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                            ::tracing_core::__macro_support::Option::Some(63u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                            ::tracing_core::field::FieldSet::new(&["expr",
                                                            "adjustment"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&expr) as
                                                                &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&adjustment)
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    let span = expr.span;
                    expr =
                        self.apply_adjustment(hir_expr, expr, adjustment, span);
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:69",
                                    "rustc_mir_build::thir::cx::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(69u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                    ::tracing_core::field::FieldSet::new(&["message",
                                                    "expr.ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("after adjustments")
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&expr.ty) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            expr =
                Expr {
                    temp_scope_id: expr_scope.local_id,
                    ty: expr.ty,
                    span: hir_expr.span,
                    kind: ExprKind::Scope {
                        region_scope: expr_scope,
                        value: self.thir.exprs.push(expr),
                        hir_id: hir_expr.hir_id,
                    },
                };
            self.thir.exprs.push(expr)
        }
    }
}#[instrument(level = "trace", skip(self, hir_expr))]
50    pub(super) fn mirror_expr_inner(&mut self, hir_expr: &'tcx hir::Expr<'tcx>) -> ExprId {
51        let expr_scope =
52            region::Scope { local_id: hir_expr.hir_id.local_id, data: region::ScopeData::Node };
53
54        trace!(?hir_expr.hir_id, ?hir_expr.span);
55
56        let mut expr = self.make_mirror_unadjusted(hir_expr);
57
58        trace!(?expr.ty);
59
60        // Now apply adjustments, if any.
61        if self.apply_adjustments {
62            for adjustment in self.typeck_results.expr_adjustments(hir_expr) {
63                trace!(?expr, ?adjustment);
64                let span = expr.span;
65                expr = self.apply_adjustment(hir_expr, expr, adjustment, span);
66            }
67        }
68
69        trace!(?expr.ty, "after adjustments");
70
71        // Finally, wrap this up in the expr's scope.
72        expr = Expr {
73            temp_scope_id: expr_scope.local_id,
74            ty: expr.ty,
75            span: hir_expr.span,
76            kind: ExprKind::Scope {
77                region_scope: expr_scope,
78                value: self.thir.exprs.push(expr),
79                hir_id: hir_expr.hir_id,
80            },
81        };
82
83        // OK, all done!
84        self.thir.exprs.push(expr)
85    }
86
87    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("apply_adjustment",
                                    "rustc_mir_build::thir::cx::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(87u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                    ::tracing_core::field::FieldSet::new(&["hir_expr",
                                                    "adjustment"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_expr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&adjustment)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Expr<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let Expr { temp_scope_id, .. } = expr;
            let mut adjust_span =
                |expr: &mut Expr<'tcx>|
                    {
                        if let ExprKind::Block { block } = expr.kind &&
                                let Some(last_expr) = self.thir[block].expr {
                            span = self.thir[last_expr].span;
                            expr.span = span;
                        }
                    };
            let kind =
                match adjustment.kind {
                    Adjust::Pointer(cast) => {
                        if cast == PointerCoercion::Unsize {
                            adjust_span(&mut expr);
                        }
                        let is_from_as_cast =
                            if let hir::Node::Expr(hir::Expr {
                                    kind: hir::ExprKind::Cast(..), span: cast_span, .. }) =
                                    self.tcx.parent_hir_node(hir_expr.hir_id) {
                                span = *cast_span;
                                true
                            } else { false };
                        ExprKind::PointerCoercion {
                            cast,
                            source: self.thir.exprs.push(expr),
                            is_from_as_cast,
                        }
                    }
                    Adjust::NeverToAny if adjustment.target.is_never() =>
                        return expr,
                    Adjust::NeverToAny =>
                        ExprKind::NeverToAny { source: self.thir.exprs.push(expr) },
                    Adjust::Deref(DerefAdjustKind::Builtin) => {
                        adjust_span(&mut expr);
                        ExprKind::Deref { arg: self.thir.exprs.push(expr) }
                    }
                    Adjust::Deref(DerefAdjustKind::Pin) => {
                        adjust_span(&mut expr);
                        let pin_ty =
                            expr.ty.pinned_ty().expect("Deref(Pin) with non-Pin type");
                        let pointer_target =
                            ExprKind::Field {
                                lhs: self.thir.exprs.push(expr),
                                variant_index: FIRST_VARIANT,
                                name: FieldIdx::ZERO,
                            };
                        let expr =
                            Expr {
                                temp_scope_id,
                                ty: pin_ty,
                                span,
                                kind: pointer_target,
                            };
                        ExprKind::Deref { arg: self.thir.exprs.push(expr) }
                    }
                    Adjust::Deref(DerefAdjustKind::Overloaded(deref)) => {
                        let call_def_id = deref.method_call(self.tcx);
                        let overloaded_callee =
                            Ty::new_fn_def(self.tcx, call_def_id,
                                self.tcx.mk_args(&[expr.ty.into()]));
                        expr =
                            Expr {
                                temp_scope_id,
                                ty: Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased,
                                    expr.ty, deref.mutbl),
                                span,
                                kind: ExprKind::Borrow {
                                    borrow_kind: deref.mutbl.to_borrow_kind(),
                                    arg: self.thir.exprs.push(expr),
                                },
                            };
                        let expr = Box::new([self.thir.exprs.push(expr)]);
                        self.overloaded_place(hir_expr, adjustment.target,
                            Some(overloaded_callee), expr, deref.span)
                    }
                    Adjust::Borrow(AutoBorrow::Ref(m)) =>
                        ExprKind::Borrow {
                            borrow_kind: m.to_borrow_kind(),
                            arg: self.thir.exprs.push(expr),
                        },
                    Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => {
                        ExprKind::RawBorrow {
                            mutability,
                            arg: self.thir.exprs.push(expr),
                        }
                    }
                    Adjust::Borrow(AutoBorrow::Pin(mutbl)) => {
                        let borrow_kind =
                            match mutbl {
                                hir::Mutability::Mut =>
                                    BorrowKind::Mut { kind: mir::MutBorrowKind::Default },
                                hir::Mutability::Not => BorrowKind::Shared,
                            };
                        let new_pin_target =
                            Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, expr.ty,
                                mutbl);
                        let arg = self.thir.exprs.push(expr);
                        let expr =
                            self.thir.exprs.push(Expr {
                                    temp_scope_id,
                                    ty: new_pin_target,
                                    span,
                                    kind: ExprKind::Borrow { borrow_kind, arg },
                                });
                        let pin_did =
                            self.tcx.require_lang_item(rustc_hir::LangItem::Pin, span);
                        let args = self.tcx.mk_args(&[new_pin_target.into()]);
                        let kind =
                            ExprKind::Adt(Box::new(AdtExpr {
                                        adt_def: self.tcx.adt_def(pin_did),
                                        variant_index: FIRST_VARIANT,
                                        args,
                                        fields: Box::new([FieldExpr {
                                                        name: FieldIdx::ZERO,
                                                        expr,
                                                    }]),
                                        user_ty: None,
                                        base: AdtExprBase::None,
                                    }));
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:221",
                                                "rustc_mir_build::thir::cx::expr", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                                ::tracing_core::__macro_support::Option::Some(221u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                                ::tracing_core::field::FieldSet::new(&["kind"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&kind) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        kind
                    }
                    Adjust::ReborrowPin(mutbl) => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:225",
                                                "rustc_mir_build::thir::cx::expr", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                                ::tracing_core::__macro_support::Option::Some(225u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("apply ReborrowPin adjustment")
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let pin_ty_args =
                            match expr.ty.kind() {
                                ty::Adt(_, args) => args,
                                _ =>
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("ReborrowPin with non-Pin type")),
                            };
                        let pin_ty = pin_ty_args.iter().next().unwrap().expect_ty();
                        let ptr_target_ty =
                            match pin_ty.kind() {
                                ty::Ref(_, ty, _) => *ty,
                                _ =>
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("ReborrowPin with non-Ref type")),
                            };
                        let pointer_target =
                            ExprKind::Field {
                                lhs: self.thir.exprs.push(expr),
                                variant_index: FIRST_VARIANT,
                                name: FieldIdx::ZERO,
                            };
                        let arg =
                            Expr {
                                temp_scope_id,
                                ty: pin_ty,
                                span,
                                kind: pointer_target,
                            };
                        let arg = self.thir.exprs.push(arg);
                        let expr = ExprKind::Deref { arg };
                        let arg =
                            self.thir.exprs.push(Expr {
                                    temp_scope_id,
                                    ty: ptr_target_ty,
                                    span,
                                    kind: expr,
                                });
                        let borrow_kind =
                            match mutbl {
                                hir::Mutability::Mut =>
                                    BorrowKind::Mut { kind: mir::MutBorrowKind::Default },
                                hir::Mutability::Not => BorrowKind::Shared,
                            };
                        let new_pin_target =
                            Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased,
                                ptr_target_ty, mutbl);
                        let expr =
                            self.thir.exprs.push(Expr {
                                    temp_scope_id,
                                    ty: new_pin_target,
                                    span,
                                    kind: ExprKind::Borrow { borrow_kind, arg },
                                });
                        let pin_did =
                            self.tcx.require_lang_item(rustc_hir::LangItem::Pin, span);
                        let args = self.tcx.mk_args(&[new_pin_target.into()]);
                        let kind =
                            ExprKind::Adt(Box::new(AdtExpr {
                                        adt_def: self.tcx.adt_def(pin_did),
                                        variant_index: FIRST_VARIANT,
                                        args,
                                        fields: Box::new([FieldExpr {
                                                        name: FieldIdx::ZERO,
                                                        expr,
                                                    }]),
                                        user_ty: None,
                                        base: AdtExprBase::None,
                                    }));
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:283",
                                                "rustc_mir_build::thir::cx::expr", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                                                ::tracing_core::__macro_support::Option::Some(283u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                                                ::tracing_core::field::FieldSet::new(&["kind"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&kind) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        kind
                    }
                };
            Expr { temp_scope_id, ty: adjustment.target, span, kind }
        }
    }
}#[instrument(level = "trace", skip(self, expr, span))]
88    fn apply_adjustment(
89        &mut self,
90        hir_expr: &'tcx hir::Expr<'tcx>,
91        mut expr: Expr<'tcx>,
92        adjustment: &Adjustment<'tcx>,
93        mut span: Span,
94    ) -> Expr<'tcx> {
95        let Expr { temp_scope_id, .. } = expr;
96
97        // Adjust the span from the block, to the last expression of the
98        // block. This is a better span when returning a mutable reference
99        // with too short a lifetime. The error message will use the span
100        // from the assignment to the return place, which should only point
101        // at the returned value, not the entire function body.
102        //
103        // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
104        //      x
105        //   // ^ error message points at this expression.
106        // }
107        let mut adjust_span = |expr: &mut Expr<'tcx>| {
108            if let ExprKind::Block { block } = expr.kind
109                && let Some(last_expr) = self.thir[block].expr
110            {
111                span = self.thir[last_expr].span;
112                expr.span = span;
113            }
114        };
115
116        let kind = match adjustment.kind {
117            Adjust::Pointer(cast) => {
118                if cast == PointerCoercion::Unsize {
119                    adjust_span(&mut expr);
120                }
121
122                let is_from_as_cast = if let hir::Node::Expr(hir::Expr {
123                    kind: hir::ExprKind::Cast(..),
124                    span: cast_span,
125                    ..
126                }) = self.tcx.parent_hir_node(hir_expr.hir_id)
127                {
128                    // Use the whole span of the `x as T` expression for the coercion.
129                    span = *cast_span;
130                    true
131                } else {
132                    false
133                };
134                ExprKind::PointerCoercion {
135                    cast,
136                    source: self.thir.exprs.push(expr),
137                    is_from_as_cast,
138                }
139            }
140            Adjust::NeverToAny if adjustment.target.is_never() => return expr,
141            Adjust::NeverToAny => ExprKind::NeverToAny { source: self.thir.exprs.push(expr) },
142            Adjust::Deref(DerefAdjustKind::Builtin) => {
143                adjust_span(&mut expr);
144                ExprKind::Deref { arg: self.thir.exprs.push(expr) }
145            }
146            Adjust::Deref(DerefAdjustKind::Pin) => {
147                adjust_span(&mut expr);
148                // pointer = ($expr).pointer
149                let pin_ty = expr.ty.pinned_ty().expect("Deref(Pin) with non-Pin type");
150                let pointer_target = ExprKind::Field {
151                    lhs: self.thir.exprs.push(expr),
152                    variant_index: FIRST_VARIANT,
153                    name: FieldIdx::ZERO,
154                };
155                let expr = Expr { temp_scope_id, ty: pin_ty, span, kind: pointer_target };
156                // expr = *pointer
157                ExprKind::Deref { arg: self.thir.exprs.push(expr) }
158            }
159            Adjust::Deref(DerefAdjustKind::Overloaded(deref)) => {
160                // We don't need to do call adjust_span here since
161                // deref coercions always start with a built-in deref.
162                let call_def_id = deref.method_call(self.tcx);
163                let overloaded_callee =
164                    Ty::new_fn_def(self.tcx, call_def_id, self.tcx.mk_args(&[expr.ty.into()]));
165
166                expr = Expr {
167                    temp_scope_id,
168                    ty: Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, expr.ty, deref.mutbl),
169                    span,
170                    kind: ExprKind::Borrow {
171                        borrow_kind: deref.mutbl.to_borrow_kind(),
172                        arg: self.thir.exprs.push(expr),
173                    },
174                };
175
176                let expr = Box::new([self.thir.exprs.push(expr)]);
177
178                self.overloaded_place(
179                    hir_expr,
180                    adjustment.target,
181                    Some(overloaded_callee),
182                    expr,
183                    deref.span,
184                )
185            }
186            Adjust::Borrow(AutoBorrow::Ref(m)) => ExprKind::Borrow {
187                borrow_kind: m.to_borrow_kind(),
188                arg: self.thir.exprs.push(expr),
189            },
190            Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => {
191                ExprKind::RawBorrow { mutability, arg: self.thir.exprs.push(expr) }
192            }
193            Adjust::Borrow(AutoBorrow::Pin(mutbl)) => {
194                // expr = &pin (mut|const|) arget
195                let borrow_kind = match mutbl {
196                    hir::Mutability::Mut => BorrowKind::Mut { kind: mir::MutBorrowKind::Default },
197                    hir::Mutability::Not => BorrowKind::Shared,
198                };
199                let new_pin_target =
200                    Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, expr.ty, mutbl);
201                let arg = self.thir.exprs.push(expr);
202                let expr = self.thir.exprs.push(Expr {
203                    temp_scope_id,
204                    ty: new_pin_target,
205                    span,
206                    kind: ExprKind::Borrow { borrow_kind, arg },
207                });
208
209                // kind = Pin { pointer }
210                let pin_did = self.tcx.require_lang_item(rustc_hir::LangItem::Pin, span);
211                let args = self.tcx.mk_args(&[new_pin_target.into()]);
212                let kind = ExprKind::Adt(Box::new(AdtExpr {
213                    adt_def: self.tcx.adt_def(pin_did),
214                    variant_index: FIRST_VARIANT,
215                    args,
216                    fields: Box::new([FieldExpr { name: FieldIdx::ZERO, expr }]),
217                    user_ty: None,
218                    base: AdtExprBase::None,
219                }));
220
221                debug!(?kind);
222                kind
223            }
224            Adjust::ReborrowPin(mutbl) => {
225                debug!("apply ReborrowPin adjustment");
226                // Rewrite `$expr` as `Pin { __pointer: &(mut)? *($expr).__pointer }`
227
228                // We'll need these types later on
229                let pin_ty_args = match expr.ty.kind() {
230                    ty::Adt(_, args) => args,
231                    _ => bug!("ReborrowPin with non-Pin type"),
232                };
233                let pin_ty = pin_ty_args.iter().next().unwrap().expect_ty();
234                let ptr_target_ty = match pin_ty.kind() {
235                    ty::Ref(_, ty, _) => *ty,
236                    _ => bug!("ReborrowPin with non-Ref type"),
237                };
238
239                // pointer = ($expr).__pointer
240                let pointer_target = ExprKind::Field {
241                    lhs: self.thir.exprs.push(expr),
242                    variant_index: FIRST_VARIANT,
243                    name: FieldIdx::ZERO,
244                };
245                let arg = Expr { temp_scope_id, ty: pin_ty, span, kind: pointer_target };
246                let arg = self.thir.exprs.push(arg);
247
248                // arg = *pointer
249                let expr = ExprKind::Deref { arg };
250                let arg = self.thir.exprs.push(Expr {
251                    temp_scope_id,
252                    ty: ptr_target_ty,
253                    span,
254                    kind: expr,
255                });
256
257                // expr = &mut target
258                let borrow_kind = match mutbl {
259                    hir::Mutability::Mut => BorrowKind::Mut { kind: mir::MutBorrowKind::Default },
260                    hir::Mutability::Not => BorrowKind::Shared,
261                };
262                let new_pin_target =
263                    Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, ptr_target_ty, mutbl);
264                let expr = self.thir.exprs.push(Expr {
265                    temp_scope_id,
266                    ty: new_pin_target,
267                    span,
268                    kind: ExprKind::Borrow { borrow_kind, arg },
269                });
270
271                // kind = Pin { __pointer: pointer }
272                let pin_did = self.tcx.require_lang_item(rustc_hir::LangItem::Pin, span);
273                let args = self.tcx.mk_args(&[new_pin_target.into()]);
274                let kind = ExprKind::Adt(Box::new(AdtExpr {
275                    adt_def: self.tcx.adt_def(pin_did),
276                    variant_index: FIRST_VARIANT,
277                    args,
278                    fields: Box::new([FieldExpr { name: FieldIdx::ZERO, expr }]),
279                    user_ty: None,
280                    base: AdtExprBase::None,
281                }));
282
283                debug!(?kind);
284                kind
285            }
286        };
287
288        Expr { temp_scope_id, ty: adjustment.target, span, kind }
289    }
290
291    /// Lowers a cast expression.
292    ///
293    /// Dealing with user type annotations is left to the caller.
294    fn mirror_expr_cast(
295        &mut self,
296        source: &'tcx hir::Expr<'tcx>,
297        temp_scope_id: hir::ItemLocalId,
298        span: Span,
299    ) -> ExprKind<'tcx> {
300        let tcx = self.tcx;
301
302        // Check to see if this cast is a "coercion cast", where the cast is actually done
303        // using a coercion (or is a no-op).
304        if self.typeck_results.is_coercion_cast(source.hir_id) {
305            // Convert the lexpr to a vexpr.
306            ExprKind::Use { source: self.mirror_expr(source) }
307        } else if self.typeck_results.expr_ty(source).is_ref() {
308            // Special cased so that we can type check that the element
309            // type of the source matches the pointed to type of the
310            // destination.
311            ExprKind::PointerCoercion {
312                source: self.mirror_expr(source),
313                cast: PointerCoercion::ArrayToPointer,
314                is_from_as_cast: true,
315            }
316        } else if let hir::ExprKind::Path(ref qpath) = source.kind
317            && let res = self.typeck_results.qpath_res(qpath, source.hir_id)
318            && let ty = self.typeck_results.node_type(source.hir_id)
319            && let ty::Adt(adt_def, args) = ty.kind()
320            && let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Const), variant_ctor_id) = res
321        {
322            // Check whether this is casting an enum variant discriminant.
323            // To prevent cycles, we refer to the discriminant initializer,
324            // which is always an integer and thus doesn't need to know the
325            // enum's layout (or its tag type) to compute it during const eval.
326            // Example:
327            // enum Foo {
328            //     A,
329            //     B = A as isize + 4,
330            // }
331            // The correct solution would be to add symbolic computations to miri,
332            // so we wouldn't have to compute and store the actual value
333
334            let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id);
335            let (discr_did, discr_offset) = adt_def.discriminant_def_for_variant(idx);
336
337            use rustc_middle::ty::util::IntTypeExt;
338            let ty = adt_def.repr().discr_type();
339            let discr_ty = ty.to_ty(tcx);
340
341            let size = tcx
342                .layout_of(self.typing_env.as_query_input(discr_ty))
343                .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("could not compute layout for {0:?}: {1:?}",
            discr_ty, e));
}panic!("could not compute layout for {discr_ty:?}: {e:?}"))
344                .size;
345
346            let (lit, overflowing) = ScalarInt::truncate_from_uint(discr_offset as u128, size);
347            if overflowing {
348                // An erroneous enum with too many variants for its repr will emit E0081 and E0370
349                self.tcx.dcx().span_delayed_bug(
350                    source.span,
351                    "overflowing enum wasn't rejected by hir analysis",
352                );
353            }
354            let kind = ExprKind::NonHirLiteral { lit, user_ty: None };
355            let offset = self.thir.exprs.push(Expr { temp_scope_id, ty: discr_ty, span, kind });
356
357            let source = match discr_did {
358                // in case we are offsetting from a computed discriminant
359                // and not the beginning of discriminants (which is always `0`)
360                Some(did) => {
361                    let kind = ExprKind::NamedConst { def_id: did, args, user_ty: None };
362                    let lhs =
363                        self.thir.exprs.push(Expr { temp_scope_id, ty: discr_ty, span, kind });
364                    let bin = ExprKind::Binary { op: BinOp::Add, lhs, rhs: offset };
365                    self.thir.exprs.push(Expr { temp_scope_id, ty: discr_ty, span, kind: bin })
366                }
367                None => offset,
368            };
369
370            ExprKind::Cast { source }
371        } else {
372            // Default to `ExprKind::Cast` for all explicit casts.
373            // MIR building then picks the right MIR casts based on the types.
374            ExprKind::Cast { source: self.mirror_expr(source) }
375        }
376    }
377
378    x;#[instrument(level = "debug", skip(self), ret)]
379    fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx> {
380        let tcx = self.tcx;
381        let expr_ty = self.typeck_results.expr_ty(expr);
382        let mk_expr =
383            |kind, ty| Expr { temp_scope_id: expr.hir_id.local_id, span: expr.span, ty, kind };
384
385        let kind = match expr.kind {
386            // Here comes the interesting stuff:
387            hir::ExprKind::MethodCall(segment, receiver, args, fn_span) => {
388                // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
389                let expr = self.method_callee(expr, segment.ident.span, None);
390                info!("Using method span: {:?}", expr.span);
391                let args = std::iter::once(receiver)
392                    .chain(args.iter())
393                    .map(|expr| self.mirror_expr(expr))
394                    .collect();
395                ExprKind::Call {
396                    ty: expr.ty,
397                    fun: self.thir.exprs.push(expr),
398                    args,
399                    from_hir_call: true,
400                    fn_span,
401                }
402            }
403
404            hir::ExprKind::Call(fun, ref args) => {
405                if self.typeck_results.is_method_call(expr) {
406                    // The callee is something implementing Fn, FnMut, or FnOnce.
407                    // Find the actual method implementation being called and
408                    // build the appropriate UFCS call expression with the
409                    // callee-object as expr parameter.
410
411                    // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
412
413                    let method = self.method_callee(expr, fun.span, None);
414
415                    let arg_tys = args.iter().map(|e| self.typeck_results.expr_ty_adjusted(e));
416                    let tupled_args = Expr {
417                        ty: Ty::new_tup_from_iter(tcx, arg_tys),
418                        temp_scope_id: expr.hir_id.local_id,
419                        span: expr.span,
420                        kind: ExprKind::Tuple { fields: self.mirror_exprs(args) },
421                    };
422                    let tupled_args = self.thir.exprs.push(tupled_args);
423
424                    ExprKind::Call {
425                        ty: method.ty,
426                        fun: self.thir.exprs.push(method),
427                        args: Box::new([self.mirror_expr(fun), tupled_args]),
428                        from_hir_call: true,
429                        fn_span: expr.span,
430                    }
431                } else {
432                    // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
433                    let adt_data = if let hir::ExprKind::Path(ref qpath) = fun.kind
434                        && let Some(adt_def) = expr_ty.ty_adt_def()
435                    {
436                        match qpath {
437                            hir::QPath::Resolved(_, path) => match path.res {
438                                Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => {
439                                    Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
440                                }
441                                Res::SelfCtor(..) => Some((adt_def, FIRST_VARIANT)),
442                                _ => None,
443                            },
444                            hir::QPath::TypeRelative(_ty, _) => {
445                                if let Some((DefKind::Ctor(_, CtorKind::Fn), ctor_id)) =
446                                    self.typeck_results.type_dependent_def(fun.hir_id)
447                                {
448                                    Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
449                                } else {
450                                    None
451                                }
452                            }
453                        }
454                    } else {
455                        None
456                    };
457                    if let Some((adt_def, index)) = adt_data {
458                        let node_args = self.typeck_results.node_args(fun.hir_id);
459                        let user_provided_types = self.typeck_results.user_provided_types();
460                        let user_ty =
461                            user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| {
462                                if let ty::UserTypeKind::TypeOf(did, _) = &mut u_ty.value.kind {
463                                    *did = adt_def.did();
464                                }
465                                Box::new(u_ty)
466                            });
467                        debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
468
469                        let field_refs = args
470                            .iter()
471                            .enumerate()
472                            .map(|(idx, e)| FieldExpr {
473                                name: FieldIdx::new(idx),
474                                expr: self.mirror_expr(e),
475                            })
476                            .collect();
477                        ExprKind::Adt(Box::new(AdtExpr {
478                            adt_def,
479                            args: node_args,
480                            variant_index: index,
481                            fields: field_refs,
482                            user_ty,
483                            base: AdtExprBase::None,
484                        }))
485                    } else {
486                        ExprKind::Call {
487                            ty: self.typeck_results.node_type(fun.hir_id),
488                            fun: self.mirror_expr(fun),
489                            args: self.mirror_exprs(args),
490                            from_hir_call: true,
491                            fn_span: expr.span,
492                        }
493                    }
494                }
495            }
496
497            hir::ExprKind::Use(expr, span) => {
498                ExprKind::ByUse { expr: self.mirror_expr(expr), span }
499            }
500
501            hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, arg) => {
502                ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: self.mirror_expr(arg) }
503            }
504
505            hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, arg) => {
506                ExprKind::RawBorrow { mutability, arg: self.mirror_expr(arg) }
507            }
508
509            // Make `&pin mut $expr` and `&pin const $expr` into
510            // `Pin { __pointer: &mut { $expr } }` and `Pin { __pointer: &$expr }`.
511            hir::ExprKind::AddrOf(hir::BorrowKind::Pin, mutbl, arg_expr) => match expr_ty.kind() {
512                &ty::Adt(adt_def, args) if tcx.is_lang_item(adt_def.did(), hir::LangItem::Pin) => {
513                    let ty = args.type_at(0);
514                    let arg_ty = self.typeck_results.expr_ty(arg_expr);
515                    let mut arg = self.mirror_expr(arg_expr);
516                    // For `&pin mut $place` where `$place` is not `Unpin`, move the place
517                    // `$place` to ensure it will not be used afterwards.
518                    if mutbl.is_mut() && !arg_ty.is_unpin(self.tcx, self.typing_env) {
519                        let block = self.thir.blocks.push(Block {
520                            targeted_by_break: false,
521                            region_scope: region::Scope {
522                                local_id: arg_expr.hir_id.local_id,
523                                data: region::ScopeData::Node,
524                            },
525                            span: arg_expr.span,
526                            stmts: Box::new([]),
527                            expr: Some(arg),
528                            safety_mode: BlockSafety::Safe,
529                        });
530                        arg = self.thir.exprs.push(Expr {
531                            temp_scope_id: arg_expr.hir_id.local_id,
532                            ty: arg_ty,
533                            span: arg_expr.span,
534                            kind: ExprKind::Block { block },
535                        });
536                    }
537                    let expr = self.thir.exprs.push(Expr {
538                        temp_scope_id: expr.hir_id.local_id,
539                        ty,
540                        span: expr.span,
541                        kind: ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg },
542                    });
543                    ExprKind::Adt(Box::new(AdtExpr {
544                        adt_def,
545                        variant_index: FIRST_VARIANT,
546                        args,
547                        fields: Box::new([FieldExpr { name: FieldIdx::from(0u32), expr }]),
548                        user_ty: None,
549                        base: AdtExprBase::None,
550                    }))
551                }
552                _ => span_bug!(expr.span, "unexpected type for pinned borrow: {:?}", expr_ty),
553            },
554
555            hir::ExprKind::Block(blk, _) => ExprKind::Block { block: self.mirror_block(blk) },
556
557            hir::ExprKind::Assign(lhs, rhs, _) => {
558                ExprKind::Assign { lhs: self.mirror_expr(lhs), rhs: self.mirror_expr(rhs) }
559            }
560
561            hir::ExprKind::AssignOp(op, lhs, rhs) => {
562                if self.typeck_results.is_method_call(expr) {
563                    let lhs = self.mirror_expr(lhs);
564                    let rhs = self.mirror_expr(rhs);
565                    self.overloaded_operator(expr, Box::new([lhs, rhs]))
566                } else {
567                    ExprKind::AssignOp {
568                        op: assign_op(op.node),
569                        lhs: self.mirror_expr(lhs),
570                        rhs: self.mirror_expr(rhs),
571                    }
572                }
573            }
574
575            hir::ExprKind::Lit(lit) => ExprKind::Literal { lit, neg: false },
576
577            hir::ExprKind::Binary(op, lhs, rhs) => {
578                if self.typeck_results.is_method_call(expr) {
579                    let lhs = self.mirror_expr(lhs);
580                    let rhs = self.mirror_expr(rhs);
581                    self.overloaded_operator(expr, Box::new([lhs, rhs]))
582                } else {
583                    match op.node {
584                        hir::BinOpKind::And => ExprKind::LogicalOp {
585                            op: LogicalOp::And,
586                            lhs: self.mirror_expr(lhs),
587                            rhs: self.mirror_expr(rhs),
588                        },
589                        hir::BinOpKind::Or => ExprKind::LogicalOp {
590                            op: LogicalOp::Or,
591                            lhs: self.mirror_expr(lhs),
592                            rhs: self.mirror_expr(rhs),
593                        },
594                        _ => {
595                            let op = bin_op(op.node);
596                            ExprKind::Binary {
597                                op,
598                                lhs: self.mirror_expr(lhs),
599                                rhs: self.mirror_expr(rhs),
600                            }
601                        }
602                    }
603                }
604            }
605
606            hir::ExprKind::Index(lhs, index, brackets_span) => {
607                if self.typeck_results.is_method_call(expr) {
608                    let lhs = self.mirror_expr(lhs);
609                    let index = self.mirror_expr(index);
610                    self.overloaded_place(
611                        expr,
612                        expr_ty,
613                        None,
614                        Box::new([lhs, index]),
615                        brackets_span,
616                    )
617                } else {
618                    ExprKind::Index { lhs: self.mirror_expr(lhs), index: self.mirror_expr(index) }
619                }
620            }
621
622            hir::ExprKind::Unary(hir::UnOp::Deref, arg) => {
623                if self.typeck_results.is_method_call(expr) {
624                    let arg = self.mirror_expr(arg);
625                    self.overloaded_place(expr, expr_ty, None, Box::new([arg]), expr.span)
626                } else {
627                    ExprKind::Deref { arg: self.mirror_expr(arg) }
628                }
629            }
630
631            hir::ExprKind::Unary(hir::UnOp::Not, arg) => {
632                if self.typeck_results.is_method_call(expr) {
633                    let arg = self.mirror_expr(arg);
634                    self.overloaded_operator(expr, Box::new([arg]))
635                } else {
636                    ExprKind::Unary { op: UnOp::Not, arg: self.mirror_expr(arg) }
637                }
638            }
639
640            hir::ExprKind::Unary(hir::UnOp::Neg, arg) => {
641                if self.typeck_results.is_method_call(expr) {
642                    let arg = self.mirror_expr(arg);
643                    self.overloaded_operator(expr, Box::new([arg]))
644                } else if let hir::ExprKind::Lit(lit) = arg.kind {
645                    ExprKind::Literal { lit, neg: true }
646                } else {
647                    ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) }
648                }
649            }
650
651            hir::ExprKind::Struct(qpath, fields, ref base) => match expr_ty.kind() {
652                ty::Adt(adt, args) => match adt.adt_kind() {
653                    AdtKind::Struct | AdtKind::Union => {
654                        let user_provided_types = self.typeck_results.user_provided_types();
655                        let user_ty = user_provided_types.get(expr.hir_id).copied().map(Box::new);
656                        debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
657                        ExprKind::Adt(Box::new(AdtExpr {
658                            adt_def: *adt,
659                            variant_index: FIRST_VARIANT,
660                            args,
661                            user_ty,
662                            fields: self.field_refs(fields),
663                            base: match base {
664                                hir::StructTailExpr::Base(base) => AdtExprBase::Base(FruInfo {
665                                    base: self.mirror_expr(base),
666                                    field_types: self.typeck_results.fru_field_types()[expr.hir_id]
667                                        .iter()
668                                        .copied()
669                                        .collect(),
670                                }),
671                                hir::StructTailExpr::DefaultFields(_) => {
672                                    AdtExprBase::DefaultFields(
673                                        self.typeck_results.fru_field_types()[expr.hir_id]
674                                            .iter()
675                                            .copied()
676                                            .collect(),
677                                    )
678                                }
679                                hir::StructTailExpr::None
680                                | hir::StructTailExpr::NoneWithError(_) => AdtExprBase::None,
681                            },
682                        }))
683                    }
684                    AdtKind::Enum => {
685                        let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
686                        match res {
687                            Res::Def(DefKind::Variant, variant_id) => {
688                                assert!(matches!(
689                                    base,
690                                    hir::StructTailExpr::None
691                                        | hir::StructTailExpr::DefaultFields(_)
692                                        | hir::StructTailExpr::NoneWithError(_)
693                                ));
694
695                                let index = adt.variant_index_with_id(variant_id);
696                                let user_provided_types = self.typeck_results.user_provided_types();
697                                let user_ty =
698                                    user_provided_types.get(expr.hir_id).copied().map(Box::new);
699                                debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty);
700                                ExprKind::Adt(Box::new(AdtExpr {
701                                    adt_def: *adt,
702                                    variant_index: index,
703                                    args,
704                                    user_ty,
705                                    fields: self.field_refs(fields),
706                                    base: match base {
707                                        hir::StructTailExpr::DefaultFields(_) => {
708                                            AdtExprBase::DefaultFields(
709                                                self.typeck_results.fru_field_types()[expr.hir_id]
710                                                    .iter()
711                                                    .copied()
712                                                    .collect(),
713                                            )
714                                        }
715                                        hir::StructTailExpr::Base(base) => {
716                                            span_bug!(base.span, "unexpected res: {:?}", res);
717                                        }
718                                        hir::StructTailExpr::None
719                                        | hir::StructTailExpr::NoneWithError(_) => {
720                                            AdtExprBase::None
721                                        }
722                                    },
723                                }))
724                            }
725                            _ => {
726                                span_bug!(expr.span, "unexpected res: {:?}", res);
727                            }
728                        }
729                    }
730                },
731                _ => {
732                    span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty);
733                }
734            },
735
736            hir::ExprKind::Closure(hir::Closure { .. }) => {
737                let closure_ty = self.typeck_results.expr_ty(expr);
738                let (def_id, args, movability) = match *closure_ty.kind() {
739                    ty::Closure(def_id, args) => (def_id, UpvarArgs::Closure(args), None),
740                    ty::Coroutine(def_id, args) => {
741                        (def_id, UpvarArgs::Coroutine(args), Some(tcx.coroutine_movability(def_id)))
742                    }
743                    ty::CoroutineClosure(def_id, args) => {
744                        (def_id, UpvarArgs::CoroutineClosure(args), None)
745                    }
746                    _ => {
747                        span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
748                    }
749                };
750                let def_id = def_id.expect_local();
751
752                let upvars = self
753                    .tcx
754                    .closure_captures(def_id)
755                    .iter()
756                    .zip_eq(args.upvar_tys())
757                    .map(|(captured_place, ty)| {
758                        let upvars = self.capture_upvar(expr, captured_place, ty);
759                        self.thir.exprs.push(upvars)
760                    })
761                    .collect();
762
763                // Convert the closure fake reads, if any, from hir `Place` to ExprRef
764                let fake_reads = match self.typeck_results.closure_fake_reads.get(&def_id) {
765                    Some(fake_reads) => fake_reads
766                        .iter()
767                        .map(|(place, cause, hir_id)| {
768                            let expr = self.convert_captured_hir_place(expr, place.clone());
769                            (self.thir.exprs.push(expr), *cause, *hir_id)
770                        })
771                        .collect(),
772                    None => Vec::new(),
773                };
774
775                ExprKind::Closure(Box::new(ClosureExpr {
776                    closure_id: def_id,
777                    args,
778                    upvars,
779                    movability,
780                    fake_reads,
781                }))
782            }
783
784            hir::ExprKind::Path(ref qpath) => {
785                let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
786                self.convert_path_expr(expr, res)
787            }
788
789            hir::ExprKind::InlineAsm(asm) => ExprKind::InlineAsm(Box::new(InlineAsmExpr {
790                asm_macro: asm.asm_macro,
791                template: asm.template,
792                operands: asm
793                    .operands
794                    .iter()
795                    .map(|(op, _op_sp)| match *op {
796                        hir::InlineAsmOperand::In { reg, expr } => {
797                            InlineAsmOperand::In { reg, expr: self.mirror_expr(expr) }
798                        }
799                        hir::InlineAsmOperand::Out { reg, late, ref expr } => {
800                            InlineAsmOperand::Out {
801                                reg,
802                                late,
803                                expr: expr.map(|expr| self.mirror_expr(expr)),
804                            }
805                        }
806                        hir::InlineAsmOperand::InOut { reg, late, expr } => {
807                            InlineAsmOperand::InOut { reg, late, expr: self.mirror_expr(expr) }
808                        }
809                        hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, ref out_expr } => {
810                            InlineAsmOperand::SplitInOut {
811                                reg,
812                                late,
813                                in_expr: self.mirror_expr(in_expr),
814                                out_expr: out_expr.map(|expr| self.mirror_expr(expr)),
815                            }
816                        }
817                        hir::InlineAsmOperand::Const { ref anon_const } => {
818                            let ty = self.typeck_results.node_type(anon_const.hir_id);
819                            let did = anon_const.def_id.to_def_id();
820                            let typeck_root_def_id = tcx.typeck_root_def_id(did);
821                            let parent_args = tcx.erase_and_anonymize_regions(
822                                GenericArgs::identity_for_item(tcx, typeck_root_def_id),
823                            );
824                            let args =
825                                InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty })
826                                    .args;
827
828                            let uneval = mir::UnevaluatedConst::new(did, args);
829                            let value = mir::Const::Unevaluated(uneval, ty);
830                            InlineAsmOperand::Const { value, span: tcx.def_span(did) }
831                        }
832                        hir::InlineAsmOperand::SymFn { expr } => {
833                            InlineAsmOperand::SymFn { value: self.mirror_expr(expr) }
834                        }
835                        hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
836                            InlineAsmOperand::SymStatic { def_id }
837                        }
838                        hir::InlineAsmOperand::Label { block } => {
839                            InlineAsmOperand::Label { block: self.mirror_block(block) }
840                        }
841                    })
842                    .collect(),
843                options: asm.options,
844                line_spans: asm.line_spans,
845            })),
846
847            hir::ExprKind::OffsetOf(_, _) => {
848                let offset_of_intrinsic = tcx.require_lang_item(LangItem::OffsetOf, expr.span);
849                let mk_u32_kind = |val: u32| ExprKind::NonHirLiteral {
850                    lit: ScalarInt::try_from_uint(val, Size::from_bits(32)).unwrap(),
851                    user_ty: None,
852                };
853                let mk_usize_kind = |val: u64| ExprKind::NonHirLiteral {
854                    lit: ScalarInt::try_from_target_usize(val, tcx).unwrap(),
855                    user_ty: None,
856                };
857                let mk_call =
858                    |thir: &mut Thir<'tcx>, ty: Ty<'tcx>, variant: VariantIdx, field: FieldIdx| {
859                        let fun_ty =
860                            Ty::new_fn_def(tcx, offset_of_intrinsic, [ty::GenericArg::from(ty)]);
861                        let fun = thir
862                            .exprs
863                            .push(mk_expr(ExprKind::ZstLiteral { user_ty: None }, fun_ty));
864                        let variant =
865                            thir.exprs.push(mk_expr(mk_u32_kind(variant.as_u32()), tcx.types.u32));
866                        let field =
867                            thir.exprs.push(mk_expr(mk_u32_kind(field.as_u32()), tcx.types.u32));
868                        let args = Box::new([variant, field]);
869                        ExprKind::Call {
870                            ty: fun_ty,
871                            fun,
872                            args,
873                            from_hir_call: false,
874                            fn_span: expr.span,
875                        }
876                    };
877
878                let indices = self.typeck_results.offset_of_data().get(expr.hir_id).unwrap();
879                let mut expr = None::<ExprKind<'tcx>>;
880
881                for &(container, variant, field) in indices.iter() {
882                    let next = mk_call(&mut self.thir, container, variant, field);
883                    expr = Some(match expr.take() {
884                        None => next,
885                        Some(last) => {
886                            let last = self.thir.exprs.push(mk_expr(last, tcx.types.usize));
887                            let next = self.thir.exprs.push(mk_expr(next, tcx.types.usize));
888                            ExprKind::Binary { op: BinOp::Add, lhs: last, rhs: next }
889                        }
890                    });
891                }
892
893                expr.unwrap_or_else(|| mk_usize_kind(0))
894            }
895
896            hir::ExprKind::ConstBlock(ref anon_const) => {
897                let ty = self.typeck_results.node_type(anon_const.hir_id);
898                let did = anon_const.def_id.to_def_id();
899                let typeck_root_def_id = tcx.typeck_root_def_id(did);
900                let parent_args = tcx.erase_and_anonymize_regions(GenericArgs::identity_for_item(
901                    tcx,
902                    typeck_root_def_id,
903                ));
904                let args = InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty }).args;
905
906                ExprKind::ConstBlock { did, args }
907            }
908            // Now comes the rote stuff:
909            hir::ExprKind::Repeat(v, _) => {
910                let ty = self.typeck_results.expr_ty(expr);
911                let ty::Array(_, count) = ty.kind() else {
912                    span_bug!(expr.span, "unexpected repeat expr ty: {:?}", ty);
913                };
914
915                ExprKind::Repeat { value: self.mirror_expr(v), count: *count }
916            }
917            hir::ExprKind::Ret(v) => ExprKind::Return { value: v.map(|v| self.mirror_expr(v)) },
918            hir::ExprKind::Become(call) => ExprKind::Become { value: self.mirror_expr(call) },
919            hir::ExprKind::Break(dest, ref value) => {
920                if find_attr!(self.tcx.hir_attrs(expr.hir_id), ConstContinue(_)) {
921                    match dest.target_id {
922                        Ok(target_id) => {
923                            let (Some(value), Some(_)) = (value, dest.label) else {
924                                let span = expr.span;
925                                self.tcx.dcx().emit_fatal(ConstContinueMissingLabelOrValue { span })
926                            };
927
928                            ExprKind::ConstContinue {
929                                label: region::Scope {
930                                    local_id: target_id.local_id,
931                                    data: region::ScopeData::Node,
932                                },
933                                value: self.mirror_expr(value),
934                            }
935                        }
936                        Err(err) => bug!("invalid loop id for break: {}", err),
937                    }
938                } else {
939                    match dest.target_id {
940                        Ok(target_id) => ExprKind::Break {
941                            label: region::Scope {
942                                local_id: target_id.local_id,
943                                data: region::ScopeData::Node,
944                            },
945                            value: value.map(|value| self.mirror_expr(value)),
946                        },
947                        Err(err) => bug!("invalid loop id for break: {}", err),
948                    }
949                }
950            }
951            hir::ExprKind::Continue(dest) => match dest.target_id {
952                Ok(loop_id) => ExprKind::Continue {
953                    label: region::Scope {
954                        local_id: loop_id.local_id,
955                        data: region::ScopeData::Node,
956                    },
957                },
958                Err(err) => bug!("invalid loop id for continue: {}", err),
959            },
960            hir::ExprKind::Let(let_expr) => ExprKind::Let {
961                expr: self.mirror_expr(let_expr.init),
962                pat: self.pattern_from_hir(let_expr.pat),
963            },
964            hir::ExprKind::If(cond, then, else_opt) => ExprKind::If {
965                if_then_scope: region::Scope {
966                    local_id: then.hir_id.local_id,
967                    data: {
968                        if expr.span.at_least_rust_2024() {
969                            region::ScopeData::IfThenRescope
970                        } else {
971                            region::ScopeData::IfThen
972                        }
973                    },
974                },
975                cond: self.mirror_expr(cond),
976                then: self.mirror_expr(then),
977                else_opt: else_opt.map(|el| self.mirror_expr(el)),
978            },
979            hir::ExprKind::Match(discr, arms, match_source) => ExprKind::Match {
980                scrutinee: self.mirror_expr(discr),
981                arms: arms.iter().map(|a| self.convert_arm(a)).collect(),
982                match_source,
983            },
984            hir::ExprKind::Loop(body, ..) => {
985                if find_attr!(self.tcx.hir_attrs(expr.hir_id), LoopMatch(_)) {
986                    let dcx = self.tcx.dcx();
987
988                    // Accept either `state = expr` or `state = expr;`.
989                    let loop_body_expr = match body.stmts {
990                        [] => match body.expr {
991                            Some(expr) => expr,
992                            None => dcx.emit_fatal(LoopMatchMissingAssignment { span: body.span }),
993                        },
994                        [single] if body.expr.is_none() => match single.kind {
995                            hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr) => expr,
996                            _ => dcx.emit_fatal(LoopMatchMissingAssignment { span: body.span }),
997                        },
998                        [first @ last] | [first, .., last] => dcx
999                            .emit_fatal(LoopMatchBadStatements { span: first.span.to(last.span) }),
1000                    };
1001
1002                    let hir::ExprKind::Assign(state, rhs_expr, _) = loop_body_expr.kind else {
1003                        dcx.emit_fatal(LoopMatchMissingAssignment { span: loop_body_expr.span })
1004                    };
1005
1006                    let hir::ExprKind::Block(block_body, _) = rhs_expr.kind else {
1007                        dcx.emit_fatal(LoopMatchBadRhs { span: rhs_expr.span })
1008                    };
1009
1010                    // The labeled block should contain one match expression, but defining items is
1011                    // allowed.
1012                    for stmt in block_body.stmts {
1013                        if !matches!(stmt.kind, rustc_hir::StmtKind::Item(_)) {
1014                            dcx.emit_fatal(LoopMatchBadStatements { span: stmt.span })
1015                        }
1016                    }
1017
1018                    let Some(block_body_expr) = block_body.expr else {
1019                        dcx.emit_fatal(LoopMatchBadRhs { span: block_body.span })
1020                    };
1021
1022                    let hir::ExprKind::Match(scrutinee, arms, _match_source) = block_body_expr.kind
1023                    else {
1024                        dcx.emit_fatal(LoopMatchBadRhs { span: block_body_expr.span })
1025                    };
1026
1027                    fn local(
1028                        cx: &mut ThirBuildCx<'_>,
1029                        expr: &rustc_hir::Expr<'_>,
1030                    ) -> Option<hir::HirId> {
1031                        if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind
1032                            && let Res::Local(hir_id) = path.res
1033                            && !cx.is_upvar(hir_id)
1034                        {
1035                            return Some(hir_id);
1036                        }
1037
1038                        None
1039                    }
1040
1041                    let Some(scrutinee_hir_id) = local(self, scrutinee) else {
1042                        dcx.emit_fatal(LoopMatchInvalidMatch { span: scrutinee.span })
1043                    };
1044
1045                    if local(self, state) != Some(scrutinee_hir_id) {
1046                        dcx.emit_fatal(LoopMatchInvalidUpdate {
1047                            scrutinee: scrutinee.span,
1048                            lhs: state.span,
1049                        })
1050                    }
1051
1052                    ExprKind::LoopMatch {
1053                        state: self.mirror_expr(state),
1054                        region_scope: region::Scope {
1055                            local_id: block_body.hir_id.local_id,
1056                            data: region::ScopeData::Node,
1057                        },
1058
1059                        match_data: Box::new(LoopMatchMatchData {
1060                            scrutinee: self.mirror_expr(scrutinee),
1061                            arms: arms.iter().map(|a| self.convert_arm(a)).collect(),
1062                            span: block_body_expr.span,
1063                        }),
1064                    }
1065                } else {
1066                    let block_ty = self.typeck_results.node_type(body.hir_id);
1067                    let block = self.mirror_block(body);
1068                    let body = self.thir.exprs.push(Expr {
1069                        ty: block_ty,
1070                        temp_scope_id: body.hir_id.local_id,
1071                        span: self.thir[block].span,
1072                        kind: ExprKind::Block { block },
1073                    });
1074                    ExprKind::Loop { body }
1075                }
1076            }
1077            hir::ExprKind::Field(source, ..) => ExprKind::Field {
1078                lhs: self.mirror_expr(source),
1079                variant_index: FIRST_VARIANT,
1080                name: self.typeck_results.field_index(expr.hir_id),
1081            },
1082            hir::ExprKind::Cast(source, cast_ty) => {
1083                // Check for a user-given type annotation on this `cast`
1084                let user_provided_types = self.typeck_results.user_provided_types();
1085                let user_ty = user_provided_types.get(cast_ty.hir_id);
1086
1087                debug!(
1088                    "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
1089                    expr, cast_ty.hir_id, user_ty,
1090                );
1091
1092                let cast = self.mirror_expr_cast(source, expr.hir_id.local_id, expr.span);
1093
1094                if let Some(user_ty) = user_ty {
1095                    // NOTE: Creating a new Expr and wrapping a Cast inside of it may be
1096                    //       inefficient, revisit this when performance becomes an issue.
1097                    let cast_expr = self.thir.exprs.push(Expr {
1098                        temp_scope_id: expr.hir_id.local_id,
1099                        ty: expr_ty,
1100                        span: expr.span,
1101                        kind: cast,
1102                    });
1103                    debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
1104
1105                    ExprKind::ValueTypeAscription {
1106                        source: cast_expr,
1107                        user_ty: Some(Box::new(*user_ty)),
1108                        user_ty_span: cast_ty.span,
1109                    }
1110                } else {
1111                    cast
1112                }
1113            }
1114            hir::ExprKind::Type(source, ty) => {
1115                let user_provided_types = self.typeck_results.user_provided_types();
1116                let user_ty = user_provided_types.get(ty.hir_id).copied().map(Box::new);
1117                debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
1118                let mirrored = self.mirror_expr(source);
1119                if source.is_syntactic_place_expr() {
1120                    ExprKind::PlaceTypeAscription {
1121                        source: mirrored,
1122                        user_ty,
1123                        user_ty_span: ty.span,
1124                    }
1125                } else {
1126                    ExprKind::ValueTypeAscription {
1127                        source: mirrored,
1128                        user_ty,
1129                        user_ty_span: ty.span,
1130                    }
1131                }
1132            }
1133
1134            hir::ExprKind::UnsafeBinderCast(UnsafeBinderCastKind::Unwrap, source, _ty) => {
1135                // FIXME(unsafe_binders): Take into account the ascribed type, too.
1136                let mirrored = self.mirror_expr(source);
1137                if source.is_syntactic_place_expr() {
1138                    ExprKind::PlaceUnwrapUnsafeBinder { source: mirrored }
1139                } else {
1140                    ExprKind::ValueUnwrapUnsafeBinder { source: mirrored }
1141                }
1142            }
1143            hir::ExprKind::UnsafeBinderCast(UnsafeBinderCastKind::Wrap, source, _ty) => {
1144                // FIXME(unsafe_binders): Take into account the ascribed type, too.
1145                let mirrored = self.mirror_expr(source);
1146                ExprKind::WrapUnsafeBinder { source: mirrored }
1147            }
1148
1149            hir::ExprKind::DropTemps(source) => ExprKind::Use { source: self.mirror_expr(source) },
1150            hir::ExprKind::Array(fields) => ExprKind::Array { fields: self.mirror_exprs(fields) },
1151            hir::ExprKind::Tup(fields) => ExprKind::Tuple { fields: self.mirror_exprs(fields) },
1152
1153            hir::ExprKind::Yield(v, _) => ExprKind::Yield { value: self.mirror_expr(v) },
1154            hir::ExprKind::Err(_) => unreachable!("cannot lower a `hir::ExprKind::Err` to THIR"),
1155        };
1156
1157        mk_expr(kind, expr_ty)
1158    }
1159
1160    fn user_args_applied_to_res(
1161        &mut self,
1162        hir_id: hir::HirId,
1163        res: Res,
1164    ) -> Option<Box<ty::CanonicalUserType<'tcx>>> {
1165        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:1165",
                        "rustc_mir_build::thir::cx::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(1165u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("user_args_applied_to_res: res={0:?}",
                                                    res) as &dyn Value))])
            });
    } else { ; }
};debug!("user_args_applied_to_res: res={:?}", res);
1166        let user_provided_type = match res {
1167            // A reference to something callable -- e.g., a fn, method, or
1168            // a tuple-struct or tuple-variant. This has the type of a
1169            // `Fn` but with the user-given generic parameters.
1170            Res::Def(DefKind::Fn, _)
1171            | Res::Def(DefKind::AssocFn, _)
1172            | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
1173            | Res::Def(DefKind::Const { .. }, _)
1174            | Res::Def(DefKind::AssocConst { .. }, _) => {
1175                self.typeck_results.user_provided_types().get(hir_id).copied().map(Box::new)
1176            }
1177
1178            // A unit struct/variant which is used as a value (e.g.,
1179            // `None`). This has the type of the enum/struct that defines
1180            // this variant -- but with the generic parameters given by the
1181            // user.
1182            Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => {
1183                self.user_args_applied_to_ty_of_hir_id(hir_id).map(Box::new)
1184            }
1185
1186            // `Self` is used in expression as a tuple struct constructor or a unit struct constructor
1187            Res::SelfCtor(_) => self.user_args_applied_to_ty_of_hir_id(hir_id).map(Box::new),
1188
1189            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("user_args_applied_to_res: unexpected res {0:?} at {1:?}",
        res, hir_id))bug!("user_args_applied_to_res: unexpected res {:?} at {:?}", res, hir_id),
1190        };
1191        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:1191",
                        "rustc_mir_build::thir::cx::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(1191u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("user_args_applied_to_res: user_provided_type={0:?}",
                                                    user_provided_type) as &dyn Value))])
            });
    } else { ; }
};debug!("user_args_applied_to_res: user_provided_type={:?}", user_provided_type);
1192        user_provided_type
1193    }
1194
1195    fn method_callee(
1196        &mut self,
1197        expr: &hir::Expr<'_>,
1198        span: Span,
1199        overloaded_callee: Option<Ty<'tcx>>,
1200    ) -> Expr<'tcx> {
1201        let (ty, user_ty) = match overloaded_callee {
1202            Some(fn_def) => (fn_def, None),
1203            None => {
1204                let (kind, def_id) =
1205                    self.typeck_results.type_dependent_def(expr.hir_id).unwrap_or_else(|| {
1206                        ::rustc_middle::util::bug::span_bug_fmt(expr.span,
    format_args!("no type-dependent def for method callee"))span_bug!(expr.span, "no type-dependent def for method callee")
1207                    });
1208                let user_ty = self.user_args_applied_to_res(expr.hir_id, Res::Def(kind, def_id));
1209                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:1209",
                        "rustc_mir_build::thir::cx::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(1209u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("method_callee: user_ty={0:?}",
                                                    user_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("method_callee: user_ty={:?}", user_ty);
1210                (
1211                    Ty::new_fn_def(self.tcx, def_id, self.typeck_results.node_args(expr.hir_id)),
1212                    user_ty,
1213                )
1214            }
1215        };
1216        Expr {
1217            temp_scope_id: expr.hir_id.local_id,
1218            ty,
1219            span,
1220            kind: ExprKind::ZstLiteral { user_ty },
1221        }
1222    }
1223
1224    fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId {
1225        let arm = Arm {
1226            pattern: self.pattern_from_hir(&arm.pat),
1227            guard: arm.guard.as_ref().map(|g| self.mirror_expr(g)),
1228            body: self.mirror_expr(arm.body),
1229            hir_id: arm.hir_id,
1230            scope: region::Scope { local_id: arm.hir_id.local_id, data: region::ScopeData::Node },
1231            span: arm.span,
1232        };
1233        self.thir.arms.push(arm)
1234    }
1235
1236    fn convert_path_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, res: Res) -> ExprKind<'tcx> {
1237        let args = self.typeck_results.node_args(expr.hir_id);
1238        match res {
1239            // A regular function, constructor function or a constant.
1240            Res::Def(DefKind::Fn, _)
1241            | Res::Def(DefKind::AssocFn, _)
1242            | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
1243            | Res::SelfCtor(_) => {
1244                let user_ty = self.user_args_applied_to_res(expr.hir_id, res);
1245                ExprKind::ZstLiteral { user_ty }
1246            }
1247
1248            Res::Def(DefKind::ConstParam, def_id) => {
1249                let hir_id = self.tcx.local_def_id_to_hir_id(def_id.expect_local());
1250                let generics = self.tcx.generics_of(hir_id.owner);
1251                let Some(&index) = generics.param_def_id_to_index.get(&def_id) else {
1252                    ::rustc_middle::util::bug::span_bug_fmt(expr.span,
    format_args!("Should have already errored about late bound consts: {0:?}",
        def_id));span_bug!(
1253                        expr.span,
1254                        "Should have already errored about late bound consts: {def_id:?}"
1255                    );
1256                };
1257                let name = self.tcx.hir_name(hir_id);
1258                let param = ty::ParamConst::new(index, name);
1259
1260                ExprKind::ConstParam { param, def_id }
1261            }
1262
1263            Res::Def(DefKind::Const { .. }, def_id)
1264            | Res::Def(DefKind::AssocConst { .. }, def_id) => {
1265                let user_ty = self.user_args_applied_to_res(expr.hir_id, res);
1266                ExprKind::NamedConst { def_id, args, user_ty }
1267            }
1268
1269            Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {
1270                let user_provided_types = self.typeck_results.user_provided_types();
1271                let user_ty = user_provided_types.get(expr.hir_id).copied().map(Box::new);
1272                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:1272",
                        "rustc_mir_build::thir::cx::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(1272u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("convert_path_expr: user_ty={0:?}",
                                                    user_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("convert_path_expr: user_ty={:?}", user_ty);
1273                let ty = self.typeck_results.node_type(expr.hir_id);
1274                match ty.kind() {
1275                    // A unit struct/variant which is used as a value.
1276                    // We return a completely different ExprKind here to account for this special case.
1277                    ty::Adt(adt_def, args) => ExprKind::Adt(Box::new(AdtExpr {
1278                        adt_def: *adt_def,
1279                        variant_index: adt_def.variant_index_with_ctor_id(def_id),
1280                        args,
1281                        user_ty,
1282                        fields: Box::new([]),
1283                        base: AdtExprBase::None,
1284                    })),
1285                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected ty: {0:?}", ty))bug!("unexpected ty: {:?}", ty),
1286                }
1287            }
1288
1289            // A source Rust `path::to::STATIC` is a place expr like *&ident is.
1290            // In THIR, we make them exactly equivalent by inserting the implied *& or *&raw,
1291            // but distinguish between &STATIC and &THREAD_LOCAL as they have different semantics
1292            Res::Def(DefKind::Static { .. }, id) => {
1293                // this is &raw for extern static or static mut, and & for other statics
1294                let ty = self.tcx.static_ptr_ty(id, self.typing_env);
1295                let kind = if self.tcx.is_thread_local_static(id) {
1296                    ExprKind::ThreadLocalRef(id)
1297                } else {
1298                    let alloc_id = self.tcx.reserve_and_set_static_alloc(id);
1299                    ExprKind::StaticRef { alloc_id, ty, def_id: id }
1300                };
1301                ExprKind::Deref {
1302                    arg: self.thir.exprs.push(Expr {
1303                        ty,
1304                        temp_scope_id: expr.hir_id.local_id,
1305                        span: expr.span,
1306                        kind,
1307                    }),
1308                }
1309            }
1310
1311            Res::Local(var_hir_id) => self.convert_var(var_hir_id),
1312
1313            _ => ::rustc_middle::util::bug::span_bug_fmt(expr.span,
    format_args!("res `{0:?}` not yet implemented", res))span_bug!(expr.span, "res `{:?}` not yet implemented", res),
1314        }
1315    }
1316
1317    fn convert_var(&mut self, var_hir_id: hir::HirId) -> ExprKind<'tcx> {
1318        // We want upvars here not captures.
1319        // Captures will be handled in MIR.
1320        let is_upvar = self.is_upvar(var_hir_id);
1321
1322        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs:1322",
                        "rustc_mir_build::thir::cx::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/cx/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(1322u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::cx::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("convert_var({0:?}): is_upvar={1}, body_owner={2:?}",
                                                    var_hir_id, is_upvar, self.body_owner) as &dyn Value))])
            });
    } else { ; }
};debug!(
1323            "convert_var({:?}): is_upvar={}, body_owner={:?}",
1324            var_hir_id, is_upvar, self.body_owner
1325        );
1326
1327        if is_upvar {
1328            ExprKind::UpvarRef {
1329                closure_def_id: self.body_owner,
1330                var_hir_id: LocalVarId(var_hir_id),
1331            }
1332        } else {
1333            ExprKind::VarRef { id: LocalVarId(var_hir_id) }
1334        }
1335    }
1336
1337    fn overloaded_operator(
1338        &mut self,
1339        expr: &'tcx hir::Expr<'tcx>,
1340        args: Box<[ExprId]>,
1341    ) -> ExprKind<'tcx> {
1342        let fun = self.method_callee(expr, expr.span, None);
1343        let fun = self.thir.exprs.push(fun);
1344        ExprKind::Call {
1345            ty: self.thir[fun].ty,
1346            fun,
1347            args,
1348            from_hir_call: false,
1349            fn_span: expr.span,
1350        }
1351    }
1352
1353    fn overloaded_place(
1354        &mut self,
1355        expr: &'tcx hir::Expr<'tcx>,
1356        place_ty: Ty<'tcx>,
1357        overloaded_callee: Option<Ty<'tcx>>,
1358        args: Box<[ExprId]>,
1359        span: Span,
1360    ) -> ExprKind<'tcx> {
1361        // For an overloaded *x or x[y] expression of type T, the method
1362        // call returns an &T and we must add the deref so that the types
1363        // line up (this is because `*x` and `x[y]` represent places):
1364
1365        // Reconstruct the output assuming it's a reference with the
1366        // same region and mutability as the receiver. This holds for
1367        // `Deref(Mut)::deref(_mut)` and `Index(Mut)::index(_mut)`.
1368        let ty::Ref(region, _, mutbl) = *self.thir[args[0]].ty.kind() else {
1369            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("overloaded_place: receiver is not a reference"));span_bug!(span, "overloaded_place: receiver is not a reference");
1370        };
1371        let ref_ty = Ty::new_ref(self.tcx, region, place_ty, mutbl);
1372
1373        // construct the complete expression `foo()` for the overloaded call,
1374        // which will yield the &T type
1375        let fun = self.method_callee(expr, span, overloaded_callee);
1376        let fun = self.thir.exprs.push(fun);
1377        let fun_ty = self.thir[fun].ty;
1378        let ref_expr = self.thir.exprs.push(Expr {
1379            temp_scope_id: expr.hir_id.local_id,
1380            ty: ref_ty,
1381            span,
1382            kind: ExprKind::Call { ty: fun_ty, fun, args, from_hir_call: false, fn_span: span },
1383        });
1384
1385        // construct and return a deref wrapper `*foo()`
1386        ExprKind::Deref { arg: ref_expr }
1387    }
1388
1389    fn convert_captured_hir_place(
1390        &mut self,
1391        closure_expr: &'tcx hir::Expr<'tcx>,
1392        place: HirPlace<'tcx>,
1393    ) -> Expr<'tcx> {
1394        let temp_scope_id = closure_expr.hir_id.local_id;
1395        let var_ty = place.base_ty;
1396
1397        // The result of capture analysis in `rustc_hir_typeck/src/upvar.rs` represents a captured path
1398        // as it's seen for use within the closure and not at the time of closure creation.
1399        //
1400        // That is we see expect to see it start from a captured upvar and not something that is local
1401        // to the closure's parent.
1402        let var_hir_id = match place.base {
1403            HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1404            base => ::rustc_middle::util::bug::bug_fmt(format_args!("Expected an upvar, found {0:?}",
        base))bug!("Expected an upvar, found {:?}", base),
1405        };
1406
1407        let mut captured_place_expr = Expr {
1408            temp_scope_id,
1409            ty: var_ty,
1410            span: closure_expr.span,
1411            kind: self.convert_var(var_hir_id),
1412        };
1413
1414        for proj in place.projections.iter() {
1415            let kind = match proj.kind {
1416                HirProjectionKind::Deref => {
1417                    ExprKind::Deref { arg: self.thir.exprs.push(captured_place_expr) }
1418                }
1419                HirProjectionKind::Field(field, variant_index) => ExprKind::Field {
1420                    lhs: self.thir.exprs.push(captured_place_expr),
1421                    variant_index,
1422                    name: field,
1423                },
1424                HirProjectionKind::OpaqueCast => {
1425                    ExprKind::Use { source: self.thir.exprs.push(captured_place_expr) }
1426                }
1427                HirProjectionKind::UnwrapUnsafeBinder => ExprKind::PlaceUnwrapUnsafeBinder {
1428                    source: self.thir.exprs.push(captured_place_expr),
1429                },
1430                HirProjectionKind::Index | HirProjectionKind::Subslice => {
1431                    // We don't capture these projections, so we can ignore them here
1432                    continue;
1433                }
1434            };
1435
1436            captured_place_expr =
1437                Expr { temp_scope_id, ty: proj.ty, span: closure_expr.span, kind };
1438        }
1439
1440        captured_place_expr
1441    }
1442
1443    fn capture_upvar(
1444        &mut self,
1445        closure_expr: &'tcx hir::Expr<'tcx>,
1446        captured_place: &'tcx ty::CapturedPlace<'tcx>,
1447        upvar_ty: Ty<'tcx>,
1448    ) -> Expr<'tcx> {
1449        let upvar_capture = captured_place.info.capture_kind;
1450        let captured_place_expr =
1451            self.convert_captured_hir_place(closure_expr, captured_place.place.clone());
1452        let temp_scope_id = closure_expr.hir_id.local_id;
1453
1454        match upvar_capture {
1455            ty::UpvarCapture::ByValue => captured_place_expr,
1456            ty::UpvarCapture::ByUse => {
1457                let span = captured_place_expr.span;
1458                let expr_id = self.thir.exprs.push(captured_place_expr);
1459
1460                Expr {
1461                    temp_scope_id,
1462                    ty: upvar_ty,
1463                    span: closure_expr.span,
1464                    kind: ExprKind::ByUse { expr: expr_id, span },
1465                }
1466            }
1467            ty::UpvarCapture::ByRef(upvar_borrow) => {
1468                let borrow_kind = match upvar_borrow {
1469                    ty::BorrowKind::Immutable => BorrowKind::Shared,
1470                    ty::BorrowKind::UniqueImmutable => {
1471                        BorrowKind::Mut { kind: mir::MutBorrowKind::ClosureCapture }
1472                    }
1473                    ty::BorrowKind::Mutable => {
1474                        BorrowKind::Mut { kind: mir::MutBorrowKind::Default }
1475                    }
1476                };
1477                Expr {
1478                    temp_scope_id,
1479                    ty: upvar_ty,
1480                    span: closure_expr.span,
1481                    kind: ExprKind::Borrow {
1482                        borrow_kind,
1483                        arg: self.thir.exprs.push(captured_place_expr),
1484                    },
1485                }
1486            }
1487        }
1488    }
1489
1490    fn is_upvar(&mut self, var_hir_id: hir::HirId) -> bool {
1491        self.tcx
1492            .upvars_mentioned(self.body_owner)
1493            .is_some_and(|upvars| upvars.contains_key(&var_hir_id))
1494    }
1495
1496    /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExpr.
1497    fn field_refs(&mut self, fields: &'tcx [hir::ExprField<'tcx>]) -> Box<[FieldExpr]> {
1498        fields
1499            .iter()
1500            .map(|field| FieldExpr {
1501                name: self.typeck_results.field_index(field.hir_id),
1502                expr: self.mirror_expr(field.expr),
1503            })
1504            .collect()
1505    }
1506}
1507
1508trait ToBorrowKind {
1509    fn to_borrow_kind(&self) -> BorrowKind;
1510}
1511
1512impl ToBorrowKind for AutoBorrowMutability {
1513    fn to_borrow_kind(&self) -> BorrowKind {
1514        use rustc_middle::ty::adjustment::AllowTwoPhase;
1515        match *self {
1516            AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut {
1517                kind: match allow_two_phase_borrow {
1518                    AllowTwoPhase::Yes => mir::MutBorrowKind::TwoPhaseBorrow,
1519                    AllowTwoPhase::No => mir::MutBorrowKind::Default,
1520                },
1521            },
1522            AutoBorrowMutability::Not => BorrowKind::Shared,
1523        }
1524    }
1525}
1526
1527impl ToBorrowKind for hir::Mutability {
1528    fn to_borrow_kind(&self) -> BorrowKind {
1529        match *self {
1530            hir::Mutability::Mut => BorrowKind::Mut { kind: mir::MutBorrowKind::Default },
1531            hir::Mutability::Not => BorrowKind::Shared,
1532        }
1533    }
1534}
1535
1536fn bin_op(op: hir::BinOpKind) -> BinOp {
1537    match op {
1538        hir::BinOpKind::Add => BinOp::Add,
1539        hir::BinOpKind::Sub => BinOp::Sub,
1540        hir::BinOpKind::Mul => BinOp::Mul,
1541        hir::BinOpKind::Div => BinOp::Div,
1542        hir::BinOpKind::Rem => BinOp::Rem,
1543        hir::BinOpKind::BitXor => BinOp::BitXor,
1544        hir::BinOpKind::BitAnd => BinOp::BitAnd,
1545        hir::BinOpKind::BitOr => BinOp::BitOr,
1546        hir::BinOpKind::Shl => BinOp::Shl,
1547        hir::BinOpKind::Shr => BinOp::Shr,
1548        hir::BinOpKind::Eq => BinOp::Eq,
1549        hir::BinOpKind::Lt => BinOp::Lt,
1550        hir::BinOpKind::Le => BinOp::Le,
1551        hir::BinOpKind::Ne => BinOp::Ne,
1552        hir::BinOpKind::Ge => BinOp::Ge,
1553        hir::BinOpKind::Gt => BinOp::Gt,
1554        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("no equivalent for ast binop {0:?}",
        op))bug!("no equivalent for ast binop {:?}", op),
1555    }
1556}
1557
1558fn assign_op(op: hir::AssignOpKind) -> AssignOp {
1559    match op {
1560        hir::AssignOpKind::AddAssign => AssignOp::AddAssign,
1561        hir::AssignOpKind::SubAssign => AssignOp::SubAssign,
1562        hir::AssignOpKind::MulAssign => AssignOp::MulAssign,
1563        hir::AssignOpKind::DivAssign => AssignOp::DivAssign,
1564        hir::AssignOpKind::RemAssign => AssignOp::RemAssign,
1565        hir::AssignOpKind::BitXorAssign => AssignOp::BitXorAssign,
1566        hir::AssignOpKind::BitAndAssign => AssignOp::BitAndAssign,
1567        hir::AssignOpKind::BitOrAssign => AssignOp::BitOrAssign,
1568        hir::AssignOpKind::ShlAssign => AssignOp::ShlAssign,
1569        hir::AssignOpKind::ShrAssign => AssignOp::ShrAssign,
1570    }
1571}