Skip to main content

rustc_ast_lowering/
expr.rs

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