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