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