1 use super::ResolverAstLoweringExt;
2 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
3 use crate::{FnDeclKind, ImplTraitPosition};
6 use rustc_ast::ptr::P as AstP;
8 use rustc_data_structures::stack::ensure_sufficient_stack;
9 use rustc_data_structures::thin_vec::ThinVec;
10 use rustc_errors::struct_span_err;
12 use rustc_hir::def::Res;
13 use rustc_hir::definitions::DefPathData;
14 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
15 use rustc_span::symbol::{sym, Ident};
16 use rustc_span::DUMMY_SP;
18 impl<'hir> LoweringContext<'_, 'hir> {
19 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
20 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
23 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
24 self.arena.alloc(self.lower_expr_mut(e))
27 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
28 ensure_sufficient_stack(|| {
29 let kind = match e.kind {
30 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
31 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
32 ExprKind::ConstBlock(ref anon_const) => {
33 let anon_const = self.lower_anon_const(anon_const);
34 hir::ExprKind::ConstBlock(anon_const)
36 ExprKind::Repeat(ref expr, ref count) => {
37 let expr = self.lower_expr(expr);
38 let count = self.lower_array_length(count);
39 hir::ExprKind::Repeat(expr, count)
41 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
42 ExprKind::Call(ref f, ref args) => {
43 if e.attrs.get(0).map_or(false, |a| a.has_name(sym::rustc_box)) {
44 if let [inner] = &args[..] && e.attrs.len() == 1 {
45 let kind = hir::ExprKind::Box(self.lower_expr(&inner));
46 let hir_id = self.lower_node_id(e.id);
47 return hir::Expr { hir_id, kind, span: self.lower_span(e.span) };
52 "#[rustc_box] requires precisely one argument \
53 and no other attributes are allowed",
58 } else if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
59 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
61 let f = self.lower_expr(f);
62 hir::ExprKind::Call(f, self.lower_exprs(args))
65 ExprKind::MethodCall(ref seg, ref args, span) => {
66 let hir_seg = self.arena.alloc(self.lower_path_segment(
70 ParenthesizedGenericArgs::Err,
71 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
73 let args = self.lower_exprs(args);
74 hir::ExprKind::MethodCall(hir_seg, args, self.lower_span(span))
76 ExprKind::Binary(binop, ref lhs, ref rhs) => {
77 let binop = self.lower_binop(binop);
78 let lhs = self.lower_expr(lhs);
79 let rhs = self.lower_expr(rhs);
80 hir::ExprKind::Binary(binop, lhs, rhs)
82 ExprKind::Unary(op, ref ohs) => {
83 let op = self.lower_unop(op);
84 let ohs = self.lower_expr(ohs);
85 hir::ExprKind::Unary(op, ohs)
87 ExprKind::Lit(ref l) => {
88 hir::ExprKind::Lit(respan(self.lower_span(l.span), l.kind.clone()))
90 ExprKind::Cast(ref expr, ref ty) => {
91 let expr = self.lower_expr(expr);
93 self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
94 hir::ExprKind::Cast(expr, ty)
96 ExprKind::Type(ref expr, ref ty) => {
97 let expr = self.lower_expr(expr);
99 self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
100 hir::ExprKind::Type(expr, ty)
102 ExprKind::AddrOf(k, m, ref ohs) => {
103 let ohs = self.lower_expr(ohs);
104 hir::ExprKind::AddrOf(k, m, ohs)
106 ExprKind::Let(ref pat, ref scrutinee, span) => {
107 hir::ExprKind::Let(self.arena.alloc(hir::Let {
108 hir_id: self.next_id(),
109 span: self.lower_span(span),
110 pat: self.lower_pat(pat),
112 init: self.lower_expr(scrutinee),
115 ExprKind::If(ref cond, ref then, ref else_opt) => {
116 self.lower_expr_if(cond, then, else_opt.as_deref())
118 ExprKind::While(ref cond, ref body, opt_label) => {
119 self.with_loop_scope(e.id, |this| {
121 this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
122 this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
125 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
127 this.lower_block(body, false),
128 this.lower_label(opt_label),
129 hir::LoopSource::Loop,
133 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
134 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
135 self.lower_expr(expr),
136 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
137 hir::MatchSource::Normal,
139 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
145 hir::AsyncGeneratorKind::Block,
146 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
148 ExprKind::Await(ref expr) => {
149 let span = if expr.span.hi() < e.span.hi() {
150 expr.span.shrink_to_hi().with_hi(e.span.hi())
152 // this is a recovered `await expr`
155 self.lower_expr_await(span, expr)
165 if let Async::Yes { closure_id, .. } = asyncness {
166 self.lower_expr_async_closure(
175 self.lower_expr_closure(
185 ExprKind::Block(ref blk, opt_label) => {
186 let opt_label = self.lower_label(opt_label);
187 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
189 ExprKind::Assign(ref el, ref er, span) => {
190 self.lower_expr_assign(el, er, span, e.span)
192 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
193 self.lower_binop(op),
197 ExprKind::Field(ref el, ident) => {
198 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
200 ExprKind::Index(ref el, ref er) => {
201 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
203 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
204 self.lower_expr_range_closed(e.span, e1, e2)
206 ExprKind::Range(ref e1, ref e2, lims) => {
207 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
209 ExprKind::Underscore => {
213 "in expressions, `_` can only be used on the left-hand side of an assignment",
215 .span_label(e.span, "`_` not allowed here")
219 ExprKind::Path(ref qself, ref path) => {
220 let qpath = self.lower_qpath(
225 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
227 hir::ExprKind::Path(qpath)
229 ExprKind::Break(opt_label, ref opt_expr) => {
230 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
231 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
233 ExprKind::Continue(opt_label) => {
234 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
236 ExprKind::Ret(ref e) => {
237 let e = e.as_ref().map(|x| self.lower_expr(x));
238 hir::ExprKind::Ret(e)
240 ExprKind::Yeet(ref sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
241 ExprKind::InlineAsm(ref asm) => {
242 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
244 ExprKind::Struct(ref se) => {
245 let rest = match &se.rest {
246 StructRest::Base(e) => Some(self.lower_expr(e)),
247 StructRest::Rest(sp) => {
249 .struct_span_err(*sp, "base expression required after `..`")
250 .span_label(*sp, "add a base expression here")
252 Some(&*self.arena.alloc(self.expr_err(*sp)))
254 StructRest::None => None,
256 hir::ExprKind::Struct(
257 self.arena.alloc(self.lower_qpath(
262 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
265 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
269 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
270 ExprKind::Err => hir::ExprKind::Err,
271 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
272 ExprKind::Paren(ref ex) => {
273 let mut ex = self.lower_expr_mut(ex);
274 // Include parens in span, but only if it is a super-span.
275 if e.span.contains(ex.span) {
276 ex.span = self.lower_span(e.span);
278 // Merge attributes into the inner expression.
279 if !e.attrs.is_empty() {
281 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
284 &*self.arena.alloc_from_iter(
287 .map(|a| self.lower_attr(a))
288 .chain(old_attrs.iter().cloned()),
295 // Desugar `ExprForLoop`
296 // from: `[opt_ident]: for <pat> in <head> <body>`
297 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
298 return self.lower_expr_for(e, pat, head, body, opt_label);
300 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
303 let hir_id = self.lower_node_id(e.id);
304 self.lower_attrs(hir_id, &e.attrs);
305 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
309 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
311 UnOp::Deref => hir::UnOp::Deref,
312 UnOp::Not => hir::UnOp::Not,
313 UnOp::Neg => hir::UnOp::Neg,
317 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
320 BinOpKind::Add => hir::BinOpKind::Add,
321 BinOpKind::Sub => hir::BinOpKind::Sub,
322 BinOpKind::Mul => hir::BinOpKind::Mul,
323 BinOpKind::Div => hir::BinOpKind::Div,
324 BinOpKind::Rem => hir::BinOpKind::Rem,
325 BinOpKind::And => hir::BinOpKind::And,
326 BinOpKind::Or => hir::BinOpKind::Or,
327 BinOpKind::BitXor => hir::BinOpKind::BitXor,
328 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
329 BinOpKind::BitOr => hir::BinOpKind::BitOr,
330 BinOpKind::Shl => hir::BinOpKind::Shl,
331 BinOpKind::Shr => hir::BinOpKind::Shr,
332 BinOpKind::Eq => hir::BinOpKind::Eq,
333 BinOpKind::Lt => hir::BinOpKind::Lt,
334 BinOpKind::Le => hir::BinOpKind::Le,
335 BinOpKind::Ne => hir::BinOpKind::Ne,
336 BinOpKind::Ge => hir::BinOpKind::Ge,
337 BinOpKind::Gt => hir::BinOpKind::Gt,
339 span: self.lower_span(b.span),
343 fn lower_legacy_const_generics(
346 args: Vec<AstP<Expr>>,
347 legacy_args_idx: &[usize],
348 ) -> hir::ExprKind<'hir> {
349 let ExprKind::Path(None, ref mut path) = f.kind else {
353 // Split the arguments into const generics and normal arguments
354 let mut real_args = vec![];
355 let mut generic_args = vec![];
356 for (idx, arg) in args.into_iter().enumerate() {
357 if legacy_args_idx.contains(&idx) {
358 let parent_def_id = self.current_hir_id_owner;
359 let node_id = self.next_node_id();
361 // Add a definition for the in-band const def.
362 self.create_def(parent_def_id, node_id, DefPathData::AnonConst);
364 let anon_const = AnonConst { id: node_id, value: arg };
365 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
371 // Add generic args to the last element of the path.
372 let last_segment = path.segments.last_mut().unwrap();
373 assert!(last_segment.args.is_none());
374 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
379 // Now lower everything as normal.
380 let f = self.lower_expr(&f);
381 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
388 else_opt: Option<&Expr>,
389 ) -> hir::ExprKind<'hir> {
390 let lowered_cond = self.lower_expr(cond);
391 let new_cond = self.manage_let_cond(lowered_cond);
392 let then_expr = self.lower_block_expr(then);
393 if let Some(rslt) = else_opt {
394 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), Some(self.lower_expr(rslt)))
396 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), None)
400 // If `cond` kind is `let`, returns `let`. Otherwise, wraps and returns `cond`
401 // in a temporary block.
402 fn manage_let_cond(&mut self, cond: &'hir hir::Expr<'hir>) -> &'hir hir::Expr<'hir> {
403 fn has_let_expr<'hir>(expr: &'hir hir::Expr<'hir>) -> bool {
405 hir::ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
406 hir::ExprKind::Let(..) => true,
410 if has_let_expr(cond) {
413 let reason = DesugaringKind::CondTemporary;
414 let span_block = self.mark_span_with_reason(reason, cond.span, None);
415 self.expr_drop_temps(span_block, cond, AttrVec::new())
419 // We desugar: `'label: while $cond $body` into:
423 // if { let _t = $cond; _t } {
432 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
433 // to preserve drop semantics since `while $cond { ... }` does not
434 // let temporaries live outside of `cond`.
435 fn lower_expr_while_in_loop_scope(
440 opt_label: Option<Label>,
441 ) -> hir::ExprKind<'hir> {
442 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
443 let new_cond = self.manage_let_cond(lowered_cond);
444 let then = self.lower_block_expr(body);
445 let expr_break = self.expr_break(span, ThinVec::new());
446 let stmt_break = self.stmt_expr(span, expr_break);
447 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
448 let else_expr = self.arena.alloc(self.expr_block(else_blk, ThinVec::new()));
449 let if_kind = hir::ExprKind::If(new_cond, self.arena.alloc(then), Some(else_expr));
450 let if_expr = self.expr(span, if_kind, ThinVec::new());
451 let block = self.block_expr(self.arena.alloc(if_expr));
452 let span = self.lower_span(span.with_hi(cond.span.hi()));
453 let opt_label = self.lower_label(opt_label);
454 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
457 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
458 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
459 /// and save the block id to use it as a break target for desugaring of the `?` operator.
460 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
461 self.with_catch_scope(body.id, |this| {
462 let mut block = this.lower_block_noalloc(body, true);
464 // Final expression of the block (if present) or `()` with span at the end of block
465 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
467 this.mark_span_with_reason(
468 DesugaringKind::TryBlock,
470 this.allow_try_trait.clone(),
475 let try_span = this.mark_span_with_reason(
476 DesugaringKind::TryBlock,
477 this.sess.source_map().end_point(body.span),
478 this.allow_try_trait.clone(),
481 (try_span, this.expr_unit(try_span))
484 let ok_wrapped_span =
485 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
487 // `::std::ops::Try::from_output($tail_expr)`
488 block.expr = Some(this.wrap_in_try_constructor(
489 hir::LangItem::TryTraitFromOutput,
495 hir::ExprKind::Block(this.arena.alloc(block), None)
499 fn wrap_in_try_constructor(
501 lang_item: hir::LangItem,
503 expr: &'hir hir::Expr<'hir>,
505 ) -> &'hir hir::Expr<'hir> {
506 let constructor = self.arena.alloc(self.expr_lang_item_path(
512 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
515 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
516 let pat = self.lower_pat(&arm.pat);
517 let guard = arm.guard.as_ref().map(|cond| {
518 if let ExprKind::Let(ref pat, ref scrutinee, span) = cond.kind {
519 hir::Guard::IfLet(self.arena.alloc(hir::Let {
520 hir_id: self.next_id(),
521 span: self.lower_span(span),
522 pat: self.lower_pat(pat),
524 init: self.lower_expr(scrutinee),
527 hir::Guard::If(self.lower_expr(cond))
530 let hir_id = self.next_id();
531 self.lower_attrs(hir_id, &arm.attrs);
536 body: self.lower_expr(&arm.body),
537 span: self.lower_span(arm.span),
541 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
546 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
550 pub(super) fn make_async_expr(
552 capture_clause: CaptureBy,
553 closure_node_id: NodeId,
554 ret_ty: Option<AstP<Ty>>,
556 async_gen_kind: hir::AsyncGeneratorKind,
557 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
558 ) -> hir::ExprKind<'hir> {
559 let output = match ret_ty {
560 Some(ty) => hir::FnRetTy::Return(
561 self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock)),
563 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
566 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
567 // fully constrained by `future::from_generator`.
568 let input_ty = hir::Ty {
569 hir_id: self.next_id(),
570 kind: hir::TyKind::Infer,
571 span: self.lower_span(span),
574 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
575 let fn_decl = self.arena.alloc(hir::FnDecl {
576 inputs: arena_vec![self; input_ty],
579 implicit_self: hir::ImplicitSelfKind::None,
582 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
583 let (pat, task_context_hid) = self.pat_ident_binding_mode(
585 Ident::with_dummy_span(sym::_task_context),
586 hir::BindingAnnotation::Mutable,
588 let param = hir::Param {
589 hir_id: self.next_id(),
591 ty_span: self.lower_span(span),
592 span: self.lower_span(span),
594 let params = arena_vec![self; param];
596 let body = self.lower_body(move |this| {
597 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
599 let old_ctx = this.task_context;
600 this.task_context = Some(task_context_hid);
601 let res = body(this);
602 this.task_context = old_ctx;
606 // `static |_task_context| -> <ret_ty> { body }`:
607 let generator_kind = hir::ExprKind::Closure {
609 bound_generic_params: &[],
612 fn_decl_span: self.lower_span(span),
613 movability: Some(hir::Movability::Static),
615 let generator = hir::Expr {
616 hir_id: self.lower_node_id(closure_node_id),
617 kind: generator_kind,
618 span: self.lower_span(span),
621 // `future::from_generator`:
623 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
624 let gen_future = self.expr_lang_item_path(
626 hir::LangItem::FromGenerator,
631 // `future::from_generator(generator)`:
632 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
635 /// Desugar `<expr>.await` into:
636 /// ```ignore (pseudo-rust)
637 /// match ::std::future::IntoFuture::into_future(<expr>) {
638 /// mut __awaitee => loop {
639 /// match unsafe { ::std::future::Future::poll(
640 /// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
641 /// ::std::future::get_context(task_context),
643 /// ::std::task::Poll::Ready(result) => break result,
644 /// ::std::task::Poll::Pending => {}
646 /// task_context = yield ();
650 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
651 let full_span = expr.span.to(dot_await_span);
652 match self.generator_kind {
653 Some(hir::GeneratorKind::Async(_)) => {}
654 Some(hir::GeneratorKind::Gen) | None => {
655 let mut err = struct_span_err!(
659 "`await` is only allowed inside `async` functions and blocks"
661 err.span_label(dot_await_span, "only allowed inside `async` functions and blocks");
662 if let Some(item_sp) = self.current_item {
663 err.span_label(item_sp, "this is not `async`");
668 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
669 let gen_future_span = self.mark_span_with_reason(
670 DesugaringKind::Await,
672 self.allow_gen_future.clone(),
674 let expr = self.lower_expr_mut(expr);
675 let expr_hir_id = expr.hir_id;
677 // Note that the name of this binding must not be changed to something else because
678 // debuggers and debugger extensions expect it to be called `__awaitee`. They use
679 // this name to identify what is being awaited by a suspended async functions.
680 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
681 let (awaitee_pat, awaitee_pat_hid) =
682 self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::Mutable);
684 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
687 // ::std::future::Future::poll(
688 // ::std::pin::Pin::new_unchecked(&mut __awaitee),
689 // ::std::future::get_context(task_context),
693 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
694 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
695 let task_context = if let Some(task_context_hid) = self.task_context {
696 self.expr_ident_mut(span, task_context_ident, task_context_hid)
698 // Use of `await` outside of an async context, we cannot use `task_context` here.
701 let new_unchecked = self.expr_call_lang_item_fn_mut(
703 hir::LangItem::PinNewUnchecked,
704 arena_vec![self; ref_mut_awaitee],
707 let get_context = self.expr_call_lang_item_fn_mut(
709 hir::LangItem::GetContext,
710 arena_vec![self; task_context],
713 let call = self.expr_call_lang_item_fn(
715 hir::LangItem::FuturePoll,
716 arena_vec![self; new_unchecked, get_context],
719 self.arena.alloc(self.expr_unsafe(call))
722 // `::std::task::Poll::Ready(result) => break result`
723 let loop_node_id = self.next_node_id();
724 let loop_hir_id = self.lower_node_id(loop_node_id);
726 let x_ident = Ident::with_dummy_span(sym::result);
727 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
728 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
729 let ready_field = self.single_pat_field(gen_future_span, x_pat);
730 let ready_pat = self.pat_lang_item_variant(
732 hir::LangItem::PollReady,
736 let break_x = self.with_loop_scope(loop_node_id, move |this| {
738 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
739 this.arena.alloc(this.expr(gen_future_span, expr_break, ThinVec::new()))
741 self.arm(ready_pat, break_x)
744 // `::std::task::Poll::Pending => {}`
746 let pending_pat = self.pat_lang_item_variant(
748 hir::LangItem::PollPending,
752 let empty_block = self.expr_block_empty(span);
753 self.arm(pending_pat, empty_block)
756 let inner_match_stmt = {
757 let match_expr = self.expr_match(
760 arena_vec![self; ready_arm, pending_arm],
761 hir::MatchSource::AwaitDesugar,
763 self.stmt_expr(span, match_expr)
766 // task_context = yield ();
768 let unit = self.expr_unit(span);
769 let yield_expr = self.expr(
771 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
774 let yield_expr = self.arena.alloc(yield_expr);
776 if let Some(task_context_hid) = self.task_context {
777 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
778 let assign = self.expr(
780 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
783 self.stmt_expr(span, assign)
785 // Use of `await` outside of an async context. Return `yield_expr` so that we can
786 // proceed with type checking.
787 self.stmt(span, hir::StmtKind::Semi(yield_expr))
791 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
794 let loop_expr = self.arena.alloc(hir::Expr {
796 kind: hir::ExprKind::Loop(
799 hir::LoopSource::Loop,
800 self.lower_span(span),
802 span: self.lower_span(span),
805 // mut __awaitee => loop { ... }
806 let awaitee_arm = self.arm(awaitee_pat, loop_expr);
808 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
809 let into_future_span = self.mark_span_with_reason(
810 DesugaringKind::Await,
812 self.allow_into_future.clone(),
814 let into_future_expr = self.expr_call_lang_item_fn(
816 hir::LangItem::IntoFutureIntoFuture,
817 arena_vec![self; expr],
821 // match <into_future_expr> {
822 // mut __awaitee => loop { .. }
824 hir::ExprKind::Match(
826 arena_vec![self; awaitee_arm],
827 hir::MatchSource::AwaitDesugar,
831 fn lower_expr_closure(
833 capture_clause: CaptureBy,
835 movability: Movability,
839 ) -> hir::ExprKind<'hir> {
840 let (body, generator_option) = self.with_new_scopes(move |this| {
841 let prev = this.current_item;
842 this.current_item = Some(fn_decl_span);
843 let mut generator_kind = None;
844 let body_id = this.lower_fn_body(decl, |this| {
845 let e = this.lower_expr_mut(body);
846 generator_kind = this.generator_kind;
849 let generator_option =
850 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
851 this.current_item = prev;
852 (body_id, generator_option)
855 self.with_lifetime_binder(closure_id, &[], |this, bound_generic_params| {
856 // Lower outside new scope to preserve `is_in_loop_condition`.
857 let fn_decl = this.lower_fn_decl(decl, None, FnDeclKind::Closure, None);
859 hir::ExprKind::Closure {
861 bound_generic_params,
864 fn_decl_span: this.lower_span(fn_decl_span),
865 movability: generator_option,
870 fn generator_movability_for_fn(
874 generator_kind: Option<hir::GeneratorKind>,
875 movability: Movability,
876 ) -> Option<hir::Movability> {
877 match generator_kind {
878 Some(hir::GeneratorKind::Gen) => {
879 if decl.inputs.len() > 1 {
884 "too many parameters for a generator (expected 0 or 1 parameters)"
890 Some(hir::GeneratorKind::Async(_)) => {
891 panic!("non-`async` closure body turned `async` during lowering");
894 if movability == Movability::Static {
895 struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
903 fn lower_expr_async_closure(
905 capture_clause: CaptureBy,
907 inner_closure_id: NodeId,
911 ) -> hir::ExprKind<'hir> {
913 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
915 let body = self.with_new_scopes(|this| {
916 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
917 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
922 "`async` non-`move` closures with parameters are not currently supported",
925 "consider using `let` statements to manually capture \
926 variables by reference before entering an `async move` closure",
931 // Transform `async |x: u8| -> X { ... }` into
932 // `|x: u8| future_from_generator(|| -> X { ... })`.
933 let body_id = this.lower_fn_body(&outer_decl, |this| {
935 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
936 let async_body = this.make_async_expr(
941 hir::AsyncGeneratorKind::Closure,
942 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
944 this.expr(fn_decl_span, async_body, ThinVec::new())
949 self.with_lifetime_binder(closure_id, &[], |this, bound_generic_params| {
950 // We need to lower the declaration outside the new scope, because we
951 // have to conserve the state of being inside a loop condition for the
952 // closure argument types.
953 let fn_decl = this.lower_fn_decl(&outer_decl, None, FnDeclKind::Closure, None);
955 hir::ExprKind::Closure {
957 bound_generic_params,
960 fn_decl_span: this.lower_span(fn_decl_span),
966 /// Destructure the LHS of complex assignments.
967 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
968 fn lower_expr_assign(
974 ) -> hir::ExprKind<'hir> {
975 // Return early in case of an ordinary assignment.
976 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
979 | ExprKind::Struct(..)
981 | ExprKind::Underscore => false,
982 // Check for tuple struct constructor.
983 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
984 ExprKind::Paren(e) => {
986 // We special-case `(..)` for consistency with patterns.
987 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
988 _ => is_ordinary(lower_ctx, e),
994 if is_ordinary(self, lhs) {
995 return hir::ExprKind::Assign(
996 self.lower_expr(lhs),
997 self.lower_expr(rhs),
998 self.lower_span(eq_sign_span),
1002 let mut assignments = vec![];
1004 // The LHS becomes a pattern: `(lhs1, lhs2)`.
1005 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1006 let rhs = self.lower_expr(rhs);
1008 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1009 let destructure_let = self.stmt_let_pat(
1014 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
1017 // `a = lhs1; b = lhs2;`.
1020 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1022 // Wrap everything in a block.
1023 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1026 /// If the given expression is a path to a tuple struct, returns that path.
1027 /// It is not a complete check, but just tries to reject most paths early
1028 /// if they are not tuple structs.
1029 /// Type checking will take care of the full validation later.
1030 fn extract_tuple_struct_path<'a>(
1033 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1034 if let ExprKind::Path(qself, path) = &expr.kind {
1035 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1036 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1037 if partial_res.unresolved_segments() == 0
1038 && !partial_res.base_res().expected_in_tuple_struct_pat()
1043 return Some((qself, path));
1048 /// If the given expression is a path to a unit struct, returns that path.
1049 /// It is not a complete check, but just tries to reject most paths early
1050 /// if they are not unit structs.
1051 /// Type checking will take care of the full validation later.
1052 fn extract_unit_struct_path<'a>(
1055 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1056 if let ExprKind::Path(qself, path) = &expr.kind {
1057 // Does the path resolve to something disallowed in a unit struct/variant pattern?
1058 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1059 if partial_res.unresolved_segments() == 0
1060 && !partial_res.base_res().expected_in_unit_struct_pat()
1065 return Some((qself, path));
1070 /// Convert the LHS of a destructuring assignment to a pattern.
1071 /// Each sub-assignment is recorded in `assignments`.
1072 fn destructure_assign(
1076 assignments: &mut Vec<hir::Stmt<'hir>>,
1077 ) -> &'hir hir::Pat<'hir> {
1078 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1081 fn destructure_assign_mut(
1085 assignments: &mut Vec<hir::Stmt<'hir>>,
1086 ) -> hir::Pat<'hir> {
1088 // Underscore pattern.
1089 ExprKind::Underscore => {
1090 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1093 ExprKind::Array(elements) => {
1095 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1096 let slice_pat = if let Some((i, span)) = rest {
1097 let (before, after) = pats.split_at(i);
1098 hir::PatKind::Slice(
1100 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1104 hir::PatKind::Slice(pats, None, &[])
1106 return self.pat_without_dbm(lhs.span, slice_pat);
1109 ExprKind::Call(callee, args) => {
1110 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1111 let (pats, rest) = self.destructure_sequence(
1113 "tuple struct or variant",
1117 let qpath = self.lower_qpath(
1121 ParamMode::Optional,
1122 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1124 // Destructure like a tuple struct.
1125 let tuple_struct_pat =
1126 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1127 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1130 // Unit structs and enum variants.
1131 ExprKind::Path(..) => {
1132 if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1133 let qpath = self.lower_qpath(
1137 ParamMode::Optional,
1138 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1140 // Destructure like a unit struct.
1141 let unit_struct_pat = hir::PatKind::Path(qpath);
1142 return self.pat_without_dbm(lhs.span, unit_struct_pat);
1146 ExprKind::Struct(se) => {
1147 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1148 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1150 hir_id: self.next_id(),
1151 ident: self.lower_ident(f.ident),
1153 is_shorthand: f.is_shorthand,
1154 span: self.lower_span(f.span),
1157 let qpath = self.lower_qpath(
1161 ParamMode::Optional,
1162 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1164 let fields_omitted = match &se.rest {
1165 StructRest::Base(e) => {
1169 "functional record updates are not allowed in destructuring \
1174 "consider removing the trailing pattern",
1176 rustc_errors::Applicability::MachineApplicable,
1181 StructRest::Rest(_) => true,
1182 StructRest::None => false,
1184 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1185 return self.pat_without_dbm(lhs.span, struct_pat);
1188 ExprKind::Tup(elements) => {
1190 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1191 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1192 return self.pat_without_dbm(lhs.span, tuple_pat);
1194 ExprKind::Paren(e) => {
1195 // We special-case `(..)` for consistency with patterns.
1196 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1197 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1198 return self.pat_without_dbm(lhs.span, tuple_pat);
1200 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1205 // Treat all other cases as normal lvalue.
1206 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1207 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1208 let ident = self.expr_ident(lhs.span, ident, binding);
1210 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1211 let expr = self.expr(lhs.span, assign, ThinVec::new());
1212 assignments.push(self.stmt_expr(lhs.span, expr));
1216 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1217 /// Such a sequence occurs in a tuple (struct)/slice.
1218 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1220 /// Each sub-assignment is recorded in `assignments`.
1221 fn destructure_sequence(
1223 elements: &[AstP<Expr>],
1226 assignments: &mut Vec<hir::Stmt<'hir>>,
1227 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1228 let mut rest = None;
1230 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1231 // Check for `..` pattern.
1232 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1233 if let Some((_, prev_span)) = rest {
1234 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1236 rest = Some((i, e.span));
1240 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1246 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1247 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1248 let e1 = self.lower_expr_mut(e1);
1249 let e2 = self.lower_expr_mut(e2);
1251 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1253 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1254 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1257 fn lower_expr_range(
1263 ) -> hir::ExprKind<'hir> {
1264 use rustc_ast::RangeLimits::*;
1266 let lang_item = match (e1, e2, lims) {
1267 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1268 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1269 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1270 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1271 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1272 (Some(..), Some(..), Closed) => unreachable!(),
1273 (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"),
1276 let fields = self.arena.alloc_from_iter(
1277 e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1279 let expr = self.lower_expr(&e);
1280 let ident = Ident::new(s, self.lower_span(e.span));
1281 self.expr_field(ident, expr, e.span)
1286 hir::ExprKind::Struct(
1287 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)),
1293 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1294 let label = opt_label?;
1295 Some(Label { ident: self.lower_ident(label.ident) })
1298 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1299 let target_id = match destination {
1301 if let Some(loop_id) = self.resolver.get_label_res(id) {
1302 Ok(self.lower_node_id(loop_id))
1304 Err(hir::LoopIdError::UnresolvedLabel)
1309 .map(|id| Ok(self.lower_node_id(id)))
1310 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1312 let label = self.lower_label(destination.map(|(_, label)| label));
1313 hir::Destination { label, target_id }
1316 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1317 if self.is_in_loop_condition && opt_label.is_none() {
1320 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1323 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1327 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1328 let old_scope = self.catch_scope.replace(catch_id);
1329 let result = f(self);
1330 self.catch_scope = old_scope;
1334 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1335 // We're no longer in the base loop's condition; we're in another loop.
1336 let was_in_loop_condition = self.is_in_loop_condition;
1337 self.is_in_loop_condition = false;
1339 let old_scope = self.loop_scope.replace(loop_id);
1340 let result = f(self);
1341 self.loop_scope = old_scope;
1343 self.is_in_loop_condition = was_in_loop_condition;
1348 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1349 let was_in_loop_condition = self.is_in_loop_condition;
1350 self.is_in_loop_condition = true;
1352 let result = f(self);
1354 self.is_in_loop_condition = was_in_loop_condition;
1359 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1361 hir_id: self.next_id(),
1362 ident: self.lower_ident(f.ident),
1363 expr: self.lower_expr(&f.expr),
1364 span: self.lower_span(f.span),
1365 is_shorthand: f.is_shorthand,
1369 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1370 match self.generator_kind {
1371 Some(hir::GeneratorKind::Gen) => {}
1372 Some(hir::GeneratorKind::Async(_)) => {
1377 "`async` generators are not yet supported"
1381 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1385 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1387 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1390 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1391 /// ```ignore (pseudo-rust)
1393 /// let result = match IntoIterator::into_iter(<head>) {
1395 /// [opt_ident]: loop {
1396 /// match Iterator::next(&mut iter) {
1398 /// Some(<pat>) => <body>,
1412 opt_label: Option<Label>,
1413 ) -> hir::Expr<'hir> {
1414 let head = self.lower_expr_mut(head);
1415 let pat = self.lower_pat(pat);
1417 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1418 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1419 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1424 self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span, ThinVec::new()));
1425 let pat = self.pat_none(for_span);
1426 self.arm(pat, break_expr)
1429 // Some(<pat>) => <body>,
1431 let some_pat = self.pat_some(pat_span, pat);
1432 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1433 let body_expr = self.arena.alloc(self.expr_block(body_block, ThinVec::new()));
1434 self.arm(some_pat, body_expr)
1438 let iter = Ident::with_dummy_span(sym::iter);
1439 let (iter_pat, iter_pat_nid) =
1440 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::Mutable);
1442 // `match Iterator::next(&mut iter) { ... }`
1444 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1445 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1446 let next_expr = self.expr_call_lang_item_fn(
1448 hir::LangItem::IteratorNext,
1449 arena_vec![self; ref_mut_iter],
1452 let arms = arena_vec![self; none_arm, some_arm];
1454 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1456 let match_stmt = self.stmt_expr(for_span, match_expr);
1458 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1460 // `[opt_ident]: loop { ... }`
1461 let kind = hir::ExprKind::Loop(
1463 self.lower_label(opt_label),
1464 hir::LoopSource::ForLoop,
1465 self.lower_span(for_span.with_hi(head.span.hi())),
1468 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1470 // `mut iter => { ... }`
1471 let iter_arm = self.arm(iter_pat, loop_expr);
1473 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1474 let into_iter_expr = {
1475 self.expr_call_lang_item_fn(
1477 hir::LangItem::IntoIterIntoIter,
1478 arena_vec![self; head],
1483 let match_expr = self.arena.alloc(self.expr_match(
1486 arena_vec![self; iter_arm],
1487 hir::MatchSource::ForLoopDesugar,
1490 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1492 // This is effectively `{ let _result = ...; _result }`.
1493 // The construct was introduced in #21984 and is necessary to make sure that
1494 // temporaries in the `head` expression are dropped and do not leak to the
1495 // surrounding scope of the `match` since the `match` is not a terminating scope.
1497 // Also, add the attributes to the outer returned expr node.
1498 self.expr_drop_temps_mut(for_span, match_expr, attrs.into())
1501 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1502 /// ```ignore (pseudo-rust)
1503 /// match Try::branch(<expr>) {
1504 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1505 /// ControlFlow::Break(residual) =>
1506 /// #[allow(unreachable_code)]
1507 /// // If there is an enclosing `try {...}`:
1508 /// break 'catch_target Try::from_residual(residual),
1510 /// return Try::from_residual(residual),
1513 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1514 let unstable_span = self.mark_span_with_reason(
1515 DesugaringKind::QuestionMark,
1517 self.allow_try_trait.clone(),
1519 let try_span = self.sess.source_map().end_point(span);
1520 let try_span = self.mark_span_with_reason(
1521 DesugaringKind::QuestionMark,
1523 self.allow_try_trait.clone(),
1526 // `Try::branch(<expr>)`
1529 let sub_expr = self.lower_expr_mut(sub_expr);
1531 self.expr_call_lang_item_fn(
1533 hir::LangItem::TryTraitBranch,
1534 arena_vec![self; sub_expr],
1539 // `#[allow(unreachable_code)]`
1541 // `allow(unreachable_code)`
1543 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1544 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1545 let uc_nested = attr::mk_nested_word_item(uc_ident);
1546 attr::mk_list_item(allow_ident, vec![uc_nested])
1548 attr::mk_attr_outer(allow)
1550 let attrs = vec![attr];
1552 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1553 let continue_arm = {
1554 let val_ident = Ident::with_dummy_span(sym::val);
1555 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1556 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1560 ThinVec::from(attrs.clone()),
1562 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1563 self.arm(continue_pat, val_expr)
1566 // `ControlFlow::Break(residual) =>
1567 // #[allow(unreachable_code)]
1568 // return Try::from_residual(residual),`
1570 let residual_ident = Ident::with_dummy_span(sym::residual);
1571 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1572 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1573 let from_residual_expr = self.wrap_in_try_constructor(
1574 hir::LangItem::TryTraitFromResidual,
1576 self.arena.alloc(residual_expr),
1579 let thin_attrs = ThinVec::from(attrs);
1580 let ret_expr = if let Some(catch_node) = self.catch_scope {
1581 let target_id = Ok(self.lower_node_id(catch_node));
1582 self.arena.alloc(self.expr(
1584 hir::ExprKind::Break(
1585 hir::Destination { label: None, target_id },
1586 Some(from_residual_expr),
1591 self.arena.alloc(self.expr(
1593 hir::ExprKind::Ret(Some(from_residual_expr)),
1598 let break_pat = self.pat_cf_break(try_span, residual_local);
1599 self.arm(break_pat, ret_expr)
1602 hir::ExprKind::Match(
1604 arena_vec![self; break_arm, continue_arm],
1605 hir::MatchSource::TryDesugar,
1609 /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into:
1611 /// // If there is an enclosing `try {...}`:
1612 /// break 'catch_target FromResidual::from_residual(Yeet(residual)),
1614 /// return FromResidual::from_residual(Yeet(residual)),
1616 /// But to simplify this, there's a `from_yeet` lang item function which
1617 /// handles the combined `FromResidual::from_residual(Yeet(residual))`.
1618 fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1619 // The expression (if present) or `()` otherwise.
1620 let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
1621 (sub_expr.span, self.lower_expr(sub_expr))
1623 (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
1626 let unstable_span = self.mark_span_with_reason(
1627 DesugaringKind::YeetExpr,
1629 self.allow_try_trait.clone(),
1632 let from_yeet_expr = self.wrap_in_try_constructor(
1633 hir::LangItem::TryTraitFromYeet,
1639 if let Some(catch_node) = self.catch_scope {
1640 let target_id = Ok(self.lower_node_id(catch_node));
1641 hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
1643 hir::ExprKind::Ret(Some(from_yeet_expr))
1647 // =========================================================================
1648 // Helper methods for building HIR.
1649 // =========================================================================
1651 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1653 /// In terms of drop order, it has the same effect as wrapping `expr` in
1654 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1656 /// The drop order can be important in e.g. `if expr { .. }`.
1657 pub(super) fn expr_drop_temps(
1660 expr: &'hir hir::Expr<'hir>,
1662 ) -> &'hir hir::Expr<'hir> {
1663 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1666 pub(super) fn expr_drop_temps_mut(
1669 expr: &'hir hir::Expr<'hir>,
1671 ) -> hir::Expr<'hir> {
1672 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1678 arg: &'hir hir::Expr<'hir>,
1679 arms: &'hir [hir::Arm<'hir>],
1680 source: hir::MatchSource,
1681 ) -> hir::Expr<'hir> {
1682 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1685 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1686 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1687 self.expr(span, expr_break, attrs)
1690 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1691 let expr_break = self.expr_break(span, attrs);
1692 self.arena.alloc(expr_break)
1695 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1698 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1703 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1704 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1710 e: &'hir hir::Expr<'hir>,
1711 args: &'hir [hir::Expr<'hir>],
1712 ) -> hir::Expr<'hir> {
1713 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1719 e: &'hir hir::Expr<'hir>,
1720 args: &'hir [hir::Expr<'hir>],
1721 ) -> &'hir hir::Expr<'hir> {
1722 self.arena.alloc(self.expr_call_mut(span, e, args))
1725 fn expr_call_lang_item_fn_mut(
1728 lang_item: hir::LangItem,
1729 args: &'hir [hir::Expr<'hir>],
1730 hir_id: Option<hir::HirId>,
1731 ) -> hir::Expr<'hir> {
1733 self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new(), hir_id));
1734 self.expr_call_mut(span, path, args)
1737 fn expr_call_lang_item_fn(
1740 lang_item: hir::LangItem,
1741 args: &'hir [hir::Expr<'hir>],
1742 hir_id: Option<hir::HirId>,
1743 ) -> &'hir hir::Expr<'hir> {
1744 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1747 fn expr_lang_item_path(
1750 lang_item: hir::LangItem,
1752 hir_id: Option<hir::HirId>,
1753 ) -> hir::Expr<'hir> {
1756 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1761 pub(super) fn expr_ident(
1765 binding: hir::HirId,
1766 ) -> &'hir hir::Expr<'hir> {
1767 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1770 pub(super) fn expr_ident_mut(
1774 binding: hir::HirId,
1775 ) -> hir::Expr<'hir> {
1776 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1779 fn expr_ident_with_attrs(
1783 binding: hir::HirId,
1785 ) -> hir::Expr<'hir> {
1786 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1788 self.arena.alloc(hir::Path {
1789 span: self.lower_span(span),
1790 res: Res::Local(binding),
1791 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1795 self.expr(span, expr_path, attrs)
1798 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1799 let hir_id = self.next_id();
1800 let span = expr.span;
1803 hir::ExprKind::Block(
1804 self.arena.alloc(hir::Block {
1808 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1809 span: self.lower_span(span),
1810 targeted_by_break: false,
1818 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1819 let blk = self.block_all(span, &[], None);
1820 let expr = self.expr_block(blk, ThinVec::new());
1821 self.arena.alloc(expr)
1824 pub(super) fn expr_block(
1826 b: &'hir hir::Block<'hir>,
1828 ) -> hir::Expr<'hir> {
1829 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1835 kind: hir::ExprKind<'hir>,
1837 ) -> hir::Expr<'hir> {
1838 let hir_id = self.next_id();
1839 self.lower_attrs(hir_id, &attrs);
1840 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1846 expr: &'hir hir::Expr<'hir>,
1848 ) -> hir::ExprField<'hir> {
1850 hir_id: self.next_id(),
1852 span: self.lower_span(span),
1854 is_shorthand: false,
1858 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1860 hir_id: self.next_id(),
1863 span: self.lower_span(expr.span),