Skip to main content

rustc_ast_lowering/
expr.rs

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