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