Skip to main content

rustc_ast_lowering/
item.rs

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