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::middle::resolve::ResolverAstLowering;
12use rustc_middle::ty::TyCtxt;
13use rustc_middle::ty::data_structures::IndexMap;
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, span_bug, 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
65        let info = lctx.curr_owner.into_owner_info(self.tcx, item);
66        hir::MaybeOwner::Owner(lctx.arena.alloc(info))
67    }
68
69    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_ast_lowering/src/item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(69u32),
                                    ::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.curr_owner.owner_id, &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))]
70    pub(super) fn lower_crate(&mut self, c: &Crate) -> hir::MaybeOwner<'hir> {
71        self.with_lctx(CRATE_NODE_ID, |lctx| {
72            debug_assert_eq!(lctx.curr_owner.owner_id, CRATE_OWNER_ID);
73            let module = lctx.lower_mod(&c.items, &c.spans);
74            lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, c.spans.inner_span, Target::Crate);
75            hir::OwnerNode::Crate(module)
76        })
77    }
78
79    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_ast_lowering/src/item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(79u32),
                                    ::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))]
80    pub(super) fn lower_item(&mut self, item: &Item) -> hir::MaybeOwner<'hir> {
81        self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
82    }
83
84    pub(super) fn lower_trait_item(&mut self, item: &AssocItem) -> hir::MaybeOwner<'hir> {
85        self.with_lctx(item.id, |lctx| hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)))
86    }
87
88    pub(super) fn lower_impl_item(&mut self, item: &AssocItem) -> hir::MaybeOwner<'hir> {
89        self.with_lctx(item.id, |lctx| hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)))
90    }
91
92    pub(super) fn lower_foreign_item(&mut self, item: &ForeignItem) -> hir::MaybeOwner<'hir> {
93        self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
94    }
95}
96
97impl<'hir> LoweringContext<'_, 'hir> {
98    pub(super) fn lower_mod(
99        &mut self,
100        items: &[Box<Item>],
101        spans: &ModSpans,
102    ) -> &'hir hir::Mod<'hir> {
103        self.arena.alloc(hir::Mod {
104            spans: hir::ModSpans {
105                inner_span: self.lower_span(spans.inner_span),
106                inject_use_span: self.lower_span(spans.inject_use_span),
107            },
108            item_ids: self.arena.alloc_from_iter(items.iter().map(|x| self.lower_item_ref(x))),
109        })
110    }
111
112    pub(super) fn lower_item_ref(&mut self, i: &Item) -> hir::ItemId {
113        hir::ItemId { owner_id: self.owner_id(i.id) }
114    }
115
116    fn lower_eii_decl(
117        &mut self,
118        id: NodeId,
119        name: Ident,
120        EiiDecl { foreign_item, impl_unsafe }: &EiiDecl,
121    ) -> Option<hir::attrs::EiiDecl> {
122        self.lower_path_simple_eii(id, foreign_item).map(|did| hir::attrs::EiiDecl {
123            foreign_item: did,
124            impl_unsafe: *impl_unsafe,
125            name,
126        })
127    }
128
129    fn lower_eii_impl(
130        &mut self,
131        EiiImpl {
132            node_id,
133            eii_macro_path,
134            impl_safety,
135            span,
136            inner_span,
137            is_default,
138            known_eii_macro_resolution,
139        }: &EiiImpl,
140    ) -> hir::attrs::EiiImpl {
141        let resolution = if let Some(target) = known_eii_macro_resolution
142            && let Some(foreign_item_did) = self.lower_path_simple_eii(*node_id, target)
143        {
144            EiiImplResolution::Known(foreign_item_did)
145        } else if let Some(macro_did) = self.lower_path_simple_eii(*node_id, eii_macro_path) {
146            EiiImplResolution::Macro(macro_did)
147        } else {
148            EiiImplResolution::Error(
149                self.dcx().span_delayed_bug(*span, "eii never resolved without errors given"),
150            )
151        };
152
153        hir::attrs::EiiImpl {
154            span: self.lower_span(*span),
155            inner_span: self.lower_span(*inner_span),
156            impl_unsafe_span: match *impl_safety {
157                Safety::Unsafe(span) => Some(self.lower_span(span)),
158                Safety::Safe(_) | Safety::Default => None,
159            },
160            is_default: *is_default,
161            resolution,
162        }
163    }
164
165    fn generate_extra_attrs_for_item_kind(
166        &mut self,
167        id: NodeId,
168        i: &ItemKind,
169    ) -> Vec<hir::Attribute> {
170        match i {
171            ItemKind::Fn(Fn { eii_impl: None, .. })
172            | ItemKind::Static(StaticItem { eii_impl: None, .. }) => Vec::new(),
173            ItemKind::Fn(Fn { eii_impl: Some(eii_impl), .. })
174            | ItemKind::Static(StaticItem { eii_impl: Some(eii_impl), .. }) => {
175                ::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(
176                    self.lower_eii_impl(eii_impl),
177                )))]
178            }
179            ItemKind::MacroDef(name, MacroDef { eii_declaration: Some(target), .. }) => self
180                .lower_eii_decl(id, *name, target)
181                .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))])
182                .unwrap_or_default(),
183
184            ItemKind::ExternCrate(..)
185            | ItemKind::Use(..)
186            | ItemKind::Const(..)
187            | ItemKind::ConstBlock(..)
188            | ItemKind::Mod(..)
189            | ItemKind::ForeignMod(..)
190            | ItemKind::GlobalAsm(..)
191            | ItemKind::TyAlias(..)
192            | ItemKind::Enum(..)
193            | ItemKind::Struct(..)
194            | ItemKind::Union(..)
195            | ItemKind::Trait(..)
196            | ItemKind::TraitAlias(..)
197            | ItemKind::Impl(..)
198            | ItemKind::MacCall(..)
199            | ItemKind::MacroDef(..)
200            | ItemKind::Delegation(..)
201            | ItemKind::DelegationMac(..)
202            | ItemKind::TestBinderConstraints(..) => Vec::new(),
203        }
204    }
205
206    fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
207        let owner_id = self.curr_owner.owner_id;
208        let hir_id: HirId = owner_id.into();
209        let vis_span = self.lower_span(i.vis.span);
210
211        let extra_hir_attributes = self.generate_extra_attrs_for_item_kind(i.id, &i.kind);
212        let attrs = self.lower_attrs_with_extra(
213            hir_id,
214            &i.attrs,
215            i.span,
216            Target::from_ast_item(i),
217            Some(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                define_opaque,
276            }) => {
277                let ident = self.lower_ident(*ident);
278                let (generics, (ty, rhs)) = self.lower_generics(
279                    generics,
280                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
281                    |this| {
282                        let ty = this.lower_ty_alloc(
283                            ty,
284                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
285                        );
286                        let rhs = this.lower_const_item_rhs(body, span);
287                        (ty, rhs)
288                    },
289                );
290                self.lower_define_opaque(hir_id, &define_opaque);
291                hir::ItemKind::Const(ident, generics, ty, rhs)
292            }
293            ItemKind::ConstBlock(ConstBlockItem { span, id, block }) => hir::ItemKind::Const(
294                self.lower_ident(ConstBlockItem::IDENT),
295                hir::Generics::empty(),
296                self.arena.alloc(self.ty_tup(DUMMY_SP, &[])),
297                hir::ConstItemRhs::Body({
298                    let body = hir::Expr {
299                        hir_id: self.lower_node_id(*id),
300                        kind: hir::ExprKind::Block(self.lower_block(block, false), None),
301                        span: self.lower_span(*span),
302                    };
303                    self.record_body(&[], body)
304                }),
305            ),
306            ItemKind::Fn(Fn {
307                sig: FnSig { decl, header, span: fn_sig_span },
308                ident,
309                generics,
310                body,
311                contract,
312                define_opaque,
313                ..
314            }) => {
315                self.with_new_scopes(*fn_sig_span, |this| {
316                    // Note: we don't need to change the return type from `T` to
317                    // `impl Future<Output = T>` here because lower_body
318                    // only cares about the input argument patterns in the function
319                    // declaration (decl), not the return types.
320                    let coroutine_marker = header.coroutine_marker;
321                    let body_id = this.lower_maybe_coroutine_body(
322                        *fn_sig_span,
323                        span,
324                        hir_id,
325                        decl,
326                        coroutine_marker,
327                        body.as_deref(),
328                        attrs,
329                        contract.as_deref(),
330                    );
331
332                    let itctx = ImplTraitContext::Universal;
333                    let (generics, decl) = this.lower_generics(generics, itctx, |this| {
334                        this.lower_fn_decl(decl, id, FnDeclKind::Fn, coroutine_marker)
335                    });
336                    let sig = hir::FnSig {
337                        decl,
338                        header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
339                        span: this.lower_span(*fn_sig_span),
340                    };
341                    this.lower_define_opaque(hir_id, define_opaque);
342                    let ident = this.lower_ident(*ident);
343                    hir::ItemKind::Fn {
344                        ident,
345                        sig,
346                        generics,
347                        body: body_id,
348                        has_body: body.is_some(),
349                    }
350                })
351            }
352            ItemKind::Mod(_, ident, mod_kind) => {
353                let ident = self.lower_ident(*ident);
354                match mod_kind {
355                    ModKind::Loaded(items, _, spans) => {
356                        hir::ItemKind::Mod(ident, self.lower_mod(items, spans))
357                    }
358                    ModKind::Unloaded => {
    ::core::panicking::panic_fmt(format_args!("`mod` items should have been loaded by now"));
}panic!("`mod` items should have been loaded by now"),
359                }
360            }
361            ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
362                abi: fm.abi.map_or(ExternAbi::FALLBACK, |abi| self.lower_abi(abi)),
363                items: self
364                    .arena
365                    .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
366            },
367            ItemKind::GlobalAsm(asm) => {
368                let asm = self.lower_inline_asm(span, asm);
369                let fake_body =
370                    self.lower_body(|this| (&[], this.expr(span, hir::ExprKind::InlineAsm(asm))));
371                hir::ItemKind::GlobalAsm { asm, fake_body }
372            }
373            ItemKind::TyAlias(TyAlias { ident, generics, after_where_clause, ty, .. }) => {
374                // We lower
375                //
376                // type Foo = impl Trait
377                //
378                // to
379                //
380                // type Foo = Foo1
381                // opaque type Foo1: Trait
382                let ident = self.lower_ident(*ident);
383                let mut generics = generics.clone();
384                add_ty_alias_where_clause(&mut generics, after_where_clause, true);
385                let (generics, ty) = self.lower_generics(
386                    &generics,
387                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
388                    |this| match ty {
389                        None => {
390                            let guar = this.dcx().span_delayed_bug(
391                                span,
392                                "expected to lower type alias type, but it was missing",
393                            );
394                            this.arena.alloc(this.ty(span, hir::TyKind::Err(guar)))
395                        }
396                        Some(ty) => this.lower_ty_alloc(
397                            ty,
398                            ImplTraitContext::OpaqueTy {
399                                origin: hir::OpaqueTyOrigin::TyAlias {
400                                    parent: this.curr_owner.owner.def_id,
401                                    in_assoc_ty: false,
402                                },
403                            },
404                        ),
405                    },
406                );
407                hir::ItemKind::TyAlias(ident, generics, ty)
408            }
409            ItemKind::Enum(ident, generics, enum_definition) => {
410                let ident = self.lower_ident(*ident);
411                let (generics, variants) = self.lower_generics(
412                    generics,
413                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
414                    |this| {
415                        this.arena.alloc_from_iter(
416                            enum_definition.variants.iter().map(|x| this.lower_variant(i, x)),
417                        )
418                    },
419                );
420                hir::ItemKind::Enum(ident, generics, hir::EnumDef { variants })
421            }
422            ItemKind::Struct(ident, generics, struct_def) => {
423                let ident = self.lower_ident(*ident);
424                let (generics, struct_def) = self.lower_generics(
425                    generics,
426                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
427                    |this| this.lower_variant_data(hir_id, i, struct_def),
428                );
429                hir::ItemKind::Struct(ident, generics, struct_def)
430            }
431            ItemKind::Union(ident, generics, vdata) => {
432                let ident = self.lower_ident(*ident);
433                let (generics, vdata) = self.lower_generics(
434                    generics,
435                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
436                    |this| this.lower_variant_data(hir_id, i, vdata),
437                );
438                hir::ItemKind::Union(ident, generics, vdata)
439            }
440            ItemKind::Impl(Impl {
441                generics: ast_generics,
442                of_trait,
443                self_ty: ty,
444                items: impl_items,
445                constness,
446            }) => {
447                // Lower the "impl header" first. This ordering is important
448                // for in-band lifetimes! Consider `'a` here:
449                //
450                //     impl Foo<'a> for u32 {
451                //         fn method(&'a self) { .. }
452                //     }
453                //
454                // Because we start by lowering the `Foo<'a> for u32`
455                // part, we will add `'a` to the list of generics on
456                // the impl. When we then encounter it later in the
457                // method, it will not be considered an in-band
458                // lifetime to be added, but rather a reference to a
459                // parent lifetime.
460                let itctx = ImplTraitContext::Universal;
461                let (generics, (of_trait, lowered_ty)) =
462                    self.lower_generics(ast_generics, itctx, |this| {
463                        let of_trait = of_trait
464                            .as_deref()
465                            .map(|of_trait| this.lower_trait_impl_header(of_trait));
466
467                        let lowered_ty = this.lower_ty_alloc(
468                            ty,
469                            ImplTraitContext::Disallowed(ImplTraitPosition::ImplSelf),
470                        );
471
472                        (of_trait, lowered_ty)
473                    });
474
475                let new_impl_items = self
476                    .arena
477                    .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
478
479                let constness = self.lower_constness(attrs, *constness);
480
481                hir::ItemKind::Impl(hir::Impl {
482                    generics,
483                    of_trait,
484                    self_ty: lowered_ty,
485                    items: new_impl_items,
486                    constness,
487                })
488            }
489            ItemKind::Trait(Trait {
490                impl_restriction,
491                constness,
492                is_auto,
493                safety,
494                ident,
495                generics,
496                bounds,
497                items,
498            }) => {
499                let constness = self.lower_constness(attrs, *constness);
500                let impl_restriction = self.lower_impl_restriction(impl_restriction, hir_id);
501                let ident = self.lower_ident(*ident);
502                let (generics, (safety, items, bounds)) = self.lower_generics(
503                    generics,
504                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
505                    |this| {
506                        let bounds = this.lower_param_bounds(
507                            bounds,
508                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::SuperTrait),
509                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
510                        );
511                        let items = this.arena.alloc_from_iter(
512                            items.iter().map(|item| this.lower_trait_item_ref(item)),
513                        );
514                        let safety = this.lower_safety(*safety, hir::Safety::Safe);
515                        (safety, items, bounds)
516                    },
517                );
518                hir::ItemKind::Trait {
519                    impl_restriction,
520                    constness,
521                    is_auto: *is_auto,
522                    safety,
523                    ident,
524                    generics,
525                    bounds,
526                    items,
527                }
528            }
529            ItemKind::TraitAlias(TraitAlias { constness, ident, generics, bounds }) => {
530                let constness = self.lower_constness(attrs, *constness);
531                let ident = self.lower_ident(*ident);
532                let (generics, bounds) = self.lower_generics(
533                    generics,
534                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
535                    |this| {
536                        this.lower_param_bounds(
537                            bounds,
538                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitAlias),
539                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
540                        )
541                    },
542                );
543                hir::ItemKind::TraitAlias(constness, ident, generics, bounds)
544            }
545            ItemKind::MacroDef(ident, MacroDef { body, macro_rules, eii_declaration: _ }) => {
546                let ident = self.lower_ident(*ident);
547                let body = Box::new(self.lower_delim_args(body));
548                let def_id = self.curr_owner.owner.def_id;
549                let def_kind = self.tcx.def_kind(def_id);
550                let DefKind::Macro(macro_kinds) = def_kind else {
551                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("expected DefKind::Macro for macro item, found {0}",
                def_kind.descr(def_id.to_def_id()))));
};unreachable!(
552                        "expected DefKind::Macro for macro item, found {}",
553                        def_kind.descr(def_id.to_def_id())
554                    );
555                };
556                let macro_def = self.arena.alloc(ast::MacroDef {
557                    body,
558                    macro_rules: *macro_rules,
559                    eii_declaration: None,
560                });
561                hir::ItemKind::Macro(ident, macro_def, macro_kinds)
562            }
563            ItemKind::Delegation(delegation) => {
564                let delegation_results = self.lower_delegation(delegation);
565                hir::ItemKind::Fn {
566                    sig: delegation_results.sig,
567                    ident: delegation_results.ident,
568                    generics: delegation_results.generics,
569                    body: delegation_results.body_id,
570                    has_body: true,
571                }
572            }
573            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
574                {
    ::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
575            }
576            ItemKind::TestBinderConstraints(TestBinderConstraints { generics, body }) => {
577                let (generics, body) = self.lower_generics(
578                    generics,
579                    ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
580                    |this| this.lower_test_binder_body(body),
581                );
582                hir::ItemKind::TestBinderConstraints { generics, body: self.arena.alloc(body) }
583            }
584        }
585    }
586
587    fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
588        let res = self.get_partial_res(id)?;
589        let Some(did) = res.expect_full_res().opt_def_id() else {
590            self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
591            return None;
592        };
593
594        Some(did)
595    }
596
597    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_ast_lowering/src/item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(597u32),
                                    ::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 }
                            }
                            _ =>
                                bug_impl(Some(path.span),
                                    format_args!("bad glob res {0:?}", res),
                                    Location::caller()),
                        };
                    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 use_tree in trees {
                        let id = use_tree.id;
                        let owner_id = self.owner_id(id);
                        self.with_hir_id_owner(id,
                            |this|
                                {
                                    let kind =
                                        this.lower_use_tree(&use_tree.inner, &prefix, id, vis_span,
                                            attrs);
                                    if !attrs.is_empty() {
                                        this.curr_owner.attrs.insert(hir::ItemLocalId::ZERO, attrs);
                                    }
                                    let item =
                                        hir::Item {
                                            owner_id,
                                            kind,
                                            vis_span,
                                            span: this.lower_span(use_tree.inner.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))]
598    fn lower_use_tree(
599        &mut self,
600        tree: &UseTree,
601        prefix: &Path,
602        id: NodeId,
603        vis_span: Span,
604        attrs: &'hir [hir::Attribute],
605    ) -> hir::ItemKind<'hir> {
606        let path = &tree.prefix;
607        let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
608
609        match tree.kind {
610            UseTreeKind::Simple(rename) => {
611                let mut ident = tree.ident();
612
613                // First, apply the prefix to the path.
614                let mut path = Path { segments, span: path.span };
615
616                // Correctly resolve `self` imports.
617                if path.segments.len() > 1
618                    && path.segments.last().unwrap().ident.name == kw::SelfLower
619                {
620                    let _ = path.segments.pop();
621                    if rename.is_none() {
622                        ident = path.segments.last().unwrap().ident;
623                    }
624                }
625
626                let res = self.lower_import_res(id, path.span);
627                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
628                let ident = self.lower_ident(ident);
629                hir::ItemKind::Use(path, hir::UseKind::Single(ident))
630            }
631            UseTreeKind::Glob(_) => {
632                let res = self.expect_full_res(id);
633                let res = self.lower_res(res);
634                // Put the result in the appropriate namespace.
635                let res = match res {
636                    Res::Def(DefKind::Mod | DefKind::Trait, _) => {
637                        PerNS { type_ns: Some(res), value_ns: None, macro_ns: None }
638                    }
639                    Res::Def(DefKind::Enum, _) => {
640                        PerNS { type_ns: None, value_ns: Some(res), macro_ns: None }
641                    }
642                    Res::Err => {
643                        // Propagate the error to all namespaces, just to be sure.
644                        let err = Some(Res::Err);
645                        PerNS { type_ns: err, value_ns: err, macro_ns: err }
646                    }
647                    _ => span_bug!(path.span, "bad glob res {:?}", res),
648                };
649                let path = Path { segments, span: path.span };
650                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
651                hir::ItemKind::Use(path, hir::UseKind::Glob)
652            }
653            UseTreeKind::Nested { items: ref trees, .. } => {
654                // Nested imports are desugared into simple imports.
655                // So, if we start with
656                //
657                // ```
658                // pub(x) use foo::{a, b};
659                // ```
660                //
661                // we will create three items:
662                //
663                // ```
664                // pub(x) use foo::a;
665                // pub(x) use foo::b;
666                // pub(x) use foo::{}; // <-- this is called the `ListStem`
667                // ```
668                //
669                // The first two are produced by recursively invoking
670                // `lower_use_tree` (and indeed there may be things
671                // like `use foo::{a::{b, c}}` and so forth). They
672                // wind up being directly added to
673                // `self.items`. However, the structure of this
674                // function also requires us to return one item, and
675                // for that we return the `{}` import (called the
676                // `ListStem`).
677
678                let span = prefix.span.to(path.span);
679                let prefix = Path { segments, span };
680
681                // Add all the nested `PathListItem`s to the HIR.
682                for use_tree in trees {
683                    let id = use_tree.id;
684                    let owner_id = self.owner_id(id);
685
686                    // Each `use` import is an item and thus are owners of the
687                    // names in the path. Up to this point the nested import is
688                    // the current owner, since we want each desugared import to
689                    // own its own names, we have to adjust the owner before
690                    // lowering the rest of the import.
691                    self.with_hir_id_owner(id, |this| {
692                        // `prefix` is lowered multiple times, but in different HIR owners.
693                        // So each segment gets renewed `HirId` with the same
694                        // `ItemLocalId` and the new owner. (See `lower_node_id`)
695                        let kind =
696                            this.lower_use_tree(&use_tree.inner, &prefix, id, vis_span, attrs);
697                        if !attrs.is_empty() {
698                            this.curr_owner.attrs.insert(hir::ItemLocalId::ZERO, attrs);
699                        }
700
701                        let item = hir::Item {
702                            owner_id,
703                            kind,
704                            vis_span,
705                            span: this.lower_span(use_tree.inner.span()),
706                            eii: find_attr!(attrs, EiiImpl(..) | EiiDeclaration(..)),
707                        };
708                        hir::OwnerNode::Item(this.arena.alloc(item))
709                    });
710                }
711
712                // Condition should match `build_reduced_graph_for_use_tree`.
713                let path = if trees.is_empty()
714                    && !(prefix.segments.is_empty()
715                        || prefix.segments.len() == 1
716                            && prefix.segments[0].ident.name == kw::PathRoot)
717                {
718                    // For empty lists we need to lower the prefix so it is checked for things
719                    // like stability later.
720                    let res = self.lower_import_res(id, span);
721                    self.lower_use_path(res, &prefix, ParamMode::Explicit)
722                } else {
723                    // For non-empty lists we can just drop all the data, the prefix is already
724                    // present in HIR as a part of nested imports.
725                    let span = self.lower_span(span);
726                    self.arena.alloc(hir::UsePath { res: PerNS::default(), segments: &[], span })
727                };
728                hir::ItemKind::Use(path, hir::UseKind::ListStem)
729            }
730        }
731    }
732
733    fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
734        let owner_id = self.curr_owner.owner_id;
735        let hir_id: HirId = owner_id.into();
736        let attrs =
737            self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_foreign_item_kind(&i.kind));
738        let (ident, kind) = match &i.kind {
739            ForeignItemKind::Fn(Fn { sig, ident, generics, define_opaque, .. }) => {
740                let fdec = &sig.decl;
741                let itctx = ImplTraitContext::Universal;
742                let (generics, (decl, fn_args)) = self.lower_generics(generics, itctx, |this| {
743                    (
744                        // Disallow `impl Trait` in foreign items.
745                        this.lower_fn_decl(fdec, i.id, FnDeclKind::ExternFn, None),
746                        this.lower_fn_params_to_idents(fdec),
747                    )
748                });
749
750                // Unmarked safety in unsafe block defaults to unsafe.
751                let header = self.lower_fn_header(sig.header, hir::Safety::Unsafe, attrs);
752
753                if define_opaque.is_some() {
754                    self.dcx().span_err(i.span, "foreign functions cannot define opaque types");
755                }
756
757                (
758                    ident,
759                    hir::ForeignItemKind::Fn(
760                        hir::FnSig { header, decl, span: self.lower_span(sig.span) },
761                        fn_args,
762                        generics,
763                    ),
764                )
765            }
766            ForeignItemKind::Static(StaticItem {
767                ident,
768                ty,
769                mutability,
770                expr: _,
771                safety,
772                define_opaque,
773                eii_impl: _,
774            }) => {
775                let ty = self
776                    .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
777                let safety = self.lower_safety(*safety, hir::Safety::Unsafe);
778                if define_opaque.is_some() {
779                    self.dcx().span_err(i.span, "foreign statics cannot define opaque types");
780                }
781                (ident, hir::ForeignItemKind::Static(ty, *mutability, safety))
782            }
783            ForeignItemKind::TyAlias(TyAlias { ident, .. }) => (ident, hir::ForeignItemKind::Type),
784            ForeignItemKind::MacCall(_) => { ::core::panicking::panic_fmt(format_args!("macro shouldn\'t exist here")); }panic!("macro shouldn't exist here"),
785        };
786
787        let item = hir::ForeignItem {
788            owner_id,
789            ident: self.lower_ident(*ident),
790            kind,
791            vis_span: self.lower_span(i.vis.span),
792            span: self.lower_span(i.span),
793        };
794        self.arena.alloc(item)
795    }
796
797    fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemId {
798        hir::ForeignItemId { owner_id: self.owner_id(i.id) }
799    }
800
801    fn lower_variant(&mut self, item_kind: &ItemKind, v: &Variant) -> hir::Variant<'hir> {
802        if v.ident.name == kw::Underscore && self.tcx.features().unnamed_enum_variants() {
803            // FIXME(#156628): lower unnamed enum variants to HIR.
804            self.dcx().span_fatal(v.span, "unnamed enum variants are not yet implemented");
805        }
806        let hir_id = self.lower_node_id(v.id);
807        self.lower_attrs(hir_id, &v.attrs, v.span, Target::Variant);
808        hir::Variant {
809            hir_id,
810            def_id: self.local_def_id(v.id),
811            data: self.lower_variant_data(hir_id, item_kind, &v.data),
812            disr_expr: v
813                .disr_expr
814                .as_ref()
815                .map(|e| self.lower_anon_const_to_anon_const(e, e.value.span)),
816            ident: self.lower_ident(v.ident),
817            span: self.lower_span(v.span),
818        }
819    }
820
821    fn lower_variant_data(
822        &mut self,
823        parent_id: hir::HirId,
824        item_kind: &ItemKind,
825        vdata: &VariantData,
826    ) -> hir::VariantData<'hir> {
827        match vdata {
828            VariantData::Struct { fields, recovered } => {
829                let fields = self
830                    .arena
831                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
832
833                if let ItemKind::Union(..) = item_kind {
834                    for field in &fields[..] {
835                        if let Some(default) = field.default {
836                            // Unions cannot derive `Default`, and it's not clear how to use default
837                            // field values of unions if that was supported. Therefore, blanket reject
838                            // trying to use field values with unions.
839                            if self.tcx.features().default_field_values() {
840                                self.dcx().emit_err(UnionWithDefault { span: default.span });
841                            } else {
842                                let _ = self.dcx().span_delayed_bug(
843                                default.span,
844                                "expected union default field values feature gate error but none \
845                                was produced",
846                            );
847                            }
848                        }
849                    }
850                }
851
852                hir::VariantData::Struct { fields, recovered: *recovered }
853            }
854            VariantData::Tuple(fields, id) => {
855                let ctor_id = self.lower_node_id(*id);
856                self.alias_attrs(ctor_id, parent_id);
857                let fields = self
858                    .arena
859                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
860                for field in &fields[..] {
861                    if let Some(default) = field.default {
862                        // Default values in tuple struct and tuple variants are not allowed by the
863                        // RFC due to concerns about the syntax, both in the item definition and the
864                        // expression. We could in the future allow `struct S(i32 = 0);` and force
865                        // users to construct the value with `let _ = S { .. };`.
866                        if self.tcx.features().default_field_values() {
867                            self.dcx().emit_err(TupleStructWithDefault { span: default.span });
868                        } else {
869                            let _ = self.dcx().span_delayed_bug(
870                                default.span,
871                                "expected `default values on `struct` fields aren't supported` \
872                                 feature-gate error but none was produced",
873                            );
874                        }
875                    }
876                }
877                hir::VariantData::Tuple(fields, ctor_id, self.local_def_id(*id))
878            }
879            VariantData::Unit(id) => {
880                let ctor_id = self.lower_node_id(*id);
881                self.alias_attrs(ctor_id, parent_id);
882                hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
883            }
884        }
885    }
886
887    pub(super) fn lower_field_def(
888        &mut self,
889        (index, f): (usize, &FieldDef),
890    ) -> hir::FieldDef<'hir> {
891        let ty =
892            self.lower_ty_alloc(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy));
893        let hir_id = self.lower_node_id(f.id);
894        self.lower_attrs(hir_id, &f.attrs, f.span, Target::Field);
895        hir::FieldDef {
896            span: self.lower_span(f.span),
897            hir_id,
898            def_id: self.local_def_id(f.id),
899            ident: match f.ident {
900                Some(ident) => self.lower_ident(ident),
901                // FIXME(jseyfried): positional field hygiene.
902                None => Ident::new(sym::integer(index), self.lower_span(f.span)),
903            },
904            vis_span: self.lower_span(f.vis.span),
905            mut_restriction: self.lower_mut_restriction(f.mut_restriction(), hir_id),
906            default: f
907                .default_value()
908                .map(|v| self.lower_anon_const_to_anon_const(v, v.value.span)),
909            ty,
910            safety: self.lower_safety(f.safety(), hir::Safety::Safe),
911        }
912    }
913
914    fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
915        let trait_item_def_id = self.curr_owner.owner_id;
916        let hir_id: HirId = trait_item_def_id.into();
917        let attrs = self.lower_attrs(
918            hir_id,
919            &i.attrs,
920            i.span,
921            Target::from_assoc_item_kind(&i.kind, AssocCtxt::Trait),
922        );
923
924        let (ident, generics, kind, has_value) = match &i.kind {
925            AssocItemKind::Const(ConstItem {
926                ident, generics, ty, body, define_opaque, ..
927            }) => {
928                let (generics, kind) = self.lower_generics(
929                    generics,
930                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
931                    |this| {
932                        let ty = this.lower_ty_alloc(
933                            ty,
934                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
935                        );
936                        // Trait associated consts don't need an expression/body.
937                        let rhs = if body.is_some() {
938                            Some(this.lower_const_item_rhs(body, i.span))
939                        } else {
940                            None
941                        };
942                        hir::TraitItemKind::Const(ty, rhs)
943                    },
944                );
945
946                if define_opaque.is_some() {
947                    if body.is_some() {
948                        self.lower_define_opaque(hir_id, &define_opaque);
949                    } else {
950                        self.dcx().span_err(
951                            i.span,
952                            "only trait consts with default bodies can define opaque types",
953                        );
954                    }
955                }
956
957                (*ident, generics, kind, body.is_some())
958            }
959            AssocItemKind::Fn(Fn { sig, ident, generics, body: None, define_opaque, .. }) => {
960                // FIXME(contracts): Deny contract here since it won't apply to
961                // any impl method or callees.
962                let idents = self.lower_fn_params_to_idents(&sig.decl);
963                let (generics, sig) = self.lower_method_sig(
964                    generics,
965                    sig,
966                    i.id,
967                    FnDeclKind::Trait,
968                    sig.header.coroutine_marker,
969                    attrs,
970                );
971                if define_opaque.is_some() {
972                    self.dcx().span_err(
973                        i.span,
974                        "only trait methods with default bodies can define opaque types",
975                    );
976                }
977                (
978                    *ident,
979                    generics,
980                    hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(idents)),
981                    false,
982                )
983            }
984            AssocItemKind::Fn(Fn {
985                sig,
986                ident,
987                generics,
988                body: Some(body),
989                contract,
990                define_opaque,
991                ..
992            }) => {
993                let body_id = self.lower_maybe_coroutine_body(
994                    sig.span,
995                    i.span,
996                    hir_id,
997                    &sig.decl,
998                    sig.header.coroutine_marker,
999                    Some(body),
1000                    attrs,
1001                    contract.as_deref(),
1002                );
1003                let (generics, sig) = self.lower_method_sig(
1004                    generics,
1005                    sig,
1006                    i.id,
1007                    FnDeclKind::Trait,
1008                    sig.header.coroutine_marker,
1009                    attrs,
1010                );
1011                self.lower_define_opaque(hir_id, &define_opaque);
1012                (
1013                    *ident,
1014                    generics,
1015                    hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)),
1016                    true,
1017                )
1018            }
1019            AssocItemKind::Type(TyAlias {
1020                ident,
1021                generics,
1022                after_where_clause,
1023                bounds,
1024                ty,
1025                ..
1026            }) => {
1027                let mut generics = generics.clone();
1028                add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1029                let (generics, kind) = self.lower_generics(
1030                    &generics,
1031                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1032                    |this| {
1033                        let ty = ty.as_ref().map(|x| {
1034                            this.lower_ty_alloc(
1035                                x,
1036                                ImplTraitContext::Disallowed(ImplTraitPosition::AssocTy),
1037                            )
1038                        });
1039                        hir::TraitItemKind::Type(
1040                            this.lower_param_bounds(
1041                                bounds,
1042                                RelaxedBoundPolicy::Allowed(&mut Default::default()),
1043                                ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1044                            ),
1045                            ty,
1046                        )
1047                    },
1048                );
1049                (*ident, generics, kind, ty.is_some())
1050            }
1051            AssocItemKind::Delegation(delegation) => {
1052                let delegation_results = self.lower_delegation(delegation);
1053                let item_kind = hir::TraitItemKind::Fn(
1054                    delegation_results.sig,
1055                    hir::TraitFn::Provided(delegation_results.body_id),
1056                );
1057                (delegation.ident, delegation_results.generics, item_kind, true)
1058            }
1059            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1060                {
    ::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
1061            }
1062        };
1063
1064        let defaultness = match i.kind.defaultness() {
1065            // We do not yet support `final` on trait associated items other than functions.
1066            // Even though we reject `final` on non-functions during AST validation, we still
1067            // need to stop propagating it here because later compiler passes do not expect
1068            // and cannot handle such items.
1069            Defaultness::Final(..) if !#[allow(non_exhaustive_omitted_patterns)] match i.kind {
    AssocItemKind::Fn(..) => true,
    _ => false,
}matches!(i.kind, AssocItemKind::Fn(..)) => {
1070                Defaultness::Implicit
1071            }
1072            defaultness => defaultness,
1073        };
1074        let (defaultness, _) = self
1075            .lower_defaultness(defaultness, has_value, || hir::Defaultness::Default { has_value });
1076
1077        let item = hir::TraitItem {
1078            owner_id: trait_item_def_id,
1079            ident: self.lower_ident(ident),
1080            generics,
1081            kind,
1082            span: self.lower_span(i.span),
1083            defaultness,
1084        };
1085        self.arena.alloc(item)
1086    }
1087
1088    fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemId {
1089        hir::TraitItemId { owner_id: self.owner_id(i.id) }
1090    }
1091
1092    /// Construct `ExprKind::Err` for the given `span`.
1093    pub(crate) fn expr_err(&mut self, span: Span, guar: ErrorGuaranteed) -> hir::Expr<'hir> {
1094        self.expr(span, hir::ExprKind::Err(guar))
1095    }
1096
1097    fn lower_trait_impl_header(
1098        &mut self,
1099        trait_impl_header: &TraitImplHeader,
1100    ) -> &'hir hir::TraitImplHeader<'hir> {
1101        let TraitImplHeader { safety, polarity, defaultness, ref trait_ref } = *trait_impl_header;
1102        let safety = self.lower_safety(safety, hir::Safety::Safe);
1103        let polarity = match polarity {
1104            ImplPolarity::Positive => ImplPolarity::Positive,
1105            ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
1106        };
1107        // `defaultness.has_value()` is never called for an `impl`, always `true` in order
1108        // to not cause an assertion failure inside the `lower_defaultness` function.
1109        let has_val = true;
1110        let (defaultness, defaultness_span) =
1111            self.lower_defaultness(defaultness, has_val, || hir::Defaultness::Final);
1112        let modifiers = TraitBoundModifiers {
1113            constness: BoundConstness::Never,
1114            asyncness: BoundAsyncness::Normal,
1115            // we don't use this in bound lowering
1116            polarity: BoundPolarity::Positive,
1117        };
1118        let trait_ref = self.lower_trait_ref(
1119            modifiers,
1120            trait_ref,
1121            ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
1122        );
1123
1124        self.arena.alloc(hir::TraitImplHeader {
1125            safety,
1126            polarity,
1127            defaultness,
1128            defaultness_span,
1129            trait_ref,
1130        })
1131    }
1132
1133    fn check_pin_drop_sugar_impl_item(
1134        &self,
1135        i: &AssocItem,
1136        ident: Ident,
1137        trait_item: Result<DefId, ErrorGuaranteed>,
1138    ) -> Ident {
1139        if let AssocItemKind::Fn(fn_kind) = &i.kind
1140            && fn_kind.is_pin_drop_sugar()
1141        {
1142            if let Ok(trait_item) = trait_item
1143                && self
1144                    .tcx
1145                    .lang_items()
1146                    .drop_trait()
1147                    .is_none_or(|drop_trait| self.tcx.parent(trait_item) != drop_trait)
1148            {
1149                self.dcx()
1150                    .struct_span_err(
1151                        i.span,
1152                        "method `drop` with `&pin mut self` is only supported for the `Drop` trait",
1153                    )
1154                    .with_span_label(i.span, "not a `Drop::pin_drop` implementation")
1155                    .emit();
1156            }
1157            return Ident::new(sym::pin_drop, ident.span);
1158        }
1159
1160        ident
1161    }
1162
1163    fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
1164        let owner_id = self.curr_owner.owner_id;
1165        let hir_id: HirId = owner_id.into();
1166        let parent_id = self.tcx.local_parent(owner_id.def_id);
1167        let is_in_trait_impl =
1168            #[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 });
1169
1170        // Since `default impl` is not yet implemented, this is always true in impls.
1171        let has_value = true;
1172        let (defaultness, _) =
1173            self.lower_defaultness(i.kind.defaultness(), has_value, || hir::Defaultness::Final);
1174        let attrs = self.lower_attrs(
1175            hir_id,
1176            &i.attrs,
1177            i.span,
1178            Target::from_assoc_item_kind(&i.kind, AssocCtxt::Impl { of_trait: is_in_trait_impl }),
1179        );
1180
1181        let (ident, (generics, kind)) = match &i.kind {
1182            AssocItemKind::Const(ConstItem {
1183                ident, generics, ty, body, define_opaque, ..
1184            }) => (
1185                *ident,
1186                self.lower_generics(
1187                    generics,
1188                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1189                    |this| {
1190                        let ty = this.lower_ty_alloc(
1191                            ty,
1192                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
1193                        );
1194                        this.lower_define_opaque(hir_id, &define_opaque);
1195                        let rhs = this.lower_const_item_rhs(body, i.span);
1196                        hir::ImplItemKind::Const(ty, rhs)
1197                    },
1198                ),
1199            ),
1200            AssocItemKind::Fn(Fn {
1201                sig, ident, generics, body, contract, define_opaque, ..
1202            }) => {
1203                let body_id = self.lower_maybe_coroutine_body(
1204                    sig.span,
1205                    i.span,
1206                    hir_id,
1207                    &sig.decl,
1208                    sig.header.coroutine_marker,
1209                    body.as_deref(),
1210                    attrs,
1211                    contract.as_deref(),
1212                );
1213                let (generics, sig) = self.lower_method_sig(
1214                    generics,
1215                    sig,
1216                    i.id,
1217                    if is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
1218                    sig.header.coroutine_marker,
1219                    attrs,
1220                );
1221                self.lower_define_opaque(hir_id, &define_opaque);
1222
1223                (*ident, (generics, hir::ImplItemKind::Fn(sig, body_id)))
1224            }
1225            AssocItemKind::Type(TyAlias { ident, generics, after_where_clause, ty, .. }) => {
1226                let mut generics = generics.clone();
1227                add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1228                (
1229                    *ident,
1230                    self.lower_generics(
1231                        &generics,
1232                        ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1233                        |this| match ty {
1234                            None => {
1235                                let guar = this.dcx().span_delayed_bug(
1236                                    i.span,
1237                                    "expected to lower associated type, but it was missing",
1238                                );
1239                                let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err(guar)));
1240                                hir::ImplItemKind::Type(ty)
1241                            }
1242                            Some(ty) => {
1243                                let ty = this.lower_ty_alloc(
1244                                    ty,
1245                                    ImplTraitContext::OpaqueTy {
1246                                        origin: hir::OpaqueTyOrigin::TyAlias {
1247                                            parent: this.curr_owner.owner.def_id,
1248                                            in_assoc_ty: true,
1249                                        },
1250                                    },
1251                                );
1252                                hir::ImplItemKind::Type(ty)
1253                            }
1254                        },
1255                    ),
1256                )
1257            }
1258            AssocItemKind::Delegation(delegation) => {
1259                let delegation_results = self.lower_delegation(delegation);
1260                (
1261                    delegation.ident,
1262                    (
1263                        delegation_results.generics,
1264                        hir::ImplItemKind::Fn(delegation_results.sig, delegation_results.body_id),
1265                    ),
1266                )
1267            }
1268            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1269                {
    ::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
1270            }
1271        };
1272
1273        let span = self.lower_span(i.span);
1274        let (effective_ident, impl_kind) = if is_in_trait_impl {
1275            let trait_item_def_id = self
1276                .get_partial_res(i.id)
1277                .and_then(|r| r.expect_full_res().opt_def_id())
1278                .ok_or_else(|| {
1279                    self.dcx()
1280                        .span_delayed_bug(span, "could not resolve trait item being implemented")
1281                });
1282            let effective_ident = self.check_pin_drop_sugar_impl_item(i, ident, trait_item_def_id);
1283            (effective_ident, ImplItemImplKind::Trait { defaultness, trait_item_def_id })
1284        } else {
1285            (ident, ImplItemImplKind::Inherent { vis_span: self.lower_span(i.vis.span) })
1286        };
1287
1288        let item = hir::ImplItem {
1289            owner_id,
1290            ident: self.lower_ident(effective_ident),
1291            generics,
1292            impl_kind,
1293            kind,
1294            span,
1295        };
1296        self.arena.alloc(item)
1297    }
1298
1299    fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemId {
1300        hir::ImplItemId { owner_id: self.owner_id(i.id) }
1301    }
1302
1303    fn lower_defaultness(
1304        &self,
1305        d: Defaultness,
1306        has_value: bool,
1307        implicit: impl FnOnce() -> hir::Defaultness,
1308    ) -> (hir::Defaultness, Option<Span>) {
1309        match d {
1310            Defaultness::Implicit => (implicit(), None),
1311            Defaultness::Default(sp) => {
1312                (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
1313            }
1314            Defaultness::Final(sp) => (hir::Defaultness::Final, Some(self.lower_span(sp))),
1315        }
1316    }
1317
1318    fn record_body(
1319        &mut self,
1320        params: &'hir [hir::Param<'hir>],
1321        value: hir::Expr<'hir>,
1322    ) -> hir::BodyId {
1323        let body = hir::Body { params, value: self.arena.alloc(value) };
1324        let id = body.id();
1325        {
    match (&id.hir_id.owner, &self.curr_owner.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);
            }
        }
    }
};assert_eq!(id.hir_id.owner, self.curr_owner.owner_id);
1326        self.curr_owner.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
1327        id
1328    }
1329
1330    pub(super) fn lower_body(
1331        &mut self,
1332        f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1333    ) -> hir::BodyId {
1334        let prev_coroutine_kind = self.coroutine_kind.take();
1335        let task_context = self.task_context.take();
1336        let (parameters, result) = f(self);
1337        let body_id = self.record_body(parameters, result);
1338        self.task_context = task_context;
1339        self.coroutine_kind = prev_coroutine_kind;
1340        body_id
1341    }
1342
1343    fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1344        let hir_id = self.lower_node_id(param.id);
1345        self.lower_attrs(hir_id, &param.attrs, param.span, Target::Param);
1346        hir::Param {
1347            hir_id,
1348            pat: self.lower_pat(&param.pat),
1349            ty_span: self.lower_span(param.ty.span),
1350            span: self.lower_span(param.span),
1351        }
1352    }
1353
1354    pub(super) fn lower_fn_body(
1355        &mut self,
1356        decl: &FnDecl,
1357        contract: Option<&FnContract>,
1358        body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1359    ) -> hir::BodyId {
1360        self.lower_body(|this| {
1361            let params =
1362                this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x)));
1363
1364            // Optionally lower the fn contract
1365            if let Some(contract) = contract {
1366                (params, this.lower_contract(body, contract))
1367            } else {
1368                (params, body(this))
1369            }
1370        })
1371    }
1372
1373    fn lower_fn_body_block(
1374        &mut self,
1375        decl: &FnDecl,
1376        body: &Block,
1377        contract: Option<&FnContract>,
1378    ) -> hir::BodyId {
1379        self.lower_fn_body(decl, contract, |this| this.lower_block_expr(body))
1380    }
1381
1382    pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1383        self.lower_body(|this| {
1384            (
1385                &[],
1386                match expr {
1387                    Some(expr) => this.lower_expr_mut(expr),
1388                    None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")),
1389                },
1390            )
1391        })
1392    }
1393
1394    /// Takes what may be the body of an `async fn` or a `gen fn` and wraps it in an `async {}` or
1395    /// `gen {}` block as appropriate.
1396    fn lower_maybe_coroutine_body(
1397        &mut self,
1398        fn_decl_span: Span,
1399        span: Span,
1400        fn_id: hir::HirId,
1401        decl: &FnDecl,
1402        coroutine_marker: Option<CoroutineMarker>,
1403        body: Option<&Block>,
1404        attrs: &'hir [hir::Attribute],
1405        contract: Option<&FnContract>,
1406    ) -> hir::BodyId {
1407        let Some(body) = body else {
1408            // Functions without a body are an error, except if this is an intrinsic. For those we
1409            // create a fake body so that the entire rest of the compiler doesn't have to deal with
1410            // this as a special case.
1411            return self.lower_fn_body(decl, contract, |this| {
1412                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() {
1413                    let span = this.lower_span(span);
1414                    let empty_block = hir::Block {
1415                        hir_id: this.next_id(),
1416                        stmts: &[],
1417                        expr: None,
1418                        rules: hir::BlockCheckMode::DefaultBlock,
1419                        span,
1420                        targeted_by_break: false,
1421                    };
1422                    let loop_ = hir::ExprKind::Loop(
1423                        this.arena.alloc(empty_block),
1424                        None,
1425                        hir::LoopSource::Loop,
1426                        span,
1427                    );
1428                    hir::Expr { hir_id: this.next_id(), kind: loop_, span }
1429                } else {
1430                    this.expr_err(span, this.dcx().has_errors().unwrap())
1431                }
1432            });
1433        };
1434        let Some(coroutine_marker) = coroutine_marker else {
1435            // Typical case: not a coroutine.
1436            return self.lower_fn_body_block(decl, body, contract);
1437        };
1438        // FIXME(contracts): Support contracts on async fn.
1439        self.lower_body(|this| {
1440            let (parameters, expr) = this.lower_coroutine_body_with_moved_arguments(
1441                decl,
1442                |this| this.lower_block_expr(body),
1443                fn_decl_span,
1444                body.span,
1445                coroutine_marker,
1446                hir::CoroutineSource::Fn,
1447            );
1448
1449            // FIXME(async_fn_track_caller): Can this be moved above?
1450            let hir_id = expr.hir_id;
1451            this.maybe_forward_track_caller(fn_id, hir_id);
1452
1453            (parameters, expr)
1454        })
1455    }
1456
1457    /// Lowers a desugared coroutine body after moving all of the arguments
1458    /// into the body. This is to make sure that the future actually owns the
1459    /// arguments that are passed to the function, and to ensure things like
1460    /// drop order are stable.
1461    pub(crate) fn lower_coroutine_body_with_moved_arguments(
1462        &mut self,
1463        decl: &FnDecl,
1464        lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::Expr<'hir>,
1465        fn_decl_span: Span,
1466        body_span: Span,
1467        coroutine_marker: CoroutineMarker,
1468        coroutine_source: hir::CoroutineSource,
1469    ) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>) {
1470        let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1471        let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1472
1473        // Async function parameters are lowered into the closure body so that they are
1474        // captured and so that the drop order matches the equivalent non-async functions.
1475        //
1476        // from:
1477        //
1478        //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1479        //         <body>
1480        //     }
1481        //
1482        // into:
1483        //
1484        //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1485        //       async move {
1486        //         let __arg2 = __arg2;
1487        //         let <pattern> = __arg2;
1488        //         let __arg1 = __arg1;
1489        //         let <pattern> = __arg1;
1490        //         let __arg0 = __arg0;
1491        //         let <pattern> = __arg0;
1492        //         drop-temps { <body> } // see comments later in fn for details
1493        //       }
1494        //     }
1495        //
1496        // If `<pattern>` is a simple ident, then it is lowered to a single
1497        // `let <pattern> = <pattern>;` statement as an optimization.
1498        //
1499        // Note that the body is embedded in `drop-temps`; an
1500        // equivalent desugaring would be `return { <body>
1501        // };`. The key point is that we wish to drop all the
1502        // let-bound variables and temporaries created in the body
1503        // (and its tail expression!) before we drop the
1504        // parameters (c.f. rust-lang/rust#64512).
1505        for (index, parameter) in decl.inputs.iter().enumerate() {
1506            let parameter = self.lower_param(parameter);
1507            let span = parameter.pat.span;
1508
1509            // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1510            // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1511            let (ident, is_simple_parameter) = match parameter.pat.kind {
1512                hir::PatKind::Binding(hir::BindingMode(ByRef::No, _), _, ident, _) => (ident, true),
1513                // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1514                // we can keep the same name for the parameter.
1515                // This lets rustdoc render it correctly in documentation.
1516                hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1517                hir::PatKind::Wild => (Ident::with_dummy_span(rustc_span::kw::Underscore), false),
1518                _ => {
1519                    // Replace the ident for bindings that aren't simple.
1520                    let name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__arg{0}", index))
    })format!("__arg{index}");
1521                    let ident = Ident::from_str(&name);
1522
1523                    (ident, false)
1524                }
1525            };
1526
1527            let desugared_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1528
1529            // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1530            // async function.
1531            //
1532            // If this is the simple case, this parameter will end up being the same as the
1533            // original parameter, but with a different pattern id.
1534            let stmt_attrs = self.curr_owner.attrs.get(&parameter.hir_id.local_id).copied();
1535            let (new_parameter_pat, new_parameter_id) = self.pat_ident(desugared_span, ident);
1536            let new_parameter = hir::Param {
1537                hir_id: parameter.hir_id,
1538                pat: new_parameter_pat,
1539                ty_span: self.lower_span(parameter.ty_span),
1540                span: self.lower_span(parameter.span),
1541            };
1542
1543            if is_simple_parameter {
1544                // If this is the simple case, then we only insert one statement that is
1545                // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1546                // `HirId`s are densely assigned.
1547                let expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1548                let stmt = self.stmt_let_pat(
1549                    stmt_attrs,
1550                    desugared_span,
1551                    Some(expr),
1552                    parameter.pat,
1553                    hir::LocalSource::AsyncFn,
1554                );
1555                statements.push(stmt);
1556            } else {
1557                // If this is not the simple case, then we construct two statements:
1558                //
1559                // ```
1560                // let __argN = __argN;
1561                // let <pat> = __argN;
1562                // ```
1563                //
1564                // The first statement moves the parameter into the closure and thus ensures
1565                // that the drop order is correct.
1566                //
1567                // The second statement creates the bindings that the user wrote.
1568
1569                // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1570                // because the user may have specified a `ref mut` binding in the next
1571                // statement.
1572                let (move_pat, move_id) =
1573                    self.pat_ident_binding_mode(desugared_span, ident, hir::BindingMode::MUT);
1574                let move_expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1575                let move_stmt = self.stmt_let_pat(
1576                    None,
1577                    desugared_span,
1578                    Some(move_expr),
1579                    move_pat,
1580                    hir::LocalSource::AsyncFn,
1581                );
1582
1583                // Construct the `let <pat> = __argN;` statement. We re-use the original
1584                // parameter's pattern so that `HirId`s are densely assigned.
1585                let pattern_expr = self.expr_ident(desugared_span, ident, move_id);
1586                let pattern_stmt = self.stmt_let_pat(
1587                    stmt_attrs,
1588                    desugared_span,
1589                    Some(pattern_expr),
1590                    parameter.pat,
1591                    hir::LocalSource::AsyncFn,
1592                );
1593
1594                statements.push(move_stmt);
1595                statements.push(pattern_stmt);
1596            };
1597
1598            parameters.push(new_parameter);
1599        }
1600
1601        let mkbody = |this: &mut LoweringContext<'_, 'hir>| {
1602            // Create a block from the user's function body:
1603            let user_body = lower_body(this);
1604
1605            // Transform into `drop-temps { <user-body> }`, an expression:
1606            let desugared_span =
1607                this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1608            let user_body = this.expr_drop_temps(desugared_span, this.arena.alloc(user_body));
1609
1610            // As noted above, create the final block like
1611            //
1612            // ```
1613            // {
1614            //   let $param_pattern = $raw_param;
1615            //   ...
1616            //   drop-temps { <user-body> }
1617            // }
1618            // ```
1619            let body = this.block_all(
1620                desugared_span,
1621                this.arena.alloc_from_iter(statements),
1622                Some(user_body),
1623            );
1624
1625            this.expr_block(body)
1626        };
1627        let desugaring_kind = match coroutine_marker.kind {
1628            CoroutineKind::Async => hir::CoroutineDesugaring::Async,
1629            CoroutineKind::Gen => hir::CoroutineDesugaring::Gen,
1630            CoroutineKind::AsyncGen => hir::CoroutineDesugaring::AsyncGen,
1631        };
1632        let closure_id = coroutine_marker.closure_id;
1633
1634        let coroutine_expr = self.make_desugared_coroutine_expr(
1635            // The default capture mode here is by-ref. Later on during upvar analysis,
1636            // we will force the captured arguments to by-move, but for async closures,
1637            // we want to make sure that we avoid unnecessarily moving captures, or else
1638            // all async closures would default to `FnOnce` as their calling mode.
1639            CaptureBy::Ref,
1640            closure_id,
1641            None,
1642            fn_decl_span,
1643            body_span,
1644            desugaring_kind,
1645            coroutine_source,
1646            mkbody,
1647        );
1648
1649        let expr = hir::Expr {
1650            hir_id: self.lower_node_id(closure_id),
1651            kind: coroutine_expr,
1652            span: self.lower_span(body_span),
1653        };
1654
1655        (self.arena.alloc_from_iter(parameters), expr)
1656    }
1657
1658    fn lower_method_sig(
1659        &mut self,
1660        generics: &Generics,
1661        sig: &FnSig,
1662        id: NodeId,
1663        kind: FnDeclKind,
1664        coroutine_marker: Option<CoroutineMarker>,
1665        attrs: &[hir::Attribute],
1666    ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1667        let header = self.lower_fn_header(sig.header, hir::Safety::Safe, attrs);
1668        let itctx = ImplTraitContext::Universal;
1669        let (generics, decl) = self.lower_generics(generics, itctx, |this| {
1670            this.lower_fn_decl(&sig.decl, id, kind, coroutine_marker)
1671        });
1672        (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1673    }
1674
1675    pub(super) fn lower_fn_header(
1676        &mut self,
1677        h: FnHeader,
1678        default_safety: hir::Safety,
1679        attrs: &[hir::Attribute],
1680    ) -> hir::FnHeader {
1681        let asyncness = if let Some(coroutine_marker) = h.coroutine_marker
1682            && let CoroutineKind::Async = coroutine_marker.kind
1683        {
1684            hir::IsAsync::Async(self.lower_span(coroutine_marker.span))
1685        } else {
1686            hir::IsAsync::NotAsync
1687        };
1688
1689        let safety = self.lower_safety(h.safety, default_safety);
1690
1691        // Treat safe `#[target_feature]` functions as unsafe, but also remember that we did so.
1692        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, .. })
1693            && safety.is_safe()
1694            && !self.tcx.sess.target.is_like_wasm
1695        {
1696            hir::HeaderSafety::SafeTargetFeatures
1697        } else {
1698            safety.into()
1699        };
1700
1701        let constness = self.lower_constness(attrs, h.constness);
1702
1703        hir::FnHeader { safety, asyncness, constness, abi: self.lower_extern(h.ext) }
1704    }
1705
1706    pub(super) fn lower_abi(&mut self, abi_str: StrLit) -> ExternAbi {
1707        let ast::StrLit { symbol_unescaped, span, .. } = abi_str;
1708        let extern_abi = symbol_unescaped.as_str().parse().unwrap_or_else(|_| {
1709            self.error_on_invalid_abi(abi_str);
1710            ExternAbi::Rust
1711        });
1712        let tcx = self.tcx;
1713
1714        // we can't do codegen for unsupported ABIs, so error now so we won't get farther
1715        if !tcx.sess.target.is_abi_supported(extern_abi) {
1716            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!(
1717                tcx.dcx(),
1718                span,
1719                E0570,
1720                "{extern_abi} is not a supported ABI for the current target",
1721            );
1722
1723            if let ExternAbi::Stdcall { unwind } = extern_abi {
1724                let c_abi = ExternAbi::C { unwind };
1725                let system_abi = ExternAbi::System { unwind };
1726                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, \
1727                    use `extern {system_abi}`"
1728                ));
1729            }
1730            err.emit();
1731        }
1732        // Show required feature gate even if we already errored, as the user is likely to build the code
1733        // for the actually intended target next and then they will need the feature gate.
1734        gate_unstable_abi(tcx.sess, tcx.features(), span, extern_abi);
1735        extern_abi
1736    }
1737
1738    pub(super) fn lower_extern(&mut self, ext: Extern) -> ExternAbi {
1739        match ext {
1740            Extern::None => ExternAbi::Rust,
1741            Extern::Implicit(_) => ExternAbi::FALLBACK,
1742            Extern::Explicit(abi, _) => self.lower_abi(abi),
1743        }
1744    }
1745
1746    fn error_on_invalid_abi(&self, abi: StrLit) {
1747        let abi_names = enabled_names(self.tcx.features(), abi.span)
1748            .iter()
1749            .map(|s| Symbol::intern(s))
1750            .collect::<Vec<_>>();
1751        let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1752        self.dcx().emit_err(InvalidAbi {
1753            abi: abi.symbol_unescaped,
1754            span: abi.span,
1755            suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1756                span: abi.span,
1757                suggestion: suggested_name.to_string(),
1758            }),
1759            command: "rustc --print=calling-conventions".to_string(),
1760        });
1761    }
1762
1763    /// Lowers constness or comptime attribute.
1764    /// Whether `const` is allowed here is checked by ast validation.
1765    /// Whether `comptime` is allowed here is checked by the `comptime` attribute parser.
1766    pub(super) fn lower_constness(&mut self, attrs: &[hir::Attribute], c: Const) -> hir::Constness {
1767        let mut constness = match c {
1768            Const::Yes(_) => hir::Constness::Const { always: false },
1769            Const::No => hir::Constness::NotConst,
1770        };
1771
1772        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) {
1773            match std::mem::replace(&mut constness, hir::Constness::Const { always: true }) {
1774                hir::Constness::Const { always: true } => {
1775                    {
    ::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")
1776                }
1777                // A function can't be `const` and `comptime` at the same time
1778                hir::Constness::Const { always: false } => {
1779                    let Const::Yes(span) = c else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1780                    self.dcx().emit_err(ConstComptimeFn { span, attr_span });
1781                }
1782                // Good
1783                hir::Constness::NotConst => {}
1784            }
1785        }
1786        constness
1787    }
1788
1789    pub(super) fn lower_safety(&self, s: Safety, default: hir::Safety) -> hir::Safety {
1790        match s {
1791            Safety::Unsafe(_) => hir::Safety::Unsafe,
1792            Safety::Default => default,
1793            Safety::Safe(_) => hir::Safety::Safe,
1794        }
1795    }
1796
1797    fn lower_restriction_kind(
1798        &mut self,
1799        restriction_kind: &RestrictionKind,
1800        hir_id: HirId,
1801        resolving_kind: ResolvingRestrictionKind,
1802    ) -> hir::RestrictionKind<'hir> {
1803        match restriction_kind {
1804            RestrictionKind::Unrestricted => hir::RestrictionKind::Unrestricted,
1805            RestrictionKind::Restricted { path, id, shorthand: _ } => {
1806                let res = self.get_partial_res(*id);
1807                let parent_module = self.tcx.parent_module(hir_id);
1808                if let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) {
1809                    if !self.tcx.is_descendant_of(parent_module, did) {
1810                        // If the restriction path is not an ancestor of the item,
1811                        // emit an error and recover by lowering the restriction to `Unrestricted`.
1812                        self.dcx()
1813                            .create_err(RestrictionAncestorOnly {
1814                                span: path.span,
1815                                kind: resolving_kind,
1816                            })
1817                            .emit();
1818                        hir::RestrictionKind::Unrestricted
1819                    } else {
1820                        hir::RestrictionKind::Restricted(self.arena.alloc(hir::Path {
1821                            res: did,
1822                            segments: self.arena.alloc_from_iter(path.segments.iter().map(
1823                                |segment| {
1824                                    self.lower_path_segment(
1825                                        path.span,
1826                                        segment,
1827                                        ParamMode::Explicit,
1828                                        GenericArgsMode::Err,
1829                                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1830                                        None,
1831                                    )
1832                                },
1833                            )),
1834                            span: self.lower_span(path.span),
1835                        }))
1836                    }
1837                } else {
1838                    self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1839                    hir::RestrictionKind::Unrestricted
1840                }
1841            }
1842        }
1843    }
1844
1845    pub(super) fn lower_impl_restriction(
1846        &mut self,
1847        r: &ImplRestriction,
1848        hir_id: HirId,
1849    ) -> &'hir hir::ImplRestriction<'hir> {
1850        let kind = self.lower_restriction_kind(&r.kind, hir_id, ResolvingRestrictionKind::Impl);
1851        self.arena.alloc(hir::ImplRestriction { kind, span: self.lower_span(r.span) })
1852    }
1853
1854    pub(super) fn lower_mut_restriction(
1855        &mut self,
1856        r: &MutRestriction,
1857        hir_id: HirId,
1858    ) -> &'hir hir::MutRestriction<'hir> {
1859        let kind = self.lower_restriction_kind(&r.kind, hir_id, ResolvingRestrictionKind::Mut);
1860        self.arena.alloc(hir::MutRestriction { kind, span: self.lower_span(r.span) })
1861    }
1862
1863    /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1864    /// the carried impl trait definitions and bounds.
1865    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_ast_lowering/src/item.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1865u32),
                                    ::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.curr_owner.impl_trait_defs.is_empty() {
                ::core::panicking::panic("assertion failed: self.curr_owner.impl_trait_defs.is_empty()")
            };
            if !self.curr_owner.impl_trait_bounds.is_empty() {
                ::core::panicking::panic("assertion failed: self.curr_owner.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.curr_owner.owner.extra_lifetime_params(self.curr_owner.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.curr_owner.impl_trait_defs);
            params.extend(impl_trait_defs.into_iter());
            let impl_trait_bounds =
                std::mem::take(&mut self.curr_owner.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))]
1866    fn lower_generics<T>(
1867        &mut self,
1868        generics: &Generics,
1869        itctx: ImplTraitContext,
1870        f: impl FnOnce(&mut Self) -> T,
1871    ) -> (&'hir hir::Generics<'hir>, T) {
1872        assert!(self.curr_owner.impl_trait_defs.is_empty());
1873        assert!(self.curr_owner.impl_trait_bounds.is_empty());
1874
1875        let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1876        // We need to make sure that generic params don't have multiple relaxed bounds for the same trait
1877        // across generic param bounds and where bounds.
1878        let mut dedup_map: IndexMap<LocalDefId, _> = Default::default();
1879        predicates.extend(generics.params.iter().filter_map(|param| {
1880            self.lower_generic_bound_predicate(
1881                param.ident,
1882                param.id,
1883                &param.kind,
1884                &param.bounds,
1885                param.colon_span,
1886                generics.span,
1887                RelaxedBoundPolicy::Allowed(
1888                    dedup_map.entry(self.local_def_id(param.id)).or_default(),
1889                ),
1890                itctx,
1891                PredicateOrigin::GenericParam,
1892            )
1893        }));
1894        predicates.extend(generics.where_clause.predicates.iter().map(|predicate| {
1895            self.lower_where_predicate(predicate, &generics.params, &mut dedup_map)
1896        }));
1897
1898        let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> = self
1899            .lower_generic_params_mut(&generics.params, hir::GenericParamSource::Generics)
1900            .collect();
1901
1902        // Introduce extra lifetimes if late resolution tells us to.
1903        let extra_lifetimes = self.curr_owner.owner.extra_lifetime_params(self.curr_owner.owner.id);
1904        params.extend(extra_lifetimes.into_iter().map(|&(ident, node_id, kind)| {
1905            self.lifetime_res_to_generic_param(
1906                ident,
1907                node_id,
1908                kind,
1909                hir::GenericParamSource::Generics,
1910            )
1911        }));
1912
1913        let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1914        let where_clause_span = self.lower_span(generics.where_clause.span);
1915        let span = self.lower_span(generics.span);
1916        let res = f(self);
1917
1918        let impl_trait_defs = std::mem::take(&mut self.curr_owner.impl_trait_defs);
1919        params.extend(impl_trait_defs.into_iter());
1920
1921        let impl_trait_bounds = std::mem::take(&mut self.curr_owner.impl_trait_bounds);
1922        predicates.extend(impl_trait_bounds.into_iter());
1923
1924        let lowered_generics = self.arena.alloc(hir::Generics {
1925            params: self.arena.alloc_from_iter(params),
1926            predicates: self.arena.alloc_from_iter(predicates),
1927            has_where_clause_predicates,
1928            where_clause_span,
1929            span,
1930        });
1931
1932        (lowered_generics, res)
1933    }
1934
1935    pub(super) fn lower_define_opaque(
1936        &mut self,
1937        hir_id: HirId,
1938        define_opaque: &Option<ThinVec<(NodeId, Path)>>,
1939    ) {
1940        {
    match (&self.curr_owner.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.curr_owner.define_opaque, None);
1941        if !hir_id.is_owner() {
    ::core::panicking::panic("assertion failed: hir_id.is_owner()")
};assert!(hir_id.is_owner());
1942        let Some(define_opaque) = define_opaque.as_ref() else {
1943            return;
1944        };
1945        let define_opaque = define_opaque.iter().filter_map(|(id, path)| {
1946            let res = self.get_partial_res(*id);
1947            let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else {
1948                self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1949                return None;
1950            };
1951            let Some(did) = did.as_local() else {
1952                self.dcx().span_err(
1953                    path.span,
1954                    "only opaque types defined in the local crate can be defined",
1955                );
1956                return None;
1957            };
1958            Some((self.lower_span(path.span), did))
1959        });
1960        let define_opaque = self.arena.alloc_from_iter(define_opaque);
1961        self.curr_owner.define_opaque = Some(define_opaque);
1962    }
1963
1964    pub(super) fn lower_generic_bound_predicate(
1965        &mut self,
1966        ident: Ident,
1967        id: NodeId,
1968        kind: &GenericParamKind,
1969        bounds: &[GenericBound],
1970        colon_span: Option<Span>,
1971        parent_span: Span,
1972        rbp: RelaxedBoundPolicy<'_>,
1973        itctx: ImplTraitContext,
1974        origin: PredicateOrigin,
1975    ) -> Option<hir::WherePredicate<'hir>> {
1976        // Do not create a clause if we do not have anything inside it.
1977        if bounds.is_empty() {
1978            return None;
1979        }
1980
1981        let bounds = self.lower_param_bounds(bounds, rbp, itctx);
1982
1983        let param_span = ident.span;
1984
1985        // Reconstruct the span of the entire predicate from the individual generic bounds.
1986        let span_start = colon_span.unwrap_or_else(|| param_span.shrink_to_hi());
1987        let span = bounds.iter().fold(span_start, |span_accum, bound| {
1988            match bound.span().find_ancestor_inside(parent_span) {
1989                Some(bound_span) => span_accum.to(bound_span),
1990                None => span_accum,
1991            }
1992        });
1993        let span = self.lower_span(span);
1994        let hir_id = self.next_id();
1995        let kind = self.arena.alloc(match kind {
1996            GenericParamKind::Const { .. } => return None,
1997            GenericParamKind::Type { .. } => {
1998                let def_id = self.local_def_id(id).to_def_id();
1999                let hir_id = self.next_id();
2000                let res = Res::Def(DefKind::TyParam, def_id);
2001                let ident = self.lower_ident(ident);
2002                let ty_path = self.arena.alloc(hir::Path {
2003                    span: self.lower_span(param_span),
2004                    res,
2005                    segments: self
2006                        .arena
2007                        .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
2008                });
2009                let ty_id = self.next_id();
2010                let bounded_ty =
2011                    self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
2012                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2013                    bounded_ty: self.arena.alloc(bounded_ty),
2014                    bounds,
2015                    bound_generic_params: &[],
2016                    origin,
2017                })
2018            }
2019            GenericParamKind::Lifetime => {
2020                let lt_id = self.next_node_id();
2021                let lifetime =
2022                    self.new_named_lifetime(id, lt_id, ident, LifetimeSource::Other, ident.into());
2023                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2024                    lifetime,
2025                    bounds,
2026                    in_where_clause: false,
2027                })
2028            }
2029        });
2030        Some(hir::WherePredicate { hir_id, span, kind })
2031    }
2032
2033    fn lower_where_predicate(
2034        &mut self,
2035        pred: &WherePredicate,
2036        params: &[ast::GenericParam],
2037        dedup_map: &mut IndexMap<LocalDefId, IndexMap<DefId, Span>>,
2038    ) -> hir::WherePredicate<'hir> {
2039        let hir_id = self.lower_node_id(pred.id);
2040        let span = self.lower_span(pred.span);
2041        self.lower_attrs(hir_id, &pred.attrs, span, Target::WherePredicate);
2042        let kind = self.arena.alloc(match &pred.kind {
2043            WherePredicateKind::BoundPredicate(WhereBoundPredicate {
2044                bound_generic_params,
2045                bounded_ty,
2046                bounds,
2047            }) => {
2048                let rbp = if bound_generic_params.is_empty()
2049                    && let Some(res) =
2050                        self.get_partial_res(bounded_ty.id).and_then(|r| r.full_res())
2051                    && let Res::Def(DefKind::TyParam, def_id) = res
2052                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2053                {
2054                    RelaxedBoundPolicy::Allowed(dedup_map.entry(def_id.expect_local()).or_default())
2055                } else {
2056                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::WhereBound)
2057                };
2058                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2059                    bound_generic_params: self.lower_generic_params(
2060                        bound_generic_params,
2061                        hir::GenericParamSource::Binder,
2062                    ),
2063                    bounded_ty: self.lower_ty_alloc(
2064                        bounded_ty,
2065                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2066                    ),
2067                    bounds: self.lower_param_bounds(
2068                        bounds,
2069                        rbp,
2070                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2071                    ),
2072                    origin: PredicateOrigin::WhereClause,
2073                })
2074            }
2075            WherePredicateKind::RegionPredicate(WhereRegionPredicate { lifetime, bounds }) => {
2076                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2077                    lifetime: self.lower_lifetime(
2078                        lifetime,
2079                        LifetimeSource::Other,
2080                        lifetime.ident.into(),
2081                    ),
2082                    bounds: self.lower_param_bounds(
2083                        bounds,
2084                        RelaxedBoundPolicy::Allowed(&mut Default::default()),
2085                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2086                    ),
2087                    in_where_clause: true,
2088                })
2089            }
2090        });
2091        hir::WherePredicate { hir_id, span, kind }
2092    }
2093
2094    fn lower_test_binder_body(&mut self, body: &TestBinderBody) -> hir::TestBinderBody<'hir> {
2095        let foralls = self.arena.alloc_from_iter(
2096            body.foralls.iter().map(|forall| self.lower_test_binder_forall(forall)),
2097        );
2098        let exists = self.arena.alloc_from_iter(
2099            body.exists.iter().map(|exists| self.lower_test_binder_exists(exists)),
2100        );
2101        let constraints = self.lower_test_binder_constraints_as_and(&body.constraints);
2102        let mut dedup_map = Default::default();
2103        let predicates = self.arena.alloc_from_iter(
2104            body.predicates
2105                .iter()
2106                .flat_map(|w| &w.predicates)
2107                .map(|predicate| self.lower_where_predicate(predicate, &[], &mut dedup_map)),
2108        );
2109        hir::TestBinderBody { foralls, exists, constraints, predicates }
2110    }
2111
2112    fn lower_test_binder_forall(
2113        &mut self,
2114        forall: &TestBinderForall,
2115    ) -> hir::TestBinderForall<'hir> {
2116        let (generics, body) = self.lower_generics(
2117            &forall.generics,
2118            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2119            |this| this.lower_test_binder_body(&forall.body),
2120        );
2121        let assert_on_exit = forall.assert_on_exit.as_ref().map(|assert_on_exit| {
2122            self.arena.alloc(self.lower_test_binder_constraints_as_and(assert_on_exit)) as &_
2123        });
2124        hir::TestBinderForall {
2125            span: self.lower_span(forall.span),
2126            hir_id: self.lower_node_id(forall.node_id),
2127            generics,
2128            body: self.arena.alloc(body),
2129            assert_on_exit,
2130        }
2131    }
2132
2133    fn lower_test_binder_exists(
2134        &mut self,
2135        exists: &TestBinderExists,
2136    ) -> hir::TestBinderExists<'hir> {
2137        let (generics, body) = self.lower_generics(
2138            &Generics {
2139                params: exists.params.clone(),
2140                where_clause: Default::default(),
2141                span: exists.span,
2142            },
2143            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2144            |this| this.lower_test_binder_body(&exists.body),
2145        );
2146        let params = generics.params;
2147        hir::TestBinderExists {
2148            span: self.lower_span(exists.span),
2149            hir_id: self.lower_node_id(exists.node_id),
2150            params,
2151            body: self.arena.alloc(body),
2152        }
2153    }
2154
2155    // if there are multiple constraints in a block body, automatically wrap them in an `and {}`
2156    fn lower_test_binder_constraints_as_and(
2157        &mut self,
2158        constraints: &[TestBinderConstraint],
2159    ) -> hir::TestBinderConstraint<'hir> {
2160        if constraints.len() == 1 {
2161            self.lower_test_binder_constraint(&constraints[0])
2162        } else {
2163            hir::TestBinderConstraint::And {
2164                items: self.arena.alloc_from_iter(
2165                    constraints.iter().map(|item| self.lower_test_binder_constraint(item)),
2166                ),
2167            }
2168        }
2169    }
2170
2171    fn lower_test_binder_constraint(
2172        &mut self,
2173        constraint: &TestBinderConstraint,
2174    ) -> hir::TestBinderConstraint<'hir> {
2175        match constraint {
2176            TestBinderConstraint::And { items } => hir::TestBinderConstraint::And {
2177                items: self.arena.alloc_from_iter(
2178                    items.iter().map(|item| self.lower_test_binder_constraint(item)),
2179                ),
2180            },
2181            TestBinderConstraint::Or { items } => hir::TestBinderConstraint::Or {
2182                items: self.arena.alloc_from_iter(
2183                    items.iter().map(|item| self.lower_test_binder_constraint(item)),
2184                ),
2185            },
2186            TestBinderConstraint::Lifetime { lhs, rhs } => {
2187                let lhs = self.lower_lifetime(lhs, LifetimeSource::Other, lhs.ident.into());
2188                let rhs = self.lower_lifetime(rhs, LifetimeSource::OutlivesBound, rhs.ident.into());
2189                hir::TestBinderConstraint::Lifetime { lhs, rhs }
2190            }
2191            TestBinderConstraint::PlaceholderOutlives { lhs, rhs } => {
2192                let lhs = self
2193                    .lower_ty_alloc(lhs, ImplTraitContext::Disallowed(ImplTraitPosition::Bound));
2194                let rhs = self.lower_lifetime(rhs, LifetimeSource::OutlivesBound, rhs.ident.into());
2195                hir::TestBinderConstraint::PlaceholderOutlives { lhs, rhs }
2196            }
2197            TestBinderConstraint::AliasOutlives { bound_type_constraint } => {
2198                hir::TestBinderConstraint::AliasOutlives {
2199                    bound_type_constraint: self
2200                        .arena
2201                        .alloc(self.lower_test_binder_bound_type_constraint(bound_type_constraint)),
2202                }
2203            }
2204        }
2205    }
2206
2207    fn lower_test_binder_bound_type_constraint(
2208        &mut self,
2209        bound_type: &TestBinderBoundTypeConstraint,
2210    ) -> hir::TestBinderBoundTypeConstraint<'hir> {
2211        let TestBinderBoundTypeConstraint { span, node_id, params, lhs, rhs } = bound_type;
2212
2213        let (generics, (lhs, rhs)) = self.lower_generics(
2214            &Generics { params: params.clone(), where_clause: Default::default(), span: *span },
2215            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2216            |this| {
2217                let lhs = this
2218                    .lower_ty_alloc(lhs, ImplTraitContext::Disallowed(ImplTraitPosition::Bound));
2219                let rhs = this.lower_lifetime(rhs, LifetimeSource::OutlivesBound, rhs.ident.into());
2220                (lhs, rhs)
2221            },
2222        );
2223
2224        hir::TestBinderBoundTypeConstraint {
2225            span: *span,
2226            hir_id: self.lower_node_id(*node_id),
2227            params: generics.params,
2228            lhs,
2229            rhs,
2230        }
2231    }
2232}