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 dot_await_span = if expr.span.hi() < e.span.hi() {
150 let span_with_whitespace = self
154 .span_extend_while(expr.span, char::is_whitespace)
155 .unwrap_or(expr.span);
156 span_with_whitespace.shrink_to_hi().with_hi(e.span.hi())
158 // this is a recovered `await expr`
161 self.lower_expr_await(dot_await_span, expr)
172 if let Async::Yes { closure_id, .. } = asyncness {
173 self.lower_expr_async_closure(
183 self.lower_expr_closure(
194 ExprKind::Block(ref blk, opt_label) => {
195 let opt_label = self.lower_label(opt_label);
196 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
198 ExprKind::Assign(ref el, ref er, span) => {
199 self.lower_expr_assign(el, er, span, e.span)
201 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
202 self.lower_binop(op),
206 ExprKind::Field(ref el, ident) => {
207 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
209 ExprKind::Index(ref el, ref er) => {
210 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
212 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
213 self.lower_expr_range_closed(e.span, e1, e2)
215 ExprKind::Range(ref e1, ref e2, lims) => {
216 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
218 ExprKind::Underscore => {
219 self.tcx.sess.emit_err(UnderscoreExprLhsAssign { span: e.span });
222 ExprKind::Path(ref qself, ref path) => {
223 let qpath = self.lower_qpath(
228 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
230 hir::ExprKind::Path(qpath)
232 ExprKind::Break(opt_label, ref opt_expr) => {
233 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
234 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
236 ExprKind::Continue(opt_label) => {
237 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
239 ExprKind::Ret(ref e) => {
240 let e = e.as_ref().map(|x| self.lower_expr(x));
241 hir::ExprKind::Ret(e)
243 ExprKind::Yeet(ref sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
244 ExprKind::InlineAsm(ref asm) => {
245 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
247 ExprKind::Struct(ref se) => {
248 let rest = match &se.rest {
249 StructRest::Base(e) => Some(self.lower_expr(e)),
250 StructRest::Rest(sp) => {
251 self.tcx.sess.emit_err(BaseExpressionDoubleDot { span: *sp });
252 Some(&*self.arena.alloc(self.expr_err(*sp)))
254 StructRest::None => None,
256 hir::ExprKind::Struct(
257 self.arena.alloc(self.lower_qpath(
262 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
265 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
269 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
270 ExprKind::Err => hir::ExprKind::Err,
271 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
272 ExprKind::Paren(ref ex) => {
273 let mut ex = self.lower_expr_mut(ex);
274 // Include parens in span, but only if it is a super-span.
275 if e.span.contains(ex.span) {
276 ex.span = self.lower_span(e.span);
278 // Merge attributes into the inner expression.
279 if !e.attrs.is_empty() {
281 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
284 &*self.arena.alloc_from_iter(
287 .map(|a| self.lower_attr(a))
288 .chain(old_attrs.iter().cloned()),
295 // Desugar `ExprForLoop`
296 // from: `[opt_ident]: for <pat> in <head> <body>`
297 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
298 return self.lower_expr_for(e, pat, head, body, opt_label);
300 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
303 let hir_id = self.lower_node_id(e.id);
304 self.lower_attrs(hir_id, &e.attrs);
305 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
309 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
311 UnOp::Deref => hir::UnOp::Deref,
312 UnOp::Not => hir::UnOp::Not,
313 UnOp::Neg => hir::UnOp::Neg,
317 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
320 BinOpKind::Add => hir::BinOpKind::Add,
321 BinOpKind::Sub => hir::BinOpKind::Sub,
322 BinOpKind::Mul => hir::BinOpKind::Mul,
323 BinOpKind::Div => hir::BinOpKind::Div,
324 BinOpKind::Rem => hir::BinOpKind::Rem,
325 BinOpKind::And => hir::BinOpKind::And,
326 BinOpKind::Or => hir::BinOpKind::Or,
327 BinOpKind::BitXor => hir::BinOpKind::BitXor,
328 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
329 BinOpKind::BitOr => hir::BinOpKind::BitOr,
330 BinOpKind::Shl => hir::BinOpKind::Shl,
331 BinOpKind::Shr => hir::BinOpKind::Shr,
332 BinOpKind::Eq => hir::BinOpKind::Eq,
333 BinOpKind::Lt => hir::BinOpKind::Lt,
334 BinOpKind::Le => hir::BinOpKind::Le,
335 BinOpKind::Ne => hir::BinOpKind::Ne,
336 BinOpKind::Ge => hir::BinOpKind::Ge,
337 BinOpKind::Gt => hir::BinOpKind::Gt,
339 span: self.lower_span(b.span),
343 fn lower_legacy_const_generics(
346 args: Vec<AstP<Expr>>,
347 legacy_args_idx: &[usize],
348 ) -> hir::ExprKind<'hir> {
349 let ExprKind::Path(None, ref mut path) = f.kind else {
353 // Split the arguments into const generics and normal arguments
354 let mut real_args = vec![];
355 let mut generic_args = vec![];
356 for (idx, arg) in args.into_iter().enumerate() {
357 if legacy_args_idx.contains(&idx) {
358 let parent_def_id = self.current_hir_id_owner;
359 let node_id = self.next_node_id();
361 // Add a definition for the in-band const def.
362 self.create_def(parent_def_id.def_id, node_id, DefPathData::AnonConst);
364 let anon_const = AnonConst { id: node_id, value: arg };
365 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
371 // Add generic args to the last element of the path.
372 let last_segment = path.segments.last_mut().unwrap();
373 assert!(last_segment.args.is_none());
374 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
379 // Now lower everything as normal.
380 let f = self.lower_expr(&f);
381 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
388 else_opt: Option<&Expr>,
389 ) -> hir::ExprKind<'hir> {
390 let lowered_cond = self.lower_cond(cond);
391 let then_expr = self.lower_block_expr(then);
392 if let Some(rslt) = else_opt {
395 self.arena.alloc(then_expr),
396 Some(self.lower_expr(rslt)),
399 hir::ExprKind::If(lowered_cond, self.arena.alloc(then_expr), None)
403 // Lowers a condition (i.e. `cond` in `if cond` or `while cond`), wrapping it in a terminating scope
404 // so that temporaries created in the condition don't live beyond it.
405 fn lower_cond(&mut self, cond: &Expr) -> &'hir hir::Expr<'hir> {
406 fn has_let_expr(expr: &Expr) -> bool {
408 ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
409 ExprKind::Let(..) => true,
414 // We have to take special care for `let` exprs in the condition, e.g. in
415 // `if let pat = val` or `if foo && let pat = val`, as we _do_ want `val` to live beyond the
416 // condition in this case.
418 // In order to mantain the drop behavior for the non `let` parts of the condition,
419 // we still wrap them in terminating scopes, e.g. `if foo && let pat = val` essentially
420 // gets transformed into `if { let _t = foo; _t } && let pat = val`
422 ExprKind::Binary(op @ Spanned { node: ast::BinOpKind::And, .. }, lhs, rhs)
423 if has_let_expr(cond) =>
425 let op = self.lower_binop(*op);
426 let lhs = self.lower_cond(lhs);
427 let rhs = self.lower_cond(rhs);
429 self.arena.alloc(self.expr(
431 hir::ExprKind::Binary(op, lhs, rhs),
435 ExprKind::Let(..) => self.lower_expr(cond),
437 let cond = self.lower_expr(cond);
438 let reason = DesugaringKind::CondTemporary;
439 let span_block = self.mark_span_with_reason(reason, cond.span, None);
440 self.expr_drop_temps(span_block, cond, AttrVec::new())
445 // We desugar: `'label: while $cond $body` into:
449 // if { let _t = $cond; _t } {
458 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
459 // to preserve drop semantics since `while $cond { ... }` does not
460 // let temporaries live outside of `cond`.
461 fn lower_expr_while_in_loop_scope(
466 opt_label: Option<Label>,
467 ) -> hir::ExprKind<'hir> {
468 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_cond(cond));
469 let then = self.lower_block_expr(body);
470 let expr_break = self.expr_break(span, AttrVec::new());
471 let stmt_break = self.stmt_expr(span, expr_break);
472 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
473 let else_expr = self.arena.alloc(self.expr_block(else_blk, AttrVec::new()));
474 let if_kind = hir::ExprKind::If(lowered_cond, self.arena.alloc(then), Some(else_expr));
475 let if_expr = self.expr(span, if_kind, AttrVec::new());
476 let block = self.block_expr(self.arena.alloc(if_expr));
477 let span = self.lower_span(span.with_hi(cond.span.hi()));
478 let opt_label = self.lower_label(opt_label);
479 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
482 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
483 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
484 /// and save the block id to use it as a break target for desugaring of the `?` operator.
485 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
486 self.with_catch_scope(body.id, |this| {
487 let mut block = this.lower_block_noalloc(body, true);
489 // Final expression of the block (if present) or `()` with span at the end of block
490 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
492 this.mark_span_with_reason(
493 DesugaringKind::TryBlock,
495 this.allow_try_trait.clone(),
500 let try_span = this.mark_span_with_reason(
501 DesugaringKind::TryBlock,
502 this.tcx.sess.source_map().end_point(body.span),
503 this.allow_try_trait.clone(),
506 (try_span, this.expr_unit(try_span))
509 let ok_wrapped_span =
510 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
512 // `::std::ops::Try::from_output($tail_expr)`
513 block.expr = Some(this.wrap_in_try_constructor(
514 hir::LangItem::TryTraitFromOutput,
520 hir::ExprKind::Block(this.arena.alloc(block), None)
524 fn wrap_in_try_constructor(
526 lang_item: hir::LangItem,
528 expr: &'hir hir::Expr<'hir>,
530 ) -> &'hir hir::Expr<'hir> {
531 let constructor = self.arena.alloc(self.expr_lang_item_path(
537 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
540 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
541 let pat = self.lower_pat(&arm.pat);
542 let guard = arm.guard.as_ref().map(|cond| {
543 if let ExprKind::Let(ref pat, ref scrutinee, span) = cond.kind {
544 hir::Guard::IfLet(self.arena.alloc(hir::Let {
545 hir_id: self.next_id(),
546 span: self.lower_span(span),
547 pat: self.lower_pat(pat),
549 init: self.lower_expr(scrutinee),
552 hir::Guard::If(self.lower_expr(cond))
555 let hir_id = self.next_id();
556 self.lower_attrs(hir_id, &arm.attrs);
561 body: self.lower_expr(&arm.body),
562 span: self.lower_span(arm.span),
566 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
571 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
575 pub(super) fn make_async_expr(
577 capture_clause: CaptureBy,
578 closure_node_id: NodeId,
579 ret_ty: Option<AstP<Ty>>,
581 async_gen_kind: hir::AsyncGeneratorKind,
582 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
583 ) -> hir::ExprKind<'hir> {
584 let output = match ret_ty {
585 Some(ty) => hir::FnRetTy::Return(
586 self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock)),
588 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
591 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
592 // fully constrained by `future::from_generator`.
593 let input_ty = hir::Ty {
594 hir_id: self.next_id(),
595 kind: hir::TyKind::Infer,
596 span: self.lower_span(span),
599 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
600 let fn_decl = self.arena.alloc(hir::FnDecl {
601 inputs: arena_vec![self; input_ty],
604 implicit_self: hir::ImplicitSelfKind::None,
607 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
608 let (pat, task_context_hid) = self.pat_ident_binding_mode(
610 Ident::with_dummy_span(sym::_task_context),
611 hir::BindingAnnotation::MUT,
613 let param = hir::Param {
614 hir_id: self.next_id(),
616 ty_span: self.lower_span(span),
617 span: self.lower_span(span),
619 let params = arena_vec![self; param];
621 let body = self.lower_body(move |this| {
622 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
624 let old_ctx = this.task_context;
625 this.task_context = Some(task_context_hid);
626 let res = body(this);
627 this.task_context = old_ctx;
631 // `static |_task_context| -> <ret_ty> { body }`:
632 let generator_kind = {
633 let c = self.arena.alloc(hir::Closure {
634 binder: hir::ClosureBinder::Default,
636 bound_generic_params: &[],
639 fn_decl_span: self.lower_span(span),
640 movability: Some(hir::Movability::Static),
643 hir::ExprKind::Closure(c)
645 let generator = hir::Expr {
646 hir_id: self.lower_node_id(closure_node_id),
647 kind: generator_kind,
648 span: self.lower_span(span),
651 // `future::from_generator`:
653 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
654 let gen_future = self.expr_lang_item_path(
656 hir::LangItem::FromGenerator,
661 // `future::from_generator(generator)`:
662 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
665 /// Desugar `<expr>.await` into:
666 /// ```ignore (pseudo-rust)
667 /// match ::std::future::IntoFuture::into_future(<expr>) {
668 /// mut __awaitee => loop {
669 /// match unsafe { ::std::future::Future::poll(
670 /// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
671 /// ::std::future::get_context(task_context),
673 /// ::std::task::Poll::Ready(result) => break result,
674 /// ::std::task::Poll::Pending => {}
676 /// task_context = yield ();
680 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
681 let full_span = expr.span.to(dot_await_span);
682 match self.generator_kind {
683 Some(hir::GeneratorKind::Async(_)) => {}
684 Some(hir::GeneratorKind::Gen) | None => {
685 self.tcx.sess.emit_err(AwaitOnlyInAsyncFnAndBlocks {
687 item_span: self.current_item,
691 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
692 let gen_future_span = self.mark_span_with_reason(
693 DesugaringKind::Await,
695 self.allow_gen_future.clone(),
697 let expr = self.lower_expr_mut(expr);
698 let expr_hir_id = expr.hir_id;
700 // Note that the name of this binding must not be changed to something else because
701 // debuggers and debugger extensions expect it to be called `__awaitee`. They use
702 // this name to identify what is being awaited by a suspended async functions.
703 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
704 let (awaitee_pat, awaitee_pat_hid) =
705 self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::MUT);
707 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
710 // ::std::future::Future::poll(
711 // ::std::pin::Pin::new_unchecked(&mut __awaitee),
712 // ::std::future::get_context(task_context),
716 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
717 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
718 let task_context = if let Some(task_context_hid) = self.task_context {
719 self.expr_ident_mut(span, task_context_ident, task_context_hid)
721 // Use of `await` outside of an async context, we cannot use `task_context` here.
724 let new_unchecked = self.expr_call_lang_item_fn_mut(
726 hir::LangItem::PinNewUnchecked,
727 arena_vec![self; ref_mut_awaitee],
730 let get_context = self.expr_call_lang_item_fn_mut(
732 hir::LangItem::GetContext,
733 arena_vec![self; task_context],
736 let call = self.expr_call_lang_item_fn(
738 hir::LangItem::FuturePoll,
739 arena_vec![self; new_unchecked, get_context],
742 self.arena.alloc(self.expr_unsafe(call))
745 // `::std::task::Poll::Ready(result) => break result`
746 let loop_node_id = self.next_node_id();
747 let loop_hir_id = self.lower_node_id(loop_node_id);
749 let x_ident = Ident::with_dummy_span(sym::result);
750 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
751 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
752 let ready_field = self.single_pat_field(gen_future_span, x_pat);
753 let ready_pat = self.pat_lang_item_variant(
755 hir::LangItem::PollReady,
759 let break_x = self.with_loop_scope(loop_node_id, move |this| {
761 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
762 this.arena.alloc(this.expr(gen_future_span, expr_break, AttrVec::new()))
764 self.arm(ready_pat, break_x)
767 // `::std::task::Poll::Pending => {}`
769 let pending_pat = self.pat_lang_item_variant(
771 hir::LangItem::PollPending,
775 let empty_block = self.expr_block_empty(span);
776 self.arm(pending_pat, empty_block)
779 let inner_match_stmt = {
780 let match_expr = self.expr_match(
783 arena_vec![self; ready_arm, pending_arm],
784 hir::MatchSource::AwaitDesugar,
786 self.stmt_expr(span, match_expr)
789 // task_context = yield ();
791 let unit = self.expr_unit(span);
792 let yield_expr = self.expr(
794 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
797 let yield_expr = self.arena.alloc(yield_expr);
799 if let Some(task_context_hid) = self.task_context {
800 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
801 let assign = self.expr(
803 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
806 self.stmt_expr(span, assign)
808 // Use of `await` outside of an async context. Return `yield_expr` so that we can
809 // proceed with type checking.
810 self.stmt(span, hir::StmtKind::Semi(yield_expr))
814 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
817 let loop_expr = self.arena.alloc(hir::Expr {
819 kind: hir::ExprKind::Loop(
822 hir::LoopSource::Loop,
823 self.lower_span(span),
825 span: self.lower_span(span),
828 // mut __awaitee => loop { ... }
829 let awaitee_arm = self.arm(awaitee_pat, loop_expr);
831 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
832 let into_future_span = self.mark_span_with_reason(
833 DesugaringKind::Await,
835 self.allow_into_future.clone(),
837 let into_future_expr = self.expr_call_lang_item_fn(
839 hir::LangItem::IntoFutureIntoFuture,
840 arena_vec![self; expr],
844 // match <into_future_expr> {
845 // mut __awaitee => loop { .. }
847 hir::ExprKind::Match(
849 arena_vec![self; awaitee_arm],
850 hir::MatchSource::AwaitDesugar,
854 fn lower_expr_closure(
856 binder: &ClosureBinder,
857 capture_clause: CaptureBy,
859 movability: Movability,
863 ) -> hir::ExprKind<'hir> {
864 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
866 let (body_id, generator_option) = self.with_new_scopes(move |this| {
867 let prev = this.current_item;
868 this.current_item = Some(fn_decl_span);
869 let mut generator_kind = None;
870 let body_id = this.lower_fn_body(decl, |this| {
871 let e = this.lower_expr_mut(body);
872 generator_kind = this.generator_kind;
875 let generator_option =
876 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
877 this.current_item = prev;
878 (body_id, generator_option)
881 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
882 // Lower outside new scope to preserve `is_in_loop_condition`.
883 let fn_decl = self.lower_fn_decl(decl, None, fn_decl_span, FnDeclKind::Closure, None);
885 let c = self.arena.alloc(hir::Closure {
886 binder: binder_clause,
888 bound_generic_params,
891 fn_decl_span: self.lower_span(fn_decl_span),
892 movability: generator_option,
895 hir::ExprKind::Closure(c)
898 fn generator_movability_for_fn(
902 generator_kind: Option<hir::GeneratorKind>,
903 movability: Movability,
904 ) -> Option<hir::Movability> {
905 match generator_kind {
906 Some(hir::GeneratorKind::Gen) => {
907 if decl.inputs.len() > 1 {
908 self.tcx.sess.emit_err(GeneratorTooManyParameters { fn_decl_span });
912 Some(hir::GeneratorKind::Async(_)) => {
913 panic!("non-`async` closure body turned `async` during lowering");
916 if movability == Movability::Static {
917 self.tcx.sess.emit_err(ClosureCannotBeStatic { fn_decl_span });
924 fn lower_closure_binder<'c>(
926 binder: &'c ClosureBinder,
927 ) -> (hir::ClosureBinder, &'c [GenericParam]) {
928 let (binder, params) = match binder {
929 ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]),
930 &ClosureBinder::For { span, ref generic_params } => {
931 let span = self.lower_span(span);
932 (hir::ClosureBinder::For { span }, &**generic_params)
939 fn lower_expr_async_closure(
941 binder: &ClosureBinder,
942 capture_clause: CaptureBy,
944 inner_closure_id: NodeId,
948 ) -> hir::ExprKind<'hir> {
949 if let &ClosureBinder::For { span, .. } = binder {
950 self.tcx.sess.emit_err(NotSupportedForLifetimeBinderAsyncClosure { span });
953 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
956 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
958 let body = self.with_new_scopes(|this| {
959 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
960 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
961 this.tcx.sess.emit_err(AsyncNonMoveClosureNotSupported { fn_decl_span });
964 // Transform `async |x: u8| -> X { ... }` into
965 // `|x: u8| future_from_generator(|| -> X { ... })`.
966 let body_id = this.lower_fn_body(&outer_decl, |this| {
968 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
969 let async_body = this.make_async_expr(
974 hir::AsyncGeneratorKind::Closure,
975 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
977 this.expr(fn_decl_span, async_body, AttrVec::new())
982 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
983 // We need to lower the declaration outside the new scope, because we
984 // have to conserve the state of being inside a loop condition for the
985 // closure argument types.
987 self.lower_fn_decl(&outer_decl, None, fn_decl_span, FnDeclKind::Closure, None);
989 let c = self.arena.alloc(hir::Closure {
990 binder: binder_clause,
992 bound_generic_params,
995 fn_decl_span: self.lower_span(fn_decl_span),
998 hir::ExprKind::Closure(c)
1001 /// Destructure the LHS of complex assignments.
1002 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
1003 fn lower_expr_assign(
1009 ) -> hir::ExprKind<'hir> {
1010 // Return early in case of an ordinary assignment.
1011 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
1014 | ExprKind::Struct(..)
1016 | ExprKind::Underscore => false,
1017 // Check for tuple struct constructor.
1018 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
1019 ExprKind::Paren(e) => {
1021 // We special-case `(..)` for consistency with patterns.
1022 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
1023 _ => is_ordinary(lower_ctx, e),
1029 if is_ordinary(self, lhs) {
1030 return hir::ExprKind::Assign(
1031 self.lower_expr(lhs),
1032 self.lower_expr(rhs),
1033 self.lower_span(eq_sign_span),
1037 let mut assignments = vec![];
1039 // The LHS becomes a pattern: `(lhs1, lhs2)`.
1040 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1041 let rhs = self.lower_expr(rhs);
1043 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1044 let destructure_let = self.stmt_let_pat(
1049 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
1052 // `a = lhs1; b = lhs2;`.
1055 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1057 // Wrap everything in a block.
1058 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1061 /// If the given expression is a path to a tuple struct, returns that path.
1062 /// It is not a complete check, but just tries to reject most paths early
1063 /// if they are not tuple structs.
1064 /// Type checking will take care of the full validation later.
1065 fn extract_tuple_struct_path<'a>(
1068 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1069 if let ExprKind::Path(qself, path) = &expr.kind {
1070 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1071 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1072 if let Some(res) = partial_res.full_res() && !res.expected_in_tuple_struct_pat() {
1076 return Some((qself, path));
1081 /// If the given expression is a path to a unit struct, returns that path.
1082 /// It is not a complete check, but just tries to reject most paths early
1083 /// if they are not unit structs.
1084 /// Type checking will take care of the full validation later.
1085 fn extract_unit_struct_path<'a>(
1088 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1089 if let ExprKind::Path(qself, path) = &expr.kind {
1090 // Does the path resolve to something disallowed in a unit struct/variant pattern?
1091 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1092 if let Some(res) = partial_res.full_res() && !res.expected_in_unit_struct_pat() {
1096 return Some((qself, path));
1101 /// Convert the LHS of a destructuring assignment to a pattern.
1102 /// Each sub-assignment is recorded in `assignments`.
1103 fn destructure_assign(
1107 assignments: &mut Vec<hir::Stmt<'hir>>,
1108 ) -> &'hir hir::Pat<'hir> {
1109 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1112 fn destructure_assign_mut(
1116 assignments: &mut Vec<hir::Stmt<'hir>>,
1117 ) -> hir::Pat<'hir> {
1119 // Underscore pattern.
1120 ExprKind::Underscore => {
1121 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1124 ExprKind::Array(elements) => {
1126 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1127 let slice_pat = if let Some((i, span)) = rest {
1128 let (before, after) = pats.split_at(i);
1129 hir::PatKind::Slice(
1131 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1135 hir::PatKind::Slice(pats, None, &[])
1137 return self.pat_without_dbm(lhs.span, slice_pat);
1140 ExprKind::Call(callee, args) => {
1141 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1142 let (pats, rest) = self.destructure_sequence(
1144 "tuple struct or variant",
1148 let qpath = self.lower_qpath(
1152 ParamMode::Optional,
1153 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1155 // Destructure like a tuple struct.
1156 let tuple_struct_pat = hir::PatKind::TupleStruct(
1159 hir::DotDotPos::new(rest.map(|r| r.0)),
1161 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1164 // Unit structs and enum variants.
1165 ExprKind::Path(..) => {
1166 if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1167 let qpath = self.lower_qpath(
1171 ParamMode::Optional,
1172 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1174 // Destructure like a unit struct.
1175 let unit_struct_pat = hir::PatKind::Path(qpath);
1176 return self.pat_without_dbm(lhs.span, unit_struct_pat);
1180 ExprKind::Struct(se) => {
1181 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1182 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1184 hir_id: self.next_id(),
1185 ident: self.lower_ident(f.ident),
1187 is_shorthand: f.is_shorthand,
1188 span: self.lower_span(f.span),
1191 let qpath = self.lower_qpath(
1195 ParamMode::Optional,
1196 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1198 let fields_omitted = match &se.rest {
1199 StructRest::Base(e) => {
1200 self.tcx.sess.emit_err(FunctionalRecordUpdateDestructuringAssignemnt {
1205 StructRest::Rest(_) => true,
1206 StructRest::None => false,
1208 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1209 return self.pat_without_dbm(lhs.span, struct_pat);
1212 ExprKind::Tup(elements) => {
1214 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1215 let tuple_pat = hir::PatKind::Tuple(pats, hir::DotDotPos::new(rest.map(|r| r.0)));
1216 return self.pat_without_dbm(lhs.span, tuple_pat);
1218 ExprKind::Paren(e) => {
1219 // We special-case `(..)` for consistency with patterns.
1220 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1221 let tuple_pat = hir::PatKind::Tuple(&[], hir::DotDotPos::new(Some(0)));
1222 return self.pat_without_dbm(lhs.span, tuple_pat);
1224 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1229 // Treat all other cases as normal lvalue.
1230 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1231 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1232 let ident = self.expr_ident(lhs.span, ident, binding);
1234 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1235 let expr = self.expr(lhs.span, assign, AttrVec::new());
1236 assignments.push(self.stmt_expr(lhs.span, expr));
1240 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1241 /// Such a sequence occurs in a tuple (struct)/slice.
1242 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1244 /// Each sub-assignment is recorded in `assignments`.
1245 fn destructure_sequence(
1247 elements: &[AstP<Expr>],
1250 assignments: &mut Vec<hir::Stmt<'hir>>,
1251 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1252 let mut rest = None;
1254 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1255 // Check for `..` pattern.
1256 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1257 if let Some((_, prev_span)) = rest {
1258 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1260 rest = Some((i, e.span));
1264 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1270 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1271 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1272 let e1 = self.lower_expr_mut(e1);
1273 let e2 = self.lower_expr_mut(e2);
1275 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1277 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), AttrVec::new()));
1278 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1281 fn lower_expr_range(
1287 ) -> hir::ExprKind<'hir> {
1288 use rustc_ast::RangeLimits::*;
1290 let lang_item = match (e1, e2, lims) {
1291 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1292 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1293 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1294 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1295 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1296 (Some(..), Some(..), Closed) => unreachable!(),
1297 (start, None, Closed) => {
1298 self.tcx.sess.emit_err(InclusiveRangeWithNoEnd { span });
1300 Some(..) => hir::LangItem::RangeFrom,
1301 None => hir::LangItem::RangeFull,
1306 let fields = self.arena.alloc_from_iter(
1307 e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1309 let expr = self.lower_expr(&e);
1310 let ident = Ident::new(s, self.lower_span(e.span));
1311 self.expr_field(ident, expr, e.span)
1316 hir::ExprKind::Struct(
1317 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)),
1323 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1324 let label = opt_label?;
1325 Some(Label { ident: self.lower_ident(label.ident) })
1328 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1329 let target_id = match destination {
1331 if let Some(loop_id) = self.resolver.get_label_res(id) {
1332 Ok(self.lower_node_id(loop_id))
1334 Err(hir::LoopIdError::UnresolvedLabel)
1339 .map(|id| Ok(self.lower_node_id(id)))
1340 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1342 let label = self.lower_label(destination.map(|(_, label)| label));
1343 hir::Destination { label, target_id }
1346 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1347 if self.is_in_loop_condition && opt_label.is_none() {
1350 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1353 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1357 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1358 let old_scope = self.catch_scope.replace(catch_id);
1359 let result = f(self);
1360 self.catch_scope = old_scope;
1364 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1365 // We're no longer in the base loop's condition; we're in another loop.
1366 let was_in_loop_condition = self.is_in_loop_condition;
1367 self.is_in_loop_condition = false;
1369 let old_scope = self.loop_scope.replace(loop_id);
1370 let result = f(self);
1371 self.loop_scope = old_scope;
1373 self.is_in_loop_condition = was_in_loop_condition;
1378 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1379 let was_in_loop_condition = self.is_in_loop_condition;
1380 self.is_in_loop_condition = true;
1382 let result = f(self);
1384 self.is_in_loop_condition = was_in_loop_condition;
1389 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1390 let hir_id = self.lower_node_id(f.id);
1391 self.lower_attrs(hir_id, &f.attrs);
1394 ident: self.lower_ident(f.ident),
1395 expr: self.lower_expr(&f.expr),
1396 span: self.lower_span(f.span),
1397 is_shorthand: f.is_shorthand,
1401 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1402 match self.generator_kind {
1403 Some(hir::GeneratorKind::Gen) => {}
1404 Some(hir::GeneratorKind::Async(_)) => {
1405 self.tcx.sess.emit_err(AsyncGeneratorsNotSupported { span });
1407 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1411 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1413 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1416 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1417 /// ```ignore (pseudo-rust)
1419 /// let result = match IntoIterator::into_iter(<head>) {
1421 /// [opt_ident]: loop {
1422 /// match Iterator::next(&mut iter) {
1424 /// Some(<pat>) => <body>,
1438 opt_label: Option<Label>,
1439 ) -> hir::Expr<'hir> {
1440 let head = self.lower_expr_mut(head);
1441 let pat = self.lower_pat(pat);
1443 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1444 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1445 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1450 self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span, AttrVec::new()));
1451 let pat = self.pat_none(for_span);
1452 self.arm(pat, break_expr)
1455 // Some(<pat>) => <body>,
1457 let some_pat = self.pat_some(pat_span, pat);
1458 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1459 let body_expr = self.arena.alloc(self.expr_block(body_block, AttrVec::new()));
1460 self.arm(some_pat, body_expr)
1464 let iter = Ident::with_dummy_span(sym::iter);
1465 let (iter_pat, iter_pat_nid) =
1466 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::MUT);
1468 // `match Iterator::next(&mut iter) { ... }`
1470 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1471 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1472 let next_expr = self.expr_call_lang_item_fn(
1474 hir::LangItem::IteratorNext,
1475 arena_vec![self; ref_mut_iter],
1478 let arms = arena_vec![self; none_arm, some_arm];
1480 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1482 let match_stmt = self.stmt_expr(for_span, match_expr);
1484 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1486 // `[opt_ident]: loop { ... }`
1487 let kind = hir::ExprKind::Loop(
1489 self.lower_label(opt_label),
1490 hir::LoopSource::ForLoop,
1491 self.lower_span(for_span.with_hi(head.span.hi())),
1494 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1496 // `mut iter => { ... }`
1497 let iter_arm = self.arm(iter_pat, loop_expr);
1499 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1500 let into_iter_expr = {
1501 self.expr_call_lang_item_fn(
1503 hir::LangItem::IntoIterIntoIter,
1504 arena_vec![self; head],
1509 let match_expr = self.arena.alloc(self.expr_match(
1512 arena_vec![self; iter_arm],
1513 hir::MatchSource::ForLoopDesugar,
1516 // This is effectively `{ let _result = ...; _result }`.
1517 // The construct was introduced in #21984 and is necessary to make sure that
1518 // temporaries in the `head` expression are dropped and do not leak to the
1519 // surrounding scope of the `match` since the `match` is not a terminating scope.
1521 // Also, add the attributes to the outer returned expr node.
1522 self.expr_drop_temps_mut(for_span, match_expr, e.attrs.clone())
1525 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1526 /// ```ignore (pseudo-rust)
1527 /// match Try::branch(<expr>) {
1528 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1529 /// ControlFlow::Break(residual) =>
1530 /// #[allow(unreachable_code)]
1531 /// // If there is an enclosing `try {...}`:
1532 /// break 'catch_target Try::from_residual(residual),
1534 /// return Try::from_residual(residual),
1537 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1538 let unstable_span = self.mark_span_with_reason(
1539 DesugaringKind::QuestionMark,
1541 self.allow_try_trait.clone(),
1543 let try_span = self.tcx.sess.source_map().end_point(span);
1544 let try_span = self.mark_span_with_reason(
1545 DesugaringKind::QuestionMark,
1547 self.allow_try_trait.clone(),
1550 // `Try::branch(<expr>)`
1553 let sub_expr = self.lower_expr_mut(sub_expr);
1555 self.expr_call_lang_item_fn(
1557 hir::LangItem::TryTraitBranch,
1558 arena_vec![self; sub_expr],
1563 // `#[allow(unreachable_code)]`
1565 // `allow(unreachable_code)`
1567 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1568 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1569 let uc_nested = attr::mk_nested_word_item(uc_ident);
1570 attr::mk_list_item(allow_ident, vec![uc_nested])
1572 attr::mk_attr_outer(&self.tcx.sess.parse_sess.attr_id_generator, allow)
1574 let attrs: AttrVec = thin_vec![attr];
1576 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1577 let continue_arm = {
1578 let val_ident = Ident::with_dummy_span(sym::val);
1579 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1580 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1586 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1587 self.arm(continue_pat, val_expr)
1590 // `ControlFlow::Break(residual) =>
1591 // #[allow(unreachable_code)]
1592 // return Try::from_residual(residual),`
1594 let residual_ident = Ident::with_dummy_span(sym::residual);
1595 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1596 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1597 let from_residual_expr = self.wrap_in_try_constructor(
1598 hir::LangItem::TryTraitFromResidual,
1600 self.arena.alloc(residual_expr),
1603 let ret_expr = if let Some(catch_node) = self.catch_scope {
1604 let target_id = Ok(self.lower_node_id(catch_node));
1605 self.arena.alloc(self.expr(
1607 hir::ExprKind::Break(
1608 hir::Destination { label: None, target_id },
1609 Some(from_residual_expr),
1614 self.arena.alloc(self.expr(
1616 hir::ExprKind::Ret(Some(from_residual_expr)),
1621 let break_pat = self.pat_cf_break(try_span, residual_local);
1622 self.arm(break_pat, ret_expr)
1625 hir::ExprKind::Match(
1627 arena_vec![self; break_arm, continue_arm],
1628 hir::MatchSource::TryDesugar,
1632 /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into:
1633 /// ```ignore(illustrative)
1634 /// // If there is an enclosing `try {...}`:
1635 /// break 'catch_target FromResidual::from_residual(Yeet(residual));
1637 /// return FromResidual::from_residual(Yeet(residual));
1639 /// But to simplify this, there's a `from_yeet` lang item function which
1640 /// handles the combined `FromResidual::from_residual(Yeet(residual))`.
1641 fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1642 // The expression (if present) or `()` otherwise.
1643 let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
1644 (sub_expr.span, self.lower_expr(sub_expr))
1646 (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
1649 let unstable_span = self.mark_span_with_reason(
1650 DesugaringKind::YeetExpr,
1652 self.allow_try_trait.clone(),
1655 let from_yeet_expr = self.wrap_in_try_constructor(
1656 hir::LangItem::TryTraitFromYeet,
1662 if let Some(catch_node) = self.catch_scope {
1663 let target_id = Ok(self.lower_node_id(catch_node));
1664 hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
1666 hir::ExprKind::Ret(Some(from_yeet_expr))
1670 // =========================================================================
1671 // Helper methods for building HIR.
1672 // =========================================================================
1674 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1676 /// In terms of drop order, it has the same effect as wrapping `expr` in
1677 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1679 /// The drop order can be important in e.g. `if expr { .. }`.
1680 pub(super) fn expr_drop_temps(
1683 expr: &'hir hir::Expr<'hir>,
1685 ) -> &'hir hir::Expr<'hir> {
1686 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1689 pub(super) fn expr_drop_temps_mut(
1692 expr: &'hir hir::Expr<'hir>,
1694 ) -> hir::Expr<'hir> {
1695 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1701 arg: &'hir hir::Expr<'hir>,
1702 arms: &'hir [hir::Arm<'hir>],
1703 source: hir::MatchSource,
1704 ) -> hir::Expr<'hir> {
1705 self.expr(span, hir::ExprKind::Match(arg, arms, source), AttrVec::new())
1708 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1709 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1710 self.expr(span, expr_break, attrs)
1713 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1714 let expr_break = self.expr_break(span, attrs);
1715 self.arena.alloc(expr_break)
1718 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1721 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1726 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1727 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), AttrVec::new()))
1733 e: &'hir hir::Expr<'hir>,
1734 args: &'hir [hir::Expr<'hir>],
1735 ) -> hir::Expr<'hir> {
1736 self.expr(span, hir::ExprKind::Call(e, args), AttrVec::new())
1742 e: &'hir hir::Expr<'hir>,
1743 args: &'hir [hir::Expr<'hir>],
1744 ) -> &'hir hir::Expr<'hir> {
1745 self.arena.alloc(self.expr_call_mut(span, e, args))
1748 fn expr_call_lang_item_fn_mut(
1751 lang_item: hir::LangItem,
1752 args: &'hir [hir::Expr<'hir>],
1753 hir_id: Option<hir::HirId>,
1754 ) -> hir::Expr<'hir> {
1756 self.arena.alloc(self.expr_lang_item_path(span, lang_item, AttrVec::new(), hir_id));
1757 self.expr_call_mut(span, path, args)
1760 fn expr_call_lang_item_fn(
1763 lang_item: hir::LangItem,
1764 args: &'hir [hir::Expr<'hir>],
1765 hir_id: Option<hir::HirId>,
1766 ) -> &'hir hir::Expr<'hir> {
1767 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1770 fn expr_lang_item_path(
1773 lang_item: hir::LangItem,
1775 hir_id: Option<hir::HirId>,
1776 ) -> hir::Expr<'hir> {
1779 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1784 pub(super) fn expr_ident(
1788 binding: hir::HirId,
1789 ) -> &'hir hir::Expr<'hir> {
1790 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1793 pub(super) fn expr_ident_mut(
1797 binding: hir::HirId,
1798 ) -> hir::Expr<'hir> {
1799 self.expr_ident_with_attrs(sp, ident, binding, AttrVec::new())
1802 fn expr_ident_with_attrs(
1806 binding: hir::HirId,
1808 ) -> hir::Expr<'hir> {
1809 let hir_id = self.next_id();
1810 let res = Res::Local(binding);
1811 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1813 self.arena.alloc(hir::Path {
1814 span: self.lower_span(span),
1816 segments: arena_vec![self; hir::PathSegment::new(ident, hir_id, res)],
1820 self.expr(span, expr_path, attrs)
1823 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1824 let hir_id = self.next_id();
1825 let span = expr.span;
1828 hir::ExprKind::Block(
1829 self.arena.alloc(hir::Block {
1833 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1834 span: self.lower_span(span),
1835 targeted_by_break: false,
1843 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1844 let blk = self.block_all(span, &[], None);
1845 let expr = self.expr_block(blk, AttrVec::new());
1846 self.arena.alloc(expr)
1849 pub(super) fn expr_block(
1851 b: &'hir hir::Block<'hir>,
1853 ) -> hir::Expr<'hir> {
1854 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1860 kind: hir::ExprKind<'hir>,
1862 ) -> hir::Expr<'hir> {
1863 let hir_id = self.next_id();
1864 self.lower_attrs(hir_id, &attrs);
1865 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1871 expr: &'hir hir::Expr<'hir>,
1873 ) -> hir::ExprField<'hir> {
1875 hir_id: self.next_id(),
1877 span: self.lower_span(span),
1879 is_shorthand: false,
1883 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1885 hir_id: self.next_id(),
1888 span: self.lower_span(expr.span),