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