rustc_ast_lowering/
item.rs

1use rustc_abi::ExternAbi;
2use rustc_ast::visit::AssocCtxt;
3use rustc_ast::*;
4use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err};
5use rustc_hir::attrs::AttributeKind;
6use rustc_hir::def::{DefKind, PerNS, Res};
7use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
8use rustc_hir::{
9    self as hir, HirId, ImplItemImplKind, LifetimeSource, PredicateOrigin, Target, find_attr,
10};
11use rustc_index::{IndexSlice, IndexVec};
12use rustc_middle::span_bug;
13use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
14use rustc_span::edit_distance::find_best_match_for_name;
15use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
16use smallvec::{SmallVec, smallvec};
17use thin_vec::ThinVec;
18use tracing::instrument;
19
20use super::errors::{InvalidAbi, InvalidAbiSuggestion, TupleStructWithDefault, UnionWithDefault};
21use super::stability::{enabled_names, gate_unstable_abi};
22use super::{
23    AstOwner, FnDeclKind, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
24    RelaxedBoundForbiddenReason, RelaxedBoundPolicy, ResolverAstLoweringExt,
25};
26
27pub(super) struct ItemLowerer<'a, 'hir> {
28    pub(super) tcx: TyCtxt<'hir>,
29    pub(super) resolver: &'a mut ResolverAstLowering,
30    pub(super) ast_index: &'a IndexSlice<LocalDefId, AstOwner<'a>>,
31    pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<'hir>>,
32}
33
34/// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
35/// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
36/// clause if it exists.
37fn add_ty_alias_where_clause(
38    generics: &mut ast::Generics,
39    after_where_clause: &ast::WhereClause,
40    prefer_first: bool,
41) {
42    generics.where_clause.predicates.extend_from_slice(&after_where_clause.predicates);
43
44    let mut before = (generics.where_clause.has_where_token, generics.where_clause.span);
45    let mut after = (after_where_clause.has_where_token, after_where_clause.span);
46    if !prefer_first {
47        (before, after) = (after, before);
48    }
49    (generics.where_clause.has_where_token, generics.where_clause.span) =
50        if before.0 || !after.0 { before } else { after };
51}
52
53impl<'a, 'hir> ItemLowerer<'a, 'hir> {
54    fn with_lctx(
55        &mut self,
56        owner: NodeId,
57        f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
58    ) {
59        let mut lctx = LoweringContext::new(self.tcx, self.resolver);
60        lctx.with_hir_id_owner(owner, |lctx| f(lctx));
61
62        for (def_id, info) in lctx.children {
63            let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
64            assert!(
65                matches!(owner, hir::MaybeOwner::Phantom),
66                "duplicate copy of {def_id:?} in lctx.children"
67            );
68            *owner = info;
69        }
70    }
71
72    pub(super) fn lower_node(&mut self, def_id: LocalDefId) {
73        let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
74        if let hir::MaybeOwner::Phantom = owner {
75            let node = self.ast_index[def_id];
76            match node {
77                AstOwner::NonOwner => {}
78                AstOwner::Crate(c) => {
79                    assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
80                    self.with_lctx(CRATE_NODE_ID, |lctx| {
81                        let module = lctx.lower_mod(&c.items, &c.spans);
82                        // FIXME(jdonszelman): is dummy span ever a problem here?
83                        lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, DUMMY_SP, Target::Crate);
84                        hir::OwnerNode::Crate(module)
85                    })
86                }
87                AstOwner::Item(item) => {
88                    self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
89                }
90                AstOwner::AssocItem(item, ctxt) => {
91                    self.with_lctx(item.id, |lctx| lctx.lower_assoc_item(item, ctxt))
92                }
93                AstOwner::ForeignItem(item) => self.with_lctx(item.id, |lctx| {
94                    hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item))
95                }),
96            }
97        }
98    }
99}
100
101impl<'hir> LoweringContext<'_, 'hir> {
102    pub(super) fn lower_mod(
103        &mut self,
104        items: &[Box<Item>],
105        spans: &ModSpans,
106    ) -> &'hir hir::Mod<'hir> {
107        self.arena.alloc(hir::Mod {
108            spans: hir::ModSpans {
109                inner_span: self.lower_span(spans.inner_span),
110                inject_use_span: self.lower_span(spans.inject_use_span),
111            },
112            item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
113        })
114    }
115
116    pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
117        let mut node_ids = smallvec![hir::ItemId { owner_id: self.owner_id(i.id) }];
118        if let ItemKind::Use(use_tree) = &i.kind {
119            self.lower_item_id_use_tree(use_tree, &mut node_ids);
120        }
121        node_ids
122    }
123
124    fn lower_item_id_use_tree(&mut self, tree: &UseTree, vec: &mut SmallVec<[hir::ItemId; 1]>) {
125        match &tree.kind {
126            UseTreeKind::Nested { items, .. } => {
127                for &(ref nested, id) in items {
128                    vec.push(hir::ItemId { owner_id: self.owner_id(id) });
129                    self.lower_item_id_use_tree(nested, vec);
130                }
131            }
132            UseTreeKind::Simple(..) | UseTreeKind::Glob => {}
133        }
134    }
135
136    fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
137        let vis_span = self.lower_span(i.vis.span);
138        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
139        let attrs = self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_ast_item(i));
140        let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind);
141        let item = hir::Item {
142            owner_id: hir_id.expect_owner(),
143            kind,
144            vis_span,
145            span: self.lower_span(i.span),
146            has_delayed_lints: !self.delayed_lints.is_empty(),
147        };
148        self.arena.alloc(item)
149    }
150
151    fn lower_item_kind(
152        &mut self,
153        span: Span,
154        id: NodeId,
155        hir_id: hir::HirId,
156        attrs: &'hir [hir::Attribute],
157        vis_span: Span,
158        i: &ItemKind,
159    ) -> hir::ItemKind<'hir> {
160        match i {
161            ItemKind::ExternCrate(orig_name, ident) => {
162                let ident = self.lower_ident(*ident);
163                hir::ItemKind::ExternCrate(*orig_name, ident)
164            }
165            ItemKind::Use(use_tree) => {
166                // Start with an empty prefix.
167                let prefix = Path { segments: ThinVec::new(), span: use_tree.span, tokens: None };
168
169                self.lower_use_tree(use_tree, &prefix, id, vis_span, attrs)
170            }
171            ItemKind::Static(box ast::StaticItem {
172                ident,
173                ty: t,
174                safety: _,
175                mutability: m,
176                expr: e,
177                define_opaque,
178            }) => {
179                let ident = self.lower_ident(*ident);
180                let (ty, body_id) =
181                    self.lower_const_item(t, span, e.as_deref(), ImplTraitPosition::StaticTy);
182                self.lower_define_opaque(hir_id, define_opaque);
183                hir::ItemKind::Static(*m, ident, ty, body_id)
184            }
185            ItemKind::Const(box ast::ConstItem {
186                ident,
187                generics,
188                ty,
189                expr,
190                define_opaque,
191                ..
192            }) => {
193                let ident = self.lower_ident(*ident);
194                let (generics, (ty, body_id)) = self.lower_generics(
195                    generics,
196                    id,
197                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
198                    |this| {
199                        this.lower_const_item(ty, span, expr.as_deref(), ImplTraitPosition::ConstTy)
200                    },
201                );
202                self.lower_define_opaque(hir_id, &define_opaque);
203                hir::ItemKind::Const(ident, generics, ty, body_id)
204            }
205            ItemKind::Fn(box Fn {
206                sig: FnSig { decl, header, span: fn_sig_span },
207                ident,
208                generics,
209                body,
210                contract,
211                define_opaque,
212                ..
213            }) => {
214                self.with_new_scopes(*fn_sig_span, |this| {
215                    // Note: we don't need to change the return type from `T` to
216                    // `impl Future<Output = T>` here because lower_body
217                    // only cares about the input argument patterns in the function
218                    // declaration (decl), not the return types.
219                    let coroutine_kind = header.coroutine_kind;
220                    let body_id = this.lower_maybe_coroutine_body(
221                        *fn_sig_span,
222                        span,
223                        hir_id,
224                        decl,
225                        coroutine_kind,
226                        body.as_deref(),
227                        attrs,
228                        contract.as_deref(),
229                    );
230
231                    let itctx = ImplTraitContext::Universal;
232                    let (generics, decl) = this.lower_generics(generics, id, itctx, |this| {
233                        this.lower_fn_decl(decl, id, *fn_sig_span, FnDeclKind::Fn, coroutine_kind)
234                    });
235                    let sig = hir::FnSig {
236                        decl,
237                        header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
238                        span: this.lower_span(*fn_sig_span),
239                    };
240                    this.lower_define_opaque(hir_id, define_opaque);
241                    let ident = this.lower_ident(*ident);
242                    hir::ItemKind::Fn {
243                        ident,
244                        sig,
245                        generics,
246                        body: body_id,
247                        has_body: body.is_some(),
248                    }
249                })
250            }
251            ItemKind::Mod(_, ident, mod_kind) => {
252                let ident = self.lower_ident(*ident);
253                match mod_kind {
254                    ModKind::Loaded(items, _, spans) => {
255                        hir::ItemKind::Mod(ident, self.lower_mod(items, spans))
256                    }
257                    ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
258                }
259            }
260            ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
261                abi: fm.abi.map_or(ExternAbi::FALLBACK, |abi| self.lower_abi(abi)),
262                items: self
263                    .arena
264                    .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
265            },
266            ItemKind::GlobalAsm(asm) => {
267                let asm = self.lower_inline_asm(span, asm);
268                let fake_body =
269                    self.lower_body(|this| (&[], this.expr(span, hir::ExprKind::InlineAsm(asm))));
270                hir::ItemKind::GlobalAsm { asm, fake_body }
271            }
272            ItemKind::TyAlias(box TyAlias { ident, generics, after_where_clause, ty, .. }) => {
273                // We lower
274                //
275                // type Foo = impl Trait
276                //
277                // to
278                //
279                // type Foo = Foo1
280                // opaque type Foo1: Trait
281                let ident = self.lower_ident(*ident);
282                let mut generics = generics.clone();
283                add_ty_alias_where_clause(&mut generics, after_where_clause, true);
284                let (generics, ty) = self.lower_generics(
285                    &generics,
286                    id,
287                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
288                    |this| match ty {
289                        None => {
290                            let guar = this.dcx().span_delayed_bug(
291                                span,
292                                "expected to lower type alias type, but it was missing",
293                            );
294                            this.arena.alloc(this.ty(span, hir::TyKind::Err(guar)))
295                        }
296                        Some(ty) => this.lower_ty(
297                            ty,
298                            ImplTraitContext::OpaqueTy {
299                                origin: hir::OpaqueTyOrigin::TyAlias {
300                                    parent: this.local_def_id(id),
301                                    in_assoc_ty: false,
302                                },
303                            },
304                        ),
305                    },
306                );
307                hir::ItemKind::TyAlias(ident, generics, ty)
308            }
309            ItemKind::Enum(ident, generics, enum_definition) => {
310                let ident = self.lower_ident(*ident);
311                let (generics, variants) = self.lower_generics(
312                    generics,
313                    id,
314                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
315                    |this| {
316                        this.arena.alloc_from_iter(
317                            enum_definition.variants.iter().map(|x| this.lower_variant(i, x)),
318                        )
319                    },
320                );
321                hir::ItemKind::Enum(ident, generics, hir::EnumDef { variants })
322            }
323            ItemKind::Struct(ident, generics, struct_def) => {
324                let ident = self.lower_ident(*ident);
325                let (generics, struct_def) = self.lower_generics(
326                    generics,
327                    id,
328                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
329                    |this| this.lower_variant_data(hir_id, i, struct_def),
330                );
331                hir::ItemKind::Struct(ident, generics, struct_def)
332            }
333            ItemKind::Union(ident, generics, vdata) => {
334                let ident = self.lower_ident(*ident);
335                let (generics, vdata) = self.lower_generics(
336                    generics,
337                    id,
338                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
339                    |this| this.lower_variant_data(hir_id, i, vdata),
340                );
341                hir::ItemKind::Union(ident, generics, vdata)
342            }
343            ItemKind::Impl(Impl {
344                generics: ast_generics,
345                of_trait,
346                self_ty: ty,
347                items: impl_items,
348            }) => {
349                // Lower the "impl header" first. This ordering is important
350                // for in-band lifetimes! Consider `'a` here:
351                //
352                //     impl Foo<'a> for u32 {
353                //         fn method(&'a self) { .. }
354                //     }
355                //
356                // Because we start by lowering the `Foo<'a> for u32`
357                // part, we will add `'a` to the list of generics on
358                // the impl. When we then encounter it later in the
359                // method, it will not be considered an in-band
360                // lifetime to be added, but rather a reference to a
361                // parent lifetime.
362                let itctx = ImplTraitContext::Universal;
363                let (generics, (of_trait, lowered_ty)) =
364                    self.lower_generics(ast_generics, id, itctx, |this| {
365                        let of_trait = of_trait
366                            .as_deref()
367                            .map(|of_trait| this.lower_trait_impl_header(of_trait));
368
369                        let lowered_ty = this.lower_ty(
370                            ty,
371                            ImplTraitContext::Disallowed(ImplTraitPosition::ImplSelf),
372                        );
373
374                        (of_trait, lowered_ty)
375                    });
376
377                let new_impl_items = self
378                    .arena
379                    .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
380
381                hir::ItemKind::Impl(hir::Impl {
382                    generics,
383                    of_trait,
384                    self_ty: lowered_ty,
385                    items: new_impl_items,
386                })
387            }
388            ItemKind::Trait(box Trait {
389                constness,
390                is_auto,
391                safety,
392                ident,
393                generics,
394                bounds,
395                items,
396            }) => {
397                let constness = self.lower_constness(*constness);
398                let ident = self.lower_ident(*ident);
399                let (generics, (safety, items, bounds)) = self.lower_generics(
400                    generics,
401                    id,
402                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
403                    |this| {
404                        let bounds = this.lower_param_bounds(
405                            bounds,
406                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::SuperTrait),
407                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
408                        );
409                        let items = this.arena.alloc_from_iter(
410                            items.iter().map(|item| this.lower_trait_item_ref(item)),
411                        );
412                        let safety = this.lower_safety(*safety, hir::Safety::Safe);
413                        (safety, items, bounds)
414                    },
415                );
416                hir::ItemKind::Trait(constness, *is_auto, safety, ident, generics, bounds, items)
417            }
418            ItemKind::TraitAlias(box TraitAlias { constness, ident, generics, bounds }) => {
419                let constness = self.lower_constness(*constness);
420                let ident = self.lower_ident(*ident);
421                let (generics, bounds) = self.lower_generics(
422                    generics,
423                    id,
424                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
425                    |this| {
426                        this.lower_param_bounds(
427                            bounds,
428                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitAlias),
429                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
430                        )
431                    },
432                );
433                hir::ItemKind::TraitAlias(constness, ident, generics, bounds)
434            }
435            ItemKind::MacroDef(ident, MacroDef { body, macro_rules }) => {
436                let ident = self.lower_ident(*ident);
437                let body = Box::new(self.lower_delim_args(body));
438                let def_id = self.local_def_id(id);
439                let def_kind = self.tcx.def_kind(def_id);
440                let DefKind::Macro(macro_kinds) = def_kind else {
441                    unreachable!(
442                        "expected DefKind::Macro for macro item, found {}",
443                        def_kind.descr(def_id.to_def_id())
444                    );
445                };
446                let macro_def = self.arena.alloc(ast::MacroDef { body, macro_rules: *macro_rules });
447                hir::ItemKind::Macro(ident, macro_def, macro_kinds)
448            }
449            ItemKind::Delegation(box delegation) => {
450                let delegation_results = self.lower_delegation(delegation, id, false);
451                hir::ItemKind::Fn {
452                    sig: delegation_results.sig,
453                    ident: delegation_results.ident,
454                    generics: delegation_results.generics,
455                    body: delegation_results.body_id,
456                    has_body: true,
457                }
458            }
459            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
460                panic!("macros should have been expanded by now")
461            }
462        }
463    }
464
465    fn lower_const_item(
466        &mut self,
467        ty: &Ty,
468        span: Span,
469        body: Option<&Expr>,
470        impl_trait_position: ImplTraitPosition,
471    ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
472        let ty = self.lower_ty(ty, ImplTraitContext::Disallowed(impl_trait_position));
473        (ty, self.lower_const_body(span, body))
474    }
475
476    #[instrument(level = "debug", skip(self))]
477    fn lower_use_tree(
478        &mut self,
479        tree: &UseTree,
480        prefix: &Path,
481        id: NodeId,
482        vis_span: Span,
483        attrs: &'hir [hir::Attribute],
484    ) -> hir::ItemKind<'hir> {
485        let path = &tree.prefix;
486        let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
487
488        match tree.kind {
489            UseTreeKind::Simple(rename) => {
490                let mut ident = tree.ident();
491
492                // First, apply the prefix to the path.
493                let mut path = Path { segments, span: path.span, tokens: None };
494
495                // Correctly resolve `self` imports.
496                if path.segments.len() > 1
497                    && path.segments.last().unwrap().ident.name == kw::SelfLower
498                {
499                    let _ = path.segments.pop();
500                    if rename.is_none() {
501                        ident = path.segments.last().unwrap().ident;
502                    }
503                }
504
505                let res = self.lower_import_res(id, path.span);
506                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
507                let ident = self.lower_ident(ident);
508                hir::ItemKind::Use(path, hir::UseKind::Single(ident))
509            }
510            UseTreeKind::Glob => {
511                let res = self.expect_full_res(id);
512                let res = self.lower_res(res);
513                // Put the result in the appropriate namespace.
514                let res = match res {
515                    Res::Def(DefKind::Mod | DefKind::Trait, _) => {
516                        PerNS { type_ns: Some(res), value_ns: None, macro_ns: None }
517                    }
518                    Res::Def(DefKind::Enum, _) => {
519                        PerNS { type_ns: None, value_ns: Some(res), macro_ns: None }
520                    }
521                    Res::Err => {
522                        // Propagate the error to all namespaces, just to be sure.
523                        let err = Some(Res::Err);
524                        PerNS { type_ns: err, value_ns: err, macro_ns: err }
525                    }
526                    _ => span_bug!(path.span, "bad glob res {:?}", res),
527                };
528                let path = Path { segments, span: path.span, tokens: None };
529                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
530                hir::ItemKind::Use(path, hir::UseKind::Glob)
531            }
532            UseTreeKind::Nested { items: ref trees, .. } => {
533                // Nested imports are desugared into simple imports.
534                // So, if we start with
535                //
536                // ```
537                // pub(x) use foo::{a, b};
538                // ```
539                //
540                // we will create three items:
541                //
542                // ```
543                // pub(x) use foo::a;
544                // pub(x) use foo::b;
545                // pub(x) use foo::{}; // <-- this is called the `ListStem`
546                // ```
547                //
548                // The first two are produced by recursively invoking
549                // `lower_use_tree` (and indeed there may be things
550                // like `use foo::{a::{b, c}}` and so forth). They
551                // wind up being directly added to
552                // `self.items`. However, the structure of this
553                // function also requires us to return one item, and
554                // for that we return the `{}` import (called the
555                // `ListStem`).
556
557                let span = prefix.span.to(path.span);
558                let prefix = Path { segments, span, tokens: None };
559
560                // Add all the nested `PathListItem`s to the HIR.
561                for &(ref use_tree, id) in trees {
562                    let owner_id = self.owner_id(id);
563
564                    // Each `use` import is an item and thus are owners of the
565                    // names in the path. Up to this point the nested import is
566                    // the current owner, since we want each desugared import to
567                    // own its own names, we have to adjust the owner before
568                    // lowering the rest of the import.
569                    self.with_hir_id_owner(id, |this| {
570                        // `prefix` is lowered multiple times, but in different HIR owners.
571                        // So each segment gets renewed `HirId` with the same
572                        // `ItemLocalId` and the new owner. (See `lower_node_id`)
573                        let kind = this.lower_use_tree(use_tree, &prefix, id, vis_span, attrs);
574                        if !attrs.is_empty() {
575                            this.attrs.insert(hir::ItemLocalId::ZERO, attrs);
576                        }
577
578                        let item = hir::Item {
579                            owner_id,
580                            kind,
581                            vis_span,
582                            span: this.lower_span(use_tree.span),
583                            has_delayed_lints: !this.delayed_lints.is_empty(),
584                        };
585                        hir::OwnerNode::Item(this.arena.alloc(item))
586                    });
587                }
588
589                // Condition should match `build_reduced_graph_for_use_tree`.
590                let path = if trees.is_empty()
591                    && !(prefix.segments.is_empty()
592                        || prefix.segments.len() == 1
593                            && prefix.segments[0].ident.name == kw::PathRoot)
594                {
595                    // For empty lists we need to lower the prefix so it is checked for things
596                    // like stability later.
597                    let res = self.lower_import_res(id, span);
598                    self.lower_use_path(res, &prefix, ParamMode::Explicit)
599                } else {
600                    // For non-empty lists we can just drop all the data, the prefix is already
601                    // present in HIR as a part of nested imports.
602                    let span = self.lower_span(span);
603                    self.arena.alloc(hir::UsePath { res: PerNS::default(), segments: &[], span })
604                };
605                hir::ItemKind::Use(path, hir::UseKind::ListStem)
606            }
607        }
608    }
609
610    fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) -> hir::OwnerNode<'hir> {
611        // Evaluate with the lifetimes in `params` in-scope.
612        // This is used to track which lifetimes have already been defined,
613        // and which need to be replicated when lowering an async fn.
614        match ctxt {
615            AssocCtxt::Trait => hir::OwnerNode::TraitItem(self.lower_trait_item(item)),
616            AssocCtxt::Impl { of_trait } => {
617                hir::OwnerNode::ImplItem(self.lower_impl_item(item, of_trait))
618            }
619        }
620    }
621
622    fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
623        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
624        let owner_id = hir_id.expect_owner();
625        let attrs =
626            self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_foreign_item_kind(&i.kind));
627        let (ident, kind) = match &i.kind {
628            ForeignItemKind::Fn(box Fn { sig, ident, generics, define_opaque, .. }) => {
629                let fdec = &sig.decl;
630                let itctx = ImplTraitContext::Universal;
631                let (generics, (decl, fn_args)) =
632                    self.lower_generics(generics, i.id, itctx, |this| {
633                        (
634                            // Disallow `impl Trait` in foreign items.
635                            this.lower_fn_decl(fdec, i.id, sig.span, FnDeclKind::ExternFn, None),
636                            this.lower_fn_params_to_idents(fdec),
637                        )
638                    });
639
640                // Unmarked safety in unsafe block defaults to unsafe.
641                let header = self.lower_fn_header(sig.header, hir::Safety::Unsafe, attrs);
642
643                if define_opaque.is_some() {
644                    self.dcx().span_err(i.span, "foreign functions cannot define opaque types");
645                }
646
647                (
648                    ident,
649                    hir::ForeignItemKind::Fn(
650                        hir::FnSig { header, decl, span: self.lower_span(sig.span) },
651                        fn_args,
652                        generics,
653                    ),
654                )
655            }
656            ForeignItemKind::Static(box StaticItem {
657                ident,
658                ty,
659                mutability,
660                expr: _,
661                safety,
662                define_opaque,
663            }) => {
664                let ty =
665                    self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
666                let safety = self.lower_safety(*safety, hir::Safety::Unsafe);
667                if define_opaque.is_some() {
668                    self.dcx().span_err(i.span, "foreign statics cannot define opaque types");
669                }
670                (ident, hir::ForeignItemKind::Static(ty, *mutability, safety))
671            }
672            ForeignItemKind::TyAlias(box TyAlias { ident, .. }) => {
673                (ident, hir::ForeignItemKind::Type)
674            }
675            ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
676        };
677
678        let item = hir::ForeignItem {
679            owner_id,
680            ident: self.lower_ident(*ident),
681            kind,
682            vis_span: self.lower_span(i.vis.span),
683            span: self.lower_span(i.span),
684            has_delayed_lints: !self.delayed_lints.is_empty(),
685        };
686        self.arena.alloc(item)
687    }
688
689    fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemId {
690        hir::ForeignItemId { owner_id: self.owner_id(i.id) }
691    }
692
693    fn lower_variant(&mut self, item_kind: &ItemKind, v: &Variant) -> hir::Variant<'hir> {
694        let hir_id = self.lower_node_id(v.id);
695        self.lower_attrs(hir_id, &v.attrs, v.span, Target::Variant);
696        hir::Variant {
697            hir_id,
698            def_id: self.local_def_id(v.id),
699            data: self.lower_variant_data(hir_id, item_kind, &v.data),
700            disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const_to_anon_const(e)),
701            ident: self.lower_ident(v.ident),
702            span: self.lower_span(v.span),
703        }
704    }
705
706    fn lower_variant_data(
707        &mut self,
708        parent_id: hir::HirId,
709        item_kind: &ItemKind,
710        vdata: &VariantData,
711    ) -> hir::VariantData<'hir> {
712        match vdata {
713            VariantData::Struct { fields, recovered } => {
714                let fields = self
715                    .arena
716                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
717
718                if let ItemKind::Union(..) = item_kind {
719                    for field in &fields[..] {
720                        if let Some(default) = field.default {
721                            // Unions cannot derive `Default`, and it's not clear how to use default
722                            // field values of unions if that was supported. Therefore, blanket reject
723                            // trying to use field values with unions.
724                            if self.tcx.features().default_field_values() {
725                                self.dcx().emit_err(UnionWithDefault { span: default.span });
726                            } else {
727                                let _ = self.dcx().span_delayed_bug(
728                                default.span,
729                                "expected union default field values feature gate error but none \
730                                was produced",
731                            );
732                            }
733                        }
734                    }
735                }
736
737                hir::VariantData::Struct { fields, recovered: *recovered }
738            }
739            VariantData::Tuple(fields, id) => {
740                let ctor_id = self.lower_node_id(*id);
741                self.alias_attrs(ctor_id, parent_id);
742                let fields = self
743                    .arena
744                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
745                for field in &fields[..] {
746                    if let Some(default) = field.default {
747                        // Default values in tuple struct and tuple variants are not allowed by the
748                        // RFC due to concerns about the syntax, both in the item definition and the
749                        // expression. We could in the future allow `struct S(i32 = 0);` and force
750                        // users to construct the value with `let _ = S { .. };`.
751                        if self.tcx.features().default_field_values() {
752                            self.dcx().emit_err(TupleStructWithDefault { span: default.span });
753                        } else {
754                            let _ = self.dcx().span_delayed_bug(
755                                default.span,
756                                "expected `default values on `struct` fields aren't supported` \
757                                 feature-gate error but none was produced",
758                            );
759                        }
760                    }
761                }
762                hir::VariantData::Tuple(fields, ctor_id, self.local_def_id(*id))
763            }
764            VariantData::Unit(id) => {
765                let ctor_id = self.lower_node_id(*id);
766                self.alias_attrs(ctor_id, parent_id);
767                hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
768            }
769        }
770    }
771
772    pub(super) fn lower_field_def(
773        &mut self,
774        (index, f): (usize, &FieldDef),
775    ) -> hir::FieldDef<'hir> {
776        let ty = self.lower_ty(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy));
777        let hir_id = self.lower_node_id(f.id);
778        self.lower_attrs(hir_id, &f.attrs, f.span, Target::Field);
779        hir::FieldDef {
780            span: self.lower_span(f.span),
781            hir_id,
782            def_id: self.local_def_id(f.id),
783            ident: match f.ident {
784                Some(ident) => self.lower_ident(ident),
785                // FIXME(jseyfried): positional field hygiene.
786                None => Ident::new(sym::integer(index), self.lower_span(f.span)),
787            },
788            vis_span: self.lower_span(f.vis.span),
789            default: f.default.as_ref().map(|v| self.lower_anon_const_to_anon_const(v)),
790            ty,
791            safety: self.lower_safety(f.safety, hir::Safety::Safe),
792        }
793    }
794
795    fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
796        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
797        let attrs = self.lower_attrs(
798            hir_id,
799            &i.attrs,
800            i.span,
801            Target::from_assoc_item_kind(&i.kind, AssocCtxt::Trait),
802        );
803        let trait_item_def_id = hir_id.expect_owner();
804
805        let (ident, generics, kind, has_default) = match &i.kind {
806            AssocItemKind::Const(box ConstItem {
807                ident,
808                generics,
809                ty,
810                expr,
811                define_opaque,
812                ..
813            }) => {
814                let (generics, kind) = self.lower_generics(
815                    generics,
816                    i.id,
817                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
818                    |this| {
819                        let ty = this
820                            .lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy));
821                        let body = expr.as_ref().map(|x| this.lower_const_body(i.span, Some(x)));
822
823                        hir::TraitItemKind::Const(ty, body)
824                    },
825                );
826
827                if define_opaque.is_some() {
828                    if expr.is_some() {
829                        self.lower_define_opaque(hir_id, &define_opaque);
830                    } else {
831                        self.dcx().span_err(
832                            i.span,
833                            "only trait consts with default bodies can define opaque types",
834                        );
835                    }
836                }
837
838                (*ident, generics, kind, expr.is_some())
839            }
840            AssocItemKind::Fn(box Fn {
841                sig, ident, generics, body: None, define_opaque, ..
842            }) => {
843                // FIXME(contracts): Deny contract here since it won't apply to
844                // any impl method or callees.
845                let idents = self.lower_fn_params_to_idents(&sig.decl);
846                let (generics, sig) = self.lower_method_sig(
847                    generics,
848                    sig,
849                    i.id,
850                    FnDeclKind::Trait,
851                    sig.header.coroutine_kind,
852                    attrs,
853                );
854                if define_opaque.is_some() {
855                    self.dcx().span_err(
856                        i.span,
857                        "only trait methods with default bodies can define opaque types",
858                    );
859                }
860                (
861                    *ident,
862                    generics,
863                    hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(idents)),
864                    false,
865                )
866            }
867            AssocItemKind::Fn(box Fn {
868                sig,
869                ident,
870                generics,
871                body: Some(body),
872                contract,
873                define_opaque,
874                ..
875            }) => {
876                let body_id = self.lower_maybe_coroutine_body(
877                    sig.span,
878                    i.span,
879                    hir_id,
880                    &sig.decl,
881                    sig.header.coroutine_kind,
882                    Some(body),
883                    attrs,
884                    contract.as_deref(),
885                );
886                let (generics, sig) = self.lower_method_sig(
887                    generics,
888                    sig,
889                    i.id,
890                    FnDeclKind::Trait,
891                    sig.header.coroutine_kind,
892                    attrs,
893                );
894                self.lower_define_opaque(hir_id, &define_opaque);
895                (
896                    *ident,
897                    generics,
898                    hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)),
899                    true,
900                )
901            }
902            AssocItemKind::Type(box TyAlias {
903                ident,
904                generics,
905                after_where_clause,
906                bounds,
907                ty,
908                ..
909            }) => {
910                let mut generics = generics.clone();
911                add_ty_alias_where_clause(&mut generics, after_where_clause, false);
912                let (generics, kind) = self.lower_generics(
913                    &generics,
914                    i.id,
915                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
916                    |this| {
917                        let ty = ty.as_ref().map(|x| {
918                            this.lower_ty(
919                                x,
920                                ImplTraitContext::Disallowed(ImplTraitPosition::AssocTy),
921                            )
922                        });
923                        hir::TraitItemKind::Type(
924                            this.lower_param_bounds(
925                                bounds,
926                                RelaxedBoundPolicy::Allowed,
927                                ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
928                            ),
929                            ty,
930                        )
931                    },
932                );
933                (*ident, generics, kind, ty.is_some())
934            }
935            AssocItemKind::Delegation(box delegation) => {
936                let delegation_results = self.lower_delegation(delegation, i.id, false);
937                let item_kind = hir::TraitItemKind::Fn(
938                    delegation_results.sig,
939                    hir::TraitFn::Provided(delegation_results.body_id),
940                );
941                (delegation.ident, delegation_results.generics, item_kind, true)
942            }
943            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
944                panic!("macros should have been expanded by now")
945            }
946        };
947
948        let item = hir::TraitItem {
949            owner_id: trait_item_def_id,
950            ident: self.lower_ident(ident),
951            generics,
952            kind,
953            span: self.lower_span(i.span),
954            defaultness: hir::Defaultness::Default { has_value: has_default },
955            has_delayed_lints: !self.delayed_lints.is_empty(),
956        };
957        self.arena.alloc(item)
958    }
959
960    fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemId {
961        hir::TraitItemId { owner_id: self.owner_id(i.id) }
962    }
963
964    /// Construct `ExprKind::Err` for the given `span`.
965    pub(crate) fn expr_err(&mut self, span: Span, guar: ErrorGuaranteed) -> hir::Expr<'hir> {
966        self.expr(span, hir::ExprKind::Err(guar))
967    }
968
969    fn lower_trait_impl_header(
970        &mut self,
971        trait_impl_header: &TraitImplHeader,
972    ) -> &'hir hir::TraitImplHeader<'hir> {
973        let TraitImplHeader { constness, safety, polarity, defaultness, ref trait_ref } =
974            *trait_impl_header;
975        let constness = self.lower_constness(constness);
976        let safety = self.lower_safety(safety, hir::Safety::Safe);
977        let polarity = match polarity {
978            ImplPolarity::Positive => ImplPolarity::Positive,
979            ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
980        };
981        // `defaultness.has_value()` is never called for an `impl`, always `true` in order
982        // to not cause an assertion failure inside the `lower_defaultness` function.
983        let has_val = true;
984        let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
985        let modifiers = TraitBoundModifiers {
986            constness: BoundConstness::Never,
987            asyncness: BoundAsyncness::Normal,
988            // we don't use this in bound lowering
989            polarity: BoundPolarity::Positive,
990        };
991        let trait_ref = self.lower_trait_ref(
992            modifiers,
993            trait_ref,
994            ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
995        );
996
997        self.arena.alloc(hir::TraitImplHeader {
998            constness,
999            safety,
1000            polarity,
1001            defaultness,
1002            defaultness_span,
1003            trait_ref,
1004        })
1005    }
1006
1007    fn lower_impl_item(
1008        &mut self,
1009        i: &AssocItem,
1010        is_in_trait_impl: bool,
1011    ) -> &'hir hir::ImplItem<'hir> {
1012        // Since `default impl` is not yet implemented, this is always true in impls.
1013        let has_value = true;
1014        let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
1015        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
1016        let attrs = self.lower_attrs(
1017            hir_id,
1018            &i.attrs,
1019            i.span,
1020            Target::from_assoc_item_kind(&i.kind, AssocCtxt::Impl { of_trait: is_in_trait_impl }),
1021        );
1022
1023        let (ident, (generics, kind)) = match &i.kind {
1024            AssocItemKind::Const(box ConstItem {
1025                ident,
1026                generics,
1027                ty,
1028                expr,
1029                define_opaque,
1030                ..
1031            }) => (
1032                *ident,
1033                self.lower_generics(
1034                    generics,
1035                    i.id,
1036                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1037                    |this| {
1038                        let ty = this
1039                            .lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy));
1040                        let body = this.lower_const_body(i.span, expr.as_deref());
1041                        this.lower_define_opaque(hir_id, &define_opaque);
1042                        hir::ImplItemKind::Const(ty, body)
1043                    },
1044                ),
1045            ),
1046            AssocItemKind::Fn(box Fn {
1047                sig,
1048                ident,
1049                generics,
1050                body,
1051                contract,
1052                define_opaque,
1053                ..
1054            }) => {
1055                let body_id = self.lower_maybe_coroutine_body(
1056                    sig.span,
1057                    i.span,
1058                    hir_id,
1059                    &sig.decl,
1060                    sig.header.coroutine_kind,
1061                    body.as_deref(),
1062                    attrs,
1063                    contract.as_deref(),
1064                );
1065                let (generics, sig) = self.lower_method_sig(
1066                    generics,
1067                    sig,
1068                    i.id,
1069                    if is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
1070                    sig.header.coroutine_kind,
1071                    attrs,
1072                );
1073                self.lower_define_opaque(hir_id, &define_opaque);
1074
1075                (*ident, (generics, hir::ImplItemKind::Fn(sig, body_id)))
1076            }
1077            AssocItemKind::Type(box TyAlias {
1078                ident, generics, after_where_clause, ty, ..
1079            }) => {
1080                let mut generics = generics.clone();
1081                add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1082                (
1083                    *ident,
1084                    self.lower_generics(
1085                        &generics,
1086                        i.id,
1087                        ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1088                        |this| match ty {
1089                            None => {
1090                                let guar = this.dcx().span_delayed_bug(
1091                                    i.span,
1092                                    "expected to lower associated type, but it was missing",
1093                                );
1094                                let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err(guar)));
1095                                hir::ImplItemKind::Type(ty)
1096                            }
1097                            Some(ty) => {
1098                                let ty = this.lower_ty(
1099                                    ty,
1100                                    ImplTraitContext::OpaqueTy {
1101                                        origin: hir::OpaqueTyOrigin::TyAlias {
1102                                            parent: this.local_def_id(i.id),
1103                                            in_assoc_ty: true,
1104                                        },
1105                                    },
1106                                );
1107                                hir::ImplItemKind::Type(ty)
1108                            }
1109                        },
1110                    ),
1111                )
1112            }
1113            AssocItemKind::Delegation(box delegation) => {
1114                let delegation_results = self.lower_delegation(delegation, i.id, is_in_trait_impl);
1115                (
1116                    delegation.ident,
1117                    (
1118                        delegation_results.generics,
1119                        hir::ImplItemKind::Fn(delegation_results.sig, delegation_results.body_id),
1120                    ),
1121                )
1122            }
1123            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1124                panic!("macros should have been expanded by now")
1125            }
1126        };
1127
1128        let span = self.lower_span(i.span);
1129        let item = hir::ImplItem {
1130            owner_id: hir_id.expect_owner(),
1131            ident: self.lower_ident(ident),
1132            generics,
1133            impl_kind: if is_in_trait_impl {
1134                ImplItemImplKind::Trait {
1135                    defaultness,
1136                    trait_item_def_id: self
1137                        .resolver
1138                        .get_partial_res(i.id)
1139                        .and_then(|r| r.expect_full_res().opt_def_id())
1140                        .ok_or_else(|| {
1141                            self.dcx().span_delayed_bug(
1142                                span,
1143                                "could not resolve trait item being implemented",
1144                            )
1145                        }),
1146                }
1147            } else {
1148                ImplItemImplKind::Inherent { vis_span: self.lower_span(i.vis.span) }
1149            },
1150            kind,
1151            span,
1152            has_delayed_lints: !self.delayed_lints.is_empty(),
1153        };
1154        self.arena.alloc(item)
1155    }
1156
1157    fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemId {
1158        hir::ImplItemId { owner_id: self.owner_id(i.id) }
1159    }
1160
1161    fn lower_defaultness(
1162        &self,
1163        d: Defaultness,
1164        has_value: bool,
1165    ) -> (hir::Defaultness, Option<Span>) {
1166        match d {
1167            Defaultness::Default(sp) => {
1168                (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
1169            }
1170            Defaultness::Final => {
1171                assert!(has_value);
1172                (hir::Defaultness::Final, None)
1173            }
1174        }
1175    }
1176
1177    fn record_body(
1178        &mut self,
1179        params: &'hir [hir::Param<'hir>],
1180        value: hir::Expr<'hir>,
1181    ) -> hir::BodyId {
1182        let body = hir::Body { params, value: self.arena.alloc(value) };
1183        let id = body.id();
1184        assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
1185        self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
1186        id
1187    }
1188
1189    pub(super) fn lower_body(
1190        &mut self,
1191        f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1192    ) -> hir::BodyId {
1193        let prev_coroutine_kind = self.coroutine_kind.take();
1194        let task_context = self.task_context.take();
1195        let (parameters, result) = f(self);
1196        let body_id = self.record_body(parameters, result);
1197        self.task_context = task_context;
1198        self.coroutine_kind = prev_coroutine_kind;
1199        body_id
1200    }
1201
1202    fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1203        let hir_id = self.lower_node_id(param.id);
1204        self.lower_attrs(hir_id, &param.attrs, param.span, Target::Param);
1205        hir::Param {
1206            hir_id,
1207            pat: self.lower_pat(&param.pat),
1208            ty_span: self.lower_span(param.ty.span),
1209            span: self.lower_span(param.span),
1210        }
1211    }
1212
1213    pub(super) fn lower_fn_body(
1214        &mut self,
1215        decl: &FnDecl,
1216        contract: Option<&FnContract>,
1217        body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1218    ) -> hir::BodyId {
1219        self.lower_body(|this| {
1220            let params =
1221                this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x)));
1222
1223            // Optionally lower the fn contract
1224            if let Some(contract) = contract {
1225                (params, this.lower_contract(body, contract))
1226            } else {
1227                (params, body(this))
1228            }
1229        })
1230    }
1231
1232    fn lower_fn_body_block(
1233        &mut self,
1234        decl: &FnDecl,
1235        body: &Block,
1236        contract: Option<&FnContract>,
1237    ) -> hir::BodyId {
1238        self.lower_fn_body(decl, contract, |this| this.lower_block_expr(body))
1239    }
1240
1241    pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1242        self.lower_body(|this| {
1243            (
1244                &[],
1245                match expr {
1246                    Some(expr) => this.lower_expr_mut(expr),
1247                    None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")),
1248                },
1249            )
1250        })
1251    }
1252
1253    /// Takes what may be the body of an `async fn` or a `gen fn` and wraps it in an `async {}` or
1254    /// `gen {}` block as appropriate.
1255    fn lower_maybe_coroutine_body(
1256        &mut self,
1257        fn_decl_span: Span,
1258        span: Span,
1259        fn_id: hir::HirId,
1260        decl: &FnDecl,
1261        coroutine_kind: Option<CoroutineKind>,
1262        body: Option<&Block>,
1263        attrs: &'hir [hir::Attribute],
1264        contract: Option<&FnContract>,
1265    ) -> hir::BodyId {
1266        let Some(body) = body else {
1267            // Functions without a body are an error, except if this is an intrinsic. For those we
1268            // create a fake body so that the entire rest of the compiler doesn't have to deal with
1269            // this as a special case.
1270            return self.lower_fn_body(decl, contract, |this| {
1271                if attrs.iter().any(|a| a.has_name(sym::rustc_intrinsic))
1272                    || this.tcx.is_sdylib_interface_build()
1273                {
1274                    let span = this.lower_span(span);
1275                    let empty_block = hir::Block {
1276                        hir_id: this.next_id(),
1277                        stmts: &[],
1278                        expr: None,
1279                        rules: hir::BlockCheckMode::DefaultBlock,
1280                        span,
1281                        targeted_by_break: false,
1282                    };
1283                    let loop_ = hir::ExprKind::Loop(
1284                        this.arena.alloc(empty_block),
1285                        None,
1286                        hir::LoopSource::Loop,
1287                        span,
1288                    );
1289                    hir::Expr { hir_id: this.next_id(), kind: loop_, span }
1290                } else {
1291                    this.expr_err(span, this.dcx().has_errors().unwrap())
1292                }
1293            });
1294        };
1295        let Some(coroutine_kind) = coroutine_kind else {
1296            // Typical case: not a coroutine.
1297            return self.lower_fn_body_block(decl, body, contract);
1298        };
1299        // FIXME(contracts): Support contracts on async fn.
1300        self.lower_body(|this| {
1301            let (parameters, expr) = this.lower_coroutine_body_with_moved_arguments(
1302                decl,
1303                |this| this.lower_block_expr(body),
1304                fn_decl_span,
1305                body.span,
1306                coroutine_kind,
1307                hir::CoroutineSource::Fn,
1308            );
1309
1310            // FIXME(async_fn_track_caller): Can this be moved above?
1311            let hir_id = expr.hir_id;
1312            this.maybe_forward_track_caller(body.span, fn_id, hir_id);
1313
1314            (parameters, expr)
1315        })
1316    }
1317
1318    /// Lowers a desugared coroutine body after moving all of the arguments
1319    /// into the body. This is to make sure that the future actually owns the
1320    /// arguments that are passed to the function, and to ensure things like
1321    /// drop order are stable.
1322    pub(crate) fn lower_coroutine_body_with_moved_arguments(
1323        &mut self,
1324        decl: &FnDecl,
1325        lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::Expr<'hir>,
1326        fn_decl_span: Span,
1327        body_span: Span,
1328        coroutine_kind: CoroutineKind,
1329        coroutine_source: hir::CoroutineSource,
1330    ) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>) {
1331        let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1332        let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1333
1334        // Async function parameters are lowered into the closure body so that they are
1335        // captured and so that the drop order matches the equivalent non-async functions.
1336        //
1337        // from:
1338        //
1339        //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1340        //         <body>
1341        //     }
1342        //
1343        // into:
1344        //
1345        //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1346        //       async move {
1347        //         let __arg2 = __arg2;
1348        //         let <pattern> = __arg2;
1349        //         let __arg1 = __arg1;
1350        //         let <pattern> = __arg1;
1351        //         let __arg0 = __arg0;
1352        //         let <pattern> = __arg0;
1353        //         drop-temps { <body> } // see comments later in fn for details
1354        //       }
1355        //     }
1356        //
1357        // If `<pattern>` is a simple ident, then it is lowered to a single
1358        // `let <pattern> = <pattern>;` statement as an optimization.
1359        //
1360        // Note that the body is embedded in `drop-temps`; an
1361        // equivalent desugaring would be `return { <body>
1362        // };`. The key point is that we wish to drop all the
1363        // let-bound variables and temporaries created in the body
1364        // (and its tail expression!) before we drop the
1365        // parameters (c.f. rust-lang/rust#64512).
1366        for (index, parameter) in decl.inputs.iter().enumerate() {
1367            let parameter = self.lower_param(parameter);
1368            let span = parameter.pat.span;
1369
1370            // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1371            // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1372            let (ident, is_simple_parameter) = match parameter.pat.kind {
1373                hir::PatKind::Binding(hir::BindingMode(ByRef::No, _), _, ident, _) => (ident, true),
1374                // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1375                // we can keep the same name for the parameter.
1376                // This lets rustdoc render it correctly in documentation.
1377                hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1378                hir::PatKind::Wild => (Ident::with_dummy_span(rustc_span::kw::Underscore), false),
1379                _ => {
1380                    // Replace the ident for bindings that aren't simple.
1381                    let name = format!("__arg{index}");
1382                    let ident = Ident::from_str(&name);
1383
1384                    (ident, false)
1385                }
1386            };
1387
1388            let desugared_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1389
1390            // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1391            // async function.
1392            //
1393            // If this is the simple case, this parameter will end up being the same as the
1394            // original parameter, but with a different pattern id.
1395            let stmt_attrs = self.attrs.get(&parameter.hir_id.local_id).copied();
1396            let (new_parameter_pat, new_parameter_id) = self.pat_ident(desugared_span, ident);
1397            let new_parameter = hir::Param {
1398                hir_id: parameter.hir_id,
1399                pat: new_parameter_pat,
1400                ty_span: self.lower_span(parameter.ty_span),
1401                span: self.lower_span(parameter.span),
1402            };
1403
1404            if is_simple_parameter {
1405                // If this is the simple case, then we only insert one statement that is
1406                // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1407                // `HirId`s are densely assigned.
1408                let expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1409                let stmt = self.stmt_let_pat(
1410                    stmt_attrs,
1411                    desugared_span,
1412                    Some(expr),
1413                    parameter.pat,
1414                    hir::LocalSource::AsyncFn,
1415                );
1416                statements.push(stmt);
1417            } else {
1418                // If this is not the simple case, then we construct two statements:
1419                //
1420                // ```
1421                // let __argN = __argN;
1422                // let <pat> = __argN;
1423                // ```
1424                //
1425                // The first statement moves the parameter into the closure and thus ensures
1426                // that the drop order is correct.
1427                //
1428                // The second statement creates the bindings that the user wrote.
1429
1430                // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1431                // because the user may have specified a `ref mut` binding in the next
1432                // statement.
1433                let (move_pat, move_id) =
1434                    self.pat_ident_binding_mode(desugared_span, ident, hir::BindingMode::MUT);
1435                let move_expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1436                let move_stmt = self.stmt_let_pat(
1437                    None,
1438                    desugared_span,
1439                    Some(move_expr),
1440                    move_pat,
1441                    hir::LocalSource::AsyncFn,
1442                );
1443
1444                // Construct the `let <pat> = __argN;` statement. We re-use the original
1445                // parameter's pattern so that `HirId`s are densely assigned.
1446                let pattern_expr = self.expr_ident(desugared_span, ident, move_id);
1447                let pattern_stmt = self.stmt_let_pat(
1448                    stmt_attrs,
1449                    desugared_span,
1450                    Some(pattern_expr),
1451                    parameter.pat,
1452                    hir::LocalSource::AsyncFn,
1453                );
1454
1455                statements.push(move_stmt);
1456                statements.push(pattern_stmt);
1457            };
1458
1459            parameters.push(new_parameter);
1460        }
1461
1462        let mkbody = |this: &mut LoweringContext<'_, 'hir>| {
1463            // Create a block from the user's function body:
1464            let user_body = lower_body(this);
1465
1466            // Transform into `drop-temps { <user-body> }`, an expression:
1467            let desugared_span =
1468                this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1469            let user_body = this.expr_drop_temps(desugared_span, this.arena.alloc(user_body));
1470
1471            // As noted above, create the final block like
1472            //
1473            // ```
1474            // {
1475            //   let $param_pattern = $raw_param;
1476            //   ...
1477            //   drop-temps { <user-body> }
1478            // }
1479            // ```
1480            let body = this.block_all(
1481                desugared_span,
1482                this.arena.alloc_from_iter(statements),
1483                Some(user_body),
1484            );
1485
1486            this.expr_block(body)
1487        };
1488        let desugaring_kind = match coroutine_kind {
1489            CoroutineKind::Async { .. } => hir::CoroutineDesugaring::Async,
1490            CoroutineKind::Gen { .. } => hir::CoroutineDesugaring::Gen,
1491            CoroutineKind::AsyncGen { .. } => hir::CoroutineDesugaring::AsyncGen,
1492        };
1493        let closure_id = coroutine_kind.closure_id();
1494
1495        let coroutine_expr = self.make_desugared_coroutine_expr(
1496            // The default capture mode here is by-ref. Later on during upvar analysis,
1497            // we will force the captured arguments to by-move, but for async closures,
1498            // we want to make sure that we avoid unnecessarily moving captures, or else
1499            // all async closures would default to `FnOnce` as their calling mode.
1500            CaptureBy::Ref,
1501            closure_id,
1502            None,
1503            fn_decl_span,
1504            body_span,
1505            desugaring_kind,
1506            coroutine_source,
1507            mkbody,
1508        );
1509
1510        let expr = hir::Expr {
1511            hir_id: self.lower_node_id(closure_id),
1512            kind: coroutine_expr,
1513            span: self.lower_span(body_span),
1514        };
1515
1516        (self.arena.alloc_from_iter(parameters), expr)
1517    }
1518
1519    fn lower_method_sig(
1520        &mut self,
1521        generics: &Generics,
1522        sig: &FnSig,
1523        id: NodeId,
1524        kind: FnDeclKind,
1525        coroutine_kind: Option<CoroutineKind>,
1526        attrs: &[hir::Attribute],
1527    ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1528        let header = self.lower_fn_header(sig.header, hir::Safety::Safe, attrs);
1529        let itctx = ImplTraitContext::Universal;
1530        let (generics, decl) = self.lower_generics(generics, id, itctx, |this| {
1531            this.lower_fn_decl(&sig.decl, id, sig.span, kind, coroutine_kind)
1532        });
1533        (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1534    }
1535
1536    pub(super) fn lower_fn_header(
1537        &mut self,
1538        h: FnHeader,
1539        default_safety: hir::Safety,
1540        attrs: &[hir::Attribute],
1541    ) -> hir::FnHeader {
1542        let asyncness = if let Some(CoroutineKind::Async { span, .. }) = h.coroutine_kind {
1543            hir::IsAsync::Async(self.lower_span(span))
1544        } else {
1545            hir::IsAsync::NotAsync
1546        };
1547
1548        let safety = self.lower_safety(h.safety, default_safety);
1549
1550        // Treat safe `#[target_feature]` functions as unsafe, but also remember that we did so.
1551        let safety = if find_attr!(attrs, AttributeKind::TargetFeature { was_forced: false, .. })
1552            && safety.is_safe()
1553            && !self.tcx.sess.target.is_like_wasm
1554        {
1555            hir::HeaderSafety::SafeTargetFeatures
1556        } else {
1557            safety.into()
1558        };
1559
1560        hir::FnHeader {
1561            safety,
1562            asyncness,
1563            constness: self.lower_constness(h.constness),
1564            abi: self.lower_extern(h.ext),
1565        }
1566    }
1567
1568    pub(super) fn lower_abi(&mut self, abi_str: StrLit) -> ExternAbi {
1569        let ast::StrLit { symbol_unescaped, span, .. } = abi_str;
1570        let extern_abi = symbol_unescaped.as_str().parse().unwrap_or_else(|_| {
1571            self.error_on_invalid_abi(abi_str);
1572            ExternAbi::Rust
1573        });
1574        let tcx = self.tcx;
1575
1576        // we can't do codegen for unsupported ABIs, so error now so we won't get farther
1577        if !tcx.sess.target.is_abi_supported(extern_abi) {
1578            let mut err = struct_span_code_err!(
1579                tcx.dcx(),
1580                span,
1581                E0570,
1582                "{extern_abi} is not a supported ABI for the current target",
1583            );
1584
1585            if let ExternAbi::Stdcall { unwind } = extern_abi {
1586                let c_abi = ExternAbi::C { unwind };
1587                let system_abi = ExternAbi::System { unwind };
1588                err.help(format!("if you need `extern {extern_abi}` on win32 and `extern {c_abi}` everywhere else, \
1589                    use `extern {system_abi}`"
1590                ));
1591            }
1592            err.emit();
1593        }
1594        // Show required feature gate even if we already errored, as the user is likely to build the code
1595        // for the actually intended target next and then they will need the feature gate.
1596        gate_unstable_abi(tcx.sess, tcx.features(), span, extern_abi);
1597        extern_abi
1598    }
1599
1600    pub(super) fn lower_extern(&mut self, ext: Extern) -> ExternAbi {
1601        match ext {
1602            Extern::None => ExternAbi::Rust,
1603            Extern::Implicit(_) => ExternAbi::FALLBACK,
1604            Extern::Explicit(abi, _) => self.lower_abi(abi),
1605        }
1606    }
1607
1608    fn error_on_invalid_abi(&self, abi: StrLit) {
1609        let abi_names = enabled_names(self.tcx.features(), abi.span)
1610            .iter()
1611            .map(|s| Symbol::intern(s))
1612            .collect::<Vec<_>>();
1613        let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1614        self.dcx().emit_err(InvalidAbi {
1615            abi: abi.symbol_unescaped,
1616            span: abi.span,
1617            suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1618                span: abi.span,
1619                suggestion: suggested_name.to_string(),
1620            }),
1621            command: "rustc --print=calling-conventions".to_string(),
1622        });
1623    }
1624
1625    pub(super) fn lower_constness(&mut self, c: Const) -> hir::Constness {
1626        match c {
1627            Const::Yes(_) => hir::Constness::Const,
1628            Const::No => hir::Constness::NotConst,
1629        }
1630    }
1631
1632    pub(super) fn lower_safety(&self, s: Safety, default: hir::Safety) -> hir::Safety {
1633        match s {
1634            Safety::Unsafe(_) => hir::Safety::Unsafe,
1635            Safety::Default => default,
1636            Safety::Safe(_) => hir::Safety::Safe,
1637        }
1638    }
1639
1640    /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1641    /// the carried impl trait definitions and bounds.
1642    #[instrument(level = "debug", skip(self, f))]
1643    fn lower_generics<T>(
1644        &mut self,
1645        generics: &Generics,
1646        parent_node_id: NodeId,
1647        itctx: ImplTraitContext,
1648        f: impl FnOnce(&mut Self) -> T,
1649    ) -> (&'hir hir::Generics<'hir>, T) {
1650        assert!(self.impl_trait_defs.is_empty());
1651        assert!(self.impl_trait_bounds.is_empty());
1652
1653        let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1654        predicates.extend(generics.params.iter().filter_map(|param| {
1655            self.lower_generic_bound_predicate(
1656                param.ident,
1657                param.id,
1658                &param.kind,
1659                &param.bounds,
1660                param.colon_span,
1661                generics.span,
1662                RelaxedBoundPolicy::Allowed,
1663                itctx,
1664                PredicateOrigin::GenericParam,
1665            )
1666        }));
1667        predicates.extend(
1668            generics
1669                .where_clause
1670                .predicates
1671                .iter()
1672                .map(|predicate| self.lower_where_predicate(predicate, &generics.params)),
1673        );
1674
1675        let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> = self
1676            .lower_generic_params_mut(&generics.params, hir::GenericParamSource::Generics)
1677            .collect();
1678
1679        // Introduce extra lifetimes if late resolution tells us to.
1680        let extra_lifetimes = self.resolver.extra_lifetime_params(parent_node_id);
1681        params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1682            self.lifetime_res_to_generic_param(
1683                ident,
1684                node_id,
1685                res,
1686                hir::GenericParamSource::Generics,
1687            )
1688        }));
1689
1690        let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1691        let where_clause_span = self.lower_span(generics.where_clause.span);
1692        let span = self.lower_span(generics.span);
1693        let res = f(self);
1694
1695        let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1696        params.extend(impl_trait_defs.into_iter());
1697
1698        let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1699        predicates.extend(impl_trait_bounds.into_iter());
1700
1701        let lowered_generics = self.arena.alloc(hir::Generics {
1702            params: self.arena.alloc_from_iter(params),
1703            predicates: self.arena.alloc_from_iter(predicates),
1704            has_where_clause_predicates,
1705            where_clause_span,
1706            span,
1707        });
1708
1709        (lowered_generics, res)
1710    }
1711
1712    pub(super) fn lower_define_opaque(
1713        &mut self,
1714        hir_id: HirId,
1715        define_opaque: &Option<ThinVec<(NodeId, Path)>>,
1716    ) {
1717        assert_eq!(self.define_opaque, None);
1718        assert!(hir_id.is_owner());
1719        let Some(define_opaque) = define_opaque.as_ref() else {
1720            return;
1721        };
1722        let define_opaque = define_opaque.iter().filter_map(|(id, path)| {
1723            let res = self.resolver.get_partial_res(*id);
1724            let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else {
1725                self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1726                return None;
1727            };
1728            let Some(did) = did.as_local() else {
1729                self.dcx().span_err(
1730                    path.span,
1731                    "only opaque types defined in the local crate can be defined",
1732                );
1733                return None;
1734            };
1735            Some((self.lower_span(path.span), did))
1736        });
1737        let define_opaque = self.arena.alloc_from_iter(define_opaque);
1738        self.define_opaque = Some(define_opaque);
1739    }
1740
1741    pub(super) fn lower_generic_bound_predicate(
1742        &mut self,
1743        ident: Ident,
1744        id: NodeId,
1745        kind: &GenericParamKind,
1746        bounds: &[GenericBound],
1747        colon_span: Option<Span>,
1748        parent_span: Span,
1749        rbp: RelaxedBoundPolicy<'_>,
1750        itctx: ImplTraitContext,
1751        origin: PredicateOrigin,
1752    ) -> Option<hir::WherePredicate<'hir>> {
1753        // Do not create a clause if we do not have anything inside it.
1754        if bounds.is_empty() {
1755            return None;
1756        }
1757
1758        let bounds = self.lower_param_bounds(bounds, rbp, itctx);
1759
1760        let param_span = ident.span;
1761
1762        // Reconstruct the span of the entire predicate from the individual generic bounds.
1763        let span_start = colon_span.unwrap_or_else(|| param_span.shrink_to_hi());
1764        let span = bounds.iter().fold(span_start, |span_accum, bound| {
1765            match bound.span().find_ancestor_inside(parent_span) {
1766                Some(bound_span) => span_accum.to(bound_span),
1767                None => span_accum,
1768            }
1769        });
1770        let span = self.lower_span(span);
1771        let hir_id = self.next_id();
1772        let kind = self.arena.alloc(match kind {
1773            GenericParamKind::Const { .. } => return None,
1774            GenericParamKind::Type { .. } => {
1775                let def_id = self.local_def_id(id).to_def_id();
1776                let hir_id = self.next_id();
1777                let res = Res::Def(DefKind::TyParam, def_id);
1778                let ident = self.lower_ident(ident);
1779                let ty_path = self.arena.alloc(hir::Path {
1780                    span: self.lower_span(param_span),
1781                    res,
1782                    segments: self
1783                        .arena
1784                        .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1785                });
1786                let ty_id = self.next_id();
1787                let bounded_ty =
1788                    self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1789                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1790                    bounded_ty: self.arena.alloc(bounded_ty),
1791                    bounds,
1792                    bound_generic_params: &[],
1793                    origin,
1794                })
1795            }
1796            GenericParamKind::Lifetime => {
1797                let lt_id = self.next_node_id();
1798                let lifetime =
1799                    self.new_named_lifetime(id, lt_id, ident, LifetimeSource::Other, ident.into());
1800                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1801                    lifetime,
1802                    bounds,
1803                    in_where_clause: false,
1804                })
1805            }
1806        });
1807        Some(hir::WherePredicate { hir_id, span, kind })
1808    }
1809
1810    fn lower_where_predicate(
1811        &mut self,
1812        pred: &WherePredicate,
1813        params: &[ast::GenericParam],
1814    ) -> hir::WherePredicate<'hir> {
1815        let hir_id = self.lower_node_id(pred.id);
1816        let span = self.lower_span(pred.span);
1817        self.lower_attrs(hir_id, &pred.attrs, span, Target::WherePredicate);
1818        let kind = self.arena.alloc(match &pred.kind {
1819            WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1820                bound_generic_params,
1821                bounded_ty,
1822                bounds,
1823            }) => {
1824                let rbp = if bound_generic_params.is_empty() {
1825                    RelaxedBoundPolicy::AllowedIfOnTyParam(bounded_ty.id, params)
1826                } else {
1827                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::LateBoundVarsInScope)
1828                };
1829                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1830                    bound_generic_params: self.lower_generic_params(
1831                        bound_generic_params,
1832                        hir::GenericParamSource::Binder,
1833                    ),
1834                    bounded_ty: self.lower_ty(
1835                        bounded_ty,
1836                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1837                    ),
1838                    bounds: self.lower_param_bounds(
1839                        bounds,
1840                        rbp,
1841                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1842                    ),
1843                    origin: PredicateOrigin::WhereClause,
1844                })
1845            }
1846            WherePredicateKind::RegionPredicate(WhereRegionPredicate { lifetime, bounds }) => {
1847                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1848                    lifetime: self.lower_lifetime(
1849                        lifetime,
1850                        LifetimeSource::Other,
1851                        lifetime.ident.into(),
1852                    ),
1853                    bounds: self.lower_param_bounds(
1854                        bounds,
1855                        RelaxedBoundPolicy::Allowed,
1856                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1857                    ),
1858                    in_where_clause: true,
1859                })
1860            }
1861            WherePredicateKind::EqPredicate(WhereEqPredicate { lhs_ty, rhs_ty }) => {
1862                hir::WherePredicateKind::EqPredicate(hir::WhereEqPredicate {
1863                    lhs_ty: self
1864                        .lower_ty(lhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Bound)),
1865                    rhs_ty: self
1866                        .lower_ty(rhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Bound)),
1867                })
1868            }
1869        });
1870        hir::WherePredicate { hir_id, span, kind }
1871    }
1872}