Skip to main content

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, EiiImplResolution};
6use rustc_hir::def::{DefKind, PerNS, Res};
7use rustc_hir::{
8    self as hir, CRATE_OWNER_ID, HirId, ImplItemImplKind, LifetimeSource, PredicateOrigin, Target,
9    find_attr,
10};
11use rustc_middle::span_bug;
12use rustc_middle::ty::data_structures::IndexMap;
13use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
14use rustc_span::def_id::{DefId, LocalDefId};
15use rustc_span::edit_distance::find_best_match_for_name;
16use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
17use smallvec::SmallVec;
18use thin_vec::ThinVec;
19use tracing::instrument;
20
21use super::diagnostics::{
22    InvalidAbi, InvalidAbiSuggestion, TupleStructWithDefault, UnionWithDefault,
23};
24use super::stability::{enabled_names, gate_unstable_abi};
25use super::{
26    FnDeclKind, GenericArgsMode, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
27    RelaxedBoundForbiddenReason, RelaxedBoundPolicy,
28};
29use crate::diagnostics::ConstComptimeFn;
30
31pub(super) struct ItemLowerer<'a, 'hir> {
32    pub(super) tcx: TyCtxt<'hir>,
33    pub(super) resolver: &'a ResolverAstLowering<'hir>,
34}
35
36/// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
37/// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
38/// clause if it exists.
39fn add_ty_alias_where_clause(
40    generics: &mut ast::Generics,
41    after_where_clause: &ast::WhereClause,
42    prefer_first: bool,
43) {
44    generics.where_clause.predicates.extend_from_slice(&after_where_clause.predicates);
45
46    let mut before = (generics.where_clause.has_where_token, generics.where_clause.span);
47    let mut after = (after_where_clause.has_where_token, after_where_clause.span);
48    if !prefer_first {
49        (before, after) = (after, before);
50    }
51    (generics.where_clause.has_where_token, generics.where_clause.span) =
52        if before.0 || !after.0 { before } else { after };
53}
54
55impl<'hir> ItemLowerer<'_, 'hir> {
56    fn with_lctx(
57        &mut self,
58        owner: NodeId,
59        f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
60    ) -> hir::MaybeOwner<'hir> {
61        let mut lctx = LoweringContext::new(self.tcx, self.resolver, owner);
62
63        let item = f(&mut lctx);
64        if true {
    {
        match (&lctx.current_hir_id_owner, &item.def_id()) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(lctx.current_hir_id_owner, item.def_id());
65
66        let info = lctx.make_owner_info(item);
67
68        hir::MaybeOwner::Owner(lctx.arena.alloc(info))
69    }
70
71    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_crate",
                                    "rustc_ast_lowering::item", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(71u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::MaybeOwner<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.with_lctx(CRATE_NODE_ID,
                |lctx|
                    {
                        if true {
                            {
                                match (&lctx.current_hir_id_owner, &CRATE_OWNER_ID) {
                                    (left_val, right_val) => {
                                        if !(*left_val == *right_val) {
                                            let kind = ::core::panicking::AssertKind::Eq;
                                            ::core::panicking::assert_failed(kind, &*left_val,
                                                &*right_val, ::core::option::Option::None);
                                        }
                                    }
                                }
                            };
                        };
                        let module = lctx.lower_mod(&c.items, &c.spans);
                        lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs,
                            c.spans.inner_span, Target::Crate);
                        hir::OwnerNode::Crate(module)
                    })
        }
    }
}#[instrument(level = "debug", skip(self, c))]
72    pub(super) fn lower_crate(&mut self, c: &Crate) -> hir::MaybeOwner<'hir> {
73        self.with_lctx(CRATE_NODE_ID, |lctx| {
74            debug_assert_eq!(lctx.current_hir_id_owner, CRATE_OWNER_ID);
75            let module = lctx.lower_mod(&c.items, &c.spans);
76            lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, c.spans.inner_span, Target::Crate);
77            hir::OwnerNode::Crate(module)
78        })
79    }
80
81    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_item",
                                    "rustc_ast_lowering::item", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(81u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::MaybeOwner<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.with_lctx(item.id,
                |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
        }
    }
}#[instrument(level = "debug", skip(self))]
82    pub(super) fn lower_item(&mut self, item: &Item) -> hir::MaybeOwner<'hir> {
83        self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
84    }
85
86    pub(super) fn lower_trait_item(&mut self, item: &AssocItem) -> hir::MaybeOwner<'hir> {
87        self.with_lctx(item.id, |lctx| hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)))
88    }
89
90    pub(super) fn lower_impl_item(&mut self, item: &AssocItem) -> hir::MaybeOwner<'hir> {
91        self.with_lctx(item.id, |lctx| hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)))
92    }
93
94    pub(super) fn lower_foreign_item(&mut self, item: &ForeignItem) -> hir::MaybeOwner<'hir> {
95        self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
96    }
97}
98
99impl<'hir> LoweringContext<'_, 'hir> {
100    pub(super) fn lower_mod(
101        &mut self,
102        items: &[Box<Item>],
103        spans: &ModSpans,
104    ) -> &'hir hir::Mod<'hir> {
105        self.arena.alloc(hir::Mod {
106            spans: hir::ModSpans {
107                inner_span: self.lower_span(spans.inner_span),
108                inject_use_span: self.lower_span(spans.inject_use_span),
109            },
110            item_ids: self.arena.alloc_from_iter(items.iter().map(|x| self.lower_item_ref(x))),
111        })
112    }
113
114    pub(super) fn lower_item_ref(&mut self, i: &Item) -> hir::ItemId {
115        hir::ItemId { owner_id: self.owner_id(i.id) }
116    }
117
118    fn lower_eii_decl(
119        &mut self,
120        id: NodeId,
121        name: Ident,
122        EiiDecl { foreign_item, impl_unsafe }: &EiiDecl,
123    ) -> Option<hir::attrs::EiiDecl> {
124        self.lower_path_simple_eii(id, foreign_item).map(|did| hir::attrs::EiiDecl {
125            foreign_item: did,
126            impl_unsafe: *impl_unsafe,
127            name,
128        })
129    }
130
131    fn lower_eii_impl(
132        &mut self,
133        EiiImpl {
134            node_id,
135            eii_macro_path,
136            impl_safety,
137            span,
138            inner_span,
139            is_default,
140            known_eii_macro_resolution,
141        }: &EiiImpl,
142    ) -> hir::attrs::EiiImpl {
143        let resolution = if let Some(target) = known_eii_macro_resolution
144            && let Some(foreign_item_did) = self.lower_path_simple_eii(*node_id, target)
145        {
146            EiiImplResolution::Known(foreign_item_did)
147        } else if let Some(macro_did) = self.lower_path_simple_eii(*node_id, eii_macro_path) {
148            EiiImplResolution::Macro(macro_did)
149        } else {
150            EiiImplResolution::Error(
151                self.dcx().span_delayed_bug(*span, "eii never resolved without errors given"),
152            )
153        };
154
155        hir::attrs::EiiImpl {
156            span: self.lower_span(*span),
157            inner_span: self.lower_span(*inner_span),
158            impl_marked_unsafe: self.lower_safety(*impl_safety, hir::Safety::Safe).is_unsafe(),
159            is_default: *is_default,
160            resolution,
161        }
162    }
163
164    fn generate_extra_attrs_for_item_kind(
165        &mut self,
166        id: NodeId,
167        i: &ItemKind,
168    ) -> Vec<hir::Attribute> {
169        match i {
170            ItemKind::Fn(Fn { eii_impls, .. }) | ItemKind::Static(StaticItem { eii_impls, .. })
171                if eii_impls.is_empty() =>
172            {
173                Vec::new()
174            }
175            ItemKind::Fn(Fn { eii_impls, .. }) | ItemKind::Static(StaticItem { eii_impls, .. }) => {
176                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [hir::Attribute::Parsed(AttributeKind::EiiImpls(eii_impls.iter().map(|i|
                                    self.lower_eii_impl(i)).collect()))]))vec![hir::Attribute::Parsed(AttributeKind::EiiImpls(
177                    eii_impls.iter().map(|i| self.lower_eii_impl(i)).collect(),
178                ))]
179            }
180            ItemKind::MacroDef(name, MacroDef { eii_declaration: Some(target), .. }) => self
181                .lower_eii_decl(id, *name, target)
182                .map(|decl| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [hir::Attribute::Parsed(AttributeKind::EiiDeclaration(decl))]))vec![hir::Attribute::Parsed(AttributeKind::EiiDeclaration(decl))])
183                .unwrap_or_default(),
184
185            ItemKind::ExternCrate(..)
186            | ItemKind::Use(..)
187            | ItemKind::Const(..)
188            | ItemKind::ConstBlock(..)
189            | ItemKind::Mod(..)
190            | ItemKind::ForeignMod(..)
191            | ItemKind::GlobalAsm(..)
192            | ItemKind::TyAlias(..)
193            | ItemKind::Enum(..)
194            | ItemKind::Struct(..)
195            | ItemKind::Union(..)
196            | ItemKind::Trait(..)
197            | ItemKind::TraitAlias(..)
198            | ItemKind::Impl(..)
199            | ItemKind::MacCall(..)
200            | ItemKind::MacroDef(..)
201            | ItemKind::Delegation(..)
202            | ItemKind::DelegationMac(..) => Vec::new(),
203        }
204    }
205
206    fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
207        let owner_id = self.current_hir_id_owner;
208        let hir_id: HirId = owner_id.into();
209        let vis_span = self.lower_span(i.vis.span);
210
211        let extra_hir_attributes = self.generate_extra_attrs_for_item_kind(i.id, &i.kind);
212        let attrs = self.lower_attrs_with_extra(
213            hir_id,
214            &i.attrs,
215            i.span,
216            Target::from_ast_item(i),
217            &extra_hir_attributes,
218        );
219
220        let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind);
221        let item = hir::Item {
222            owner_id,
223            kind,
224            vis_span,
225            span: self.lower_span(i.span),
226            eii: {
    {
            '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(EiiImpls(..) |
                            EiiDeclaration(..)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, EiiImpls(..) | EiiDeclaration(..)),
227        };
228        self.arena.alloc(item)
229    }
230
231    fn lower_item_kind(
232        &mut self,
233        span: Span,
234        id: NodeId,
235        hir_id: hir::HirId,
236        attrs: &'hir [hir::Attribute],
237        vis_span: Span,
238        i: &ItemKind,
239    ) -> hir::ItemKind<'hir> {
240        match i {
241            ItemKind::ExternCrate(orig_name, ident) => {
242                let ident = self.lower_ident(*ident);
243                hir::ItemKind::ExternCrate(*orig_name, ident)
244            }
245            ItemKind::Use(use_tree) => {
246                // Start with an empty prefix.
247                let prefix =
248                    Path { segments: ThinVec::new(), span: use_tree.prefix.span.shrink_to_lo() };
249
250                self.lower_use_tree(use_tree, &prefix, id, vis_span, attrs)
251            }
252            ItemKind::Static(ast::StaticItem {
253                ident,
254                ty,
255                safety: _,
256                mutability: m,
257                expr: e,
258                define_opaque,
259                eii_impls: _,
260            }) => {
261                let ident = self.lower_ident(*ident);
262                let ty = self
263                    .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
264                let body_id = self.lower_const_body(span, e.as_deref());
265                self.lower_define_opaque(hir_id, define_opaque);
266                hir::ItemKind::Static(*m, ident, ty, body_id)
267            }
268            ItemKind::Const(ConstItem {
269                defaultness: _,
270                ident,
271                generics,
272                ty,
273                body,
274                kind,
275                define_opaque,
276            }) => {
277                let ident = self.lower_ident(*ident);
278                let (generics, (ty, rhs)) = self.lower_generics(
279                    generics,
280                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
281                    |this| {
282                        let ty = this.lower_ty_alloc(
283                            ty,
284                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
285                        );
286                        let rhs = this.lower_const_item_rhs(body, *kind, span);
287                        (ty, rhs)
288                    },
289                );
290                self.lower_define_opaque(hir_id, &define_opaque);
291                hir::ItemKind::Const(ident, generics, ty, rhs)
292            }
293            ItemKind::ConstBlock(ConstBlockItem { span, id, block }) => hir::ItemKind::Const(
294                self.lower_ident(ConstBlockItem::IDENT),
295                hir::Generics::empty(),
296                self.arena.alloc(self.ty_tup(DUMMY_SP, &[])),
297                hir::ConstItemRhs::Body({
298                    let body = hir::Expr {
299                        hir_id: self.lower_node_id(*id),
300                        kind: hir::ExprKind::Block(self.lower_block(block, false), None),
301                        span: self.lower_span(*span),
302                    };
303                    self.record_body(&[], body)
304                }),
305            ),
306            ItemKind::Fn(Fn {
307                sig: FnSig { decl, header, span: fn_sig_span },
308                ident,
309                generics,
310                body,
311                contract,
312                define_opaque,
313                ..
314            }) => {
315                self.with_new_scopes(*fn_sig_span, |this| {
316                    // Note: we don't need to change the return type from `T` to
317                    // `impl Future<Output = T>` here because lower_body
318                    // only cares about the input argument patterns in the function
319                    // declaration (decl), not the return types.
320                    let coroutine_kind = header.coroutine_kind;
321                    let body_id = this.lower_maybe_coroutine_body(
322                        *fn_sig_span,
323                        span,
324                        hir_id,
325                        decl,
326                        coroutine_kind,
327                        body.as_deref(),
328                        attrs,
329                        contract.as_deref(),
330                    );
331
332                    let itctx = ImplTraitContext::Universal;
333                    let (generics, decl) = this.lower_generics(generics, itctx, |this| {
334                        this.lower_fn_decl(decl, id, *fn_sig_span, FnDeclKind::Fn, coroutine_kind)
335                    });
336                    let sig = hir::FnSig {
337                        decl,
338                        header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
339                        span: this.lower_span(*fn_sig_span),
340                    };
341                    this.lower_define_opaque(hir_id, define_opaque);
342                    let ident = this.lower_ident(*ident);
343                    hir::ItemKind::Fn {
344                        ident,
345                        sig,
346                        generics,
347                        body: body_id,
348                        has_body: body.is_some(),
349                    }
350                })
351            }
352            ItemKind::Mod(_, ident, mod_kind) => {
353                let ident = self.lower_ident(*ident);
354                match mod_kind {
355                    ModKind::Loaded(items, _, spans) => {
356                        hir::ItemKind::Mod(ident, self.lower_mod(items, spans))
357                    }
358                    ModKind::Unloaded => {
    ::core::panicking::panic_fmt(format_args!("`mod` items should have been loaded by now"));
}panic!("`mod` items should have been loaded by now"),
359                }
360            }
361            ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
362                abi: fm.abi.map_or(ExternAbi::FALLBACK, |abi| self.lower_abi(abi)),
363                items: self
364                    .arena
365                    .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
366            },
367            ItemKind::GlobalAsm(asm) => {
368                let asm = self.lower_inline_asm(span, asm);
369                let fake_body =
370                    self.lower_body(|this| (&[], this.expr(span, hir::ExprKind::InlineAsm(asm))));
371                hir::ItemKind::GlobalAsm { asm, fake_body }
372            }
373            ItemKind::TyAlias(TyAlias { ident, generics, after_where_clause, ty, .. }) => {
374                // We lower
375                //
376                // type Foo = impl Trait
377                //
378                // to
379                //
380                // type Foo = Foo1
381                // opaque type Foo1: Trait
382                let ident = self.lower_ident(*ident);
383                let mut generics = generics.clone();
384                add_ty_alias_where_clause(&mut generics, after_where_clause, true);
385                let (generics, ty) = self.lower_generics(
386                    &generics,
387                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
388                    |this| match ty {
389                        None => {
390                            let guar = this.dcx().span_delayed_bug(
391                                span,
392                                "expected to lower type alias type, but it was missing",
393                            );
394                            this.arena.alloc(this.ty(span, hir::TyKind::Err(guar)))
395                        }
396                        Some(ty) => this.lower_ty_alloc(
397                            ty,
398                            ImplTraitContext::OpaqueTy {
399                                origin: hir::OpaqueTyOrigin::TyAlias {
400                                    parent: this.owner.def_id,
401                                    in_assoc_ty: false,
402                                },
403                            },
404                        ),
405                    },
406                );
407                hir::ItemKind::TyAlias(ident, generics, ty)
408            }
409            ItemKind::Enum(ident, generics, enum_definition) => {
410                let ident = self.lower_ident(*ident);
411                let (generics, variants) = self.lower_generics(
412                    generics,
413                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
414                    |this| {
415                        this.arena.alloc_from_iter(
416                            enum_definition.variants.iter().map(|x| this.lower_variant(i, x)),
417                        )
418                    },
419                );
420                hir::ItemKind::Enum(ident, generics, hir::EnumDef { variants })
421            }
422            ItemKind::Struct(ident, generics, struct_def) => {
423                let ident = self.lower_ident(*ident);
424                let (generics, struct_def) = self.lower_generics(
425                    generics,
426                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
427                    |this| this.lower_variant_data(hir_id, i, struct_def),
428                );
429                hir::ItemKind::Struct(ident, generics, struct_def)
430            }
431            ItemKind::Union(ident, generics, vdata) => {
432                let ident = self.lower_ident(*ident);
433                let (generics, vdata) = self.lower_generics(
434                    generics,
435                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
436                    |this| this.lower_variant_data(hir_id, i, vdata),
437                );
438                hir::ItemKind::Union(ident, generics, vdata)
439            }
440            ItemKind::Impl(Impl {
441                generics: ast_generics,
442                of_trait,
443                self_ty: ty,
444                items: impl_items,
445                constness,
446            }) => {
447                // Lower the "impl header" first. This ordering is important
448                // for in-band lifetimes! Consider `'a` here:
449                //
450                //     impl Foo<'a> for u32 {
451                //         fn method(&'a self) { .. }
452                //     }
453                //
454                // Because we start by lowering the `Foo<'a> for u32`
455                // part, we will add `'a` to the list of generics on
456                // the impl. When we then encounter it later in the
457                // method, it will not be considered an in-band
458                // lifetime to be added, but rather a reference to a
459                // parent lifetime.
460                let itctx = ImplTraitContext::Universal;
461                let (generics, (of_trait, lowered_ty)) =
462                    self.lower_generics(ast_generics, itctx, |this| {
463                        let of_trait = of_trait
464                            .as_deref()
465                            .map(|of_trait| this.lower_trait_impl_header(of_trait));
466
467                        let lowered_ty = this.lower_ty_alloc(
468                            ty,
469                            ImplTraitContext::Disallowed(ImplTraitPosition::ImplSelf),
470                        );
471
472                        (of_trait, lowered_ty)
473                    });
474
475                let new_impl_items = self
476                    .arena
477                    .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
478
479                let constness = self.lower_constness(attrs, *constness);
480
481                hir::ItemKind::Impl(hir::Impl {
482                    generics,
483                    of_trait,
484                    self_ty: lowered_ty,
485                    items: new_impl_items,
486                    constness,
487                })
488            }
489            ItemKind::Trait(Trait {
490                impl_restriction,
491                constness,
492                is_auto,
493                safety,
494                ident,
495                generics,
496                bounds,
497                items,
498            }) => {
499                let constness = self.lower_constness(attrs, *constness);
500                let impl_restriction = self.lower_impl_restriction(impl_restriction);
501                let ident = self.lower_ident(*ident);
502                let (generics, (safety, items, bounds)) = self.lower_generics(
503                    generics,
504                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
505                    |this| {
506                        let bounds = this.lower_param_bounds(
507                            bounds,
508                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::SuperTrait),
509                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
510                        );
511                        let items = this.arena.alloc_from_iter(
512                            items.iter().map(|item| this.lower_trait_item_ref(item)),
513                        );
514                        let safety = this.lower_safety(*safety, hir::Safety::Safe);
515                        (safety, items, bounds)
516                    },
517                );
518                hir::ItemKind::Trait {
519                    impl_restriction,
520                    constness,
521                    is_auto: *is_auto,
522                    safety,
523                    ident,
524                    generics,
525                    bounds,
526                    items,
527                }
528            }
529            ItemKind::TraitAlias(TraitAlias { constness, ident, generics, bounds }) => {
530                let constness = self.lower_constness(attrs, *constness);
531                let ident = self.lower_ident(*ident);
532                let (generics, bounds) = self.lower_generics(
533                    generics,
534                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
535                    |this| {
536                        this.lower_param_bounds(
537                            bounds,
538                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitAlias),
539                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
540                        )
541                    },
542                );
543                hir::ItemKind::TraitAlias(constness, ident, generics, bounds)
544            }
545            ItemKind::MacroDef(ident, MacroDef { body, macro_rules, eii_declaration: _ }) => {
546                let ident = self.lower_ident(*ident);
547                let body = Box::new(self.lower_delim_args(body));
548                let def_id = self.owner.def_id;
549                let def_kind = self.tcx.def_kind(def_id);
550                let DefKind::Macro(macro_kinds) = def_kind else {
551                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("expected DefKind::Macro for macro item, found {0}",
                def_kind.descr(def_id.to_def_id()))));
};unreachable!(
552                        "expected DefKind::Macro for macro item, found {}",
553                        def_kind.descr(def_id.to_def_id())
554                    );
555                };
556                let macro_def = self.arena.alloc(ast::MacroDef {
557                    body,
558                    macro_rules: *macro_rules,
559                    eii_declaration: None,
560                });
561                hir::ItemKind::Macro(ident, macro_def, macro_kinds)
562            }
563            ItemKind::Delegation(delegation) => {
564                let delegation_results = self.lower_delegation(delegation);
565                hir::ItemKind::Fn {
566                    sig: delegation_results.sig,
567                    ident: delegation_results.ident,
568                    generics: delegation_results.generics,
569                    body: delegation_results.body_id,
570                    has_body: true,
571                }
572            }
573            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
574                {
    ::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
575            }
576        }
577    }
578
579    fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
580        let res = self.get_partial_res(id)?;
581        let Some(did) = res.expect_full_res().opt_def_id() else {
582            self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
583            return None;
584        };
585
586        Some(did)
587    }
588
589    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_use_tree",
                                    "rustc_ast_lowering::item", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(589u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("tree")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("tree");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("prefix")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("prefix");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("vis_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("vis_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("attrs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("attrs");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tree)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&prefix)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&attrs)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::ItemKind<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let path = &tree.prefix;
            let segments =
                prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
            match tree.kind {
                UseTreeKind::Simple(rename) => {
                    let mut ident = tree.ident();
                    let mut path = Path { segments, span: path.span };
                    if path.segments.len() > 1 &&
                            path.segments.last().unwrap().ident.name == kw::SelfLower {
                        let _ = path.segments.pop();
                        if rename.is_none() {
                            ident = path.segments.last().unwrap().ident;
                        }
                    }
                    let res = self.lower_import_res(id, path.span);
                    let path =
                        self.lower_use_path(res, &path, ParamMode::Explicit);
                    let ident = self.lower_ident(ident);
                    hir::ItemKind::Use(path, hir::UseKind::Single(ident))
                }
                UseTreeKind::Glob(_) => {
                    let res = self.expect_full_res(id);
                    let res = self.lower_res(res);
                    let res =
                        match res {
                            Res::Def(DefKind::Mod | DefKind::Trait, _) => {
                                PerNS { type_ns: Some(res), value_ns: None, macro_ns: None }
                            }
                            Res::Def(DefKind::Enum, _) => {
                                PerNS { type_ns: None, value_ns: Some(res), macro_ns: None }
                            }
                            Res::Err => {
                                let err = Some(Res::Err);
                                PerNS { type_ns: err, value_ns: err, macro_ns: err }
                            }
                            _ =>
                                ::rustc_middle::util::bug::span_bug_fmt(path.span,
                                    format_args!("bad glob res {0:?}", res)),
                        };
                    let path = Path { segments, span: path.span };
                    let path =
                        self.lower_use_path(res, &path, ParamMode::Explicit);
                    hir::ItemKind::Use(path, hir::UseKind::Glob)
                }
                UseTreeKind::Nested { items: ref trees, .. } => {
                    let span = prefix.span.to(path.span);
                    let prefix = Path { segments, span };
                    for &(ref use_tree, id) in trees {
                        let owner_id = self.owner_id(id);
                        self.with_hir_id_owner(id,
                            |this|
                                {
                                    let kind =
                                        this.lower_use_tree(use_tree, &prefix, id, vis_span, attrs);
                                    if !attrs.is_empty() {
                                        this.attrs.insert(hir::ItemLocalId::ZERO, attrs);
                                    }
                                    let item =
                                        hir::Item {
                                            owner_id,
                                            kind,
                                            vis_span,
                                            span: this.lower_span(use_tree.span()),
                                            eii: {
                                                {
                                                        '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(EiiImpls(..) |
                                                                        EiiDeclaration(..)) => {
                                                                        break 'done Some(());
                                                                    }
                                                                    rustc_hir::Attribute::Unparsed(..) =>
                                                                        {}
                                                                        #[deny(unreachable_patterns)]
                                                                        _ => {}
                                                                }
                                                            }
                                                            None
                                                        }
                                                    }.is_some()
                                            },
                                        };
                                    hir::OwnerNode::Item(this.arena.alloc(item))
                                });
                    }
                    let path =
                        if trees.is_empty() &&
                                !(prefix.segments.is_empty() ||
                                            prefix.segments.len() == 1 &&
                                                prefix.segments[0].ident.name == kw::PathRoot) {
                            let res = self.lower_import_res(id, span);
                            self.lower_use_path(res, &prefix, ParamMode::Explicit)
                        } else {
                            let span = self.lower_span(span);
                            self.arena.alloc(hir::UsePath {
                                    res: PerNS::default(),
                                    segments: &[],
                                    span,
                                })
                        };
                    hir::ItemKind::Use(path, hir::UseKind::ListStem)
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
590    fn lower_use_tree(
591        &mut self,
592        tree: &UseTree,
593        prefix: &Path,
594        id: NodeId,
595        vis_span: Span,
596        attrs: &'hir [hir::Attribute],
597    ) -> hir::ItemKind<'hir> {
598        let path = &tree.prefix;
599        let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
600
601        match tree.kind {
602            UseTreeKind::Simple(rename) => {
603                let mut ident = tree.ident();
604
605                // First, apply the prefix to the path.
606                let mut path = Path { segments, span: path.span };
607
608                // Correctly resolve `self` imports.
609                if path.segments.len() > 1
610                    && path.segments.last().unwrap().ident.name == kw::SelfLower
611                {
612                    let _ = path.segments.pop();
613                    if rename.is_none() {
614                        ident = path.segments.last().unwrap().ident;
615                    }
616                }
617
618                let res = self.lower_import_res(id, path.span);
619                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
620                let ident = self.lower_ident(ident);
621                hir::ItemKind::Use(path, hir::UseKind::Single(ident))
622            }
623            UseTreeKind::Glob(_) => {
624                let res = self.expect_full_res(id);
625                let res = self.lower_res(res);
626                // Put the result in the appropriate namespace.
627                let res = match res {
628                    Res::Def(DefKind::Mod | DefKind::Trait, _) => {
629                        PerNS { type_ns: Some(res), value_ns: None, macro_ns: None }
630                    }
631                    Res::Def(DefKind::Enum, _) => {
632                        PerNS { type_ns: None, value_ns: Some(res), macro_ns: None }
633                    }
634                    Res::Err => {
635                        // Propagate the error to all namespaces, just to be sure.
636                        let err = Some(Res::Err);
637                        PerNS { type_ns: err, value_ns: err, macro_ns: err }
638                    }
639                    _ => span_bug!(path.span, "bad glob res {:?}", res),
640                };
641                let path = Path { segments, span: path.span };
642                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
643                hir::ItemKind::Use(path, hir::UseKind::Glob)
644            }
645            UseTreeKind::Nested { items: ref trees, .. } => {
646                // Nested imports are desugared into simple imports.
647                // So, if we start with
648                //
649                // ```
650                // pub(x) use foo::{a, b};
651                // ```
652                //
653                // we will create three items:
654                //
655                // ```
656                // pub(x) use foo::a;
657                // pub(x) use foo::b;
658                // pub(x) use foo::{}; // <-- this is called the `ListStem`
659                // ```
660                //
661                // The first two are produced by recursively invoking
662                // `lower_use_tree` (and indeed there may be things
663                // like `use foo::{a::{b, c}}` and so forth). They
664                // wind up being directly added to
665                // `self.items`. However, the structure of this
666                // function also requires us to return one item, and
667                // for that we return the `{}` import (called the
668                // `ListStem`).
669
670                let span = prefix.span.to(path.span);
671                let prefix = Path { segments, span };
672
673                // Add all the nested `PathListItem`s to the HIR.
674                for &(ref use_tree, id) in trees {
675                    let owner_id = self.owner_id(id);
676
677                    // Each `use` import is an item and thus are owners of the
678                    // names in the path. Up to this point the nested import is
679                    // the current owner, since we want each desugared import to
680                    // own its own names, we have to adjust the owner before
681                    // lowering the rest of the import.
682                    self.with_hir_id_owner(id, |this| {
683                        // `prefix` is lowered multiple times, but in different HIR owners.
684                        // So each segment gets renewed `HirId` with the same
685                        // `ItemLocalId` and the new owner. (See `lower_node_id`)
686                        let kind = this.lower_use_tree(use_tree, &prefix, id, vis_span, attrs);
687                        if !attrs.is_empty() {
688                            this.attrs.insert(hir::ItemLocalId::ZERO, attrs);
689                        }
690
691                        let item = hir::Item {
692                            owner_id,
693                            kind,
694                            vis_span,
695                            span: this.lower_span(use_tree.span()),
696                            eii: find_attr!(attrs, EiiImpls(..) | EiiDeclaration(..)),
697                        };
698                        hir::OwnerNode::Item(this.arena.alloc(item))
699                    });
700                }
701
702                // Condition should match `build_reduced_graph_for_use_tree`.
703                let path = if trees.is_empty()
704                    && !(prefix.segments.is_empty()
705                        || prefix.segments.len() == 1
706                            && prefix.segments[0].ident.name == kw::PathRoot)
707                {
708                    // For empty lists we need to lower the prefix so it is checked for things
709                    // like stability later.
710                    let res = self.lower_import_res(id, span);
711                    self.lower_use_path(res, &prefix, ParamMode::Explicit)
712                } else {
713                    // For non-empty lists we can just drop all the data, the prefix is already
714                    // present in HIR as a part of nested imports.
715                    let span = self.lower_span(span);
716                    self.arena.alloc(hir::UsePath { res: PerNS::default(), segments: &[], span })
717                };
718                hir::ItemKind::Use(path, hir::UseKind::ListStem)
719            }
720        }
721    }
722
723    fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
724        let owner_id = self.current_hir_id_owner;
725        let hir_id: HirId = owner_id.into();
726        let attrs =
727            self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_foreign_item_kind(&i.kind));
728        let (ident, kind) = match &i.kind {
729            ForeignItemKind::Fn(Fn { sig, ident, generics, define_opaque, .. }) => {
730                let fdec = &sig.decl;
731                let itctx = ImplTraitContext::Universal;
732                let (generics, (decl, fn_args)) = self.lower_generics(generics, itctx, |this| {
733                    (
734                        // Disallow `impl Trait` in foreign items.
735                        this.lower_fn_decl(fdec, i.id, sig.span, FnDeclKind::ExternFn, None),
736                        this.lower_fn_params_to_idents(fdec),
737                    )
738                });
739
740                // Unmarked safety in unsafe block defaults to unsafe.
741                let header = self.lower_fn_header(sig.header, hir::Safety::Unsafe, attrs);
742
743                if define_opaque.is_some() {
744                    self.dcx().span_err(i.span, "foreign functions cannot define opaque types");
745                }
746
747                (
748                    ident,
749                    hir::ForeignItemKind::Fn(
750                        hir::FnSig { header, decl, span: self.lower_span(sig.span) },
751                        fn_args,
752                        generics,
753                    ),
754                )
755            }
756            ForeignItemKind::Static(StaticItem {
757                ident,
758                ty,
759                mutability,
760                expr: _,
761                safety,
762                define_opaque,
763                eii_impls: _,
764            }) => {
765                let ty = self
766                    .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
767                let safety = self.lower_safety(*safety, hir::Safety::Unsafe);
768                if define_opaque.is_some() {
769                    self.dcx().span_err(i.span, "foreign statics cannot define opaque types");
770                }
771                (ident, hir::ForeignItemKind::Static(ty, *mutability, safety))
772            }
773            ForeignItemKind::TyAlias(TyAlias { ident, .. }) => (ident, hir::ForeignItemKind::Type),
774            ForeignItemKind::MacCall(_) => { ::core::panicking::panic_fmt(format_args!("macro shouldn\'t exist here")); }panic!("macro shouldn't exist here"),
775        };
776
777        let item = hir::ForeignItem {
778            owner_id,
779            ident: self.lower_ident(*ident),
780            kind,
781            vis_span: self.lower_span(i.vis.span),
782            span: self.lower_span(i.span),
783        };
784        self.arena.alloc(item)
785    }
786
787    fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemId {
788        hir::ForeignItemId { owner_id: self.owner_id(i.id) }
789    }
790
791    fn lower_variant(&mut self, item_kind: &ItemKind, v: &Variant) -> hir::Variant<'hir> {
792        if v.ident.name == kw::Underscore && self.tcx.features().unnamed_enum_variants() {
793            // FIXME(#156628): lower unnamed enum variants to HIR.
794            self.dcx()
795                .struct_span_fatal(v.span, "unnamed enum variants are not yet implemented")
796                .emit()
797        }
798        let hir_id = self.lower_node_id(v.id);
799        self.lower_attrs(hir_id, &v.attrs, v.span, Target::Variant);
800        hir::Variant {
801            hir_id,
802            def_id: self.local_def_id(v.id),
803            data: self.lower_variant_data(hir_id, item_kind, &v.data),
804            disr_expr: v
805                .disr_expr
806                .as_ref()
807                .map(|e| self.lower_anon_const_to_anon_const(e, e.value.span)),
808            ident: self.lower_ident(v.ident),
809            span: self.lower_span(v.span),
810        }
811    }
812
813    fn lower_variant_data(
814        &mut self,
815        parent_id: hir::HirId,
816        item_kind: &ItemKind,
817        vdata: &VariantData,
818    ) -> hir::VariantData<'hir> {
819        match vdata {
820            VariantData::Struct { fields, recovered } => {
821                let fields = self
822                    .arena
823                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
824
825                if let ItemKind::Union(..) = item_kind {
826                    for field in &fields[..] {
827                        if let Some(default) = field.default {
828                            // Unions cannot derive `Default`, and it's not clear how to use default
829                            // field values of unions if that was supported. Therefore, blanket reject
830                            // trying to use field values with unions.
831                            if self.tcx.features().default_field_values() {
832                                self.dcx().emit_err(UnionWithDefault { span: default.span });
833                            } else {
834                                let _ = self.dcx().span_delayed_bug(
835                                default.span,
836                                "expected union default field values feature gate error but none \
837                                was produced",
838                            );
839                            }
840                        }
841                    }
842                }
843
844                hir::VariantData::Struct { fields, recovered: *recovered }
845            }
846            VariantData::Tuple(fields, id) => {
847                let ctor_id = self.lower_node_id(*id);
848                self.alias_attrs(ctor_id, parent_id);
849                let fields = self
850                    .arena
851                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
852                for field in &fields[..] {
853                    if let Some(default) = field.default {
854                        // Default values in tuple struct and tuple variants are not allowed by the
855                        // RFC due to concerns about the syntax, both in the item definition and the
856                        // expression. We could in the future allow `struct S(i32 = 0);` and force
857                        // users to construct the value with `let _ = S { .. };`.
858                        if self.tcx.features().default_field_values() {
859                            self.dcx().emit_err(TupleStructWithDefault { span: default.span });
860                        } else {
861                            let _ = self.dcx().span_delayed_bug(
862                                default.span,
863                                "expected `default values on `struct` fields aren't supported` \
864                                 feature-gate error but none was produced",
865                            );
866                        }
867                    }
868                }
869                hir::VariantData::Tuple(fields, ctor_id, self.local_def_id(*id))
870            }
871            VariantData::Unit(id) => {
872                let ctor_id = self.lower_node_id(*id);
873                self.alias_attrs(ctor_id, parent_id);
874                hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
875            }
876        }
877    }
878
879    pub(super) fn lower_field_def(
880        &mut self,
881        (index, f): (usize, &FieldDef),
882    ) -> hir::FieldDef<'hir> {
883        let ty =
884            self.lower_ty_alloc(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy));
885        let hir_id = self.lower_node_id(f.id);
886        self.lower_attrs(hir_id, &f.attrs, f.span, Target::Field);
887        hir::FieldDef {
888            span: self.lower_span(f.span),
889            hir_id,
890            def_id: self.local_def_id(f.id),
891            ident: match f.ident {
892                Some(ident) => self.lower_ident(ident),
893                // FIXME(jseyfried): positional field hygiene.
894                None => Ident::new(sym::integer(index), self.lower_span(f.span)),
895            },
896            vis_span: self.lower_span(f.vis.span),
897            mut_restriction: self.lower_mut_restriction(&f.mut_restriction),
898            default: f
899                .default
900                .as_ref()
901                .map(|v| self.lower_anon_const_to_anon_const(v, v.value.span)),
902            ty,
903            safety: self.lower_safety(f.safety, hir::Safety::Safe),
904        }
905    }
906
907    fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
908        let trait_item_def_id = self.current_hir_id_owner;
909        let hir_id: HirId = trait_item_def_id.into();
910        let attrs = self.lower_attrs(
911            hir_id,
912            &i.attrs,
913            i.span,
914            Target::from_assoc_item_kind(&i.kind, AssocCtxt::Trait),
915        );
916
917        let (ident, generics, kind, has_value) = match &i.kind {
918            AssocItemKind::Const(ConstItem {
919                ident,
920                generics,
921                ty,
922                body,
923                kind,
924                define_opaque,
925                ..
926            }) => {
927                let (generics, kind) = self.lower_generics(
928                    generics,
929                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
930                    |this| {
931                        let ty = this.lower_ty_alloc(
932                            ty,
933                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
934                        );
935                        // Trait associated consts don't need an expression/body.
936                        let rhs = if body.is_some() {
937                            Some(this.lower_const_item_rhs(body, *kind, i.span))
938                        } else {
939                            None
940                        };
941                        hir::TraitItemKind::Const(ty, rhs)
942                    },
943                );
944
945                if define_opaque.is_some() {
946                    if body.is_some() {
947                        self.lower_define_opaque(hir_id, &define_opaque);
948                    } else {
949                        self.dcx().span_err(
950                            i.span,
951                            "only trait consts with default bodies can define opaque types",
952                        );
953                    }
954                }
955
956                (*ident, generics, kind, body.is_some())
957            }
958            AssocItemKind::Fn(Fn { sig, ident, generics, body: None, define_opaque, .. }) => {
959                // FIXME(contracts): Deny contract here since it won't apply to
960                // any impl method or callees.
961                let idents = self.lower_fn_params_to_idents(&sig.decl);
962                let (generics, sig) = self.lower_method_sig(
963                    generics,
964                    sig,
965                    i.id,
966                    FnDeclKind::Trait,
967                    sig.header.coroutine_kind,
968                    attrs,
969                );
970                if define_opaque.is_some() {
971                    self.dcx().span_err(
972                        i.span,
973                        "only trait methods with default bodies can define opaque types",
974                    );
975                }
976                (
977                    *ident,
978                    generics,
979                    hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(idents)),
980                    false,
981                )
982            }
983            AssocItemKind::Fn(Fn {
984                sig,
985                ident,
986                generics,
987                body: Some(body),
988                contract,
989                define_opaque,
990                ..
991            }) => {
992                let body_id = self.lower_maybe_coroutine_body(
993                    sig.span,
994                    i.span,
995                    hir_id,
996                    &sig.decl,
997                    sig.header.coroutine_kind,
998                    Some(body),
999                    attrs,
1000                    contract.as_deref(),
1001                );
1002                let (generics, sig) = self.lower_method_sig(
1003                    generics,
1004                    sig,
1005                    i.id,
1006                    FnDeclKind::Trait,
1007                    sig.header.coroutine_kind,
1008                    attrs,
1009                );
1010                self.lower_define_opaque(hir_id, &define_opaque);
1011                (
1012                    *ident,
1013                    generics,
1014                    hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)),
1015                    true,
1016                )
1017            }
1018            AssocItemKind::Type(TyAlias {
1019                ident,
1020                generics,
1021                after_where_clause,
1022                bounds,
1023                ty,
1024                ..
1025            }) => {
1026                let mut generics = generics.clone();
1027                add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1028                let (generics, kind) = self.lower_generics(
1029                    &generics,
1030                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1031                    |this| {
1032                        let ty = ty.as_ref().map(|x| {
1033                            this.lower_ty_alloc(
1034                                x,
1035                                ImplTraitContext::Disallowed(ImplTraitPosition::AssocTy),
1036                            )
1037                        });
1038                        hir::TraitItemKind::Type(
1039                            this.lower_param_bounds(
1040                                bounds,
1041                                RelaxedBoundPolicy::Allowed(&mut Default::default()),
1042                                ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1043                            ),
1044                            ty,
1045                        )
1046                    },
1047                );
1048                (*ident, generics, kind, ty.is_some())
1049            }
1050            AssocItemKind::Delegation(delegation) => {
1051                let delegation_results = self.lower_delegation(delegation);
1052                let item_kind = hir::TraitItemKind::Fn(
1053                    delegation_results.sig,
1054                    hir::TraitFn::Provided(delegation_results.body_id),
1055                );
1056                (delegation.ident, delegation_results.generics, item_kind, true)
1057            }
1058            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1059                {
    ::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
1060            }
1061        };
1062
1063        let defaultness = match i.kind.defaultness() {
1064            // We do not yet support `final` on trait associated items other than functions.
1065            // Even though we reject `final` on non-functions during AST validation, we still
1066            // need to stop propagating it here because later compiler passes do not expect
1067            // and cannot handle such items.
1068            Defaultness::Final(..) if !#[allow(non_exhaustive_omitted_patterns)] match i.kind {
    AssocItemKind::Fn(..) => true,
    _ => false,
}matches!(i.kind, AssocItemKind::Fn(..)) => {
1069                Defaultness::Implicit
1070            }
1071            defaultness => defaultness,
1072        };
1073        let (defaultness, _) = self
1074            .lower_defaultness(defaultness, has_value, || hir::Defaultness::Default { has_value });
1075
1076        let item = hir::TraitItem {
1077            owner_id: trait_item_def_id,
1078            ident: self.lower_ident(ident),
1079            generics,
1080            kind,
1081            span: self.lower_span(i.span),
1082            defaultness,
1083        };
1084        self.arena.alloc(item)
1085    }
1086
1087    fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemId {
1088        hir::TraitItemId { owner_id: self.owner_id(i.id) }
1089    }
1090
1091    /// Construct `ExprKind::Err` for the given `span`.
1092    pub(crate) fn expr_err(&mut self, span: Span, guar: ErrorGuaranteed) -> hir::Expr<'hir> {
1093        self.expr(span, hir::ExprKind::Err(guar))
1094    }
1095
1096    fn lower_trait_impl_header(
1097        &mut self,
1098        trait_impl_header: &TraitImplHeader,
1099    ) -> &'hir hir::TraitImplHeader<'hir> {
1100        let TraitImplHeader { safety, polarity, defaultness, ref trait_ref } = *trait_impl_header;
1101        let safety = self.lower_safety(safety, hir::Safety::Safe);
1102        let polarity = match polarity {
1103            ImplPolarity::Positive => ImplPolarity::Positive,
1104            ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
1105        };
1106        // `defaultness.has_value()` is never called for an `impl`, always `true` in order
1107        // to not cause an assertion failure inside the `lower_defaultness` function.
1108        let has_val = true;
1109        let (defaultness, defaultness_span) =
1110            self.lower_defaultness(defaultness, has_val, || hir::Defaultness::Final);
1111        let modifiers = TraitBoundModifiers {
1112            constness: BoundConstness::Never,
1113            asyncness: BoundAsyncness::Normal,
1114            // we don't use this in bound lowering
1115            polarity: BoundPolarity::Positive,
1116        };
1117        let trait_ref = self.lower_trait_ref(
1118            modifiers,
1119            trait_ref,
1120            ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
1121        );
1122
1123        self.arena.alloc(hir::TraitImplHeader {
1124            safety,
1125            polarity,
1126            defaultness,
1127            defaultness_span,
1128            trait_ref,
1129        })
1130    }
1131
1132    fn check_pin_drop_sugar_impl_item(
1133        &self,
1134        i: &AssocItem,
1135        ident: Ident,
1136        trait_item: Result<DefId, ErrorGuaranteed>,
1137    ) -> Ident {
1138        if let AssocItemKind::Fn(fn_kind) = &i.kind
1139            && fn_kind.is_pin_drop_sugar()
1140        {
1141            if let Ok(trait_item) = trait_item
1142                && self
1143                    .tcx
1144                    .lang_items()
1145                    .drop_trait()
1146                    .is_none_or(|drop_trait| self.tcx.parent(trait_item) != drop_trait)
1147            {
1148                self.dcx()
1149                    .struct_span_err(
1150                        i.span,
1151                        "method `drop` with `&pin mut self` is only supported for the `Drop` trait",
1152                    )
1153                    .with_span_label(i.span, "not a `Drop::pin_drop` implementation")
1154                    .emit();
1155            }
1156            return Ident::new(sym::pin_drop, ident.span);
1157        }
1158
1159        ident
1160    }
1161
1162    fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
1163        let owner_id = self.current_hir_id_owner;
1164        let hir_id: HirId = owner_id.into();
1165        let parent_id = self.tcx.local_parent(owner_id.def_id);
1166        let is_in_trait_impl =
1167            #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(parent_id) {
    DefKind::Impl { of_trait: true } => true,
    _ => false,
}matches!(self.tcx.def_kind(parent_id), DefKind::Impl { of_trait: true });
1168
1169        // Since `default impl` is not yet implemented, this is always true in impls.
1170        let has_value = true;
1171        let (defaultness, _) =
1172            self.lower_defaultness(i.kind.defaultness(), has_value, || hir::Defaultness::Final);
1173        let attrs = self.lower_attrs(
1174            hir_id,
1175            &i.attrs,
1176            i.span,
1177            Target::from_assoc_item_kind(&i.kind, AssocCtxt::Impl { of_trait: is_in_trait_impl }),
1178        );
1179
1180        let (ident, (generics, kind)) = match &i.kind {
1181            AssocItemKind::Const(ConstItem {
1182                ident,
1183                generics,
1184                ty,
1185                body,
1186                kind,
1187                define_opaque,
1188                ..
1189            }) => (
1190                *ident,
1191                self.lower_generics(
1192                    generics,
1193                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1194                    |this| {
1195                        let ty = this.lower_ty_alloc(
1196                            ty,
1197                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
1198                        );
1199                        this.lower_define_opaque(hir_id, &define_opaque);
1200                        let rhs = this.lower_const_item_rhs(body, *kind, i.span);
1201                        hir::ImplItemKind::Const(ty, rhs)
1202                    },
1203                ),
1204            ),
1205            AssocItemKind::Fn(Fn {
1206                sig, ident, generics, body, contract, define_opaque, ..
1207            }) => {
1208                let body_id = self.lower_maybe_coroutine_body(
1209                    sig.span,
1210                    i.span,
1211                    hir_id,
1212                    &sig.decl,
1213                    sig.header.coroutine_kind,
1214                    body.as_deref(),
1215                    attrs,
1216                    contract.as_deref(),
1217                );
1218                let (generics, sig) = self.lower_method_sig(
1219                    generics,
1220                    sig,
1221                    i.id,
1222                    if is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
1223                    sig.header.coroutine_kind,
1224                    attrs,
1225                );
1226                self.lower_define_opaque(hir_id, &define_opaque);
1227
1228                (*ident, (generics, hir::ImplItemKind::Fn(sig, body_id)))
1229            }
1230            AssocItemKind::Type(TyAlias { ident, generics, after_where_clause, ty, .. }) => {
1231                let mut generics = generics.clone();
1232                add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1233                (
1234                    *ident,
1235                    self.lower_generics(
1236                        &generics,
1237                        ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1238                        |this| match ty {
1239                            None => {
1240                                let guar = this.dcx().span_delayed_bug(
1241                                    i.span,
1242                                    "expected to lower associated type, but it was missing",
1243                                );
1244                                let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err(guar)));
1245                                hir::ImplItemKind::Type(ty)
1246                            }
1247                            Some(ty) => {
1248                                let ty = this.lower_ty_alloc(
1249                                    ty,
1250                                    ImplTraitContext::OpaqueTy {
1251                                        origin: hir::OpaqueTyOrigin::TyAlias {
1252                                            parent: this.owner.def_id,
1253                                            in_assoc_ty: true,
1254                                        },
1255                                    },
1256                                );
1257                                hir::ImplItemKind::Type(ty)
1258                            }
1259                        },
1260                    ),
1261                )
1262            }
1263            AssocItemKind::Delegation(delegation) => {
1264                let delegation_results = self.lower_delegation(delegation);
1265                (
1266                    delegation.ident,
1267                    (
1268                        delegation_results.generics,
1269                        hir::ImplItemKind::Fn(delegation_results.sig, delegation_results.body_id),
1270                    ),
1271                )
1272            }
1273            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1274                {
    ::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
1275            }
1276        };
1277
1278        let span = self.lower_span(i.span);
1279        let (effective_ident, impl_kind) = if is_in_trait_impl {
1280            let trait_item_def_id = self
1281                .get_partial_res(i.id)
1282                .and_then(|r| r.expect_full_res().opt_def_id())
1283                .ok_or_else(|| {
1284                    self.dcx()
1285                        .span_delayed_bug(span, "could not resolve trait item being implemented")
1286                });
1287            let effective_ident = self.check_pin_drop_sugar_impl_item(i, ident, trait_item_def_id);
1288            (effective_ident, ImplItemImplKind::Trait { defaultness, trait_item_def_id })
1289        } else {
1290            (ident, ImplItemImplKind::Inherent { vis_span: self.lower_span(i.vis.span) })
1291        };
1292
1293        let item = hir::ImplItem {
1294            owner_id,
1295            ident: self.lower_ident(effective_ident),
1296            generics,
1297            impl_kind,
1298            kind,
1299            span,
1300        };
1301        self.arena.alloc(item)
1302    }
1303
1304    fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemId {
1305        hir::ImplItemId { owner_id: self.owner_id(i.id) }
1306    }
1307
1308    fn lower_defaultness(
1309        &self,
1310        d: Defaultness,
1311        has_value: bool,
1312        implicit: impl FnOnce() -> hir::Defaultness,
1313    ) -> (hir::Defaultness, Option<Span>) {
1314        match d {
1315            Defaultness::Implicit => (implicit(), None),
1316            Defaultness::Default(sp) => {
1317                (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
1318            }
1319            Defaultness::Final(sp) => (hir::Defaultness::Final, Some(self.lower_span(sp))),
1320        }
1321    }
1322
1323    fn record_body(
1324        &mut self,
1325        params: &'hir [hir::Param<'hir>],
1326        value: hir::Expr<'hir>,
1327    ) -> hir::BodyId {
1328        let body = hir::Body { params, value: self.arena.alloc(value) };
1329        let id = body.id();
1330        {
    match (&id.hir_id.owner, &self.current_hir_id_owner) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
1331        self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
1332        id
1333    }
1334
1335    pub(super) fn lower_body(
1336        &mut self,
1337        f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1338    ) -> hir::BodyId {
1339        let prev_coroutine_kind = self.coroutine_kind.take();
1340        let task_context = self.task_context.take();
1341        let (parameters, result) = f(self);
1342        let body_id = self.record_body(parameters, result);
1343        self.task_context = task_context;
1344        self.coroutine_kind = prev_coroutine_kind;
1345        body_id
1346    }
1347
1348    fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1349        let hir_id = self.lower_node_id(param.id);
1350        self.lower_attrs(hir_id, &param.attrs, param.span, Target::Param);
1351        hir::Param {
1352            hir_id,
1353            pat: self.lower_pat(&param.pat),
1354            ty_span: self.lower_span(param.ty.span),
1355            span: self.lower_span(param.span),
1356        }
1357    }
1358
1359    pub(super) fn lower_fn_body(
1360        &mut self,
1361        decl: &FnDecl,
1362        contract: Option<&FnContract>,
1363        body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1364    ) -> hir::BodyId {
1365        self.lower_body(|this| {
1366            let params =
1367                this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x)));
1368
1369            // Optionally lower the fn contract
1370            if let Some(contract) = contract {
1371                (params, this.lower_contract(body, contract))
1372            } else {
1373                (params, body(this))
1374            }
1375        })
1376    }
1377
1378    fn lower_fn_body_block(
1379        &mut self,
1380        decl: &FnDecl,
1381        body: &Block,
1382        contract: Option<&FnContract>,
1383    ) -> hir::BodyId {
1384        self.lower_fn_body(decl, contract, |this| this.lower_block_expr(body))
1385    }
1386
1387    pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1388        self.lower_body(|this| {
1389            (
1390                &[],
1391                match expr {
1392                    Some(expr) => this.lower_expr_mut(expr),
1393                    None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")),
1394                },
1395            )
1396        })
1397    }
1398
1399    /// Takes what may be the body of an `async fn` or a `gen fn` and wraps it in an `async {}` or
1400    /// `gen {}` block as appropriate.
1401    fn lower_maybe_coroutine_body(
1402        &mut self,
1403        fn_decl_span: Span,
1404        span: Span,
1405        fn_id: hir::HirId,
1406        decl: &FnDecl,
1407        coroutine_kind: Option<CoroutineKind>,
1408        body: Option<&Block>,
1409        attrs: &'hir [hir::Attribute],
1410        contract: Option<&FnContract>,
1411    ) -> hir::BodyId {
1412        let Some(body) = body else {
1413            // Functions without a body are an error, except if this is an intrinsic. For those we
1414            // create a fake body so that the entire rest of the compiler doesn't have to deal with
1415            // this as a special case.
1416            return self.lower_fn_body(decl, contract, |this| {
1417                if {
    {
            '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(RustcIntrinsic) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcIntrinsic) || this.tcx.is_sdylib_interface_build() {
1418                    let span = this.lower_span(span);
1419                    let empty_block = hir::Block {
1420                        hir_id: this.next_id(),
1421                        stmts: &[],
1422                        expr: None,
1423                        rules: hir::BlockCheckMode::DefaultBlock,
1424                        span,
1425                        targeted_by_break: false,
1426                    };
1427                    let loop_ = hir::ExprKind::Loop(
1428                        this.arena.alloc(empty_block),
1429                        None,
1430                        hir::LoopSource::Loop,
1431                        span,
1432                    );
1433                    hir::Expr { hir_id: this.next_id(), kind: loop_, span }
1434                } else {
1435                    this.expr_err(span, this.dcx().has_errors().unwrap())
1436                }
1437            });
1438        };
1439        let Some(coroutine_kind) = coroutine_kind else {
1440            // Typical case: not a coroutine.
1441            return self.lower_fn_body_block(decl, body, contract);
1442        };
1443        // FIXME(contracts): Support contracts on async fn.
1444        self.lower_body(|this| {
1445            let (parameters, expr) = this.lower_coroutine_body_with_moved_arguments(
1446                decl,
1447                |this| this.lower_block_expr(body),
1448                fn_decl_span,
1449                body.span,
1450                coroutine_kind,
1451                hir::CoroutineSource::Fn,
1452            );
1453
1454            // FIXME(async_fn_track_caller): Can this be moved above?
1455            let hir_id = expr.hir_id;
1456            this.maybe_forward_track_caller(body.span, fn_id, hir_id);
1457
1458            (parameters, expr)
1459        })
1460    }
1461
1462    /// Lowers a desugared coroutine body after moving all of the arguments
1463    /// into the body. This is to make sure that the future actually owns the
1464    /// arguments that are passed to the function, and to ensure things like
1465    /// drop order are stable.
1466    pub(crate) fn lower_coroutine_body_with_moved_arguments(
1467        &mut self,
1468        decl: &FnDecl,
1469        lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::Expr<'hir>,
1470        fn_decl_span: Span,
1471        body_span: Span,
1472        coroutine_kind: CoroutineKind,
1473        coroutine_source: hir::CoroutineSource,
1474    ) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>) {
1475        let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1476        let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1477
1478        // Async function parameters are lowered into the closure body so that they are
1479        // captured and so that the drop order matches the equivalent non-async functions.
1480        //
1481        // from:
1482        //
1483        //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1484        //         <body>
1485        //     }
1486        //
1487        // into:
1488        //
1489        //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1490        //       async move {
1491        //         let __arg2 = __arg2;
1492        //         let <pattern> = __arg2;
1493        //         let __arg1 = __arg1;
1494        //         let <pattern> = __arg1;
1495        //         let __arg0 = __arg0;
1496        //         let <pattern> = __arg0;
1497        //         drop-temps { <body> } // see comments later in fn for details
1498        //       }
1499        //     }
1500        //
1501        // If `<pattern>` is a simple ident, then it is lowered to a single
1502        // `let <pattern> = <pattern>;` statement as an optimization.
1503        //
1504        // Note that the body is embedded in `drop-temps`; an
1505        // equivalent desugaring would be `return { <body>
1506        // };`. The key point is that we wish to drop all the
1507        // let-bound variables and temporaries created in the body
1508        // (and its tail expression!) before we drop the
1509        // parameters (c.f. rust-lang/rust#64512).
1510        for (index, parameter) in decl.inputs.iter().enumerate() {
1511            let parameter = self.lower_param(parameter);
1512            let span = parameter.pat.span;
1513
1514            // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1515            // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1516            let (ident, is_simple_parameter) = match parameter.pat.kind {
1517                hir::PatKind::Binding(hir::BindingMode(ByRef::No, _), _, ident, _) => (ident, true),
1518                // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1519                // we can keep the same name for the parameter.
1520                // This lets rustdoc render it correctly in documentation.
1521                hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1522                hir::PatKind::Wild => (Ident::with_dummy_span(rustc_span::kw::Underscore), false),
1523                _ => {
1524                    // Replace the ident for bindings that aren't simple.
1525                    let name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__arg{0}", index))
    })format!("__arg{index}");
1526                    let ident = Ident::from_str(&name);
1527
1528                    (ident, false)
1529                }
1530            };
1531
1532            let desugared_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1533
1534            // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1535            // async function.
1536            //
1537            // If this is the simple case, this parameter will end up being the same as the
1538            // original parameter, but with a different pattern id.
1539            let stmt_attrs = self.attrs.get(&parameter.hir_id.local_id).copied();
1540            let (new_parameter_pat, new_parameter_id) = self.pat_ident(desugared_span, ident);
1541            let new_parameter = hir::Param {
1542                hir_id: parameter.hir_id,
1543                pat: new_parameter_pat,
1544                ty_span: self.lower_span(parameter.ty_span),
1545                span: self.lower_span(parameter.span),
1546            };
1547
1548            if is_simple_parameter {
1549                // If this is the simple case, then we only insert one statement that is
1550                // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1551                // `HirId`s are densely assigned.
1552                let expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1553                let stmt = self.stmt_let_pat(
1554                    stmt_attrs,
1555                    desugared_span,
1556                    Some(expr),
1557                    parameter.pat,
1558                    hir::LocalSource::AsyncFn,
1559                );
1560                statements.push(stmt);
1561            } else {
1562                // If this is not the simple case, then we construct two statements:
1563                //
1564                // ```
1565                // let __argN = __argN;
1566                // let <pat> = __argN;
1567                // ```
1568                //
1569                // The first statement moves the parameter into the closure and thus ensures
1570                // that the drop order is correct.
1571                //
1572                // The second statement creates the bindings that the user wrote.
1573
1574                // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1575                // because the user may have specified a `ref mut` binding in the next
1576                // statement.
1577                let (move_pat, move_id) =
1578                    self.pat_ident_binding_mode(desugared_span, ident, hir::BindingMode::MUT);
1579                let move_expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1580                let move_stmt = self.stmt_let_pat(
1581                    None,
1582                    desugared_span,
1583                    Some(move_expr),
1584                    move_pat,
1585                    hir::LocalSource::AsyncFn,
1586                );
1587
1588                // Construct the `let <pat> = __argN;` statement. We re-use the original
1589                // parameter's pattern so that `HirId`s are densely assigned.
1590                let pattern_expr = self.expr_ident(desugared_span, ident, move_id);
1591                let pattern_stmt = self.stmt_let_pat(
1592                    stmt_attrs,
1593                    desugared_span,
1594                    Some(pattern_expr),
1595                    parameter.pat,
1596                    hir::LocalSource::AsyncFn,
1597                );
1598
1599                statements.push(move_stmt);
1600                statements.push(pattern_stmt);
1601            };
1602
1603            parameters.push(new_parameter);
1604        }
1605
1606        let mkbody = |this: &mut LoweringContext<'_, 'hir>| {
1607            // Create a block from the user's function body:
1608            let user_body = lower_body(this);
1609
1610            // Transform into `drop-temps { <user-body> }`, an expression:
1611            let desugared_span =
1612                this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1613            let user_body = this.expr_drop_temps(desugared_span, this.arena.alloc(user_body));
1614
1615            // As noted above, create the final block like
1616            //
1617            // ```
1618            // {
1619            //   let $param_pattern = $raw_param;
1620            //   ...
1621            //   drop-temps { <user-body> }
1622            // }
1623            // ```
1624            let body = this.block_all(
1625                desugared_span,
1626                this.arena.alloc_from_iter(statements),
1627                Some(user_body),
1628            );
1629
1630            this.expr_block(body)
1631        };
1632        let desugaring_kind = match coroutine_kind {
1633            CoroutineKind::Async { .. } => hir::CoroutineDesugaring::Async,
1634            CoroutineKind::Gen { .. } => hir::CoroutineDesugaring::Gen,
1635            CoroutineKind::AsyncGen { .. } => hir::CoroutineDesugaring::AsyncGen,
1636        };
1637        let closure_id = coroutine_kind.closure_id();
1638
1639        let coroutine_expr = self.make_desugared_coroutine_expr(
1640            // The default capture mode here is by-ref. Later on during upvar analysis,
1641            // we will force the captured arguments to by-move, but for async closures,
1642            // we want to make sure that we avoid unnecessarily moving captures, or else
1643            // all async closures would default to `FnOnce` as their calling mode.
1644            CaptureBy::Ref,
1645            closure_id,
1646            None,
1647            fn_decl_span,
1648            body_span,
1649            desugaring_kind,
1650            coroutine_source,
1651            mkbody,
1652        );
1653
1654        let expr = hir::Expr {
1655            hir_id: self.lower_node_id(closure_id),
1656            kind: coroutine_expr,
1657            span: self.lower_span(body_span),
1658        };
1659
1660        (self.arena.alloc_from_iter(parameters), expr)
1661    }
1662
1663    fn lower_method_sig(
1664        &mut self,
1665        generics: &Generics,
1666        sig: &FnSig,
1667        id: NodeId,
1668        kind: FnDeclKind,
1669        coroutine_kind: Option<CoroutineKind>,
1670        attrs: &[hir::Attribute],
1671    ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1672        let header = self.lower_fn_header(sig.header, hir::Safety::Safe, attrs);
1673        let itctx = ImplTraitContext::Universal;
1674        let (generics, decl) = self.lower_generics(generics, itctx, |this| {
1675            this.lower_fn_decl(&sig.decl, id, sig.span, kind, coroutine_kind)
1676        });
1677        (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1678    }
1679
1680    pub(super) fn lower_fn_header(
1681        &mut self,
1682        h: FnHeader,
1683        default_safety: hir::Safety,
1684        attrs: &[hir::Attribute],
1685    ) -> hir::FnHeader {
1686        let asyncness = if let Some(CoroutineKind::Async { span, .. }) = h.coroutine_kind {
1687            hir::IsAsync::Async(self.lower_span(span))
1688        } else {
1689            hir::IsAsync::NotAsync
1690        };
1691
1692        let safety = self.lower_safety(h.safety, default_safety);
1693
1694        // Treat safe `#[target_feature]` functions as unsafe, but also remember that we did so.
1695        let safety = if {
    {
            '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(TargetFeature {
                            was_forced: false, .. }) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, TargetFeature { was_forced: false, .. })
1696            && safety.is_safe()
1697            && !self.tcx.sess.target.is_like_wasm
1698        {
1699            hir::HeaderSafety::SafeTargetFeatures
1700        } else {
1701            safety.into()
1702        };
1703
1704        let constness = self.lower_constness(attrs, h.constness);
1705
1706        hir::FnHeader { safety, asyncness, constness, abi: self.lower_extern(h.ext) }
1707    }
1708
1709    pub(super) fn lower_abi(&mut self, abi_str: StrLit) -> ExternAbi {
1710        let ast::StrLit { symbol_unescaped, span, .. } = abi_str;
1711        let extern_abi = symbol_unescaped.as_str().parse().unwrap_or_else(|_| {
1712            self.error_on_invalid_abi(abi_str);
1713            ExternAbi::Rust
1714        });
1715        let tcx = self.tcx;
1716
1717        // we can't do codegen for unsupported ABIs, so error now so we won't get farther
1718        if !tcx.sess.target.is_abi_supported(extern_abi) {
1719            let mut err = {
    tcx.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} is not a supported ABI for the current target",
                            extern_abi))
                })).with_code(E0570)
}struct_span_code_err!(
1720                tcx.dcx(),
1721                span,
1722                E0570,
1723                "{extern_abi} is not a supported ABI for the current target",
1724            );
1725
1726            if let ExternAbi::Stdcall { unwind } = extern_abi {
1727                let c_abi = ExternAbi::C { unwind };
1728                let system_abi = ExternAbi::System { unwind };
1729                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you need `extern {0}` on win32 and `extern {1}` everywhere else, use `extern {2}`",
                extern_abi, c_abi, system_abi))
    })format!("if you need `extern {extern_abi}` on win32 and `extern {c_abi}` everywhere else, \
1730                    use `extern {system_abi}`"
1731                ));
1732            }
1733            err.emit();
1734        }
1735        // Show required feature gate even if we already errored, as the user is likely to build the code
1736        // for the actually intended target next and then they will need the feature gate.
1737        gate_unstable_abi(tcx.sess, tcx.features(), span, extern_abi);
1738        extern_abi
1739    }
1740
1741    pub(super) fn lower_extern(&mut self, ext: Extern) -> ExternAbi {
1742        match ext {
1743            Extern::None => ExternAbi::Rust,
1744            Extern::Implicit(_) => ExternAbi::FALLBACK,
1745            Extern::Explicit(abi, _) => self.lower_abi(abi),
1746        }
1747    }
1748
1749    fn error_on_invalid_abi(&self, abi: StrLit) {
1750        let abi_names = enabled_names(self.tcx.features(), abi.span)
1751            .iter()
1752            .map(|s| Symbol::intern(s))
1753            .collect::<Vec<_>>();
1754        let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1755        self.dcx().emit_err(InvalidAbi {
1756            abi: abi.symbol_unescaped,
1757            span: abi.span,
1758            suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1759                span: abi.span,
1760                suggestion: suggested_name.to_string(),
1761            }),
1762            command: "rustc --print=calling-conventions".to_string(),
1763        });
1764    }
1765
1766    /// Lowers constness or comptime attribute.
1767    /// Whether `const` is allowed here is checked by ast validation.
1768    /// Whether `comptime` is allowed here is checked by the `comptime` attribute parser.
1769    pub(super) fn lower_constness(&mut self, attrs: &[hir::Attribute], c: Const) -> hir::Constness {
1770        let mut constness = match c {
1771            Const::Yes(_) => hir::Constness::Const { always: false },
1772            Const::No => hir::Constness::NotConst,
1773        };
1774
1775        if let Some(&attr_span) = {
    '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(RustcComptime(span)) => {
                    break 'done Some(span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcComptime(span) => span) {
1776            match std::mem::replace(&mut constness, hir::Constness::Const { always: true }) {
1777                hir::Constness::Const { always: true } => {
1778                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("lower_constness cannot produce comptime")));
}unreachable!("lower_constness cannot produce comptime")
1779                }
1780                // A function can't be `const` and `comptime` at the same time
1781                hir::Constness::Const { always: false } => {
1782                    let Const::Yes(span) = c else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1783                    self.dcx().emit_err(ConstComptimeFn { span, attr_span });
1784                }
1785                // Good
1786                hir::Constness::NotConst => {}
1787            }
1788        }
1789        constness
1790    }
1791
1792    pub(super) fn lower_safety(&self, s: Safety, default: hir::Safety) -> hir::Safety {
1793        match s {
1794            Safety::Unsafe(_) => hir::Safety::Unsafe,
1795            Safety::Default => default,
1796            Safety::Safe(_) => hir::Safety::Safe,
1797        }
1798    }
1799
1800    fn lower_restriction_kind(&mut self, kind: &RestrictionKind) -> hir::RestrictionKind<'hir> {
1801        match kind {
1802            RestrictionKind::Unrestricted => hir::RestrictionKind::Unrestricted,
1803            RestrictionKind::Restricted { path, id, shorthand: _ } => {
1804                let res = self.get_partial_res(*id);
1805                if let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) {
1806                    hir::RestrictionKind::Restricted(self.arena.alloc(hir::Path {
1807                        res: did,
1808                        segments: self.arena.alloc_from_iter(path.segments.iter().map(|segment| {
1809                            self.lower_path_segment(
1810                                path.span,
1811                                segment,
1812                                ParamMode::Explicit,
1813                                GenericArgsMode::Err,
1814                                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1815                                None,
1816                            )
1817                        })),
1818                        span: self.lower_span(path.span),
1819                    }))
1820                } else {
1821                    self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1822                    hir::RestrictionKind::Unrestricted
1823                }
1824            }
1825        }
1826    }
1827
1828    pub(super) fn lower_impl_restriction(
1829        &mut self,
1830        r: &ImplRestriction,
1831    ) -> &'hir hir::ImplRestriction<'hir> {
1832        let kind = self.lower_restriction_kind(&r.kind);
1833        self.arena.alloc(hir::ImplRestriction { kind, span: self.lower_span(r.span) })
1834    }
1835
1836    pub(super) fn lower_mut_restriction(
1837        &mut self,
1838        r: &MutRestriction,
1839    ) -> &'hir hir::MutRestriction<'hir> {
1840        let kind = self.lower_restriction_kind(&r.kind);
1841        self.arena.alloc(hir::MutRestriction { kind, span: self.lower_span(r.span) })
1842    }
1843
1844    /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1845    /// the carried impl trait definitions and bounds.
1846    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_generics",
                                    "rustc_ast_lowering::item", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1846u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("generics")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("generics");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("itctx")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("itctx");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: (&'hir hir::Generics<'hir>, T) =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !self.impl_trait_defs.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_defs.is_empty()")
            };
            if !self.impl_trait_bounds.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_bounds.is_empty()")
            };
            let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> =
                SmallVec::new();
            let mut dedup_map: IndexMap<LocalDefId, _> = Default::default();
            predicates.extend(generics.params.iter().filter_map(|param|
                        {
                            self.lower_generic_bound_predicate(param.ident, param.id,
                                &param.kind, &param.bounds, param.colon_span, generics.span,
                                RelaxedBoundPolicy::Allowed(dedup_map.entry(self.local_def_id(param.id)).or_default()),
                                itctx, PredicateOrigin::GenericParam)
                        }));
            predicates.extend(generics.where_clause.predicates.iter().map(|predicate|
                        {
                            self.lower_where_predicate(predicate, &generics.params,
                                &mut dedup_map)
                        }));
            let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
                self.lower_generic_params_mut(&generics.params,
                        hir::GenericParamSource::Generics).collect();
            let extra_lifetimes =
                self.owner.extra_lifetime_params(self.owner.id);
            params.extend(extra_lifetimes.into_iter().map(|&(ident, node_id,
                            kind)|
                        {
                            self.lifetime_res_to_generic_param(ident, node_id, kind,
                                hir::GenericParamSource::Generics)
                        }));
            let has_where_clause_predicates =
                !generics.where_clause.predicates.is_empty();
            let where_clause_span =
                self.lower_span(generics.where_clause.span);
            let span = self.lower_span(generics.span);
            let res = f(self);
            let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
            params.extend(impl_trait_defs.into_iter());
            let impl_trait_bounds =
                std::mem::take(&mut self.impl_trait_bounds);
            predicates.extend(impl_trait_bounds.into_iter());
            let lowered_generics =
                self.arena.alloc(hir::Generics {
                        params: self.arena.alloc_from_iter(params),
                        predicates: self.arena.alloc_from_iter(predicates),
                        has_where_clause_predicates,
                        where_clause_span,
                        span,
                    });
            (lowered_generics, res)
        }
    }
}#[instrument(level = "debug", skip(self, f))]
1847    fn lower_generics<T>(
1848        &mut self,
1849        generics: &Generics,
1850        itctx: ImplTraitContext,
1851        f: impl FnOnce(&mut Self) -> T,
1852    ) -> (&'hir hir::Generics<'hir>, T) {
1853        assert!(self.impl_trait_defs.is_empty());
1854        assert!(self.impl_trait_bounds.is_empty());
1855
1856        let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1857        // We need to make sure that generic params don't have multiple relaxed bounds for the same trait
1858        // across generic param bounds and where bounds.
1859        let mut dedup_map: IndexMap<LocalDefId, _> = Default::default();
1860        predicates.extend(generics.params.iter().filter_map(|param| {
1861            self.lower_generic_bound_predicate(
1862                param.ident,
1863                param.id,
1864                &param.kind,
1865                &param.bounds,
1866                param.colon_span,
1867                generics.span,
1868                RelaxedBoundPolicy::Allowed(
1869                    dedup_map.entry(self.local_def_id(param.id)).or_default(),
1870                ),
1871                itctx,
1872                PredicateOrigin::GenericParam,
1873            )
1874        }));
1875        predicates.extend(generics.where_clause.predicates.iter().map(|predicate| {
1876            self.lower_where_predicate(predicate, &generics.params, &mut dedup_map)
1877        }));
1878
1879        let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> = self
1880            .lower_generic_params_mut(&generics.params, hir::GenericParamSource::Generics)
1881            .collect();
1882
1883        // Introduce extra lifetimes if late resolution tells us to.
1884        let extra_lifetimes = self.owner.extra_lifetime_params(self.owner.id);
1885        params.extend(extra_lifetimes.into_iter().map(|&(ident, node_id, kind)| {
1886            self.lifetime_res_to_generic_param(
1887                ident,
1888                node_id,
1889                kind,
1890                hir::GenericParamSource::Generics,
1891            )
1892        }));
1893
1894        let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1895        let where_clause_span = self.lower_span(generics.where_clause.span);
1896        let span = self.lower_span(generics.span);
1897        let res = f(self);
1898
1899        let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1900        params.extend(impl_trait_defs.into_iter());
1901
1902        let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1903        predicates.extend(impl_trait_bounds.into_iter());
1904
1905        let lowered_generics = self.arena.alloc(hir::Generics {
1906            params: self.arena.alloc_from_iter(params),
1907            predicates: self.arena.alloc_from_iter(predicates),
1908            has_where_clause_predicates,
1909            where_clause_span,
1910            span,
1911        });
1912
1913        (lowered_generics, res)
1914    }
1915
1916    pub(super) fn lower_define_opaque(
1917        &mut self,
1918        hir_id: HirId,
1919        define_opaque: &Option<ThinVec<(NodeId, Path)>>,
1920    ) {
1921        {
    match (&self.define_opaque, &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(self.define_opaque, None);
1922        if !hir_id.is_owner() {
    ::core::panicking::panic("assertion failed: hir_id.is_owner()")
};assert!(hir_id.is_owner());
1923        let Some(define_opaque) = define_opaque.as_ref() else {
1924            return;
1925        };
1926        let define_opaque = define_opaque.iter().filter_map(|(id, path)| {
1927            let res = self.get_partial_res(*id);
1928            let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else {
1929                self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1930                return None;
1931            };
1932            let Some(did) = did.as_local() else {
1933                self.dcx().span_err(
1934                    path.span,
1935                    "only opaque types defined in the local crate can be defined",
1936                );
1937                return None;
1938            };
1939            Some((self.lower_span(path.span), did))
1940        });
1941        let define_opaque = self.arena.alloc_from_iter(define_opaque);
1942        self.define_opaque = Some(define_opaque);
1943    }
1944
1945    pub(super) fn lower_generic_bound_predicate(
1946        &mut self,
1947        ident: Ident,
1948        id: NodeId,
1949        kind: &GenericParamKind,
1950        bounds: &[GenericBound],
1951        colon_span: Option<Span>,
1952        parent_span: Span,
1953        rbp: RelaxedBoundPolicy<'_>,
1954        itctx: ImplTraitContext,
1955        origin: PredicateOrigin,
1956    ) -> Option<hir::WherePredicate<'hir>> {
1957        // Do not create a clause if we do not have anything inside it.
1958        if bounds.is_empty() {
1959            return None;
1960        }
1961
1962        let bounds = self.lower_param_bounds(bounds, rbp, itctx);
1963
1964        let param_span = ident.span;
1965
1966        // Reconstruct the span of the entire predicate from the individual generic bounds.
1967        let span_start = colon_span.unwrap_or_else(|| param_span.shrink_to_hi());
1968        let span = bounds.iter().fold(span_start, |span_accum, bound| {
1969            match bound.span().find_ancestor_inside(parent_span) {
1970                Some(bound_span) => span_accum.to(bound_span),
1971                None => span_accum,
1972            }
1973        });
1974        let span = self.lower_span(span);
1975        let hir_id = self.next_id();
1976        let kind = self.arena.alloc(match kind {
1977            GenericParamKind::Const { .. } => return None,
1978            GenericParamKind::Type { .. } => {
1979                let def_id = self.local_def_id(id).to_def_id();
1980                let hir_id = self.next_id();
1981                let res = Res::Def(DefKind::TyParam, def_id);
1982                let ident = self.lower_ident(ident);
1983                let ty_path = self.arena.alloc(hir::Path {
1984                    span: self.lower_span(param_span),
1985                    res,
1986                    segments: self
1987                        .arena
1988                        .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1989                });
1990                let ty_id = self.next_id();
1991                let bounded_ty =
1992                    self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1993                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1994                    bounded_ty: self.arena.alloc(bounded_ty),
1995                    bounds,
1996                    bound_generic_params: &[],
1997                    origin,
1998                })
1999            }
2000            GenericParamKind::Lifetime => {
2001                let lt_id = self.next_node_id();
2002                let lifetime =
2003                    self.new_named_lifetime(id, lt_id, ident, LifetimeSource::Other, ident.into());
2004                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2005                    lifetime,
2006                    bounds,
2007                    in_where_clause: false,
2008                })
2009            }
2010        });
2011        Some(hir::WherePredicate { hir_id, span, kind })
2012    }
2013
2014    fn lower_where_predicate(
2015        &mut self,
2016        pred: &WherePredicate,
2017        params: &[ast::GenericParam],
2018        dedup_map: &mut IndexMap<LocalDefId, IndexMap<DefId, Span>>,
2019    ) -> hir::WherePredicate<'hir> {
2020        let hir_id = self.lower_node_id(pred.id);
2021        let span = self.lower_span(pred.span);
2022        self.lower_attrs(hir_id, &pred.attrs, span, Target::WherePredicate);
2023        let kind = self.arena.alloc(match &pred.kind {
2024            WherePredicateKind::BoundPredicate(WhereBoundPredicate {
2025                bound_generic_params,
2026                bounded_ty,
2027                bounds,
2028            }) => {
2029                let rbp = if bound_generic_params.is_empty()
2030                    && let Some(res) =
2031                        self.get_partial_res(bounded_ty.id).and_then(|r| r.full_res())
2032                    && let Res::Def(DefKind::TyParam, def_id) = res
2033                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2034                {
2035                    RelaxedBoundPolicy::Allowed(dedup_map.entry(def_id.expect_local()).or_default())
2036                } else {
2037                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::WhereBound)
2038                };
2039                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2040                    bound_generic_params: self.lower_generic_params(
2041                        bound_generic_params,
2042                        hir::GenericParamSource::Binder,
2043                    ),
2044                    bounded_ty: self.lower_ty_alloc(
2045                        bounded_ty,
2046                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2047                    ),
2048                    bounds: self.lower_param_bounds(
2049                        bounds,
2050                        rbp,
2051                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2052                    ),
2053                    origin: PredicateOrigin::WhereClause,
2054                })
2055            }
2056            WherePredicateKind::RegionPredicate(WhereRegionPredicate { lifetime, bounds }) => {
2057                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2058                    lifetime: self.lower_lifetime(
2059                        lifetime,
2060                        LifetimeSource::Other,
2061                        lifetime.ident.into(),
2062                    ),
2063                    bounds: self.lower_param_bounds(
2064                        bounds,
2065                        RelaxedBoundPolicy::Allowed(&mut Default::default()),
2066                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2067                    ),
2068                    in_where_clause: true,
2069                })
2070            }
2071        });
2072        hir::WherePredicate { hir_id, span, kind }
2073    }
2074}