Skip to main content

rustc_ast_lowering/
item.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: (&'hir hir::Generics<'hir>, T) =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !self.impl_trait_defs.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_defs.is_empty()")
            };
            if !self.impl_trait_bounds.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_bounds.is_empty()")
            };
            let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> =
                SmallVec::new();
            predicates.extend(generics.params.iter().filter_map(|param|
                        {
                            self.lower_generic_bound_predicate(param.ident, param.id,
                                &param.kind, &param.bounds, param.colon_span, generics.span,
                                RelaxedBoundPolicy::Allowed, itctx,
                                PredicateOrigin::GenericParam)
                        }));
            predicates.extend(generics.where_clause.predicates.iter().map(|predicate|
                        self.lower_where_predicate(predicate, &generics.params)));
            let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
                self.lower_generic_params_mut(&generics.params,
                        hir::GenericParamSource::Generics).collect();
            let extra_lifetimes =
                self.resolver.extra_lifetime_params(parent_node_id);
            params.extend(extra_lifetimes.into_iter().filter_map(|(ident,
                            node_id, res)|
                        {
                            self.lifetime_res_to_generic_param(ident, node_id, res,
                                hir::GenericParamSource::Generics)
                        }));
            let has_where_clause_predicates =
                !generics.where_clause.predicates.is_empty();
            let where_clause_span =
                self.lower_span(generics.where_clause.span);
            let span = self.lower_span(generics.span);
            let res = f(self);
            let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
            params.extend(impl_trait_defs.into_iter());
            let impl_trait_bounds =
                std::mem::take(&mut self.impl_trait_bounds);
            predicates.extend(impl_trait_bounds.into_iter());
            let lowered_generics =
                self.arena.alloc(hir::Generics {
                        params: self.arena.alloc_from_iter(params),
                        predicates: self.arena.alloc_from_iter(predicates),
                        has_where_clause_predicates,
                        where_clause_span,
                        span,
                    });
            (lowered_generics, res)
        }
    }
}#[instrument(level = "debug", skip(self, f))]
1878    fn lower_generics<T>(
1879        &mut self,
1880        generics: &Generics,
1881        parent_node_id: NodeId,
1882        itctx: ImplTraitContext,
1883        f: impl FnOnce(&mut Self) -> T,
1884    ) -> (&'hir hir::Generics<'hir>, T) {
1885        assert!(self.impl_trait_defs.is_empty());
1886        assert!(self.impl_trait_bounds.is_empty());
1887
1888        let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1889        predicates.extend(generics.params.iter().filter_map(|param| {
1890            self.lower_generic_bound_predicate(
1891                param.ident,
1892                param.id,
1893                &param.kind,
1894                &param.bounds,
1895                param.colon_span,
1896                generics.span,
1897                RelaxedBoundPolicy::Allowed,
1898                itctx,
1899                PredicateOrigin::GenericParam,
1900            )
1901        }));
1902        predicates.extend(
1903            generics
1904                .where_clause
1905                .predicates
1906                .iter()
1907                .map(|predicate| self.lower_where_predicate(predicate, &generics.params)),
1908        );
1909
1910        let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> = self
1911            .lower_generic_params_mut(&generics.params, hir::GenericParamSource::Generics)
1912            .collect();
1913
1914        // Introduce extra lifetimes if late resolution tells us to.
1915        let extra_lifetimes = self.resolver.extra_lifetime_params(parent_node_id);
1916        params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1917            self.lifetime_res_to_generic_param(
1918                ident,
1919                node_id,
1920                res,
1921                hir::GenericParamSource::Generics,
1922            )
1923        }));
1924
1925        let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1926        let where_clause_span = self.lower_span(generics.where_clause.span);
1927        let span = self.lower_span(generics.span);
1928        let res = f(self);
1929
1930        let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1931        params.extend(impl_trait_defs.into_iter());
1932
1933        let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1934        predicates.extend(impl_trait_bounds.into_iter());
1935
1936        let lowered_generics = self.arena.alloc(hir::Generics {
1937            params: self.arena.alloc_from_iter(params),
1938            predicates: self.arena.alloc_from_iter(predicates),
1939            has_where_clause_predicates,
1940            where_clause_span,
1941            span,
1942        });
1943
1944        (lowered_generics, res)
1945    }
1946
1947    pub(super) fn lower_define_opaque(
1948        &mut self,
1949        hir_id: HirId,
1950        define_opaque: &Option<ThinVec<(NodeId, Path)>>,
1951    ) {
1952        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);
1953        if !hir_id.is_owner() {
    ::core::panicking::panic("assertion failed: hir_id.is_owner()")
};assert!(hir_id.is_owner());
1954        let Some(define_opaque) = define_opaque.as_ref() else {
1955            return;
1956        };
1957        let define_opaque = define_opaque.iter().filter_map(|(id, path)| {
1958            let res = self.resolver.get_partial_res(*id);
1959            let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else {
1960                self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1961                return None;
1962            };
1963            let Some(did) = did.as_local() else {
1964                self.dcx().span_err(
1965                    path.span,
1966                    "only opaque types defined in the local crate can be defined",
1967                );
1968                return None;
1969            };
1970            Some((self.lower_span(path.span), did))
1971        });
1972        let define_opaque = self.arena.alloc_from_iter(define_opaque);
1973        self.define_opaque = Some(define_opaque);
1974    }
1975
1976    pub(super) fn lower_generic_bound_predicate(
1977        &mut self,
1978        ident: Ident,
1979        id: NodeId,
1980        kind: &GenericParamKind,
1981        bounds: &[GenericBound],
1982        colon_span: Option<Span>,
1983        parent_span: Span,
1984        rbp: RelaxedBoundPolicy<'_>,
1985        itctx: ImplTraitContext,
1986        origin: PredicateOrigin,
1987    ) -> Option<hir::WherePredicate<'hir>> {
1988        // Do not create a clause if we do not have anything inside it.
1989        if bounds.is_empty() {
1990            return None;
1991        }
1992
1993        let bounds = self.lower_param_bounds(bounds, rbp, itctx);
1994
1995        let param_span = ident.span;
1996
1997        // Reconstruct the span of the entire predicate from the individual generic bounds.
1998        let span_start = colon_span.unwrap_or_else(|| param_span.shrink_to_hi());
1999        let span = bounds.iter().fold(span_start, |span_accum, bound| {
2000            match bound.span().find_ancestor_inside(parent_span) {
2001                Some(bound_span) => span_accum.to(bound_span),
2002                None => span_accum,
2003            }
2004        });
2005        let span = self.lower_span(span);
2006        let hir_id = self.next_id();
2007        let kind = self.arena.alloc(match kind {
2008            GenericParamKind::Const { .. } => return None,
2009            GenericParamKind::Type { .. } => {
2010                let def_id = self.local_def_id(id).to_def_id();
2011                let hir_id = self.next_id();
2012                let res = Res::Def(DefKind::TyParam, def_id);
2013                let ident = self.lower_ident(ident);
2014                let ty_path = self.arena.alloc(hir::Path {
2015                    span: self.lower_span(param_span),
2016                    res,
2017                    segments: self
2018                        .arena
2019                        .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
2020                });
2021                let ty_id = self.next_id();
2022                let bounded_ty =
2023                    self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
2024                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2025                    bounded_ty: self.arena.alloc(bounded_ty),
2026                    bounds,
2027                    bound_generic_params: &[],
2028                    origin,
2029                })
2030            }
2031            GenericParamKind::Lifetime => {
2032                let lt_id = self.next_node_id();
2033                let lifetime =
2034                    self.new_named_lifetime(id, lt_id, ident, LifetimeSource::Other, ident.into());
2035                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2036                    lifetime,
2037                    bounds,
2038                    in_where_clause: false,
2039                })
2040            }
2041        });
2042        Some(hir::WherePredicate { hir_id, span, kind })
2043    }
2044
2045    fn lower_where_predicate(
2046        &mut self,
2047        pred: &WherePredicate,
2048        params: &[ast::GenericParam],
2049    ) -> hir::WherePredicate<'hir> {
2050        let hir_id = self.lower_node_id(pred.id);
2051        let span = self.lower_span(pred.span);
2052        self.lower_attrs(hir_id, &pred.attrs, span, Target::WherePredicate);
2053        let kind = self.arena.alloc(match &pred.kind {
2054            WherePredicateKind::BoundPredicate(WhereBoundPredicate {
2055                bound_generic_params,
2056                bounded_ty,
2057                bounds,
2058            }) => {
2059                let rbp = if bound_generic_params.is_empty() {
2060                    RelaxedBoundPolicy::AllowedIfOnTyParam(bounded_ty.id, params)
2061                } else {
2062                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::LateBoundVarsInScope)
2063                };
2064                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2065                    bound_generic_params: self.lower_generic_params(
2066                        bound_generic_params,
2067                        hir::GenericParamSource::Binder,
2068                    ),
2069                    bounded_ty: self.lower_ty_alloc(
2070                        bounded_ty,
2071                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2072                    ),
2073                    bounds: self.lower_param_bounds(
2074                        bounds,
2075                        rbp,
2076                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2077                    ),
2078                    origin: PredicateOrigin::WhereClause,
2079                })
2080            }
2081            WherePredicateKind::RegionPredicate(WhereRegionPredicate { lifetime, bounds }) => {
2082                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2083                    lifetime: self.lower_lifetime(
2084                        lifetime,
2085                        LifetimeSource::Other,
2086                        lifetime.ident.into(),
2087                    ),
2088                    bounds: self.lower_param_bounds(
2089                        bounds,
2090                        RelaxedBoundPolicy::Allowed,
2091                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2092                    ),
2093                    in_where_clause: true,
2094                })
2095            }
2096            WherePredicateKind::EqPredicate(WhereEqPredicate { lhs_ty, rhs_ty }) => {
2097                hir::WherePredicateKind::EqPredicate(hir::WhereEqPredicate {
2098                    lhs_ty: self.lower_ty_alloc(
2099                        lhs_ty,
2100                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2101                    ),
2102                    rhs_ty: self.lower_ty_alloc(
2103                        rhs_ty,
2104                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2105                    ),
2106                })
2107            }
2108        });
2109        hir::WherePredicate { hir_id, span, kind }
2110    }
2111}