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