rustc_ast_lowering/
expr.rs

1use std::ops::ControlFlow;
2use std::sync::Arc;
3
4use rustc_ast::ptr::P as AstP;
5use rustc_ast::*;
6use rustc_ast_pretty::pprust::expr_to_string;
7use rustc_attr_data_structures::{AttributeKind, find_attr};
8use rustc_data_structures::stack::ensure_sufficient_stack;
9use rustc_hir as hir;
10use rustc_hir::HirId;
11use rustc_hir::def::{DefKind, Res};
12use rustc_middle::span_bug;
13use rustc_middle::ty::TyCtxt;
14use rustc_session::errors::report_lit_error;
15use rustc_span::source_map::{Spanned, respan};
16use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, sym};
17use thin_vec::{ThinVec, thin_vec};
18use visit::{Visitor, walk_expr};
19
20use super::errors::{
21    AsyncCoroutinesNotSupported, AwaitOnlyInAsyncFnAndBlocks, ClosureCannotBeStatic,
22    CoroutineTooManyParameters, FunctionalRecordUpdateDestructuringAssignment,
23    InclusiveRangeWithNoEnd, MatchArmWithNoBody, NeverPatternWithBody, NeverPatternWithGuard,
24    UnderscoreExprLhsAssign,
25};
26use super::{
27    GenericArgsMode, ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt,
28};
29use crate::errors::{InvalidLegacyConstGenericArg, UseConstGenericArg, YieldInClosure};
30use crate::{AllowReturnTypeNotation, FnDeclKind, ImplTraitPosition, fluent_generated};
31
32struct WillCreateDefIdsVisitor {}
33
34impl<'v> rustc_ast::visit::Visitor<'v> for WillCreateDefIdsVisitor {
35    type Result = ControlFlow<Span>;
36
37    fn visit_anon_const(&mut self, c: &'v AnonConst) -> Self::Result {
38        ControlFlow::Break(c.value.span)
39    }
40
41    fn visit_item(&mut self, item: &'v Item) -> Self::Result {
42        ControlFlow::Break(item.span)
43    }
44
45    fn visit_expr(&mut self, ex: &'v Expr) -> Self::Result {
46        match ex.kind {
47            ExprKind::Gen(..) | ExprKind::ConstBlock(..) | ExprKind::Closure(..) => {
48                ControlFlow::Break(ex.span)
49            }
50            _ => walk_expr(self, ex),
51        }
52    }
53}
54
55impl<'hir> LoweringContext<'_, 'hir> {
56    fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
57        self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
58    }
59
60    pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
61        self.arena.alloc(self.lower_expr_mut(e))
62    }
63
64    pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
65        ensure_sufficient_stack(|| {
66            match &e.kind {
67                // Parenthesis expression does not have a HirId and is handled specially.
68                ExprKind::Paren(ex) => {
69                    let mut ex = self.lower_expr_mut(ex);
70                    // Include parens in span, but only if it is a super-span.
71                    if e.span.contains(ex.span) {
72                        ex.span = self.lower_span(e.span);
73                    }
74                    // Merge attributes into the inner expression.
75                    if !e.attrs.is_empty() {
76                        let old_attrs = self.attrs.get(&ex.hir_id.local_id).copied().unwrap_or(&[]);
77                        let new_attrs = self
78                            .lower_attrs_vec(&e.attrs, e.span, ex.hir_id)
79                            .into_iter()
80                            .chain(old_attrs.iter().cloned());
81                        let new_attrs = &*self.arena.alloc_from_iter(new_attrs);
82                        if new_attrs.is_empty() {
83                            return ex;
84                        }
85                        self.attrs.insert(ex.hir_id.local_id, new_attrs);
86                    }
87                    return ex;
88                }
89                // Desugar `ExprForLoop`
90                // from: `[opt_ident]: for await? <pat> in <iter> <body>`
91                //
92                // This also needs special handling because the HirId of the returned `hir::Expr` will not
93                // correspond to the `e.id`, so `lower_expr_for` handles attribute lowering itself.
94                ExprKind::ForLoop { pat, iter, body, label, kind } => {
95                    return self.lower_expr_for(e, pat, iter, body, *label, *kind);
96                }
97                _ => (),
98            }
99
100            let expr_hir_id = self.lower_node_id(e.id);
101            self.lower_attrs(expr_hir_id, &e.attrs, e.span);
102
103            let kind = match &e.kind {
104                ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
105                ExprKind::ConstBlock(c) => hir::ExprKind::ConstBlock(self.lower_const_block(c)),
106                ExprKind::Repeat(expr, count) => {
107                    let expr = self.lower_expr(expr);
108                    let count = self.lower_array_length_to_const_arg(count);
109                    hir::ExprKind::Repeat(expr, count)
110                }
111                ExprKind::Tup(elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
112                ExprKind::Call(f, args) => {
113                    if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
114                        self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
115                    } else {
116                        let f = self.lower_expr(f);
117                        hir::ExprKind::Call(f, self.lower_exprs(args))
118                    }
119                }
120                ExprKind::MethodCall(box MethodCall { seg, receiver, args, span }) => {
121                    let hir_seg = self.arena.alloc(self.lower_path_segment(
122                        e.span,
123                        seg,
124                        ParamMode::Optional,
125                        GenericArgsMode::Err,
126                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
127                        // Method calls can't have bound modifiers
128                        None,
129                    ));
130                    let receiver = self.lower_expr(receiver);
131                    let args =
132                        self.arena.alloc_from_iter(args.iter().map(|x| self.lower_expr_mut(x)));
133                    hir::ExprKind::MethodCall(hir_seg, receiver, args, self.lower_span(*span))
134                }
135                ExprKind::Binary(binop, lhs, rhs) => {
136                    let binop = self.lower_binop(*binop);
137                    let lhs = self.lower_expr(lhs);
138                    let rhs = self.lower_expr(rhs);
139                    hir::ExprKind::Binary(binop, lhs, rhs)
140                }
141                ExprKind::Unary(op, ohs) => {
142                    let op = self.lower_unop(*op);
143                    let ohs = self.lower_expr(ohs);
144                    hir::ExprKind::Unary(op, ohs)
145                }
146                ExprKind::Lit(token_lit) => hir::ExprKind::Lit(self.lower_lit(token_lit, e.span)),
147                ExprKind::IncludedBytes(byte_sym) => {
148                    let lit = respan(
149                        self.lower_span(e.span),
150                        LitKind::ByteStr(*byte_sym, StrStyle::Cooked),
151                    );
152                    hir::ExprKind::Lit(lit)
153                }
154                ExprKind::Cast(expr, ty) => {
155                    let expr = self.lower_expr(expr);
156                    let ty =
157                        self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Cast));
158                    hir::ExprKind::Cast(expr, ty)
159                }
160                ExprKind::Type(expr, ty) => {
161                    let expr = self.lower_expr(expr);
162                    let ty =
163                        self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Cast));
164                    hir::ExprKind::Type(expr, ty)
165                }
166                ExprKind::AddrOf(k, m, ohs) => {
167                    let ohs = self.lower_expr(ohs);
168                    hir::ExprKind::AddrOf(*k, *m, ohs)
169                }
170                ExprKind::Let(pat, scrutinee, span, recovered) => {
171                    hir::ExprKind::Let(self.arena.alloc(hir::LetExpr {
172                        span: self.lower_span(*span),
173                        pat: self.lower_pat(pat),
174                        ty: None,
175                        init: self.lower_expr(scrutinee),
176                        recovered: *recovered,
177                    }))
178                }
179                ExprKind::If(cond, then, else_opt) => {
180                    self.lower_expr_if(cond, then, else_opt.as_deref())
181                }
182                ExprKind::While(cond, body, opt_label) => {
183                    self.with_loop_scope(expr_hir_id, |this| {
184                        let span =
185                            this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
186                        let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id);
187                        this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
188                    })
189                }
190                ExprKind::Loop(body, opt_label, span) => {
191                    self.with_loop_scope(expr_hir_id, |this| {
192                        let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id);
193                        hir::ExprKind::Loop(
194                            this.lower_block(body, false),
195                            opt_label,
196                            hir::LoopSource::Loop,
197                            this.lower_span(*span),
198                        )
199                    })
200                }
201                ExprKind::TryBlock(body) => self.lower_expr_try_block(body),
202                ExprKind::Match(expr, arms, kind) => hir::ExprKind::Match(
203                    self.lower_expr(expr),
204                    self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
205                    match kind {
206                        MatchKind::Prefix => hir::MatchSource::Normal,
207                        MatchKind::Postfix => hir::MatchSource::Postfix,
208                    },
209                ),
210                ExprKind::Await(expr, await_kw_span) => self.lower_expr_await(*await_kw_span, expr),
211                ExprKind::Use(expr, use_kw_span) => self.lower_expr_use(*use_kw_span, expr),
212                ExprKind::Closure(box Closure {
213                    binder,
214                    capture_clause,
215                    constness,
216                    coroutine_kind,
217                    movability,
218                    fn_decl,
219                    body,
220                    fn_decl_span,
221                    fn_arg_span,
222                }) => match coroutine_kind {
223                    Some(coroutine_kind) => self.lower_expr_coroutine_closure(
224                        binder,
225                        *capture_clause,
226                        e.id,
227                        expr_hir_id,
228                        *coroutine_kind,
229                        fn_decl,
230                        body,
231                        *fn_decl_span,
232                        *fn_arg_span,
233                    ),
234                    None => self.lower_expr_closure(
235                        binder,
236                        *capture_clause,
237                        e.id,
238                        expr_hir_id,
239                        *constness,
240                        *movability,
241                        fn_decl,
242                        body,
243                        *fn_decl_span,
244                        *fn_arg_span,
245                    ),
246                },
247                ExprKind::Gen(capture_clause, block, genblock_kind, decl_span) => {
248                    let desugaring_kind = match genblock_kind {
249                        GenBlockKind::Async => hir::CoroutineDesugaring::Async,
250                        GenBlockKind::Gen => hir::CoroutineDesugaring::Gen,
251                        GenBlockKind::AsyncGen => hir::CoroutineDesugaring::AsyncGen,
252                    };
253                    self.make_desugared_coroutine_expr(
254                        *capture_clause,
255                        e.id,
256                        None,
257                        *decl_span,
258                        e.span,
259                        desugaring_kind,
260                        hir::CoroutineSource::Block,
261                        |this| this.with_new_scopes(e.span, |this| this.lower_block_expr(block)),
262                    )
263                }
264                ExprKind::Block(blk, opt_label) => {
265                    // Different from loops, label of block resolves to block id rather than
266                    // expr node id.
267                    let block_hir_id = self.lower_node_id(blk.id);
268                    let opt_label = self.lower_label(*opt_label, blk.id, block_hir_id);
269                    let hir_block = self.arena.alloc(self.lower_block_noalloc(
270                        block_hir_id,
271                        blk,
272                        opt_label.is_some(),
273                    ));
274                    hir::ExprKind::Block(hir_block, opt_label)
275                }
276                ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span),
277                ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp(
278                    self.lower_assign_op(*op),
279                    self.lower_expr(el),
280                    self.lower_expr(er),
281                ),
282                ExprKind::Field(el, ident) => {
283                    hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(*ident))
284                }
285                ExprKind::Index(el, er, brackets_span) => {
286                    hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er), *brackets_span)
287                }
288                ExprKind::Range(e1, e2, lims) => {
289                    self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), *lims)
290                }
291                ExprKind::Underscore => {
292                    let guar = self.dcx().emit_err(UnderscoreExprLhsAssign { span: e.span });
293                    hir::ExprKind::Err(guar)
294                }
295                ExprKind::Path(qself, path) => {
296                    let qpath = self.lower_qpath(
297                        e.id,
298                        qself,
299                        path,
300                        ParamMode::Optional,
301                        AllowReturnTypeNotation::No,
302                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
303                        None,
304                    );
305                    hir::ExprKind::Path(qpath)
306                }
307                ExprKind::Break(opt_label, opt_expr) => {
308                    let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
309                    hir::ExprKind::Break(self.lower_jump_destination(e.id, *opt_label), opt_expr)
310                }
311                ExprKind::Continue(opt_label) => {
312                    hir::ExprKind::Continue(self.lower_jump_destination(e.id, *opt_label))
313                }
314                ExprKind::Ret(e) => {
315                    let expr = e.as_ref().map(|x| self.lower_expr(x));
316                    self.checked_return(expr)
317                }
318                ExprKind::Yeet(sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
319                ExprKind::Become(sub_expr) => {
320                    let sub_expr = self.lower_expr(sub_expr);
321                    hir::ExprKind::Become(sub_expr)
322                }
323                ExprKind::InlineAsm(asm) => {
324                    hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
325                }
326                ExprKind::FormatArgs(fmt) => self.lower_format_args(e.span, fmt),
327                ExprKind::OffsetOf(container, fields) => hir::ExprKind::OffsetOf(
328                    self.lower_ty(
329                        container,
330                        ImplTraitContext::Disallowed(ImplTraitPosition::OffsetOf),
331                    ),
332                    self.arena.alloc_from_iter(fields.iter().map(|&ident| self.lower_ident(ident))),
333                ),
334                ExprKind::Struct(se) => {
335                    let rest = match &se.rest {
336                        StructRest::Base(e) => hir::StructTailExpr::Base(self.lower_expr(e)),
337                        StructRest::Rest(sp) => hir::StructTailExpr::DefaultFields(*sp),
338                        StructRest::None => hir::StructTailExpr::None,
339                    };
340                    hir::ExprKind::Struct(
341                        self.arena.alloc(self.lower_qpath(
342                            e.id,
343                            &se.qself,
344                            &se.path,
345                            ParamMode::Optional,
346                            AllowReturnTypeNotation::No,
347                            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
348                            None,
349                        )),
350                        self.arena
351                            .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
352                        rest,
353                    )
354                }
355                ExprKind::Yield(kind) => self.lower_expr_yield(e.span, kind.expr().map(|x| &**x)),
356                ExprKind::Err(guar) => hir::ExprKind::Err(*guar),
357
358                ExprKind::UnsafeBinderCast(kind, expr, ty) => hir::ExprKind::UnsafeBinderCast(
359                    *kind,
360                    self.lower_expr(expr),
361                    ty.as_ref().map(|ty| {
362                        self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Cast))
363                    }),
364                ),
365
366                ExprKind::Dummy => {
367                    span_bug!(e.span, "lowered ExprKind::Dummy")
368                }
369
370                ExprKind::Try(sub_expr) => self.lower_expr_try(e.span, sub_expr),
371
372                ExprKind::Paren(_) | ExprKind::ForLoop { .. } => {
373                    unreachable!("already handled")
374                }
375
376                ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
377            };
378
379            hir::Expr { hir_id: expr_hir_id, kind, span: self.lower_span(e.span) }
380        })
381    }
382
383    /// Create an `ExprKind::Ret` that is optionally wrapped by a call to check
384    /// a contract ensures clause, if it exists.
385    fn checked_return(&mut self, opt_expr: Option<&'hir hir::Expr<'hir>>) -> hir::ExprKind<'hir> {
386        let checked_ret =
387            if let Some((check_span, check_ident, check_hir_id)) = self.contract_ensures {
388                let expr = opt_expr.unwrap_or_else(|| self.expr_unit(check_span));
389                Some(self.inject_ensures_check(expr, check_span, check_ident, check_hir_id))
390            } else {
391                opt_expr
392            };
393        hir::ExprKind::Ret(checked_ret)
394    }
395
396    /// Wraps an expression with a call to the ensures check before it gets returned.
397    pub(crate) fn inject_ensures_check(
398        &mut self,
399        expr: &'hir hir::Expr<'hir>,
400        span: Span,
401        cond_ident: Ident,
402        cond_hir_id: HirId,
403    ) -> &'hir hir::Expr<'hir> {
404        let cond_fn = self.expr_ident(span, cond_ident, cond_hir_id);
405        let call_expr = self.expr_call_lang_item_fn_mut(
406            span,
407            hir::LangItem::ContractCheckEnsures,
408            arena_vec![self; *cond_fn, *expr],
409        );
410        self.arena.alloc(call_expr)
411    }
412
413    pub(crate) fn lower_const_block(&mut self, c: &AnonConst) -> hir::ConstBlock {
414        self.with_new_scopes(c.value.span, |this| {
415            let def_id = this.local_def_id(c.id);
416            hir::ConstBlock {
417                def_id,
418                hir_id: this.lower_node_id(c.id),
419                body: this.lower_const_body(c.value.span, Some(&c.value)),
420            }
421        })
422    }
423
424    pub(crate) fn lower_lit(&mut self, token_lit: &token::Lit, span: Span) -> hir::Lit {
425        let lit_kind = match LitKind::from_token_lit(*token_lit) {
426            Ok(lit_kind) => lit_kind,
427            Err(err) => {
428                let guar = report_lit_error(&self.tcx.sess.psess, err, *token_lit, span);
429                LitKind::Err(guar)
430            }
431        };
432        respan(self.lower_span(span), lit_kind)
433    }
434
435    fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
436        match u {
437            UnOp::Deref => hir::UnOp::Deref,
438            UnOp::Not => hir::UnOp::Not,
439            UnOp::Neg => hir::UnOp::Neg,
440        }
441    }
442
443    fn lower_binop(&mut self, b: BinOp) -> BinOp {
444        Spanned { node: b.node, span: self.lower_span(b.span) }
445    }
446
447    fn lower_assign_op(&mut self, a: AssignOp) -> AssignOp {
448        Spanned { node: a.node, span: self.lower_span(a.span) }
449    }
450
451    fn lower_legacy_const_generics(
452        &mut self,
453        mut f: Expr,
454        args: ThinVec<AstP<Expr>>,
455        legacy_args_idx: &[usize],
456    ) -> hir::ExprKind<'hir> {
457        let ExprKind::Path(None, path) = &mut f.kind else {
458            unreachable!();
459        };
460
461        let mut error = None;
462        let mut invalid_expr_error = |tcx: TyCtxt<'_>, span| {
463            // Avoid emitting the error multiple times.
464            if error.is_none() {
465                let mut const_args = vec![];
466                let mut other_args = vec![];
467                for (idx, arg) in args.iter().enumerate() {
468                    if legacy_args_idx.contains(&idx) {
469                        const_args.push(format!("{{ {} }}", expr_to_string(arg)));
470                    } else {
471                        other_args.push(expr_to_string(arg));
472                    }
473                }
474                let suggestion = UseConstGenericArg {
475                    end_of_fn: f.span.shrink_to_hi(),
476                    const_args: const_args.join(", "),
477                    other_args: other_args.join(", "),
478                    call_args: args[0].span.to(args.last().unwrap().span),
479                };
480                error = Some(tcx.dcx().emit_err(InvalidLegacyConstGenericArg { span, suggestion }));
481            }
482            error.unwrap()
483        };
484
485        // Split the arguments into const generics and normal arguments
486        let mut real_args = vec![];
487        let mut generic_args = ThinVec::new();
488        for (idx, arg) in args.iter().cloned().enumerate() {
489            if legacy_args_idx.contains(&idx) {
490                let node_id = self.next_node_id();
491                self.create_def(node_id, None, DefKind::AnonConst, f.span);
492                let mut visitor = WillCreateDefIdsVisitor {};
493                let const_value = if let ControlFlow::Break(span) = visitor.visit_expr(&arg) {
494                    AstP(Expr {
495                        id: self.next_node_id(),
496                        kind: ExprKind::Err(invalid_expr_error(self.tcx, span)),
497                        span: f.span,
498                        attrs: [].into(),
499                        tokens: None,
500                    })
501                } else {
502                    arg
503                };
504
505                let anon_const = AnonConst { id: node_id, value: const_value };
506                generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
507            } else {
508                real_args.push(arg);
509            }
510        }
511
512        // Add generic args to the last element of the path.
513        let last_segment = path.segments.last_mut().unwrap();
514        assert!(last_segment.args.is_none());
515        last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
516            span: DUMMY_SP,
517            args: generic_args,
518        })));
519
520        // Now lower everything as normal.
521        let f = self.lower_expr(&f);
522        hir::ExprKind::Call(f, self.lower_exprs(&real_args))
523    }
524
525    fn lower_expr_if(
526        &mut self,
527        cond: &Expr,
528        then: &Block,
529        else_opt: Option<&Expr>,
530    ) -> hir::ExprKind<'hir> {
531        let lowered_cond = self.lower_expr(cond);
532        let then_expr = self.lower_block_expr(then);
533        if let Some(rslt) = else_opt {
534            hir::ExprKind::If(
535                lowered_cond,
536                self.arena.alloc(then_expr),
537                Some(self.lower_expr(rslt)),
538            )
539        } else {
540            hir::ExprKind::If(lowered_cond, self.arena.alloc(then_expr), None)
541        }
542    }
543
544    // We desugar: `'label: while $cond $body` into:
545    //
546    // ```
547    // 'label: loop {
548    //   if { let _t = $cond; _t } {
549    //     $body
550    //   }
551    //   else {
552    //     break;
553    //   }
554    // }
555    // ```
556    //
557    // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
558    // to preserve drop semantics since `while $cond { ... }` does not
559    // let temporaries live outside of `cond`.
560    fn lower_expr_while_in_loop_scope(
561        &mut self,
562        span: Span,
563        cond: &Expr,
564        body: &Block,
565        opt_label: Option<Label>,
566    ) -> hir::ExprKind<'hir> {
567        let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
568        let then = self.lower_block_expr(body);
569        let expr_break = self.expr_break(span);
570        let stmt_break = self.stmt_expr(span, expr_break);
571        let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
572        let else_expr = self.arena.alloc(self.expr_block(else_blk));
573        let if_kind = hir::ExprKind::If(lowered_cond, self.arena.alloc(then), Some(else_expr));
574        let if_expr = self.expr(span, if_kind);
575        let block = self.block_expr(self.arena.alloc(if_expr));
576        let span = self.lower_span(span.with_hi(cond.span.hi()));
577        hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
578    }
579
580    /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
581    /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
582    /// and save the block id to use it as a break target for desugaring of the `?` operator.
583    fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
584        let body_hir_id = self.lower_node_id(body.id);
585        self.with_catch_scope(body_hir_id, |this| {
586            let mut block = this.lower_block_noalloc(body_hir_id, body, true);
587
588            // Final expression of the block (if present) or `()` with span at the end of block
589            let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
590                (
591                    this.mark_span_with_reason(
592                        DesugaringKind::TryBlock,
593                        expr.span,
594                        Some(Arc::clone(&this.allow_try_trait)),
595                    ),
596                    expr,
597                )
598            } else {
599                let try_span = this.mark_span_with_reason(
600                    DesugaringKind::TryBlock,
601                    this.tcx.sess.source_map().end_point(body.span),
602                    Some(Arc::clone(&this.allow_try_trait)),
603                );
604
605                (try_span, this.expr_unit(try_span))
606            };
607
608            let ok_wrapped_span =
609                this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
610
611            // `::std::ops::Try::from_output($tail_expr)`
612            block.expr = Some(this.wrap_in_try_constructor(
613                hir::LangItem::TryTraitFromOutput,
614                try_span,
615                tail_expr,
616                ok_wrapped_span,
617            ));
618
619            hir::ExprKind::Block(this.arena.alloc(block), None)
620        })
621    }
622
623    fn wrap_in_try_constructor(
624        &mut self,
625        lang_item: hir::LangItem,
626        method_span: Span,
627        expr: &'hir hir::Expr<'hir>,
628        overall_span: Span,
629    ) -> &'hir hir::Expr<'hir> {
630        let constructor = self.arena.alloc(self.expr_lang_item_path(method_span, lang_item));
631        self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
632    }
633
634    fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
635        let pat = self.lower_pat(&arm.pat);
636        let guard = arm.guard.as_ref().map(|cond| self.lower_expr(cond));
637        let hir_id = self.next_id();
638        let span = self.lower_span(arm.span);
639        self.lower_attrs(hir_id, &arm.attrs, arm.span);
640        let is_never_pattern = pat.is_never_pattern();
641        // We need to lower the body even if it's unneeded for never pattern in match,
642        // ensure that we can get HirId for DefId if need (issue #137708).
643        let body = arm.body.as_ref().map(|x| self.lower_expr(x));
644        let body = if let Some(body) = body
645            && !is_never_pattern
646        {
647            body
648        } else {
649            // Either `body.is_none()` or `is_never_pattern` here.
650            if !is_never_pattern {
651                if self.tcx.features().never_patterns() {
652                    // If the feature is off we already emitted the error after parsing.
653                    let suggestion = span.shrink_to_hi();
654                    self.dcx().emit_err(MatchArmWithNoBody { span, suggestion });
655                }
656            } else if let Some(body) = &arm.body {
657                self.dcx().emit_err(NeverPatternWithBody { span: body.span });
658            } else if let Some(g) = &arm.guard {
659                self.dcx().emit_err(NeverPatternWithGuard { span: g.span });
660            }
661
662            // We add a fake `loop {}` arm body so that it typecks to `!`. The mir lowering of never
663            // patterns ensures this loop is not reachable.
664            let block = self.arena.alloc(hir::Block {
665                stmts: &[],
666                expr: None,
667                hir_id: self.next_id(),
668                rules: hir::BlockCheckMode::DefaultBlock,
669                span,
670                targeted_by_break: false,
671            });
672            self.arena.alloc(hir::Expr {
673                hir_id: self.next_id(),
674                kind: hir::ExprKind::Loop(block, None, hir::LoopSource::Loop, span),
675                span,
676            })
677        };
678        hir::Arm { hir_id, pat, guard, body, span }
679    }
680
681    /// Lower/desugar a coroutine construct.
682    ///
683    /// In particular, this creates the correct async resume argument and `_task_context`.
684    ///
685    /// This results in:
686    ///
687    /// ```text
688    /// static move? |<_task_context?>| -> <return_ty> {
689    ///     <body>
690    /// }
691    /// ```
692    pub(super) fn make_desugared_coroutine_expr(
693        &mut self,
694        capture_clause: CaptureBy,
695        closure_node_id: NodeId,
696        return_ty: Option<hir::FnRetTy<'hir>>,
697        fn_decl_span: Span,
698        span: Span,
699        desugaring_kind: hir::CoroutineDesugaring,
700        coroutine_source: hir::CoroutineSource,
701        body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
702    ) -> hir::ExprKind<'hir> {
703        let closure_def_id = self.local_def_id(closure_node_id);
704        let coroutine_kind = hir::CoroutineKind::Desugared(desugaring_kind, coroutine_source);
705
706        // The `async` desugaring takes a resume argument and maintains a `task_context`,
707        // whereas a generator does not.
708        let (inputs, params, task_context): (&[_], &[_], _) = match desugaring_kind {
709            hir::CoroutineDesugaring::Async | hir::CoroutineDesugaring::AsyncGen => {
710                // Resume argument type: `ResumeTy`
711                let unstable_span = self.mark_span_with_reason(
712                    DesugaringKind::Async,
713                    self.lower_span(span),
714                    Some(Arc::clone(&self.allow_gen_future)),
715                );
716                let resume_ty =
717                    self.make_lang_item_qpath(hir::LangItem::ResumeTy, unstable_span, None);
718                let input_ty = hir::Ty {
719                    hir_id: self.next_id(),
720                    kind: hir::TyKind::Path(resume_ty),
721                    span: unstable_span,
722                };
723                let inputs = arena_vec![self; input_ty];
724
725                // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
726                let (pat, task_context_hid) = self.pat_ident_binding_mode(
727                    span,
728                    Ident::with_dummy_span(sym::_task_context),
729                    hir::BindingMode::MUT,
730                );
731                let param = hir::Param {
732                    hir_id: self.next_id(),
733                    pat,
734                    ty_span: self.lower_span(span),
735                    span: self.lower_span(span),
736                };
737                let params = arena_vec![self; param];
738
739                (inputs, params, Some(task_context_hid))
740            }
741            hir::CoroutineDesugaring::Gen => (&[], &[], None),
742        };
743
744        let output =
745            return_ty.unwrap_or_else(|| hir::FnRetTy::DefaultReturn(self.lower_span(span)));
746
747        let fn_decl = self.arena.alloc(hir::FnDecl {
748            inputs,
749            output,
750            c_variadic: false,
751            implicit_self: hir::ImplicitSelfKind::None,
752            lifetime_elision_allowed: false,
753        });
754
755        let body = self.lower_body(move |this| {
756            this.coroutine_kind = Some(coroutine_kind);
757
758            let old_ctx = this.task_context;
759            if task_context.is_some() {
760                this.task_context = task_context;
761            }
762            let res = body(this);
763            this.task_context = old_ctx;
764
765            (params, res)
766        });
767
768        // `static |<_task_context?>| -> <return_ty> { <body> }`:
769        hir::ExprKind::Closure(self.arena.alloc(hir::Closure {
770            def_id: closure_def_id,
771            binder: hir::ClosureBinder::Default,
772            capture_clause,
773            bound_generic_params: &[],
774            fn_decl,
775            body,
776            fn_decl_span: self.lower_span(fn_decl_span),
777            fn_arg_span: None,
778            kind: hir::ClosureKind::Coroutine(coroutine_kind),
779            constness: hir::Constness::NotConst,
780        }))
781    }
782
783    /// Forwards a possible `#[track_caller]` annotation from `outer_hir_id` to
784    /// `inner_hir_id` in case the `async_fn_track_caller` feature is enabled.
785    pub(super) fn maybe_forward_track_caller(
786        &mut self,
787        span: Span,
788        outer_hir_id: HirId,
789        inner_hir_id: HirId,
790    ) {
791        if self.tcx.features().async_fn_track_caller()
792            && let Some(attrs) = self.attrs.get(&outer_hir_id.local_id)
793            && find_attr!(*attrs, AttributeKind::TrackCaller(_))
794        {
795            let unstable_span = self.mark_span_with_reason(
796                DesugaringKind::Async,
797                span,
798                Some(Arc::clone(&self.allow_gen_future)),
799            );
800            self.lower_attrs(
801                inner_hir_id,
802                &[Attribute {
803                    kind: AttrKind::Normal(ptr::P(NormalAttr::from_ident(Ident::new(
804                        sym::track_caller,
805                        span,
806                    )))),
807                    id: self.tcx.sess.psess.attr_id_generator.mk_attr_id(),
808                    style: AttrStyle::Outer,
809                    span: unstable_span,
810                }],
811                span,
812            );
813        }
814    }
815
816    /// Desugar `<expr>.await` into:
817    /// ```ignore (pseudo-rust)
818    /// match ::std::future::IntoFuture::into_future(<expr>) {
819    ///     mut __awaitee => loop {
820    ///         match unsafe { ::std::future::Future::poll(
821    ///             <::std::pin::Pin>::new_unchecked(&mut __awaitee),
822    ///             ::std::future::get_context(task_context),
823    ///         ) } {
824    ///             ::std::task::Poll::Ready(result) => break result,
825    ///             ::std::task::Poll::Pending => {}
826    ///         }
827    ///         task_context = yield ();
828    ///     }
829    /// }
830    /// ```
831    fn lower_expr_await(&mut self, await_kw_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
832        let expr = self.arena.alloc(self.lower_expr_mut(expr));
833        self.make_lowered_await(await_kw_span, expr, FutureKind::Future)
834    }
835
836    /// Takes an expr that has already been lowered and generates a desugared await loop around it
837    fn make_lowered_await(
838        &mut self,
839        await_kw_span: Span,
840        expr: &'hir hir::Expr<'hir>,
841        await_kind: FutureKind,
842    ) -> hir::ExprKind<'hir> {
843        let full_span = expr.span.to(await_kw_span);
844
845        let is_async_gen = match self.coroutine_kind {
846            Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => false,
847            Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => true,
848            Some(hir::CoroutineKind::Coroutine(_))
849            | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _))
850            | None => {
851                // Lower to a block `{ EXPR; <error> }` so that the awaited expr
852                // is not accidentally orphaned.
853                let stmt_id = self.next_id();
854                let expr_err = self.expr(
855                    expr.span,
856                    hir::ExprKind::Err(self.dcx().emit_err(AwaitOnlyInAsyncFnAndBlocks {
857                        await_kw_span,
858                        item_span: self.current_item,
859                    })),
860                );
861                return hir::ExprKind::Block(
862                    self.block_all(
863                        expr.span,
864                        arena_vec![self; hir::Stmt {
865                            hir_id: stmt_id,
866                            kind: hir::StmtKind::Semi(expr),
867                            span: expr.span,
868                        }],
869                        Some(self.arena.alloc(expr_err)),
870                    ),
871                    None,
872                );
873            }
874        };
875
876        let features = match await_kind {
877            FutureKind::Future => None,
878            FutureKind::AsyncIterator => Some(Arc::clone(&self.allow_for_await)),
879        };
880        let span = self.mark_span_with_reason(DesugaringKind::Await, await_kw_span, features);
881        let gen_future_span = self.mark_span_with_reason(
882            DesugaringKind::Await,
883            full_span,
884            Some(Arc::clone(&self.allow_gen_future)),
885        );
886        let expr_hir_id = expr.hir_id;
887
888        // Note that the name of this binding must not be changed to something else because
889        // debuggers and debugger extensions expect it to be called `__awaitee`. They use
890        // this name to identify what is being awaited by a suspended async functions.
891        let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
892        let (awaitee_pat, awaitee_pat_hid) =
893            self.pat_ident_binding_mode(gen_future_span, awaitee_ident, hir::BindingMode::MUT);
894
895        let task_context_ident = Ident::with_dummy_span(sym::_task_context);
896
897        // unsafe {
898        //     ::std::future::Future::poll(
899        //         ::std::pin::Pin::new_unchecked(&mut __awaitee),
900        //         ::std::future::get_context(task_context),
901        //     )
902        // }
903        let poll_expr = {
904            let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
905            let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
906
907            let Some(task_context_hid) = self.task_context else {
908                unreachable!("use of `await` outside of an async context.");
909            };
910
911            let task_context = self.expr_ident_mut(span, task_context_ident, task_context_hid);
912
913            let new_unchecked = self.expr_call_lang_item_fn_mut(
914                span,
915                hir::LangItem::PinNewUnchecked,
916                arena_vec![self; ref_mut_awaitee],
917            );
918            let get_context = self.expr_call_lang_item_fn_mut(
919                gen_future_span,
920                hir::LangItem::GetContext,
921                arena_vec![self; task_context],
922            );
923            let call = match await_kind {
924                FutureKind::Future => self.expr_call_lang_item_fn(
925                    span,
926                    hir::LangItem::FuturePoll,
927                    arena_vec![self; new_unchecked, get_context],
928                ),
929                FutureKind::AsyncIterator => self.expr_call_lang_item_fn(
930                    span,
931                    hir::LangItem::AsyncIteratorPollNext,
932                    arena_vec![self; new_unchecked, get_context],
933                ),
934            };
935            self.arena.alloc(self.expr_unsafe(call))
936        };
937
938        // `::std::task::Poll::Ready(result) => break result`
939        let loop_node_id = self.next_node_id();
940        let loop_hir_id = self.lower_node_id(loop_node_id);
941        let ready_arm = {
942            let x_ident = Ident::with_dummy_span(sym::result);
943            let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
944            let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
945            let ready_field = self.single_pat_field(gen_future_span, x_pat);
946            let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
947            let break_x = self.with_loop_scope(loop_hir_id, move |this| {
948                let expr_break =
949                    hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
950                this.arena.alloc(this.expr(gen_future_span, expr_break))
951            });
952            self.arm(ready_pat, break_x)
953        };
954
955        // `::std::task::Poll::Pending => {}`
956        let pending_arm = {
957            let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]);
958            let empty_block = self.expr_block_empty(span);
959            self.arm(pending_pat, empty_block)
960        };
961
962        let inner_match_stmt = {
963            let match_expr = self.expr_match(
964                span,
965                poll_expr,
966                arena_vec![self; ready_arm, pending_arm],
967                hir::MatchSource::AwaitDesugar,
968            );
969            self.stmt_expr(span, match_expr)
970        };
971
972        // Depending on `async` of `async gen`:
973        // async     - task_context = yield ();
974        // async gen - task_context = yield ASYNC_GEN_PENDING;
975        let yield_stmt = {
976            let yielded = if is_async_gen {
977                self.arena.alloc(self.expr_lang_item_path(span, hir::LangItem::AsyncGenPending))
978            } else {
979                self.expr_unit(span)
980            };
981
982            let yield_expr = self.expr(
983                span,
984                hir::ExprKind::Yield(yielded, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
985            );
986            let yield_expr = self.arena.alloc(yield_expr);
987
988            let Some(task_context_hid) = self.task_context else {
989                unreachable!("use of `await` outside of an async context.");
990            };
991
992            let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
993            let assign =
994                self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)));
995            self.stmt_expr(span, assign)
996        };
997
998        let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
999
1000        // loop { .. }
1001        let loop_expr = self.arena.alloc(hir::Expr {
1002            hir_id: loop_hir_id,
1003            kind: hir::ExprKind::Loop(
1004                loop_block,
1005                None,
1006                hir::LoopSource::Loop,
1007                self.lower_span(span),
1008            ),
1009            span: self.lower_span(span),
1010        });
1011
1012        // mut __awaitee => loop { ... }
1013        let awaitee_arm = self.arm(awaitee_pat, loop_expr);
1014
1015        // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
1016        let into_future_expr = match await_kind {
1017            FutureKind::Future => self.expr_call_lang_item_fn(
1018                span,
1019                hir::LangItem::IntoFutureIntoFuture,
1020                arena_vec![self; *expr],
1021            ),
1022            // Not needed for `for await` because we expect to have already called
1023            // `IntoAsyncIterator::into_async_iter` on it.
1024            FutureKind::AsyncIterator => expr,
1025        };
1026
1027        // match <into_future_expr> {
1028        //     mut __awaitee => loop { .. }
1029        // }
1030        hir::ExprKind::Match(
1031            into_future_expr,
1032            arena_vec![self; awaitee_arm],
1033            hir::MatchSource::AwaitDesugar,
1034        )
1035    }
1036
1037    fn lower_expr_use(&mut self, use_kw_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
1038        hir::ExprKind::Use(self.lower_expr(expr), use_kw_span)
1039    }
1040
1041    fn lower_expr_closure(
1042        &mut self,
1043        binder: &ClosureBinder,
1044        capture_clause: CaptureBy,
1045        closure_id: NodeId,
1046        closure_hir_id: hir::HirId,
1047        constness: Const,
1048        movability: Movability,
1049        decl: &FnDecl,
1050        body: &Expr,
1051        fn_decl_span: Span,
1052        fn_arg_span: Span,
1053    ) -> hir::ExprKind<'hir> {
1054        let closure_def_id = self.local_def_id(closure_id);
1055        let (binder_clause, generic_params) = self.lower_closure_binder(binder);
1056
1057        let (body_id, closure_kind) = self.with_new_scopes(fn_decl_span, move |this| {
1058            let mut coroutine_kind = if this
1059                .attrs
1060                .get(&closure_hir_id.local_id)
1061                .is_some_and(|attrs| attrs.iter().any(|attr| attr.has_name(sym::coroutine)))
1062            {
1063                Some(hir::CoroutineKind::Coroutine(Movability::Movable))
1064            } else {
1065                None
1066            };
1067            // FIXME(contracts): Support contracts on closures?
1068            let body_id = this.lower_fn_body(decl, None, |this| {
1069                this.coroutine_kind = coroutine_kind;
1070                let e = this.lower_expr_mut(body);
1071                coroutine_kind = this.coroutine_kind;
1072                e
1073            });
1074            let coroutine_option =
1075                this.closure_movability_for_fn(decl, fn_decl_span, coroutine_kind, movability);
1076            (body_id, coroutine_option)
1077        });
1078
1079        let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
1080        // Lower outside new scope to preserve `is_in_loop_condition`.
1081        let fn_decl = self.lower_fn_decl(decl, closure_id, fn_decl_span, FnDeclKind::Closure, None);
1082
1083        let c = self.arena.alloc(hir::Closure {
1084            def_id: closure_def_id,
1085            binder: binder_clause,
1086            capture_clause,
1087            bound_generic_params,
1088            fn_decl,
1089            body: body_id,
1090            fn_decl_span: self.lower_span(fn_decl_span),
1091            fn_arg_span: Some(self.lower_span(fn_arg_span)),
1092            kind: closure_kind,
1093            constness: self.lower_constness(constness),
1094        });
1095
1096        hir::ExprKind::Closure(c)
1097    }
1098
1099    fn closure_movability_for_fn(
1100        &mut self,
1101        decl: &FnDecl,
1102        fn_decl_span: Span,
1103        coroutine_kind: Option<hir::CoroutineKind>,
1104        movability: Movability,
1105    ) -> hir::ClosureKind {
1106        match coroutine_kind {
1107            Some(hir::CoroutineKind::Coroutine(_)) => {
1108                if decl.inputs.len() > 1 {
1109                    self.dcx().emit_err(CoroutineTooManyParameters { fn_decl_span });
1110                }
1111                hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(movability))
1112            }
1113            Some(
1114                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
1115                | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
1116                | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _),
1117            ) => {
1118                panic!("non-`async`/`gen` closure body turned `async`/`gen` during lowering");
1119            }
1120            None => {
1121                if movability == Movability::Static {
1122                    self.dcx().emit_err(ClosureCannotBeStatic { fn_decl_span });
1123                }
1124                hir::ClosureKind::Closure
1125            }
1126        }
1127    }
1128
1129    fn lower_closure_binder<'c>(
1130        &mut self,
1131        binder: &'c ClosureBinder,
1132    ) -> (hir::ClosureBinder, &'c [GenericParam]) {
1133        let (binder, params) = match binder {
1134            ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]),
1135            ClosureBinder::For { span, generic_params } => {
1136                let span = self.lower_span(*span);
1137                (hir::ClosureBinder::For { span }, &**generic_params)
1138            }
1139        };
1140
1141        (binder, params)
1142    }
1143
1144    fn lower_expr_coroutine_closure(
1145        &mut self,
1146        binder: &ClosureBinder,
1147        capture_clause: CaptureBy,
1148        closure_id: NodeId,
1149        closure_hir_id: HirId,
1150        coroutine_kind: CoroutineKind,
1151        decl: &FnDecl,
1152        body: &Expr,
1153        fn_decl_span: Span,
1154        fn_arg_span: Span,
1155    ) -> hir::ExprKind<'hir> {
1156        let closure_def_id = self.local_def_id(closure_id);
1157        let (binder_clause, generic_params) = self.lower_closure_binder(binder);
1158
1159        let coroutine_desugaring = match coroutine_kind {
1160            CoroutineKind::Async { .. } => hir::CoroutineDesugaring::Async,
1161            CoroutineKind::Gen { .. } => hir::CoroutineDesugaring::Gen,
1162            CoroutineKind::AsyncGen { span, .. } => {
1163                span_bug!(span, "only async closures and `iter!` closures are supported currently")
1164            }
1165        };
1166
1167        let body = self.with_new_scopes(fn_decl_span, |this| {
1168            let inner_decl =
1169                FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
1170
1171            // Transform `async |x: u8| -> X { ... }` into
1172            // `|x: u8| || -> X { ... }`.
1173            let body_id = this.lower_body(|this| {
1174                let (parameters, expr) = this.lower_coroutine_body_with_moved_arguments(
1175                    &inner_decl,
1176                    |this| this.with_new_scopes(fn_decl_span, |this| this.lower_expr_mut(body)),
1177                    fn_decl_span,
1178                    body.span,
1179                    coroutine_kind,
1180                    hir::CoroutineSource::Closure,
1181                );
1182
1183                this.maybe_forward_track_caller(body.span, closure_hir_id, expr.hir_id);
1184
1185                (parameters, expr)
1186            });
1187            body_id
1188        });
1189
1190        let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
1191        // We need to lower the declaration outside the new scope, because we
1192        // have to conserve the state of being inside a loop condition for the
1193        // closure argument types.
1194        let fn_decl =
1195            self.lower_fn_decl(&decl, closure_id, fn_decl_span, FnDeclKind::Closure, None);
1196
1197        let c = self.arena.alloc(hir::Closure {
1198            def_id: closure_def_id,
1199            binder: binder_clause,
1200            capture_clause,
1201            bound_generic_params,
1202            fn_decl,
1203            body,
1204            fn_decl_span: self.lower_span(fn_decl_span),
1205            fn_arg_span: Some(self.lower_span(fn_arg_span)),
1206            // Lower this as a `CoroutineClosure`. That will ensure that HIR typeck
1207            // knows that a `FnDecl` output type like `-> &str` actually means
1208            // "coroutine that returns &str", rather than directly returning a `&str`.
1209            kind: hir::ClosureKind::CoroutineClosure(coroutine_desugaring),
1210            constness: hir::Constness::NotConst,
1211        });
1212        hir::ExprKind::Closure(c)
1213    }
1214
1215    /// Destructure the LHS of complex assignments.
1216    /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
1217    fn lower_expr_assign(
1218        &mut self,
1219        lhs: &Expr,
1220        rhs: &Expr,
1221        eq_sign_span: Span,
1222        whole_span: Span,
1223    ) -> hir::ExprKind<'hir> {
1224        // Return early in case of an ordinary assignment.
1225        fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
1226            match &lhs.kind {
1227                ExprKind::Array(..)
1228                | ExprKind::Struct(..)
1229                | ExprKind::Tup(..)
1230                | ExprKind::Underscore => false,
1231                // Check for unit struct constructor.
1232                ExprKind::Path(..) => lower_ctx.extract_unit_struct_path(lhs).is_none(),
1233                // Check for tuple struct constructor.
1234                ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
1235                ExprKind::Paren(e) => {
1236                    match e.kind {
1237                        // We special-case `(..)` for consistency with patterns.
1238                        ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
1239                        _ => is_ordinary(lower_ctx, e),
1240                    }
1241                }
1242                _ => true,
1243            }
1244        }
1245        if is_ordinary(self, lhs) {
1246            return hir::ExprKind::Assign(
1247                self.lower_expr(lhs),
1248                self.lower_expr(rhs),
1249                self.lower_span(eq_sign_span),
1250            );
1251        }
1252
1253        let mut assignments = vec![];
1254
1255        // The LHS becomes a pattern: `(lhs1, lhs2)`.
1256        let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1257        let rhs = self.lower_expr(rhs);
1258
1259        // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1260        let destructure_let = self.stmt_let_pat(
1261            None,
1262            whole_span,
1263            Some(rhs),
1264            pat,
1265            hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
1266        );
1267
1268        // `a = lhs1; b = lhs2;`.
1269        let stmts = self.arena.alloc_from_iter(std::iter::once(destructure_let).chain(assignments));
1270
1271        // Wrap everything in a block.
1272        hir::ExprKind::Block(self.block_all(whole_span, stmts, None), None)
1273    }
1274
1275    /// If the given expression is a path to a tuple struct, returns that path.
1276    /// It is not a complete check, but just tries to reject most paths early
1277    /// if they are not tuple structs.
1278    /// Type checking will take care of the full validation later.
1279    fn extract_tuple_struct_path<'a>(
1280        &mut self,
1281        expr: &'a Expr,
1282    ) -> Option<(&'a Option<AstP<QSelf>>, &'a Path)> {
1283        if let ExprKind::Path(qself, path) = &expr.kind {
1284            // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1285            if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1286                if let Some(res) = partial_res.full_res()
1287                    && !res.expected_in_tuple_struct_pat()
1288                {
1289                    return None;
1290                }
1291            }
1292            return Some((qself, path));
1293        }
1294        None
1295    }
1296
1297    /// If the given expression is a path to a unit struct, returns that path.
1298    /// It is not a complete check, but just tries to reject most paths early
1299    /// if they are not unit structs.
1300    /// Type checking will take care of the full validation later.
1301    fn extract_unit_struct_path<'a>(
1302        &mut self,
1303        expr: &'a Expr,
1304    ) -> Option<(&'a Option<AstP<QSelf>>, &'a Path)> {
1305        if let ExprKind::Path(qself, path) = &expr.kind {
1306            // Does the path resolve to something disallowed in a unit struct/variant pattern?
1307            if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1308                if let Some(res) = partial_res.full_res()
1309                    && !res.expected_in_unit_struct_pat()
1310                {
1311                    return None;
1312                }
1313            }
1314            return Some((qself, path));
1315        }
1316        None
1317    }
1318
1319    /// Convert the LHS of a destructuring assignment to a pattern.
1320    /// Each sub-assignment is recorded in `assignments`.
1321    fn destructure_assign(
1322        &mut self,
1323        lhs: &Expr,
1324        eq_sign_span: Span,
1325        assignments: &mut Vec<hir::Stmt<'hir>>,
1326    ) -> &'hir hir::Pat<'hir> {
1327        self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1328    }
1329
1330    fn destructure_assign_mut(
1331        &mut self,
1332        lhs: &Expr,
1333        eq_sign_span: Span,
1334        assignments: &mut Vec<hir::Stmt<'hir>>,
1335    ) -> hir::Pat<'hir> {
1336        match &lhs.kind {
1337            // Underscore pattern.
1338            ExprKind::Underscore => {
1339                return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1340            }
1341            // Slice patterns.
1342            ExprKind::Array(elements) => {
1343                let (pats, rest) =
1344                    self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1345                let slice_pat = if let Some((i, span)) = rest {
1346                    let (before, after) = pats.split_at(i);
1347                    hir::PatKind::Slice(
1348                        before,
1349                        Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1350                        after,
1351                    )
1352                } else {
1353                    hir::PatKind::Slice(pats, None, &[])
1354                };
1355                return self.pat_without_dbm(lhs.span, slice_pat);
1356            }
1357            // Tuple structs.
1358            ExprKind::Call(callee, args) => {
1359                if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1360                    let (pats, rest) = self.destructure_sequence(
1361                        args,
1362                        "tuple struct or variant",
1363                        eq_sign_span,
1364                        assignments,
1365                    );
1366                    let qpath = self.lower_qpath(
1367                        callee.id,
1368                        qself,
1369                        path,
1370                        ParamMode::Optional,
1371                        AllowReturnTypeNotation::No,
1372                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1373                        None,
1374                    );
1375                    // Destructure like a tuple struct.
1376                    let tuple_struct_pat = hir::PatKind::TupleStruct(
1377                        qpath,
1378                        pats,
1379                        hir::DotDotPos::new(rest.map(|r| r.0)),
1380                    );
1381                    return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1382                }
1383            }
1384            // Unit structs and enum variants.
1385            ExprKind::Path(..) => {
1386                if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1387                    let qpath = self.lower_qpath(
1388                        lhs.id,
1389                        qself,
1390                        path,
1391                        ParamMode::Optional,
1392                        AllowReturnTypeNotation::No,
1393                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1394                        None,
1395                    );
1396                    // Destructure like a unit struct.
1397                    let unit_struct_pat = hir::PatKind::Expr(self.arena.alloc(hir::PatExpr {
1398                        kind: hir::PatExprKind::Path(qpath),
1399                        hir_id: self.next_id(),
1400                        span: self.lower_span(lhs.span),
1401                    }));
1402                    return self.pat_without_dbm(lhs.span, unit_struct_pat);
1403                }
1404            }
1405            // Structs.
1406            ExprKind::Struct(se) => {
1407                let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1408                    let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1409                    hir::PatField {
1410                        hir_id: self.next_id(),
1411                        ident: self.lower_ident(f.ident),
1412                        pat,
1413                        is_shorthand: f.is_shorthand,
1414                        span: self.lower_span(f.span),
1415                    }
1416                }));
1417                let qpath = self.lower_qpath(
1418                    lhs.id,
1419                    &se.qself,
1420                    &se.path,
1421                    ParamMode::Optional,
1422                    AllowReturnTypeNotation::No,
1423                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1424                    None,
1425                );
1426                let fields_omitted = match &se.rest {
1427                    StructRest::Base(e) => {
1428                        self.dcx().emit_err(FunctionalRecordUpdateDestructuringAssignment {
1429                            span: e.span,
1430                        });
1431                        true
1432                    }
1433                    StructRest::Rest(_) => true,
1434                    StructRest::None => false,
1435                };
1436                let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1437                return self.pat_without_dbm(lhs.span, struct_pat);
1438            }
1439            // Tuples.
1440            ExprKind::Tup(elements) => {
1441                let (pats, rest) =
1442                    self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1443                let tuple_pat = hir::PatKind::Tuple(pats, hir::DotDotPos::new(rest.map(|r| r.0)));
1444                return self.pat_without_dbm(lhs.span, tuple_pat);
1445            }
1446            ExprKind::Paren(e) => {
1447                // We special-case `(..)` for consistency with patterns.
1448                if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1449                    let tuple_pat = hir::PatKind::Tuple(&[], hir::DotDotPos::new(Some(0)));
1450                    return self.pat_without_dbm(lhs.span, tuple_pat);
1451                } else {
1452                    return self.destructure_assign_mut(e, eq_sign_span, assignments);
1453                }
1454            }
1455            _ => {}
1456        }
1457        // Treat all other cases as normal lvalue.
1458        let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1459        let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1460        let ident = self.expr_ident(lhs.span, ident, binding);
1461        let assign =
1462            hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1463        let expr = self.expr(lhs.span, assign);
1464        assignments.push(self.stmt_expr(lhs.span, expr));
1465        pat
1466    }
1467
1468    /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1469    /// Such a sequence occurs in a tuple (struct)/slice.
1470    /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1471    /// exists.
1472    /// Each sub-assignment is recorded in `assignments`.
1473    fn destructure_sequence(
1474        &mut self,
1475        elements: &[AstP<Expr>],
1476        ctx: &str,
1477        eq_sign_span: Span,
1478        assignments: &mut Vec<hir::Stmt<'hir>>,
1479    ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1480        let mut rest = None;
1481        let elements =
1482            self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1483                // Check for `..` pattern.
1484                if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1485                    if let Some((_, prev_span)) = rest {
1486                        self.ban_extra_rest_pat(e.span, prev_span, ctx);
1487                    } else {
1488                        rest = Some((i, e.span));
1489                    }
1490                    None
1491                } else {
1492                    Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1493                }
1494            }));
1495        (elements, rest)
1496    }
1497
1498    /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1499    fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1500        let e1 = self.lower_expr_mut(e1);
1501        let e2 = self.lower_expr_mut(e2);
1502        let fn_path = hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span));
1503        let fn_expr = self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path)));
1504        hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1505    }
1506
1507    fn lower_expr_range(
1508        &mut self,
1509        span: Span,
1510        e1: Option<&Expr>,
1511        e2: Option<&Expr>,
1512        lims: RangeLimits,
1513    ) -> hir::ExprKind<'hir> {
1514        use rustc_ast::RangeLimits::*;
1515
1516        let lang_item = match (e1, e2, lims) {
1517            (None, None, HalfOpen) => hir::LangItem::RangeFull,
1518            (Some(..), None, HalfOpen) => {
1519                if self.tcx.features().new_range() {
1520                    hir::LangItem::RangeFromCopy
1521                } else {
1522                    hir::LangItem::RangeFrom
1523                }
1524            }
1525            (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1526            (Some(..), Some(..), HalfOpen) => {
1527                if self.tcx.features().new_range() {
1528                    hir::LangItem::RangeCopy
1529                } else {
1530                    hir::LangItem::Range
1531                }
1532            }
1533            (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1534            (Some(e1), Some(e2), Closed) => {
1535                if self.tcx.features().new_range() {
1536                    hir::LangItem::RangeInclusiveCopy
1537                } else {
1538                    return self.lower_expr_range_closed(span, e1, e2);
1539                }
1540            }
1541            (start, None, Closed) => {
1542                self.dcx().emit_err(InclusiveRangeWithNoEnd { span });
1543                match start {
1544                    Some(..) => {
1545                        if self.tcx.features().new_range() {
1546                            hir::LangItem::RangeFromCopy
1547                        } else {
1548                            hir::LangItem::RangeFrom
1549                        }
1550                    }
1551                    None => hir::LangItem::RangeFull,
1552                }
1553            }
1554        };
1555
1556        let fields = self.arena.alloc_from_iter(
1557            e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1558                |(s, e)| {
1559                    let expr = self.lower_expr(e);
1560                    let ident = Ident::new(s, self.lower_span(e.span));
1561                    self.expr_field(ident, expr, e.span)
1562                },
1563            ),
1564        );
1565
1566        hir::ExprKind::Struct(
1567            self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span))),
1568            fields,
1569            hir::StructTailExpr::None,
1570        )
1571    }
1572
1573    // Record labelled expr's HirId so that we can retrieve it in `lower_jump_destination` without
1574    // lowering node id again.
1575    fn lower_label(
1576        &mut self,
1577        opt_label: Option<Label>,
1578        dest_id: NodeId,
1579        dest_hir_id: hir::HirId,
1580    ) -> Option<Label> {
1581        let label = opt_label?;
1582        self.ident_and_label_to_local_id.insert(dest_id, dest_hir_id.local_id);
1583        Some(Label { ident: self.lower_ident(label.ident) })
1584    }
1585
1586    fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1587        let target_id = match destination {
1588            Some((id, _)) => {
1589                if let Some(loop_id) = self.resolver.get_label_res(id) {
1590                    let local_id = self.ident_and_label_to_local_id[&loop_id];
1591                    let loop_hir_id = HirId { owner: self.current_hir_id_owner, local_id };
1592                    Ok(loop_hir_id)
1593                } else {
1594                    Err(hir::LoopIdError::UnresolvedLabel)
1595                }
1596            }
1597            None => {
1598                self.loop_scope.map(|id| Ok(id)).unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1599            }
1600        };
1601        let label = destination
1602            .map(|(_, label)| label)
1603            .map(|label| Label { ident: self.lower_ident(label.ident) });
1604        hir::Destination { label, target_id }
1605    }
1606
1607    fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1608        if self.is_in_loop_condition && opt_label.is_none() {
1609            hir::Destination {
1610                label: None,
1611                target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1612            }
1613        } else {
1614            self.lower_loop_destination(opt_label.map(|label| (id, label)))
1615        }
1616    }
1617
1618    fn with_catch_scope<T>(&mut self, catch_id: hir::HirId, f: impl FnOnce(&mut Self) -> T) -> T {
1619        let old_scope = self.catch_scope.replace(catch_id);
1620        let result = f(self);
1621        self.catch_scope = old_scope;
1622        result
1623    }
1624
1625    fn with_loop_scope<T>(&mut self, loop_id: hir::HirId, f: impl FnOnce(&mut Self) -> T) -> T {
1626        // We're no longer in the base loop's condition; we're in another loop.
1627        let was_in_loop_condition = self.is_in_loop_condition;
1628        self.is_in_loop_condition = false;
1629
1630        let old_scope = self.loop_scope.replace(loop_id);
1631        let result = f(self);
1632        self.loop_scope = old_scope;
1633
1634        self.is_in_loop_condition = was_in_loop_condition;
1635
1636        result
1637    }
1638
1639    fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1640        let was_in_loop_condition = self.is_in_loop_condition;
1641        self.is_in_loop_condition = true;
1642
1643        let result = f(self);
1644
1645        self.is_in_loop_condition = was_in_loop_condition;
1646
1647        result
1648    }
1649
1650    fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1651        let hir_id = self.lower_node_id(f.id);
1652        self.lower_attrs(hir_id, &f.attrs, f.span);
1653        hir::ExprField {
1654            hir_id,
1655            ident: self.lower_ident(f.ident),
1656            expr: self.lower_expr(&f.expr),
1657            span: self.lower_span(f.span),
1658            is_shorthand: f.is_shorthand,
1659        }
1660    }
1661
1662    fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1663        let yielded =
1664            opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1665
1666        if !self.tcx.features().yield_expr()
1667            && !self.tcx.features().coroutines()
1668            && !self.tcx.features().gen_blocks()
1669        {
1670            rustc_session::parse::feature_err(
1671                &self.tcx.sess,
1672                sym::yield_expr,
1673                span,
1674                fluent_generated::ast_lowering_yield,
1675            )
1676            .emit();
1677        }
1678
1679        let is_async_gen = match self.coroutine_kind {
1680            Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => false,
1681            Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => true,
1682            Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
1683                // Lower to a block `{ EXPR; <error> }` so that the awaited expr
1684                // is not accidentally orphaned.
1685                let stmt_id = self.next_id();
1686                let expr_err = self.expr(
1687                    yielded.span,
1688                    hir::ExprKind::Err(self.dcx().emit_err(AsyncCoroutinesNotSupported { span })),
1689                );
1690                return hir::ExprKind::Block(
1691                    self.block_all(
1692                        yielded.span,
1693                        arena_vec![self; hir::Stmt {
1694                            hir_id: stmt_id,
1695                            kind: hir::StmtKind::Semi(yielded),
1696                            span: yielded.span,
1697                        }],
1698                        Some(self.arena.alloc(expr_err)),
1699                    ),
1700                    None,
1701                );
1702            }
1703            Some(hir::CoroutineKind::Coroutine(_)) => false,
1704            None => {
1705                let suggestion = self.current_item.map(|s| s.shrink_to_lo());
1706                self.dcx().emit_err(YieldInClosure { span, suggestion });
1707                self.coroutine_kind = Some(hir::CoroutineKind::Coroutine(Movability::Movable));
1708
1709                false
1710            }
1711        };
1712
1713        if is_async_gen {
1714            // `yield $expr` is transformed into `task_context = yield async_gen_ready($expr)`.
1715            // This ensures that we store our resumed `ResumeContext` correctly, and also that
1716            // the apparent value of the `yield` expression is `()`.
1717            let wrapped_yielded = self.expr_call_lang_item_fn(
1718                span,
1719                hir::LangItem::AsyncGenReady,
1720                std::slice::from_ref(yielded),
1721            );
1722            let yield_expr = self.arena.alloc(
1723                self.expr(span, hir::ExprKind::Yield(wrapped_yielded, hir::YieldSource::Yield)),
1724            );
1725
1726            let Some(task_context_hid) = self.task_context else {
1727                unreachable!("use of `await` outside of an async context.");
1728            };
1729            let task_context_ident = Ident::with_dummy_span(sym::_task_context);
1730            let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
1731
1732            hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span))
1733        } else {
1734            hir::ExprKind::Yield(yielded, hir::YieldSource::Yield)
1735        }
1736    }
1737
1738    /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1739    /// ```ignore (pseudo-rust)
1740    /// {
1741    ///     let result = match IntoIterator::into_iter(<head>) {
1742    ///         mut iter => {
1743    ///             [opt_ident]: loop {
1744    ///                 match Iterator::next(&mut iter) {
1745    ///                     None => break,
1746    ///                     Some(<pat>) => <body>,
1747    ///                 };
1748    ///             }
1749    ///         }
1750    ///     };
1751    ///     result
1752    /// }
1753    /// ```
1754    fn lower_expr_for(
1755        &mut self,
1756        e: &Expr,
1757        pat: &Pat,
1758        head: &Expr,
1759        body: &Block,
1760        opt_label: Option<Label>,
1761        loop_kind: ForLoopKind,
1762    ) -> hir::Expr<'hir> {
1763        let head = self.lower_expr_mut(head);
1764        let pat = self.lower_pat(pat);
1765        let for_span =
1766            self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1767        let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1768        let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1769
1770        let loop_hir_id = self.lower_node_id(e.id);
1771        let label = self.lower_label(opt_label, e.id, loop_hir_id);
1772
1773        // `None => break`
1774        let none_arm = {
1775            let break_expr =
1776                self.with_loop_scope(loop_hir_id, |this| this.expr_break_alloc(for_span));
1777            let pat = self.pat_none(for_span);
1778            self.arm(pat, break_expr)
1779        };
1780
1781        // Some(<pat>) => <body>,
1782        let some_arm = {
1783            let some_pat = self.pat_some(pat_span, pat);
1784            let body_block =
1785                self.with_loop_scope(loop_hir_id, |this| this.lower_block(body, false));
1786            let body_expr = self.arena.alloc(self.expr_block(body_block));
1787            self.arm(some_pat, body_expr)
1788        };
1789
1790        // `mut iter`
1791        let iter = Ident::with_dummy_span(sym::iter);
1792        let (iter_pat, iter_pat_nid) =
1793            self.pat_ident_binding_mode(head_span, iter, hir::BindingMode::MUT);
1794
1795        let match_expr = {
1796            let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1797            let next_expr = match loop_kind {
1798                ForLoopKind::For => {
1799                    // `Iterator::next(&mut iter)`
1800                    let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1801                    self.expr_call_lang_item_fn(
1802                        head_span,
1803                        hir::LangItem::IteratorNext,
1804                        arena_vec![self; ref_mut_iter],
1805                    )
1806                }
1807                ForLoopKind::ForAwait => {
1808                    // we'll generate `unsafe { Pin::new_unchecked(&mut iter) })` and then pass this
1809                    // to make_lowered_await with `FutureKind::AsyncIterator` which will generator
1810                    // calls to `poll_next`. In user code, this would probably be a call to
1811                    // `Pin::as_mut` but here it's easy enough to do `new_unchecked`.
1812
1813                    // `&mut iter`
1814                    let iter = self.expr_mut_addr_of(head_span, iter);
1815                    // `Pin::new_unchecked(...)`
1816                    let iter = self.arena.alloc(self.expr_call_lang_item_fn_mut(
1817                        head_span,
1818                        hir::LangItem::PinNewUnchecked,
1819                        arena_vec![self; iter],
1820                    ));
1821                    // `unsafe { ... }`
1822                    let iter = self.arena.alloc(self.expr_unsafe(iter));
1823                    let kind = self.make_lowered_await(head_span, iter, FutureKind::AsyncIterator);
1824                    self.arena.alloc(hir::Expr { hir_id: self.next_id(), kind, span: head_span })
1825                }
1826            };
1827            let arms = arena_vec![self; none_arm, some_arm];
1828
1829            // `match $next_expr { ... }`
1830            self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1831        };
1832        let match_stmt = self.stmt_expr(for_span, match_expr);
1833
1834        let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1835
1836        // `[opt_ident]: loop { ... }`
1837        let kind = hir::ExprKind::Loop(
1838            loop_block,
1839            label,
1840            hir::LoopSource::ForLoop,
1841            self.lower_span(for_span.with_hi(head.span.hi())),
1842        );
1843        let loop_expr = self.arena.alloc(hir::Expr { hir_id: loop_hir_id, kind, span: for_span });
1844
1845        // `mut iter => { ... }`
1846        let iter_arm = self.arm(iter_pat, loop_expr);
1847
1848        let match_expr = match loop_kind {
1849            ForLoopKind::For => {
1850                // `::std::iter::IntoIterator::into_iter(<head>)`
1851                let into_iter_expr = self.expr_call_lang_item_fn(
1852                    head_span,
1853                    hir::LangItem::IntoIterIntoIter,
1854                    arena_vec![self; head],
1855                );
1856
1857                self.arena.alloc(self.expr_match(
1858                    for_span,
1859                    into_iter_expr,
1860                    arena_vec![self; iter_arm],
1861                    hir::MatchSource::ForLoopDesugar,
1862                ))
1863            }
1864            // `match into_async_iter(<head>) { ref mut iter => match unsafe { Pin::new_unchecked(iter) } { ... } }`
1865            ForLoopKind::ForAwait => {
1866                let iter_ident = iter;
1867                let (async_iter_pat, async_iter_pat_id) =
1868                    self.pat_ident_binding_mode(head_span, iter_ident, hir::BindingMode::REF_MUT);
1869                let iter = self.expr_ident_mut(head_span, iter_ident, async_iter_pat_id);
1870                // `Pin::new_unchecked(...)`
1871                let iter = self.arena.alloc(self.expr_call_lang_item_fn_mut(
1872                    head_span,
1873                    hir::LangItem::PinNewUnchecked,
1874                    arena_vec![self; iter],
1875                ));
1876                // `unsafe { ... }`
1877                let iter = self.arena.alloc(self.expr_unsafe(iter));
1878                let inner_match_expr = self.arena.alloc(self.expr_match(
1879                    for_span,
1880                    iter,
1881                    arena_vec![self; iter_arm],
1882                    hir::MatchSource::ForLoopDesugar,
1883                ));
1884
1885                // `::core::async_iter::IntoAsyncIterator::into_async_iter(<head>)`
1886                let iter = self.expr_call_lang_item_fn(
1887                    head_span,
1888                    hir::LangItem::IntoAsyncIterIntoIter,
1889                    arena_vec![self; head],
1890                );
1891                let iter_arm = self.arm(async_iter_pat, inner_match_expr);
1892                self.arena.alloc(self.expr_match(
1893                    for_span,
1894                    iter,
1895                    arena_vec![self; iter_arm],
1896                    hir::MatchSource::ForLoopDesugar,
1897                ))
1898            }
1899        };
1900
1901        // This is effectively `{ let _result = ...; _result }`.
1902        // The construct was introduced in #21984 and is necessary to make sure that
1903        // temporaries in the `head` expression are dropped and do not leak to the
1904        // surrounding scope of the `match` since the `match` is not a terminating scope.
1905        //
1906        // Also, add the attributes to the outer returned expr node.
1907        let expr = self.expr_drop_temps_mut(for_span, match_expr);
1908        self.lower_attrs(expr.hir_id, &e.attrs, e.span);
1909        expr
1910    }
1911
1912    /// Desugar `ExprKind::Try` from: `<expr>?` into:
1913    /// ```ignore (pseudo-rust)
1914    /// match Try::branch(<expr>) {
1915    ///     ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1916    ///     ControlFlow::Break(residual) =>
1917    ///         #[allow(unreachable_code)]
1918    ///         // If there is an enclosing `try {...}`:
1919    ///         break 'catch_target Try::from_residual(residual),
1920    ///         // Otherwise:
1921    ///         return Try::from_residual(residual),
1922    /// }
1923    /// ```
1924    fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1925        let unstable_span = self.mark_span_with_reason(
1926            DesugaringKind::QuestionMark,
1927            span,
1928            Some(Arc::clone(&self.allow_try_trait)),
1929        );
1930        let try_span = self.tcx.sess.source_map().end_point(span);
1931        let try_span = self.mark_span_with_reason(
1932            DesugaringKind::QuestionMark,
1933            try_span,
1934            Some(Arc::clone(&self.allow_try_trait)),
1935        );
1936
1937        // `Try::branch(<expr>)`
1938        let scrutinee = {
1939            // expand <expr>
1940            let sub_expr = self.lower_expr_mut(sub_expr);
1941
1942            self.expr_call_lang_item_fn(
1943                unstable_span,
1944                hir::LangItem::TryTraitBranch,
1945                arena_vec![self; sub_expr],
1946            )
1947        };
1948
1949        // `#[allow(unreachable_code)]`
1950        let attr = attr::mk_attr_nested_word(
1951            &self.tcx.sess.psess.attr_id_generator,
1952            AttrStyle::Outer,
1953            Safety::Default,
1954            sym::allow,
1955            sym::unreachable_code,
1956            try_span,
1957        );
1958        let attrs: AttrVec = thin_vec![attr];
1959
1960        // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1961        let continue_arm = {
1962            let val_ident = Ident::with_dummy_span(sym::val);
1963            let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1964            let val_expr = self.expr_ident(span, val_ident, val_pat_nid);
1965            self.lower_attrs(val_expr.hir_id, &attrs, span);
1966            let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1967            self.arm(continue_pat, val_expr)
1968        };
1969
1970        // `ControlFlow::Break(residual) =>
1971        //     #[allow(unreachable_code)]
1972        //     return Try::from_residual(residual),`
1973        let break_arm = {
1974            let residual_ident = Ident::with_dummy_span(sym::residual);
1975            let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1976            let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1977            let from_residual_expr = self.wrap_in_try_constructor(
1978                hir::LangItem::TryTraitFromResidual,
1979                try_span,
1980                self.arena.alloc(residual_expr),
1981                unstable_span,
1982            );
1983            let ret_expr = if let Some(catch_id) = self.catch_scope {
1984                let target_id = Ok(catch_id);
1985                self.arena.alloc(self.expr(
1986                    try_span,
1987                    hir::ExprKind::Break(
1988                        hir::Destination { label: None, target_id },
1989                        Some(from_residual_expr),
1990                    ),
1991                ))
1992            } else {
1993                let ret_expr = self.checked_return(Some(from_residual_expr));
1994                self.arena.alloc(self.expr(try_span, ret_expr))
1995            };
1996            self.lower_attrs(ret_expr.hir_id, &attrs, span);
1997
1998            let break_pat = self.pat_cf_break(try_span, residual_local);
1999            self.arm(break_pat, ret_expr)
2000        };
2001
2002        hir::ExprKind::Match(
2003            scrutinee,
2004            arena_vec![self; break_arm, continue_arm],
2005            hir::MatchSource::TryDesugar(scrutinee.hir_id),
2006        )
2007    }
2008
2009    /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into:
2010    /// ```ignore(illustrative)
2011    /// // If there is an enclosing `try {...}`:
2012    /// break 'catch_target FromResidual::from_residual(Yeet(residual));
2013    /// // Otherwise:
2014    /// return FromResidual::from_residual(Yeet(residual));
2015    /// ```
2016    /// But to simplify this, there's a `from_yeet` lang item function which
2017    /// handles the combined `FromResidual::from_residual(Yeet(residual))`.
2018    fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
2019        // The expression (if present) or `()` otherwise.
2020        let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
2021            (sub_expr.span, self.lower_expr(sub_expr))
2022        } else {
2023            (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
2024        };
2025
2026        let unstable_span = self.mark_span_with_reason(
2027            DesugaringKind::YeetExpr,
2028            span,
2029            Some(Arc::clone(&self.allow_try_trait)),
2030        );
2031
2032        let from_yeet_expr = self.wrap_in_try_constructor(
2033            hir::LangItem::TryTraitFromYeet,
2034            unstable_span,
2035            yeeted_expr,
2036            yeeted_span,
2037        );
2038
2039        if let Some(catch_id) = self.catch_scope {
2040            let target_id = Ok(catch_id);
2041            hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
2042        } else {
2043            self.checked_return(Some(from_yeet_expr))
2044        }
2045    }
2046
2047    // =========================================================================
2048    // Helper methods for building HIR.
2049    // =========================================================================
2050
2051    /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
2052    ///
2053    /// In terms of drop order, it has the same effect as wrapping `expr` in
2054    /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
2055    ///
2056    /// The drop order can be important, e.g. to drop temporaries from an `async fn`
2057    /// body before its parameters.
2058    pub(super) fn expr_drop_temps(
2059        &mut self,
2060        span: Span,
2061        expr: &'hir hir::Expr<'hir>,
2062    ) -> &'hir hir::Expr<'hir> {
2063        self.arena.alloc(self.expr_drop_temps_mut(span, expr))
2064    }
2065
2066    pub(super) fn expr_drop_temps_mut(
2067        &mut self,
2068        span: Span,
2069        expr: &'hir hir::Expr<'hir>,
2070    ) -> hir::Expr<'hir> {
2071        self.expr(span, hir::ExprKind::DropTemps(expr))
2072    }
2073
2074    pub(super) fn expr_match(
2075        &mut self,
2076        span: Span,
2077        arg: &'hir hir::Expr<'hir>,
2078        arms: &'hir [hir::Arm<'hir>],
2079        source: hir::MatchSource,
2080    ) -> hir::Expr<'hir> {
2081        self.expr(span, hir::ExprKind::Match(arg, arms, source))
2082    }
2083
2084    fn expr_break(&mut self, span: Span) -> hir::Expr<'hir> {
2085        let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
2086        self.expr(span, expr_break)
2087    }
2088
2089    fn expr_break_alloc(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
2090        let expr_break = self.expr_break(span);
2091        self.arena.alloc(expr_break)
2092    }
2093
2094    fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
2095        self.expr(span, hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e))
2096    }
2097
2098    fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
2099        self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[])))
2100    }
2101
2102    fn expr_uint(&mut self, sp: Span, ty: ast::UintTy, value: u128) -> hir::Expr<'hir> {
2103        let lit = hir::Lit {
2104            span: sp,
2105            node: ast::LitKind::Int(value.into(), ast::LitIntType::Unsigned(ty)),
2106        };
2107        self.expr(sp, hir::ExprKind::Lit(lit))
2108    }
2109
2110    pub(super) fn expr_usize(&mut self, sp: Span, value: usize) -> hir::Expr<'hir> {
2111        self.expr_uint(sp, ast::UintTy::Usize, value as u128)
2112    }
2113
2114    pub(super) fn expr_u32(&mut self, sp: Span, value: u32) -> hir::Expr<'hir> {
2115        self.expr_uint(sp, ast::UintTy::U32, value as u128)
2116    }
2117
2118    pub(super) fn expr_u16(&mut self, sp: Span, value: u16) -> hir::Expr<'hir> {
2119        self.expr_uint(sp, ast::UintTy::U16, value as u128)
2120    }
2121
2122    pub(super) fn expr_str(&mut self, sp: Span, value: Symbol) -> hir::Expr<'hir> {
2123        let lit = hir::Lit { span: sp, node: ast::LitKind::Str(value, ast::StrStyle::Cooked) };
2124        self.expr(sp, hir::ExprKind::Lit(lit))
2125    }
2126
2127    pub(super) fn expr_call_mut(
2128        &mut self,
2129        span: Span,
2130        e: &'hir hir::Expr<'hir>,
2131        args: &'hir [hir::Expr<'hir>],
2132    ) -> hir::Expr<'hir> {
2133        self.expr(span, hir::ExprKind::Call(e, args))
2134    }
2135
2136    pub(super) fn expr_call(
2137        &mut self,
2138        span: Span,
2139        e: &'hir hir::Expr<'hir>,
2140        args: &'hir [hir::Expr<'hir>],
2141    ) -> &'hir hir::Expr<'hir> {
2142        self.arena.alloc(self.expr_call_mut(span, e, args))
2143    }
2144
2145    pub(super) fn expr_call_lang_item_fn_mut(
2146        &mut self,
2147        span: Span,
2148        lang_item: hir::LangItem,
2149        args: &'hir [hir::Expr<'hir>],
2150    ) -> hir::Expr<'hir> {
2151        let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item));
2152        self.expr_call_mut(span, path, args)
2153    }
2154
2155    pub(super) fn expr_call_lang_item_fn(
2156        &mut self,
2157        span: Span,
2158        lang_item: hir::LangItem,
2159        args: &'hir [hir::Expr<'hir>],
2160    ) -> &'hir hir::Expr<'hir> {
2161        self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args))
2162    }
2163
2164    fn expr_lang_item_path(&mut self, span: Span, lang_item: hir::LangItem) -> hir::Expr<'hir> {
2165        self.expr(span, hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span))))
2166    }
2167
2168    /// `<LangItem>::name`
2169    pub(super) fn expr_lang_item_type_relative(
2170        &mut self,
2171        span: Span,
2172        lang_item: hir::LangItem,
2173        name: Symbol,
2174    ) -> hir::Expr<'hir> {
2175        let qpath = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
2176        let path = hir::ExprKind::Path(hir::QPath::TypeRelative(
2177            self.arena.alloc(self.ty(span, hir::TyKind::Path(qpath))),
2178            self.arena.alloc(hir::PathSegment::new(
2179                Ident::new(name, self.lower_span(span)),
2180                self.next_id(),
2181                Res::Err,
2182            )),
2183        ));
2184        self.expr(span, path)
2185    }
2186
2187    pub(super) fn expr_ident(
2188        &mut self,
2189        sp: Span,
2190        ident: Ident,
2191        binding: HirId,
2192    ) -> &'hir hir::Expr<'hir> {
2193        self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
2194    }
2195
2196    pub(super) fn expr_ident_mut(
2197        &mut self,
2198        span: Span,
2199        ident: Ident,
2200        binding: HirId,
2201    ) -> hir::Expr<'hir> {
2202        let hir_id = self.next_id();
2203        let res = Res::Local(binding);
2204        let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
2205            None,
2206            self.arena.alloc(hir::Path {
2207                span: self.lower_span(span),
2208                res,
2209                segments: arena_vec![self; hir::PathSegment::new(ident, hir_id, res)],
2210            }),
2211        ));
2212
2213        self.expr(span, expr_path)
2214    }
2215
2216    fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
2217        let hir_id = self.next_id();
2218        let span = expr.span;
2219        self.expr(
2220            span,
2221            hir::ExprKind::Block(
2222                self.arena.alloc(hir::Block {
2223                    stmts: &[],
2224                    expr: Some(expr),
2225                    hir_id,
2226                    rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
2227                    span: self.lower_span(span),
2228                    targeted_by_break: false,
2229                }),
2230                None,
2231            ),
2232        )
2233    }
2234
2235    fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
2236        let blk = self.block_all(span, &[], None);
2237        let expr = self.expr_block(blk);
2238        self.arena.alloc(expr)
2239    }
2240
2241    pub(super) fn expr_block(&mut self, b: &'hir hir::Block<'hir>) -> hir::Expr<'hir> {
2242        self.expr(b.span, hir::ExprKind::Block(b, None))
2243    }
2244
2245    pub(super) fn expr_array_ref(
2246        &mut self,
2247        span: Span,
2248        elements: &'hir [hir::Expr<'hir>],
2249    ) -> hir::Expr<'hir> {
2250        let array = self.arena.alloc(self.expr(span, hir::ExprKind::Array(elements)));
2251        self.expr_ref(span, array)
2252    }
2253
2254    pub(super) fn expr_ref(&mut self, span: Span, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
2255        self.expr(span, hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr))
2256    }
2257
2258    pub(super) fn expr(&mut self, span: Span, kind: hir::ExprKind<'hir>) -> hir::Expr<'hir> {
2259        let hir_id = self.next_id();
2260        hir::Expr { hir_id, kind, span: self.lower_span(span) }
2261    }
2262
2263    pub(super) fn expr_field(
2264        &mut self,
2265        ident: Ident,
2266        expr: &'hir hir::Expr<'hir>,
2267        span: Span,
2268    ) -> hir::ExprField<'hir> {
2269        hir::ExprField {
2270            hir_id: self.next_id(),
2271            ident,
2272            span: self.lower_span(span),
2273            expr,
2274            is_shorthand: false,
2275        }
2276    }
2277
2278    pub(super) fn arm(
2279        &mut self,
2280        pat: &'hir hir::Pat<'hir>,
2281        expr: &'hir hir::Expr<'hir>,
2282    ) -> hir::Arm<'hir> {
2283        hir::Arm {
2284            hir_id: self.next_id(),
2285            pat,
2286            guard: None,
2287            span: self.lower_span(expr.span),
2288            body: expr,
2289        }
2290    }
2291}
2292
2293/// Used by [`LoweringContext::make_lowered_await`] to customize the desugaring based on what kind
2294/// of future we are awaiting.
2295#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2296enum FutureKind {
2297    /// We are awaiting a normal future
2298    Future,
2299    /// We are awaiting something that's known to be an AsyncIterator (i.e. we are in the header of
2300    /// a `for await` loop)
2301    AsyncIterator,
2302}