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 pub(crate) fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId {
39 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 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 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 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 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 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 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 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 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 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 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 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 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 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 if self.typeck_results.is_coercion_cast(source.hir_id) {
262 ExprKind::Use { source: self.mirror_expr(source) }
264 } else if self.typeck_results.expr_ty(source).is_ref() {
265 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 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 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 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 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.rvalue_scopes.temporary_scope(self.region_scope_tree, expr.hir_id.local_id);
341
342 let kind = match expr.kind {
343 hir::ExprKind::MethodCall(segment, receiver, args, fn_span) => {
345 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 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 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 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 _ => None,
429 }
430 } else {
431 None
432 };
433 if let Some((adt_def, index)) = adt_data {
434 let node_args = self.typeck_results.node_args(fun.hir_id);
435 let user_provided_types = self.typeck_results.user_provided_types();
436 let user_ty =
437 user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| {
438 if let ty::UserTypeKind::TypeOf(did, _) = &mut u_ty.value.kind {
439 *did = adt_def.did();
440 }
441 Box::new(u_ty)
442 });
443 debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
444
445 let field_refs = args
446 .iter()
447 .enumerate()
448 .map(|(idx, e)| FieldExpr {
449 name: FieldIdx::new(idx),
450 expr: self.mirror_expr(e),
451 })
452 .collect();
453 ExprKind::Adt(Box::new(AdtExpr {
454 adt_def,
455 args: node_args,
456 variant_index: index,
457 fields: field_refs,
458 user_ty,
459 base: AdtExprBase::None,
460 }))
461 } else {
462 ExprKind::Call {
463 ty: self.typeck_results.node_type(fun.hir_id),
464 fun: self.mirror_expr(fun),
465 args: self.mirror_exprs(args),
466 from_hir_call: true,
467 fn_span: expr.span,
468 }
469 }
470 }
471 }
472
473 hir::ExprKind::Use(expr, span) => {
474 ExprKind::ByUse { expr: self.mirror_expr(expr), span }
475 }
476
477 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, arg) => {
478 ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: self.mirror_expr(arg) }
479 }
480
481 hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, arg) => {
482 ExprKind::RawBorrow { mutability, arg: self.mirror_expr(arg) }
483 }
484
485 hir::ExprKind::AddrOf(hir::BorrowKind::Pin, mutbl, arg_expr) => match expr_ty.kind() {
488 &ty::Adt(adt_def, args) if tcx.is_lang_item(adt_def.did(), hir::LangItem::Pin) => {
489 let ty = args.type_at(0);
490 let arg_ty = self.typeck_results.expr_ty(arg_expr);
491 let mut arg = self.mirror_expr(arg_expr);
492 if mutbl.is_mut() && !arg_ty.is_unpin(self.tcx, self.typing_env) {
495 let block = self.thir.blocks.push(Block {
496 targeted_by_break: false,
497 region_scope: region::Scope {
498 local_id: arg_expr.hir_id.local_id,
499 data: region::ScopeData::Node,
500 },
501 span: arg_expr.span,
502 stmts: Box::new([]),
503 expr: Some(arg),
504 safety_mode: BlockSafety::Safe,
505 });
506 let (temp_lifetime, backwards_incompatible) = self
507 .rvalue_scopes
508 .temporary_scope(self.region_scope_tree, arg_expr.hir_id.local_id);
509 arg = self.thir.exprs.push(Expr {
510 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
511 ty: arg_ty,
512 span: arg_expr.span,
513 kind: ExprKind::Block { block },
514 });
515 }
516 let expr = self.thir.exprs.push(Expr {
517 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
518 ty,
519 span: expr.span,
520 kind: ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg },
521 });
522 ExprKind::Adt(Box::new(AdtExpr {
523 adt_def,
524 variant_index: FIRST_VARIANT,
525 args,
526 fields: Box::new([FieldExpr { name: FieldIdx::from(0u32), expr }]),
527 user_ty: None,
528 base: AdtExprBase::None,
529 }))
530 }
531 _ => span_bug!(expr.span, "unexpected type for pinned borrow: {:?}", expr_ty),
532 },
533
534 hir::ExprKind::Block(blk, _) => ExprKind::Block { block: self.mirror_block(blk) },
535
536 hir::ExprKind::Assign(lhs, rhs, _) => {
537 ExprKind::Assign { lhs: self.mirror_expr(lhs), rhs: self.mirror_expr(rhs) }
538 }
539
540 hir::ExprKind::AssignOp(op, lhs, rhs) => {
541 if self.typeck_results.is_method_call(expr) {
542 let lhs = self.mirror_expr(lhs);
543 let rhs = self.mirror_expr(rhs);
544 self.overloaded_operator(expr, Box::new([lhs, rhs]))
545 } else {
546 ExprKind::AssignOp {
547 op: assign_op(op.node),
548 lhs: self.mirror_expr(lhs),
549 rhs: self.mirror_expr(rhs),
550 }
551 }
552 }
553
554 hir::ExprKind::Lit(lit) => ExprKind::Literal { lit, neg: false },
555
556 hir::ExprKind::Binary(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 match op.node {
563 hir::BinOpKind::And => ExprKind::LogicalOp {
564 op: LogicalOp::And,
565 lhs: self.mirror_expr(lhs),
566 rhs: self.mirror_expr(rhs),
567 },
568 hir::BinOpKind::Or => ExprKind::LogicalOp {
569 op: LogicalOp::Or,
570 lhs: self.mirror_expr(lhs),
571 rhs: self.mirror_expr(rhs),
572 },
573 _ => {
574 let op = bin_op(op.node);
575 ExprKind::Binary {
576 op,
577 lhs: self.mirror_expr(lhs),
578 rhs: self.mirror_expr(rhs),
579 }
580 }
581 }
582 }
583 }
584
585 hir::ExprKind::Index(lhs, index, brackets_span) => {
586 if self.typeck_results.is_method_call(expr) {
587 let lhs = self.mirror_expr(lhs);
588 let index = self.mirror_expr(index);
589 self.overloaded_place(
590 expr,
591 expr_ty,
592 None,
593 Box::new([lhs, index]),
594 brackets_span,
595 )
596 } else {
597 ExprKind::Index { lhs: self.mirror_expr(lhs), index: self.mirror_expr(index) }
598 }
599 }
600
601 hir::ExprKind::Unary(hir::UnOp::Deref, arg) => {
602 if self.typeck_results.is_method_call(expr) {
603 let arg = self.mirror_expr(arg);
604 self.overloaded_place(expr, expr_ty, None, Box::new([arg]), expr.span)
605 } else {
606 ExprKind::Deref { arg: self.mirror_expr(arg) }
607 }
608 }
609
610 hir::ExprKind::Unary(hir::UnOp::Not, arg) => {
611 if self.typeck_results.is_method_call(expr) {
612 let arg = self.mirror_expr(arg);
613 self.overloaded_operator(expr, Box::new([arg]))
614 } else {
615 ExprKind::Unary { op: UnOp::Not, arg: self.mirror_expr(arg) }
616 }
617 }
618
619 hir::ExprKind::Unary(hir::UnOp::Neg, arg) => {
620 if self.typeck_results.is_method_call(expr) {
621 let arg = self.mirror_expr(arg);
622 self.overloaded_operator(expr, Box::new([arg]))
623 } else if let hir::ExprKind::Lit(lit) = arg.kind {
624 ExprKind::Literal { lit, neg: true }
625 } else {
626 ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) }
627 }
628 }
629
630 hir::ExprKind::Struct(qpath, fields, ref base) => match expr_ty.kind() {
631 ty::Adt(adt, args) => match adt.adt_kind() {
632 AdtKind::Struct | AdtKind::Union => {
633 let user_provided_types = self.typeck_results.user_provided_types();
634 let user_ty = user_provided_types.get(expr.hir_id).copied().map(Box::new);
635 debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
636 ExprKind::Adt(Box::new(AdtExpr {
637 adt_def: *adt,
638 variant_index: FIRST_VARIANT,
639 args,
640 user_ty,
641 fields: self.field_refs(fields),
642 base: match base {
643 hir::StructTailExpr::Base(base) => AdtExprBase::Base(FruInfo {
644 base: self.mirror_expr(base),
645 field_types: self.typeck_results.fru_field_types()[expr.hir_id]
646 .iter()
647 .copied()
648 .collect(),
649 }),
650 hir::StructTailExpr::DefaultFields(_) => {
651 AdtExprBase::DefaultFields(
652 self.typeck_results.fru_field_types()[expr.hir_id]
653 .iter()
654 .copied()
655 .collect(),
656 )
657 }
658 hir::StructTailExpr::None => AdtExprBase::None,
659 },
660 }))
661 }
662 AdtKind::Enum => {
663 let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
664 match res {
665 Res::Def(DefKind::Variant, variant_id) => {
666 assert!(matches!(
667 base,
668 hir::StructTailExpr::None
669 | hir::StructTailExpr::DefaultFields(_)
670 ));
671
672 let index = adt.variant_index_with_id(variant_id);
673 let user_provided_types = self.typeck_results.user_provided_types();
674 let user_ty =
675 user_provided_types.get(expr.hir_id).copied().map(Box::new);
676 debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty);
677 ExprKind::Adt(Box::new(AdtExpr {
678 adt_def: *adt,
679 variant_index: index,
680 args,
681 user_ty,
682 fields: self.field_refs(fields),
683 base: match base {
684 hir::StructTailExpr::DefaultFields(_) => {
685 AdtExprBase::DefaultFields(
686 self.typeck_results.fru_field_types()[expr.hir_id]
687 .iter()
688 .copied()
689 .collect(),
690 )
691 }
692 hir::StructTailExpr::Base(base) => {
693 span_bug!(base.span, "unexpected res: {:?}", res);
694 }
695 hir::StructTailExpr::None => AdtExprBase::None,
696 },
697 }))
698 }
699 _ => {
700 span_bug!(expr.span, "unexpected res: {:?}", res);
701 }
702 }
703 }
704 },
705 _ => {
706 span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty);
707 }
708 },
709
710 hir::ExprKind::Closure(hir::Closure { .. }) => {
711 let closure_ty = self.typeck_results.expr_ty(expr);
712 let (def_id, args, movability) = match *closure_ty.kind() {
713 ty::Closure(def_id, args) => (def_id, UpvarArgs::Closure(args), None),
714 ty::Coroutine(def_id, args) => {
715 (def_id, UpvarArgs::Coroutine(args), Some(tcx.coroutine_movability(def_id)))
716 }
717 ty::CoroutineClosure(def_id, args) => {
718 (def_id, UpvarArgs::CoroutineClosure(args), None)
719 }
720 _ => {
721 span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
722 }
723 };
724 let def_id = def_id.expect_local();
725
726 let upvars = self
727 .tcx
728 .closure_captures(def_id)
729 .iter()
730 .zip_eq(args.upvar_tys())
731 .map(|(captured_place, ty)| {
732 let upvars = self.capture_upvar(expr, captured_place, ty);
733 self.thir.exprs.push(upvars)
734 })
735 .collect();
736
737 let fake_reads = match self.typeck_results.closure_fake_reads.get(&def_id) {
739 Some(fake_reads) => fake_reads
740 .iter()
741 .map(|(place, cause, hir_id)| {
742 let expr = self.convert_captured_hir_place(expr, place.clone());
743 (self.thir.exprs.push(expr), *cause, *hir_id)
744 })
745 .collect(),
746 None => Vec::new(),
747 };
748
749 ExprKind::Closure(Box::new(ClosureExpr {
750 closure_id: def_id,
751 args,
752 upvars,
753 movability,
754 fake_reads,
755 }))
756 }
757
758 hir::ExprKind::Path(ref qpath) => {
759 let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
760 self.convert_path_expr(expr, res)
761 }
762
763 hir::ExprKind::InlineAsm(asm) => ExprKind::InlineAsm(Box::new(InlineAsmExpr {
764 asm_macro: asm.asm_macro,
765 template: asm.template,
766 operands: asm
767 .operands
768 .iter()
769 .map(|(op, _op_sp)| match *op {
770 hir::InlineAsmOperand::In { reg, expr } => {
771 InlineAsmOperand::In { reg, expr: self.mirror_expr(expr) }
772 }
773 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
774 InlineAsmOperand::Out {
775 reg,
776 late,
777 expr: expr.map(|expr| self.mirror_expr(expr)),
778 }
779 }
780 hir::InlineAsmOperand::InOut { reg, late, expr } => {
781 InlineAsmOperand::InOut { reg, late, expr: self.mirror_expr(expr) }
782 }
783 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, ref out_expr } => {
784 InlineAsmOperand::SplitInOut {
785 reg,
786 late,
787 in_expr: self.mirror_expr(in_expr),
788 out_expr: out_expr.map(|expr| self.mirror_expr(expr)),
789 }
790 }
791 hir::InlineAsmOperand::Const { ref anon_const } => {
792 let ty = self.typeck_results.node_type(anon_const.hir_id);
793 let did = anon_const.def_id.to_def_id();
794 let typeck_root_def_id = tcx.typeck_root_def_id(did);
795 let parent_args = tcx.erase_regions(GenericArgs::identity_for_item(
796 tcx,
797 typeck_root_def_id,
798 ));
799 let args =
800 InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty })
801 .args;
802
803 let uneval = mir::UnevaluatedConst::new(did, args);
804 let value = mir::Const::Unevaluated(uneval, ty);
805 InlineAsmOperand::Const { value, span: tcx.def_span(did) }
806 }
807 hir::InlineAsmOperand::SymFn { expr } => {
808 InlineAsmOperand::SymFn { value: self.mirror_expr(expr) }
809 }
810 hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
811 InlineAsmOperand::SymStatic { def_id }
812 }
813 hir::InlineAsmOperand::Label { block } => {
814 InlineAsmOperand::Label { block: self.mirror_block(block) }
815 }
816 })
817 .collect(),
818 options: asm.options,
819 line_spans: asm.line_spans,
820 })),
821
822 hir::ExprKind::OffsetOf(_, _) => {
823 let data = self.typeck_results.offset_of_data();
824 let &(container, ref indices) = data.get(expr.hir_id).unwrap();
825 let fields = tcx.mk_offset_of_from_iter(indices.iter().copied());
826
827 ExprKind::OffsetOf { container, fields }
828 }
829
830 hir::ExprKind::ConstBlock(ref anon_const) => {
831 let ty = self.typeck_results.node_type(anon_const.hir_id);
832 let did = anon_const.def_id.to_def_id();
833 let typeck_root_def_id = tcx.typeck_root_def_id(did);
834 let parent_args =
835 tcx.erase_regions(GenericArgs::identity_for_item(tcx, typeck_root_def_id));
836 let args = InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty }).args;
837
838 ExprKind::ConstBlock { did, args }
839 }
840 hir::ExprKind::Repeat(v, _) => {
842 let ty = self.typeck_results.expr_ty(expr);
843 let ty::Array(_, count) = ty.kind() else {
844 span_bug!(expr.span, "unexpected repeat expr ty: {:?}", ty);
845 };
846
847 ExprKind::Repeat { value: self.mirror_expr(v), count: *count }
848 }
849 hir::ExprKind::Ret(v) => ExprKind::Return { value: v.map(|v| self.mirror_expr(v)) },
850 hir::ExprKind::Become(call) => ExprKind::Become { value: self.mirror_expr(call) },
851 hir::ExprKind::Break(dest, ref value) => {
852 if find_attr!(self.tcx.hir_attrs(expr.hir_id), AttributeKind::ConstContinue(_)) {
853 match dest.target_id {
854 Ok(target_id) => {
855 let (Some(value), Some(_)) = (value, dest.label) else {
856 let span = expr.span;
857 self.tcx.dcx().emit_fatal(ConstContinueMissingLabelOrValue { span })
858 };
859
860 ExprKind::ConstContinue {
861 label: region::Scope {
862 local_id: target_id.local_id,
863 data: region::ScopeData::Node,
864 },
865 value: self.mirror_expr(value),
866 }
867 }
868 Err(err) => bug!("invalid loop id for break: {}", err),
869 }
870 } else {
871 match dest.target_id {
872 Ok(target_id) => ExprKind::Break {
873 label: region::Scope {
874 local_id: target_id.local_id,
875 data: region::ScopeData::Node,
876 },
877 value: value.map(|value| self.mirror_expr(value)),
878 },
879 Err(err) => bug!("invalid loop id for break: {}", err),
880 }
881 }
882 }
883 hir::ExprKind::Continue(dest) => match dest.target_id {
884 Ok(loop_id) => ExprKind::Continue {
885 label: region::Scope {
886 local_id: loop_id.local_id,
887 data: region::ScopeData::Node,
888 },
889 },
890 Err(err) => bug!("invalid loop id for continue: {}", err),
891 },
892 hir::ExprKind::Let(let_expr) => ExprKind::Let {
893 expr: self.mirror_expr(let_expr.init),
894 pat: self.pattern_from_hir(let_expr.pat),
895 },
896 hir::ExprKind::If(cond, then, else_opt) => ExprKind::If {
897 if_then_scope: region::Scope {
898 local_id: then.hir_id.local_id,
899 data: {
900 if expr.span.at_least_rust_2024() {
901 region::ScopeData::IfThenRescope
902 } else {
903 region::ScopeData::IfThen
904 }
905 },
906 },
907 cond: self.mirror_expr(cond),
908 then: self.mirror_expr(then),
909 else_opt: else_opt.map(|el| self.mirror_expr(el)),
910 },
911 hir::ExprKind::Match(discr, arms, match_source) => ExprKind::Match {
912 scrutinee: self.mirror_expr(discr),
913 arms: arms.iter().map(|a| self.convert_arm(a)).collect(),
914 match_source,
915 },
916 hir::ExprKind::Loop(body, ..) => {
917 if find_attr!(self.tcx.hir_attrs(expr.hir_id), AttributeKind::LoopMatch(_)) {
918 let dcx = self.tcx.dcx();
919
920 let loop_body_expr = match body.stmts {
922 [] => match body.expr {
923 Some(expr) => expr,
924 None => dcx.emit_fatal(LoopMatchMissingAssignment { span: body.span }),
925 },
926 [single] if body.expr.is_none() => match single.kind {
927 hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr) => expr,
928 _ => dcx.emit_fatal(LoopMatchMissingAssignment { span: body.span }),
929 },
930 [first @ last] | [first, .., last] => dcx
931 .emit_fatal(LoopMatchBadStatements { span: first.span.to(last.span) }),
932 };
933
934 let hir::ExprKind::Assign(state, rhs_expr, _) = loop_body_expr.kind else {
935 dcx.emit_fatal(LoopMatchMissingAssignment { span: loop_body_expr.span })
936 };
937
938 let hir::ExprKind::Block(block_body, _) = rhs_expr.kind else {
939 dcx.emit_fatal(LoopMatchBadRhs { span: rhs_expr.span })
940 };
941
942 for stmt in block_body.stmts {
945 if !matches!(stmt.kind, rustc_hir::StmtKind::Item(_)) {
946 dcx.emit_fatal(LoopMatchBadStatements { span: stmt.span })
947 }
948 }
949
950 let Some(block_body_expr) = block_body.expr else {
951 dcx.emit_fatal(LoopMatchBadRhs { span: block_body.span })
952 };
953
954 let hir::ExprKind::Match(scrutinee, arms, _match_source) = block_body_expr.kind
955 else {
956 dcx.emit_fatal(LoopMatchBadRhs { span: block_body_expr.span })
957 };
958
959 fn local(
960 cx: &mut ThirBuildCx<'_>,
961 expr: &rustc_hir::Expr<'_>,
962 ) -> Option<hir::HirId> {
963 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind
964 && let Res::Local(hir_id) = path.res
965 && !cx.is_upvar(hir_id)
966 {
967 return Some(hir_id);
968 }
969
970 None
971 }
972
973 let Some(scrutinee_hir_id) = local(self, scrutinee) else {
974 dcx.emit_fatal(LoopMatchInvalidMatch { span: scrutinee.span })
975 };
976
977 if local(self, state) != Some(scrutinee_hir_id) {
978 dcx.emit_fatal(LoopMatchInvalidUpdate {
979 scrutinee: scrutinee.span,
980 lhs: state.span,
981 })
982 }
983
984 ExprKind::LoopMatch {
985 state: self.mirror_expr(state),
986 region_scope: region::Scope {
987 local_id: block_body.hir_id.local_id,
988 data: region::ScopeData::Node,
989 },
990
991 match_data: Box::new(LoopMatchMatchData {
992 scrutinee: self.mirror_expr(scrutinee),
993 arms: arms.iter().map(|a| self.convert_arm(a)).collect(),
994 span: block_body_expr.span,
995 }),
996 }
997 } else {
998 let block_ty = self.typeck_results.node_type(body.hir_id);
999 let (temp_lifetime, backwards_incompatible) = self
1000 .rvalue_scopes
1001 .temporary_scope(self.region_scope_tree, body.hir_id.local_id);
1002 let block = self.mirror_block(body);
1003 let body = self.thir.exprs.push(Expr {
1004 ty: block_ty,
1005 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1006 span: self.thir[block].span,
1007 kind: ExprKind::Block { block },
1008 });
1009 ExprKind::Loop { body }
1010 }
1011 }
1012 hir::ExprKind::Field(source, ..) => ExprKind::Field {
1013 lhs: self.mirror_expr(source),
1014 variant_index: FIRST_VARIANT,
1015 name: self.typeck_results.field_index(expr.hir_id),
1016 },
1017 hir::ExprKind::Cast(source, cast_ty) => {
1018 let user_provided_types = self.typeck_results.user_provided_types();
1020 let user_ty = user_provided_types.get(cast_ty.hir_id);
1021
1022 debug!(
1023 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
1024 expr, cast_ty.hir_id, user_ty,
1025 );
1026
1027 let cast = self.mirror_expr_cast(
1028 source,
1029 TempLifetime { temp_lifetime, backwards_incompatible },
1030 expr.span,
1031 );
1032
1033 if let Some(user_ty) = user_ty {
1034 let cast_expr = self.thir.exprs.push(Expr {
1037 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1038 ty: expr_ty,
1039 span: expr.span,
1040 kind: cast,
1041 });
1042 debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
1043
1044 ExprKind::ValueTypeAscription {
1045 source: cast_expr,
1046 user_ty: Some(Box::new(*user_ty)),
1047 user_ty_span: cast_ty.span,
1048 }
1049 } else {
1050 cast
1051 }
1052 }
1053 hir::ExprKind::Type(source, ty) => {
1054 let user_provided_types = self.typeck_results.user_provided_types();
1055 let user_ty = user_provided_types.get(ty.hir_id).copied().map(Box::new);
1056 debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
1057 let mirrored = self.mirror_expr(source);
1058 if source.is_syntactic_place_expr() {
1059 ExprKind::PlaceTypeAscription {
1060 source: mirrored,
1061 user_ty,
1062 user_ty_span: ty.span,
1063 }
1064 } else {
1065 ExprKind::ValueTypeAscription {
1066 source: mirrored,
1067 user_ty,
1068 user_ty_span: ty.span,
1069 }
1070 }
1071 }
1072
1073 hir::ExprKind::UnsafeBinderCast(UnsafeBinderCastKind::Unwrap, source, _ty) => {
1074 let mirrored = self.mirror_expr(source);
1076 if source.is_syntactic_place_expr() {
1077 ExprKind::PlaceUnwrapUnsafeBinder { source: mirrored }
1078 } else {
1079 ExprKind::ValueUnwrapUnsafeBinder { source: mirrored }
1080 }
1081 }
1082 hir::ExprKind::UnsafeBinderCast(UnsafeBinderCastKind::Wrap, source, _ty) => {
1083 let mirrored = self.mirror_expr(source);
1085 ExprKind::WrapUnsafeBinder { source: mirrored }
1086 }
1087
1088 hir::ExprKind::DropTemps(source) => ExprKind::Use { source: self.mirror_expr(source) },
1089 hir::ExprKind::Array(fields) => ExprKind::Array { fields: self.mirror_exprs(fields) },
1090 hir::ExprKind::Tup(fields) => ExprKind::Tuple { fields: self.mirror_exprs(fields) },
1091
1092 hir::ExprKind::Yield(v, _) => ExprKind::Yield { value: self.mirror_expr(v) },
1093 hir::ExprKind::Err(_) => unreachable!("cannot lower a `hir::ExprKind::Err` to THIR"),
1094 };
1095
1096 Expr {
1097 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1098 ty: expr_ty,
1099 span: expr.span,
1100 kind,
1101 }
1102 }
1103
1104 fn user_args_applied_to_res(
1105 &mut self,
1106 hir_id: hir::HirId,
1107 res: Res,
1108 ) -> Option<Box<ty::CanonicalUserType<'tcx>>> {
1109 debug!("user_args_applied_to_res: res={:?}", res);
1110 let user_provided_type = match res {
1111 Res::Def(DefKind::Fn, _)
1115 | Res::Def(DefKind::AssocFn, _)
1116 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
1117 | Res::Def(DefKind::Const, _)
1118 | Res::Def(DefKind::AssocConst, _) => {
1119 self.typeck_results.user_provided_types().get(hir_id).copied().map(Box::new)
1120 }
1121
1122 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => {
1127 self.user_args_applied_to_ty_of_hir_id(hir_id).map(Box::new)
1128 }
1129
1130 Res::SelfCtor(_) => self.user_args_applied_to_ty_of_hir_id(hir_id).map(Box::new),
1132
1133 _ => bug!("user_args_applied_to_res: unexpected res {:?} at {:?}", res, hir_id),
1134 };
1135 debug!("user_args_applied_to_res: user_provided_type={:?}", user_provided_type);
1136 user_provided_type
1137 }
1138
1139 fn method_callee(
1140 &mut self,
1141 expr: &hir::Expr<'_>,
1142 span: Span,
1143 overloaded_callee: Option<Ty<'tcx>>,
1144 ) -> Expr<'tcx> {
1145 let (temp_lifetime, backwards_incompatible) =
1146 self.rvalue_scopes.temporary_scope(self.region_scope_tree, expr.hir_id.local_id);
1147 let (ty, user_ty) = match overloaded_callee {
1148 Some(fn_def) => (fn_def, None),
1149 None => {
1150 let (kind, def_id) =
1151 self.typeck_results.type_dependent_def(expr.hir_id).unwrap_or_else(|| {
1152 span_bug!(expr.span, "no type-dependent def for method callee")
1153 });
1154 let user_ty = self.user_args_applied_to_res(expr.hir_id, Res::Def(kind, def_id));
1155 debug!("method_callee: user_ty={:?}", user_ty);
1156 (
1157 Ty::new_fn_def(self.tcx, def_id, self.typeck_results.node_args(expr.hir_id)),
1158 user_ty,
1159 )
1160 }
1161 };
1162 Expr {
1163 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1164 ty,
1165 span,
1166 kind: ExprKind::ZstLiteral { user_ty },
1167 }
1168 }
1169
1170 fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId {
1171 let arm = Arm {
1172 pattern: self.pattern_from_hir(&arm.pat),
1173 guard: arm.guard.as_ref().map(|g| self.mirror_expr(g)),
1174 body: self.mirror_expr(arm.body),
1175 lint_level: LintLevel::Explicit(arm.hir_id),
1176 scope: region::Scope { local_id: arm.hir_id.local_id, data: region::ScopeData::Node },
1177 span: arm.span,
1178 };
1179 self.thir.arms.push(arm)
1180 }
1181
1182 fn convert_path_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, res: Res) -> ExprKind<'tcx> {
1183 let args = self.typeck_results.node_args(expr.hir_id);
1184 match res {
1185 Res::Def(DefKind::Fn, _)
1187 | Res::Def(DefKind::AssocFn, _)
1188 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
1189 | Res::SelfCtor(_) => {
1190 let user_ty = self.user_args_applied_to_res(expr.hir_id, res);
1191 ExprKind::ZstLiteral { user_ty }
1192 }
1193
1194 Res::Def(DefKind::ConstParam, def_id) => {
1195 let hir_id = self.tcx.local_def_id_to_hir_id(def_id.expect_local());
1196 let generics = self.tcx.generics_of(hir_id.owner);
1197 let Some(&index) = generics.param_def_id_to_index.get(&def_id) else {
1198 span_bug!(
1199 expr.span,
1200 "Should have already errored about late bound consts: {def_id:?}"
1201 );
1202 };
1203 let name = self.tcx.hir_name(hir_id);
1204 let param = ty::ParamConst::new(index, name);
1205
1206 ExprKind::ConstParam { param, def_id }
1207 }
1208
1209 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
1210 let user_ty = self.user_args_applied_to_res(expr.hir_id, res);
1211 ExprKind::NamedConst { def_id, args, user_ty }
1212 }
1213
1214 Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {
1215 let user_provided_types = self.typeck_results.user_provided_types();
1216 let user_ty = user_provided_types.get(expr.hir_id).copied().map(Box::new);
1217 debug!("convert_path_expr: user_ty={:?}", user_ty);
1218 let ty = self.typeck_results.node_type(expr.hir_id);
1219 match ty.kind() {
1220 ty::Adt(adt_def, args) => ExprKind::Adt(Box::new(AdtExpr {
1223 adt_def: *adt_def,
1224 variant_index: adt_def.variant_index_with_ctor_id(def_id),
1225 args,
1226 user_ty,
1227 fields: Box::new([]),
1228 base: AdtExprBase::None,
1229 })),
1230 _ => bug!("unexpected ty: {:?}", ty),
1231 }
1232 }
1233
1234 Res::Def(DefKind::Static { .. }, id) => {
1238 let ty = self.tcx.static_ptr_ty(id, self.typing_env);
1240 let (temp_lifetime, backwards_incompatible) = self
1241 .rvalue_scopes
1242 .temporary_scope(self.region_scope_tree, expr.hir_id.local_id);
1243 let kind = if self.tcx.is_thread_local_static(id) {
1244 ExprKind::ThreadLocalRef(id)
1245 } else {
1246 let alloc_id = self.tcx.reserve_and_set_static_alloc(id);
1247 ExprKind::StaticRef { alloc_id, ty, def_id: id }
1248 };
1249 ExprKind::Deref {
1250 arg: self.thir.exprs.push(Expr {
1251 ty,
1252 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1253 span: expr.span,
1254 kind,
1255 }),
1256 }
1257 }
1258
1259 Res::Local(var_hir_id) => self.convert_var(var_hir_id),
1260
1261 _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res),
1262 }
1263 }
1264
1265 fn convert_var(&mut self, var_hir_id: hir::HirId) -> ExprKind<'tcx> {
1266 let is_upvar = self.is_upvar(var_hir_id);
1269
1270 debug!(
1271 "convert_var({:?}): is_upvar={}, body_owner={:?}",
1272 var_hir_id, is_upvar, self.body_owner
1273 );
1274
1275 if is_upvar {
1276 ExprKind::UpvarRef {
1277 closure_def_id: self.body_owner,
1278 var_hir_id: LocalVarId(var_hir_id),
1279 }
1280 } else {
1281 ExprKind::VarRef { id: LocalVarId(var_hir_id) }
1282 }
1283 }
1284
1285 fn overloaded_operator(
1286 &mut self,
1287 expr: &'tcx hir::Expr<'tcx>,
1288 args: Box<[ExprId]>,
1289 ) -> ExprKind<'tcx> {
1290 let fun = self.method_callee(expr, expr.span, None);
1291 let fun = self.thir.exprs.push(fun);
1292 ExprKind::Call {
1293 ty: self.thir[fun].ty,
1294 fun,
1295 args,
1296 from_hir_call: false,
1297 fn_span: expr.span,
1298 }
1299 }
1300
1301 fn overloaded_place(
1302 &mut self,
1303 expr: &'tcx hir::Expr<'tcx>,
1304 place_ty: Ty<'tcx>,
1305 overloaded_callee: Option<Ty<'tcx>>,
1306 args: Box<[ExprId]>,
1307 span: Span,
1308 ) -> ExprKind<'tcx> {
1309 let ty::Ref(region, _, mutbl) = *self.thir[args[0]].ty.kind() else {
1317 span_bug!(span, "overloaded_place: receiver is not a reference");
1318 };
1319 let ref_ty = Ty::new_ref(self.tcx, region, place_ty, mutbl);
1320
1321 let (temp_lifetime, backwards_incompatible) =
1324 self.rvalue_scopes.temporary_scope(self.region_scope_tree, expr.hir_id.local_id);
1325 let fun = self.method_callee(expr, span, overloaded_callee);
1326 let fun = self.thir.exprs.push(fun);
1327 let fun_ty = self.thir[fun].ty;
1328 let ref_expr = self.thir.exprs.push(Expr {
1329 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1330 ty: ref_ty,
1331 span,
1332 kind: ExprKind::Call { ty: fun_ty, fun, args, from_hir_call: false, fn_span: span },
1333 });
1334
1335 ExprKind::Deref { arg: ref_expr }
1337 }
1338
1339 fn convert_captured_hir_place(
1340 &mut self,
1341 closure_expr: &'tcx hir::Expr<'tcx>,
1342 place: HirPlace<'tcx>,
1343 ) -> Expr<'tcx> {
1344 let (temp_lifetime, backwards_incompatible) = self
1345 .rvalue_scopes
1346 .temporary_scope(self.region_scope_tree, closure_expr.hir_id.local_id);
1347 let var_ty = place.base_ty;
1348
1349 let var_hir_id = match place.base {
1355 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1356 base => bug!("Expected an upvar, found {:?}", base),
1357 };
1358
1359 let mut captured_place_expr = Expr {
1360 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1361 ty: var_ty,
1362 span: closure_expr.span,
1363 kind: self.convert_var(var_hir_id),
1364 };
1365
1366 for proj in place.projections.iter() {
1367 let kind = match proj.kind {
1368 HirProjectionKind::Deref => {
1369 ExprKind::Deref { arg: self.thir.exprs.push(captured_place_expr) }
1370 }
1371 HirProjectionKind::Field(field, variant_index) => ExprKind::Field {
1372 lhs: self.thir.exprs.push(captured_place_expr),
1373 variant_index,
1374 name: field,
1375 },
1376 HirProjectionKind::OpaqueCast => {
1377 ExprKind::Use { source: self.thir.exprs.push(captured_place_expr) }
1378 }
1379 HirProjectionKind::UnwrapUnsafeBinder => ExprKind::PlaceUnwrapUnsafeBinder {
1380 source: self.thir.exprs.push(captured_place_expr),
1381 },
1382 HirProjectionKind::Index | HirProjectionKind::Subslice => {
1383 continue;
1385 }
1386 };
1387
1388 captured_place_expr = Expr {
1389 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1390 ty: proj.ty,
1391 span: closure_expr.span,
1392 kind,
1393 };
1394 }
1395
1396 captured_place_expr
1397 }
1398
1399 fn capture_upvar(
1400 &mut self,
1401 closure_expr: &'tcx hir::Expr<'tcx>,
1402 captured_place: &'tcx ty::CapturedPlace<'tcx>,
1403 upvar_ty: Ty<'tcx>,
1404 ) -> Expr<'tcx> {
1405 let upvar_capture = captured_place.info.capture_kind;
1406 let captured_place_expr =
1407 self.convert_captured_hir_place(closure_expr, captured_place.place.clone());
1408 let (temp_lifetime, backwards_incompatible) = self
1409 .rvalue_scopes
1410 .temporary_scope(self.region_scope_tree, closure_expr.hir_id.local_id);
1411
1412 match upvar_capture {
1413 ty::UpvarCapture::ByValue => captured_place_expr,
1414 ty::UpvarCapture::ByUse => {
1415 let span = captured_place_expr.span;
1416 let expr_id = self.thir.exprs.push(captured_place_expr);
1417
1418 Expr {
1419 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1420 ty: upvar_ty,
1421 span: closure_expr.span,
1422 kind: ExprKind::ByUse { expr: expr_id, span },
1423 }
1424 }
1425 ty::UpvarCapture::ByRef(upvar_borrow) => {
1426 let borrow_kind = match upvar_borrow {
1427 ty::BorrowKind::Immutable => BorrowKind::Shared,
1428 ty::BorrowKind::UniqueImmutable => {
1429 BorrowKind::Mut { kind: mir::MutBorrowKind::ClosureCapture }
1430 }
1431 ty::BorrowKind::Mutable => {
1432 BorrowKind::Mut { kind: mir::MutBorrowKind::Default }
1433 }
1434 };
1435 Expr {
1436 temp_lifetime: TempLifetime { temp_lifetime, backwards_incompatible },
1437 ty: upvar_ty,
1438 span: closure_expr.span,
1439 kind: ExprKind::Borrow {
1440 borrow_kind,
1441 arg: self.thir.exprs.push(captured_place_expr),
1442 },
1443 }
1444 }
1445 }
1446 }
1447
1448 fn is_upvar(&mut self, var_hir_id: hir::HirId) -> bool {
1449 self.tcx
1450 .upvars_mentioned(self.body_owner)
1451 .is_some_and(|upvars| upvars.contains_key(&var_hir_id))
1452 }
1453
1454 fn field_refs(&mut self, fields: &'tcx [hir::ExprField<'tcx>]) -> Box<[FieldExpr]> {
1456 fields
1457 .iter()
1458 .map(|field| FieldExpr {
1459 name: self.typeck_results.field_index(field.hir_id),
1460 expr: self.mirror_expr(field.expr),
1461 })
1462 .collect()
1463 }
1464}
1465
1466trait ToBorrowKind {
1467 fn to_borrow_kind(&self) -> BorrowKind;
1468}
1469
1470impl ToBorrowKind for AutoBorrowMutability {
1471 fn to_borrow_kind(&self) -> BorrowKind {
1472 use rustc_middle::ty::adjustment::AllowTwoPhase;
1473 match *self {
1474 AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut {
1475 kind: match allow_two_phase_borrow {
1476 AllowTwoPhase::Yes => mir::MutBorrowKind::TwoPhaseBorrow,
1477 AllowTwoPhase::No => mir::MutBorrowKind::Default,
1478 },
1479 },
1480 AutoBorrowMutability::Not => BorrowKind::Shared,
1481 }
1482 }
1483}
1484
1485impl ToBorrowKind for hir::Mutability {
1486 fn to_borrow_kind(&self) -> BorrowKind {
1487 match *self {
1488 hir::Mutability::Mut => BorrowKind::Mut { kind: mir::MutBorrowKind::Default },
1489 hir::Mutability::Not => BorrowKind::Shared,
1490 }
1491 }
1492}
1493
1494fn bin_op(op: hir::BinOpKind) -> BinOp {
1495 match op {
1496 hir::BinOpKind::Add => BinOp::Add,
1497 hir::BinOpKind::Sub => BinOp::Sub,
1498 hir::BinOpKind::Mul => BinOp::Mul,
1499 hir::BinOpKind::Div => BinOp::Div,
1500 hir::BinOpKind::Rem => BinOp::Rem,
1501 hir::BinOpKind::BitXor => BinOp::BitXor,
1502 hir::BinOpKind::BitAnd => BinOp::BitAnd,
1503 hir::BinOpKind::BitOr => BinOp::BitOr,
1504 hir::BinOpKind::Shl => BinOp::Shl,
1505 hir::BinOpKind::Shr => BinOp::Shr,
1506 hir::BinOpKind::Eq => BinOp::Eq,
1507 hir::BinOpKind::Lt => BinOp::Lt,
1508 hir::BinOpKind::Le => BinOp::Le,
1509 hir::BinOpKind::Ne => BinOp::Ne,
1510 hir::BinOpKind::Ge => BinOp::Ge,
1511 hir::BinOpKind::Gt => BinOp::Gt,
1512 _ => bug!("no equivalent for ast binop {:?}", op),
1513 }
1514}
1515
1516fn assign_op(op: hir::AssignOpKind) -> AssignOp {
1517 match op {
1518 hir::AssignOpKind::AddAssign => AssignOp::AddAssign,
1519 hir::AssignOpKind::SubAssign => AssignOp::SubAssign,
1520 hir::AssignOpKind::MulAssign => AssignOp::MulAssign,
1521 hir::AssignOpKind::DivAssign => AssignOp::DivAssign,
1522 hir::AssignOpKind::RemAssign => AssignOp::RemAssign,
1523 hir::AssignOpKind::BitXorAssign => AssignOp::BitXorAssign,
1524 hir::AssignOpKind::BitAndAssign => AssignOp::BitAndAssign,
1525 hir::AssignOpKind::BitOrAssign => AssignOp::BitOrAssign,
1526 hir::AssignOpKind::ShlAssign => AssignOp::ShlAssign,
1527 hir::AssignOpKind::ShrAssign => AssignOp::ShrAssign,
1528 }
1529}