Skip to main content

rustc_ast_lowering/
item.rs

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