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