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