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, ResolvingRestrictionKind, RestrictionAncestorOnly};
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_unsafe_span: match *impl_safety {
159                Safety::Unsafe(span) => Some(self.lower_span(span)),
160                Safety::Safe(_) | Safety::Default => None,
161            },
162            is_default: *is_default,
163            resolution,
164        }
165    }
166
167    fn generate_extra_attrs_for_item_kind(
168        &mut self,
169        id: NodeId,
170        i: &ItemKind,
171    ) -> Vec<hir::Attribute> {
172        match i {
173            ItemKind::Fn(Fn { eii_impl: None, .. })
174            | ItemKind::Static(StaticItem { eii_impl: None, .. }) => Vec::new(),
175            ItemKind::Fn(Fn { eii_impl: Some(eii_impl), .. })
176            | ItemKind::Static(StaticItem { eii_impl: Some(eii_impl), .. }) => {
177                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [hir::Attribute::Parsed(AttributeKind::EiiImpl(Box::new(self.lower_eii_impl(eii_impl))))]))vec![hir::Attribute::Parsed(AttributeKind::EiiImpl(Box::new(
178                    self.lower_eii_impl(eii_impl),
179                )))]
180            }
181            ItemKind::MacroDef(name, MacroDef { eii_declaration: Some(target), .. }) => self
182                .lower_eii_decl(id, *name, target)
183                .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))])
184                .unwrap_or_default(),
185
186            ItemKind::ExternCrate(..)
187            | ItemKind::Use(..)
188            | ItemKind::Const(..)
189            | ItemKind::ConstBlock(..)
190            | ItemKind::Mod(..)
191            | ItemKind::ForeignMod(..)
192            | ItemKind::GlobalAsm(..)
193            | ItemKind::TyAlias(..)
194            | ItemKind::Enum(..)
195            | ItemKind::Struct(..)
196            | ItemKind::Union(..)
197            | ItemKind::Trait(..)
198            | ItemKind::TraitAlias(..)
199            | ItemKind::Impl(..)
200            | ItemKind::MacCall(..)
201            | ItemKind::MacroDef(..)
202            | ItemKind::Delegation(..)
203            | ItemKind::DelegationMac(..) => Vec::new(),
204        }
205    }
206
207    fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
208        let owner_id = self.current_hir_id_owner;
209        let hir_id: HirId = owner_id.into();
210        let vis_span = self.lower_span(i.vis.span);
211
212        let extra_hir_attributes = self.generate_extra_attrs_for_item_kind(i.id, &i.kind);
213        let attrs = self.lower_attrs_with_extra(
214            hir_id,
215            &i.attrs,
216            i.span,
217            Target::from_ast_item(i),
218            &extra_hir_attributes,
219        );
220
221        let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind);
222        let item = hir::Item {
223            owner_id,
224            kind,
225            vis_span,
226            span: self.lower_span(i.span),
227            eii: {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(EiiImpl(..) |
                            EiiDeclaration(..)) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, EiiImpl(..) | EiiDeclaration(..)),
228        };
229        self.arena.alloc(item)
230    }
231
232    fn lower_item_kind(
233        &mut self,
234        span: Span,
235        id: NodeId,
236        hir_id: hir::HirId,
237        attrs: &'hir [hir::Attribute],
238        vis_span: Span,
239        i: &ItemKind,
240    ) -> hir::ItemKind<'hir> {
241        match i {
242            ItemKind::ExternCrate(orig_name, ident) => {
243                let ident = self.lower_ident(*ident);
244                hir::ItemKind::ExternCrate(*orig_name, ident)
245            }
246            ItemKind::Use(use_tree) => {
247                // Start with an empty prefix.
248                let prefix =
249                    Path { segments: ThinVec::new(), span: use_tree.prefix.span.shrink_to_lo() };
250
251                self.lower_use_tree(use_tree, &prefix, id, vis_span, attrs)
252            }
253            ItemKind::Static(ast::StaticItem {
254                ident,
255                ty,
256                safety: _,
257                mutability: m,
258                expr: e,
259                define_opaque,
260                eii_impl: _,
261            }) => {
262                let ident = self.lower_ident(*ident);
263                let ty = self
264                    .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
265                let body_id = self.lower_const_body(span, e.as_deref());
266                self.lower_define_opaque(hir_id, define_opaque);
267                hir::ItemKind::Static(*m, ident, ty, body_id)
268            }
269            ItemKind::Const(ConstItem {
270                defaultness: _,
271                ident,
272                generics,
273                ty,
274                body,
275                kind,
276                define_opaque,
277            }) => {
278                let ident = self.lower_ident(*ident);
279                let (generics, (ty, rhs)) = self.lower_generics(
280                    generics,
281                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
282                    |this| {
283                        let ty = this.lower_ty_alloc(
284                            ty,
285                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
286                        );
287                        let rhs = this.lower_const_item_rhs(body, *kind, span);
288                        (ty, rhs)
289                    },
290                );
291                self.lower_define_opaque(hir_id, &define_opaque);
292                hir::ItemKind::Const(ident, generics, ty, rhs)
293            }
294            ItemKind::ConstBlock(ConstBlockItem { span, id, block }) => hir::ItemKind::Const(
295                self.lower_ident(ConstBlockItem::IDENT),
296                hir::Generics::empty(),
297                self.arena.alloc(self.ty_tup(DUMMY_SP, &[])),
298                hir::ConstItemRhs::Body({
299                    let body = hir::Expr {
300                        hir_id: self.lower_node_id(*id),
301                        kind: hir::ExprKind::Block(self.lower_block(block, false), None),
302                        span: self.lower_span(*span),
303                    };
304                    self.record_body(&[], body)
305                }),
306            ),
307            ItemKind::Fn(Fn {
308                sig: FnSig { decl, header, span: fn_sig_span },
309                ident,
310                generics,
311                body,
312                contract,
313                define_opaque,
314                ..
315            }) => {
316                self.with_new_scopes(*fn_sig_span, |this| {
317                    // Note: we don't need to change the return type from `T` to
318                    // `impl Future<Output = T>` here because lower_body
319                    // only cares about the input argument patterns in the function
320                    // declaration (decl), not the return types.
321                    let coroutine_marker = header.coroutine_marker;
322                    let body_id = this.lower_maybe_coroutine_body(
323                        *fn_sig_span,
324                        span,
325                        hir_id,
326                        decl,
327                        coroutine_marker,
328                        body.as_deref(),
329                        attrs,
330                        contract.as_deref(),
331                    );
332
333                    let itctx = ImplTraitContext::Universal;
334                    let (generics, decl) = this.lower_generics(generics, itctx, |this| {
335                        this.lower_fn_decl(decl, id, *fn_sig_span, FnDeclKind::Fn, coroutine_marker)
336                    });
337                    let sig = hir::FnSig {
338                        decl,
339                        header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
340                        span: this.lower_span(*fn_sig_span),
341                    };
342                    this.lower_define_opaque(hir_id, define_opaque);
343                    let ident = this.lower_ident(*ident);
344                    hir::ItemKind::Fn {
345                        ident,
346                        sig,
347                        generics,
348                        body: body_id,
349                        has_body: body.is_some(),
350                    }
351                })
352            }
353            ItemKind::Mod(_, ident, mod_kind) => {
354                let ident = self.lower_ident(*ident);
355                match mod_kind {
356                    ModKind::Loaded(items, _, spans) => {
357                        hir::ItemKind::Mod(ident, self.lower_mod(items, spans))
358                    }
359                    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"),
360                }
361            }
362            ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
363                abi: fm.abi.map_or(ExternAbi::FALLBACK, |abi| self.lower_abi(abi)),
364                items: self
365                    .arena
366                    .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
367            },
368            ItemKind::GlobalAsm(asm) => {
369                let asm = self.lower_inline_asm(span, asm);
370                let fake_body =
371                    self.lower_body(|this| (&[], this.expr(span, hir::ExprKind::InlineAsm(asm))));
372                hir::ItemKind::GlobalAsm { asm, fake_body }
373            }
374            ItemKind::TyAlias(TyAlias { ident, generics, after_where_clause, ty, .. }) => {
375                // We lower
376                //
377                // type Foo = impl Trait
378                //
379                // to
380                //
381                // type Foo = Foo1
382                // opaque type Foo1: Trait
383                let ident = self.lower_ident(*ident);
384                let mut generics = generics.clone();
385                add_ty_alias_where_clause(&mut generics, after_where_clause, true);
386                let (generics, ty) = self.lower_generics(
387                    &generics,
388                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
389                    |this| match ty {
390                        None => {
391                            let guar = this.dcx().span_delayed_bug(
392                                span,
393                                "expected to lower type alias type, but it was missing",
394                            );
395                            this.arena.alloc(this.ty(span, hir::TyKind::Err(guar)))
396                        }
397                        Some(ty) => this.lower_ty_alloc(
398                            ty,
399                            ImplTraitContext::OpaqueTy {
400                                origin: hir::OpaqueTyOrigin::TyAlias {
401                                    parent: this.owner.def_id,
402                                    in_assoc_ty: false,
403                                },
404                            },
405                        ),
406                    },
407                );
408                hir::ItemKind::TyAlias(ident, generics, ty)
409            }
410            ItemKind::Enum(ident, generics, enum_definition) => {
411                let ident = self.lower_ident(*ident);
412                let (generics, variants) = self.lower_generics(
413                    generics,
414                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
415                    |this| {
416                        this.arena.alloc_from_iter(
417                            enum_definition.variants.iter().map(|x| this.lower_variant(i, x)),
418                        )
419                    },
420                );
421                hir::ItemKind::Enum(ident, generics, hir::EnumDef { variants })
422            }
423            ItemKind::Struct(ident, generics, struct_def) => {
424                let ident = self.lower_ident(*ident);
425                let (generics, struct_def) = self.lower_generics(
426                    generics,
427                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
428                    |this| this.lower_variant_data(hir_id, i, struct_def),
429                );
430                hir::ItemKind::Struct(ident, generics, struct_def)
431            }
432            ItemKind::Union(ident, generics, vdata) => {
433                let ident = self.lower_ident(*ident);
434                let (generics, vdata) = self.lower_generics(
435                    generics,
436                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
437                    |this| this.lower_variant_data(hir_id, i, vdata),
438                );
439                hir::ItemKind::Union(ident, generics, vdata)
440            }
441            ItemKind::Impl(Impl {
442                generics: ast_generics,
443                of_trait,
444                self_ty: ty,
445                items: impl_items,
446                constness,
447            }) => {
448                // Lower the "impl header" first. This ordering is important
449                // for in-band lifetimes! Consider `'a` here:
450                //
451                //     impl Foo<'a> for u32 {
452                //         fn method(&'a self) { .. }
453                //     }
454                //
455                // Because we start by lowering the `Foo<'a> for u32`
456                // part, we will add `'a` to the list of generics on
457                // the impl. When we then encounter it later in the
458                // method, it will not be considered an in-band
459                // lifetime to be added, but rather a reference to a
460                // parent lifetime.
461                let itctx = ImplTraitContext::Universal;
462                let (generics, (of_trait, lowered_ty)) =
463                    self.lower_generics(ast_generics, itctx, |this| {
464                        let of_trait = of_trait
465                            .as_deref()
466                            .map(|of_trait| this.lower_trait_impl_header(of_trait));
467
468                        let lowered_ty = this.lower_ty_alloc(
469                            ty,
470                            ImplTraitContext::Disallowed(ImplTraitPosition::ImplSelf),
471                        );
472
473                        (of_trait, lowered_ty)
474                    });
475
476                let new_impl_items = self
477                    .arena
478                    .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
479
480                let constness = self.lower_constness(attrs, *constness);
481
482                hir::ItemKind::Impl(hir::Impl {
483                    generics,
484                    of_trait,
485                    self_ty: lowered_ty,
486                    items: new_impl_items,
487                    constness,
488                })
489            }
490            ItemKind::Trait(Trait {
491                impl_restriction,
492                constness,
493                is_auto,
494                safety,
495                ident,
496                generics,
497                bounds,
498                items,
499            }) => {
500                let constness = self.lower_constness(attrs, *constness);
501                let impl_restriction = self.lower_impl_restriction(impl_restriction, hir_id);
502                let ident = self.lower_ident(*ident);
503                let (generics, (safety, items, bounds)) = self.lower_generics(
504                    generics,
505                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
506                    |this| {
507                        let bounds = this.lower_param_bounds(
508                            bounds,
509                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::SuperTrait),
510                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
511                        );
512                        let items = this.arena.alloc_from_iter(
513                            items.iter().map(|item| this.lower_trait_item_ref(item)),
514                        );
515                        let safety = this.lower_safety(*safety, hir::Safety::Safe);
516                        (safety, items, bounds)
517                    },
518                );
519                hir::ItemKind::Trait {
520                    impl_restriction,
521                    constness,
522                    is_auto: *is_auto,
523                    safety,
524                    ident,
525                    generics,
526                    bounds,
527                    items,
528                }
529            }
530            ItemKind::TraitAlias(TraitAlias { constness, ident, generics, bounds }) => {
531                let constness = self.lower_constness(attrs, *constness);
532                let ident = self.lower_ident(*ident);
533                let (generics, bounds) = self.lower_generics(
534                    generics,
535                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
536                    |this| {
537                        this.lower_param_bounds(
538                            bounds,
539                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitAlias),
540                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
541                        )
542                    },
543                );
544                hir::ItemKind::TraitAlias(constness, ident, generics, bounds)
545            }
546            ItemKind::MacroDef(ident, MacroDef { body, macro_rules, eii_declaration: _ }) => {
547                let ident = self.lower_ident(*ident);
548                let body = Box::new(self.lower_delim_args(body));
549                let def_id = self.owner.def_id;
550                let def_kind = self.tcx.def_kind(def_id);
551                let DefKind::Macro(macro_kinds) = def_kind else {
552                    {
    ::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!(
553                        "expected DefKind::Macro for macro item, found {}",
554                        def_kind.descr(def_id.to_def_id())
555                    );
556                };
557                let macro_def = self.arena.alloc(ast::MacroDef {
558                    body,
559                    macro_rules: *macro_rules,
560                    eii_declaration: None,
561                });
562                hir::ItemKind::Macro(ident, macro_def, macro_kinds)
563            }
564            ItemKind::Delegation(delegation) => {
565                let delegation_results = self.lower_delegation(delegation);
566                hir::ItemKind::Fn {
567                    sig: delegation_results.sig,
568                    ident: delegation_results.ident,
569                    generics: delegation_results.generics,
570                    body: delegation_results.body_id,
571                    has_body: true,
572                }
573            }
574            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
575                {
    ::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
576            }
577        }
578    }
579
580    fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
581        let res = self.get_partial_res(id)?;
582        let Some(did) = res.expect_full_res().opt_def_id() else {
583            self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
584            return None;
585        };
586
587        Some(did)
588    }
589
590    #[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(590u32),
                                    ::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_attr_ir::AttributeKind::*;
                                                                let i: &::rustc_attr_ir::Attribute = i;
                                                                match i {
                                                                    ::rustc_attr_ir::Attribute::Parsed(EiiImpl(..) |
                                                                        EiiDeclaration(..)) => {
                                                                        break 'done Some(());
                                                                    }
                                                                    ::rustc_attr_ir::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))]
591    fn lower_use_tree(
592        &mut self,
593        tree: &UseTree,
594        prefix: &Path,
595        id: NodeId,
596        vis_span: Span,
597        attrs: &'hir [hir::Attribute],
598    ) -> hir::ItemKind<'hir> {
599        let path = &tree.prefix;
600        let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
601
602        match tree.kind {
603            UseTreeKind::Simple(rename) => {
604                let mut ident = tree.ident();
605
606                // First, apply the prefix to the path.
607                let mut path = Path { segments, span: path.span };
608
609                // Correctly resolve `self` imports.
610                if path.segments.len() > 1
611                    && path.segments.last().unwrap().ident.name == kw::SelfLower
612                {
613                    let _ = path.segments.pop();
614                    if rename.is_none() {
615                        ident = path.segments.last().unwrap().ident;
616                    }
617                }
618
619                let res = self.lower_import_res(id, path.span);
620                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
621                let ident = self.lower_ident(ident);
622                hir::ItemKind::Use(path, hir::UseKind::Single(ident))
623            }
624            UseTreeKind::Glob(_) => {
625                let res = self.expect_full_res(id);
626                let res = self.lower_res(res);
627                // Put the result in the appropriate namespace.
628                let res = match res {
629                    Res::Def(DefKind::Mod | DefKind::Trait, _) => {
630                        PerNS { type_ns: Some(res), value_ns: None, macro_ns: None }
631                    }
632                    Res::Def(DefKind::Enum, _) => {
633                        PerNS { type_ns: None, value_ns: Some(res), macro_ns: None }
634                    }
635                    Res::Err => {
636                        // Propagate the error to all namespaces, just to be sure.
637                        let err = Some(Res::Err);
638                        PerNS { type_ns: err, value_ns: err, macro_ns: err }
639                    }
640                    _ => span_bug!(path.span, "bad glob res {:?}", res),
641                };
642                let path = Path { segments, span: path.span };
643                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
644                hir::ItemKind::Use(path, hir::UseKind::Glob)
645            }
646            UseTreeKind::Nested { items: ref trees, .. } => {
647                // Nested imports are desugared into simple imports.
648                // So, if we start with
649                //
650                // ```
651                // pub(x) use foo::{a, b};
652                // ```
653                //
654                // we will create three items:
655                //
656                // ```
657                // pub(x) use foo::a;
658                // pub(x) use foo::b;
659                // pub(x) use foo::{}; // <-- this is called the `ListStem`
660                // ```
661                //
662                // The first two are produced by recursively invoking
663                // `lower_use_tree` (and indeed there may be things
664                // like `use foo::{a::{b, c}}` and so forth). They
665                // wind up being directly added to
666                // `self.items`. However, the structure of this
667                // function also requires us to return one item, and
668                // for that we return the `{}` import (called the
669                // `ListStem`).
670
671                let span = prefix.span.to(path.span);
672                let prefix = Path { segments, span };
673
674                // Add all the nested `PathListItem`s to the HIR.
675                for &(ref use_tree, id) in trees {
676                    let owner_id = self.owner_id(id);
677
678                    // Each `use` import is an item and thus are owners of the
679                    // names in the path. Up to this point the nested import is
680                    // the current owner, since we want each desugared import to
681                    // own its own names, we have to adjust the owner before
682                    // lowering the rest of the import.
683                    self.with_hir_id_owner(id, |this| {
684                        // `prefix` is lowered multiple times, but in different HIR owners.
685                        // So each segment gets renewed `HirId` with the same
686                        // `ItemLocalId` and the new owner. (See `lower_node_id`)
687                        let kind = this.lower_use_tree(use_tree, &prefix, id, vis_span, attrs);
688                        if !attrs.is_empty() {
689                            this.attrs.insert(hir::ItemLocalId::ZERO, attrs);
690                        }
691
692                        let item = hir::Item {
693                            owner_id,
694                            kind,
695                            vis_span,
696                            span: this.lower_span(use_tree.span()),
697                            eii: find_attr!(attrs, EiiImpl(..) | EiiDeclaration(..)),
698                        };
699                        hir::OwnerNode::Item(this.arena.alloc(item))
700                    });
701                }
702
703                // Condition should match `build_reduced_graph_for_use_tree`.
704                let path = if trees.is_empty()
705                    && !(prefix.segments.is_empty()
706                        || prefix.segments.len() == 1
707                            && prefix.segments[0].ident.name == kw::PathRoot)
708                {
709                    // For empty lists we need to lower the prefix so it is checked for things
710                    // like stability later.
711                    let res = self.lower_import_res(id, span);
712                    self.lower_use_path(res, &prefix, ParamMode::Explicit)
713                } else {
714                    // For non-empty lists we can just drop all the data, the prefix is already
715                    // present in HIR as a part of nested imports.
716                    let span = self.lower_span(span);
717                    self.arena.alloc(hir::UsePath { res: PerNS::default(), segments: &[], span })
718                };
719                hir::ItemKind::Use(path, hir::UseKind::ListStem)
720            }
721        }
722    }
723
724    fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
725        let owner_id = self.current_hir_id_owner;
726        let hir_id: HirId = owner_id.into();
727        let attrs =
728            self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_foreign_item_kind(&i.kind));
729        let (ident, kind) = match &i.kind {
730            ForeignItemKind::Fn(Fn { sig, ident, generics, define_opaque, .. }) => {
731                let fdec = &sig.decl;
732                let itctx = ImplTraitContext::Universal;
733                let (generics, (decl, fn_args)) = self.lower_generics(generics, itctx, |this| {
734                    (
735                        // Disallow `impl Trait` in foreign items.
736                        this.lower_fn_decl(fdec, i.id, sig.span, FnDeclKind::ExternFn, None),
737                        this.lower_fn_params_to_idents(fdec),
738                    )
739                });
740
741                // Unmarked safety in unsafe block defaults to unsafe.
742                let header = self.lower_fn_header(sig.header, hir::Safety::Unsafe, attrs);
743
744                if define_opaque.is_some() {
745                    self.dcx().span_err(i.span, "foreign functions cannot define opaque types");
746                }
747
748                (
749                    ident,
750                    hir::ForeignItemKind::Fn(
751                        hir::FnSig { header, decl, span: self.lower_span(sig.span) },
752                        fn_args,
753                        generics,
754                    ),
755                )
756            }
757            ForeignItemKind::Static(StaticItem {
758                ident,
759                ty,
760                mutability,
761                expr: _,
762                safety,
763                define_opaque,
764                eii_impl: _,
765            }) => {
766                let ty = self
767                    .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
768                let safety = self.lower_safety(*safety, hir::Safety::Unsafe);
769                if define_opaque.is_some() {
770                    self.dcx().span_err(i.span, "foreign statics cannot define opaque types");
771                }
772                (ident, hir::ForeignItemKind::Static(ty, *mutability, safety))
773            }
774            ForeignItemKind::TyAlias(TyAlias { ident, .. }) => (ident, hir::ForeignItemKind::Type),
775            ForeignItemKind::MacCall(_) => { ::core::panicking::panic_fmt(format_args!("macro shouldn\'t exist here")); }panic!("macro shouldn't exist here"),
776        };
777
778        let item = hir::ForeignItem {
779            owner_id,
780            ident: self.lower_ident(*ident),
781            kind,
782            vis_span: self.lower_span(i.vis.span),
783            span: self.lower_span(i.span),
784        };
785        self.arena.alloc(item)
786    }
787
788    fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemId {
789        hir::ForeignItemId { owner_id: self.owner_id(i.id) }
790    }
791
792    fn lower_variant(&mut self, item_kind: &ItemKind, v: &Variant) -> hir::Variant<'hir> {
793        if v.ident.name == kw::Underscore && self.tcx.features().unnamed_enum_variants() {
794            // FIXME(#156628): lower unnamed enum variants to HIR.
795            self.dcx()
796                .struct_span_fatal(v.span, "unnamed enum variants are not yet implemented")
797                .emit()
798        }
799        let hir_id = self.lower_node_id(v.id);
800        self.lower_attrs(hir_id, &v.attrs, v.span, Target::Variant);
801        hir::Variant {
802            hir_id,
803            def_id: self.local_def_id(v.id),
804            data: self.lower_variant_data(hir_id, item_kind, &v.data),
805            disr_expr: v
806                .disr_expr
807                .as_ref()
808                .map(|e| self.lower_anon_const_to_anon_const(e, e.value.span)),
809            ident: self.lower_ident(v.ident),
810            span: self.lower_span(v.span),
811        }
812    }
813
814    fn lower_variant_data(
815        &mut self,
816        parent_id: hir::HirId,
817        item_kind: &ItemKind,
818        vdata: &VariantData,
819    ) -> hir::VariantData<'hir> {
820        match vdata {
821            VariantData::Struct { fields, recovered } => {
822                let fields = self
823                    .arena
824                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
825
826                if let ItemKind::Union(..) = item_kind {
827                    for field in &fields[..] {
828                        if let Some(default) = field.default {
829                            // Unions cannot derive `Default`, and it's not clear how to use default
830                            // field values of unions if that was supported. Therefore, blanket reject
831                            // trying to use field values with unions.
832                            if self.tcx.features().default_field_values() {
833                                self.dcx().emit_err(UnionWithDefault { span: default.span });
834                            } else {
835                                let _ = self.dcx().span_delayed_bug(
836                                default.span,
837                                "expected union default field values feature gate error but none \
838                                was produced",
839                            );
840                            }
841                        }
842                    }
843                }
844
845                hir::VariantData::Struct { fields, recovered: *recovered }
846            }
847            VariantData::Tuple(fields, id) => {
848                let ctor_id = self.lower_node_id(*id);
849                self.alias_attrs(ctor_id, parent_id);
850                let fields = self
851                    .arena
852                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
853                for field in &fields[..] {
854                    if let Some(default) = field.default {
855                        // Default values in tuple struct and tuple variants are not allowed by the
856                        // RFC due to concerns about the syntax, both in the item definition and the
857                        // expression. We could in the future allow `struct S(i32 = 0);` and force
858                        // users to construct the value with `let _ = S { .. };`.
859                        if self.tcx.features().default_field_values() {
860                            self.dcx().emit_err(TupleStructWithDefault { span: default.span });
861                        } else {
862                            let _ = self.dcx().span_delayed_bug(
863                                default.span,
864                                "expected `default values on `struct` fields aren't supported` \
865                                 feature-gate error but none was produced",
866                            );
867                        }
868                    }
869                }
870                hir::VariantData::Tuple(fields, ctor_id, self.local_def_id(*id))
871            }
872            VariantData::Unit(id) => {
873                let ctor_id = self.lower_node_id(*id);
874                self.alias_attrs(ctor_id, parent_id);
875                hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
876            }
877        }
878    }
879
880    pub(super) fn lower_field_def(
881        &mut self,
882        (index, f): (usize, &FieldDef),
883    ) -> hir::FieldDef<'hir> {
884        let ty =
885            self.lower_ty_alloc(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy));
886        let hir_id = self.lower_node_id(f.id);
887        self.lower_attrs(hir_id, &f.attrs, f.span, Target::Field);
888        hir::FieldDef {
889            span: self.lower_span(f.span),
890            hir_id,
891            def_id: self.local_def_id(f.id),
892            ident: match f.ident {
893                Some(ident) => self.lower_ident(ident),
894                // FIXME(jseyfried): positional field hygiene.
895                None => Ident::new(sym::integer(index), self.lower_span(f.span)),
896            },
897            vis_span: self.lower_span(f.vis.span),
898            mut_restriction: self.lower_mut_restriction(f.mut_restriction(), hir_id),
899            default: f
900                .default_value()
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_marker,
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_marker,
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_marker,
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_marker,
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_marker,
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_marker: Option<CoroutineMarker>,
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_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcIntrinsic) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::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_marker) = coroutine_marker 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_marker,
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_marker: CoroutineMarker,
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_marker.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_marker.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_marker: Option<CoroutineMarker>,
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_marker)
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(coroutine_marker) = h.coroutine_marker
1687            && let CoroutineKind::Async = coroutine_marker.kind
1688        {
1689            hir::IsAsync::Async(self.lower_span(coroutine_marker.span))
1690        } else {
1691            hir::IsAsync::NotAsync
1692        };
1693
1694        let safety = self.lower_safety(h.safety, default_safety);
1695
1696        // Treat safe `#[target_feature]` functions as unsafe, but also remember that we did so.
1697        let safety = if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(TargetFeature {
                            was_forced: false, .. }) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, TargetFeature { was_forced: false, .. })
1698            && safety.is_safe()
1699            && !self.tcx.sess.target.is_like_wasm
1700        {
1701            hir::HeaderSafety::SafeTargetFeatures
1702        } else {
1703            safety.into()
1704        };
1705
1706        let constness = self.lower_constness(attrs, h.constness);
1707
1708        hir::FnHeader { safety, asyncness, constness, abi: self.lower_extern(h.ext) }
1709    }
1710
1711    pub(super) fn lower_abi(&mut self, abi_str: StrLit) -> ExternAbi {
1712        let ast::StrLit { symbol_unescaped, span, .. } = abi_str;
1713        let extern_abi = symbol_unescaped.as_str().parse().unwrap_or_else(|_| {
1714            self.error_on_invalid_abi(abi_str);
1715            ExternAbi::Rust
1716        });
1717        let tcx = self.tcx;
1718
1719        // we can't do codegen for unsupported ABIs, so error now so we won't get farther
1720        if !tcx.sess.target.is_abi_supported(extern_abi) {
1721            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!(
1722                tcx.dcx(),
1723                span,
1724                E0570,
1725                "{extern_abi} is not a supported ABI for the current target",
1726            );
1727
1728            if let ExternAbi::Stdcall { unwind } = extern_abi {
1729                let c_abi = ExternAbi::C { unwind };
1730                let system_abi = ExternAbi::System { unwind };
1731                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, \
1732                    use `extern {system_abi}`"
1733                ));
1734            }
1735            err.emit();
1736        }
1737        // Show required feature gate even if we already errored, as the user is likely to build the code
1738        // for the actually intended target next and then they will need the feature gate.
1739        gate_unstable_abi(tcx.sess, tcx.features(), span, extern_abi);
1740        extern_abi
1741    }
1742
1743    pub(super) fn lower_extern(&mut self, ext: Extern) -> ExternAbi {
1744        match ext {
1745            Extern::None => ExternAbi::Rust,
1746            Extern::Implicit(_) => ExternAbi::FALLBACK,
1747            Extern::Explicit(abi, _) => self.lower_abi(abi),
1748        }
1749    }
1750
1751    fn error_on_invalid_abi(&self, abi: StrLit) {
1752        let abi_names = enabled_names(self.tcx.features(), abi.span)
1753            .iter()
1754            .map(|s| Symbol::intern(s))
1755            .collect::<Vec<_>>();
1756        let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1757        self.dcx().emit_err(InvalidAbi {
1758            abi: abi.symbol_unescaped,
1759            span: abi.span,
1760            suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1761                span: abi.span,
1762                suggestion: suggested_name.to_string(),
1763            }),
1764            command: "rustc --print=calling-conventions".to_string(),
1765        });
1766    }
1767
1768    /// Lowers constness or comptime attribute.
1769    /// Whether `const` is allowed here is checked by ast validation.
1770    /// Whether `comptime` is allowed here is checked by the `comptime` attribute parser.
1771    pub(super) fn lower_constness(&mut self, attrs: &[hir::Attribute], c: Const) -> hir::Constness {
1772        let mut constness = match c {
1773            Const::Yes(_) => hir::Constness::Const { always: false },
1774            Const::No => hir::Constness::NotConst,
1775        };
1776
1777        if let Some(&attr_span) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(RustcComptime(span)) => {
                    break 'done Some(span);
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcComptime(span) => span) {
1778            match std::mem::replace(&mut constness, hir::Constness::Const { always: true }) {
1779                hir::Constness::Const { always: true } => {
1780                    {
    ::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")
1781                }
1782                // A function can't be `const` and `comptime` at the same time
1783                hir::Constness::Const { always: false } => {
1784                    let Const::Yes(span) = c else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1785                    self.dcx().emit_err(ConstComptimeFn { span, attr_span });
1786                }
1787                // Good
1788                hir::Constness::NotConst => {}
1789            }
1790        }
1791        constness
1792    }
1793
1794    pub(super) fn lower_safety(&self, s: Safety, default: hir::Safety) -> hir::Safety {
1795        match s {
1796            Safety::Unsafe(_) => hir::Safety::Unsafe,
1797            Safety::Default => default,
1798            Safety::Safe(_) => hir::Safety::Safe,
1799        }
1800    }
1801
1802    fn lower_restriction_kind(
1803        &mut self,
1804        restriction_kind: &RestrictionKind,
1805        hir_id: HirId,
1806        resolving_kind: ResolvingRestrictionKind,
1807    ) -> hir::RestrictionKind<'hir> {
1808        match restriction_kind {
1809            RestrictionKind::Unrestricted => hir::RestrictionKind::Unrestricted,
1810            RestrictionKind::Restricted { path, id, shorthand: _ } => {
1811                let res = self.get_partial_res(*id);
1812                let parent_module = self.tcx.parent_module(hir_id);
1813                if let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) {
1814                    if !self.tcx.is_descendant_of(parent_module, did) {
1815                        // If the restriction path is not an ancestor of the item,
1816                        // emit an error and recover by lowering the restriction to `Unrestricted`.
1817                        self.dcx()
1818                            .create_err(RestrictionAncestorOnly {
1819                                span: path.span,
1820                                kind: resolving_kind,
1821                            })
1822                            .emit();
1823                        hir::RestrictionKind::Unrestricted
1824                    } else {
1825                        hir::RestrictionKind::Restricted(self.arena.alloc(hir::Path {
1826                            res: did,
1827                            segments: self.arena.alloc_from_iter(path.segments.iter().map(
1828                                |segment| {
1829                                    self.lower_path_segment(
1830                                        path.span,
1831                                        segment,
1832                                        ParamMode::Explicit,
1833                                        GenericArgsMode::Err,
1834                                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1835                                        None,
1836                                    )
1837                                },
1838                            )),
1839                            span: self.lower_span(path.span),
1840                        }))
1841                    }
1842                } else {
1843                    self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1844                    hir::RestrictionKind::Unrestricted
1845                }
1846            }
1847        }
1848    }
1849
1850    pub(super) fn lower_impl_restriction(
1851        &mut self,
1852        r: &ImplRestriction,
1853        hir_id: HirId,
1854    ) -> &'hir hir::ImplRestriction<'hir> {
1855        let kind = self.lower_restriction_kind(&r.kind, hir_id, ResolvingRestrictionKind::Impl);
1856        self.arena.alloc(hir::ImplRestriction { kind, span: self.lower_span(r.span) })
1857    }
1858
1859    pub(super) fn lower_mut_restriction(
1860        &mut self,
1861        r: &MutRestriction,
1862        hir_id: HirId,
1863    ) -> &'hir hir::MutRestriction<'hir> {
1864        let kind = self.lower_restriction_kind(&r.kind, hir_id, ResolvingRestrictionKind::Mut);
1865        self.arena.alloc(hir::MutRestriction { kind, span: self.lower_span(r.span) })
1866    }
1867
1868    /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1869    /// the carried impl trait definitions and bounds.
1870    #[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(1870u32),
                                    ::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))]
1871    fn lower_generics<T>(
1872        &mut self,
1873        generics: &Generics,
1874        itctx: ImplTraitContext,
1875        f: impl FnOnce(&mut Self) -> T,
1876    ) -> (&'hir hir::Generics<'hir>, T) {
1877        assert!(self.impl_trait_defs.is_empty());
1878        assert!(self.impl_trait_bounds.is_empty());
1879
1880        let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1881        // We need to make sure that generic params don't have multiple relaxed bounds for the same trait
1882        // across generic param bounds and where bounds.
1883        let mut dedup_map: IndexMap<LocalDefId, _> = Default::default();
1884        predicates.extend(generics.params.iter().filter_map(|param| {
1885            self.lower_generic_bound_predicate(
1886                param.ident,
1887                param.id,
1888                &param.kind,
1889                &param.bounds,
1890                param.colon_span,
1891                generics.span,
1892                RelaxedBoundPolicy::Allowed(
1893                    dedup_map.entry(self.local_def_id(param.id)).or_default(),
1894                ),
1895                itctx,
1896                PredicateOrigin::GenericParam,
1897            )
1898        }));
1899        predicates.extend(generics.where_clause.predicates.iter().map(|predicate| {
1900            self.lower_where_predicate(predicate, &generics.params, &mut dedup_map)
1901        }));
1902
1903        let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> = self
1904            .lower_generic_params_mut(&generics.params, hir::GenericParamSource::Generics)
1905            .collect();
1906
1907        // Introduce extra lifetimes if late resolution tells us to.
1908        let extra_lifetimes = self.owner.extra_lifetime_params(self.owner.id);
1909        params.extend(extra_lifetimes.into_iter().map(|&(ident, node_id, kind)| {
1910            self.lifetime_res_to_generic_param(
1911                ident,
1912                node_id,
1913                kind,
1914                hir::GenericParamSource::Generics,
1915            )
1916        }));
1917
1918        let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1919        let where_clause_span = self.lower_span(generics.where_clause.span);
1920        let span = self.lower_span(generics.span);
1921        let res = f(self);
1922
1923        let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1924        params.extend(impl_trait_defs.into_iter());
1925
1926        let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1927        predicates.extend(impl_trait_bounds.into_iter());
1928
1929        let lowered_generics = self.arena.alloc(hir::Generics {
1930            params: self.arena.alloc_from_iter(params),
1931            predicates: self.arena.alloc_from_iter(predicates),
1932            has_where_clause_predicates,
1933            where_clause_span,
1934            span,
1935        });
1936
1937        (lowered_generics, res)
1938    }
1939
1940    pub(super) fn lower_define_opaque(
1941        &mut self,
1942        hir_id: HirId,
1943        define_opaque: &Option<ThinVec<(NodeId, Path)>>,
1944    ) {
1945        {
    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);
1946        if !hir_id.is_owner() {
    ::core::panicking::panic("assertion failed: hir_id.is_owner()")
};assert!(hir_id.is_owner());
1947        let Some(define_opaque) = define_opaque.as_ref() else {
1948            return;
1949        };
1950        let define_opaque = define_opaque.iter().filter_map(|(id, path)| {
1951            let res = self.get_partial_res(*id);
1952            let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else {
1953                self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1954                return None;
1955            };
1956            let Some(did) = did.as_local() else {
1957                self.dcx().span_err(
1958                    path.span,
1959                    "only opaque types defined in the local crate can be defined",
1960                );
1961                return None;
1962            };
1963            Some((self.lower_span(path.span), did))
1964        });
1965        let define_opaque = self.arena.alloc_from_iter(define_opaque);
1966        self.define_opaque = Some(define_opaque);
1967    }
1968
1969    pub(super) fn lower_generic_bound_predicate(
1970        &mut self,
1971        ident: Ident,
1972        id: NodeId,
1973        kind: &GenericParamKind,
1974        bounds: &[GenericBound],
1975        colon_span: Option<Span>,
1976        parent_span: Span,
1977        rbp: RelaxedBoundPolicy<'_>,
1978        itctx: ImplTraitContext,
1979        origin: PredicateOrigin,
1980    ) -> Option<hir::WherePredicate<'hir>> {
1981        // Do not create a clause if we do not have anything inside it.
1982        if bounds.is_empty() {
1983            return None;
1984        }
1985
1986        let bounds = self.lower_param_bounds(bounds, rbp, itctx);
1987
1988        let param_span = ident.span;
1989
1990        // Reconstruct the span of the entire predicate from the individual generic bounds.
1991        let span_start = colon_span.unwrap_or_else(|| param_span.shrink_to_hi());
1992        let span = bounds.iter().fold(span_start, |span_accum, bound| {
1993            match bound.span().find_ancestor_inside(parent_span) {
1994                Some(bound_span) => span_accum.to(bound_span),
1995                None => span_accum,
1996            }
1997        });
1998        let span = self.lower_span(span);
1999        let hir_id = self.next_id();
2000        let kind = self.arena.alloc(match kind {
2001            GenericParamKind::Const { .. } => return None,
2002            GenericParamKind::Type { .. } => {
2003                let def_id = self.local_def_id(id).to_def_id();
2004                let hir_id = self.next_id();
2005                let res = Res::Def(DefKind::TyParam, def_id);
2006                let ident = self.lower_ident(ident);
2007                let ty_path = self.arena.alloc(hir::Path {
2008                    span: self.lower_span(param_span),
2009                    res,
2010                    segments: self
2011                        .arena
2012                        .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
2013                });
2014                let ty_id = self.next_id();
2015                let bounded_ty =
2016                    self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
2017                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2018                    bounded_ty: self.arena.alloc(bounded_ty),
2019                    bounds,
2020                    bound_generic_params: &[],
2021                    origin,
2022                })
2023            }
2024            GenericParamKind::Lifetime => {
2025                let lt_id = self.next_node_id();
2026                let lifetime =
2027                    self.new_named_lifetime(id, lt_id, ident, LifetimeSource::Other, ident.into());
2028                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2029                    lifetime,
2030                    bounds,
2031                    in_where_clause: false,
2032                })
2033            }
2034        });
2035        Some(hir::WherePredicate { hir_id, span, kind })
2036    }
2037
2038    fn lower_where_predicate(
2039        &mut self,
2040        pred: &WherePredicate,
2041        params: &[ast::GenericParam],
2042        dedup_map: &mut IndexMap<LocalDefId, IndexMap<DefId, Span>>,
2043    ) -> hir::WherePredicate<'hir> {
2044        let hir_id = self.lower_node_id(pred.id);
2045        let span = self.lower_span(pred.span);
2046        self.lower_attrs(hir_id, &pred.attrs, span, Target::WherePredicate);
2047        let kind = self.arena.alloc(match &pred.kind {
2048            WherePredicateKind::BoundPredicate(WhereBoundPredicate {
2049                bound_generic_params,
2050                bounded_ty,
2051                bounds,
2052            }) => {
2053                let rbp = if bound_generic_params.is_empty()
2054                    && let Some(res) =
2055                        self.get_partial_res(bounded_ty.id).and_then(|r| r.full_res())
2056                    && let Res::Def(DefKind::TyParam, def_id) = res
2057                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2058                {
2059                    RelaxedBoundPolicy::Allowed(dedup_map.entry(def_id.expect_local()).or_default())
2060                } else {
2061                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::WhereBound)
2062                };
2063                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2064                    bound_generic_params: self.lower_generic_params(
2065                        bound_generic_params,
2066                        hir::GenericParamSource::Binder,
2067                    ),
2068                    bounded_ty: self.lower_ty_alloc(
2069                        bounded_ty,
2070                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2071                    ),
2072                    bounds: self.lower_param_bounds(
2073                        bounds,
2074                        rbp,
2075                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2076                    ),
2077                    origin: PredicateOrigin::WhereClause,
2078                })
2079            }
2080            WherePredicateKind::RegionPredicate(WhereRegionPredicate { lifetime, bounds }) => {
2081                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2082                    lifetime: self.lower_lifetime(
2083                        lifetime,
2084                        LifetimeSource::Other,
2085                        lifetime.ident.into(),
2086                    ),
2087                    bounds: self.lower_param_bounds(
2088                        bounds,
2089                        RelaxedBoundPolicy::Allowed(&mut Default::default()),
2090                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2091                    ),
2092                    in_where_clause: true,
2093                })
2094            }
2095        });
2096        hir::WherePredicate { hir_id, span, kind }
2097    }
2098}