Skip to main content

rustc_ast_lowering/
item.rs

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