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