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