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