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