Skip to main content

rustc_ast_lowering/
item.rs

1use rustc_abi::ExternAbi;
2use rustc_ast::visit::AssocCtxt;
3use rustc_ast::*;
4use rustc_data_structures::fx::FxIndexMap;
5use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err};
6use rustc_hir::attrs::{AttributeKind, EiiImplResolution};
7use rustc_hir::def::{DefKind, PerNS, Res};
8use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
9use rustc_hir::{
10    self as hir, HirId, ImplItemImplKind, LifetimeSource, PredicateOrigin, Target, find_attr,
11};
12use rustc_index::{IndexSlice, IndexVec};
13use rustc_middle::span_bug;
14use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
15use rustc_span::def_id::DefId;
16use rustc_span::edit_distance::find_best_match_for_name;
17use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
18use smallvec::{SmallVec, smallvec};
19use thin_vec::ThinVec;
20use tracing::instrument;
21
22use super::errors::{InvalidAbi, InvalidAbiSuggestion, TupleStructWithDefault, UnionWithDefault};
23use super::stability::{enabled_names, gate_unstable_abi};
24use super::{
25    AstOwner, FnDeclKind, GenericArgsMode, ImplTraitContext, ImplTraitPosition, LoweringContext,
26    ParamMode, RelaxedBoundForbiddenReason, RelaxedBoundPolicy, ResolverAstLoweringExt,
27};
28
29/// Wraps either IndexVec (during `hir_crate`), which acts like a primary
30/// storage for most of the MaybeOwners, or FxIndexMap during delayed AST -> HIR
31/// lowering of delegations (`lower_delayed_owner`),
32/// in this case we can not modify already created IndexVec, so we use other map.
33pub(super) enum Owners<'a, 'hir> {
34    IndexVec(&'a mut IndexVec<LocalDefId, hir::MaybeOwner<'hir>>),
35    Map(&'a mut FxIndexMap<LocalDefId, hir::MaybeOwner<'hir>>),
36}
37
38impl<'hir> Owners<'_, 'hir> {
39    fn get_or_insert_mut(&mut self, def_id: LocalDefId) -> &mut hir::MaybeOwner<'hir> {
40        match self {
41            Owners::IndexVec(index_vec) => {
42                index_vec.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom)
43            }
44            Owners::Map(map) => map.entry(def_id).or_insert(hir::MaybeOwner::Phantom),
45        }
46    }
47}
48
49pub(super) struct ItemLowerer<'a, 'hir> {
50    pub(super) tcx: TyCtxt<'hir>,
51    pub(super) resolver: &'a ResolverAstLowering<'hir>,
52    pub(super) ast_index: &'a IndexSlice<LocalDefId, AstOwner<'a>>,
53    pub(super) owners: Owners<'a, 'hir>,
54}
55
56/// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
57/// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
58/// clause if it exists.
59fn add_ty_alias_where_clause(
60    generics: &mut ast::Generics,
61    after_where_clause: &ast::WhereClause,
62    prefer_first: bool,
63) {
64    generics.where_clause.predicates.extend_from_slice(&after_where_clause.predicates);
65
66    let mut before = (generics.where_clause.has_where_token, generics.where_clause.span);
67    let mut after = (after_where_clause.has_where_token, after_where_clause.span);
68    if !prefer_first {
69        (before, after) = (after, before);
70    }
71    (generics.where_clause.has_where_token, generics.where_clause.span) =
72        if before.0 || !after.0 { before } else { after };
73}
74
75impl<'hir> ItemLowerer<'_, 'hir> {
76    fn with_lctx(
77        &mut self,
78        owner: NodeId,
79        f: impl for<'a> FnOnce(&mut LoweringContext<'a, 'hir>) -> hir::OwnerNode<'hir>,
80    ) {
81        let mut lctx = LoweringContext::new(self.tcx, self.resolver);
82        lctx.with_hir_id_owner(owner, |lctx| f(lctx));
83
84        for (def_id, info) in lctx.children {
85            let owner = self.owners.get_or_insert_mut(def_id);
86            if !#[allow(non_exhaustive_omitted_patterns)] match owner {
            hir::MaybeOwner::Phantom => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("duplicate copy of {0:?} in lctx.children",
                def_id));
    }
};assert!(
87                matches!(owner, hir::MaybeOwner::Phantom),
88                "duplicate copy of {def_id:?} in lctx.children"
89            );
90            *owner = info;
91        }
92    }
93
94    pub(super) fn lower_node(&mut self, def_id: LocalDefId) {
95        let owner = self.owners.get_or_insert_mut(def_id);
96        if let hir::MaybeOwner::Phantom = owner {
97            let node = self.ast_index[def_id];
98            match node {
99                AstOwner::NonOwner => {}
100                AstOwner::Crate(c) => {
101                    match (&self.resolver.owner_def_id(CRATE_NODE_ID), &CRATE_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);
        }
    }
};assert_eq!(self.resolver.owner_def_id(CRATE_NODE_ID), CRATE_DEF_ID);
102                    self.with_lctx(CRATE_NODE_ID, |lctx| {
103                        let module = lctx.lower_mod(&c.items, &c.spans);
104                        // FIXME(jdonszelman): is dummy span ever a problem here?
105                        lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, DUMMY_SP, Target::Crate);
106                        hir::OwnerNode::Crate(module)
107                    })
108                }
109                AstOwner::Item(item) => {
110                    self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
111                }
112                AstOwner::AssocItem(item, ctxt) => {
113                    self.with_lctx(item.id, |lctx| lctx.lower_assoc_item(item, ctxt))
114                }
115                AstOwner::ForeignItem(item) => self.with_lctx(item.id, |lctx| {
116                    hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item))
117                }),
118            }
119        }
120    }
121}
122
123impl<'hir> LoweringContext<'_, 'hir> {
124    pub(super) fn lower_mod(
125        &mut self,
126        items: &[Box<Item>],
127        spans: &ModSpans,
128    ) -> &'hir hir::Mod<'hir> {
129        self.arena.alloc(hir::Mod {
130            spans: hir::ModSpans {
131                inner_span: self.lower_span(spans.inner_span),
132                inject_use_span: self.lower_span(spans.inject_use_span),
133            },
134            item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
135        })
136    }
137
138    pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
139        let mut node_ids = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(hir::ItemId { owner_id: self.owner_id(i.id) });
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [hir::ItemId { owner_id: self.owner_id(i.id) }])))
    }
}smallvec![hir::ItemId { owner_id: self.owner_id(i.id) }];
140        if let ItemKind::Use(use_tree) = &i.kind {
141            self.lower_item_id_use_tree(use_tree, &mut node_ids);
142        }
143        node_ids
144    }
145
146    fn lower_item_id_use_tree(&mut self, tree: &UseTree, vec: &mut SmallVec<[hir::ItemId; 1]>) {
147        match &tree.kind {
148            UseTreeKind::Nested { items, .. } => {
149                for &(ref nested, id) in items {
150                    vec.push(hir::ItemId { owner_id: self.owner_id(id) });
151                    self.lower_item_id_use_tree(nested, vec);
152                }
153            }
154            UseTreeKind::Simple(..) | UseTreeKind::Glob(_) => {}
155        }
156    }
157
158    fn lower_eii_decl(
159        &mut self,
160        id: NodeId,
161        name: Ident,
162        EiiDecl { foreign_item, impl_unsafe }: &EiiDecl,
163    ) -> Option<hir::attrs::EiiDecl> {
164        self.lower_path_simple_eii(id, foreign_item).map(|did| hir::attrs::EiiDecl {
165            foreign_item: did,
166            impl_unsafe: *impl_unsafe,
167            name,
168        })
169    }
170
171    fn lower_eii_impl(
172        &mut self,
173        EiiImpl {
174            node_id,
175            eii_macro_path,
176            impl_safety,
177            span,
178            inner_span,
179            is_default,
180            known_eii_macro_resolution,
181        }: &EiiImpl,
182    ) -> hir::attrs::EiiImpl {
183        let resolution = if let Some(target) = known_eii_macro_resolution
184            && let Some(decl) = self.lower_eii_decl(
185                *node_id,
186                // the expect is ok here since we always generate this path in the eii macro.
187                eii_macro_path.segments.last().expect("at least one segment").ident,
188                target,
189            ) {
190            EiiImplResolution::Known(decl)
191        } else if let Some(macro_did) = self.lower_path_simple_eii(*node_id, eii_macro_path) {
192            EiiImplResolution::Macro(macro_did)
193        } else {
194            EiiImplResolution::Error(
195                self.dcx().span_delayed_bug(*span, "eii never resolved without errors given"),
196            )
197        };
198
199        hir::attrs::EiiImpl {
200            span: self.lower_span(*span),
201            inner_span: self.lower_span(*inner_span),
202            impl_marked_unsafe: self.lower_safety(*impl_safety, hir::Safety::Safe).is_unsafe(),
203            is_default: *is_default,
204            resolution,
205        }
206    }
207
208    fn generate_extra_attrs_for_item_kind(
209        &mut self,
210        id: NodeId,
211        i: &ItemKind,
212    ) -> Vec<hir::Attribute> {
213        match i {
214            ItemKind::Fn(Fn { eii_impls, .. }) | ItemKind::Static(StaticItem { eii_impls, .. })
215                if eii_impls.is_empty() =>
216            {
217                Vec::new()
218            }
219            ItemKind::Fn(Fn { eii_impls, .. }) | ItemKind::Static(StaticItem { eii_impls, .. }) => {
220                ::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(
221                    eii_impls.iter().map(|i| self.lower_eii_impl(i)).collect(),
222                ))]
223            }
224            ItemKind::MacroDef(name, MacroDef { eii_declaration: Some(target), .. }) => self
225                .lower_eii_decl(id, *name, target)
226                .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))])
227                .unwrap_or_default(),
228
229            ItemKind::ExternCrate(..)
230            | ItemKind::Use(..)
231            | ItemKind::Const(..)
232            | ItemKind::ConstBlock(..)
233            | ItemKind::Mod(..)
234            | ItemKind::ForeignMod(..)
235            | ItemKind::GlobalAsm(..)
236            | ItemKind::TyAlias(..)
237            | ItemKind::Enum(..)
238            | ItemKind::Struct(..)
239            | ItemKind::Union(..)
240            | ItemKind::Trait(..)
241            | ItemKind::TraitAlias(..)
242            | ItemKind::Impl(..)
243            | ItemKind::MacCall(..)
244            | ItemKind::MacroDef(..)
245            | ItemKind::Delegation(..)
246            | ItemKind::DelegationMac(..) => Vec::new(),
247        }
248    }
249
250    fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
251        let vis_span = self.lower_span(i.vis.span);
252        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
253
254        let extra_hir_attributes = self.generate_extra_attrs_for_item_kind(i.id, &i.kind);
255        let attrs = self.lower_attrs_with_extra(
256            hir_id,
257            &i.attrs,
258            i.span,
259            Target::from_ast_item(i),
260            &extra_hir_attributes,
261        );
262
263        let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind);
264        let item = hir::Item {
265            owner_id: hir_id.expect_owner(),
266            kind,
267            vis_span,
268            span: self.lower_span(i.span),
269            has_delayed_lints: !self.delayed_lints.is_empty(),
270            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(..)),
271        };
272        self.arena.alloc(item)
273    }
274
275    fn lower_item_kind(
276        &mut self,
277        span: Span,
278        id: NodeId,
279        hir_id: hir::HirId,
280        attrs: &'hir [hir::Attribute],
281        vis_span: Span,
282        i: &ItemKind,
283    ) -> hir::ItemKind<'hir> {
284        match i {
285            ItemKind::ExternCrate(orig_name, ident) => {
286                let ident = self.lower_ident(*ident);
287                hir::ItemKind::ExternCrate(*orig_name, ident)
288            }
289            ItemKind::Use(use_tree) => {
290                // Start with an empty prefix.
291                let prefix = Path {
292                    segments: ThinVec::new(),
293                    span: use_tree.prefix.span.shrink_to_lo(),
294                    tokens: None,
295                };
296
297                self.lower_use_tree(use_tree, &prefix, id, vis_span, attrs)
298            }
299            ItemKind::Static(ast::StaticItem {
300                ident,
301                ty,
302                safety: _,
303                mutability: m,
304                expr: e,
305                define_opaque,
306                eii_impls: _,
307            }) => {
308                let ident = self.lower_ident(*ident);
309                let ty = self
310                    .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
311                let body_id = self.lower_const_body(span, e.as_deref());
312                self.lower_define_opaque(hir_id, define_opaque);
313                hir::ItemKind::Static(*m, ident, ty, body_id)
314            }
315            ItemKind::Const(ConstItem {
316                defaultness: _,
317                ident,
318                generics,
319                ty,
320                rhs_kind,
321                define_opaque,
322            }) => {
323                let ident = self.lower_ident(*ident);
324                let (generics, (ty, rhs)) = self.lower_generics(
325                    generics,
326                    id,
327                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
328                    |this| {
329                        let ty = this.lower_ty_alloc(
330                            ty,
331                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
332                        );
333                        let rhs = this.lower_const_item_rhs(rhs_kind, span);
334                        (ty, rhs)
335                    },
336                );
337                self.lower_define_opaque(hir_id, &define_opaque);
338                hir::ItemKind::Const(ident, generics, ty, rhs)
339            }
340            ItemKind::ConstBlock(ConstBlockItem { span, id, block }) => hir::ItemKind::Const(
341                self.lower_ident(ConstBlockItem::IDENT),
342                hir::Generics::empty(),
343                self.arena.alloc(self.ty_tup(DUMMY_SP, &[])),
344                hir::ConstItemRhs::Body({
345                    let body = hir::Expr {
346                        hir_id: self.lower_node_id(*id),
347                        kind: hir::ExprKind::Block(self.lower_block(block, false), None),
348                        span: self.lower_span(*span),
349                    };
350                    self.record_body(&[], body)
351                }),
352            ),
353            ItemKind::Fn(Fn {
354                sig: FnSig { decl, header, span: fn_sig_span },
355                ident,
356                generics,
357                body,
358                contract,
359                define_opaque,
360                ..
361            }) => {
362                self.with_new_scopes(*fn_sig_span, |this| {
363                    // Note: we don't need to change the return type from `T` to
364                    // `impl Future<Output = T>` here because lower_body
365                    // only cares about the input argument patterns in the function
366                    // declaration (decl), not the return types.
367                    let coroutine_kind = header.coroutine_kind;
368                    let body_id = this.lower_maybe_coroutine_body(
369                        *fn_sig_span,
370                        span,
371                        hir_id,
372                        decl,
373                        coroutine_kind,
374                        body.as_deref(),
375                        attrs,
376                        contract.as_deref(),
377                    );
378
379                    let itctx = ImplTraitContext::Universal;
380                    let (generics, decl) = this.lower_generics(generics, id, itctx, |this| {
381                        this.lower_fn_decl(decl, id, *fn_sig_span, FnDeclKind::Fn, coroutine_kind)
382                    });
383                    let sig = hir::FnSig {
384                        decl,
385                        header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
386                        span: this.lower_span(*fn_sig_span),
387                    };
388                    this.lower_define_opaque(hir_id, define_opaque);
389                    let ident = this.lower_ident(*ident);
390                    hir::ItemKind::Fn {
391                        ident,
392                        sig,
393                        generics,
394                        body: body_id,
395                        has_body: body.is_some(),
396                    }
397                })
398            }
399            ItemKind::Mod(_, ident, mod_kind) => {
400                let ident = self.lower_ident(*ident);
401                match mod_kind {
402                    ModKind::Loaded(items, _, spans) => {
403                        hir::ItemKind::Mod(ident, self.lower_mod(items, spans))
404                    }
405                    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"),
406                }
407            }
408            ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
409                abi: fm.abi.map_or(ExternAbi::FALLBACK, |abi| self.lower_abi(abi)),
410                items: self
411                    .arena
412                    .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
413            },
414            ItemKind::GlobalAsm(asm) => {
415                let asm = self.lower_inline_asm(span, asm);
416                let fake_body =
417                    self.lower_body(|this| (&[], this.expr(span, hir::ExprKind::InlineAsm(asm))));
418                hir::ItemKind::GlobalAsm { asm, fake_body }
419            }
420            ItemKind::TyAlias(TyAlias { ident, generics, after_where_clause, ty, .. }) => {
421                // We lower
422                //
423                // type Foo = impl Trait
424                //
425                // to
426                //
427                // type Foo = Foo1
428                // opaque type Foo1: Trait
429                let ident = self.lower_ident(*ident);
430                let mut generics = generics.clone();
431                add_ty_alias_where_clause(&mut generics, after_where_clause, true);
432                let (generics, ty) = self.lower_generics(
433                    &generics,
434                    id,
435                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
436                    |this| match ty {
437                        None => {
438                            let guar = this.dcx().span_delayed_bug(
439                                span,
440                                "expected to lower type alias type, but it was missing",
441                            );
442                            this.arena.alloc(this.ty(span, hir::TyKind::Err(guar)))
443                        }
444                        Some(ty) => this.lower_ty_alloc(
445                            ty,
446                            ImplTraitContext::OpaqueTy {
447                                origin: hir::OpaqueTyOrigin::TyAlias {
448                                    parent: this.owner.def_id,
449                                    in_assoc_ty: false,
450                                },
451                            },
452                        ),
453                    },
454                );
455                hir::ItemKind::TyAlias(ident, generics, ty)
456            }
457            ItemKind::Enum(ident, generics, enum_definition) => {
458                let ident = self.lower_ident(*ident);
459                let (generics, variants) = self.lower_generics(
460                    generics,
461                    id,
462                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
463                    |this| {
464                        this.arena.alloc_from_iter(
465                            enum_definition.variants.iter().map(|x| this.lower_variant(i, x)),
466                        )
467                    },
468                );
469                hir::ItemKind::Enum(ident, generics, hir::EnumDef { variants })
470            }
471            ItemKind::Struct(ident, generics, struct_def) => {
472                let ident = self.lower_ident(*ident);
473                let (generics, struct_def) = self.lower_generics(
474                    generics,
475                    id,
476                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
477                    |this| this.lower_variant_data(hir_id, i, struct_def),
478                );
479                hir::ItemKind::Struct(ident, generics, struct_def)
480            }
481            ItemKind::Union(ident, generics, vdata) => {
482                let ident = self.lower_ident(*ident);
483                let (generics, vdata) = self.lower_generics(
484                    generics,
485                    id,
486                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
487                    |this| this.lower_variant_data(hir_id, i, vdata),
488                );
489                hir::ItemKind::Union(ident, generics, vdata)
490            }
491            ItemKind::Impl(Impl {
492                generics: ast_generics,
493                of_trait,
494                self_ty: ty,
495                items: impl_items,
496                constness,
497            }) => {
498                // Lower the "impl header" first. This ordering is important
499                // for in-band lifetimes! Consider `'a` here:
500                //
501                //     impl Foo<'a> for u32 {
502                //         fn method(&'a self) { .. }
503                //     }
504                //
505                // Because we start by lowering the `Foo<'a> for u32`
506                // part, we will add `'a` to the list of generics on
507                // the impl. When we then encounter it later in the
508                // method, it will not be considered an in-band
509                // lifetime to be added, but rather a reference to a
510                // parent lifetime.
511                let itctx = ImplTraitContext::Universal;
512                let (generics, (of_trait, lowered_ty)) =
513                    self.lower_generics(ast_generics, id, itctx, |this| {
514                        let of_trait = of_trait
515                            .as_deref()
516                            .map(|of_trait| this.lower_trait_impl_header(of_trait));
517
518                        let lowered_ty = this.lower_ty_alloc(
519                            ty,
520                            ImplTraitContext::Disallowed(ImplTraitPosition::ImplSelf),
521                        );
522
523                        (of_trait, lowered_ty)
524                    });
525
526                let new_impl_items = self
527                    .arena
528                    .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
529
530                let constness = self.lower_constness(*constness);
531
532                hir::ItemKind::Impl(hir::Impl {
533                    generics,
534                    of_trait,
535                    self_ty: lowered_ty,
536                    items: new_impl_items,
537                    constness,
538                })
539            }
540            ItemKind::Trait(Trait {
541                impl_restriction,
542                constness,
543                is_auto,
544                safety,
545                ident,
546                generics,
547                bounds,
548                items,
549            }) => {
550                let constness = self.lower_constness(*constness);
551                let impl_restriction = self.lower_impl_restriction(impl_restriction);
552                let ident = self.lower_ident(*ident);
553                let (generics, (safety, items, bounds)) = self.lower_generics(
554                    generics,
555                    id,
556                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
557                    |this| {
558                        let bounds = this.lower_param_bounds(
559                            bounds,
560                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::SuperTrait),
561                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
562                        );
563                        let items = this.arena.alloc_from_iter(
564                            items.iter().map(|item| this.lower_trait_item_ref(item)),
565                        );
566                        let safety = this.lower_safety(*safety, hir::Safety::Safe);
567                        (safety, items, bounds)
568                    },
569                );
570                hir::ItemKind::Trait {
571                    impl_restriction,
572                    constness,
573                    is_auto: *is_auto,
574                    safety,
575                    ident,
576                    generics,
577                    bounds,
578                    items,
579                }
580            }
581            ItemKind::TraitAlias(TraitAlias { constness, ident, generics, bounds }) => {
582                let constness = self.lower_constness(*constness);
583                let ident = self.lower_ident(*ident);
584                let (generics, bounds) = self.lower_generics(
585                    generics,
586                    id,
587                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
588                    |this| {
589                        this.lower_param_bounds(
590                            bounds,
591                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitAlias),
592                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
593                        )
594                    },
595                );
596                hir::ItemKind::TraitAlias(constness, ident, generics, bounds)
597            }
598            ItemKind::MacroDef(ident, MacroDef { body, macro_rules, eii_declaration: _ }) => {
599                let ident = self.lower_ident(*ident);
600                let body = Box::new(self.lower_delim_args(body));
601                let def_id = self.owner.def_id;
602                let def_kind = self.tcx.def_kind(def_id);
603                let DefKind::Macro(macro_kinds) = def_kind else {
604                    {
    ::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!(
605                        "expected DefKind::Macro for macro item, found {}",
606                        def_kind.descr(def_id.to_def_id())
607                    );
608                };
609                let macro_def = self.arena.alloc(ast::MacroDef {
610                    body,
611                    macro_rules: *macro_rules,
612                    eii_declaration: None,
613                });
614                hir::ItemKind::Macro(ident, macro_def, macro_kinds)
615            }
616            ItemKind::Delegation(delegation) => {
617                let delegation_results = self.lower_delegation(delegation, id);
618                hir::ItemKind::Fn {
619                    sig: delegation_results.sig,
620                    ident: delegation_results.ident,
621                    generics: delegation_results.generics,
622                    body: delegation_results.body_id,
623                    has_body: true,
624                }
625            }
626            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
627                {
    ::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
628            }
629        }
630    }
631
632    fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
633        let res = self.get_partial_res(id)?;
634        let Some(did) = res.expect_full_res().opt_def_id() else {
635            self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
636            return None;
637        };
638
639        Some(did)
640    }
641
642    #[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(642u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
                                    ::tracing_core::field::FieldSet::new(&["tree", "prefix",
                                                    "id", "vis_span", "attrs"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tree)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&prefix)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&attrs)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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