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