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