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