Skip to main content

rustc_mir_build/thir/cx/
expr.rs

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