2 AsyncGeneratorsNotSupported, AsyncNonMoveClosureNotSupported, AwaitOnlyInAsyncFnAndBlocks,
3 BaseExpressionDoubleDot, ClosureCannotBeStatic, FunctionalRecordUpdateDestructuringAssignemnt,
4 GeneratorTooManyParameters, InclusiveRangeWithNoEnd, NotSupportedForLifetimeBinderAsyncClosure,
5 RustcBoxAttributeError, UnderscoreExprLhsAssign,
7 use super::ResolverAstLoweringExt;
8 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
9 use crate::{FnDeclKind, ImplTraitPosition};
11 use rustc_ast::ptr::P as AstP;
13 use rustc_data_structures::stack::ensure_sufficient_stack;
15 use rustc_hir::def::Res;
16 use rustc_hir::definitions::DefPathData;
17 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
18 use rustc_span::symbol::{sym, Ident};
19 use rustc_span::DUMMY_SP;
20 use thin_vec::thin_vec;
22 impl<'hir> LoweringContext<'_, 'hir> {
23 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
24 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
27 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
28 self.arena.alloc(self.lower_expr_mut(e))
31 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
32 ensure_sufficient_stack(|| {
33 let kind = match e.kind {
34 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
35 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
36 ExprKind::ConstBlock(ref anon_const) => {
37 let anon_const = self.lower_anon_const(anon_const);
38 hir::ExprKind::ConstBlock(anon_const)
40 ExprKind::Repeat(ref expr, ref count) => {
41 let expr = self.lower_expr(expr);
42 let count = self.lower_array_length(count);
43 hir::ExprKind::Repeat(expr, count)
45 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
46 ExprKind::Call(ref f, ref args) => {
47 if e.attrs.get(0).map_or(false, |a| a.has_name(sym::rustc_box)) {
48 if let [inner] = &args[..] && e.attrs.len() == 1 {
49 let kind = hir::ExprKind::Box(self.lower_expr(&inner));
50 let hir_id = self.lower_node_id(e.id);
51 return hir::Expr { hir_id, kind, span: self.lower_span(e.span) };
53 self.tcx.sess.emit_err(RustcBoxAttributeError { span: e.span });
56 } else if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
57 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
59 let f = self.lower_expr(f);
60 hir::ExprKind::Call(f, self.lower_exprs(args))
63 ExprKind::MethodCall(ref seg, ref receiver, ref args, span) => {
64 let hir_seg = self.arena.alloc(self.lower_path_segment(
68 ParenthesizedGenericArgs::Err,
69 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
71 let receiver = self.lower_expr(receiver);
73 self.arena.alloc_from_iter(args.iter().map(|x| self.lower_expr_mut(x)));
74 hir::ExprKind::MethodCall(hir_seg, receiver, 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)
166 if let Async::Yes { closure_id, .. } = asyncness {
167 self.lower_expr_async_closure(
177 self.lower_expr_closure(
188 ExprKind::Block(ref blk, opt_label) => {
189 let opt_label = self.lower_label(opt_label);
190 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
192 ExprKind::Assign(ref el, ref er, span) => {
193 self.lower_expr_assign(el, er, span, e.span)
195 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
196 self.lower_binop(op),
200 ExprKind::Field(ref el, ident) => {
201 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
203 ExprKind::Index(ref el, ref er) => {
204 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
206 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
207 self.lower_expr_range_closed(e.span, e1, e2)
209 ExprKind::Range(ref e1, ref e2, lims) => {
210 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
212 ExprKind::Underscore => {
213 self.tcx.sess.emit_err(UnderscoreExprLhsAssign { span: e.span });
216 ExprKind::Path(ref qself, ref path) => {
217 let qpath = self.lower_qpath(
222 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
224 hir::ExprKind::Path(qpath)
226 ExprKind::Break(opt_label, ref opt_expr) => {
227 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
228 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
230 ExprKind::Continue(opt_label) => {
231 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
233 ExprKind::Ret(ref e) => {
234 let e = e.as_ref().map(|x| self.lower_expr(x));
235 hir::ExprKind::Ret(e)
237 ExprKind::Yeet(ref sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
238 ExprKind::InlineAsm(ref asm) => {
239 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
241 ExprKind::Struct(ref se) => {
242 let rest = match &se.rest {
243 StructRest::Base(e) => Some(self.lower_expr(e)),
244 StructRest::Rest(sp) => {
245 self.tcx.sess.emit_err(BaseExpressionDoubleDot { span: *sp });
246 Some(&*self.arena.alloc(self.expr_err(*sp)))
248 StructRest::None => None,
250 hir::ExprKind::Struct(
251 self.arena.alloc(self.lower_qpath(
256 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
259 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
263 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
264 ExprKind::Err => hir::ExprKind::Err,
265 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
266 ExprKind::Paren(ref ex) => {
267 let mut ex = self.lower_expr_mut(ex);
268 // Include parens in span, but only if it is a super-span.
269 if e.span.contains(ex.span) {
270 ex.span = self.lower_span(e.span);
272 // Merge attributes into the inner expression.
273 if !e.attrs.is_empty() {
275 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
278 &*self.arena.alloc_from_iter(
281 .map(|a| self.lower_attr(a))
282 .chain(old_attrs.iter().cloned()),
289 // Desugar `ExprForLoop`
290 // from: `[opt_ident]: for <pat> in <head> <body>`
291 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
292 return self.lower_expr_for(e, pat, head, body, opt_label);
294 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
297 let hir_id = self.lower_node_id(e.id);
298 self.lower_attrs(hir_id, &e.attrs);
299 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
303 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
305 UnOp::Deref => hir::UnOp::Deref,
306 UnOp::Not => hir::UnOp::Not,
307 UnOp::Neg => hir::UnOp::Neg,
311 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
314 BinOpKind::Add => hir::BinOpKind::Add,
315 BinOpKind::Sub => hir::BinOpKind::Sub,
316 BinOpKind::Mul => hir::BinOpKind::Mul,
317 BinOpKind::Div => hir::BinOpKind::Div,
318 BinOpKind::Rem => hir::BinOpKind::Rem,
319 BinOpKind::And => hir::BinOpKind::And,
320 BinOpKind::Or => hir::BinOpKind::Or,
321 BinOpKind::BitXor => hir::BinOpKind::BitXor,
322 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
323 BinOpKind::BitOr => hir::BinOpKind::BitOr,
324 BinOpKind::Shl => hir::BinOpKind::Shl,
325 BinOpKind::Shr => hir::BinOpKind::Shr,
326 BinOpKind::Eq => hir::BinOpKind::Eq,
327 BinOpKind::Lt => hir::BinOpKind::Lt,
328 BinOpKind::Le => hir::BinOpKind::Le,
329 BinOpKind::Ne => hir::BinOpKind::Ne,
330 BinOpKind::Ge => hir::BinOpKind::Ge,
331 BinOpKind::Gt => hir::BinOpKind::Gt,
333 span: self.lower_span(b.span),
337 fn lower_legacy_const_generics(
340 args: Vec<AstP<Expr>>,
341 legacy_args_idx: &[usize],
342 ) -> hir::ExprKind<'hir> {
343 let ExprKind::Path(None, ref mut path) = f.kind else {
347 // Split the arguments into const generics and normal arguments
348 let mut real_args = vec![];
349 let mut generic_args = vec![];
350 for (idx, arg) in args.into_iter().enumerate() {
351 if legacy_args_idx.contains(&idx) {
352 let parent_def_id = self.current_hir_id_owner;
353 let node_id = self.next_node_id();
355 // Add a definition for the in-band const def.
356 self.create_def(parent_def_id, node_id, DefPathData::AnonConst);
358 let anon_const = AnonConst { id: node_id, value: arg };
359 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
365 // Add generic args to the last element of the path.
366 let last_segment = path.segments.last_mut().unwrap();
367 assert!(last_segment.args.is_none());
368 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
373 // Now lower everything as normal.
374 let f = self.lower_expr(&f);
375 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
382 else_opt: Option<&Expr>,
383 ) -> hir::ExprKind<'hir> {
384 let lowered_cond = self.lower_expr(cond);
385 let new_cond = self.manage_let_cond(lowered_cond);
386 let then_expr = self.lower_block_expr(then);
387 if let Some(rslt) = else_opt {
388 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), Some(self.lower_expr(rslt)))
390 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), None)
394 // If `cond` kind is `let`, returns `let`. Otherwise, wraps and returns `cond`
395 // in a temporary block.
396 fn manage_let_cond(&mut self, cond: &'hir hir::Expr<'hir>) -> &'hir hir::Expr<'hir> {
397 fn has_let_expr<'hir>(expr: &'hir hir::Expr<'hir>) -> bool {
399 hir::ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
400 hir::ExprKind::Let(..) => true,
404 if has_let_expr(cond) {
407 let reason = DesugaringKind::CondTemporary;
408 let span_block = self.mark_span_with_reason(reason, cond.span, None);
409 self.expr_drop_temps(span_block, cond, AttrVec::new())
413 // We desugar: `'label: while $cond $body` into:
417 // if { let _t = $cond; _t } {
426 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
427 // to preserve drop semantics since `while $cond { ... }` does not
428 // let temporaries live outside of `cond`.
429 fn lower_expr_while_in_loop_scope(
434 opt_label: Option<Label>,
435 ) -> hir::ExprKind<'hir> {
436 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
437 let new_cond = self.manage_let_cond(lowered_cond);
438 let then = self.lower_block_expr(body);
439 let expr_break = self.expr_break(span, AttrVec::new());
440 let stmt_break = self.stmt_expr(span, expr_break);
441 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
442 let else_expr = self.arena.alloc(self.expr_block(else_blk, AttrVec::new()));
443 let if_kind = hir::ExprKind::If(new_cond, self.arena.alloc(then), Some(else_expr));
444 let if_expr = self.expr(span, if_kind, AttrVec::new());
445 let block = self.block_expr(self.arena.alloc(if_expr));
446 let span = self.lower_span(span.with_hi(cond.span.hi()));
447 let opt_label = self.lower_label(opt_label);
448 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
451 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
452 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
453 /// and save the block id to use it as a break target for desugaring of the `?` operator.
454 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
455 self.with_catch_scope(body.id, |this| {
456 let mut block = this.lower_block_noalloc(body, true);
458 // Final expression of the block (if present) or `()` with span at the end of block
459 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
461 this.mark_span_with_reason(
462 DesugaringKind::TryBlock,
464 this.allow_try_trait.clone(),
469 let try_span = this.mark_span_with_reason(
470 DesugaringKind::TryBlock,
471 this.tcx.sess.source_map().end_point(body.span),
472 this.allow_try_trait.clone(),
475 (try_span, this.expr_unit(try_span))
478 let ok_wrapped_span =
479 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
481 // `::std::ops::Try::from_output($tail_expr)`
482 block.expr = Some(this.wrap_in_try_constructor(
483 hir::LangItem::TryTraitFromOutput,
489 hir::ExprKind::Block(this.arena.alloc(block), None)
493 fn wrap_in_try_constructor(
495 lang_item: hir::LangItem,
497 expr: &'hir hir::Expr<'hir>,
499 ) -> &'hir hir::Expr<'hir> {
500 let constructor = self.arena.alloc(self.expr_lang_item_path(
506 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
509 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
510 let pat = self.lower_pat(&arm.pat);
511 let guard = arm.guard.as_ref().map(|cond| {
512 if let ExprKind::Let(ref pat, ref scrutinee, span) = cond.kind {
513 hir::Guard::IfLet(self.arena.alloc(hir::Let {
514 hir_id: self.next_id(),
515 span: self.lower_span(span),
516 pat: self.lower_pat(pat),
518 init: self.lower_expr(scrutinee),
521 hir::Guard::If(self.lower_expr(cond))
524 let hir_id = self.next_id();
525 self.lower_attrs(hir_id, &arm.attrs);
530 body: self.lower_expr(&arm.body),
531 span: self.lower_span(arm.span),
535 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
540 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
544 pub(super) fn make_async_expr(
546 capture_clause: CaptureBy,
547 closure_node_id: NodeId,
548 ret_ty: Option<AstP<Ty>>,
550 async_gen_kind: hir::AsyncGeneratorKind,
551 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
552 ) -> hir::ExprKind<'hir> {
553 let output = match ret_ty {
554 Some(ty) => hir::FnRetTy::Return(
555 self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock)),
557 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
560 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
561 // fully constrained by `future::from_generator`.
562 let input_ty = hir::Ty {
563 hir_id: self.next_id(),
564 kind: hir::TyKind::Infer,
565 span: self.lower_span(span),
568 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
569 let fn_decl = self.arena.alloc(hir::FnDecl {
570 inputs: arena_vec![self; input_ty],
573 implicit_self: hir::ImplicitSelfKind::None,
576 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
577 let (pat, task_context_hid) = self.pat_ident_binding_mode(
579 Ident::with_dummy_span(sym::_task_context),
580 hir::BindingAnnotation::MUT,
582 let param = hir::Param {
583 hir_id: self.next_id(),
585 ty_span: self.lower_span(span),
586 span: self.lower_span(span),
588 let params = arena_vec![self; param];
590 let body = self.lower_body(move |this| {
591 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
593 let old_ctx = this.task_context;
594 this.task_context = Some(task_context_hid);
595 let res = body(this);
596 this.task_context = old_ctx;
600 // `static |_task_context| -> <ret_ty> { body }`:
601 let generator_kind = {
602 let c = self.arena.alloc(hir::Closure {
603 binder: hir::ClosureBinder::Default,
605 bound_generic_params: &[],
608 fn_decl_span: self.lower_span(span),
609 movability: Some(hir::Movability::Static),
612 hir::ExprKind::Closure(c)
614 let generator = hir::Expr {
615 hir_id: self.lower_node_id(closure_node_id),
616 kind: generator_kind,
617 span: self.lower_span(span),
620 // `future::from_generator`:
622 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
623 let gen_future = self.expr_lang_item_path(
625 hir::LangItem::FromGenerator,
630 // `future::from_generator(generator)`:
631 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
634 /// Desugar `<expr>.await` into:
635 /// ```ignore (pseudo-rust)
636 /// match ::std::future::IntoFuture::into_future(<expr>) {
637 /// mut __awaitee => loop {
638 /// match unsafe { ::std::future::Future::poll(
639 /// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
640 /// ::std::future::get_context(task_context),
642 /// ::std::task::Poll::Ready(result) => break result,
643 /// ::std::task::Poll::Pending => {}
645 /// task_context = yield ();
649 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
650 let full_span = expr.span.to(dot_await_span);
651 match self.generator_kind {
652 Some(hir::GeneratorKind::Async(_)) => {}
653 Some(hir::GeneratorKind::Gen) | None => {
654 self.tcx.sess.emit_err(AwaitOnlyInAsyncFnAndBlocks {
656 item_span: self.current_item,
660 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
661 let gen_future_span = self.mark_span_with_reason(
662 DesugaringKind::Await,
664 self.allow_gen_future.clone(),
666 let expr = self.lower_expr_mut(expr);
667 let expr_hir_id = expr.hir_id;
669 // Note that the name of this binding must not be changed to something else because
670 // debuggers and debugger extensions expect it to be called `__awaitee`. They use
671 // this name to identify what is being awaited by a suspended async functions.
672 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
673 let (awaitee_pat, awaitee_pat_hid) =
674 self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::MUT);
676 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
679 // ::std::future::Future::poll(
680 // ::std::pin::Pin::new_unchecked(&mut __awaitee),
681 // ::std::future::get_context(task_context),
685 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
686 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
687 let task_context = if let Some(task_context_hid) = self.task_context {
688 self.expr_ident_mut(span, task_context_ident, task_context_hid)
690 // Use of `await` outside of an async context, we cannot use `task_context` here.
693 let new_unchecked = self.expr_call_lang_item_fn_mut(
695 hir::LangItem::PinNewUnchecked,
696 arena_vec![self; ref_mut_awaitee],
699 let get_context = self.expr_call_lang_item_fn_mut(
701 hir::LangItem::GetContext,
702 arena_vec![self; task_context],
705 let call = self.expr_call_lang_item_fn(
707 hir::LangItem::FuturePoll,
708 arena_vec![self; new_unchecked, get_context],
711 self.arena.alloc(self.expr_unsafe(call))
714 // `::std::task::Poll::Ready(result) => break result`
715 let loop_node_id = self.next_node_id();
716 let loop_hir_id = self.lower_node_id(loop_node_id);
718 let x_ident = Ident::with_dummy_span(sym::result);
719 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
720 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
721 let ready_field = self.single_pat_field(gen_future_span, x_pat);
722 let ready_pat = self.pat_lang_item_variant(
724 hir::LangItem::PollReady,
728 let break_x = self.with_loop_scope(loop_node_id, move |this| {
730 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
731 this.arena.alloc(this.expr(gen_future_span, expr_break, AttrVec::new()))
733 self.arm(ready_pat, break_x)
736 // `::std::task::Poll::Pending => {}`
738 let pending_pat = self.pat_lang_item_variant(
740 hir::LangItem::PollPending,
744 let empty_block = self.expr_block_empty(span);
745 self.arm(pending_pat, empty_block)
748 let inner_match_stmt = {
749 let match_expr = self.expr_match(
752 arena_vec![self; ready_arm, pending_arm],
753 hir::MatchSource::AwaitDesugar,
755 self.stmt_expr(span, match_expr)
758 // task_context = yield ();
760 let unit = self.expr_unit(span);
761 let yield_expr = self.expr(
763 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
766 let yield_expr = self.arena.alloc(yield_expr);
768 if let Some(task_context_hid) = self.task_context {
769 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
770 let assign = self.expr(
772 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
775 self.stmt_expr(span, assign)
777 // Use of `await` outside of an async context. Return `yield_expr` so that we can
778 // proceed with type checking.
779 self.stmt(span, hir::StmtKind::Semi(yield_expr))
783 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
786 let loop_expr = self.arena.alloc(hir::Expr {
788 kind: hir::ExprKind::Loop(
791 hir::LoopSource::Loop,
792 self.lower_span(span),
794 span: self.lower_span(span),
797 // mut __awaitee => loop { ... }
798 let awaitee_arm = self.arm(awaitee_pat, loop_expr);
800 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
801 let into_future_span = self.mark_span_with_reason(
802 DesugaringKind::Await,
804 self.allow_into_future.clone(),
806 let into_future_expr = self.expr_call_lang_item_fn(
808 hir::LangItem::IntoFutureIntoFuture,
809 arena_vec![self; expr],
813 // match <into_future_expr> {
814 // mut __awaitee => loop { .. }
816 hir::ExprKind::Match(
818 arena_vec![self; awaitee_arm],
819 hir::MatchSource::AwaitDesugar,
823 fn lower_expr_closure(
825 binder: &ClosureBinder,
826 capture_clause: CaptureBy,
828 movability: Movability,
832 ) -> hir::ExprKind<'hir> {
833 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
835 let (body_id, generator_option) = self.with_new_scopes(move |this| {
836 let prev = this.current_item;
837 this.current_item = Some(fn_decl_span);
838 let mut generator_kind = None;
839 let body_id = this.lower_fn_body(decl, |this| {
840 let e = this.lower_expr_mut(body);
841 generator_kind = this.generator_kind;
844 let generator_option =
845 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
846 this.current_item = prev;
847 (body_id, generator_option)
850 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
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 let c = self.arena.alloc(hir::Closure {
855 binder: binder_clause,
857 bound_generic_params,
860 fn_decl_span: self.lower_span(fn_decl_span),
861 movability: generator_option,
864 hir::ExprKind::Closure(c)
867 fn generator_movability_for_fn(
871 generator_kind: Option<hir::GeneratorKind>,
872 movability: Movability,
873 ) -> Option<hir::Movability> {
874 match generator_kind {
875 Some(hir::GeneratorKind::Gen) => {
876 if decl.inputs.len() > 1 {
877 self.tcx.sess.emit_err(GeneratorTooManyParameters { fn_decl_span });
881 Some(hir::GeneratorKind::Async(_)) => {
882 panic!("non-`async` closure body turned `async` during lowering");
885 if movability == Movability::Static {
886 self.tcx.sess.emit_err(ClosureCannotBeStatic { fn_decl_span });
893 fn lower_closure_binder<'c>(
895 binder: &'c ClosureBinder,
896 ) -> (hir::ClosureBinder, &'c [GenericParam]) {
897 let (binder, params) = match binder {
898 ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]),
899 &ClosureBinder::For { span, ref generic_params } => {
900 let span = self.lower_span(span);
901 (hir::ClosureBinder::For { span }, &**generic_params)
908 fn lower_expr_async_closure(
910 binder: &ClosureBinder,
911 capture_clause: CaptureBy,
913 inner_closure_id: NodeId,
917 ) -> hir::ExprKind<'hir> {
918 if let &ClosureBinder::For { span, .. } = binder {
919 self.tcx.sess.emit_err(NotSupportedForLifetimeBinderAsyncClosure { span });
922 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
925 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
927 let body = self.with_new_scopes(|this| {
928 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
929 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
930 this.tcx.sess.emit_err(AsyncNonMoveClosureNotSupported { fn_decl_span });
933 // Transform `async |x: u8| -> X { ... }` into
934 // `|x: u8| future_from_generator(|| -> X { ... })`.
935 let body_id = this.lower_fn_body(&outer_decl, |this| {
937 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
938 let async_body = this.make_async_expr(
943 hir::AsyncGeneratorKind::Closure,
944 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
946 this.expr(fn_decl_span, async_body, AttrVec::new())
951 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
953 // We need to lower the declaration outside the new scope, because we
954 // have to conserve the state of being inside a loop condition for the
955 // closure argument types.
956 let fn_decl = self.lower_fn_decl(&outer_decl, None, FnDeclKind::Closure, None);
958 let c = self.arena.alloc(hir::Closure {
959 binder: binder_clause,
961 bound_generic_params,
964 fn_decl_span: self.lower_span(fn_decl_span),
967 hir::ExprKind::Closure(c)
970 /// Destructure the LHS of complex assignments.
971 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
972 fn lower_expr_assign(
978 ) -> hir::ExprKind<'hir> {
979 // Return early in case of an ordinary assignment.
980 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
983 | ExprKind::Struct(..)
985 | ExprKind::Underscore => false,
986 // Check for tuple struct constructor.
987 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
988 ExprKind::Paren(e) => {
990 // We special-case `(..)` for consistency with patterns.
991 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
992 _ => is_ordinary(lower_ctx, e),
998 if is_ordinary(self, lhs) {
999 return hir::ExprKind::Assign(
1000 self.lower_expr(lhs),
1001 self.lower_expr(rhs),
1002 self.lower_span(eq_sign_span),
1006 let mut assignments = vec![];
1008 // The LHS becomes a pattern: `(lhs1, lhs2)`.
1009 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1010 let rhs = self.lower_expr(rhs);
1012 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1013 let destructure_let = self.stmt_let_pat(
1018 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
1021 // `a = lhs1; b = lhs2;`.
1024 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1026 // Wrap everything in a block.
1027 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1030 /// If the given expression is a path to a tuple struct, returns that path.
1031 /// It is not a complete check, but just tries to reject most paths early
1032 /// if they are not tuple structs.
1033 /// Type checking will take care of the full validation later.
1034 fn extract_tuple_struct_path<'a>(
1037 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1038 if let ExprKind::Path(qself, path) = &expr.kind {
1039 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1040 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1041 if partial_res.unresolved_segments() == 0
1042 && !partial_res.base_res().expected_in_tuple_struct_pat()
1047 return Some((qself, path));
1052 /// If the given expression is a path to a unit struct, returns that path.
1053 /// It is not a complete check, but just tries to reject most paths early
1054 /// if they are not unit structs.
1055 /// Type checking will take care of the full validation later.
1056 fn extract_unit_struct_path<'a>(
1059 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1060 if let ExprKind::Path(qself, path) = &expr.kind {
1061 // Does the path resolve to something disallowed in a unit struct/variant pattern?
1062 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1063 if partial_res.unresolved_segments() == 0
1064 && !partial_res.base_res().expected_in_unit_struct_pat()
1069 return Some((qself, path));
1074 /// Convert the LHS of a destructuring assignment to a pattern.
1075 /// Each sub-assignment is recorded in `assignments`.
1076 fn destructure_assign(
1080 assignments: &mut Vec<hir::Stmt<'hir>>,
1081 ) -> &'hir hir::Pat<'hir> {
1082 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1085 fn destructure_assign_mut(
1089 assignments: &mut Vec<hir::Stmt<'hir>>,
1090 ) -> hir::Pat<'hir> {
1092 // Underscore pattern.
1093 ExprKind::Underscore => {
1094 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1097 ExprKind::Array(elements) => {
1099 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1100 let slice_pat = if let Some((i, span)) = rest {
1101 let (before, after) = pats.split_at(i);
1102 hir::PatKind::Slice(
1104 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1108 hir::PatKind::Slice(pats, None, &[])
1110 return self.pat_without_dbm(lhs.span, slice_pat);
1113 ExprKind::Call(callee, args) => {
1114 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1115 let (pats, rest) = self.destructure_sequence(
1117 "tuple struct or variant",
1121 let qpath = self.lower_qpath(
1125 ParamMode::Optional,
1126 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1128 // Destructure like a tuple struct.
1129 let tuple_struct_pat =
1130 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1131 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1134 // Unit structs and enum variants.
1135 ExprKind::Path(..) => {
1136 if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1137 let qpath = self.lower_qpath(
1141 ParamMode::Optional,
1142 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1144 // Destructure like a unit struct.
1145 let unit_struct_pat = hir::PatKind::Path(qpath);
1146 return self.pat_without_dbm(lhs.span, unit_struct_pat);
1150 ExprKind::Struct(se) => {
1151 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1152 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1154 hir_id: self.next_id(),
1155 ident: self.lower_ident(f.ident),
1157 is_shorthand: f.is_shorthand,
1158 span: self.lower_span(f.span),
1161 let qpath = self.lower_qpath(
1165 ParamMode::Optional,
1166 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1168 let fields_omitted = match &se.rest {
1169 StructRest::Base(e) => {
1170 self.tcx.sess.emit_err(FunctionalRecordUpdateDestructuringAssignemnt {
1175 StructRest::Rest(_) => true,
1176 StructRest::None => false,
1178 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1179 return self.pat_without_dbm(lhs.span, struct_pat);
1182 ExprKind::Tup(elements) => {
1184 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1185 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1186 return self.pat_without_dbm(lhs.span, tuple_pat);
1188 ExprKind::Paren(e) => {
1189 // We special-case `(..)` for consistency with patterns.
1190 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1191 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1192 return self.pat_without_dbm(lhs.span, tuple_pat);
1194 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1199 // Treat all other cases as normal lvalue.
1200 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1201 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1202 let ident = self.expr_ident(lhs.span, ident, binding);
1204 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1205 let expr = self.expr(lhs.span, assign, AttrVec::new());
1206 assignments.push(self.stmt_expr(lhs.span, expr));
1210 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1211 /// Such a sequence occurs in a tuple (struct)/slice.
1212 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1214 /// Each sub-assignment is recorded in `assignments`.
1215 fn destructure_sequence(
1217 elements: &[AstP<Expr>],
1220 assignments: &mut Vec<hir::Stmt<'hir>>,
1221 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1222 let mut rest = None;
1224 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1225 // Check for `..` pattern.
1226 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1227 if let Some((_, prev_span)) = rest {
1228 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1230 rest = Some((i, e.span));
1234 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1240 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1241 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1242 let e1 = self.lower_expr_mut(e1);
1243 let e2 = self.lower_expr_mut(e2);
1245 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1247 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), AttrVec::new()));
1248 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1251 fn lower_expr_range(
1257 ) -> hir::ExprKind<'hir> {
1258 use rustc_ast::RangeLimits::*;
1260 let lang_item = match (e1, e2, lims) {
1261 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1262 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1263 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1264 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1265 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1266 (Some(..), Some(..), Closed) => unreachable!(),
1267 (start, None, Closed) => {
1268 self.tcx.sess.emit_err(InclusiveRangeWithNoEnd { span });
1270 Some(..) => hir::LangItem::RangeFrom,
1271 None => hir::LangItem::RangeFull,
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> {
1360 let hir_id = self.lower_node_id(f.id);
1361 self.lower_attrs(hir_id, &f.attrs);
1364 ident: self.lower_ident(f.ident),
1365 expr: self.lower_expr(&f.expr),
1366 span: self.lower_span(f.span),
1367 is_shorthand: f.is_shorthand,
1371 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1372 match self.generator_kind {
1373 Some(hir::GeneratorKind::Gen) => {}
1374 Some(hir::GeneratorKind::Async(_)) => {
1375 self.tcx.sess.emit_err(AsyncGeneratorsNotSupported { span });
1377 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1381 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1383 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1386 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1387 /// ```ignore (pseudo-rust)
1389 /// let result = match IntoIterator::into_iter(<head>) {
1391 /// [opt_ident]: loop {
1392 /// match Iterator::next(&mut iter) {
1394 /// Some(<pat>) => <body>,
1408 opt_label: Option<Label>,
1409 ) -> hir::Expr<'hir> {
1410 let head = self.lower_expr_mut(head);
1411 let pat = self.lower_pat(pat);
1413 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1414 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1415 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1420 self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span, AttrVec::new()));
1421 let pat = self.pat_none(for_span);
1422 self.arm(pat, break_expr)
1425 // Some(<pat>) => <body>,
1427 let some_pat = self.pat_some(pat_span, pat);
1428 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1429 let body_expr = self.arena.alloc(self.expr_block(body_block, AttrVec::new()));
1430 self.arm(some_pat, body_expr)
1434 let iter = Ident::with_dummy_span(sym::iter);
1435 let (iter_pat, iter_pat_nid) =
1436 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::MUT);
1438 // `match Iterator::next(&mut iter) { ... }`
1440 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1441 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1442 let next_expr = self.expr_call_lang_item_fn(
1444 hir::LangItem::IteratorNext,
1445 arena_vec![self; ref_mut_iter],
1448 let arms = arena_vec![self; none_arm, some_arm];
1450 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1452 let match_stmt = self.stmt_expr(for_span, match_expr);
1454 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1456 // `[opt_ident]: loop { ... }`
1457 let kind = hir::ExprKind::Loop(
1459 self.lower_label(opt_label),
1460 hir::LoopSource::ForLoop,
1461 self.lower_span(for_span.with_hi(head.span.hi())),
1464 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1466 // `mut iter => { ... }`
1467 let iter_arm = self.arm(iter_pat, loop_expr);
1469 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1470 let into_iter_expr = {
1471 self.expr_call_lang_item_fn(
1473 hir::LangItem::IntoIterIntoIter,
1474 arena_vec![self; head],
1479 let match_expr = self.arena.alloc(self.expr_match(
1482 arena_vec![self; iter_arm],
1483 hir::MatchSource::ForLoopDesugar,
1486 // This is effectively `{ let _result = ...; _result }`.
1487 // The construct was introduced in #21984 and is necessary to make sure that
1488 // temporaries in the `head` expression are dropped and do not leak to the
1489 // surrounding scope of the `match` since the `match` is not a terminating scope.
1491 // Also, add the attributes to the outer returned expr node.
1492 self.expr_drop_temps_mut(for_span, match_expr, e.attrs.clone())
1495 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1496 /// ```ignore (pseudo-rust)
1497 /// match Try::branch(<expr>) {
1498 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1499 /// ControlFlow::Break(residual) =>
1500 /// #[allow(unreachable_code)]
1501 /// // If there is an enclosing `try {...}`:
1502 /// break 'catch_target Try::from_residual(residual),
1504 /// return Try::from_residual(residual),
1507 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1508 let unstable_span = self.mark_span_with_reason(
1509 DesugaringKind::QuestionMark,
1511 self.allow_try_trait.clone(),
1513 let try_span = self.tcx.sess.source_map().end_point(span);
1514 let try_span = self.mark_span_with_reason(
1515 DesugaringKind::QuestionMark,
1517 self.allow_try_trait.clone(),
1520 // `Try::branch(<expr>)`
1523 let sub_expr = self.lower_expr_mut(sub_expr);
1525 self.expr_call_lang_item_fn(
1527 hir::LangItem::TryTraitBranch,
1528 arena_vec![self; sub_expr],
1533 // `#[allow(unreachable_code)]`
1535 // `allow(unreachable_code)`
1537 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1538 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1539 let uc_nested = attr::mk_nested_word_item(uc_ident);
1540 attr::mk_list_item(allow_ident, vec![uc_nested])
1542 attr::mk_attr_outer(allow)
1544 let attrs: AttrVec = thin_vec![attr];
1546 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1547 let continue_arm = {
1548 let val_ident = Ident::with_dummy_span(sym::val);
1549 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1550 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1556 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1557 self.arm(continue_pat, val_expr)
1560 // `ControlFlow::Break(residual) =>
1561 // #[allow(unreachable_code)]
1562 // return Try::from_residual(residual),`
1564 let residual_ident = Ident::with_dummy_span(sym::residual);
1565 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1566 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1567 let from_residual_expr = self.wrap_in_try_constructor(
1568 hir::LangItem::TryTraitFromResidual,
1570 self.arena.alloc(residual_expr),
1573 let ret_expr = if let Some(catch_node) = self.catch_scope {
1574 let target_id = Ok(self.lower_node_id(catch_node));
1575 self.arena.alloc(self.expr(
1577 hir::ExprKind::Break(
1578 hir::Destination { label: None, target_id },
1579 Some(from_residual_expr),
1584 self.arena.alloc(self.expr(
1586 hir::ExprKind::Ret(Some(from_residual_expr)),
1591 let break_pat = self.pat_cf_break(try_span, residual_local);
1592 self.arm(break_pat, ret_expr)
1595 hir::ExprKind::Match(
1597 arena_vec![self; break_arm, continue_arm],
1598 hir::MatchSource::TryDesugar,
1602 /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into:
1604 /// // If there is an enclosing `try {...}`:
1605 /// break 'catch_target FromResidual::from_residual(Yeet(residual)),
1607 /// return FromResidual::from_residual(Yeet(residual)),
1609 /// But to simplify this, there's a `from_yeet` lang item function which
1610 /// handles the combined `FromResidual::from_residual(Yeet(residual))`.
1611 fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1612 // The expression (if present) or `()` otherwise.
1613 let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
1614 (sub_expr.span, self.lower_expr(sub_expr))
1616 (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
1619 let unstable_span = self.mark_span_with_reason(
1620 DesugaringKind::YeetExpr,
1622 self.allow_try_trait.clone(),
1625 let from_yeet_expr = self.wrap_in_try_constructor(
1626 hir::LangItem::TryTraitFromYeet,
1632 if let Some(catch_node) = self.catch_scope {
1633 let target_id = Ok(self.lower_node_id(catch_node));
1634 hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
1636 hir::ExprKind::Ret(Some(from_yeet_expr))
1640 // =========================================================================
1641 // Helper methods for building HIR.
1642 // =========================================================================
1644 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1646 /// In terms of drop order, it has the same effect as wrapping `expr` in
1647 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1649 /// The drop order can be important in e.g. `if expr { .. }`.
1650 pub(super) fn expr_drop_temps(
1653 expr: &'hir hir::Expr<'hir>,
1655 ) -> &'hir hir::Expr<'hir> {
1656 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1659 pub(super) fn expr_drop_temps_mut(
1662 expr: &'hir hir::Expr<'hir>,
1664 ) -> hir::Expr<'hir> {
1665 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1671 arg: &'hir hir::Expr<'hir>,
1672 arms: &'hir [hir::Arm<'hir>],
1673 source: hir::MatchSource,
1674 ) -> hir::Expr<'hir> {
1675 self.expr(span, hir::ExprKind::Match(arg, arms, source), AttrVec::new())
1678 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1679 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1680 self.expr(span, expr_break, attrs)
1683 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1684 let expr_break = self.expr_break(span, attrs);
1685 self.arena.alloc(expr_break)
1688 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1691 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1696 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1697 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), AttrVec::new()))
1703 e: &'hir hir::Expr<'hir>,
1704 args: &'hir [hir::Expr<'hir>],
1705 ) -> hir::Expr<'hir> {
1706 self.expr(span, hir::ExprKind::Call(e, args), AttrVec::new())
1712 e: &'hir hir::Expr<'hir>,
1713 args: &'hir [hir::Expr<'hir>],
1714 ) -> &'hir hir::Expr<'hir> {
1715 self.arena.alloc(self.expr_call_mut(span, e, args))
1718 fn expr_call_lang_item_fn_mut(
1721 lang_item: hir::LangItem,
1722 args: &'hir [hir::Expr<'hir>],
1723 hir_id: Option<hir::HirId>,
1724 ) -> hir::Expr<'hir> {
1726 self.arena.alloc(self.expr_lang_item_path(span, lang_item, AttrVec::new(), hir_id));
1727 self.expr_call_mut(span, path, args)
1730 fn expr_call_lang_item_fn(
1733 lang_item: hir::LangItem,
1734 args: &'hir [hir::Expr<'hir>],
1735 hir_id: Option<hir::HirId>,
1736 ) -> &'hir hir::Expr<'hir> {
1737 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1740 fn expr_lang_item_path(
1743 lang_item: hir::LangItem,
1745 hir_id: Option<hir::HirId>,
1746 ) -> hir::Expr<'hir> {
1749 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1754 pub(super) fn expr_ident(
1758 binding: hir::HirId,
1759 ) -> &'hir hir::Expr<'hir> {
1760 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1763 pub(super) fn expr_ident_mut(
1767 binding: hir::HirId,
1768 ) -> hir::Expr<'hir> {
1769 self.expr_ident_with_attrs(sp, ident, binding, AttrVec::new())
1772 fn expr_ident_with_attrs(
1776 binding: hir::HirId,
1778 ) -> hir::Expr<'hir> {
1779 let hir_id = self.next_id();
1780 let res = Res::Local(binding);
1781 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1783 self.arena.alloc(hir::Path {
1784 span: self.lower_span(span),
1786 segments: arena_vec![self; hir::PathSegment::new(ident, hir_id, res)],
1790 self.expr(span, expr_path, attrs)
1793 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1794 let hir_id = self.next_id();
1795 let span = expr.span;
1798 hir::ExprKind::Block(
1799 self.arena.alloc(hir::Block {
1803 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1804 span: self.lower_span(span),
1805 targeted_by_break: false,
1813 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1814 let blk = self.block_all(span, &[], None);
1815 let expr = self.expr_block(blk, AttrVec::new());
1816 self.arena.alloc(expr)
1819 pub(super) fn expr_block(
1821 b: &'hir hir::Block<'hir>,
1823 ) -> hir::Expr<'hir> {
1824 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1830 kind: hir::ExprKind<'hir>,
1832 ) -> hir::Expr<'hir> {
1833 let hir_id = self.next_id();
1834 self.lower_attrs(hir_id, &attrs);
1835 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1841 expr: &'hir hir::Expr<'hir>,
1843 ) -> hir::ExprField<'hir> {
1845 hir_id: self.next_id(),
1847 span: self.lower_span(span),
1849 is_shorthand: false,
1853 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1855 hir_id: self.next_id(),
1858 span: self.lower_span(expr.span),