Skip to main content

rustc_ast_lowering/
item.rs

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