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(
174 self.lower_expr_closure(
183 ExprKind::Block(ref blk, opt_label) => {
184 let opt_label = self.lower_label(opt_label);
185 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
187 ExprKind::Assign(ref el, ref er, span) => {
188 self.lower_expr_assign(el, er, span, e.span)
190 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
191 self.lower_binop(op),
195 ExprKind::Field(ref el, ident) => {
196 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
198 ExprKind::Index(ref el, ref er) => {
199 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
201 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
202 self.lower_expr_range_closed(e.span, e1, e2)
204 ExprKind::Range(ref e1, ref e2, lims) => {
205 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
207 ExprKind::Underscore => {
211 "in expressions, `_` can only be used on the left-hand side of an assignment",
213 .span_label(e.span, "`_` not allowed here")
217 ExprKind::Path(ref qself, ref path) => {
218 let qpath = self.lower_qpath(
223 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
225 hir::ExprKind::Path(qpath)
227 ExprKind::Break(opt_label, ref opt_expr) => {
228 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
229 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
231 ExprKind::Continue(opt_label) => {
232 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
234 ExprKind::Ret(ref e) => {
235 let e = e.as_ref().map(|x| self.lower_expr(x));
236 hir::ExprKind::Ret(e)
238 ExprKind::Yeet(ref sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
239 ExprKind::InlineAsm(ref asm) => {
240 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
242 ExprKind::Struct(ref se) => {
243 let rest = match &se.rest {
244 StructRest::Base(e) => Some(self.lower_expr(e)),
245 StructRest::Rest(sp) => {
247 .struct_span_err(*sp, "base expression required after `..`")
248 .span_label(*sp, "add a base expression here")
250 Some(&*self.arena.alloc(self.expr_err(*sp)))
252 StructRest::None => None,
254 hir::ExprKind::Struct(
255 self.arena.alloc(self.lower_qpath(
260 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
263 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
267 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
268 ExprKind::Err => hir::ExprKind::Err,
269 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
270 ExprKind::Paren(ref ex) => {
271 let mut ex = self.lower_expr_mut(ex);
272 // Include parens in span, but only if it is a super-span.
273 if e.span.contains(ex.span) {
274 ex.span = self.lower_span(e.span);
276 // Merge attributes into the inner expression.
277 if !e.attrs.is_empty() {
279 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
282 &*self.arena.alloc_from_iter(
285 .map(|a| self.lower_attr(a))
286 .chain(old_attrs.iter().cloned()),
293 // Desugar `ExprForLoop`
294 // from: `[opt_ident]: for <pat> in <head> <body>`
295 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
296 return self.lower_expr_for(e, pat, head, body, opt_label);
298 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
301 let hir_id = self.lower_node_id(e.id);
302 self.lower_attrs(hir_id, &e.attrs);
303 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
307 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
309 UnOp::Deref => hir::UnOp::Deref,
310 UnOp::Not => hir::UnOp::Not,
311 UnOp::Neg => hir::UnOp::Neg,
315 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
318 BinOpKind::Add => hir::BinOpKind::Add,
319 BinOpKind::Sub => hir::BinOpKind::Sub,
320 BinOpKind::Mul => hir::BinOpKind::Mul,
321 BinOpKind::Div => hir::BinOpKind::Div,
322 BinOpKind::Rem => hir::BinOpKind::Rem,
323 BinOpKind::And => hir::BinOpKind::And,
324 BinOpKind::Or => hir::BinOpKind::Or,
325 BinOpKind::BitXor => hir::BinOpKind::BitXor,
326 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
327 BinOpKind::BitOr => hir::BinOpKind::BitOr,
328 BinOpKind::Shl => hir::BinOpKind::Shl,
329 BinOpKind::Shr => hir::BinOpKind::Shr,
330 BinOpKind::Eq => hir::BinOpKind::Eq,
331 BinOpKind::Lt => hir::BinOpKind::Lt,
332 BinOpKind::Le => hir::BinOpKind::Le,
333 BinOpKind::Ne => hir::BinOpKind::Ne,
334 BinOpKind::Ge => hir::BinOpKind::Ge,
335 BinOpKind::Gt => hir::BinOpKind::Gt,
337 span: self.lower_span(b.span),
341 fn lower_legacy_const_generics(
344 args: Vec<AstP<Expr>>,
345 legacy_args_idx: &[usize],
346 ) -> hir::ExprKind<'hir> {
347 let ExprKind::Path(None, ref mut path) = f.kind else {
351 // Split the arguments into const generics and normal arguments
352 let mut real_args = vec![];
353 let mut generic_args = vec![];
354 for (idx, arg) in args.into_iter().enumerate() {
355 if legacy_args_idx.contains(&idx) {
356 let parent_def_id = self.current_hir_id_owner;
357 let node_id = self.next_node_id();
359 // Add a definition for the in-band const def.
360 self.create_def(parent_def_id, node_id, DefPathData::AnonConst);
362 let anon_const = AnonConst { id: node_id, value: arg };
363 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
369 // Add generic args to the last element of the path.
370 let last_segment = path.segments.last_mut().unwrap();
371 assert!(last_segment.args.is_none());
372 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
377 // Now lower everything as normal.
378 let f = self.lower_expr(&f);
379 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
386 else_opt: Option<&Expr>,
387 ) -> hir::ExprKind<'hir> {
388 let lowered_cond = self.lower_expr(cond);
389 let new_cond = self.manage_let_cond(lowered_cond);
390 let then_expr = self.lower_block_expr(then);
391 if let Some(rslt) = else_opt {
392 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), Some(self.lower_expr(rslt)))
394 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), None)
398 // If `cond` kind is `let`, returns `let`. Otherwise, wraps and returns `cond`
399 // in a temporary block.
400 fn manage_let_cond(&mut self, cond: &'hir hir::Expr<'hir>) -> &'hir hir::Expr<'hir> {
401 fn has_let_expr<'hir>(expr: &'hir hir::Expr<'hir>) -> bool {
403 hir::ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
404 hir::ExprKind::Let(..) => true,
408 if has_let_expr(cond) {
411 let reason = DesugaringKind::CondTemporary;
412 let span_block = self.mark_span_with_reason(reason, cond.span, None);
413 self.expr_drop_temps(span_block, cond, AttrVec::new())
417 // We desugar: `'label: while $cond $body` into:
421 // if { let _t = $cond; _t } {
430 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
431 // to preserve drop semantics since `while $cond { ... }` does not
432 // let temporaries live outside of `cond`.
433 fn lower_expr_while_in_loop_scope(
438 opt_label: Option<Label>,
439 ) -> hir::ExprKind<'hir> {
440 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
441 let new_cond = self.manage_let_cond(lowered_cond);
442 let then = self.lower_block_expr(body);
443 let expr_break = self.expr_break(span, ThinVec::new());
444 let stmt_break = self.stmt_expr(span, expr_break);
445 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
446 let else_expr = self.arena.alloc(self.expr_block(else_blk, ThinVec::new()));
447 let if_kind = hir::ExprKind::If(new_cond, self.arena.alloc(then), Some(else_expr));
448 let if_expr = self.expr(span, if_kind, ThinVec::new());
449 let block = self.block_expr(self.arena.alloc(if_expr));
450 let span = self.lower_span(span.with_hi(cond.span.hi()));
451 let opt_label = self.lower_label(opt_label);
452 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
455 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
456 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
457 /// and save the block id to use it as a break target for desugaring of the `?` operator.
458 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
459 self.with_catch_scope(body.id, |this| {
460 let mut block = this.lower_block_noalloc(body, true);
462 // Final expression of the block (if present) or `()` with span at the end of block
463 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
465 this.mark_span_with_reason(
466 DesugaringKind::TryBlock,
468 this.allow_try_trait.clone(),
473 let try_span = this.mark_span_with_reason(
474 DesugaringKind::TryBlock,
475 this.sess.source_map().end_point(body.span),
476 this.allow_try_trait.clone(),
479 (try_span, this.expr_unit(try_span))
482 let ok_wrapped_span =
483 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
485 // `::std::ops::Try::from_output($tail_expr)`
486 block.expr = Some(this.wrap_in_try_constructor(
487 hir::LangItem::TryTraitFromOutput,
493 hir::ExprKind::Block(this.arena.alloc(block), None)
497 fn wrap_in_try_constructor(
499 lang_item: hir::LangItem,
501 expr: &'hir hir::Expr<'hir>,
503 ) -> &'hir hir::Expr<'hir> {
504 let constructor = self.arena.alloc(self.expr_lang_item_path(
510 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
513 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
514 let pat = self.lower_pat(&arm.pat);
515 let guard = arm.guard.as_ref().map(|cond| {
516 if let ExprKind::Let(ref pat, ref scrutinee, span) = cond.kind {
517 hir::Guard::IfLet(self.arena.alloc(hir::Let {
518 hir_id: self.next_id(),
519 span: self.lower_span(span),
520 pat: self.lower_pat(pat),
522 init: self.lower_expr(scrutinee),
525 hir::Guard::If(self.lower_expr(cond))
528 let hir_id = self.next_id();
529 self.lower_attrs(hir_id, &arm.attrs);
534 body: self.lower_expr(&arm.body),
535 span: self.lower_span(arm.span),
539 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
544 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
548 pub(super) fn make_async_expr(
550 capture_clause: CaptureBy,
551 closure_node_id: NodeId,
552 ret_ty: Option<AstP<Ty>>,
554 async_gen_kind: hir::AsyncGeneratorKind,
555 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
556 ) -> hir::ExprKind<'hir> {
557 let output = match ret_ty {
558 Some(ty) => hir::FnRetTy::Return(
559 self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock)),
561 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
564 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
565 // fully constrained by `future::from_generator`.
566 let input_ty = hir::Ty {
567 hir_id: self.next_id(),
568 kind: hir::TyKind::Infer,
569 span: self.lower_span(span),
572 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
573 let fn_decl = self.arena.alloc(hir::FnDecl {
574 inputs: arena_vec![self; input_ty],
577 implicit_self: hir::ImplicitSelfKind::None,
580 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
581 let (pat, task_context_hid) = self.pat_ident_binding_mode(
583 Ident::with_dummy_span(sym::_task_context),
584 hir::BindingAnnotation::Mutable,
586 let param = hir::Param {
587 hir_id: self.next_id(),
589 ty_span: self.lower_span(span),
590 span: self.lower_span(span),
592 let params = arena_vec![self; param];
594 let body = self.lower_body(move |this| {
595 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
597 let old_ctx = this.task_context;
598 this.task_context = Some(task_context_hid);
599 let res = body(this);
600 this.task_context = old_ctx;
604 // `static |_task_context| -> <ret_ty> { body }`:
605 let generator_kind = hir::ExprKind::Closure {
609 fn_decl_span: self.lower_span(span),
610 movability: Some(hir::Movability::Static),
612 let generator = hir::Expr {
613 hir_id: self.lower_node_id(closure_node_id),
614 kind: generator_kind,
615 span: self.lower_span(span),
618 // `future::from_generator`:
620 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
621 let gen_future = self.expr_lang_item_path(
623 hir::LangItem::FromGenerator,
628 // `future::from_generator(generator)`:
629 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
632 /// Desugar `<expr>.await` into:
633 /// ```ignore (pseudo-rust)
634 /// match ::std::future::IntoFuture::into_future(<expr>) {
635 /// mut __awaitee => loop {
636 /// match unsafe { ::std::future::Future::poll(
637 /// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
638 /// ::std::future::get_context(task_context),
640 /// ::std::task::Poll::Ready(result) => break result,
641 /// ::std::task::Poll::Pending => {}
643 /// task_context = yield ();
647 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
648 let full_span = expr.span.to(dot_await_span);
649 match self.generator_kind {
650 Some(hir::GeneratorKind::Async(_)) => {}
651 Some(hir::GeneratorKind::Gen) | None => {
652 let mut err = struct_span_err!(
656 "`await` is only allowed inside `async` functions and blocks"
658 err.span_label(dot_await_span, "only allowed inside `async` functions and blocks");
659 if let Some(item_sp) = self.current_item {
660 err.span_label(item_sp, "this is not `async`");
665 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
666 let gen_future_span = self.mark_span_with_reason(
667 DesugaringKind::Await,
669 self.allow_gen_future.clone(),
671 let expr = self.lower_expr_mut(expr);
672 let expr_hir_id = expr.hir_id;
674 // Note that the name of this binding must not be changed to something else because
675 // debuggers and debugger extensions expect it to be called `__awaitee`. They use
676 // this name to identify what is being awaited by a suspended async functions.
677 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
678 let (awaitee_pat, awaitee_pat_hid) =
679 self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::Mutable);
681 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
684 // ::std::future::Future::poll(
685 // ::std::pin::Pin::new_unchecked(&mut __awaitee),
686 // ::std::future::get_context(task_context),
690 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
691 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
692 let task_context = if let Some(task_context_hid) = self.task_context {
693 self.expr_ident_mut(span, task_context_ident, task_context_hid)
695 // Use of `await` outside of an async context, we cannot use `task_context` here.
698 let new_unchecked = self.expr_call_lang_item_fn_mut(
700 hir::LangItem::PinNewUnchecked,
701 arena_vec![self; ref_mut_awaitee],
704 let get_context = self.expr_call_lang_item_fn_mut(
706 hir::LangItem::GetContext,
707 arena_vec![self; task_context],
710 let call = self.expr_call_lang_item_fn(
712 hir::LangItem::FuturePoll,
713 arena_vec![self; new_unchecked, get_context],
716 self.arena.alloc(self.expr_unsafe(call))
719 // `::std::task::Poll::Ready(result) => break result`
720 let loop_node_id = self.next_node_id();
721 let loop_hir_id = self.lower_node_id(loop_node_id);
723 let x_ident = Ident::with_dummy_span(sym::result);
724 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
725 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
726 let ready_field = self.single_pat_field(gen_future_span, x_pat);
727 let ready_pat = self.pat_lang_item_variant(
729 hir::LangItem::PollReady,
733 let break_x = self.with_loop_scope(loop_node_id, move |this| {
735 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
736 this.arena.alloc(this.expr(gen_future_span, expr_break, ThinVec::new()))
738 self.arm(ready_pat, break_x)
741 // `::std::task::Poll::Pending => {}`
743 let pending_pat = self.pat_lang_item_variant(
745 hir::LangItem::PollPending,
749 let empty_block = self.expr_block_empty(span);
750 self.arm(pending_pat, empty_block)
753 let inner_match_stmt = {
754 let match_expr = self.expr_match(
757 arena_vec![self; ready_arm, pending_arm],
758 hir::MatchSource::AwaitDesugar,
760 self.stmt_expr(span, match_expr)
763 // task_context = yield ();
765 let unit = self.expr_unit(span);
766 let yield_expr = self.expr(
768 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
771 let yield_expr = self.arena.alloc(yield_expr);
773 if let Some(task_context_hid) = self.task_context {
774 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
775 let assign = self.expr(
777 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
780 self.stmt_expr(span, assign)
782 // Use of `await` outside of an async context. Return `yield_expr` so that we can
783 // proceed with type checking.
784 self.stmt(span, hir::StmtKind::Semi(yield_expr))
788 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
791 let loop_expr = self.arena.alloc(hir::Expr {
793 kind: hir::ExprKind::Loop(
796 hir::LoopSource::Loop,
797 self.lower_span(span),
799 span: self.lower_span(span),
802 // mut __awaitee => loop { ... }
803 let awaitee_arm = self.arm(awaitee_pat, loop_expr);
805 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
806 let into_future_span = self.mark_span_with_reason(
807 DesugaringKind::Await,
809 self.allow_into_future.clone(),
811 let into_future_expr = self.expr_call_lang_item_fn(
813 hir::LangItem::IntoFutureIntoFuture,
814 arena_vec![self; expr],
818 // match <into_future_expr> {
819 // mut __awaitee => loop { .. }
821 hir::ExprKind::Match(
823 arena_vec![self; awaitee_arm],
824 hir::MatchSource::AwaitDesugar,
828 fn lower_expr_closure(
830 capture_clause: CaptureBy,
831 movability: Movability,
835 ) -> hir::ExprKind<'hir> {
836 let (body, generator_option) = self.with_new_scopes(move |this| {
837 let prev = this.current_item;
838 this.current_item = Some(fn_decl_span);
839 let mut generator_kind = None;
840 let body_id = this.lower_fn_body(decl, |this| {
841 let e = this.lower_expr_mut(body);
842 generator_kind = this.generator_kind;
845 let generator_option =
846 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
847 this.current_item = prev;
848 (body_id, generator_option)
851 // Lower outside new scope to preserve `is_in_loop_condition`.
852 let fn_decl = self.lower_fn_decl(decl, None, FnDeclKind::Closure, None);
854 hir::ExprKind::Closure {
858 fn_decl_span: self.lower_span(fn_decl_span),
859 movability: generator_option,
863 fn generator_movability_for_fn(
867 generator_kind: Option<hir::GeneratorKind>,
868 movability: Movability,
869 ) -> Option<hir::Movability> {
870 match generator_kind {
871 Some(hir::GeneratorKind::Gen) => {
872 if decl.inputs.len() > 1 {
877 "too many parameters for a generator (expected 0 or 1 parameters)"
883 Some(hir::GeneratorKind::Async(_)) => {
884 panic!("non-`async` closure body turned `async` during lowering");
887 if movability == Movability::Static {
888 struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
896 fn lower_expr_async_closure(
898 capture_clause: CaptureBy,
903 ) -> hir::ExprKind<'hir> {
905 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
907 let body = self.with_new_scopes(|this| {
908 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
909 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
914 "`async` non-`move` closures with parameters are not currently supported",
917 "consider using `let` statements to manually capture \
918 variables by reference before entering an `async move` closure",
923 // Transform `async |x: u8| -> X { ... }` into
924 // `|x: u8| future_from_generator(|| -> X { ... })`.
925 let body_id = this.lower_fn_body(&outer_decl, |this| {
927 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
928 let async_body = this.make_async_expr(
933 hir::AsyncGeneratorKind::Closure,
934 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
936 this.expr(fn_decl_span, async_body, ThinVec::new())
941 // We need to lower the declaration outside the new scope, because we
942 // have to conserve the state of being inside a loop condition for the
943 // closure argument types.
944 let fn_decl = self.lower_fn_decl(&outer_decl, None, FnDeclKind::Closure, None);
946 hir::ExprKind::Closure {
950 fn_decl_span: self.lower_span(fn_decl_span),
955 /// Destructure the LHS of complex assignments.
956 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
957 fn lower_expr_assign(
963 ) -> hir::ExprKind<'hir> {
964 // Return early in case of an ordinary assignment.
965 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
968 | ExprKind::Struct(..)
970 | ExprKind::Underscore => false,
971 // Check for tuple struct constructor.
972 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
973 ExprKind::Paren(e) => {
975 // We special-case `(..)` for consistency with patterns.
976 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
977 _ => is_ordinary(lower_ctx, e),
983 if is_ordinary(self, lhs) {
984 return hir::ExprKind::Assign(
985 self.lower_expr(lhs),
986 self.lower_expr(rhs),
987 self.lower_span(eq_sign_span),
991 let mut assignments = vec![];
993 // The LHS becomes a pattern: `(lhs1, lhs2)`.
994 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
995 let rhs = self.lower_expr(rhs);
997 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
998 let destructure_let = self.stmt_let_pat(
1003 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
1006 // `a = lhs1; b = lhs2;`.
1009 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1011 // Wrap everything in a block.
1012 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1015 /// If the given expression is a path to a tuple struct, returns that path.
1016 /// It is not a complete check, but just tries to reject most paths early
1017 /// if they are not tuple structs.
1018 /// Type checking will take care of the full validation later.
1019 fn extract_tuple_struct_path<'a>(
1022 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1023 if let ExprKind::Path(qself, path) = &expr.kind {
1024 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1025 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1026 if partial_res.unresolved_segments() == 0
1027 && !partial_res.base_res().expected_in_tuple_struct_pat()
1032 return Some((qself, path));
1037 /// If the given expression is a path to a unit struct, returns that path.
1038 /// It is not a complete check, but just tries to reject most paths early
1039 /// if they are not unit structs.
1040 /// Type checking will take care of the full validation later.
1041 fn extract_unit_struct_path<'a>(
1044 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1045 if let ExprKind::Path(qself, path) = &expr.kind {
1046 // Does the path resolve to something disallowed in a unit struct/variant pattern?
1047 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1048 if partial_res.unresolved_segments() == 0
1049 && !partial_res.base_res().expected_in_unit_struct_pat()
1054 return Some((qself, path));
1059 /// Convert the LHS of a destructuring assignment to a pattern.
1060 /// Each sub-assignment is recorded in `assignments`.
1061 fn destructure_assign(
1065 assignments: &mut Vec<hir::Stmt<'hir>>,
1066 ) -> &'hir hir::Pat<'hir> {
1067 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1070 fn destructure_assign_mut(
1074 assignments: &mut Vec<hir::Stmt<'hir>>,
1075 ) -> hir::Pat<'hir> {
1077 // Underscore pattern.
1078 ExprKind::Underscore => {
1079 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1082 ExprKind::Array(elements) => {
1084 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1085 let slice_pat = if let Some((i, span)) = rest {
1086 let (before, after) = pats.split_at(i);
1087 hir::PatKind::Slice(
1089 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1093 hir::PatKind::Slice(pats, None, &[])
1095 return self.pat_without_dbm(lhs.span, slice_pat);
1098 ExprKind::Call(callee, args) => {
1099 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1100 let (pats, rest) = self.destructure_sequence(
1102 "tuple struct or variant",
1106 let qpath = self.lower_qpath(
1110 ParamMode::Optional,
1111 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1113 // Destructure like a tuple struct.
1114 let tuple_struct_pat =
1115 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1116 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1119 // Unit structs and enum variants.
1120 ExprKind::Path(..) => {
1121 if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1122 let qpath = self.lower_qpath(
1126 ParamMode::Optional,
1127 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1129 // Destructure like a unit struct.
1130 let unit_struct_pat = hir::PatKind::Path(qpath);
1131 return self.pat_without_dbm(lhs.span, unit_struct_pat);
1135 ExprKind::Struct(se) => {
1136 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1137 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1139 hir_id: self.next_id(),
1140 ident: self.lower_ident(f.ident),
1142 is_shorthand: f.is_shorthand,
1143 span: self.lower_span(f.span),
1146 let qpath = self.lower_qpath(
1150 ParamMode::Optional,
1151 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1153 let fields_omitted = match &se.rest {
1154 StructRest::Base(e) => {
1158 "functional record updates are not allowed in destructuring \
1163 "consider removing the trailing pattern",
1165 rustc_errors::Applicability::MachineApplicable,
1170 StructRest::Rest(_) => true,
1171 StructRest::None => false,
1173 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1174 return self.pat_without_dbm(lhs.span, struct_pat);
1177 ExprKind::Tup(elements) => {
1179 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1180 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1181 return self.pat_without_dbm(lhs.span, tuple_pat);
1183 ExprKind::Paren(e) => {
1184 // We special-case `(..)` for consistency with patterns.
1185 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1186 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1187 return self.pat_without_dbm(lhs.span, tuple_pat);
1189 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1194 // Treat all other cases as normal lvalue.
1195 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1196 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1197 let ident = self.expr_ident(lhs.span, ident, binding);
1199 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1200 let expr = self.expr(lhs.span, assign, ThinVec::new());
1201 assignments.push(self.stmt_expr(lhs.span, expr));
1205 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1206 /// Such a sequence occurs in a tuple (struct)/slice.
1207 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1209 /// Each sub-assignment is recorded in `assignments`.
1210 fn destructure_sequence(
1212 elements: &[AstP<Expr>],
1215 assignments: &mut Vec<hir::Stmt<'hir>>,
1216 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1217 let mut rest = None;
1219 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1220 // Check for `..` pattern.
1221 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1222 if let Some((_, prev_span)) = rest {
1223 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1225 rest = Some((i, e.span));
1229 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1235 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1236 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1237 let e1 = self.lower_expr_mut(e1);
1238 let e2 = self.lower_expr_mut(e2);
1240 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1242 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1243 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1246 fn lower_expr_range(
1252 ) -> hir::ExprKind<'hir> {
1253 use rustc_ast::RangeLimits::*;
1255 let lang_item = match (e1, e2, lims) {
1256 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1257 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1258 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1259 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1260 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1261 (Some(..), Some(..), Closed) => unreachable!(),
1262 (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"),
1265 let fields = self.arena.alloc_from_iter(
1266 e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1268 let expr = self.lower_expr(&e);
1269 let ident = Ident::new(s, self.lower_span(e.span));
1270 self.expr_field(ident, expr, e.span)
1275 hir::ExprKind::Struct(
1276 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)),
1282 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1283 let label = opt_label?;
1284 Some(Label { ident: self.lower_ident(label.ident) })
1287 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1288 let target_id = match destination {
1290 if let Some(loop_id) = self.resolver.get_label_res(id) {
1291 Ok(self.lower_node_id(loop_id))
1293 Err(hir::LoopIdError::UnresolvedLabel)
1298 .map(|id| Ok(self.lower_node_id(id)))
1299 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1301 let label = self.lower_label(destination.map(|(_, label)| label));
1302 hir::Destination { label, target_id }
1305 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1306 if self.is_in_loop_condition && opt_label.is_none() {
1309 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1312 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1316 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1317 let old_scope = self.catch_scope.replace(catch_id);
1318 let result = f(self);
1319 self.catch_scope = old_scope;
1323 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1324 // We're no longer in the base loop's condition; we're in another loop.
1325 let was_in_loop_condition = self.is_in_loop_condition;
1326 self.is_in_loop_condition = false;
1328 let old_scope = self.loop_scope.replace(loop_id);
1329 let result = f(self);
1330 self.loop_scope = old_scope;
1332 self.is_in_loop_condition = was_in_loop_condition;
1337 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1338 let was_in_loop_condition = self.is_in_loop_condition;
1339 self.is_in_loop_condition = true;
1341 let result = f(self);
1343 self.is_in_loop_condition = was_in_loop_condition;
1348 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1350 hir_id: self.next_id(),
1351 ident: self.lower_ident(f.ident),
1352 expr: self.lower_expr(&f.expr),
1353 span: self.lower_span(f.span),
1354 is_shorthand: f.is_shorthand,
1358 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1359 match self.generator_kind {
1360 Some(hir::GeneratorKind::Gen) => {}
1361 Some(hir::GeneratorKind::Async(_)) => {
1366 "`async` generators are not yet supported"
1370 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1374 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1376 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1379 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1380 /// ```ignore (pseudo-rust)
1382 /// let result = match IntoIterator::into_iter(<head>) {
1384 /// [opt_ident]: loop {
1385 /// match Iterator::next(&mut iter) {
1387 /// Some(<pat>) => <body>,
1401 opt_label: Option<Label>,
1402 ) -> hir::Expr<'hir> {
1403 let head = self.lower_expr_mut(head);
1404 let pat = self.lower_pat(pat);
1406 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1407 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1408 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1413 self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span, ThinVec::new()));
1414 let pat = self.pat_none(for_span);
1415 self.arm(pat, break_expr)
1418 // Some(<pat>) => <body>,
1420 let some_pat = self.pat_some(pat_span, pat);
1421 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1422 let body_expr = self.arena.alloc(self.expr_block(body_block, ThinVec::new()));
1423 self.arm(some_pat, body_expr)
1427 let iter = Ident::with_dummy_span(sym::iter);
1428 let (iter_pat, iter_pat_nid) =
1429 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::Mutable);
1431 // `match Iterator::next(&mut iter) { ... }`
1433 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1434 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1435 let next_expr = self.expr_call_lang_item_fn(
1437 hir::LangItem::IteratorNext,
1438 arena_vec![self; ref_mut_iter],
1441 let arms = arena_vec![self; none_arm, some_arm];
1443 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1445 let match_stmt = self.stmt_expr(for_span, match_expr);
1447 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1449 // `[opt_ident]: loop { ... }`
1450 let kind = hir::ExprKind::Loop(
1452 self.lower_label(opt_label),
1453 hir::LoopSource::ForLoop,
1454 self.lower_span(for_span.with_hi(head.span.hi())),
1457 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1459 // `mut iter => { ... }`
1460 let iter_arm = self.arm(iter_pat, loop_expr);
1462 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1463 let into_iter_expr = {
1464 self.expr_call_lang_item_fn(
1466 hir::LangItem::IntoIterIntoIter,
1467 arena_vec![self; head],
1472 let match_expr = self.arena.alloc(self.expr_match(
1475 arena_vec![self; iter_arm],
1476 hir::MatchSource::ForLoopDesugar,
1479 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1481 // This is effectively `{ let _result = ...; _result }`.
1482 // The construct was introduced in #21984 and is necessary to make sure that
1483 // temporaries in the `head` expression are dropped and do not leak to the
1484 // surrounding scope of the `match` since the `match` is not a terminating scope.
1486 // Also, add the attributes to the outer returned expr node.
1487 self.expr_drop_temps_mut(for_span, match_expr, attrs.into())
1490 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1491 /// ```ignore (pseudo-rust)
1492 /// match Try::branch(<expr>) {
1493 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1494 /// ControlFlow::Break(residual) =>
1495 /// #[allow(unreachable_code)]
1496 /// // If there is an enclosing `try {...}`:
1497 /// break 'catch_target Try::from_residual(residual),
1499 /// return Try::from_residual(residual),
1502 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1503 let unstable_span = self.mark_span_with_reason(
1504 DesugaringKind::QuestionMark,
1506 self.allow_try_trait.clone(),
1508 let try_span = self.sess.source_map().end_point(span);
1509 let try_span = self.mark_span_with_reason(
1510 DesugaringKind::QuestionMark,
1512 self.allow_try_trait.clone(),
1515 // `Try::branch(<expr>)`
1518 let sub_expr = self.lower_expr_mut(sub_expr);
1520 self.expr_call_lang_item_fn(
1522 hir::LangItem::TryTraitBranch,
1523 arena_vec![self; sub_expr],
1528 // `#[allow(unreachable_code)]`
1530 // `allow(unreachable_code)`
1532 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1533 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1534 let uc_nested = attr::mk_nested_word_item(uc_ident);
1535 attr::mk_list_item(allow_ident, vec![uc_nested])
1537 attr::mk_attr_outer(allow)
1539 let attrs = vec![attr];
1541 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1542 let continue_arm = {
1543 let val_ident = Ident::with_dummy_span(sym::val);
1544 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1545 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1549 ThinVec::from(attrs.clone()),
1551 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1552 self.arm(continue_pat, val_expr)
1555 // `ControlFlow::Break(residual) =>
1556 // #[allow(unreachable_code)]
1557 // return Try::from_residual(residual),`
1559 let residual_ident = Ident::with_dummy_span(sym::residual);
1560 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1561 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1562 let from_residual_expr = self.wrap_in_try_constructor(
1563 hir::LangItem::TryTraitFromResidual,
1565 self.arena.alloc(residual_expr),
1568 let thin_attrs = ThinVec::from(attrs);
1569 let ret_expr = if let Some(catch_node) = self.catch_scope {
1570 let target_id = Ok(self.lower_node_id(catch_node));
1571 self.arena.alloc(self.expr(
1573 hir::ExprKind::Break(
1574 hir::Destination { label: None, target_id },
1575 Some(from_residual_expr),
1580 self.arena.alloc(self.expr(
1582 hir::ExprKind::Ret(Some(from_residual_expr)),
1587 let break_pat = self.pat_cf_break(try_span, residual_local);
1588 self.arm(break_pat, ret_expr)
1591 hir::ExprKind::Match(
1593 arena_vec![self; break_arm, continue_arm],
1594 hir::MatchSource::TryDesugar,
1598 /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into:
1600 /// // If there is an enclosing `try {...}`:
1601 /// break 'catch_target FromResidual::from_residual(Yeet(residual)),
1603 /// return FromResidual::from_residual(Yeet(residual)),
1605 /// But to simplify this, there's a `from_yeet` lang item function which
1606 /// handles the combined `FromResidual::from_residual(Yeet(residual))`.
1607 fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1608 // The expression (if present) or `()` otherwise.
1609 let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
1610 (sub_expr.span, self.lower_expr(sub_expr))
1612 (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
1615 let unstable_span = self.mark_span_with_reason(
1616 DesugaringKind::YeetExpr,
1618 self.allow_try_trait.clone(),
1621 let from_yeet_expr = self.wrap_in_try_constructor(
1622 hir::LangItem::TryTraitFromYeet,
1628 if let Some(catch_node) = self.catch_scope {
1629 let target_id = Ok(self.lower_node_id(catch_node));
1630 hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
1632 hir::ExprKind::Ret(Some(from_yeet_expr))
1636 // =========================================================================
1637 // Helper methods for building HIR.
1638 // =========================================================================
1640 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1642 /// In terms of drop order, it has the same effect as wrapping `expr` in
1643 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1645 /// The drop order can be important in e.g. `if expr { .. }`.
1646 pub(super) fn expr_drop_temps(
1649 expr: &'hir hir::Expr<'hir>,
1651 ) -> &'hir hir::Expr<'hir> {
1652 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1655 pub(super) fn expr_drop_temps_mut(
1658 expr: &'hir hir::Expr<'hir>,
1660 ) -> hir::Expr<'hir> {
1661 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1667 arg: &'hir hir::Expr<'hir>,
1668 arms: &'hir [hir::Arm<'hir>],
1669 source: hir::MatchSource,
1670 ) -> hir::Expr<'hir> {
1671 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1674 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1675 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1676 self.expr(span, expr_break, attrs)
1679 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1680 let expr_break = self.expr_break(span, attrs);
1681 self.arena.alloc(expr_break)
1684 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1687 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1692 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1693 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1699 e: &'hir hir::Expr<'hir>,
1700 args: &'hir [hir::Expr<'hir>],
1701 ) -> hir::Expr<'hir> {
1702 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1708 e: &'hir hir::Expr<'hir>,
1709 args: &'hir [hir::Expr<'hir>],
1710 ) -> &'hir hir::Expr<'hir> {
1711 self.arena.alloc(self.expr_call_mut(span, e, args))
1714 fn expr_call_lang_item_fn_mut(
1717 lang_item: hir::LangItem,
1718 args: &'hir [hir::Expr<'hir>],
1719 hir_id: Option<hir::HirId>,
1720 ) -> hir::Expr<'hir> {
1722 self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new(), hir_id));
1723 self.expr_call_mut(span, path, args)
1726 fn expr_call_lang_item_fn(
1729 lang_item: hir::LangItem,
1730 args: &'hir [hir::Expr<'hir>],
1731 hir_id: Option<hir::HirId>,
1732 ) -> &'hir hir::Expr<'hir> {
1733 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1736 fn expr_lang_item_path(
1739 lang_item: hir::LangItem,
1741 hir_id: Option<hir::HirId>,
1742 ) -> hir::Expr<'hir> {
1745 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1750 pub(super) fn expr_ident(
1754 binding: hir::HirId,
1755 ) -> &'hir hir::Expr<'hir> {
1756 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1759 pub(super) fn expr_ident_mut(
1763 binding: hir::HirId,
1764 ) -> hir::Expr<'hir> {
1765 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1768 fn expr_ident_with_attrs(
1772 binding: hir::HirId,
1774 ) -> hir::Expr<'hir> {
1775 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1777 self.arena.alloc(hir::Path {
1778 span: self.lower_span(span),
1779 res: Res::Local(binding),
1780 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1784 self.expr(span, expr_path, attrs)
1787 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1788 let hir_id = self.next_id();
1789 let span = expr.span;
1792 hir::ExprKind::Block(
1793 self.arena.alloc(hir::Block {
1797 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1798 span: self.lower_span(span),
1799 targeted_by_break: false,
1807 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1808 let blk = self.block_all(span, &[], None);
1809 let expr = self.expr_block(blk, ThinVec::new());
1810 self.arena.alloc(expr)
1813 pub(super) fn expr_block(
1815 b: &'hir hir::Block<'hir>,
1817 ) -> hir::Expr<'hir> {
1818 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1824 kind: hir::ExprKind<'hir>,
1826 ) -> hir::Expr<'hir> {
1827 let hir_id = self.next_id();
1828 self.lower_attrs(hir_id, &attrs);
1829 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1835 expr: &'hir hir::Expr<'hir>,
1837 ) -> hir::ExprField<'hir> {
1839 hir_id: self.next_id(),
1841 span: self.lower_span(span),
1843 is_shorthand: false,
1847 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1849 hir_id: self.next_id(),
1852 span: self.lower_span(expr.span),