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