Skip to main content

rustc_ast_lowering/
expr.rs

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