Skip to main content

rustc_ast_lowering/
item.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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