Skip to main content

rustc_ast_lowering/
item.rs

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