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_session::errors::report_lit_error;
18 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
19 use rustc_span::symbol::{kw, sym, Ident};
20 use rustc_span::DUMMY_SP;
21 use thin_vec::thin_vec;
23 impl<'hir> LoweringContext<'_, 'hir> {
24 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
25 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
28 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
29 self.arena.alloc(self.lower_expr_mut(e))
32 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
33 ensure_sufficient_stack(|| {
34 let hir_id = self.lower_node_id(e.id);
35 self.lower_attrs(hir_id, &e.attrs);
37 let kind = match &e.kind {
38 ExprKind::Box(inner) => hir::ExprKind::Box(self.lower_expr(inner)),
39 ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
40 ExprKind::ConstBlock(anon_const) => {
41 let anon_const = self.lower_anon_const(anon_const);
42 hir::ExprKind::ConstBlock(anon_const)
44 ExprKind::Repeat(expr, count) => {
45 let expr = self.lower_expr(expr);
46 let count = self.lower_array_length(count);
47 hir::ExprKind::Repeat(expr, count)
49 ExprKind::Tup(elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
50 ExprKind::Call(f, args) => {
51 if e.attrs.get(0).map_or(false, |a| a.has_name(sym::rustc_box)) {
52 if let [inner] = &args[..] && e.attrs.len() == 1 {
53 let kind = hir::ExprKind::Box(self.lower_expr(&inner));
54 let hir_id = self.lower_node_id(e.id);
55 return hir::Expr { hir_id, kind, span: self.lower_span(e.span) };
57 self.tcx.sess.emit_err(RustcBoxAttributeError { span: e.span });
60 } else if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
61 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
63 let f = self.lower_expr(f);
64 hir::ExprKind::Call(f, self.lower_exprs(args))
67 ExprKind::MethodCall(box MethodCall { seg, receiver, args, span }) => {
68 let hir_seg = self.arena.alloc(self.lower_path_segment(
72 ParenthesizedGenericArgs::Err,
73 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
75 let receiver = self.lower_expr(receiver);
77 self.arena.alloc_from_iter(args.iter().map(|x| self.lower_expr_mut(x)));
78 hir::ExprKind::MethodCall(hir_seg, receiver, args, self.lower_span(*span))
80 ExprKind::Binary(binop, lhs, rhs) => {
81 let binop = self.lower_binop(*binop);
82 let lhs = self.lower_expr(lhs);
83 let rhs = self.lower_expr(rhs);
84 hir::ExprKind::Binary(binop, lhs, rhs)
86 ExprKind::Unary(op, ohs) => {
87 let op = self.lower_unop(*op);
88 let ohs = self.lower_expr(ohs);
89 hir::ExprKind::Unary(op, ohs)
91 ExprKind::Lit(token_lit) => {
92 let lit_kind = match LitKind::from_token_lit(*token_lit) {
93 Ok(lit_kind) => lit_kind,
95 report_lit_error(&self.tcx.sess.parse_sess, err, *token_lit, e.span);
99 hir::ExprKind::Lit(respan(self.lower_span(e.span), lit_kind))
101 ExprKind::IncludedBytes(bytes) => hir::ExprKind::Lit(respan(
102 self.lower_span(e.span),
103 LitKind::ByteStr(bytes.clone()),
105 ExprKind::Cast(expr, ty) => {
106 let expr = self.lower_expr(expr);
108 self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
109 hir::ExprKind::Cast(expr, ty)
111 ExprKind::Type(expr, ty) => {
112 let expr = self.lower_expr(expr);
114 self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
115 hir::ExprKind::Type(expr, ty)
117 ExprKind::AddrOf(k, m, ohs) => {
118 let ohs = self.lower_expr(ohs);
119 hir::ExprKind::AddrOf(*k, *m, ohs)
121 ExprKind::Let(pat, scrutinee, span) => {
122 hir::ExprKind::Let(self.arena.alloc(hir::Let {
123 hir_id: self.next_id(),
124 span: self.lower_span(*span),
125 pat: self.lower_pat(pat),
127 init: self.lower_expr(scrutinee),
130 ExprKind::If(cond, then, else_opt) => {
131 self.lower_expr_if(cond, then, else_opt.as_deref())
133 ExprKind::While(cond, body, opt_label) => self.with_loop_scope(e.id, |this| {
134 let span = this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
135 this.lower_expr_while_in_loop_scope(span, cond, body, *opt_label)
137 ExprKind::Loop(body, opt_label, span) => self.with_loop_scope(e.id, |this| {
139 this.lower_block(body, false),
140 this.lower_label(*opt_label),
141 hir::LoopSource::Loop,
142 this.lower_span(*span),
145 ExprKind::TryBlock(body) => self.lower_expr_try_block(body),
146 ExprKind::Match(expr, arms) => hir::ExprKind::Match(
147 self.lower_expr(expr),
148 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
149 hir::MatchSource::Normal,
151 ExprKind::Async(capture_clause, closure_node_id, block) => self.make_async_expr(
157 hir::AsyncGeneratorKind::Block,
158 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
160 ExprKind::Await(expr) => {
161 let dot_await_span = if expr.span.hi() < e.span.hi() {
162 let span_with_whitespace = self
166 .span_extend_while(expr.span, char::is_whitespace)
167 .unwrap_or(expr.span);
168 span_with_whitespace.shrink_to_hi().with_hi(e.span.hi())
170 // this is a recovered `await expr`
173 self.lower_expr_await(dot_await_span, expr)
175 ExprKind::Closure(box Closure {
185 if let Async::Yes { closure_id, .. } = asyncness {
186 self.lower_expr_async_closure(
198 self.lower_expr_closure(
210 ExprKind::Block(blk, opt_label) => {
211 let opt_label = self.lower_label(*opt_label);
212 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
214 ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span),
215 ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp(
216 self.lower_binop(*op),
220 ExprKind::Field(el, ident) => {
221 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(*ident))
223 ExprKind::Index(el, er) => {
224 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
226 ExprKind::Range(Some(e1), Some(e2), RangeLimits::Closed) => {
227 self.lower_expr_range_closed(e.span, e1, e2)
229 ExprKind::Range(e1, e2, lims) => {
230 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), *lims)
232 ExprKind::Underscore => {
233 self.tcx.sess.emit_err(UnderscoreExprLhsAssign { span: e.span });
236 ExprKind::Path(qself, path) => {
237 let qpath = self.lower_qpath(
242 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
244 hir::ExprKind::Path(qpath)
246 ExprKind::Break(opt_label, opt_expr) => {
247 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
248 hir::ExprKind::Break(self.lower_jump_destination(e.id, *opt_label), opt_expr)
250 ExprKind::Continue(opt_label) => {
251 hir::ExprKind::Continue(self.lower_jump_destination(e.id, *opt_label))
253 ExprKind::Ret(e) => {
254 let e = e.as_ref().map(|x| self.lower_expr(x));
255 hir::ExprKind::Ret(e)
257 ExprKind::Yeet(sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
258 ExprKind::InlineAsm(asm) => {
259 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
261 ExprKind::Struct(se) => {
262 let rest = match &se.rest {
263 StructRest::Base(e) => Some(self.lower_expr(e)),
264 StructRest::Rest(sp) => {
265 self.tcx.sess.emit_err(BaseExpressionDoubleDot { span: *sp });
266 Some(&*self.arena.alloc(self.expr_err(*sp)))
268 StructRest::None => None,
270 hir::ExprKind::Struct(
271 self.arena.alloc(self.lower_qpath(
276 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
279 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
283 ExprKind::Yield(opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
284 ExprKind::Err => hir::ExprKind::Err,
285 ExprKind::Try(sub_expr) => self.lower_expr_try(e.span, sub_expr),
286 ExprKind::Paren(ex) => {
287 let mut ex = self.lower_expr_mut(ex);
288 // Include parens in span, but only if it is a super-span.
289 if e.span.contains(ex.span) {
290 ex.span = self.lower_span(e.span);
292 // Merge attributes into the inner expression.
293 if !e.attrs.is_empty() {
295 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
298 &*self.arena.alloc_from_iter(
301 .map(|a| self.lower_attr(a))
302 .chain(old_attrs.iter().cloned()),
309 // Desugar `ExprForLoop`
310 // from: `[opt_ident]: for <pat> in <head> <body>`
311 ExprKind::ForLoop(pat, head, body, opt_label) => {
312 return self.lower_expr_for(e, pat, head, body, *opt_label);
314 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
317 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
321 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
323 UnOp::Deref => hir::UnOp::Deref,
324 UnOp::Not => hir::UnOp::Not,
325 UnOp::Neg => hir::UnOp::Neg,
329 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
332 BinOpKind::Add => hir::BinOpKind::Add,
333 BinOpKind::Sub => hir::BinOpKind::Sub,
334 BinOpKind::Mul => hir::BinOpKind::Mul,
335 BinOpKind::Div => hir::BinOpKind::Div,
336 BinOpKind::Rem => hir::BinOpKind::Rem,
337 BinOpKind::And => hir::BinOpKind::And,
338 BinOpKind::Or => hir::BinOpKind::Or,
339 BinOpKind::BitXor => hir::BinOpKind::BitXor,
340 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
341 BinOpKind::BitOr => hir::BinOpKind::BitOr,
342 BinOpKind::Shl => hir::BinOpKind::Shl,
343 BinOpKind::Shr => hir::BinOpKind::Shr,
344 BinOpKind::Eq => hir::BinOpKind::Eq,
345 BinOpKind::Lt => hir::BinOpKind::Lt,
346 BinOpKind::Le => hir::BinOpKind::Le,
347 BinOpKind::Ne => hir::BinOpKind::Ne,
348 BinOpKind::Ge => hir::BinOpKind::Ge,
349 BinOpKind::Gt => hir::BinOpKind::Gt,
351 span: self.lower_span(b.span),
355 fn lower_legacy_const_generics(
358 args: Vec<AstP<Expr>>,
359 legacy_args_idx: &[usize],
360 ) -> hir::ExprKind<'hir> {
361 let ExprKind::Path(None, path) = &mut f.kind else {
365 // Split the arguments into const generics and normal arguments
366 let mut real_args = vec![];
367 let mut generic_args = vec![];
368 for (idx, arg) in args.into_iter().enumerate() {
369 if legacy_args_idx.contains(&idx) {
370 let parent_def_id = self.current_hir_id_owner;
371 let node_id = self.next_node_id();
373 // Add a definition for the in-band const def.
374 self.create_def(parent_def_id.def_id, node_id, DefPathData::AnonConst, f.span);
376 let anon_const = AnonConst { id: node_id, value: arg };
377 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
383 // Add generic args to the last element of the path.
384 let last_segment = path.segments.last_mut().unwrap();
385 assert!(last_segment.args.is_none());
386 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
391 // Now lower everything as normal.
392 let f = self.lower_expr(&f);
393 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
400 else_opt: Option<&Expr>,
401 ) -> hir::ExprKind<'hir> {
402 let lowered_cond = self.lower_cond(cond);
403 let then_expr = self.lower_block_expr(then);
404 if let Some(rslt) = else_opt {
407 self.arena.alloc(then_expr),
408 Some(self.lower_expr(rslt)),
411 hir::ExprKind::If(lowered_cond, self.arena.alloc(then_expr), None)
415 // Lowers a condition (i.e. `cond` in `if cond` or `while cond`), wrapping it in a terminating scope
416 // so that temporaries created in the condition don't live beyond it.
417 fn lower_cond(&mut self, cond: &Expr) -> &'hir hir::Expr<'hir> {
418 fn has_let_expr(expr: &Expr) -> bool {
420 ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
421 ExprKind::Let(..) => true,
426 // We have to take special care for `let` exprs in the condition, e.g. in
427 // `if let pat = val` or `if foo && let pat = val`, as we _do_ want `val` to live beyond the
428 // condition in this case.
430 // In order to mantain the drop behavior for the non `let` parts of the condition,
431 // we still wrap them in terminating scopes, e.g. `if foo && let pat = val` essentially
432 // gets transformed into `if { let _t = foo; _t } && let pat = val`
434 ExprKind::Binary(op @ Spanned { node: ast::BinOpKind::And, .. }, lhs, rhs)
435 if has_let_expr(cond) =>
437 let op = self.lower_binop(*op);
438 let lhs = self.lower_cond(lhs);
439 let rhs = self.lower_cond(rhs);
441 self.arena.alloc(self.expr(cond.span, hir::ExprKind::Binary(op, lhs, rhs)))
443 ExprKind::Let(..) => self.lower_expr(cond),
445 let cond = self.lower_expr(cond);
446 let reason = DesugaringKind::CondTemporary;
447 let span_block = self.mark_span_with_reason(reason, cond.span, None);
448 self.expr_drop_temps(span_block, cond)
453 // We desugar: `'label: while $cond $body` into:
457 // if { let _t = $cond; _t } {
466 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
467 // to preserve drop semantics since `while $cond { ... }` does not
468 // let temporaries live outside of `cond`.
469 fn lower_expr_while_in_loop_scope(
474 opt_label: Option<Label>,
475 ) -> hir::ExprKind<'hir> {
476 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_cond(cond));
477 let then = self.lower_block_expr(body);
478 let expr_break = self.expr_break(span);
479 let stmt_break = self.stmt_expr(span, expr_break);
480 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
481 let else_expr = self.arena.alloc(self.expr_block(else_blk));
482 let if_kind = hir::ExprKind::If(lowered_cond, self.arena.alloc(then), Some(else_expr));
483 let if_expr = self.expr(span, if_kind);
484 let block = self.block_expr(self.arena.alloc(if_expr));
485 let span = self.lower_span(span.with_hi(cond.span.hi()));
486 let opt_label = self.lower_label(opt_label);
487 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
490 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
491 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
492 /// and save the block id to use it as a break target for desugaring of the `?` operator.
493 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
494 self.with_catch_scope(body.id, |this| {
495 let mut block = this.lower_block_noalloc(body, true);
497 // Final expression of the block (if present) or `()` with span at the end of block
498 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
500 this.mark_span_with_reason(
501 DesugaringKind::TryBlock,
503 this.allow_try_trait.clone(),
508 let try_span = this.mark_span_with_reason(
509 DesugaringKind::TryBlock,
510 this.tcx.sess.source_map().end_point(body.span),
511 this.allow_try_trait.clone(),
514 (try_span, this.expr_unit(try_span))
517 let ok_wrapped_span =
518 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
520 // `::std::ops::Try::from_output($tail_expr)`
521 block.expr = Some(this.wrap_in_try_constructor(
522 hir::LangItem::TryTraitFromOutput,
528 hir::ExprKind::Block(this.arena.alloc(block), None)
532 fn wrap_in_try_constructor(
534 lang_item: hir::LangItem,
536 expr: &'hir hir::Expr<'hir>,
538 ) -> &'hir hir::Expr<'hir> {
539 let constructor = self.arena.alloc(self.expr_lang_item_path(method_span, lang_item, None));
540 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
543 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
544 let pat = self.lower_pat(&arm.pat);
545 let guard = arm.guard.as_ref().map(|cond| {
546 if let ExprKind::Let(pat, scrutinee, span) = &cond.kind {
547 hir::Guard::IfLet(self.arena.alloc(hir::Let {
548 hir_id: self.next_id(),
549 span: self.lower_span(*span),
550 pat: self.lower_pat(pat),
552 init: self.lower_expr(scrutinee),
555 hir::Guard::If(self.lower_expr(cond))
558 let hir_id = self.next_id();
559 self.lower_attrs(hir_id, &arm.attrs);
564 body: self.lower_expr(&arm.body),
565 span: self.lower_span(arm.span),
569 /// Lower an `async` construct to a generator that implements `Future`.
574 /// std::future::identity_future(static move? |_task_context| -> <ret_ty> {
578 pub(super) fn make_async_expr(
580 capture_clause: CaptureBy,
581 outer_hir_id: hir::HirId,
582 closure_node_id: NodeId,
583 ret_ty: Option<hir::FnRetTy<'hir>>,
585 async_gen_kind: hir::AsyncGeneratorKind,
586 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
587 ) -> hir::ExprKind<'hir> {
588 let output = ret_ty.unwrap_or_else(|| hir::FnRetTy::DefaultReturn(self.lower_span(span)));
590 // Resume argument type, which should be `&mut Context<'_>`.
591 // NOTE: Using the `'static` lifetime here is technically cheating.
592 // The `Future::poll` argument really is `&'a mut Context<'b>`, but we cannot
593 // express the fact that we are not storing it across yield-points yet,
594 // and we would thus run into lifetime errors.
595 // See <https://github.com/rust-lang/rust/issues/68923>.
596 // Our lowering makes sure we are not mis-using the `_task_context` input type
597 // in the sense that we are indeed not using it across yield points. We
598 // get a fresh `&mut Context` for each resume / call of `Future::poll`.
599 // This "cheating" was previously done with a `ResumeTy` that contained a raw
600 // pointer, and a `get_context` accessor that pulled the `Context` lifetimes
602 let context_lifetime_ident = Ident::with_dummy_span(kw::StaticLifetime);
603 let context_lifetime = self.arena.alloc(hir::Lifetime {
604 hir_id: self.next_id(),
605 ident: context_lifetime_ident,
606 res: hir::LifetimeName::Static,
609 hir::QPath::LangItem(hir::LangItem::Context, self.lower_span(span), None);
610 let context_ty = hir::MutTy {
611 ty: self.arena.alloc(hir::Ty {
612 hir_id: self.next_id(),
613 kind: hir::TyKind::Path(context_path),
614 span: self.lower_span(span),
616 mutbl: hir::Mutability::Mut,
618 let input_ty = hir::Ty {
619 hir_id: self.next_id(),
620 kind: hir::TyKind::Rptr(context_lifetime, context_ty),
621 span: self.lower_span(span),
624 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
625 let fn_decl = self.arena.alloc(hir::FnDecl {
626 inputs: arena_vec![self; input_ty],
629 implicit_self: hir::ImplicitSelfKind::None,
630 lifetime_elision_allowed: false,
633 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
634 let (pat, task_context_hid) = self.pat_ident_binding_mode(
636 Ident::with_dummy_span(sym::_task_context),
637 hir::BindingAnnotation::MUT,
639 let param = hir::Param {
640 hir_id: self.next_id(),
642 ty_span: self.lower_span(span),
643 span: self.lower_span(span),
645 let params = arena_vec![self; param];
647 let body = self.lower_body(move |this| {
648 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
650 let old_ctx = this.task_context;
651 this.task_context = Some(task_context_hid);
652 let res = body(this);
653 this.task_context = old_ctx;
657 // `static |_task_context| -> <ret_ty> { body }`:
658 let generator_kind = {
659 let c = self.arena.alloc(hir::Closure {
660 def_id: self.local_def_id(closure_node_id),
661 binder: hir::ClosureBinder::Default,
663 bound_generic_params: &[],
666 fn_decl_span: self.lower_span(span),
668 movability: Some(hir::Movability::Static),
671 hir::ExprKind::Closure(c)
674 let track_caller = self
676 .get(&outer_hir_id.local_id)
677 .map_or(false, |attrs| attrs.into_iter().any(|attr| attr.has_name(sym::track_caller)));
679 let hir_id = self.lower_node_id(closure_node_id);
681 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
686 kind: AttrKind::Normal(ptr::P(NormalAttr {
688 path: Path::from_ident(Ident::new(sym::track_caller, span)),
689 args: AttrArgs::Empty,
694 id: self.tcx.sess.parse_sess.attr_id_generator.mk_attr_id(),
695 style: AttrStyle::Outer,
701 let generator = hir::Expr { hir_id, kind: generator_kind, span: self.lower_span(span) };
704 // For some reason, the async block needs to flow through *any*
705 // call (like the identity function), as otherwise type and lifetime
706 // inference have a hard time figuring things out.
707 // Without this, we would get:
708 // E0720 in src/test/ui/impl-trait/in-trait/default-body-with-rpit.rs
709 // E0700 in src/test/ui/self/self_lifetime-async.rs
711 // `future::identity_future`:
712 let identity_future =
713 self.expr_lang_item_path(unstable_span, hir::LangItem::IdentityFuture, None);
715 // `future::identity_future(generator)`:
716 hir::ExprKind::Call(self.arena.alloc(identity_future), arena_vec![self; generator])
719 /// Desugar `<expr>.await` into:
720 /// ```ignore (pseudo-rust)
721 /// match ::std::future::IntoFuture::into_future(<expr>) {
722 /// mut __awaitee => loop {
723 /// match unsafe { ::std::future::Future::poll(
724 /// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
727 /// ::std::task::Poll::Ready(result) => break result,
728 /// ::std::task::Poll::Pending => {}
730 /// task_context = yield ();
734 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
735 let full_span = expr.span.to(dot_await_span);
736 match self.generator_kind {
737 Some(hir::GeneratorKind::Async(_)) => {}
738 Some(hir::GeneratorKind::Gen) | None => {
739 self.tcx.sess.emit_err(AwaitOnlyInAsyncFnAndBlocks {
741 item_span: self.current_item,
745 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
746 let gen_future_span = self.mark_span_with_reason(
747 DesugaringKind::Await,
749 self.allow_gen_future.clone(),
751 let expr = self.lower_expr_mut(expr);
752 let expr_hir_id = expr.hir_id;
754 // Note that the name of this binding must not be changed to something else because
755 // debuggers and debugger extensions expect it to be called `__awaitee`. They use
756 // this name to identify what is being awaited by a suspended async functions.
757 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
758 let (awaitee_pat, awaitee_pat_hid) =
759 self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::MUT);
761 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
764 // ::std::future::Future::poll(
765 // ::std::pin::Pin::new_unchecked(&mut __awaitee),
770 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
771 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
772 let task_context = if let Some(task_context_hid) = self.task_context {
773 self.expr_ident_mut(span, task_context_ident, task_context_hid)
775 // Use of `await` outside of an async context, we cannot use `task_context` here.
778 let new_unchecked = self.expr_call_lang_item_fn_mut(
780 hir::LangItem::PinNewUnchecked,
781 arena_vec![self; ref_mut_awaitee],
784 let call = self.expr_call_lang_item_fn(
786 hir::LangItem::FuturePoll,
787 arena_vec![self; new_unchecked, task_context],
790 self.arena.alloc(self.expr_unsafe(call))
793 // `::std::task::Poll::Ready(result) => break result`
794 let loop_node_id = self.next_node_id();
795 let loop_hir_id = self.lower_node_id(loop_node_id);
797 let x_ident = Ident::with_dummy_span(sym::result);
798 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
799 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
800 let ready_field = self.single_pat_field(gen_future_span, x_pat);
801 let ready_pat = self.pat_lang_item_variant(
803 hir::LangItem::PollReady,
807 let break_x = self.with_loop_scope(loop_node_id, move |this| {
809 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
810 this.arena.alloc(this.expr(gen_future_span, expr_break))
812 self.arm(ready_pat, break_x)
815 // `::std::task::Poll::Pending => {}`
817 let pending_pat = self.pat_lang_item_variant(
819 hir::LangItem::PollPending,
823 let empty_block = self.expr_block_empty(span);
824 self.arm(pending_pat, empty_block)
827 let inner_match_stmt = {
828 let match_expr = self.expr_match(
831 arena_vec![self; ready_arm, pending_arm],
832 hir::MatchSource::AwaitDesugar,
834 self.stmt_expr(span, match_expr)
837 // task_context = yield ();
839 let unit = self.expr_unit(span);
840 let yield_expr = self.expr(
842 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
844 let yield_expr = self.arena.alloc(yield_expr);
846 if let Some(task_context_hid) = self.task_context {
847 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
849 self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)));
850 self.stmt_expr(span, assign)
852 // Use of `await` outside of an async context. Return `yield_expr` so that we can
853 // proceed with type checking.
854 self.stmt(span, hir::StmtKind::Semi(yield_expr))
858 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
861 let loop_expr = self.arena.alloc(hir::Expr {
863 kind: hir::ExprKind::Loop(
866 hir::LoopSource::Loop,
867 self.lower_span(span),
869 span: self.lower_span(span),
872 // mut __awaitee => loop { ... }
873 let awaitee_arm = self.arm(awaitee_pat, loop_expr);
875 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
876 let into_future_span = self.mark_span_with_reason(
877 DesugaringKind::Await,
879 self.allow_into_future.clone(),
881 let into_future_expr = self.expr_call_lang_item_fn(
883 hir::LangItem::IntoFutureIntoFuture,
884 arena_vec![self; expr],
888 // match <into_future_expr> {
889 // mut __awaitee => loop { .. }
891 hir::ExprKind::Match(
893 arena_vec![self; awaitee_arm],
894 hir::MatchSource::AwaitDesugar,
898 fn lower_expr_closure(
900 binder: &ClosureBinder,
901 capture_clause: CaptureBy,
903 movability: Movability,
908 ) -> hir::ExprKind<'hir> {
909 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
911 let (body_id, generator_option) = self.with_new_scopes(move |this| {
912 let prev = this.current_item;
913 this.current_item = Some(fn_decl_span);
914 let mut generator_kind = None;
915 let body_id = this.lower_fn_body(decl, |this| {
916 let e = this.lower_expr_mut(body);
917 generator_kind = this.generator_kind;
920 let generator_option =
921 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
922 this.current_item = prev;
923 (body_id, generator_option)
926 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
927 // Lower outside new scope to preserve `is_in_loop_condition`.
928 let fn_decl = self.lower_fn_decl(decl, closure_id, fn_decl_span, FnDeclKind::Closure, None);
930 let c = self.arena.alloc(hir::Closure {
931 def_id: self.local_def_id(closure_id),
932 binder: binder_clause,
934 bound_generic_params,
937 fn_decl_span: self.lower_span(fn_decl_span),
938 fn_arg_span: Some(self.lower_span(fn_arg_span)),
939 movability: generator_option,
942 hir::ExprKind::Closure(c)
945 fn generator_movability_for_fn(
949 generator_kind: Option<hir::GeneratorKind>,
950 movability: Movability,
951 ) -> Option<hir::Movability> {
952 match generator_kind {
953 Some(hir::GeneratorKind::Gen) => {
954 if decl.inputs.len() > 1 {
955 self.tcx.sess.emit_err(GeneratorTooManyParameters { fn_decl_span });
959 Some(hir::GeneratorKind::Async(_)) => {
960 panic!("non-`async` closure body turned `async` during lowering");
963 if movability == Movability::Static {
964 self.tcx.sess.emit_err(ClosureCannotBeStatic { fn_decl_span });
971 fn lower_closure_binder<'c>(
973 binder: &'c ClosureBinder,
974 ) -> (hir::ClosureBinder, &'c [GenericParam]) {
975 let (binder, params) = match binder {
976 ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]),
977 ClosureBinder::For { span, generic_params } => {
978 let span = self.lower_span(*span);
979 (hir::ClosureBinder::For { span }, &**generic_params)
986 fn lower_expr_async_closure(
988 binder: &ClosureBinder,
989 capture_clause: CaptureBy,
991 closure_hir_id: hir::HirId,
992 inner_closure_id: NodeId,
997 ) -> hir::ExprKind<'hir> {
998 if let &ClosureBinder::For { span, .. } = binder {
999 self.tcx.sess.emit_err(NotSupportedForLifetimeBinderAsyncClosure { span });
1002 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
1005 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
1007 let body = self.with_new_scopes(|this| {
1008 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
1009 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
1010 this.tcx.sess.emit_err(AsyncNonMoveClosureNotSupported { fn_decl_span });
1013 // Transform `async |x: u8| -> X { ... }` into
1014 // `|x: u8| identity_future(|| -> X { ... })`.
1015 let body_id = this.lower_fn_body(&outer_decl, |this| {
1016 let async_ret_ty = if let FnRetTy::Ty(ty) = &decl.output {
1017 let itctx = ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock);
1018 Some(hir::FnRetTy::Return(this.lower_ty(&ty, &itctx)))
1023 let async_body = this.make_async_expr(
1029 hir::AsyncGeneratorKind::Closure,
1030 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
1032 this.expr(fn_decl_span, async_body)
1037 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
1038 // We need to lower the declaration outside the new scope, because we
1039 // have to conserve the state of being inside a loop condition for the
1040 // closure argument types.
1042 self.lower_fn_decl(&outer_decl, closure_id, fn_decl_span, FnDeclKind::Closure, None);
1044 let c = self.arena.alloc(hir::Closure {
1045 def_id: self.local_def_id(closure_id),
1046 binder: binder_clause,
1048 bound_generic_params,
1051 fn_decl_span: self.lower_span(fn_decl_span),
1052 fn_arg_span: Some(self.lower_span(fn_arg_span)),
1055 hir::ExprKind::Closure(c)
1058 /// Destructure the LHS of complex assignments.
1059 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
1060 fn lower_expr_assign(
1066 ) -> hir::ExprKind<'hir> {
1067 // Return early in case of an ordinary assignment.
1068 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
1071 | ExprKind::Struct(..)
1073 | ExprKind::Underscore => false,
1074 // Check for tuple struct constructor.
1075 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
1076 ExprKind::Paren(e) => {
1078 // We special-case `(..)` for consistency with patterns.
1079 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
1080 _ => is_ordinary(lower_ctx, e),
1086 if is_ordinary(self, lhs) {
1087 return hir::ExprKind::Assign(
1088 self.lower_expr(lhs),
1089 self.lower_expr(rhs),
1090 self.lower_span(eq_sign_span),
1094 let mut assignments = vec![];
1096 // The LHS becomes a pattern: `(lhs1, lhs2)`.
1097 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1098 let rhs = self.lower_expr(rhs);
1100 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1101 let destructure_let = self.stmt_let_pat(
1106 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
1109 // `a = lhs1; b = lhs2;`.
1112 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1114 // Wrap everything in a block.
1115 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1118 /// If the given expression is a path to a tuple struct, returns that path.
1119 /// It is not a complete check, but just tries to reject most paths early
1120 /// if they are not tuple structs.
1121 /// Type checking will take care of the full validation later.
1122 fn extract_tuple_struct_path<'a>(
1125 ) -> Option<(&'a Option<AstP<QSelf>>, &'a Path)> {
1126 if let ExprKind::Path(qself, path) = &expr.kind {
1127 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1128 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1129 if let Some(res) = partial_res.full_res() && !res.expected_in_tuple_struct_pat() {
1133 return Some((qself, path));
1138 /// If the given expression is a path to a unit struct, returns that path.
1139 /// It is not a complete check, but just tries to reject most paths early
1140 /// if they are not unit structs.
1141 /// Type checking will take care of the full validation later.
1142 fn extract_unit_struct_path<'a>(
1145 ) -> Option<(&'a Option<AstP<QSelf>>, &'a Path)> {
1146 if let ExprKind::Path(qself, path) = &expr.kind {
1147 // Does the path resolve to something disallowed in a unit struct/variant pattern?
1148 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1149 if let Some(res) = partial_res.full_res() && !res.expected_in_unit_struct_pat() {
1153 return Some((qself, path));
1158 /// Convert the LHS of a destructuring assignment to a pattern.
1159 /// Each sub-assignment is recorded in `assignments`.
1160 fn destructure_assign(
1164 assignments: &mut Vec<hir::Stmt<'hir>>,
1165 ) -> &'hir hir::Pat<'hir> {
1166 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1169 fn destructure_assign_mut(
1173 assignments: &mut Vec<hir::Stmt<'hir>>,
1174 ) -> hir::Pat<'hir> {
1176 // Underscore pattern.
1177 ExprKind::Underscore => {
1178 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1181 ExprKind::Array(elements) => {
1183 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1184 let slice_pat = if let Some((i, span)) = rest {
1185 let (before, after) = pats.split_at(i);
1186 hir::PatKind::Slice(
1188 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1192 hir::PatKind::Slice(pats, None, &[])
1194 return self.pat_without_dbm(lhs.span, slice_pat);
1197 ExprKind::Call(callee, args) => {
1198 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1199 let (pats, rest) = self.destructure_sequence(
1201 "tuple struct or variant",
1205 let qpath = self.lower_qpath(
1209 ParamMode::Optional,
1210 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1212 // Destructure like a tuple struct.
1213 let tuple_struct_pat = hir::PatKind::TupleStruct(
1216 hir::DotDotPos::new(rest.map(|r| r.0)),
1218 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1221 // Unit structs and enum variants.
1222 ExprKind::Path(..) => {
1223 if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1224 let qpath = self.lower_qpath(
1228 ParamMode::Optional,
1229 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1231 // Destructure like a unit struct.
1232 let unit_struct_pat = hir::PatKind::Path(qpath);
1233 return self.pat_without_dbm(lhs.span, unit_struct_pat);
1237 ExprKind::Struct(se) => {
1238 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1239 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1241 hir_id: self.next_id(),
1242 ident: self.lower_ident(f.ident),
1244 is_shorthand: f.is_shorthand,
1245 span: self.lower_span(f.span),
1248 let qpath = self.lower_qpath(
1252 ParamMode::Optional,
1253 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1255 let fields_omitted = match &se.rest {
1256 StructRest::Base(e) => {
1257 self.tcx.sess.emit_err(FunctionalRecordUpdateDestructuringAssignemnt {
1262 StructRest::Rest(_) => true,
1263 StructRest::None => false,
1265 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1266 return self.pat_without_dbm(lhs.span, struct_pat);
1269 ExprKind::Tup(elements) => {
1271 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1272 let tuple_pat = hir::PatKind::Tuple(pats, hir::DotDotPos::new(rest.map(|r| r.0)));
1273 return self.pat_without_dbm(lhs.span, tuple_pat);
1275 ExprKind::Paren(e) => {
1276 // We special-case `(..)` for consistency with patterns.
1277 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1278 let tuple_pat = hir::PatKind::Tuple(&[], hir::DotDotPos::new(Some(0)));
1279 return self.pat_without_dbm(lhs.span, tuple_pat);
1281 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1286 // Treat all other cases as normal lvalue.
1287 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1288 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1289 let ident = self.expr_ident(lhs.span, ident, binding);
1291 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1292 let expr = self.expr(lhs.span, assign);
1293 assignments.push(self.stmt_expr(lhs.span, expr));
1297 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1298 /// Such a sequence occurs in a tuple (struct)/slice.
1299 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1301 /// Each sub-assignment is recorded in `assignments`.
1302 fn destructure_sequence(
1304 elements: &[AstP<Expr>],
1307 assignments: &mut Vec<hir::Stmt<'hir>>,
1308 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1309 let mut rest = None;
1311 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1312 // Check for `..` pattern.
1313 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1314 if let Some((_, prev_span)) = rest {
1315 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1317 rest = Some((i, e.span));
1321 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1327 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1328 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1329 let e1 = self.lower_expr_mut(e1);
1330 let e2 = self.lower_expr_mut(e2);
1332 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1333 let fn_expr = self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path)));
1334 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1337 fn lower_expr_range(
1343 ) -> hir::ExprKind<'hir> {
1344 use rustc_ast::RangeLimits::*;
1346 let lang_item = match (e1, e2, lims) {
1347 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1348 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1349 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1350 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1351 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1352 (Some(..), Some(..), Closed) => unreachable!(),
1353 (start, None, Closed) => {
1354 self.tcx.sess.emit_err(InclusiveRangeWithNoEnd { span });
1356 Some(..) => hir::LangItem::RangeFrom,
1357 None => hir::LangItem::RangeFull,
1362 let fields = self.arena.alloc_from_iter(
1363 e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1365 let expr = self.lower_expr(&e);
1366 let ident = Ident::new(s, self.lower_span(e.span));
1367 self.expr_field(ident, expr, e.span)
1372 hir::ExprKind::Struct(
1373 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)),
1379 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1380 let label = opt_label?;
1381 Some(Label { ident: self.lower_ident(label.ident) })
1384 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1385 let target_id = match destination {
1387 if let Some(loop_id) = self.resolver.get_label_res(id) {
1388 Ok(self.lower_node_id(loop_id))
1390 Err(hir::LoopIdError::UnresolvedLabel)
1395 .map(|id| Ok(self.lower_node_id(id)))
1396 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1398 let label = self.lower_label(destination.map(|(_, label)| label));
1399 hir::Destination { label, target_id }
1402 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1403 if self.is_in_loop_condition && opt_label.is_none() {
1406 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1409 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1413 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1414 let old_scope = self.catch_scope.replace(catch_id);
1415 let result = f(self);
1416 self.catch_scope = old_scope;
1420 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1421 // We're no longer in the base loop's condition; we're in another loop.
1422 let was_in_loop_condition = self.is_in_loop_condition;
1423 self.is_in_loop_condition = false;
1425 let old_scope = self.loop_scope.replace(loop_id);
1426 let result = f(self);
1427 self.loop_scope = old_scope;
1429 self.is_in_loop_condition = was_in_loop_condition;
1434 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1435 let was_in_loop_condition = self.is_in_loop_condition;
1436 self.is_in_loop_condition = true;
1438 let result = f(self);
1440 self.is_in_loop_condition = was_in_loop_condition;
1445 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1446 let hir_id = self.lower_node_id(f.id);
1447 self.lower_attrs(hir_id, &f.attrs);
1450 ident: self.lower_ident(f.ident),
1451 expr: self.lower_expr(&f.expr),
1452 span: self.lower_span(f.span),
1453 is_shorthand: f.is_shorthand,
1457 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1458 match self.generator_kind {
1459 Some(hir::GeneratorKind::Gen) => {}
1460 Some(hir::GeneratorKind::Async(_)) => {
1461 self.tcx.sess.emit_err(AsyncGeneratorsNotSupported { span });
1463 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1467 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1469 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1472 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1473 /// ```ignore (pseudo-rust)
1475 /// let result = match IntoIterator::into_iter(<head>) {
1477 /// [opt_ident]: loop {
1478 /// match Iterator::next(&mut iter) {
1480 /// Some(<pat>) => <body>,
1494 opt_label: Option<Label>,
1495 ) -> hir::Expr<'hir> {
1496 let head = self.lower_expr_mut(head);
1497 let pat = self.lower_pat(pat);
1499 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1500 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1501 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1505 let break_expr = self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span));
1506 let pat = self.pat_none(for_span);
1507 self.arm(pat, break_expr)
1510 // Some(<pat>) => <body>,
1512 let some_pat = self.pat_some(pat_span, pat);
1513 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1514 let body_expr = self.arena.alloc(self.expr_block(body_block));
1515 self.arm(some_pat, body_expr)
1519 let iter = Ident::with_dummy_span(sym::iter);
1520 let (iter_pat, iter_pat_nid) =
1521 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::MUT);
1523 // `match Iterator::next(&mut iter) { ... }`
1525 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1526 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1527 let next_expr = self.expr_call_lang_item_fn(
1529 hir::LangItem::IteratorNext,
1530 arena_vec![self; ref_mut_iter],
1533 let arms = arena_vec![self; none_arm, some_arm];
1535 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1537 let match_stmt = self.stmt_expr(for_span, match_expr);
1539 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1541 // `[opt_ident]: loop { ... }`
1542 let kind = hir::ExprKind::Loop(
1544 self.lower_label(opt_label),
1545 hir::LoopSource::ForLoop,
1546 self.lower_span(for_span.with_hi(head.span.hi())),
1549 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1551 // `mut iter => { ... }`
1552 let iter_arm = self.arm(iter_pat, loop_expr);
1554 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1555 let into_iter_expr = {
1556 self.expr_call_lang_item_fn(
1558 hir::LangItem::IntoIterIntoIter,
1559 arena_vec![self; head],
1564 let match_expr = self.arena.alloc(self.expr_match(
1567 arena_vec![self; iter_arm],
1568 hir::MatchSource::ForLoopDesugar,
1571 // This is effectively `{ let _result = ...; _result }`.
1572 // The construct was introduced in #21984 and is necessary to make sure that
1573 // temporaries in the `head` expression are dropped and do not leak to the
1574 // surrounding scope of the `match` since the `match` is not a terminating scope.
1576 // Also, add the attributes to the outer returned expr node.
1577 let expr = self.expr_drop_temps_mut(for_span, match_expr);
1578 self.lower_attrs(expr.hir_id, &e.attrs);
1582 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1583 /// ```ignore (pseudo-rust)
1584 /// match Try::branch(<expr>) {
1585 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1586 /// ControlFlow::Break(residual) =>
1587 /// #[allow(unreachable_code)]
1588 /// // If there is an enclosing `try {...}`:
1589 /// break 'catch_target Try::from_residual(residual),
1591 /// return Try::from_residual(residual),
1594 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1595 let unstable_span = self.mark_span_with_reason(
1596 DesugaringKind::QuestionMark,
1598 self.allow_try_trait.clone(),
1600 let try_span = self.tcx.sess.source_map().end_point(span);
1601 let try_span = self.mark_span_with_reason(
1602 DesugaringKind::QuestionMark,
1604 self.allow_try_trait.clone(),
1607 // `Try::branch(<expr>)`
1610 let sub_expr = self.lower_expr_mut(sub_expr);
1612 self.expr_call_lang_item_fn(
1614 hir::LangItem::TryTraitBranch,
1615 arena_vec![self; sub_expr],
1620 // `#[allow(unreachable_code)]`
1621 let attr = attr::mk_attr_nested_word(
1622 &self.tcx.sess.parse_sess.attr_id_generator,
1625 sym::unreachable_code,
1626 self.lower_span(span),
1628 let attrs: AttrVec = thin_vec![attr];
1630 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1631 let continue_arm = {
1632 let val_ident = Ident::with_dummy_span(sym::val);
1633 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1634 let val_expr = self.expr_ident(span, val_ident, val_pat_nid);
1635 self.lower_attrs(val_expr.hir_id, &attrs);
1636 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1637 self.arm(continue_pat, val_expr)
1640 // `ControlFlow::Break(residual) =>
1641 // #[allow(unreachable_code)]
1642 // return Try::from_residual(residual),`
1644 let residual_ident = Ident::with_dummy_span(sym::residual);
1645 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1646 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1647 let from_residual_expr = self.wrap_in_try_constructor(
1648 hir::LangItem::TryTraitFromResidual,
1650 self.arena.alloc(residual_expr),
1653 let ret_expr = if let Some(catch_node) = self.catch_scope {
1654 let target_id = Ok(self.lower_node_id(catch_node));
1655 self.arena.alloc(self.expr(
1657 hir::ExprKind::Break(
1658 hir::Destination { label: None, target_id },
1659 Some(from_residual_expr),
1663 self.arena.alloc(self.expr(try_span, hir::ExprKind::Ret(Some(from_residual_expr))))
1665 self.lower_attrs(ret_expr.hir_id, &attrs);
1667 let break_pat = self.pat_cf_break(try_span, residual_local);
1668 self.arm(break_pat, ret_expr)
1671 hir::ExprKind::Match(
1673 arena_vec![self; break_arm, continue_arm],
1674 hir::MatchSource::TryDesugar,
1678 /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into:
1679 /// ```ignore(illustrative)
1680 /// // If there is an enclosing `try {...}`:
1681 /// break 'catch_target FromResidual::from_residual(Yeet(residual));
1683 /// return FromResidual::from_residual(Yeet(residual));
1685 /// But to simplify this, there's a `from_yeet` lang item function which
1686 /// handles the combined `FromResidual::from_residual(Yeet(residual))`.
1687 fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1688 // The expression (if present) or `()` otherwise.
1689 let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
1690 (sub_expr.span, self.lower_expr(sub_expr))
1692 (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
1695 let unstable_span = self.mark_span_with_reason(
1696 DesugaringKind::YeetExpr,
1698 self.allow_try_trait.clone(),
1701 let from_yeet_expr = self.wrap_in_try_constructor(
1702 hir::LangItem::TryTraitFromYeet,
1708 if let Some(catch_node) = self.catch_scope {
1709 let target_id = Ok(self.lower_node_id(catch_node));
1710 hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
1712 hir::ExprKind::Ret(Some(from_yeet_expr))
1716 // =========================================================================
1717 // Helper methods for building HIR.
1718 // =========================================================================
1720 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1722 /// In terms of drop order, it has the same effect as wrapping `expr` in
1723 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1725 /// The drop order can be important in e.g. `if expr { .. }`.
1726 pub(super) fn expr_drop_temps(
1729 expr: &'hir hir::Expr<'hir>,
1730 ) -> &'hir hir::Expr<'hir> {
1731 self.arena.alloc(self.expr_drop_temps_mut(span, expr))
1734 pub(super) fn expr_drop_temps_mut(
1737 expr: &'hir hir::Expr<'hir>,
1738 ) -> hir::Expr<'hir> {
1739 self.expr(span, hir::ExprKind::DropTemps(expr))
1745 arg: &'hir hir::Expr<'hir>,
1746 arms: &'hir [hir::Arm<'hir>],
1747 source: hir::MatchSource,
1748 ) -> hir::Expr<'hir> {
1749 self.expr(span, hir::ExprKind::Match(arg, arms, source))
1752 fn expr_break(&mut self, span: Span) -> hir::Expr<'hir> {
1753 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1754 self.expr(span, expr_break)
1757 fn expr_break_alloc(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1758 let expr_break = self.expr_break(span);
1759 self.arena.alloc(expr_break)
1762 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1763 self.expr(span, hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e))
1766 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1767 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[])))
1773 e: &'hir hir::Expr<'hir>,
1774 args: &'hir [hir::Expr<'hir>],
1775 ) -> hir::Expr<'hir> {
1776 self.expr(span, hir::ExprKind::Call(e, args))
1782 e: &'hir hir::Expr<'hir>,
1783 args: &'hir [hir::Expr<'hir>],
1784 ) -> &'hir hir::Expr<'hir> {
1785 self.arena.alloc(self.expr_call_mut(span, e, args))
1788 fn expr_call_lang_item_fn_mut(
1791 lang_item: hir::LangItem,
1792 args: &'hir [hir::Expr<'hir>],
1793 hir_id: Option<hir::HirId>,
1794 ) -> hir::Expr<'hir> {
1795 let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, hir_id));
1796 self.expr_call_mut(span, path, args)
1799 fn expr_call_lang_item_fn(
1802 lang_item: hir::LangItem,
1803 args: &'hir [hir::Expr<'hir>],
1804 hir_id: Option<hir::HirId>,
1805 ) -> &'hir hir::Expr<'hir> {
1806 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1809 fn expr_lang_item_path(
1812 lang_item: hir::LangItem,
1813 hir_id: Option<hir::HirId>,
1814 ) -> hir::Expr<'hir> {
1817 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1821 pub(super) fn expr_ident(
1825 binding: hir::HirId,
1826 ) -> &'hir hir::Expr<'hir> {
1827 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1830 pub(super) fn expr_ident_mut(
1834 binding: hir::HirId,
1835 ) -> hir::Expr<'hir> {
1836 let hir_id = self.next_id();
1837 let res = Res::Local(binding);
1838 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1840 self.arena.alloc(hir::Path {
1841 span: self.lower_span(span),
1843 segments: arena_vec![self; hir::PathSegment::new(ident, hir_id, res)],
1847 self.expr(span, expr_path)
1850 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1851 let hir_id = self.next_id();
1852 let span = expr.span;
1855 hir::ExprKind::Block(
1856 self.arena.alloc(hir::Block {
1860 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1861 span: self.lower_span(span),
1862 targeted_by_break: false,
1869 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1870 let blk = self.block_all(span, &[], None);
1871 let expr = self.expr_block(blk);
1872 self.arena.alloc(expr)
1875 pub(super) fn expr_block(&mut self, b: &'hir hir::Block<'hir>) -> hir::Expr<'hir> {
1876 self.expr(b.span, hir::ExprKind::Block(b, None))
1879 pub(super) fn expr(&mut self, span: Span, kind: hir::ExprKind<'hir>) -> hir::Expr<'hir> {
1880 let hir_id = self.next_id();
1881 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1887 expr: &'hir hir::Expr<'hir>,
1889 ) -> hir::ExprField<'hir> {
1891 hir_id: self.next_id(),
1893 span: self.lower_span(span),
1895 is_shorthand: false,
1899 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1901 hir_id: self.next_id(),
1904 span: self.lower_span(expr.span),