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