rustc_mir_build/thir/cx/
expr.rs

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