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(&[]) })
                } 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(&["hir_expr.hir_id",
                                                    "hir_expr.span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&hir_expr.hir_id)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&hir_expr.span)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let mut expr = self.make_mirror_unadjusted(hir_expr);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs: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(&["expr.ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&expr.ty) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            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(&["expr",
                                                            "adjustment"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&expr) as
                                                                &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&adjustment)
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    let span = expr.span;
                    expr =
                        self.apply_adjustment(hir_expr, expr, adjustment, span);
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/cx/expr.rs: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",
                                                    "expr.ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("after adjustments")
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&expr.ty) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            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(&["hir_expr",
                                                    "adjustment"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_expr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&adjustment)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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