Skip to main content

rustc_hir_analysis/hir_ty_lowering/
mod.rs

1//! HIR ty lowering: Lowers type-system entities[^1] from the [HIR][hir] to
2//! the [`rustc_middle::ty`] representation.
3//!
4//! Not to be confused with *AST lowering* which lowers AST constructs to HIR ones
5//! or with *THIR* / *MIR* *lowering* / *building* which lowers HIR *bodies*
6//! (i.e., “executable code”) to THIR / MIR.
7//!
8//! Most lowering routines are defined on [`dyn HirTyLowerer`](HirTyLowerer) directly,
9//! like the main routine of this module, `lower_ty`.
10//!
11//! This module used to be called `astconv`.
12//!
13//! [^1]: This includes types, lifetimes / regions, constants in type positions,
14//! trait references and bounds.
15
16mod bounds;
17mod cmse;
18mod dyn_trait;
19pub mod errors;
20pub mod generics;
21
22use std::{assert_matches, slice};
23
24use rustc_abi::FIRST_VARIANT;
25use rustc_ast::LitKind;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_data_structures::sso::SsoHashSet;
28use rustc_data_structures::thin_vec::ThinVec;
29use rustc_errors::codes::*;
30use rustc_errors::{
31    Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, StashKey,
32    struct_span_code_err,
33};
34use rustc_hir::attrs::lang_items::LangItem;
35use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
36use rustc_hir::def_id::{DefId, LocalDefId};
37use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
38use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
39use rustc_infer::traits::DynCompatibilityViolation;
40use rustc_macros::{TypeFoldable, TypeVisitable};
41use rustc_middle::middle::stability::AllowUnstable;
42use rustc_middle::ty::{
43    self, Const, FnSigKind, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput,
44    RegionExt, Ty, TyCtxt, TypeSuperFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast,
45    const_lit_matches_ty, fold_regions,
46};
47use rustc_middle::{bug, span_bug};
48use rustc_session::diagnostics::feature_err;
49use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
50use rustc_span::def_id::ModId;
51use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
52use rustc_trait_selection::infer::InferCtxtExt;
53use rustc_trait_selection::traits::{self, FulfillmentError};
54use tracing::{debug, instrument};
55
56use crate::check::check_abi;
57use crate::check_c_variadic_abi;
58use crate::diagnostics::{self, BadReturnTypeNotation, NoFieldOnType, NoVariantNamed};
59use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
60use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
61use crate::middle::resolve_bound_vars as rbv;
62
63/// The context in which an implied bound is being added to a item being lowered (i.e. a sizedness
64/// trait or a default trait)
65#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImpliedBoundsContext<'tcx> {
    #[inline]
    fn clone(&self) -> ImpliedBoundsContext<'tcx> {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _:
                ::core::clone::AssertParamIsClone<&'tcx [hir::WherePredicate<'tcx>]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ImpliedBoundsContext<'tcx> { }Copy)]
66pub(crate) enum ImpliedBoundsContext<'tcx> {
67    /// An implied bound is added to a trait definition (i.e. a new supertrait), used when adding
68    /// a default `MetaSized` supertrait
69    TraitDef(LocalDefId),
70    /// An implied bound is added to a type parameter
71    TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
72    /// An implied bound being added in any other context
73    AssociatedTypeOrImplTrait,
74}
75
76/// A path segment that is semantically allowed to have generic arguments.
77#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericPathSegment {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field2_finish(f,
            "GenericPathSegment", &self.0, &&self.1)
    }
}Debug)]
78pub struct GenericPathSegment(pub DefId, pub usize);
79
80#[derive(#[automatically_derived]
impl ::core::marker::Copy for PredicateFilter { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PredicateFilter {
    #[inline]
    fn clone(&self) -> PredicateFilter {
        let _: ::core::clone::AssertParamIsClone<Ident>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PredicateFilter {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PredicateFilter::All =>
                ::core::fmt::Formatter::write_str(f, "All"),
            PredicateFilter::SelfOnly =>
                ::core::fmt::Formatter::write_str(f, "SelfOnly"),
            PredicateFilter::SelfTraitThatDefines(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "SelfTraitThatDefines", &__self_0),
            PredicateFilter::SelfAndAssociatedTypeBounds =>
                ::core::fmt::Formatter::write_str(f,
                    "SelfAndAssociatedTypeBounds"),
            PredicateFilter::ConstIfConst =>
                ::core::fmt::Formatter::write_str(f, "ConstIfConst"),
            PredicateFilter::SelfConstIfConst =>
                ::core::fmt::Formatter::write_str(f, "SelfConstIfConst"),
        }
    }
}Debug)]
81pub enum PredicateFilter {
82    /// All predicates may be implied by the trait.
83    All,
84
85    /// Only traits that reference `Self: ..` are implied by the trait.
86    SelfOnly,
87
88    /// Only traits that reference `Self: ..` and define an associated type
89    /// with the given ident are implied by the trait. This mode exists to
90    /// side-step query cycles when lowering associated types.
91    SelfTraitThatDefines(Ident),
92
93    /// Only traits that reference `Self: ..` and their associated type bounds.
94    /// For example, given `Self: Tr<A: B>`, this would expand to `Self: Tr`
95    /// and `<Self as Tr>::A: B`.
96    SelfAndAssociatedTypeBounds,
97
98    /// Filter only the `[const]` bounds, which are lowered into `HostEffect` clauses.
99    ConstIfConst,
100
101    /// Filter only the `[const]` bounds which are *also* in the supertrait position.
102    SelfConstIfConst,
103}
104
105#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for RegionInferReason<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RegionInferReason::ExplicitObjectLifetime =>
                ::core::fmt::Formatter::write_str(f,
                    "ExplicitObjectLifetime"),
            RegionInferReason::ObjectLifetimeDefault(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ObjectLifetimeDefault", &__self_0),
            RegionInferReason::Param(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Param",
                    &__self_0),
            RegionInferReason::RegionPredicate =>
                ::core::fmt::Formatter::write_str(f, "RegionPredicate"),
            RegionInferReason::Reference =>
                ::core::fmt::Formatter::write_str(f, "Reference"),
            RegionInferReason::OutlivesBound =>
                ::core::fmt::Formatter::write_str(f, "OutlivesBound"),
        }
    }
}Debug)]
106pub enum RegionInferReason<'a> {
107    /// Lifetime on a trait object that is spelled explicitly, e.g. `+ 'a` or `+ '_`.
108    ExplicitObjectLifetime,
109    /// A trait object's lifetime when it is elided, e.g. `dyn Any`.
110    ObjectLifetimeDefault(Span),
111    /// Generic lifetime parameter
112    Param(&'a ty::GenericParamDef),
113    RegionPredicate,
114    Reference,
115    OutlivesBound,
116}
117
118#[derive(#[automatically_derived]
impl ::core::marker::Copy for InherentAssocCandidate { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InherentAssocCandidate {
    #[inline]
    fn clone(&self) -> InherentAssocCandidate {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<ModId>;
        *self
    }
}Clone, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for InherentAssocCandidate {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        InherentAssocCandidate {
                            impl_: __binding_0,
                            assoc_item: __binding_1,
                            scope: __binding_2 } => {
                            InherentAssocCandidate {
                                impl_: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                assoc_item: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                scope: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    InherentAssocCandidate {
                        impl_: __binding_0,
                        assoc_item: __binding_1,
                        scope: __binding_2 } => {
                        InherentAssocCandidate {
                            impl_: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            assoc_item: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            scope: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for InherentAssocCandidate {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    InherentAssocCandidate {
                        impl_: ref __binding_0,
                        assoc_item: ref __binding_1,
                        scope: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, #[automatically_derived]
impl ::core::fmt::Debug for InherentAssocCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "InherentAssocCandidate", "impl_", &self.impl_, "assoc_item",
            &self.assoc_item, "scope", &&self.scope)
    }
}Debug)]
119pub struct InherentAssocCandidate {
120    pub impl_: DefId,
121    pub assoc_item: DefId,
122    pub scope: ModId,
123}
124
125pub struct ResolvedStructPath<'tcx> {
126    pub res: Result<Res, ErrorGuaranteed>,
127    pub ty: Ty<'tcx>,
128}
129
130/// A context which can lower type-system entities from the [HIR][hir] to
131/// the [`rustc_middle::ty`] representation.
132///
133/// This trait used to be called `AstConv`.
134pub trait HirTyLowerer<'tcx> {
135    fn tcx(&self) -> TyCtxt<'tcx>;
136
137    fn dcx(&self) -> DiagCtxtHandle<'_>;
138
139    /// Returns the [`LocalDefId`] of the overarching item whose constituents get lowered.
140    fn item_def_id(&self) -> LocalDefId;
141
142    /// Returns the region to use when a lifetime is omitted (and not elided).
143    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
144
145    /// Returns the type to use when a type is omitted.
146    fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
147
148    /// Returns the const to use when a const is omitted.
149    fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
150
151    fn register_trait_ascription_bounds(
152        &self,
153        bounds: Vec<(ty::Clause<'tcx>, Span)>,
154        hir_id: HirId,
155        span: Span,
156    );
157
158    /// Probe bounds in scope where the bounded type coincides with the given type parameter.
159    ///
160    /// Rephrased, this returns bounds of the form `T: Trait`, where `T` is a type parameter
161    /// with the given `def_id`. This is a subset of the full set of bounds.
162    ///
163    /// This method may use the given `assoc_name` to disregard bounds whose trait reference
164    /// doesn't define an associated item with the provided name.
165    ///
166    /// This is used for one specific purpose: Resolving “short-hand” associated type references
167    /// like `T::Item` where `T` is a type parameter. In principle, we would do that by first
168    /// getting the full set of predicates in scope and then filtering down to find those that
169    /// apply to `T`, but this can lead to cycle errors. The problem is that we have to do this
170    /// resolution *in order to create the predicates in the first place*.
171    /// Hence, we have this “special pass”.
172    fn probe_ty_param_bounds(
173        &self,
174        span: Span,
175        def_id: LocalDefId,
176        assoc_ident: Ident,
177    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
178
179    fn select_inherent_assoc_candidates(
180        &self,
181        span: Span,
182        self_ty: Ty<'tcx>,
183        candidates: Vec<InherentAssocCandidate>,
184    ) -> (Vec<InherentAssocCandidate>, ThinVec<FulfillmentError<'tcx>>);
185
186    /// Lower a path to an associated item (of a trait) to a projection.
187    ///
188    /// This method has to be defined by the concrete lowering context because
189    /// dealing with higher-ranked trait references depends on its capabilities:
190    ///
191    /// If the context can make use of type inference, it can simply instantiate
192    /// any late-bound vars bound by the trait reference with inference variables.
193    /// If it doesn't support type inference, there is nothing reasonable it can
194    /// do except reject the associated type.
195    ///
196    /// The canonical example of this is associated type `T::P` where `T` is a type
197    /// param constrained by `T: for<'a> Trait<'a>` and where `Trait` defines `P`.
198    fn lower_assoc_item_path(
199        &self,
200        span: Span,
201        item_def_id: DefId,
202        item_segment: &hir::PathSegment<'_>,
203        poly_trait_ref: ty::PolyTraitRef<'tcx>,
204    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
205
206    fn lower_fn_sig(
207        &self,
208        decl: &hir::FnDecl<'_>,
209        generics: Option<&hir::Generics<'_>>,
210        hir_id: HirId,
211        hir_ty: Option<&hir::Ty<'_>>,
212    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
213
214    /// Returns `AdtDef` if `ty` is an ADT.
215    ///
216    /// Note that `ty` might be a alias type that needs normalization.
217    /// This used to get the enum variants in scope of the type.
218    /// For example, `Self::A` could refer to an associated type
219    /// or to an enum variant depending on the result of this function.
220    fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
221
222    /// Record the lowered type of a HIR node in this context.
223    fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
224
225    /// The inference context of the lowering context if applicable.
226    fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
227
228    /// Convenience method for coercing the lowering context into a trait object type.
229    ///
230    /// Most lowering routines are defined on the trait object type directly
231    /// necessitating a coercion step from the concrete lowering context.
232    fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
233    where
234        Self: Sized,
235    {
236        self
237    }
238
239    /// Performs minimalistic dyn compat checks outside of bodies, but full within bodies.
240    /// Outside of bodies we could end up in cycles, so we delay most checks to later phases.
241    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
242}
243
244/// The "qualified self" of an associated item path.
245///
246/// For diagnostic purposes only.
247enum AssocItemQSelf {
248    Trait(DefId),
249    TyParam(LocalDefId, Span),
250    SelfTyAlias,
251}
252
253impl AssocItemQSelf {
254    fn to_string(&self, tcx: TyCtxt<'_>) -> String {
255        match *self {
256            Self::Trait(def_id) => tcx.def_path_str(def_id),
257            Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
258            Self::SelfTyAlias => kw::SelfUpper.to_string(),
259        }
260    }
261}
262
263#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LowerTypeRelativePathMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LowerTypeRelativePathMode::Type(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Type",
                    &__self_0),
            LowerTypeRelativePathMode::Const =>
                ::core::fmt::Formatter::write_str(f, "Const"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for LowerTypeRelativePathMode {
    #[inline]
    fn clone(&self) -> LowerTypeRelativePathMode {
        let _: ::core::clone::AssertParamIsClone<PermitVariants>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LowerTypeRelativePathMode { }Copy)]
264enum LowerTypeRelativePathMode {
265    Type(PermitVariants),
266    Const,
267}
268
269impl LowerTypeRelativePathMode {
270    fn assoc_tag(self) -> ty::AssocTag {
271        match self {
272            Self::Type(_) => ty::AssocTag::Type,
273            Self::Const => ty::AssocTag::Const,
274        }
275    }
276
277    ///NOTE: use `assoc_tag` for any important logic
278    fn def_kind_for_diagnostics(self) -> DefKind {
279        match self {
280            Self::Type(_) => DefKind::AssocTy,
281            Self::Const => DefKind::AssocConst { is_type_const: false },
282        }
283    }
284
285    fn permit_variants(self) -> PermitVariants {
286        match self {
287            Self::Type(permit_variants) => permit_variants,
288            // FIXME(mgca): Support paths like `Option::<T>::None` or `Option::<T>::Some` which
289            // resolve to const ctors/fn items respectively.
290            Self::Const => PermitVariants::No,
291        }
292    }
293}
294
295/// Whether to permit a path to resolve to an enum variant.
296#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PermitVariants {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PermitVariants::Yes => "Yes",
                PermitVariants::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for PermitVariants {
    #[inline]
    fn clone(&self) -> PermitVariants { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PermitVariants { }Copy)]
297pub enum PermitVariants {
298    Yes,
299    No,
300}
301
302#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeRelativePath<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TypeRelativePath::AssocItem(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AssocItem", &__self_0),
            TypeRelativePath::Variant { adt: __self_0, variant_did: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Variant", "adt", __self_0, "variant_did", &__self_1),
            TypeRelativePath::Ctor { ctor_def_id: __self_0, args: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Ctor",
                    "ctor_def_id", __self_0, "args", &__self_1),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeRelativePath<'tcx> {
    #[inline]
    fn clone(&self) -> TypeRelativePath<'tcx> {
        let _: ::core::clone::AssertParamIsClone<ty::AliasTerm<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
303enum TypeRelativePath<'tcx> {
304    AssocItem(ty::AliasTerm<'tcx>),
305    Variant { adt: Ty<'tcx>, variant_did: DefId },
306    Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
307}
308
309/// New-typed boolean indicating whether explicit late-bound lifetimes
310/// are present in a set of generic arguments.
311///
312/// For example if we have some method `fn f<'a>(&'a self)` implemented
313/// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
314/// is late-bound so should not be provided explicitly. Thus, if `f` is
315/// instantiated with some generic arguments providing `'a` explicitly,
316/// we taint those arguments with `ExplicitLateBound::Yes` so that we
317/// can provide an appropriate diagnostic later.
318#[derive(#[automatically_derived]
impl ::core::marker::Copy for ExplicitLateBound { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ExplicitLateBound {
    #[inline]
    fn clone(&self) -> ExplicitLateBound { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ExplicitLateBound {
    #[inline]
    fn eq(&self, other: &ExplicitLateBound) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for ExplicitLateBound {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ExplicitLateBound::Yes => "Yes",
                ExplicitLateBound::No => "No",
            })
    }
}Debug)]
319pub enum ExplicitLateBound {
320    Yes,
321    No,
322}
323
324#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IsMethodCall {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                IsMethodCall::Yes => "Yes",
                IsMethodCall::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for IsMethodCall { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsMethodCall {
    #[inline]
    fn clone(&self) -> IsMethodCall { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for IsMethodCall {
    #[inline]
    fn eq(&self, other: &IsMethodCall) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
325pub enum IsMethodCall {
326    Yes,
327    No,
328}
329
330/// Denotes the "position" of a generic argument, indicating if it is a generic type,
331/// generic function or generic method call.
332#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericArgPosition {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            GenericArgPosition::Type =>
                ::core::fmt::Formatter::write_str(f, "Type"),
            GenericArgPosition::Value(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Value",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for GenericArgPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for GenericArgPosition {
    #[inline]
    fn clone(&self) -> GenericArgPosition {
        let _: ::core::clone::AssertParamIsClone<IsMethodCall>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for GenericArgPosition {
    #[inline]
    fn eq(&self, other: &GenericArgPosition) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (GenericArgPosition::Value(__self_0),
                    GenericArgPosition::Value(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
333pub(crate) enum GenericArgPosition {
334    Type,
335    Value(IsMethodCall),
336}
337
338/// Whether to allow duplicate associated iten constraints in a trait ref, e.g.
339/// `Trait<Assoc = Ty, Assoc = Ty>`. This is forbidden in `dyn Trait<...>`
340/// but allowed everywhere else.
341#[derive(#[automatically_derived]
impl ::core::clone::Clone for OverlappingAsssocItemConstraints {
    #[inline]
    fn clone(&self) -> OverlappingAsssocItemConstraints { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for OverlappingAsssocItemConstraints { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for OverlappingAsssocItemConstraints {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                OverlappingAsssocItemConstraints::Allowed => "Allowed",
                OverlappingAsssocItemConstraints::Forbidden => "Forbidden",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for OverlappingAsssocItemConstraints {
    #[inline]
    fn eq(&self, other: &OverlappingAsssocItemConstraints) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
342pub(crate) enum OverlappingAsssocItemConstraints {
343    Allowed,
344    Forbidden,
345}
346
347/// A marker denoting that the generic arguments that were
348/// provided did not match the respective generic parameters.
349#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericArgCountMismatch {
    #[inline]
    fn clone(&self) -> GenericArgCountMismatch {
        GenericArgCountMismatch {
            reported: ::core::clone::Clone::clone(&self.reported),
            invalid_args: ::core::clone::Clone::clone(&self.invalid_args),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericArgCountMismatch {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "GenericArgCountMismatch", "reported", &self.reported,
            "invalid_args", &&self.invalid_args)
    }
}Debug)]
350pub struct GenericArgCountMismatch {
351    pub reported: ErrorGuaranteed,
352    /// A list of indices of arguments provided that were not valid.
353    pub invalid_args: Vec<usize>,
354}
355
356/// Decorates the result of a generic argument count mismatch
357/// check with whether explicit late bounds were provided.
358#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericArgCountResult {
    #[inline]
    fn clone(&self) -> GenericArgCountResult {
        GenericArgCountResult {
            explicit_late_bound: ::core::clone::Clone::clone(&self.explicit_late_bound),
            correct: ::core::clone::Clone::clone(&self.correct),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericArgCountResult {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "GenericArgCountResult", "explicit_late_bound",
            &self.explicit_late_bound, "correct", &&self.correct)
    }
}Debug)]
359pub struct GenericArgCountResult {
360    pub explicit_late_bound: ExplicitLateBound,
361    pub correct: Result<(), GenericArgCountMismatch>,
362}
363
364/// A context which can lower HIR's [`GenericArg`] to `rustc_middle`'s [`ty::GenericArg`].
365///
366/// Its only consumer is [`generics::lower_generic_args`].
367/// Read its documentation to learn more.
368pub trait GenericArgsLowerer<'a, 'tcx> {
369    fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
370
371    fn provided_kind(
372        &mut self,
373        preceding_args: &[ty::GenericArg<'tcx>],
374        param: &ty::GenericParamDef,
375        arg: &GenericArg<'_>,
376    ) -> ty::GenericArg<'tcx>;
377
378    fn inferred_kind(
379        &mut self,
380        preceding_args: &[ty::GenericArg<'tcx>],
381        param: &ty::GenericParamDef,
382        infer_args: bool,
383    ) -> ty::GenericArg<'tcx>;
384}
385
386/// Context in which `ForbidParamUsesFolder` is being used, to emit appropriate diagnostics.
387enum ForbidParamContext {
388    /// Anon const in a const argument position.
389    ConstArgument,
390    /// Enum discriminant expression.
391    EnumDiscriminant,
392}
393
394struct ForbidParamUsesFolder<'tcx> {
395    tcx: TyCtxt<'tcx>,
396    anon_const_def_id: LocalDefId,
397    span: Span,
398    is_self_alias: bool,
399    context: ForbidParamContext,
400}
401
402impl<'tcx> ForbidParamUsesFolder<'tcx> {
403    fn error(&self) -> ErrorGuaranteed {
404        let msg = match self.context {
405            ForbidParamContext::EnumDiscriminant if self.is_self_alias => {
406                "generic `Self` types are not permitted in enum discriminant values"
407            }
408            ForbidParamContext::EnumDiscriminant => {
409                "generic parameters may not be used in enum discriminant values"
410            }
411            ForbidParamContext::ConstArgument if self.is_self_alias => {
412                "generic `Self` types are currently not permitted in anonymous constants"
413            }
414            ForbidParamContext::ConstArgument => {
415                if self.tcx.features().generic_const_args() {
416                    "generic parameters in const blocks are not allowed; use a named `const` item instead"
417                } else {
418                    "generic parameters may not be used in const operations"
419                }
420            }
421        };
422        let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
423        if self.is_self_alias && #[allow(non_exhaustive_omitted_patterns)] match self.context {
    ForbidParamContext::ConstArgument => true,
    _ => false,
}matches!(self.context, ForbidParamContext::ConstArgument) {
424            let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
425            let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
426                |(_, node)| match node {
427                    hir::OwnerNode::Item(hir::Item {
428                        kind: hir::ItemKind::Impl(impl_), ..
429                    }) => Some(impl_),
430                    _ => None,
431                },
432            );
433            if let Some(impl_) = parent_impl {
434                diag.span_note(impl_.self_ty.span, "not a concrete type");
435            }
436        }
437        if #[allow(non_exhaustive_omitted_patterns)] match self.context {
    ForbidParamContext::ConstArgument => true,
    _ => false,
}matches!(self.context, ForbidParamContext::ConstArgument) {
438            if self.tcx.features().generic_const_args() {
439                diag.help("consider factoring the expression into a `type const` item and use it as the const argument instead");
440            } else if self.tcx.features().min_generic_const_args() {
441                diag.help("add `#![feature(generic_const_args)]` and extract the expression into a `type const` item");
442            } else if self.tcx.sess.is_nightly_build() {
443                diag.help(
444                    "add `#![feature(generic_const_exprs)]` to allow generic const expressions",
445                );
446                diag.help("alternatively, you can use `#![feature(generic_const_args)]` and extract the expression into a `type const` item");
447            }
448        }
449        diag.emit()
450    }
451}
452
453impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidParamUsesFolder<'tcx> {
454    fn cx(&self) -> TyCtxt<'tcx> {
455        self.tcx
456    }
457
458    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
459        if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
    ty::Param(..) => true,
    _ => false,
}matches!(t.kind(), ty::Param(..)) {
460            return Ty::new_error(self.tcx, self.error());
461        }
462        t.super_fold_with(self)
463    }
464
465    fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
466        if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
    ty::ConstKind::Param(..) => true,
    _ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
467            return Const::new_error(self.tcx, self.error());
468        }
469        c.super_fold_with(self)
470    }
471
472    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
473        if #[allow(non_exhaustive_omitted_patterns)] match r.kind() {
    ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..) =>
        true,
    _ => false,
}matches!(r.kind(), ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..)) {
474            return ty::Region::new_error(self.tcx, self.error());
475        }
476        r
477    }
478}
479
480impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
481    /// See `check_param_uses_if_mcg`.
482    ///
483    /// FIXME(mgca): this is pub only for instantiate_value_path and would be nice to avoid altogether
484    pub fn check_param_res_if_mcg_for_instantiate_value_path(
485        &self,
486        res: Res,
487        span: Span,
488    ) -> Result<(), ErrorGuaranteed> {
489        let tcx = self.tcx();
490        let parent_def_id = self.item_def_id();
491        // In this path, `Some(context)` should be `ConstArgument`: enum
492        // discriminants are handled earlier by resolve. We still use the helper so
493        // nested inline consts are checked in the outer const-argument context.
494        if let Res::Def(DefKind::ConstParam, _) = res
495            && let Some(context) = self.anon_const_forbids_generic_params()
496        {
497            let folder = ForbidParamUsesFolder {
498                tcx,
499                anon_const_def_id: parent_def_id,
500                span,
501                is_self_alias: false,
502                context,
503            };
504            return Err(folder.error());
505        }
506        Ok(())
507    }
508
509    /// Returns the `ForbidParamContext` for the current anon const if it is a context that
510    /// forbids uses of generic parameters. `None` if the current item is not such a context.
511    ///
512    /// Name resolution handles most invalid generic parameter uses in these contexts, but it
513    /// cannot reject `Self` that aliases a generic type, nor generic parameters introduced by
514    /// type-dependent name resolution (e.g. `<Self as Trait>::Assoc` resolving to a type that
515    /// contains params). Those cases are handled by `check_param_uses_if_mcg`.
516    fn anon_const_forbids_generic_params(&self) -> Option<ForbidParamContext> {
517        let tcx = self.tcx();
518        let item_def_id = self.item_def_id();
519
520        // Inline consts and closures can be nested inside anon consts that forbid generic
521        // params (e.g. an enum discriminant). Walk up the def parent chain to find the
522        // nearest enclosing AnonConst and use that to determine the context.
523        let anon_const_def_id = tcx.typeck_root_def_id_local(item_def_id);
524
525        if tcx.def_kind(anon_const_def_id) != DefKind::AnonConst {
526            return None;
527        }
528
529        match tcx.anon_const_kind(anon_const_def_id) {
530            ty::AnonConstKind::MCG => Some(ForbidParamContext::ConstArgument),
531            ty::AnonConstKind::NonTypeSystemAnon => {
532                // NonTypeSystem anon consts only have accessible generic parameters in specific
533                // positions (ty patterns and field defaults — see `generics_of`). In all other
534                // positions (e.g. enum discriminants) generic parameters are not in scope.
535                if tcx.generics_of(anon_const_def_id).count() == 0 {
536                    Some(ForbidParamContext::EnumDiscriminant)
537                } else {
538                    None
539                }
540            }
541            ty::AnonConstKind::NonTypeSystemInline
542            | ty::AnonConstKind::GCE
543            | ty::AnonConstKind::RepeatExprCount => None,
544        }
545    }
546
547    /// Check for uses of generic parameters that are not in scope due to this being
548    /// in a non-generic anon const context (e.g. MCG or an enum discriminant).
549    ///
550    /// Name resolution rejects most invalid uses, but cannot handle `Self` aliasing a
551    /// generic type or generic parameters introduced by type-dependent name resolution.
552    #[must_use = "need to use transformed output"]
553    fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
554    where
555        T: ty::TypeFoldable<TyCtxt<'tcx>>,
556    {
557        let tcx = self.tcx();
558        if let Some(context) = self.anon_const_forbids_generic_params()
559            // Fast path if contains no params/escaping bound vars.
560            && (term.has_param() || term.has_escaping_bound_vars())
561        {
562            let anon_const_def_id = self.item_def_id();
563            let mut folder =
564                ForbidParamUsesFolder { tcx, anon_const_def_id, span, is_self_alias, context };
565            term.fold_with(&mut folder)
566        } else {
567            term
568        }
569    }
570
571    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
572    x;#[instrument(level = "debug", skip(self), ret)]
573    pub fn lower_lifetime(
574        &self,
575        lifetime: &hir::Lifetime,
576        reason: RegionInferReason<'_>,
577    ) -> ty::Region<'tcx> {
578        if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
579            let region = self.lower_resolved_lifetime(resolved);
580            self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
581        } else {
582            self.re_infer(lifetime.ident.span, reason)
583        }
584    }
585
586    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
587    x;#[instrument(level = "debug", skip(self), ret)]
588    fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
589        let tcx = self.tcx();
590
591        match resolved {
592            rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
593
594            rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
595                let br = ty::BoundRegion {
596                    var: ty::BoundVar::from_u32(index),
597                    kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
598                };
599                ty::Region::new_bound(tcx, debruijn, br)
600            }
601
602            rbv::ResolvedArg::EarlyBound(def_id) => {
603                let name = tcx.hir_ty_param_name(def_id);
604                let item_def_id = tcx.hir_ty_param_owner(def_id);
605                let generics = tcx.generics_of(item_def_id);
606                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
607                ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
608            }
609
610            rbv::ResolvedArg::Free(scope, id) => {
611                ty::Region::new_late_param(
612                    tcx,
613                    scope.to_def_id(),
614                    ty::LateParamRegionKind::Named(id.to_def_id()),
615                )
616
617                // (*) -- not late-bound, won't change
618            }
619
620            rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
621        }
622    }
623
624    pub fn lower_generic_args_of_path_segment(
625        &self,
626        span: Span,
627        def_id: DefId,
628        item_segment: &hir::PathSegment<'_>,
629    ) -> GenericArgsRef<'tcx> {
630        let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
631        if let Some(c) = item_segment.args().constraints.first() {
632            prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
633        }
634        args
635    }
636
637    /// Lower the generic arguments provided to some path.
638    ///
639    /// If this is a trait reference, you also need to pass the self type `self_ty`.
640    /// The lowering process may involve applying defaulted type parameters.
641    ///
642    /// Associated item constraints are not handled here! They are either lowered via
643    /// `lower_assoc_item_constraint` or rejected via `prohibit_assoc_item_constraint`.
644    ///
645    /// ### Example
646    ///
647    /// ```ignore (illustrative)
648    ///    T: std::ops::Index<usize, Output = u32>
649    /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
650    /// ```
651    ///
652    /// 1. The `self_ty` here would refer to the type `T`.
653    /// 2. The path in question is the path to the trait `std::ops::Index`,
654    ///    which will have been resolved to a `def_id`
655    /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
656    ///    parameters are returned in the `GenericArgsRef`
657    /// 4. Associated item constraints like `Output = u32` are contained in `generic_args.constraints`.
658    ///
659    /// Note that the type listing given here is *exactly* what the user provided.
660    ///
661    /// For (generic) associated types
662    ///
663    /// ```ignore (illustrative)
664    /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
665    /// ```
666    ///
667    /// We have the parent args are the args for the parent trait:
668    /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
669    /// type itself: `['a]`. The returned `GenericArgsRef` concatenates these two
670    /// lists: `[Vec<u8>, u8, 'a]`.
671    x;#[instrument(level = "debug", skip(self, span), ret)]
672    pub(crate) fn lower_generic_args_of_path(
673        &self,
674        span: Span,
675        def_id: DefId,
676        parent_args: &[ty::GenericArg<'tcx>],
677        segment: &hir::PathSegment<'_>,
678        self_ty: Option<Ty<'tcx>>,
679    ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
680        // If the type is parameterized by this region, then replace this
681        // region with the current anon region binding (in other words,
682        // whatever & would get replaced with).
683
684        let tcx = self.tcx();
685        let generics = tcx.generics_of(def_id);
686        debug!(?generics);
687
688        if generics.has_self {
689            if generics.parent.is_some() {
690                // The parent is a trait so it should have at least one
691                // generic parameter for the `Self` type.
692                assert!(!parent_args.is_empty())
693            } else {
694                // This item (presumably a trait) needs a self-type.
695                assert!(self_ty.is_some());
696            }
697        } else {
698            assert!(self_ty.is_none());
699        }
700
701        let arg_count = check_generic_arg_count(
702            self,
703            def_id,
704            segment,
705            generics,
706            GenericArgPosition::Type,
707            self_ty.is_some(),
708        );
709
710        // Skip processing if type has no generic parameters.
711        // Traits always have `Self` as a generic parameter, which means they will not return early
712        // here and so associated item constraints will be handled regardless of whether there are
713        // any non-`Self` generic parameters.
714        if generics.is_own_empty() {
715            return (tcx.mk_args(parent_args), arg_count);
716        }
717
718        struct GenericArgsCtxt<'a, 'tcx> {
719            lowerer: &'a dyn HirTyLowerer<'tcx>,
720            def_id: DefId,
721            generic_args: &'a GenericArgs<'a>,
722            span: Span,
723            infer_args: bool,
724            create_synth_args: bool,
725            incorrect_args: &'a Result<(), GenericArgCountMismatch>,
726        }
727
728        impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
729            fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
730                if did == self.def_id {
731                    (Some(self.generic_args), self.infer_args)
732                } else {
733                    // The last component of this tuple is unimportant.
734                    (None, false)
735                }
736            }
737
738            fn provided_kind(
739                &mut self,
740                preceding_args: &[ty::GenericArg<'tcx>],
741                param: &ty::GenericParamDef,
742                arg: &GenericArg<'_>,
743            ) -> ty::GenericArg<'tcx> {
744                let tcx = self.lowerer.tcx();
745
746                if let Err(incorrect) = self.incorrect_args {
747                    if incorrect.invalid_args.contains(&(param.index as usize)) {
748                        return param.to_error(tcx);
749                    }
750                }
751
752                let handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
753                    if has_default {
754                        tcx.check_optional_stability(
755                            param.def_id,
756                            Some(arg.hir_id()),
757                            arg.span(),
758                            None,
759                            AllowUnstable::No,
760                            |_, _| {
761                                // Default generic parameters may not be marked
762                                // with stability attributes, i.e. when the
763                                // default parameter was defined at the same time
764                                // as the rest of the type. As such, we ignore missing
765                                // stability attributes.
766                            },
767                        );
768                    }
769                    self.lowerer.lower_ty(ty).into()
770                };
771
772                match (&param.kind, arg) {
773                    (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
774                        self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
775                    }
776                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
777                        // We handle the other parts of `Ty` in the match arm below
778                        handle_ty_args(has_default, ty.as_unambig_ty())
779                    }
780                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
781                        handle_ty_args(has_default, &inf.to_ty())
782                    }
783                    (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
784                        .lowerer
785                        // Ambig portions of `ConstArg` are handled in the match arm below
786                        .lower_const_arg(
787                            ct.as_unambig_ct(),
788                            tcx.type_of(param.def_id)
789                                .instantiate(tcx, preceding_args)
790                                .skip_norm_wip(),
791                        )
792                        .into(),
793                    (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
794                        self.lowerer.ct_infer(Some(param), inf.span).into()
795                    }
796                    (kind, arg) => span_bug!(
797                        self.span,
798                        "mismatched path argument for kind {kind:?}: found arg {arg:?}"
799                    ),
800                }
801            }
802
803            fn inferred_kind(
804                &mut self,
805                preceding_args: &[ty::GenericArg<'tcx>],
806                param: &ty::GenericParamDef,
807                infer_args: bool,
808            ) -> ty::GenericArg<'tcx> {
809                let tcx = self.lowerer.tcx();
810
811                if let Err(incorrect) = self.incorrect_args {
812                    if incorrect.invalid_args.contains(&(param.index as usize)) {
813                        return param.to_error(tcx);
814                    }
815                }
816                match param.kind {
817                    GenericParamDefKind::Lifetime => {
818                        self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
819                    }
820                    GenericParamDefKind::Type { has_default, synthetic } => {
821                        if !infer_args && has_default {
822                            // No type parameter provided, but a default exists.
823                            if let Some(prev) =
824                                preceding_args.iter().find_map(|arg| match arg.kind() {
825                                    GenericArgKind::Type(ty) => ty.error_reported().err(),
826                                    _ => None,
827                                })
828                            {
829                                // Avoid ICE #86756 when type error recovery goes awry.
830                                return Ty::new_error(tcx, prev).into();
831                            }
832                            tcx.at(self.span)
833                                .type_of(param.def_id)
834                                .instantiate(tcx, preceding_args)
835                                .skip_norm_wip()
836                                .into()
837                        } else if self.create_synth_args && synthetic {
838                            Ty::new_param(tcx, param.index, param.name).into()
839                        } else if infer_args {
840                            self.lowerer.ty_infer(Some(param), self.span).into()
841                        } else {
842                            // We've already errored above about the mismatch.
843                            Ty::new_misc_error(tcx).into()
844                        }
845                    }
846                    GenericParamDefKind::Const { has_default, .. } => {
847                        let ty = tcx
848                            .at(self.span)
849                            .type_of(param.def_id)
850                            .instantiate(tcx, preceding_args)
851                            .skip_norm_wip();
852                        if let Err(guar) = ty.error_reported() {
853                            return ty::Const::new_error(tcx, guar).into();
854                        }
855                        if !infer_args && has_default {
856                            tcx.const_param_default(param.def_id)
857                                .instantiate(tcx, preceding_args)
858                                .skip_norm_wip()
859                                .into()
860                        } else if infer_args {
861                            self.lowerer.ct_infer(Some(param), self.span).into()
862                        } else {
863                            // We've already errored above about the mismatch.
864                            ty::Const::new_misc_error(tcx).into()
865                        }
866                    }
867                }
868            }
869        }
870
871        let mut args_ctx = GenericArgsCtxt {
872            lowerer: self,
873            def_id,
874            span,
875            generic_args: segment.args(),
876            infer_args: segment.infer_args,
877            create_synth_args: segment.delegation_child_segment,
878            incorrect_args: &arg_count.correct,
879        };
880
881        let args = lower_generic_args(
882            self,
883            def_id,
884            parent_args,
885            self_ty.is_some(),
886            self_ty,
887            &arg_count,
888            &mut args_ctx,
889        );
890
891        (args, arg_count)
892    }
893
894    #[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_generic_args_of_assoc_item",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(894u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item_segment")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item_segment");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_args");
                                                        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(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_segment)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_args)
                                                            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: GenericArgsRef<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (args, _) =
                self.lower_generic_args_of_path(span, item_def_id,
                    parent_args, item_segment, None);
            if let Some(c) = item_segment.args().constraints.first() {
                prohibit_assoc_item_constraint(self, c,
                    Some((item_def_id, item_segment, span)));
            }
            args
        }
    }
}#[instrument(level = "debug", skip(self))]
895    pub fn lower_generic_args_of_assoc_item(
896        &self,
897        span: Span,
898        item_def_id: DefId,
899        item_segment: &hir::PathSegment<'_>,
900        parent_args: GenericArgsRef<'tcx>,
901    ) -> GenericArgsRef<'tcx> {
902        let (args, _) =
903            self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
904        if let Some(c) = item_segment.args().constraints.first() {
905            prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
906        }
907        args
908    }
909
910    /// Lower a trait reference as found in an impl header as the implementee.
911    ///
912    /// The self type `self_ty` is the implementer of the trait.
913    pub fn lower_impl_trait_ref(
914        &self,
915        trait_ref: &hir::TraitRef<'tcx>,
916        self_ty: Ty<'tcx>,
917    ) -> ty::TraitRef<'tcx> {
918        let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
919
920        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
921
922        self.lower_mono_trait_ref(
923            trait_ref.path.span,
924            trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
925            self_ty,
926            segment,
927            true,
928        )
929    }
930
931    /// Lower a polymorphic trait reference given a self type into `bounds`.
932    ///
933    /// *Polymorphic* in the sense that it may bind late-bound vars.
934    ///
935    /// This may generate auxiliary bounds iff the trait reference contains associated item constraints.
936    ///
937    /// ### Example
938    ///
939    /// Given the trait ref `Iterator<Item = u32>` and the self type `Ty`, this will add the
940    ///
941    /// 1. *trait predicate* `<Ty as Iterator>` (known as `Ty: Iterator` in the surface syntax) and the
942    /// 2. *projection predicate* `<Ty as Iterator>::Item = u32`
943    ///
944    /// to `bounds`.
945    ///
946    /// ### A Note on Binders
947    ///
948    /// Against our usual convention, there is an implied binder around the `self_ty` and the
949    /// `trait_ref` here. So they may reference late-bound vars.
950    ///
951    /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
952    /// where `'a` is a bound region at depth 0. Similarly, the `trait_ref` would be `Bar<'a>`.
953    /// The lowered poly-trait-ref will track this binder explicitly, however.
954    #[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_poly_trait_ref",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(954u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("bound_generic_params")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("bound_generic_params");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constness")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constness");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("polarity")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("polarity");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ref");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("predicate_filter")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("predicate_filter");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("overlapping_assoc_item_constraints")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("overlapping_assoc_item_constraints");
                                                        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(&bound_generic_params)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constness)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&polarity)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlapping_assoc_item_constraints)
                                                            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: GenericArgCountResult = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let _ = bound_generic_params;
            let trait_def_id =
                trait_ref.trait_def_id().unwrap_or_else(||
                        FatalError.raise());
            let transient =
                match polarity {
                    hir::BoundPolarity::Positive => {
                        tcx.is_lang_item(trait_def_id, LangItem::PointeeSized)
                    }
                    hir::BoundPolarity::Negative(_) => false,
                    hir::BoundPolarity::Maybe(_) => {
                        self.require_bound_to_relax_default_trait(trait_ref, span);
                        true
                    }
                };
            let bounds = if transient { &mut Vec::new() } else { bounds };
            let polarity =
                match polarity {
                    hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_)
                        => {
                        ty::ClausePolarity::Positive
                    }
                    hir::BoundPolarity::Negative(_) =>
                        ty::ClausePolarity::Negative,
                };
            let [leading_segments @ .., segment] =
                trait_ref.path.segments else {
                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                };
            let _ =
                self.prohibit_generic_args(leading_segments.iter(),
                    GenericsArgsErrExtend::None);
            self.report_internal_fn_trait(span, trait_def_id, segment, false);
            let (generic_args, arg_count) =
                self.lower_generic_args_of_path(trait_ref.path.span,
                    trait_def_id, &[], segment, Some(self_ty));
            let constraints = segment.args().constraints;
            if transient &&
                    (!generic_args[1..].is_empty() || !constraints.is_empty()) {
                self.dcx().span_delayed_bug(span,
                    "transient bound should not have args or constraints");
            }
            let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1034",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1034u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("bound_vars")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("bound_vars");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_vars)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let poly_trait_ref =
                ty::Binder::bind_with_vars(ty::TraitRef::new_from_args(tcx,
                        trait_def_id, generic_args), bound_vars);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1041",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1041u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("poly_trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("poly_trait_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&poly_trait_ref)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            match predicate_filter {
                PredicateFilter::All | PredicateFilter::SelfOnly |
                    PredicateFilter::SelfTraitThatDefines(..) |
                    PredicateFilter::SelfAndAssociatedTypeBounds => {
                    let bound =
                        poly_trait_ref.map_bound(|trait_ref|
                                {
                                    ty::ClauseKind::Trait(ty::TraitClause {
                                            trait_ref,
                                            polarity,
                                        })
                                });
                    let bound = (bound.upcast(tcx), span);
                    if tcx.is_lang_item(trait_def_id, LangItem::Sized) {
                        bounds.insert(0, bound);
                    } else { bounds.push(bound); }
                }
                PredicateFilter::ConstIfConst |
                    PredicateFilter::SelfConstIfConst => {}
            }
            if let hir::BoundConstness::Always(span) |
                        hir::BoundConstness::Maybe(span) = constness &&
                    !tcx.is_const_trait(trait_def_id) {
                let (def_span, suggestion, suggestion_pre) =
                    match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
                        {
                        (Some(trait_def_id), true) => {
                            let span = tcx.hir_expect_item(trait_def_id).vis_span;
                            let span =
                                tcx.sess.source_map().span_extend_while_whitespace(span);
                            (None, Some(span.shrink_to_hi()),
                                if self.tcx().features().const_trait_impl() {
                                    ""
                                } else {
                                    "enable `#![feature(const_trait_impl)]` in your crate and "
                                })
                        }
                        (None, _) | (_, false) =>
                            (Some(tcx.def_span(trait_def_id)), None, ""),
                    };
                self.dcx().emit_err(crate::diagnostics::ConstBoundForNonConstTrait {
                        span,
                        modifier: constness.as_str(),
                        def_span,
                        trait_name: tcx.def_path_str(trait_def_id),
                        suggestion,
                        suggestion_pre,
                    });
            } else {
                match predicate_filter {
                    PredicateFilter::SelfTraitThatDefines(..) => {}
                    PredicateFilter::All | PredicateFilter::SelfOnly |
                        PredicateFilter::SelfAndAssociatedTypeBounds => {
                        match constness {
                            hir::BoundConstness::Always(_) => {
                                if polarity == ty::ClausePolarity::Positive {
                                    bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
                                                ty::BoundConstness::Const), span));
                                }
                            }
                            hir::BoundConstness::Maybe(_) => {}
                            hir::BoundConstness::Never => {}
                        }
                    }
                    PredicateFilter::ConstIfConst |
                        PredicateFilter::SelfConstIfConst => {
                        match constness {
                            hir::BoundConstness::Maybe(_) => {
                                if polarity == ty::ClausePolarity::Positive {
                                    bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
                                                ty::BoundConstness::Maybe), span));
                                }
                            }
                            hir::BoundConstness::Always(_) | hir::BoundConstness::Never
                                => {}
                        }
                    }
                }
            }
            let mut dup_constraints =
                (overlapping_assoc_item_constraints ==
                            OverlappingAsssocItemConstraints::Forbidden).then_some(FxIndexMap::default());
            for constraint in constraints {
                if polarity == ty::ClausePolarity::Negative {
                    self.dcx().span_delayed_bug(constraint.span,
                        "negative trait bounds should not have assoc item constraints");
                    break;
                }
                let _: Result<_, ErrorGuaranteed> =
                    self.lower_assoc_item_constraint(trait_ref.hir_ref_id,
                        poly_trait_ref, constraint, bounds,
                        dup_constraints.as_mut(), constraint.span,
                        predicate_filter);
            }
            arg_count
        }
    }
}#[instrument(level = "debug", skip(self, bounds))]
955    pub(crate) fn lower_poly_trait_ref(
956        &self,
957        &hir::PolyTraitRef {
958            bound_generic_params,
959            modifiers: hir::TraitBoundModifiers { constness, polarity },
960            trait_ref,
961            span,
962        }: &hir::PolyTraitRef<'_>,
963        self_ty: Ty<'tcx>,
964        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
965        predicate_filter: PredicateFilter,
966        overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
967    ) -> GenericArgCountResult {
968        let tcx = self.tcx();
969
970        // We use the *resolved* bound vars later instead of the HIR ones since the former
971        // also include the bound vars of the overarching predicate if applicable.
972        let _ = bound_generic_params;
973
974        let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
975
976        // Relaxed bounds `?Trait` and `PointeeSized` bounds aren't represented in the middle::ty IR
977        // as they denote the *absence* of a default bound. However, we can't bail out early here since
978        // we still need to perform several validation steps (see below). Instead, simply "pour" all
979        // resulting bounds "down the drain", i.e., into a new `Vec` that just gets dropped at the end.
980        let transient = match polarity {
981            hir::BoundPolarity::Positive => {
982                // To elaborate on the comment directly above, regarding `PointeeSized` specifically,
983                // we don't "reify" such bounds to avoid trait system limitations -- namely,
984                // non-global where-clauses being preferred over item bounds (where `PointeeSized`
985                // bounds would be proven) -- which can result in errors when a `PointeeSized`
986                // supertrait / bound / predicate is added to some items.
987                tcx.is_lang_item(trait_def_id, LangItem::PointeeSized)
988            }
989            hir::BoundPolarity::Negative(_) => false,
990            hir::BoundPolarity::Maybe(_) => {
991                self.require_bound_to_relax_default_trait(trait_ref, span);
992                true
993            }
994        };
995        let bounds = if transient { &mut Vec::new() } else { bounds };
996
997        let polarity = match polarity {
998            hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
999                ty::ClausePolarity::Positive
1000            }
1001            hir::BoundPolarity::Negative(_) => ty::ClausePolarity::Negative,
1002        };
1003
1004        let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
1005
1006        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
1007        self.report_internal_fn_trait(span, trait_def_id, segment, false);
1008
1009        let (generic_args, arg_count) = self.lower_generic_args_of_path(
1010            trait_ref.path.span,
1011            trait_def_id,
1012            &[],
1013            segment,
1014            Some(self_ty),
1015        );
1016
1017        let constraints = segment.args().constraints;
1018
1019        if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
1020            // Since the bound won't be present in the middle::ty IR as established above, any
1021            // arguments or constraints won't be checked for well-formedness in later passes.
1022            //
1023            // This is only an issue if the trait ref is otherwise valid which can only happen if
1024            // the corresponding default trait has generic parameters or associated items. Such a
1025            // trait would be degenerate. We delay a bug to detect and guard us against these.
1026            //
1027            // E.g: Given `/*default*/ trait Bound<'a: 'static, T, const N: usize> {}`,
1028            // `?Bound<Vec<str>, { panic!() }>` won't be wfchecked.
1029            self.dcx()
1030                .span_delayed_bug(span, "transient bound should not have args or constraints");
1031        }
1032
1033        let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
1034        debug!(?bound_vars);
1035
1036        let poly_trait_ref = ty::Binder::bind_with_vars(
1037            ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
1038            bound_vars,
1039        );
1040
1041        debug!(?poly_trait_ref);
1042
1043        // We deal with const conditions later.
1044        match predicate_filter {
1045            PredicateFilter::All
1046            | PredicateFilter::SelfOnly
1047            | PredicateFilter::SelfTraitThatDefines(..)
1048            | PredicateFilter::SelfAndAssociatedTypeBounds => {
1049                let bound = poly_trait_ref.map_bound(|trait_ref| {
1050                    ty::ClauseKind::Trait(ty::TraitClause { trait_ref, polarity })
1051                });
1052                let bound = (bound.upcast(tcx), span);
1053                // FIXME(-Znext-solver): We can likely remove this hack once the
1054                // new trait solver lands. This fixed an overflow in the old solver.
1055                // This may have performance implications, so please check perf when
1056                // removing it.
1057                // This was added in <https://github.com/rust-lang/rust/pull/123302>.
1058                if tcx.is_lang_item(trait_def_id, LangItem::Sized) {
1059                    bounds.insert(0, bound);
1060                } else {
1061                    bounds.push(bound);
1062                }
1063            }
1064            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
1065        }
1066
1067        if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
1068            && !tcx.is_const_trait(trait_def_id)
1069        {
1070            let (def_span, suggestion, suggestion_pre) =
1071                match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
1072                    (Some(trait_def_id), true) => {
1073                        let span = tcx.hir_expect_item(trait_def_id).vis_span;
1074                        let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1075
1076                        (
1077                            None,
1078                            Some(span.shrink_to_hi()),
1079                            if self.tcx().features().const_trait_impl() {
1080                                ""
1081                            } else {
1082                                "enable `#![feature(const_trait_impl)]` in your crate and "
1083                            },
1084                        )
1085                    }
1086                    (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1087                };
1088            self.dcx().emit_err(crate::diagnostics::ConstBoundForNonConstTrait {
1089                span,
1090                modifier: constness.as_str(),
1091                def_span,
1092                trait_name: tcx.def_path_str(trait_def_id),
1093                suggestion,
1094                suggestion_pre,
1095            });
1096        } else {
1097            match predicate_filter {
1098                // This is only concerned with trait predicates.
1099                PredicateFilter::SelfTraitThatDefines(..) => {}
1100                PredicateFilter::All
1101                | PredicateFilter::SelfOnly
1102                | PredicateFilter::SelfAndAssociatedTypeBounds => {
1103                    match constness {
1104                        hir::BoundConstness::Always(_) => {
1105                            if polarity == ty::ClausePolarity::Positive {
1106                                bounds.push((
1107                                    poly_trait_ref
1108                                        .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1109                                    span,
1110                                ));
1111                            }
1112                        }
1113                        hir::BoundConstness::Maybe(_) => {
1114                            // We don't emit a const bound here, since that would mean that we
1115                            // unconditionally need to prove a `HostEffect` predicate, even when
1116                            // the predicates are being instantiated in a non-const context. This
1117                            // is instead handled in the `const_conditions` query.
1118                        }
1119                        hir::BoundConstness::Never => {}
1120                    }
1121                }
1122                // On the flip side, when filtering `ConstIfConst` bounds, we only need to convert
1123                // `[const]` bounds. All other predicates are handled in their respective queries.
1124                //
1125                // Note that like `PredicateFilter::SelfOnly`, we don't need to do any filtering
1126                // here because we only call this on self bounds, and deal with the recursive case
1127                // in `lower_assoc_item_constraint`.
1128                PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1129                    match constness {
1130                        hir::BoundConstness::Maybe(_) => {
1131                            if polarity == ty::ClausePolarity::Positive {
1132                                bounds.push((
1133                                    poly_trait_ref
1134                                        .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1135                                    span,
1136                                ));
1137                            }
1138                        }
1139                        hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1140                    }
1141                }
1142            }
1143        }
1144
1145        let mut dup_constraints = (overlapping_assoc_item_constraints
1146            == OverlappingAsssocItemConstraints::Forbidden)
1147            .then_some(FxIndexMap::default());
1148
1149        for constraint in constraints {
1150            // Don't register any associated item constraints for negative bounds,
1151            // since we should have emitted an error for them earlier, and they
1152            // would not be well-formed!
1153            if polarity == ty::ClausePolarity::Negative {
1154                self.dcx().span_delayed_bug(
1155                    constraint.span,
1156                    "negative trait bounds should not have assoc item constraints",
1157                );
1158                break;
1159            }
1160
1161            // Specify type to assert that error was already reported in `Err` case.
1162            let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1163                trait_ref.hir_ref_id,
1164                poly_trait_ref,
1165                constraint,
1166                bounds,
1167                dup_constraints.as_mut(),
1168                constraint.span,
1169                predicate_filter,
1170            );
1171            // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
1172        }
1173
1174        arg_count
1175    }
1176
1177    /// Lower a monomorphic trait reference given a self type while prohibiting associated item bindings.
1178    ///
1179    /// *Monomorphic* in the sense that it doesn't bind any late-bound vars.
1180    fn lower_mono_trait_ref(
1181        &self,
1182        span: Span,
1183        trait_def_id: DefId,
1184        self_ty: Ty<'tcx>,
1185        trait_segment: &hir::PathSegment<'_>,
1186        is_impl: bool,
1187    ) -> ty::TraitRef<'tcx> {
1188        self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1189
1190        let (generic_args, _) =
1191            self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1192        if let Some(c) = trait_segment.args().constraints.first() {
1193            prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1194        }
1195        ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1196    }
1197
1198    fn probe_trait_that_defines_assoc_item(
1199        &self,
1200        trait_def_id: DefId,
1201        assoc_tag: ty::AssocTag,
1202        assoc_ident: Ident,
1203    ) -> bool {
1204        self.tcx()
1205            .associated_items(trait_def_id)
1206            .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1207            .is_some()
1208    }
1209
1210    fn lower_path_segment(
1211        &self,
1212        span: Span,
1213        def_id: DefId,
1214        item_segment: &hir::PathSegment<'_>,
1215    ) -> Ty<'tcx> {
1216        let tcx = self.tcx();
1217        let args = self.lower_generic_args_of_path_segment(span, def_id, item_segment);
1218
1219        if let DefKind::TyAlias = tcx.def_kind(def_id)
1220            && tcx.type_alias_is_checked(def_id)
1221        {
1222            // Type aliases defined in crates that have the
1223            // feature `checked_type_alias` enabled get encoded as a type alias that normalization will
1224            // then actually instantiate the where bounds of.
1225            let alias_ty = ty::AliasTy::new_from_args(tcx, ty::Free { def_id }, args);
1226            Ty::new_alias(tcx, ty::IsRigid::No, alias_ty)
1227        } else {
1228            tcx.at(span).type_of(def_id).instantiate(tcx, args).skip_norm_wip()
1229        }
1230    }
1231
1232    /// Search for a trait bound on a type parameter whose trait defines the associated item
1233    /// given by `assoc_ident` and `kind`.
1234    ///
1235    /// This fails if there is no such bound in the list of candidates or if there are multiple
1236    /// candidates in which case it reports ambiguity.
1237    ///
1238    /// `ty_param_def_id` is the `LocalDefId` of the type parameter.
1239    x;#[instrument(level = "debug", skip_all, ret)]
1240    fn probe_single_ty_param_bound_for_assoc_item(
1241        &self,
1242        ty_param_def_id: LocalDefId,
1243        ty_param_span: Span,
1244        assoc_tag: ty::AssocTag,
1245        assoc_ident: Ident,
1246        span: Span,
1247    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1248        debug!(?ty_param_def_id, ?assoc_ident, ?span);
1249        let tcx = self.tcx();
1250
1251        let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1252        debug!("predicates={:#?}", predicates);
1253
1254        self.probe_single_bound_for_assoc_item(
1255            || {
1256                let trait_refs = predicates
1257                    .iter_identity_copied()
1258                    .map(Unnormalized::skip_norm_wip)
1259                    .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1260                traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1261            },
1262            AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1263            assoc_tag,
1264            assoc_ident,
1265            span,
1266            None,
1267        )
1268    }
1269
1270    /// When there are multiple traits which contain an identically named
1271    /// associated item, this function eliminates any traits which are a
1272    /// supertrait of another candidate trait.
1273    ///
1274    /// This is the type-level analogue of
1275    /// `rustc_hir_typeck::method::probe::ProbeContext::collapse_candidates_to_subtrait_pick`;
1276    /// keep both implementations in sync.
1277    ///
1278    /// This implements RFC #3624.
1279    fn collapse_candidates_to_subtrait_pick(
1280        &self,
1281        matching_candidates: &[ty::PolyTraitRef<'tcx>],
1282    ) -> Option<ty::PolyTraitRef<'tcx>> {
1283        if !self.tcx().features().supertrait_item_shadowing() {
1284            return None;
1285        }
1286
1287        let mut child_trait = matching_candidates[0];
1288        let mut supertraits: SsoHashSet<_> =
1289            traits::supertrait_def_ids(self.tcx(), child_trait.def_id()).collect();
1290
1291        let mut remaining_candidates: Vec<_> = matching_candidates[1..].iter().copied().collect();
1292        while !remaining_candidates.is_empty() {
1293            let mut made_progress = false;
1294            let mut next_round = ::alloc::vec::Vec::new()vec![];
1295
1296            for remaining_trait in remaining_candidates {
1297                if supertraits.contains(&remaining_trait.def_id()) {
1298                    made_progress = true;
1299                    continue;
1300                }
1301
1302                // This candidate is not a supertrait of the `child_trait`.
1303                // Check if it's a subtrait of the `child_trait`, instead.
1304                // If it is, then it must have been a subtrait of every
1305                // other pick we've eliminated at this point. It will
1306                // take over at this point.
1307                let remaining_trait_supertraits: SsoHashSet<_> =
1308                    traits::supertrait_def_ids(self.tcx(), remaining_trait.def_id()).collect();
1309                if remaining_trait_supertraits.contains(&child_trait.def_id()) {
1310                    child_trait = remaining_trait;
1311                    supertraits = remaining_trait_supertraits;
1312                    made_progress = true;
1313                    continue;
1314                }
1315
1316                // Neither `child_trait` or the current candidate are
1317                // supertraits of each other.
1318                // Don't bail here, since we may be comparing two supertraits
1319                // of a common subtrait. These two supertraits won't be related
1320                // at all, but we will pick them up next round when we find their
1321                // child as we continue iterating in this round.
1322                next_round.push(remaining_trait);
1323            }
1324
1325            if made_progress {
1326                // If we've made progress, iterate again.
1327                remaining_candidates = next_round;
1328            } else {
1329                // Otherwise, we must have at least two candidates which
1330                // are not related to each other at all.
1331                return None;
1332            }
1333        }
1334
1335        Some(child_trait)
1336    }
1337
1338    /// Search for a single trait bound whose trait defines the associated item given by
1339    /// `assoc_ident`.
1340    ///
1341    /// This fails if there is no such bound in the list of candidates or if there are multiple
1342    /// candidates in which case it reports ambiguity.
1343    x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1344    fn probe_single_bound_for_assoc_item<I>(
1345        &self,
1346        all_candidates: impl Fn() -> I,
1347        qself: AssocItemQSelf,
1348        assoc_tag: ty::AssocTag,
1349        assoc_ident: Ident,
1350        span: Span,
1351        constraint: Option<&hir::AssocItemConstraint<'_>>,
1352    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1353    where
1354        I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1355    {
1356        let mut matching_candidates = all_candidates().filter(|r| {
1357            self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1358        });
1359
1360        let Some(bound1) = matching_candidates.next() else {
1361            return Err(self.report_unresolved_assoc_item(
1362                all_candidates,
1363                qself,
1364                assoc_tag,
1365                assoc_ident,
1366                span,
1367                constraint,
1368            ));
1369        };
1370
1371        if let Some(bound2) = matching_candidates.next() {
1372            let all_matching_candidates: Vec<_> =
1373                [bound1, bound2].into_iter().chain(matching_candidates).collect();
1374            if let Some(bound) = self.collapse_candidates_to_subtrait_pick(&all_matching_candidates)
1375            {
1376                return Ok(bound);
1377            }
1378
1379            return Err(self.report_ambiguous_assoc_item(
1380                &all_matching_candidates,
1381                qself,
1382                assoc_tag,
1383                assoc_ident,
1384                span,
1385                constraint,
1386            ));
1387        }
1388
1389        Ok(bound1)
1390    }
1391
1392    /// Lower a [type-relative](hir::QPath::TypeRelative) path in type position to a type.
1393    ///
1394    /// If the path refers to an enum variant and `permit_variants` holds,
1395    /// the returned type is simply the provided self type `qself_ty`.
1396    ///
1397    /// A path like `A::B::C::D` is understood as `<A::B::C>::D`. I.e.,
1398    /// `qself_ty` / `qself` is `A::B::C` and `assoc_segment` is `D`.
1399    /// We return the lowered type and the `DefId` for the whole path.
1400    ///
1401    /// We only support associated type paths whose self type is a type parameter or a `Self`
1402    /// type alias (in a trait impl) like `T::Ty` (where `T` is a ty param) or `Self::Ty`.
1403    /// We **don't** support paths whose self type is an arbitrary type like `Struct::Ty` where
1404    /// struct `Struct` impls an in-scope trait that defines an associated type called `Ty`.
1405    /// For the latter case, we report ambiguity.
1406    /// While desirable to support, the implementation would be non-trivial. Tracked in [#22519].
1407    ///
1408    /// At the time of writing, *inherent associated types* are also resolved here. This however
1409    /// is [problematic][iat]. A proper implementation would be as non-trivial as the one
1410    /// described in the previous paragraph and their modeling of projections would likely be
1411    /// very similar in nature.
1412    ///
1413    /// [#22519]: https://github.com/rust-lang/rust/issues/22519
1414    /// [iat]: https://github.com/rust-lang/rust/issues/8995#issuecomment-1569208403
1415    //
1416    // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1417    // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1418    x;#[instrument(level = "debug", skip_all, ret)]
1419    pub fn lower_type_relative_ty_path(
1420        &self,
1421        self_ty: Ty<'tcx>,
1422        hir_self_ty: &hir::Ty<'_>,
1423        segment: &hir::PathSegment<'_>,
1424        qpath_hir_id: HirId,
1425        span: Span,
1426        permit_variants: PermitVariants,
1427    ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1428        let tcx = self.tcx();
1429        match self.lower_type_relative_path(
1430            self_ty,
1431            hir_self_ty,
1432            segment,
1433            qpath_hir_id,
1434            span,
1435            LowerTypeRelativePathMode::Type(permit_variants),
1436        )? {
1437            TypeRelativePath::AssocItem(alias_term) => {
1438                let alias_ty = alias_term.expect_ty();
1439                let def_id = match alias_ty.kind {
1440                    ty::AliasTyKind::Projection { def_id } => def_id,
1441                    ty::AliasTyKind::Inherent { def_id } => def_id,
1442                    kind => bug!("expected projection or inherent alias, got {kind:?}"),
1443                };
1444                let ty = alias_ty.to_ty(tcx, ty::IsRigid::No);
1445                let ty = self.check_param_uses_if_mcg(ty, span, false);
1446                Ok((ty, tcx.def_kind(def_id), def_id))
1447            }
1448            TypeRelativePath::Variant { adt, variant_did } => {
1449                let adt = self.check_param_uses_if_mcg(adt, span, false);
1450                Ok((adt, DefKind::Variant, variant_did))
1451            }
1452            TypeRelativePath::Ctor { .. } => {
1453                let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1454                Err(e)
1455            }
1456        }
1457    }
1458
1459    /// Lower a [type-relative][hir::QPath::TypeRelative] path to a (type-level) constant.
1460    x;#[instrument(level = "debug", skip_all, ret)]
1461    fn lower_type_relative_const_path(
1462        &self,
1463        self_ty: Ty<'tcx>,
1464        hir_self_ty: &hir::Ty<'_>,
1465        segment: &hir::PathSegment<'_>,
1466        qpath_hir_id: HirId,
1467        span: Span,
1468    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1469        let tcx = self.tcx();
1470        match self.lower_type_relative_path(
1471            self_ty,
1472            hir_self_ty,
1473            segment,
1474            qpath_hir_id,
1475            span,
1476            LowerTypeRelativePathMode::Const,
1477        )? {
1478            TypeRelativePath::AssocItem(alias_term) => {
1479                let alias_ct = alias_term.expect_ct();
1480                if let Some(def_id) = alias_ct.kind.opt_def_id() {
1481                    self.require_type_const_attribute(def_id, span)?;
1482                }
1483                let ct = Const::new_alias(tcx, ty::IsRigid::No, alias_ct);
1484                let ct = self.check_param_uses_if_mcg(ct, span, false);
1485                Ok(ct)
1486            }
1487            TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1488                DefKind::Ctor(_, CtorKind::Fn) => Ok(ty::Const::zero_sized(
1489                    tcx,
1490                    tcx.type_of(ctor_def_id).instantiate(tcx, args).skip_norm_wip(),
1491                )),
1492                DefKind::Ctor(ctor_of, CtorKind::Const) => {
1493                    Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1494                }
1495                _ => unreachable!(),
1496            },
1497            // FIXME(mgca): implement support for this once ready to support all adt ctor expressions,
1498            // not just const ctors
1499            TypeRelativePath::Variant { .. } => {
1500                span_bug!(span, "unexpected variant res for type associated const path")
1501            }
1502        }
1503    }
1504
1505    /// Lower a [type-relative][hir::QPath::TypeRelative] (and type-level) path.
1506    x;#[instrument(level = "debug", skip_all, ret)]
1507    fn lower_type_relative_path(
1508        &self,
1509        self_ty: Ty<'tcx>,
1510        hir_self_ty: &hir::Ty<'_>,
1511        segment: &hir::PathSegment<'_>,
1512        qpath_hir_id: HirId,
1513        span: Span,
1514        mode: LowerTypeRelativePathMode,
1515    ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1516        debug!(%self_ty, ?segment.ident);
1517        let tcx = self.tcx();
1518
1519        // Check if we have an enum variant or an inherent associated type.
1520        let mut variant_def_id = None;
1521        if let Some(adt_def) = self.probe_adt(span, self_ty) {
1522            if adt_def.is_enum() {
1523                let variant_def = adt_def
1524                    .variants()
1525                    .iter()
1526                    .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1527                if let Some(variant_def) = variant_def {
1528                    // FIXME(mgca): do we want constructor resolutions to take priority over
1529                    // other possible resolutions?
1530                    if matches!(mode, LowerTypeRelativePathMode::Const)
1531                        && let Some((_, ctor_def_id)) = variant_def.ctor
1532                    {
1533                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1534                        let _ = self.prohibit_generic_args(
1535                            slice::from_ref(segment).iter(),
1536                            GenericsArgsErrExtend::EnumVariant {
1537                                qself: hir_self_ty,
1538                                assoc_segment: segment,
1539                                adt_def,
1540                            },
1541                        );
1542                        let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1543                        return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1544                    }
1545                    if let PermitVariants::Yes = mode.permit_variants() {
1546                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1547                        let _ = self.prohibit_generic_args(
1548                            slice::from_ref(segment).iter(),
1549                            GenericsArgsErrExtend::EnumVariant {
1550                                qself: hir_self_ty,
1551                                assoc_segment: segment,
1552                                adt_def,
1553                            },
1554                        );
1555                        return Ok(TypeRelativePath::Variant {
1556                            adt: self_ty,
1557                            variant_did: variant_def.def_id,
1558                        });
1559                    } else {
1560                        variant_def_id = Some(variant_def.def_id);
1561                    }
1562                }
1563            }
1564
1565            // FIXME(inherent_associated_types, #106719): Support self types other than ADTs.
1566            if let Some(alias_term) = self.probe_inherent_assoc_item(
1567                segment,
1568                adt_def.did(),
1569                self_ty,
1570                qpath_hir_id,
1571                span,
1572                mode.assoc_tag(),
1573            )? {
1574                return Ok(TypeRelativePath::AssocItem(alias_term));
1575            }
1576        }
1577
1578        let (item_def_id, bound) = self.resolve_type_relative_path(
1579            self_ty,
1580            hir_self_ty,
1581            mode.assoc_tag(),
1582            segment,
1583            qpath_hir_id,
1584            span,
1585            variant_def_id,
1586        )?;
1587
1588        let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1589
1590        if let Some(variant_def_id) = variant_def_id {
1591            tcx.emit_node_span_lint(
1592                AMBIGUOUS_ASSOCIATED_ITEMS,
1593                qpath_hir_id,
1594                span,
1595                errors::AmbiguityBetweenVariantAndAssocItem {
1596                    variant_def_id,
1597                    item_def_id,
1598                    span,
1599                    segment_ident: segment.ident,
1600                    bound_def_id: bound.def_id(),
1601                    self_ty,
1602                    tcx,
1603                    mode,
1604                },
1605            );
1606        }
1607
1608        Ok(TypeRelativePath::AssocItem(ty::AliasTerm::new_from_def_id(tcx, item_def_id, args)))
1609    }
1610
1611    /// Resolve a [type-relative](hir::QPath::TypeRelative) (and type-level) path.
1612    fn resolve_type_relative_path(
1613        &self,
1614        self_ty: Ty<'tcx>,
1615        hir_self_ty: &hir::Ty<'_>,
1616        assoc_tag: ty::AssocTag,
1617        segment: &hir::PathSegment<'_>,
1618        qpath_hir_id: HirId,
1619        span: Span,
1620        variant_def_id: Option<DefId>,
1621    ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1622        let tcx = self.tcx();
1623
1624        let self_ty_res = match hir_self_ty.kind {
1625            hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1626            _ => Res::Err,
1627        };
1628
1629        // Find the type of the assoc item, and the trait where the associated item is declared.
1630        let bound = match (self_ty.kind(), self_ty_res) {
1631            (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1632                // `Self` in an impl of a trait -- we have a concrete self type and a
1633                // trait reference.
1634                let trait_ref = tcx.impl_trait_ref(impl_def_id);
1635
1636                self.probe_single_bound_for_assoc_item(
1637                    || {
1638                        let trait_ref =
1639                            ty::Binder::dummy(trait_ref.instantiate_identity().skip_norm_wip());
1640                        traits::supertraits(tcx, trait_ref)
1641                    },
1642                    AssocItemQSelf::SelfTyAlias,
1643                    assoc_tag,
1644                    segment.ident,
1645                    span,
1646                    None,
1647                )?
1648            }
1649            (
1650                &ty::Param(_),
1651                Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1652            ) => self.probe_single_ty_param_bound_for_assoc_item(
1653                param_did.expect_local(),
1654                hir_self_ty.span,
1655                assoc_tag,
1656                segment.ident,
1657                span,
1658            )?,
1659            _ => {
1660                return Err(self.report_unresolved_type_relative_path(
1661                    self_ty,
1662                    hir_self_ty,
1663                    assoc_tag,
1664                    segment.ident,
1665                    qpath_hir_id,
1666                    span,
1667                    variant_def_id,
1668                ));
1669            }
1670        };
1671
1672        let assoc_item = self
1673            .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1674            .expect("failed to find associated item");
1675
1676        Ok((assoc_item.def_id, bound))
1677    }
1678
1679    /// Search for inherent associated items for use at the type level.
1680    fn probe_inherent_assoc_item(
1681        &self,
1682        segment: &hir::PathSegment<'_>,
1683        adt_did: DefId,
1684        self_ty: Ty<'tcx>,
1685        block: HirId,
1686        span: Span,
1687        assoc_tag: ty::AssocTag,
1688    ) -> Result<Option<ty::AliasTerm<'tcx>>, ErrorGuaranteed> {
1689        let tcx = self.tcx();
1690
1691        if !tcx.features().inherent_associated_types() {
1692            match assoc_tag {
1693                // Don't attempt to look up inherent associated types when the feature is not
1694                // enabled. Theoretically it'd be fine to do so since we feature-gate their
1695                // definition site. However, the current implementation of inherent associated
1696                // items is somewhat brittle, so let's not run it by default.
1697                ty::AssocTag::Type => return Ok(None),
1698                ty::AssocTag::Const => {
1699                    // We also gate the mgca codepath for type-level uses of inherent consts
1700                    // with the inherent_associated_types feature gate since it relies on the
1701                    // same machinery and has similar rough edges.
1702                    return Err(feature_err(
1703                        &tcx.sess,
1704                        sym::inherent_associated_types,
1705                        span,
1706                        "inherent associated types are unstable",
1707                    )
1708                    .emit());
1709                }
1710                ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1711            }
1712        }
1713
1714        let name = segment.ident;
1715        let candidates: Vec<_> = tcx
1716            .inherent_impls(adt_did)
1717            .iter()
1718            .filter_map(|&impl_| {
1719                let (item, scope) = self.probe_assoc_item_unchecked(name, assoc_tag, impl_)?;
1720                Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1721            })
1722            .collect();
1723
1724        // At the moment, we actually bail out with a hard error if the selection of an inherent
1725        // associated item fails (see below). This means we never consider trait associated items
1726        // as potential fallback candidates (#142006). To temporarily mask that issue, let's not
1727        // select at all if there are no early inherent candidates.
1728        if candidates.is_empty() {
1729            return Ok(None);
1730        }
1731
1732        let (applicable_candidates, fulfillment_errors) =
1733            self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1734
1735        // FIXME(#142006): Don't eagerly error here, there might be applicable trait candidates.
1736        let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1737            match &applicable_candidates[..] {
1738                &[] => Err(self.report_unresolved_inherent_assoc_item(
1739                    name,
1740                    self_ty,
1741                    candidates,
1742                    fulfillment_errors,
1743                    span,
1744                    assoc_tag,
1745                )),
1746
1747                &[applicable_candidate] => Ok(applicable_candidate),
1748
1749                &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1750                    name,
1751                    candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1752                    span,
1753                )),
1754            }?;
1755
1756        // FIXME(#142006): Don't eagerly validate here, there might be trait candidates that are
1757        // accessible (visible and stable) contrary to the inherent candidate.
1758        self.check_assoc_item(assoc_item, name, def_scope, block, span);
1759
1760        // FIXME(fmease): Currently creating throwaway `parent_args` to please
1761        // `lower_generic_args_of_assoc_item`. Modify the latter instead (or sth. similar) to
1762        // not require the parent args logic.
1763        let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1764        let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1765        let args = tcx.mk_args_from_iter(
1766            std::iter::once(ty::GenericArg::from(self_ty))
1767                .chain(args.into_iter().skip(parent_args.len())),
1768        );
1769
1770        let kind = match assoc_tag {
1771            ty::AssocTag::Type => ty::AliasTermKind::InherentTy { def_id: assoc_item },
1772            ty::AssocTag::Const => {
1773                // FIXME(mgca): drop once `InherentConst` accepts IAC-shaped args (issue #156181)
1774                // without this, `new_from_args` errors (#155341).
1775                self.require_type_const_attribute(assoc_item, span)?;
1776                ty::AliasTermKind::InherentConst { def_id: assoc_item }
1777            }
1778            ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1779        };
1780
1781        Ok(Some(ty::AliasTerm::new_from_args(tcx, kind, args)))
1782    }
1783
1784    /// Given name and kind search for the assoc item in the provided scope and check if it's accessible[^1].
1785    ///
1786    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1787    fn probe_assoc_item(
1788        &self,
1789        ident: Ident,
1790        assoc_tag: ty::AssocTag,
1791        block: HirId,
1792        span: Span,
1793        scope: DefId,
1794    ) -> Option<ty::AssocItem> {
1795        let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, scope)?;
1796        self.check_assoc_item(item.def_id, ident, scope, block, span);
1797        Some(item)
1798    }
1799
1800    /// Given name and kind search for the assoc item in the provided scope
1801    /// *without* checking if it's accessible[^1].
1802    ///
1803    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1804    fn probe_assoc_item_unchecked(
1805        &self,
1806        ident: Ident,
1807        assoc_tag: ty::AssocTag,
1808        scope: DefId,
1809    ) -> Option<(ty::AssocItem, /*scope*/ ModId)> {
1810        let tcx = self.tcx();
1811
1812        let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, self.item_def_id());
1813        // We have already adjusted the item name above, so compare with `.normalize_to_macros_2_0()`
1814        // instead of calling `filter_by_name_and_kind` which would needlessly normalize the
1815        // `ident` again and again.
1816        let item = tcx
1817            .associated_items(scope)
1818            .filter_by_name_unhygienic(ident.name)
1819            .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1820
1821        Some((*item, def_scope))
1822    }
1823
1824    /// Check if the given assoc item is accessible in the provided scope wrt. visibility and stability.
1825    fn check_assoc_item(
1826        &self,
1827        item_def_id: DefId,
1828        ident: Ident,
1829        scope: ModId,
1830        block: HirId,
1831        span: Span,
1832    ) {
1833        let tcx = self.tcx();
1834
1835        if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1836            self.dcx().emit_err(crate::diagnostics::AssocItemIsPrivate {
1837                span,
1838                kind: tcx.def_descr(item_def_id),
1839                name: ident,
1840                defined_here_label: tcx.def_span(item_def_id),
1841            });
1842        }
1843
1844        tcx.check_stability(item_def_id, Some(block), span, None);
1845    }
1846
1847    fn probe_traits_that_match_assoc_ty(
1848        &self,
1849        qself_ty: Ty<'tcx>,
1850        assoc_ident: Ident,
1851    ) -> Vec<String> {
1852        let tcx = self.tcx();
1853
1854        // In contexts that have no inference context, just make a new one.
1855        // We do need a local variable to store it, though.
1856        let infcx_;
1857        let infcx = if let Some(infcx) = self.infcx() {
1858            infcx
1859        } else {
1860            if !!qself_ty.has_infer() {
    ::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1861            infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1862            &infcx_
1863        };
1864
1865        tcx.all_traits_including_private()
1866            .filter(|trait_def_id| {
1867                // Consider only traits with the associated type
1868                tcx.associated_items(*trait_def_id)
1869                        .in_definition_order()
1870                        .any(|i| {
1871                            i.is_type()
1872                                && !i.is_impl_trait_in_trait()
1873                                && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1874                        })
1875                    // Consider only accessible traits
1876                    && tcx.visibility(*trait_def_id)
1877                        .is_accessible_from(self.item_def_id(), tcx)
1878                    && tcx.all_impls(*trait_def_id)
1879                        .any(|impl_def_id| {
1880                            let header = tcx.impl_trait_header(impl_def_id);
1881                            let trait_ref = header.trait_ref.instantiate(tcx, infcx.fresh_args_for_item(DUMMY_SP, impl_def_id)).skip_norm_wip();
1882
1883                            let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1884                            // FIXME: Don't bother dealing with non-lifetime binders here...
1885                            if value.has_escaping_bound_vars() {
1886                                return false;
1887                            }
1888                            infcx
1889                                .can_eq(
1890                                    ty::ParamEnv::empty(),
1891                                    trait_ref.self_ty(),
1892                                    value,
1893                                ) && header.polarity != ty::ImplPolarity::Negative
1894                        })
1895            })
1896            .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1897            .collect()
1898    }
1899
1900    /// Lower a [resolved][hir::QPath::Resolved] associated type path to a projection.
1901    #[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_resolved_assoc_ty_path",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1901u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match self.lower_resolved_assoc_item_path(span, opt_self_ty,
                    item_def_id, trait_segment, item_segment,
                    ty::AssocTag::Type) {
                Ok((item_def_id, item_args)) => {
                    Ty::new_projection_from_args(self.tcx(), ty::IsRigid::No,
                        item_def_id, item_args)
                }
                Err(guar) => Ty::new_error(self.tcx(), guar),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
1902    fn lower_resolved_assoc_ty_path(
1903        &self,
1904        span: Span,
1905        opt_self_ty: Option<Ty<'tcx>>,
1906        item_def_id: DefId,
1907        trait_segment: Option<&hir::PathSegment<'_>>,
1908        item_segment: &hir::PathSegment<'_>,
1909    ) -> Ty<'tcx> {
1910        match self.lower_resolved_assoc_item_path(
1911            span,
1912            opt_self_ty,
1913            item_def_id,
1914            trait_segment,
1915            item_segment,
1916            ty::AssocTag::Type,
1917        ) {
1918            Ok((item_def_id, item_args)) => {
1919                Ty::new_projection_from_args(self.tcx(), ty::IsRigid::No, item_def_id, item_args)
1920            }
1921            Err(guar) => Ty::new_error(self.tcx(), guar),
1922        }
1923    }
1924
1925    /// Lower a [resolved][hir::QPath::Resolved] associated const path to a (type-level) constant.
1926    #[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_resolved_assoc_const_path",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1926u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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:
                    Result<Const<'tcx>, ErrorGuaranteed> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let (item_def_id, item_args) =
                self.lower_resolved_assoc_item_path(span, opt_self_ty,
                        item_def_id, trait_segment, item_segment,
                        ty::AssocTag::Const)?;
            self.require_type_const_attribute(item_def_id, span)?;
            let alias_const =
                ty::AliasConst::new(tcx,
                    ty::AliasConstKind::new_from_def_id(tcx, item_def_id),
                    item_args);
            Ok(Const::new_alias(tcx, ty::IsRigid::No, alias_const))
        }
    }
}#[instrument(level = "debug", skip_all)]
1927    fn lower_resolved_assoc_const_path(
1928        &self,
1929        span: Span,
1930        opt_self_ty: Option<Ty<'tcx>>,
1931        item_def_id: DefId,
1932        trait_segment: Option<&hir::PathSegment<'_>>,
1933        item_segment: &hir::PathSegment<'_>,
1934    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1935        let tcx = self.tcx();
1936        let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1937            span,
1938            opt_self_ty,
1939            item_def_id,
1940            trait_segment,
1941            item_segment,
1942            ty::AssocTag::Const,
1943        )?;
1944        self.require_type_const_attribute(item_def_id, span)?;
1945        let alias_const = ty::AliasConst::new(
1946            tcx,
1947            ty::AliasConstKind::new_from_def_id(tcx, item_def_id),
1948            item_args,
1949        );
1950        Ok(Const::new_alias(tcx, ty::IsRigid::No, alias_const))
1951    }
1952
1953    /// Lower a [resolved][hir::QPath::Resolved] (type-level) associated item path.
1954    #[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_resolved_assoc_item_path",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1954u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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:
                    Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let trait_def_id = tcx.parent(item_def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1967",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1967u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let Some(self_ty) =
                opt_self_ty else {
                    return Err(self.report_missing_self_ty_for_resolved_path(trait_def_id,
                                span, item_segment, assoc_tag));
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1977",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1977u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let trait_ref =
                self.lower_mono_trait_ref(span, trait_def_id, self_ty,
                    trait_segment.unwrap(), false);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1981",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1981u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ref");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let item_args =
                self.lower_generic_args_of_assoc_item(span, item_def_id,
                    item_segment, trait_ref.args);
            Ok((item_def_id, item_args))
        }
    }
}#[instrument(level = "debug", skip_all)]
1955    fn lower_resolved_assoc_item_path(
1956        &self,
1957        span: Span,
1958        opt_self_ty: Option<Ty<'tcx>>,
1959        item_def_id: DefId,
1960        trait_segment: Option<&hir::PathSegment<'_>>,
1961        item_segment: &hir::PathSegment<'_>,
1962        assoc_tag: ty::AssocTag,
1963    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1964        let tcx = self.tcx();
1965
1966        let trait_def_id = tcx.parent(item_def_id);
1967        debug!(?trait_def_id);
1968
1969        let Some(self_ty) = opt_self_ty else {
1970            return Err(self.report_missing_self_ty_for_resolved_path(
1971                trait_def_id,
1972                span,
1973                item_segment,
1974                assoc_tag,
1975            ));
1976        };
1977        debug!(?self_ty);
1978
1979        let trait_ref =
1980            self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1981        debug!(?trait_ref);
1982
1983        let item_args =
1984            self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1985
1986        Ok((item_def_id, item_args))
1987    }
1988
1989    pub fn prohibit_generic_args<'a>(
1990        &self,
1991        segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1992        err_extend: GenericsArgsErrExtend<'a>,
1993    ) -> Result<(), ErrorGuaranteed> {
1994        let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1995        let mut result = Ok(());
1996        if let Some(_) = args_visitors.clone().next() {
1997            result = Err(self.report_prohibited_generic_args(
1998                segments.clone(),
1999                args_visitors,
2000                err_extend,
2001            ));
2002        }
2003
2004        for segment in segments {
2005            // Only emit the first error to avoid overloading the user with error messages.
2006            if let Some(c) = segment.args().constraints.first() {
2007                return Err(prohibit_assoc_item_constraint(self, c, None));
2008            }
2009        }
2010
2011        result
2012    }
2013
2014    /// Probe path segments that are semantically allowed to have generic arguments.
2015    ///
2016    /// ### Example
2017    ///
2018    /// ```ignore (illustrative)
2019    ///    Option::None::<()>
2020    /// //         ^^^^ permitted to have generic args
2021    ///
2022    /// // ==> [GenericPathSegment(Option_def_id, 1)]
2023    ///
2024    ///    Option::<()>::None
2025    /// // ^^^^^^        ^^^^ *not* permitted to have generic args
2026    /// // permitted to have generic args
2027    ///
2028    /// // ==> [GenericPathSegment(Option_def_id, 0)]
2029    /// ```
2030    // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2031    pub fn probe_generic_path_segments(
2032        &self,
2033        segments: &[hir::PathSegment<'_>],
2034        self_ty: Option<Ty<'tcx>>,
2035        kind: DefKind,
2036        def_id: DefId,
2037        span: Span,
2038    ) -> Vec<GenericPathSegment> {
2039        // We need to extract the generic arguments supplied by the user in
2040        // the path `path`. Due to the current setup, this is a bit of a
2041        // tricky process; the problem is that resolve only tells us the
2042        // end-point of the path resolution, and not the intermediate steps.
2043        // Luckily, we can (at least for now) deduce the intermediate steps
2044        // just from the end-point.
2045        //
2046        // There are basically five cases to consider:
2047        //
2048        // 1. Reference to a constructor of a struct:
2049        //
2050        //        struct Foo<T>(...)
2051        //
2052        //    In this case, the generic arguments are declared in the type space.
2053        //
2054        // 2. Reference to a constructor of an enum variant:
2055        //
2056        //        enum E<T> { Foo(...) }
2057        //
2058        //    In this case, the generic arguments are defined in the type space,
2059        //    but may be specified either on the type or the variant.
2060        //
2061        // 3. Reference to a free function or constant:
2062        //
2063        //        fn foo<T>() {}
2064        //
2065        //    In this case, the path will again always have the form
2066        //    `a::b::foo::<T>` where only the final segment should have generic
2067        //    arguments. However, in this case, those arguments are declared on
2068        //    a value, and hence are in the value space.
2069        //
2070        // 4. Reference to an associated function or constant:
2071        //
2072        //        impl<A> SomeStruct<A> {
2073        //            fn foo<B>(...) {}
2074        //        }
2075        //
2076        //    Here we can have a path like `a::b::SomeStruct::<A>::foo::<B>`,
2077        //    in which case generic arguments may appear in two places. The
2078        //    penultimate segment, `SomeStruct::<A>`, contains generic arguments
2079        //    in the type space, and the final segment, `foo::<B>` contains
2080        //    generic arguments in value space.
2081        //
2082        // The first step then is to categorize the segments appropriately.
2083
2084        let tcx = self.tcx();
2085
2086        if !!segments.is_empty() {
    ::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2087        let last = segments.len() - 1;
2088
2089        let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2090
2091        match kind {
2092            // Case 1. Reference to a struct constructor.
2093            DefKind::Ctor(CtorOf::Struct, ..) => {
2094                // Everything but the final segment should have no
2095                // parameters at all.
2096                let generics = tcx.generics_of(def_id);
2097                // Variant and struct constructors use the
2098                // generics of their parent type definition.
2099                let generics_def_id = generics.parent.unwrap_or(def_id);
2100                generic_segments.push(GenericPathSegment(generics_def_id, last));
2101            }
2102
2103            // Case 2. Reference to a variant constructor.
2104            DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2105                let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2106                    // We have something like `<module::Enum>::Variant`.
2107
2108                    let adt_def = self.probe_adt(span, self_ty).unwrap();
2109                    if true {
    if !adt_def.is_enum() {
        ::core::panicking::panic("assertion failed: adt_def.is_enum()")
    };
};debug_assert!(adt_def.is_enum());
2110
2111                    // FIXME: Stating that the last segment (here: `Variant`) is allowed to have
2112                    // generic args is a lie! We should set the index to `None` instead as it's
2113                    // the *self type* that's allowed to have args.
2114                    // HIR typeck's `instantiate_value_path` actually contains a special case to
2115                    // reject args on `DefKind::Ctor` segments (see `is_alias_variant_ctor`).
2116                    // Using `None` here for this should allow us to get rid of that workaround.
2117                    //
2118                    // (For additional context, `DefKind::Variant` segments never actually reach
2119                    // this branch as they're interpreted as `TypeRelative` paths whose lowering
2120                    // routines manually reject args on them).
2121
2122                    (adt_def.did(), last)
2123                } else if let [.., second_to_last, _] = segments
2124                    && second_to_last.args.is_some()
2125                    && let Res::Def(DefKind::Enum, _) = second_to_last.res
2126                {
2127                    // We have something like `module::Enum::<…>::Variant`.
2128                    // No segment other than the penultimate one is allowed to have generic args.
2129
2130                    // We had to check that the second to last segment actually referred to an enum
2131                    // since at this stage it could very well refer to a module in which case we
2132                    // certainly don't want to allow generic args on it!
2133
2134                    // `DefKind::Ctor` -> `DefKind::Variant`
2135                    let def_id = match kind {
2136                        DefKind::Ctor(..) => tcx.parent(def_id),
2137                        _ => def_id,
2138                    };
2139
2140                    // `DefKind::Variant` -> `DefKind::Enum`
2141                    let enum_def_id = tcx.parent(def_id);
2142
2143                    (enum_def_id, last - 1)
2144                } else {
2145                    // We have something like `module::Enum::Variant` or `module::Variant`.
2146                    // No segment other than the final one is allowed to have generic args.
2147
2148                    // FIXME: lint here recommending `Enum::<...>::Variant` form
2149                    // instead of `Enum::Variant::<...>` form.
2150
2151                    let generics = tcx.generics_of(def_id);
2152                    // Variant and struct constructors use the
2153                    // generics of their parent type definition.
2154                    (generics.parent.unwrap_or(def_id), last)
2155                };
2156                generic_segments.push(GenericPathSegment(generics_def_id, index));
2157            }
2158
2159            // Case 3. Reference to a top-level value.
2160            DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2161                generic_segments.push(GenericPathSegment(def_id, last));
2162            }
2163
2164            // Case 4. Reference to a method or associated const.
2165            DefKind::AssocFn | DefKind::AssocConst { .. } => {
2166                if segments.len() >= 2 {
2167                    let generics = tcx.generics_of(def_id);
2168                    generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2169                }
2170                generic_segments.push(GenericPathSegment(def_id, last));
2171            }
2172
2173            kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected definition kind {0:?} for {1:?}",
        kind, def_id))bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2174        }
2175
2176        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2176",
                        "rustc_hir_analysis::hir_ty_lowering",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2176u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("generic_segments")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("generic_segments");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_segments)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?generic_segments);
2177
2178        generic_segments
2179    }
2180
2181    /// Lower a [resolved][hir::QPath::Resolved] path to a type.
2182    #[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_resolved_ty_path",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2182u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2190",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2190u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path.res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path.res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("opt_self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("opt_self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path.segments")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path.segments");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path.res)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_self_ty)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path.segments)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let tcx = self.tcx();
            let span = path.span;
            match path.res {
                Res::Def(DefKind::OpaqueTy, did) => {
                    {
                        match tcx.opaque_ty_origin(did) {
                            hir::OpaqueTyOrigin::TyAlias { .. } => {}
                            ref left_val => {
                                ::core::panicking::assert_matches_failed(left_val,
                                    "hir::OpaqueTyOrigin::TyAlias { .. }",
                                    ::core::option::Option::None);
                            }
                        }
                    };
                    let [leading_segments @ .., segment] =
                        path.segments else {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                        };
                    let _ =
                        self.prohibit_generic_args(leading_segments.iter(),
                            GenericsArgsErrExtend::OpaqueTy);
                    let args =
                        self.lower_generic_args_of_path_segment(span, did, segment);
                    Ty::new_opaque(tcx, ty::IsRigid::No, did, args)
                }
                Res::Def(DefKind::Enum | DefKind::TyAlias | DefKind::Struct |
                    DefKind::Union | DefKind::ForeignTy, did) => {
                    {
                        match (&opt_self_ty, &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);
                                }
                            }
                        }
                    };
                    let [leading_segments @ .., segment] =
                        path.segments else {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                        };
                    let _ =
                        self.prohibit_generic_args(leading_segments.iter(),
                            GenericsArgsErrExtend::None);
                    self.lower_path_segment(span, did, segment)
                }
                Res::Def(kind @ DefKind::Variant, def_id) if
                    let PermitVariants::Yes = permit_variants => {
                    {
                        match (&opt_self_ty, &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);
                                }
                            }
                        }
                    };
                    let generic_segments =
                        self.probe_generic_path_segments(path.segments, None, kind,
                            def_id, span);
                    let indices: FxHashSet<_> =
                        generic_segments.iter().map(|GenericPathSegment(_, index)|
                                    index).collect();
                    let _ =
                        self.prohibit_generic_args(path.segments.iter().enumerate().filter_map(|(index,
                                        seg)|
                                    {
                                        if !indices.contains(&index) { Some(seg) } else { None }
                                    }), GenericsArgsErrExtend::DefVariant(&path.segments));
                    let &GenericPathSegment(def_id, index) =
                        generic_segments.last().unwrap();
                    self.lower_path_segment(span, def_id, &path.segments[index])
                }
                Res::Def(DefKind::TyParam, def_id) => {
                    {
                        match (&opt_self_ty, &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);
                                }
                            }
                        }
                    };
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::Param(def_id));
                    self.lower_ty_param(hir_id)
                }
                Res::SelfTyParam { .. } => {
                    {
                        match (&opt_self_ty, &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);
                                }
                            }
                        }
                    };
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            if let [hir::PathSegment { args: Some(args), ident, .. }] =
                                    &path.segments {
                                GenericsArgsErrExtend::SelfTyParam(ident.span.shrink_to_hi().to(args.span_ext))
                            } else { GenericsArgsErrExtend::None });
                    self.check_param_uses_if_mcg(tcx.types.self_param, span,
                        false)
                }
                Res::SelfTyAlias { alias_to: def_id, .. } => {
                    {
                        match (&opt_self_ty, &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);
                                }
                            }
                        }
                    };
                    let ty =
                        tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::SelfTyAlias { def_id, span });
                    self.check_param_uses_if_mcg(ty, span, true)
                }
                Res::Def(DefKind::AssocTy, def_id) => {
                    let trait_segment =
                        if let [modules @ .., trait_, _item] = path.segments {
                            let _ =
                                self.prohibit_generic_args(modules.iter(),
                                    GenericsArgsErrExtend::None);
                            Some(trait_)
                        } else { None };
                    self.lower_resolved_assoc_ty_path(span, opt_self_ty, def_id,
                        trait_segment, path.segments.last().unwrap())
                }
                Res::PrimTy(prim_ty) => {
                    {
                        match (&opt_self_ty, &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);
                                }
                            }
                        }
                    };
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::PrimTy(prim_ty));
                    match prim_ty {
                        hir::PrimTy::Bool => tcx.types.bool,
                        hir::PrimTy::Char => tcx.types.char,
                        hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
                        hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
                        hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
                        hir::PrimTy::Str => tcx.types.str_,
                    }
                }
                Res::Err => {
                    let e =
                        self.tcx().dcx().span_delayed_bug(path.span,
                            "path with `Res::Err` but no error emitted");
                    Ty::new_error(tcx, e)
                }
                Res::Def(..) => {
                    {
                        match (&path.segments.get(0).map(|seg| seg.ident.name),
                                &Some(kw::SelfUpper)) {
                            (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::Some(format_args!("only expected incorrect resolution for `Self`")));
                                }
                            }
                        }
                    };
                    Ty::new_error(self.tcx(),
                        self.dcx().span_delayed_bug(span,
                            "incorrect resolution for `Self`"))
                }
                _ =>
                    ::rustc_middle::util::bug::span_bug_fmt(span,
                        format_args!("unexpected resolution: {0:?}", path.res)),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
2183    pub fn lower_resolved_ty_path(
2184        &self,
2185        opt_self_ty: Option<Ty<'tcx>>,
2186        path: &hir::Path<'_>,
2187        hir_id: HirId,
2188        permit_variants: PermitVariants,
2189    ) -> Ty<'tcx> {
2190        debug!(?path.res, ?opt_self_ty, ?path.segments);
2191        let tcx = self.tcx();
2192
2193        let span = path.span;
2194        match path.res {
2195            Res::Def(DefKind::OpaqueTy, did) => {
2196                // Check for desugared `impl Trait`.
2197                assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2198                let [leading_segments @ .., segment] = path.segments else { bug!() };
2199                let _ = self.prohibit_generic_args(
2200                    leading_segments.iter(),
2201                    GenericsArgsErrExtend::OpaqueTy,
2202                );
2203                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2204                Ty::new_opaque(tcx, ty::IsRigid::No, did, args)
2205            }
2206            Res::Def(
2207                DefKind::Enum
2208                | DefKind::TyAlias
2209                | DefKind::Struct
2210                | DefKind::Union
2211                | DefKind::ForeignTy,
2212                did,
2213            ) => {
2214                assert_eq!(opt_self_ty, None);
2215                let [leading_segments @ .., segment] = path.segments else { bug!() };
2216                let _ = self
2217                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2218                self.lower_path_segment(span, did, segment)
2219            }
2220            Res::Def(kind @ DefKind::Variant, def_id)
2221                if let PermitVariants::Yes = permit_variants =>
2222            {
2223                // Lower "variant type" as if it were a real type.
2224                // The resulting `Ty` is type of the variant's enum for now.
2225                assert_eq!(opt_self_ty, None);
2226
2227                let generic_segments =
2228                    self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2229                let indices: FxHashSet<_> =
2230                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2231                let _ = self.prohibit_generic_args(
2232                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2233                        if !indices.contains(&index) { Some(seg) } else { None }
2234                    }),
2235                    GenericsArgsErrExtend::DefVariant(&path.segments),
2236                );
2237
2238                let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2239                self.lower_path_segment(span, def_id, &path.segments[index])
2240            }
2241            Res::Def(DefKind::TyParam, def_id) => {
2242                assert_eq!(opt_self_ty, None);
2243                let _ = self.prohibit_generic_args(
2244                    path.segments.iter(),
2245                    GenericsArgsErrExtend::Param(def_id),
2246                );
2247                self.lower_ty_param(hir_id)
2248            }
2249            Res::SelfTyParam { .. } => {
2250                // `Self` in trait or type alias.
2251                assert_eq!(opt_self_ty, None);
2252                let _ = self.prohibit_generic_args(
2253                    path.segments.iter(),
2254                    if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2255                        GenericsArgsErrExtend::SelfTyParam(
2256                            ident.span.shrink_to_hi().to(args.span_ext),
2257                        )
2258                    } else {
2259                        GenericsArgsErrExtend::None
2260                    },
2261                );
2262                self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2263            }
2264            Res::SelfTyAlias { alias_to: def_id, .. } => {
2265                // `Self` in impl (we know the concrete type).
2266                assert_eq!(opt_self_ty, None);
2267                // Try to evaluate any array length constants.
2268                let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
2269                let _ = self.prohibit_generic_args(
2270                    path.segments.iter(),
2271                    GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2272                );
2273                self.check_param_uses_if_mcg(ty, span, true)
2274            }
2275            Res::Def(DefKind::AssocTy, def_id) => {
2276                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2277                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2278                    Some(trait_)
2279                } else {
2280                    None
2281                };
2282                self.lower_resolved_assoc_ty_path(
2283                    span,
2284                    opt_self_ty,
2285                    def_id,
2286                    trait_segment,
2287                    path.segments.last().unwrap(),
2288                )
2289            }
2290            Res::PrimTy(prim_ty) => {
2291                assert_eq!(opt_self_ty, None);
2292                let _ = self.prohibit_generic_args(
2293                    path.segments.iter(),
2294                    GenericsArgsErrExtend::PrimTy(prim_ty),
2295                );
2296                match prim_ty {
2297                    hir::PrimTy::Bool => tcx.types.bool,
2298                    hir::PrimTy::Char => tcx.types.char,
2299                    hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2300                    hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2301                    hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2302                    hir::PrimTy::Str => tcx.types.str_,
2303                }
2304            }
2305            Res::Err => {
2306                let e = self
2307                    .tcx()
2308                    .dcx()
2309                    .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2310                Ty::new_error(tcx, e)
2311            }
2312            Res::Def(..) => {
2313                assert_eq!(
2314                    path.segments.get(0).map(|seg| seg.ident.name),
2315                    Some(kw::SelfUpper),
2316                    "only expected incorrect resolution for `Self`"
2317                );
2318                Ty::new_error(
2319                    self.tcx(),
2320                    self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2321                )
2322            }
2323            _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2324        }
2325    }
2326
2327    /// Lower a type parameter from the HIR to our internal notion of a type.
2328    ///
2329    /// Early-bound type parameters get lowered to [`ty::Param`]
2330    /// and late-bound ones to [`ty::Bound`].
2331    pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2332        let tcx = self.tcx();
2333
2334        let ty = match tcx.named_bound_var(hir_id) {
2335            Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2336                let br = ty::BoundTy {
2337                    var: ty::BoundVar::from_u32(index),
2338                    kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2339                };
2340                Ty::new_bound(tcx, debruijn, br)
2341            }
2342            Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2343                let item_def_id = tcx.hir_ty_param_owner(def_id);
2344                let generics = tcx.generics_of(item_def_id);
2345                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2346                Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2347            }
2348            Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2349            arg => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected bound var resolution for {0:?}: {1:?}",
        hir_id, arg))bug!("unexpected bound var resolution for {hir_id:?}: {arg:?}"),
2350        };
2351        self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2352    }
2353
2354    /// Lower a const parameter from the HIR to our internal notion of a constant.
2355    ///
2356    /// Early-bound const parameters get lowered to [`ty::ConstKind::Param`]
2357    /// and late-bound ones to [`ty::ConstKind::Bound`].
2358    pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2359        let tcx = self.tcx();
2360
2361        let ct = match tcx.named_bound_var(path_hir_id) {
2362            Some(rbv::ResolvedArg::EarlyBound(_)) => {
2363                // Find the name and index of the const parameter by indexing the generics of
2364                // the parent item and construct a `ParamConst`.
2365                let item_def_id = tcx.parent(param_def_id);
2366                let generics = tcx.generics_of(item_def_id);
2367                let index = generics.param_def_id_to_index[&param_def_id];
2368                let name = tcx.item_name(param_def_id);
2369                ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2370            }
2371            Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2372                tcx,
2373                debruijn,
2374                ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2375            ),
2376            Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2377            arg => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected bound var resolution for {0:?}: {1:?}",
        path_hir_id, arg))bug!("unexpected bound var resolution for {:?}: {arg:?}", path_hir_id),
2378        };
2379        self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2380    }
2381
2382    /// Lower a [`hir::ConstArg`] to a (type-level) [`ty::Const`].
2383    #[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_const_arg",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2383u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("const_arg")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("const_arg");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        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(&const_arg)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            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: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
                if tcx.features().generic_const_parameter_types() &&
                        (ty.has_free_regions() || ty.has_erased_regions()) {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants with lifetimes in their type are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                if ty.has_non_region_infer() {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants with inferred types are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                if ty.has_non_region_param() {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants referencing generics are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                tcx.feed_anon_const_type(anon.def_id,
                    ty::EarlyBinder::bind(tcx, ty));
            }
            let hir_id = const_arg.hir_id;
            match const_arg.kind {
                hir::ConstArgKind::Tup(exprs) =>
                    self.lower_const_arg_tup(exprs, ty, const_arg.span),
                hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself,
                    path)) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2444",
                                            "rustc_hir_analysis::hir_ty_lowering",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(2444u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("maybe_qself")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("maybe_qself");
                                                                NAME.as_str()
                                                            },
                                                            {
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("path")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("path");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&maybe_qself)
                                                                as &dyn ::tracing::field::Value)),
                                                    (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let opt_self_ty =
                        maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
                    self.lower_resolved_const_path(opt_self_ty, path, hir_id)
                }
                hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty,
                    segment)) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2449",
                                            "rustc_hir_analysis::hir_ty_lowering",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(2449u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("hir_self_ty")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("hir_self_ty");
                                                                NAME.as_str()
                                                            },
                                                            {
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("segment")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("segment");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_self_ty)
                                                                as &dyn ::tracing::field::Value)),
                                                    (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&segment)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let self_ty = self.lower_ty(hir_self_ty);
                    self.lower_type_relative_const_path(self_ty, hir_self_ty,
                            segment, hir_id,
                            const_arg.span).unwrap_or_else(|guar|
                            Const::new_error(tcx, guar))
                }
                hir::ConstArgKind::Struct(qpath, inits) => {
                    self.lower_const_arg_struct(hir_id, qpath, inits,
                        const_arg.span)
                }
                hir::ConstArgKind::TupleCall(qpath, args) => {
                    self.lower_const_arg_tuple_call(hir_id, qpath, args,
                        const_arg.span)
                }
                hir::ConstArgKind::Array(array_expr) =>
                    self.lower_const_arg_array(array_expr, ty),
                hir::ConstArgKind::Anon(anon) =>
                    self.lower_const_arg_anon(anon),
                hir::ConstArgKind::Infer(()) =>
                    self.ct_infer(None, const_arg.span),
                hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
                hir::ConstArgKind::Literal { lit, negated } => {
                    self.lower_const_arg_literal(&lit, negated, ty,
                        const_arg.span)
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
2384    pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'_>, ty: Ty<'tcx>) -> Const<'tcx> {
2385        let tcx = self.tcx();
2386
2387        if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2388            // FIXME(generic_const_parameter_types): Ideally we remove these errors below when
2389            // we have the ability to intermix typeck of anon const const args with the parent
2390            // bodies typeck.
2391
2392            // We also error if the type contains any regions as effectively any region will wind
2393            // up as a region variable in mir borrowck. It would also be somewhat concerning if
2394            // hir typeck was using equality but mir borrowck wound up using subtyping as that could
2395            // result in a non-infer in hir typeck but a region variable in borrowck.
2396            if tcx.features().generic_const_parameter_types()
2397                && (ty.has_free_regions() || ty.has_erased_regions())
2398            {
2399                let e = self.dcx().span_err(
2400                    const_arg.span,
2401                    "anonymous constants with lifetimes in their type are not yet supported",
2402                );
2403                tcx.feed_anon_const_type(
2404                    anon.def_id,
2405                    ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2406                );
2407                return ty::Const::new_error(tcx, e);
2408            }
2409            // We must error if the instantiated type has any inference variables as we will
2410            // use this type to feed the `type_of` and query results must not contain inference
2411            // variables otherwise we will ICE.
2412            if ty.has_non_region_infer() {
2413                let e = self.dcx().span_err(
2414                    const_arg.span,
2415                    "anonymous constants with inferred types are not yet supported",
2416                );
2417                tcx.feed_anon_const_type(
2418                    anon.def_id,
2419                    ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2420                );
2421                return ty::Const::new_error(tcx, e);
2422            }
2423            // We error when the type contains unsubstituted generics since we do not currently
2424            // give the anon const any of the generics from the parent.
2425            if ty.has_non_region_param() {
2426                let e = self.dcx().span_err(
2427                    const_arg.span,
2428                    "anonymous constants referencing generics are not yet supported",
2429                );
2430                tcx.feed_anon_const_type(
2431                    anon.def_id,
2432                    ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2433                );
2434                return ty::Const::new_error(tcx, e);
2435            }
2436
2437            tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(tcx, ty));
2438        }
2439
2440        let hir_id = const_arg.hir_id;
2441        match const_arg.kind {
2442            hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2443            hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2444                debug!(?maybe_qself, ?path);
2445                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2446                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2447            }
2448            hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2449                debug!(?hir_self_ty, ?segment);
2450                let self_ty = self.lower_ty(hir_self_ty);
2451                self.lower_type_relative_const_path(
2452                    self_ty,
2453                    hir_self_ty,
2454                    segment,
2455                    hir_id,
2456                    const_arg.span,
2457                )
2458                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2459            }
2460            hir::ConstArgKind::Struct(qpath, inits) => {
2461                self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2462            }
2463            hir::ConstArgKind::TupleCall(qpath, args) => {
2464                self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2465            }
2466            hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2467            hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2468            hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2469            hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2470            hir::ConstArgKind::Literal { lit, negated } => {
2471                self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2472            }
2473        }
2474    }
2475
2476    fn lower_const_arg_array(
2477        &self,
2478        array_expr: &hir::ConstArgArrayExpr<'_>,
2479        ty: Ty<'tcx>,
2480    ) -> Const<'tcx> {
2481        let tcx = self.tcx();
2482
2483        let (elem_ty, len) = match ty.kind() {
2484            ty::Array(elem_ty, len) => (elem_ty, len),
2485            ty::Error(e) => return Const::new_error(tcx, *e),
2486            _ => {
2487                let e = tcx
2488                    .dcx()
2489                    .span_err(array_expr.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found const array",
                ty))
    })format!("expected `{ty}`, found const array"));
2490                return Const::new_error(tcx, e);
2491            }
2492        };
2493
2494        let elems = array_expr
2495            .elems
2496            .iter()
2497            .map(|elem| self.lower_const_arg(elem, *elem_ty))
2498            .collect::<Vec<_>>();
2499
2500        let len = tcx
2501            .try_normalize_erasing_regions(
2502                ty::TypingEnv::new(ty::ParamEnv::empty(), TypingMode::non_body_analysis()),
2503                Unnormalized::new_wip(*len),
2504            )
2505            .unwrap_or(*len);
2506        if let Some(expected_len) = len.try_to_target_usize(tcx)
2507            && expected_len != elems.len() as u64
2508        {
2509            let e = tcx.dcx().span_err(
2510                array_expr.span,
2511                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected array with {1} elements, found {0} elements",
                array_expr.elems.len(), expected_len))
    })format!(
2512                    "expected array with {expected_len} elements, found {} elements",
2513                    array_expr.elems.len()
2514                ),
2515            );
2516            return Const::new_error(tcx, e);
2517        }
2518
2519        let valtree = ty::ValTree::from_branches(tcx, elems);
2520
2521        ty::Const::new_value(tcx, valtree, ty)
2522    }
2523
2524    fn lower_const_arg_tuple_call(
2525        &self,
2526        hir_id: HirId,
2527        qpath: hir::QPath<'_>,
2528        args: &[&hir::ConstArg<'_>],
2529        span: Span,
2530    ) -> Const<'tcx> {
2531        let tcx = self.tcx();
2532
2533        let non_adt_or_variant_res = || {
2534            let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2535            ty::Const::new_error(tcx, e)
2536        };
2537
2538        let ctor_const = match qpath {
2539            hir::QPath::Resolved(maybe_qself, path) => {
2540                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2541                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2542            }
2543            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2544                let self_ty = self.lower_ty(hir_self_ty);
2545                match self.lower_type_relative_const_path(
2546                    self_ty,
2547                    hir_self_ty,
2548                    segment,
2549                    hir_id,
2550                    span,
2551                ) {
2552                    Ok(c) => c,
2553                    Err(_) => return non_adt_or_variant_res(),
2554                }
2555            }
2556        };
2557
2558        let Some(value) = ctor_const.try_to_value() else {
2559            return non_adt_or_variant_res();
2560        };
2561
2562        let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2563            ty::FnDef(def_id, fn_args)
2564                if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2565            {
2566                let parent_did = tcx.parent(*def_id);
2567                let enum_did = tcx.parent(parent_did);
2568                (tcx.adt_def(enum_did), fn_args, parent_did)
2569            }
2570            ty::FnDef(def_id, fn_args)
2571                if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2572            {
2573                let parent_did = tcx.parent(*def_id);
2574                (tcx.adt_def(parent_did), fn_args, parent_did)
2575            }
2576            _ => {
2577                let e = self.dcx().span_err(
2578                    span,
2579                    "complex const arguments must be placed inside of a `const` block",
2580                );
2581                return Const::new_error(tcx, e);
2582            }
2583        };
2584
2585        let variant_def = adt_def.variant_with_id(variant_did);
2586        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2587
2588        if args.len() != variant_def.fields.len() {
2589            let e = tcx.dcx().span_err(
2590                span,
2591                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("tuple constructor has {0} arguments but {1} were provided",
                variant_def.fields.len(), args.len()))
    })format!(
2592                    "tuple constructor has {} arguments but {} were provided",
2593                    variant_def.fields.len(),
2594                    args.len()
2595                ),
2596            );
2597            return ty::Const::new_error(tcx, e);
2598        }
2599
2600        let fields = variant_def
2601            .fields
2602            .iter()
2603            .zip(args)
2604            .map(|(field_def, arg)| {
2605                self.lower_const_arg(
2606                    arg,
2607                    tcx.type_of(field_def.did)
2608                        .instantiate(tcx, adt_args.no_bound_vars().unwrap())
2609                        .skip_norm_wip(),
2610                )
2611            })
2612            .collect::<Vec<_>>();
2613
2614        let opt_discr_const = if adt_def.is_enum() {
2615            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2616            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2617        } else {
2618            None
2619        };
2620
2621        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2622        let adt_ty = Ty::new_adt(tcx, adt_def, adt_args.no_bound_vars().unwrap());
2623        ty::Const::new_value(tcx, valtree, adt_ty)
2624    }
2625
2626    fn lower_const_arg_tup(
2627        &self,
2628        exprs: &[&hir::ConstArg<'_>],
2629        ty: Ty<'tcx>,
2630        span: Span,
2631    ) -> Const<'tcx> {
2632        let tcx = self.tcx();
2633
2634        let found_tuple = || {
2635            tcx.sess
2636                .source_map()
2637                .span_to_snippet(span)
2638                .map(|snippet| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", snippet))
    })format!("`{snippet}`"))
2639                .unwrap_or_else(|_| "const tuple".to_string())
2640        };
2641
2642        let tys = match ty.kind() {
2643            ty::Tuple(tys) => tys,
2644            ty::Error(e) => return Const::new_error(tcx, *e),
2645            _ => {
2646                let e =
2647                    tcx.dcx().span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found {1}", ty,
                found_tuple()))
    })format!("expected `{}`, found {}", ty, found_tuple()));
2648                return Const::new_error(tcx, e);
2649            }
2650        };
2651
2652        if exprs.len() != tys.len() {
2653            let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found {1}", ty,
                found_tuple()))
    })format!("expected `{}`, found {}", ty, found_tuple()));
2654            return Const::new_error(tcx, e);
2655        }
2656
2657        let exprs = exprs
2658            .iter()
2659            .zip(tys.iter())
2660            .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2661            .collect::<Vec<_>>();
2662
2663        let valtree = ty::ValTree::from_branches(tcx, exprs);
2664        ty::Const::new_value(tcx, valtree, ty)
2665    }
2666
2667    fn lower_const_arg_struct(
2668        &self,
2669        hir_id: HirId,
2670        qpath: hir::QPath<'_>,
2671        inits: &[&hir::ConstArgExprField<'_>],
2672        span: Span,
2673    ) -> Const<'tcx> {
2674        // FIXME(mgca): try to deduplicate this function with
2675        // the equivalent HIR typeck logic.
2676        let tcx = self.tcx();
2677
2678        let non_adt_or_variant_res = || {
2679            let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2680            ty::Const::new_error(tcx, e)
2681        };
2682
2683        let ResolvedStructPath { res: opt_res, ty } =
2684            self.lower_path_for_struct_expr(qpath, span, hir_id);
2685
2686        let variant_did = match qpath {
2687            hir::QPath::Resolved(maybe_qself, path) => {
2688                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2688",
                        "rustc_hir_analysis::hir_ty_lowering",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2688u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("maybe_qself")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("maybe_qself");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("path")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("path");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&maybe_qself)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?maybe_qself, ?path);
2689                let variant_did = match path.res {
2690                    Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2691                    _ => return non_adt_or_variant_res(),
2692                };
2693
2694                variant_did
2695            }
2696            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2697                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2697",
                        "rustc_hir_analysis::hir_ty_lowering",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2697u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("hir_self_ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("hir_self_ty");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("segment")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("segment");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_self_ty)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&segment)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?hir_self_ty, ?segment);
2698
2699                let res_def_id = match opt_res {
2700                    Ok(r)
2701                        if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(r.def_id()) {
    DefKind::Variant | DefKind::Struct => true,
    _ => false,
}matches!(
2702                            tcx.def_kind(r.def_id()),
2703                            DefKind::Variant | DefKind::Struct
2704                        ) =>
2705                    {
2706                        r.def_id()
2707                    }
2708                    Ok(_) => return non_adt_or_variant_res(),
2709                    Err(e) => return ty::Const::new_error(tcx, e),
2710                };
2711
2712                res_def_id
2713            }
2714        };
2715
2716        let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2717
2718        let variant_def = adt_def.variant_with_id(variant_did);
2719        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2720
2721        for init in inits {
2722            if !variant_def.fields.iter().any(|field_def| field_def.name == init.field.name) {
2723                let mut err = if adt_def.is_enum() {
2724                    {
    tcx.dcx().struct_span_err(init.field.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("variant `{0}::{1}` has no field named `{2}`",
                            ty, variant_def.name, init.field))
                })).with_code(E0559)
}struct_span_code_err!(
2725                        tcx.dcx(),
2726                        init.field.span,
2727                        E0559,
2728                        "variant `{}::{}` has no field named `{}`",
2729                        ty,
2730                        variant_def.name,
2731                        init.field
2732                    )
2733                } else {
2734                    {
    tcx.dcx().struct_span_err(init.field.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("struct `{0}` has no field named `{1}`",
                            variant_def.name, init.field))
                })).with_code(E0560)
}struct_span_code_err!(
2735                        tcx.dcx(),
2736                        init.field.span,
2737                        E0560,
2738                        "struct `{}` has no field named `{}`",
2739                        variant_def.name,
2740                        init.field
2741                    )
2742                };
2743                if adt_def.is_enum() {
2744                    err.span_label(
2745                        init.field.span,
2746                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` does not have this field",
                ty, variant_def.name))
    })format!("`{}::{}` does not have this field", ty, variant_def.name),
2747                    );
2748                } else {
2749                    err.span_label(
2750                        init.field.span,
2751                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` does not have this field",
                variant_def.name))
    })format!("`{}` does not have this field", variant_def.name),
2752                    );
2753                }
2754                return ty::Const::new_error(tcx, err.emit());
2755            }
2756        }
2757
2758        let fields = variant_def
2759            .fields
2760            .iter()
2761            .map(|field_def| {
2762                // FIXME(mgca): we aren't really handling privacy, stability,
2763                // or macro hygeniene but we should.
2764                let mut init_expr =
2765                    inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2766
2767                match init_expr.next() {
2768                    Some(expr) => {
2769                        if let Some(expr) = init_expr.next() {
2770                            let e = tcx.dcx().span_err(
2771                                expr.span,
2772                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
                field_def.name))
    })format!(
2773                                    "struct expression with multiple initialisers for `{}`",
2774                                    field_def.name,
2775                                ),
2776                            );
2777                            return ty::Const::new_error(tcx, e);
2778                        }
2779
2780                        self.lower_const_arg(
2781                            expr.expr,
2782                            tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2783                        )
2784                    }
2785                    None => {
2786                        let e = tcx.dcx().span_err(
2787                            span,
2788                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
                field_def.name))
    })format!(
2789                                "struct expression with missing field initialiser for `{}`",
2790                                field_def.name
2791                            ),
2792                        );
2793                        ty::Const::new_error(tcx, e)
2794                    }
2795                }
2796            })
2797            .collect::<Vec<_>>();
2798
2799        let opt_discr_const = if adt_def.is_enum() {
2800            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2801            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2802        } else {
2803            None
2804        };
2805
2806        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2807        ty::Const::new_value(tcx, valtree, ty)
2808    }
2809
2810    pub fn lower_path_for_struct_expr(
2811        &self,
2812        qpath: hir::QPath<'_>,
2813        path_span: Span,
2814        hir_id: HirId,
2815    ) -> ResolvedStructPath<'tcx> {
2816        match qpath {
2817            hir::QPath::Resolved(ref maybe_qself, path) => {
2818                let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2819                let ty = self.lower_resolved_ty_path(self_ty, path, hir_id, PermitVariants::Yes);
2820                ResolvedStructPath { res: Ok(path.res), ty }
2821            }
2822            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2823                let self_ty = self.lower_ty(hir_self_ty);
2824
2825                let result = self.lower_type_relative_ty_path(
2826                    self_ty,
2827                    hir_self_ty,
2828                    segment,
2829                    hir_id,
2830                    path_span,
2831                    PermitVariants::Yes,
2832                );
2833                let ty = result
2834                    .map(|(ty, _, _)| ty)
2835                    .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
2836
2837                ResolvedStructPath {
2838                    res: result.map(|(_, kind, def_id)| Res::Def(kind, def_id)),
2839                    ty,
2840                }
2841            }
2842        }
2843    }
2844
2845    /// Lower a [resolved][hir::QPath::Resolved] path to a (type-level) constant.
2846    fn lower_resolved_const_path(
2847        &self,
2848        opt_self_ty: Option<Ty<'tcx>>,
2849        path: &hir::Path<'_>,
2850        hir_id: HirId,
2851    ) -> Const<'tcx> {
2852        let tcx = self.tcx();
2853        let span = path.span;
2854        let ct = match path.res {
2855            Res::Def(DefKind::ConstParam, def_id) => {
2856                {
    match (&opt_self_ty, &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!(opt_self_ty, None);
2857                let _ = self.prohibit_generic_args(
2858                    path.segments.iter(),
2859                    GenericsArgsErrExtend::Param(def_id),
2860                );
2861                self.lower_const_param(def_id, hir_id)
2862            }
2863            Res::Def(DefKind::Const { .. }, did) => {
2864                if let Err(guar) = self.require_type_const_attribute(did, span) {
2865                    return Const::new_error(self.tcx(), guar);
2866                }
2867
2868                {
    match (&opt_self_ty, &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!(opt_self_ty, None);
2869                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2870                let _ = self
2871                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2872                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2873                ty::Const::new_alias(
2874                    tcx,
2875                    ty::IsRigid::No,
2876                    ty::AliasConst::new(tcx, ty::AliasConstKind::new_from_def_id(tcx, did), args),
2877                )
2878            }
2879            Res::Def(kind @ DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2880                {
    match (&opt_self_ty, &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!(opt_self_ty, None);
2881                let generic_segments =
2882                    self.probe_generic_path_segments(path.segments, opt_self_ty, kind, did, span);
2883                let indices: FxHashSet<_> =
2884                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2885                let _ = self.prohibit_generic_args(
2886                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2887                        if !indices.contains(&index) { Some(seg) } else { None }
2888                    }),
2889                    GenericsArgsErrExtend::DefVariant(&path.segments),
2890                );
2891
2892                let parent_did = tcx.parent(did);
2893                let generics_did = match ctor_of {
2894                    CtorOf::Variant => tcx.parent(parent_did),
2895                    CtorOf::Struct => parent_did,
2896                };
2897                let args = self.lower_generic_args_of_path_segment(
2898                    span,
2899                    generics_did,
2900                    &path.segments[generic_segments[0].1],
2901                );
2902                self.construct_const_ctor_value(did, ctor_of, args)
2903            }
2904            Res::Def(DefKind::Ctor(ctor_of, CtorKind::Fn), did) => {
2905                {
    match (&opt_self_ty, &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!(opt_self_ty, None);
2906                let generic_segments = self.probe_generic_path_segments(
2907                    path.segments,
2908                    opt_self_ty,
2909                    DefKind::Ctor(ctor_of, CtorKind::Const),
2910                    did,
2911                    span,
2912                );
2913                let indices: FxHashSet<_> =
2914                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2915                let _ = self.prohibit_generic_args(
2916                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2917                        if !indices.contains(&index) { Some(seg) } else { None }
2918                    }),
2919                    GenericsArgsErrExtend::DefVariant(&path.segments),
2920                );
2921
2922                let parent_did = tcx.parent(did);
2923                let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2924                    tcx.parent(parent_did)
2925                } else {
2926                    parent_did
2927                };
2928                let args = self.lower_generic_args_of_path_segment(
2929                    span,
2930                    generics_did,
2931                    &path.segments[generic_segments[0].1],
2932                );
2933
2934                ty::Const::zero_sized(tcx, tcx.type_of(did).instantiate(tcx, args).skip_norm_wip())
2935            }
2936            Res::Def(DefKind::AssocConst { .. }, did) => {
2937                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2938                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2939                    Some(trait_)
2940                } else {
2941                    None
2942                };
2943                self.lower_resolved_assoc_const_path(
2944                    span,
2945                    opt_self_ty,
2946                    did,
2947                    trait_segment,
2948                    path.segments.last().unwrap(),
2949                )
2950                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2951            }
2952            Res::Def(DefKind::Static { .. }, _) => {
2953                let guar = self
2954                    .dcx()
2955                    .span_err(path.span, "static items cannot be used as const arguments");
2956                return Const::new_error(tcx, guar);
2957            }
2958            // FIXME(const_generics): create real consts to allow fn items as const paths.
2959            // Lowering these to recovered `FnDef` consts currently interacts poorly with WF
2960            // checking: WF of a `FnDef` walks the function signature, so a signature that mentions
2961            // the same function item as a const arg can recurse until it overflows/segfaults.
2962            Res::Def(DefKind::Fn | DefKind::AssocFn, _) => {
2963                let guar = self
2964                    .dcx()
2965                    .struct_span_err(span, "function items cannot be used as const args")
2966                    .emit();
2967                Const::new_error(tcx, guar)
2968            }
2969            // Exhaustive match to be clear about what exactly we're considering to be
2970            // an invalid Res for a const path.
2971            res @ (Res::Def(
2972                DefKind::Mod
2973                | DefKind::Enum
2974                | DefKind::Variant
2975                | DefKind::Struct
2976                | DefKind::OpaqueTy
2977                | DefKind::TyAlias
2978                | DefKind::TraitAlias
2979                | DefKind::AssocTy
2980                | DefKind::Union
2981                | DefKind::Trait
2982                | DefKind::ForeignTy
2983                | DefKind::TyParam
2984                | DefKind::Macro(_)
2985                | DefKind::LifetimeParam
2986                | DefKind::Use
2987                | DefKind::ForeignMod
2988                | DefKind::AnonConst
2989                | DefKind::Field
2990                | DefKind::Impl { .. }
2991                | DefKind::Closure
2992                | DefKind::ExternCrate
2993                | DefKind::GlobalAsm
2994                | DefKind::SyntheticCoroutineBody,
2995                _,
2996            )
2997            | Res::PrimTy(_)
2998            | Res::SelfTyParam { .. }
2999            | Res::SelfTyAlias { .. }
3000            | Res::SelfCtor(_)
3001            | Res::Local(_)
3002            | Res::ToolMod
3003            | Res::OpenMod(..)
3004            | Res::NonMacroAttr(_)
3005            | Res::Err) => Const::new_error_with_message(
3006                tcx,
3007                span,
3008                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
                res))
    })format!("invalid Res {res:?} for const path"),
3009            ),
3010        };
3011        self.check_param_uses_if_mcg(ct, span, false)
3012    }
3013
3014    /// Literals are eagerly converted to a constant, everything else becomes `ConstKind::Alias`.
3015    #[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_const_arg_anon",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3015u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("anon")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("anon");
                                                        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(&anon)
                                                            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: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let expr = &tcx.hir_body(anon.body).value;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:3020",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3020u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expr");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let ty =
                tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
            match self.try_lower_anon_const_lit(ty, expr) {
                Some(v) => v,
                None =>
                    ty::Const::new_alias(tcx, ty::IsRigid::No,
                        ty::AliasConst::new(tcx,
                            ty::AliasConstKind::Anon {
                                def_id: anon.def_id.to_def_id(),
                            },
                            ty::GenericArgs::identity_for_item(tcx,
                                anon.def_id.to_def_id()))),
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
3016    fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
3017        let tcx = self.tcx();
3018
3019        let expr = &tcx.hir_body(anon.body).value;
3020        debug!(?expr);
3021
3022        // FIXME(generic_const_parameter_types): We should use the proper generic args
3023        // here. It's only used as a hint for literals so doesn't matter too much to use the right
3024        // generic arguments, just weaker type inference.
3025        let ty = tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
3026
3027        match self.try_lower_anon_const_lit(ty, expr) {
3028            Some(v) => v,
3029            None => ty::Const::new_alias(
3030                tcx,
3031                ty::IsRigid::No,
3032                ty::AliasConst::new(
3033                    tcx,
3034                    ty::AliasConstKind::Anon { def_id: anon.def_id.to_def_id() },
3035                    ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
3036                ),
3037            ),
3038        }
3039    }
3040
3041    #[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_const_arg_literal",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3041u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("kind");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("neg")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("neg");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        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(&kind)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&neg as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            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: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let ty = if !ty.has_infer() { Some(ty) } else { None };
            if let LitKind::Err(guar) = *kind {
                return ty::Const::new_error(tcx, guar);
            }
            let input = LitToConstInput { lit: *kind, ty, neg };
            match tcx.at(span).lit_to_const(input) {
                Some(value) =>
                    ty::Const::new_value(tcx, value.valtree, value.ty),
                None => {
                    let e =
                        tcx.dcx().span_err(span,
                            "type annotations needed for the literal");
                    ty::Const::new_error(tcx, e)
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
3042    fn lower_const_arg_literal(
3043        &self,
3044        kind: &LitKind,
3045        neg: bool,
3046        ty: Ty<'tcx>,
3047        span: Span,
3048    ) -> Const<'tcx> {
3049        let tcx = self.tcx();
3050
3051        let ty = if !ty.has_infer() { Some(ty) } else { None };
3052
3053        if let LitKind::Err(guar) = *kind {
3054            return ty::Const::new_error(tcx, guar);
3055        }
3056        let input = LitToConstInput { lit: *kind, ty, neg };
3057        match tcx.at(span).lit_to_const(input) {
3058            Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
3059            None => {
3060                let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
3061                ty::Const::new_error(tcx, e)
3062            }
3063        }
3064    }
3065
3066    #[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("try_lower_anon_const_lit",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3066u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expr");
                                                        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(&ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            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: Option<Const<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let expr =
                match &expr.kind {
                    hir::ExprKind::Block(block, _) if
                        block.stmts.is_empty() && block.expr.is_some() => {
                        block.expr.as_ref().unwrap()
                    }
                    _ => expr,
                };
            let lit_input =
                match expr.kind {
                    hir::ExprKind::Lit(lit) => {
                        Some(LitToConstInput {
                                lit: lit.node,
                                ty: Some(ty),
                                neg: false,
                            })
                    }
                    hir::ExprKind::Unary(hir::UnOp::Neg, expr) =>
                        match expr.kind {
                            hir::ExprKind::Lit(lit) => {
                                Some(LitToConstInput {
                                        lit: lit.node,
                                        ty: Some(ty),
                                        neg: true,
                                    })
                            }
                            _ => None,
                        },
                    _ => None,
                };
            lit_input.and_then(|l|
                    {
                        if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
                            tcx.at(expr.span).lit_to_const(l).map(|value|
                                    ty::Const::new_value(tcx, value.valtree, value.ty))
                        } else { None }
                    })
        }
    }
}#[instrument(skip(self), level = "debug")]
3067    fn try_lower_anon_const_lit(
3068        &self,
3069        ty: Ty<'tcx>,
3070        expr: &'tcx hir::Expr<'tcx>,
3071    ) -> Option<Const<'tcx>> {
3072        let tcx = self.tcx();
3073
3074        // Unwrap a block, so that e.g. `{ 1 }` is recognised as a literal. This makes the
3075        // performance optimisation of directly lowering anon consts occur more often.
3076        let expr = match &expr.kind {
3077            hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
3078                block.expr.as_ref().unwrap()
3079            }
3080            _ => expr,
3081        };
3082
3083        let lit_input = match expr.kind {
3084            hir::ExprKind::Lit(lit) => {
3085                Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
3086            }
3087            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
3088                hir::ExprKind::Lit(lit) => {
3089                    Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
3090                }
3091                _ => None,
3092            },
3093            _ => None,
3094        };
3095
3096        lit_input.and_then(|l| {
3097            if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
3098                tcx.at(expr.span)
3099                    .lit_to_const(l)
3100                    .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
3101            } else {
3102                None
3103            }
3104        })
3105    }
3106
3107    fn require_type_const_attribute(
3108        &self,
3109        def_id: DefId,
3110        span: Span,
3111    ) -> Result<(), ErrorGuaranteed> {
3112        let tcx = self.tcx();
3113        // FIXME(gca): Intentionally disallowing paths to inherent associated non-type constants
3114        // until a refactoring for how generic args for IACs are represented has been landed.
3115        let is_inherent_assoc_const = tcx.def_kind(def_id)
3116            == DefKind::AssocConst { is_type_const: false }
3117            && tcx.def_kind(tcx.parent(def_id)) == DefKind::Impl { of_trait: false };
3118        if tcx.is_type_const(def_id)
3119            || tcx.features().generic_const_args() && !is_inherent_assoc_const
3120        {
3121            Ok(())
3122        } else {
3123            let mut err = self.dcx().struct_span_err(
3124                span,
3125                "use of `const` in the type system not defined as `type const`",
3126            );
3127            if let Some(local_def_id) = def_id.as_local() {
3128                let name = tcx.def_path_str(def_id);
3129                let (insertion_span, sugg) = match tcx.hir_node_by_def_id(local_def_id) {
3130                    hir::Node::Item(item) if !item.vis_span.is_empty() => {
3131                        (item.vis_span.shrink_to_hi(), " type")
3132                    }
3133                    hir::Node::ImplItem(impl_item)
3134                        if let Some(vis_span) =
3135                            impl_item.vis_span().filter(|span| !span.is_empty()) =>
3136                    {
3137                        (vis_span.shrink_to_hi(), " type")
3138                    }
3139                    _ => (tcx.def_span(def_id).shrink_to_lo(), "type "),
3140                };
3141
3142                err.span_suggestion_verbose(
3143                    insertion_span,
3144                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
                name))
    })format!("add `type` before `const` for `{name}`"),
3145                    sugg,
3146                    Applicability::MaybeIncorrect,
3147                );
3148            } else {
3149                err.note("only consts marked defined as `type const` may be used in types");
3150            }
3151            Err(err.emit())
3152        }
3153    }
3154
3155    fn lower_delegation_ty(&self, infer: hir::InferDelegation<'_>) -> Ty<'tcx> {
3156        match infer {
3157            hir::InferDelegation::DefId(def_id) => {
3158                self.tcx().type_of(def_id).instantiate_identity().skip_norm_wip()
3159            }
3160            rustc_hir::InferDelegation::Sig(_, idx) => {
3161                let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
3162
3163                match idx {
3164                    hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
3165                    hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
3166                }
3167            }
3168        }
3169    }
3170
3171    /// Lower a type from the HIR to our internal notion of a type.
3172    x;#[instrument(level = "debug", skip(self), ret)]
3173    pub fn lower_ty(&self, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
3174        let tcx = self.tcx();
3175
3176        let result_ty = match &hir_ty.kind {
3177            hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
3178            hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
3179            hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
3180            hir::TyKind::Ref(region, mt) => {
3181                let r = self.lower_lifetime(region, RegionInferReason::Reference);
3182                debug!(?r);
3183                let t = self.lower_ty(mt.ty);
3184                Ty::new_ref(tcx, r, t, mt.mutbl)
3185            }
3186            hir::TyKind::Never => tcx.types.never,
3187            hir::TyKind::Tup(fields) => {
3188                Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
3189            }
3190            hir::TyKind::FnPtr(bf) => {
3191                check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
3192
3193                Ty::new_fn_ptr(
3194                    tcx,
3195                    self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
3196                )
3197            }
3198            hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
3199                tcx,
3200                ty::Binder::bind_with_vars(
3201                    self.lower_ty(binder.inner_ty),
3202                    tcx.late_bound_vars(hir_ty.hir_id),
3203                ),
3204            ),
3205            hir::TyKind::TraitObject(bounds, tagged_ptr) => {
3206                let lifetime = tagged_ptr.pointer();
3207                let syntax = tagged_ptr.tag();
3208                self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3209            }
3210            // If we encounter a fully qualified path with RTN generics, then it must have
3211            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3212            // it's certainly in an illegal position.
3213            hir::TyKind::Path(hir::QPath::Resolved(_, path))
3214                if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3215                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3216                }) =>
3217            {
3218                let guar = self
3219                    .dcx()
3220                    .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
3221                Ty::new_error(tcx, guar)
3222            }
3223            hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3224                debug!(?maybe_qself, ?path);
3225                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3226                self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3227            }
3228            &hir::TyKind::OpaqueDef(opaque_ty) => {
3229                // If this is an RPITIT and we are using the new RPITIT lowering scheme, we
3230                // generate the def_id of an associated type for the trait and return as
3231                // type a projection.
3232                let in_trait = match opaque_ty.origin {
3233                    hir::OpaqueTyOrigin::FnReturn {
3234                        parent,
3235                        in_trait_or_impl: Some(hir::RpitContext::Trait),
3236                        ..
3237                    }
3238                    | hir::OpaqueTyOrigin::AsyncFn {
3239                        parent,
3240                        in_trait_or_impl: Some(hir::RpitContext::Trait),
3241                        ..
3242                    } => Some(parent),
3243                    hir::OpaqueTyOrigin::FnReturn {
3244                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3245                        ..
3246                    }
3247                    | hir::OpaqueTyOrigin::AsyncFn {
3248                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3249                        ..
3250                    }
3251                    | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3252                };
3253
3254                self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3255            }
3256            hir::TyKind::TraitAscription(hir_bounds) => {
3257                // Impl trait in bindings lower as an infer var with additional
3258                // set of type bounds.
3259                let self_ty = self.ty_infer(None, hir_ty.span);
3260                let mut bounds = Vec::new();
3261                self.lower_bounds(
3262                    self_ty,
3263                    hir_bounds.iter(),
3264                    &mut bounds,
3265                    ty::List::empty(),
3266                    PredicateFilter::All,
3267                    OverlappingAsssocItemConstraints::Allowed,
3268                );
3269                self.add_implicit_sizedness_bounds(
3270                    &mut bounds,
3271                    self_ty,
3272                    hir_bounds,
3273                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3274                    hir_ty.span,
3275                );
3276                self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3277                self_ty
3278            }
3279            // If we encounter a type relative path with RTN generics, then it must have
3280            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3281            // it's certainly in an illegal position.
3282            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3283                if segment.args.is_some_and(|args| {
3284                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3285                }) =>
3286            {
3287                let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3288                    && let None = stmt.init
3289                    && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3290                        hir_self_ty.kind
3291                    && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3292                        self_ty_path.res
3293                    && let Some(_) = tcx
3294                        .inherent_impls(def_id)
3295                        .iter()
3296                        .flat_map(|imp| {
3297                            tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3298                        })
3299                        .filter(|assoc| {
3300                            matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3301                        })
3302                        .next()
3303                {
3304                    // `let x: S::new(valid_in_ty_ctxt);` -> `let x = S::new(valid_in_ty_ctxt);`
3305                    let err = tcx
3306                        .dcx()
3307                        .struct_span_err(
3308                            hir_ty.span,
3309                            "expected type, found associated function call",
3310                        )
3311                        .with_span_suggestion_verbose(
3312                            stmt.pat.span.between(hir_ty.span),
3313                            "use `=` if you meant to assign",
3314                            " = ".to_string(),
3315                            Applicability::MaybeIncorrect,
3316                        );
3317                    self.dcx().try_steal_replace_and_emit_err(
3318                        hir_ty.span,
3319                        StashKey::ReturnTypeNotation,
3320                        err,
3321                    )
3322                } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3323                    && let None = stmt.init
3324                    && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3325                        hir_self_ty.kind
3326                    && let Res::PrimTy(_) = self_ty_path.res
3327                    && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3328                {
3329                    // `let x: i32::something(valid_in_ty_ctxt);` -> `let x = i32::something(valid_in_ty_ctxt);`
3330                    // FIXME: Check that `something` is a valid function in `i32`.
3331                    let err = tcx
3332                        .dcx()
3333                        .struct_span_err(
3334                            hir_ty.span,
3335                            "expected type, found associated function call",
3336                        )
3337                        .with_span_suggestion_verbose(
3338                            stmt.pat.span.between(hir_ty.span),
3339                            "use `=` if you meant to assign",
3340                            " = ".to_string(),
3341                            Applicability::MaybeIncorrect,
3342                        );
3343                    self.dcx().try_steal_replace_and_emit_err(
3344                        hir_ty.span,
3345                        StashKey::ReturnTypeNotation,
3346                        err,
3347                    )
3348                } else {
3349                    let suggestion = if self
3350                        .dcx()
3351                        .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3352                    {
3353                        // We already created a diagnostic complaining that `foo(bar)` is wrong and
3354                        // should have been `foo(..)`. Instead, emit only the current error and
3355                        // include that prior suggestion. Changes are that the problems go further,
3356                        // but keep the suggestion just in case. Either way, we want a single error
3357                        // instead of two.
3358                        Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3359                    } else {
3360                        None
3361                    };
3362                    let err = self
3363                        .dcx()
3364                        .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3365                    self.dcx().try_steal_replace_and_emit_err(
3366                        hir_ty.span,
3367                        StashKey::ReturnTypeNotation,
3368                        err,
3369                    )
3370                };
3371                Ty::new_error(tcx, guar)
3372            }
3373            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3374                debug!(?hir_self_ty, ?segment);
3375                let self_ty = self.lower_ty(hir_self_ty);
3376                self.lower_type_relative_ty_path(
3377                    self_ty,
3378                    hir_self_ty,
3379                    segment,
3380                    hir_ty.hir_id,
3381                    hir_ty.span,
3382                    PermitVariants::No,
3383                )
3384                .map(|(ty, _, _)| ty)
3385                .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3386            }
3387            hir::TyKind::Array(ty, length) => {
3388                let length = self.lower_const_arg(length, tcx.types.usize);
3389                Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3390            }
3391            hir::TyKind::Infer(()) => {
3392                // Infer also appears as the type of arguments or return
3393                // values in an ExprKind::Closure, or as
3394                // the type of local variables. Both of these cases are
3395                // handled specially and will not descend into this routine.
3396                self.ty_infer(None, hir_ty.span)
3397            }
3398            hir::TyKind::Pat(ty, pat) => {
3399                let ty_span = ty.span;
3400                let ty = self.lower_ty(ty);
3401                let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3402                    Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3403                    Err(guar) => Ty::new_error(tcx, guar),
3404                };
3405                self.record_ty(pat.hir_id, ty, pat.span);
3406                pat_ty
3407            }
3408            hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3409                self.lower_ty(ty),
3410                self.item_def_id(),
3411                ty.span,
3412                hir_ty.hir_id,
3413                *variant,
3414                *field,
3415            ),
3416            hir::TyKind::View(ty, fields) => {
3417                self.lower_view(self.lower_ty(ty), fields, hir_ty.span)
3418            }
3419
3420            hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3421        };
3422
3423        self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3424        result_ty
3425    }
3426
3427    fn lower_pat_ty_pat(
3428        &self,
3429        ty: Ty<'tcx>,
3430        ty_span: Span,
3431        pat: &hir::TyPat<'_>,
3432    ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3433        let tcx = self.tcx();
3434        match pat.kind {
3435            hir::TyPatKind::Range(start, end) => {
3436                match ty.kind() {
3437                    // Keep this list of types in sync with the list of types that
3438                    // the `RangePattern` trait is implemented for.
3439                    ty::Int(_) | ty::Uint(_) | ty::Char => {
3440                        let start = self.lower_const_arg(start, ty);
3441                        let end = self.lower_const_arg(end, ty);
3442                        Ok(ty::PatternKind::Range { start, end })
3443                    }
3444                    _ => Err(self
3445                        .dcx()
3446                        .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3447                }
3448            }
3449            hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3450            hir::TyPatKind::Or(patterns) => {
3451                self.tcx()
3452                    .mk_patterns_from_iter(patterns.iter().map(|pat| {
3453                        self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3454                    }))
3455                    .map(ty::PatternKind::Or)
3456            }
3457            hir::TyPatKind::Err(e) => Err(e),
3458        }
3459    }
3460
3461    fn lower_field_of(
3462        &self,
3463        ty: Ty<'tcx>,
3464        item_def_id: LocalDefId,
3465        ty_span: Span,
3466        hir_id: HirId,
3467        variant: Option<Ident>,
3468        field: Ident,
3469    ) -> Ty<'tcx> {
3470        let dcx = self.dcx();
3471        let tcx = self.tcx();
3472        match ty.kind() {
3473            ty::Adt(def, _) => {
3474                let base_did = def.did();
3475                let kind_name = tcx.def_descr(base_did);
3476                let (variant_idx, variant) = if def.is_enum() {
3477                    let Some(variant) = variant else {
3478                        let err = dcx
3479                            .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3480                            .with_span_help(
3481                                field.span.shrink_to_lo(),
3482                                "you might be missing a variant here: `Variant.`",
3483                            )
3484                            .emit();
3485                        return Ty::new_error(tcx, err);
3486                    };
3487
3488                    if let Some(res) = def
3489                        .variants()
3490                        .iter_enumerated()
3491                        .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3492                    {
3493                        res
3494                    } else {
3495                        let err = dcx
3496                            .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3497                            .emit();
3498                        return Ty::new_error(tcx, err);
3499                    }
3500                } else {
3501                    if let Some(variant) = variant {
3502                        let adt_path = tcx.def_path_str(base_did);
3503                        {
    dcx.struct_span_err(variant.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}` does not have any variants",
                            kind_name, adt_path))
                })).with_code(E0609)
}struct_span_code_err!(
3504                            dcx,
3505                            variant.span,
3506                            E0609,
3507                            "{kind_name} `{adt_path}` does not have any variants",
3508                        )
3509                        .with_span_label(variant.span, "variant unknown")
3510                        .emit();
3511                    }
3512                    (FIRST_VARIANT, def.non_enum_variant())
3513                };
3514                let (ident, def_scope) =
3515                    tcx.adjust_ident_and_get_scope(field, def.did(), item_def_id);
3516                if let Some((field_idx, field)) = variant
3517                    .fields
3518                    .iter_enumerated()
3519                    .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3520                {
3521                    if field.vis.is_accessible_from(def_scope, tcx) {
3522                        tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3523                    } else {
3524                        let adt_path = tcx.def_path_str(base_did);
3525                        {
    dcx.struct_span_err(ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("field `{0}` of {1} `{2}` is private",
                            ident, kind_name, adt_path))
                })).with_code(E0616)
}struct_span_code_err!(
3526                            dcx,
3527                            ident.span,
3528                            E0616,
3529                            "field `{ident}` of {kind_name} `{adt_path}` is private",
3530                        )
3531                        .with_span_label(ident.span, "private field")
3532                        .emit();
3533                    }
3534                    Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3535                } else {
3536                    let err =
3537                        dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3538                    Ty::new_error(tcx, err)
3539                }
3540            }
3541            ty::Tuple(tys) => {
3542                let index = match field.as_str().parse::<usize>() {
3543                    Ok(idx) => idx,
3544                    Err(_) => {
3545                        let err =
3546                            dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3547                        return Ty::new_error(tcx, err);
3548                    }
3549                };
3550                if field.name != sym::integer(index) {
3551                    ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3552                }
3553                if tys.get(index).is_some() {
3554                    Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3555                } else {
3556                    let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3557                    Ty::new_error(tcx, err)
3558                }
3559            }
3560            // FIXME(FRTs): support type aliases
3561            /*
3562            ty::Alias(AliasTyKind::Free, ty) => {
3563                return self.lower_field_of(
3564                    ty,
3565                    item_def_id,
3566                    ty_span,
3567                    hir_id,
3568                    variant,
3569                    field,
3570                );
3571            }*/
3572            ty::Alias(..) => Ty::new_error(
3573                tcx,
3574                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not resolve fields of `{0}`",
                ty))
    })format!("could not resolve fields of `{ty}`")),
3575            ),
3576            ty::Error(err) => Ty::new_error(tcx, *err),
3577            ty::Bool
3578            | ty::Char
3579            | ty::Int(_)
3580            | ty::Uint(_)
3581            | ty::Float(_)
3582            | ty::Foreign(_)
3583            | ty::Str
3584            | ty::RawPtr(_, _)
3585            | ty::Ref(_, _, _)
3586            | ty::FnDef(_, _)
3587            | ty::FnPtr(_, _)
3588            | ty::UnsafeBinder(_)
3589            | ty::Dynamic(_, _)
3590            | ty::Closure(_, _)
3591            | ty::CoroutineClosure(_, _)
3592            | ty::Coroutine(_, _)
3593            | ty::CoroutineWitness(_, _)
3594            | ty::Never
3595            | ty::Param(_)
3596            | ty::Bound(_, _)
3597            | ty::Placeholder(_)
3598            | ty::Slice(..) => Ty::new_error(
3599                tcx,
3600                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}` doesn\'t have fields",
                ty))
    })format!("type `{ty}` doesn't have fields")),
3601            ),
3602            ty::Infer(_) => Ty::new_error(
3603                tcx,
3604                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot use `{0}` in this position",
                ty))
    })format!("cannot use `{ty}` in this position")),
3605            ),
3606            // FIXME(FRTs): support these types?
3607            ty::Array(..) | ty::Pat(..) => Ty::new_error(
3608                tcx,
3609                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}` is not yet supported in `field_of!`",
                ty))
    })format!("type `{ty}` is not yet supported in `field_of!`")),
3610            ),
3611        }
3612    }
3613
3614    /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR.
3615    x;#[instrument(level = "debug", skip(self), ret)]
3616    fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3617        let tcx = self.tcx();
3618
3619        let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3620        debug!(?lifetimes);
3621
3622        // If this is an RPITIT and we are using the new RPITIT lowering scheme,
3623        // do a linear search to map this to the synthetic associated type that
3624        // it will be lowered to.
3625        let def_id = if let Some(parent_def_id) = in_trait {
3626            *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3627                .iter()
3628                .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3629                    Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3630                        opaque_def_id.expect_local() == def_id
3631                    }
3632                    _ => unreachable!(),
3633                })
3634                .unwrap()
3635        } else {
3636            def_id.to_def_id()
3637        };
3638
3639        let generics = tcx.generics_of(def_id);
3640        debug!(?generics);
3641
3642        // We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count`
3643        // since return-position impl trait in trait squashes all of the generics from its source fn
3644        // into its own generics, so the opaque's "own" params isn't always just lifetimes.
3645        let offset = generics.count() - lifetimes.len();
3646
3647        let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3648            if let Some(i) = (param.index as usize).checked_sub(offset) {
3649                let (lifetime, _) = lifetimes[i];
3650                // FIXME(mgca): should we be calling self.check_params_use_if_mcg here too?
3651                self.lower_resolved_lifetime(lifetime).into()
3652            } else {
3653                tcx.mk_param_from_def(param)
3654            }
3655        });
3656        debug!(?args);
3657
3658        if in_trait.is_some() {
3659            Ty::new_projection_from_args(tcx, ty::IsRigid::No, def_id, args)
3660        } else {
3661            Ty::new_opaque(tcx, ty::IsRigid::No, def_id, args)
3662        }
3663    }
3664
3665    /// Lower a function type from the HIR to our internal notion of a function signature.
3666    x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3667    pub fn lower_fn_ty(
3668        &self,
3669        hir_id: HirId,
3670        safety: hir::Safety,
3671        abi: rustc_abi::ExternAbi,
3672        decl: &hir::FnDecl<'_>,
3673        generics: Option<&hir::Generics<'_>>,
3674        hir_ty: Option<&hir::Ty<'_>>,
3675    ) -> ty::PolyFnSig<'tcx> {
3676        let tcx = self.tcx();
3677        let bound_vars = tcx.late_bound_vars(hir_id);
3678        debug!(?bound_vars);
3679
3680        let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3681
3682        debug!(?output_ty);
3683
3684        debug!(?abi, ?safety, ?decl.fn_decl_kind, input_tys_len = ?input_tys.len());
3685        let fn_sig_kind = FnSigKind::default()
3686            .set_abi(abi)
3687            .set_safety(safety)
3688            .set_c_variadic(decl.fn_decl_kind.c_variadic())
3689            .set_splatted(decl.splatted(), input_tys.len())
3690            .unwrap();
3691        let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, fn_sig_kind);
3692        let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3693
3694        if let Some(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) = hir_ty {
3695            check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3696        }
3697
3698        // reject function types that violate cmse ABI requirements
3699        cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3700
3701        if !fn_ptr_ty.references_error() {
3702            // Find any late-bound regions declared in return type that do
3703            // not appear in the arguments. These are not well-formed.
3704            //
3705            // Example:
3706            //     for<'a> fn() -> &'a str <-- 'a is bad
3707            //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3708            let inputs = fn_ptr_ty.inputs();
3709            let late_bound_in_args =
3710                tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3711            let output = fn_ptr_ty.output();
3712            let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3713
3714            self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3715                struct_span_code_err!(
3716                    self.dcx(),
3717                    decl.output.span(),
3718                    E0581,
3719                    "return type references {}, which is not constrained by the fn input types",
3720                    br_name
3721                )
3722            });
3723        }
3724
3725        fn_ptr_ty
3726    }
3727
3728    /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3729    /// corresponding function in the trait that the impl implements, if it exists.
3730    /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3731    /// corresponds to the return type.
3732    pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3733        &self,
3734        fn_hir_id: HirId,
3735        arg_idx: Option<usize>,
3736    ) -> Option<Ty<'tcx>> {
3737        let tcx = self.tcx();
3738        let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3739            tcx.hir_node(fn_hir_id)
3740        else {
3741            return None;
3742        };
3743        let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3744
3745        let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3746
3747        let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3748            tcx,
3749            *ident,
3750            ty::AssocTag::Fn,
3751            trait_ref.def_id,
3752        )?;
3753
3754        let fn_sig = tcx
3755            .fn_sig(assoc.def_id)
3756            .instantiate(
3757                tcx,
3758                trait_ref
3759                    .args
3760                    .extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3761            )
3762            .skip_norm_wip();
3763        let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3764
3765        Some(if let Some(arg_idx) = arg_idx {
3766            *fn_sig.inputs().get(arg_idx)?
3767        } else {
3768            fn_sig.output()
3769        })
3770    }
3771
3772    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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("validate_late_bound_regions",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3772u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constrained_regions")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constrained_regions");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("referenced_regions")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("referenced_regions");
                                                        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::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::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(&constrained_regions)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&referenced_regions)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            for br in referenced_regions.difference(&constrained_regions) {
                let br_name =
                    if let Some(name) = br.get_name(self.tcx()) {
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("lifetime `{0}`", name))
                            })
                    } else { "an anonymous lifetime".to_string() };
                let mut err = generate_err(&br_name);
                if !br.is_named(self.tcx()) {
                    err.note("lifetimes appearing in an associated or opaque type are not considered constrained");
                    err.note("consider introducing a named lifetime parameter");
                }
                err.emit();
            }
        }
    }
}#[instrument(level = "trace", skip(self, generate_err))]
3773    fn validate_late_bound_regions<'cx>(
3774        &'cx self,
3775        constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3776        referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3777        generate_err: impl Fn(&str) -> Diag<'cx>,
3778    ) {
3779        for br in referenced_regions.difference(&constrained_regions) {
3780            let br_name = if let Some(name) = br.get_name(self.tcx()) {
3781                format!("lifetime `{name}`")
3782            } else {
3783                "an anonymous lifetime".to_string()
3784            };
3785
3786            let mut err = generate_err(&br_name);
3787
3788            if !br.is_named(self.tcx()) {
3789                // The only way for an anonymous lifetime to wind up
3790                // in the return type but **also** be unconstrained is
3791                // if it only appears in "associated types" in the
3792                // input. See #47511 and #62200 for examples. In this case,
3793                // though we can easily give a hint that ought to be
3794                // relevant.
3795                err.note(
3796                    "lifetimes appearing in an associated or opaque type are not considered constrained",
3797                );
3798                err.note("consider introducing a named lifetime parameter");
3799            }
3800
3801            err.emit();
3802        }
3803    }
3804
3805    fn construct_const_ctor_value(
3806        &self,
3807        ctor_def_id: DefId,
3808        ctor_of: CtorOf,
3809        args: GenericArgsRef<'tcx>,
3810    ) -> Const<'tcx> {
3811        let tcx = self.tcx();
3812        let parent_did = tcx.parent(ctor_def_id);
3813
3814        let adt_def = tcx.adt_def(match ctor_of {
3815            CtorOf::Variant => tcx.parent(parent_did),
3816            CtorOf::Struct => parent_did,
3817        });
3818
3819        let variant_idx = adt_def.variant_index_with_id(parent_did);
3820
3821        let valtree = if adt_def.is_enum() {
3822            let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3823            ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3824        } else {
3825            ty::ValTree::zst(tcx)
3826        };
3827
3828        let adt_ty = Ty::new_adt(tcx, adt_def, args);
3829        ty::Const::new_value(tcx, valtree, adt_ty)
3830    }
3831
3832    fn lower_view(&self, inner_ty: Ty<'tcx>, fields: &[Ident], ty_span: Span) -> Ty<'tcx> {
3833        // Step 1: check that every field is unique, and keep a list of field that we know are
3834        // unique.
3835        let mut viewed_fields = Vec::<Ident>::with_capacity(fields.len());
3836
3837        for f in fields {
3838            let f = f.normalize_to_macros_2_0();
3839            // PERF: this is quadratic, but ~fine since the amount of fields is very low.
3840            if let Some(previous_field_span) =
3841                viewed_fields.iter().find_map(|f_| (*f_ == f).then_some(f_.span))
3842            {
3843                self.dcx().emit_err(diagnostics::ViewedFieldIsAlreadyPartOfTheView {
3844                    name: f.name,
3845                    span: f.span,
3846                    previous_field_span,
3847                });
3848                continue;
3849            }
3850            viewed_fields.push(f);
3851        }
3852
3853        // Step 2: check that the viewed type is a struct.
3854        let variant = match inner_ty.kind() {
3855            ty::Adt(def, _) if def.is_struct() => def.non_enum_variant(),
3856
3857            ty::Adt(def, _) => {
3858                let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedAdt {
3859                    ty: inner_ty,
3860                    span: ty_span,
3861                    article: def.article(),
3862                    kind: def.descr(),
3863                });
3864                return Ty::new_error(self.tcx(), guar);
3865            }
3866
3867            _ => {
3868                let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedNonAdt {
3869                    ty: inner_ty,
3870                    span: ty_span,
3871                });
3872                return Ty::new_error(self.tcx(), guar);
3873            }
3874        };
3875
3876        // Step 3: check that every viewed field exists.
3877        let mut viewed_indices = Vec::with_capacity(viewed_fields.len());
3878        let mut error = None;
3879        for field in viewed_fields {
3880            let Some((_, field)) = variant
3881                .fields
3882                .iter_enumerated()
3883                .find(|(_, f)| f.ident(self.tcx()).normalize_to_macros_2_0() == field)
3884            else {
3885                let err =
3886                    self.dcx().emit_err(NoFieldOnType { span: field.span, field, ty: inner_ty });
3887                error = Some(err);
3888                continue;
3889            };
3890
3891            viewed_indices.push(field);
3892        }
3893        if let Some(guar) = error {
3894            return Ty::new_error(self.tcx(), guar);
3895        }
3896
3897        // FIXME(scrabsha): actually lower view types.
3898        inner_ty
3899    }
3900}