Skip to main content

hir_ty/
lower.rs

1//! Methods for lowering the HIR to types. There are two main cases here:
2//!
3//!  - Lowering a type reference like `&usize` or `Option<foo::bar::Baz>` to a
4//!    type: The entry point for this is `TyLoweringContext::lower_ty`.
5//!  - Building the type for an item: This happens through the `ty` query.
6//!
7//! This usually involves resolving names, collecting generic arguments etc.
8pub(crate) mod diagnostics;
9pub(crate) mod path;
10
11use std::{cell::OnceCell, iter, mem, ops::Deref, sync::OnceLock};
12
13use either::Either;
14use hir_def::{
15    AdtId, AssocItemId, CallableDefId, ConstId, ConstParamId, EnumId, EnumVariantId,
16    ExpressionStoreOwnerId, FunctionId, GenericDefId, GenericParamId, HasModule, ImplId,
17    ItemContainerId, LifetimeParamId, LocalFieldId, Lookup, StaticId, StructId, TraitId,
18    TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId, VariantId,
19    builtin_type::BuiltinType,
20    expr_store::{ExpressionStore, path::Path},
21    hir::{
22        ExprId, PatId,
23        generics::{
24            GenericParamDataRef, GenericParams, LocalTypeOrConstParamId, TypeOrConstParamData,
25            TypeParamProvenance, WherePredicate,
26        },
27    },
28    item_tree::FieldsShape,
29    lang_item::LangItems,
30    resolver::{HasResolver, LifetimeNs, Resolver, TypeNs},
31    signatures::{
32        ConstSignature, FunctionSignature, ImplSignature, StaticSignature, StructSignature,
33        TraitFlags, TraitSignature, TypeAliasFlags, TypeAliasSignature,
34    },
35    type_ref::{
36        ConstRef, FnType, LifetimeRef, LifetimeRefId, PathId, TraitBoundModifier,
37        TraitRef as HirTraitRef, TypeBound, TypeRef, TypeRefId,
38    },
39};
40use hir_expand::name::Name;
41use la_arena::ArenaMap;
42use path::{PathDiagnosticCallback, PathLoweringContext};
43use rustc_abi::ExternAbi;
44use rustc_ast_ir::Mutability;
45use rustc_hash::FxHashSet;
46use rustc_type_ir::{
47    AliasTyKind, BoundRegion, BoundRegionKind, BoundTyKind, BoundVar, BoundVarIndexKind,
48    DebruijnIndex, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig,
49    Interner, OutlivesPredicate, TermKind, TyKind, TypeFoldable, TypeFolder, TypeSuperFoldable,
50    TypeVisitableExt, Upcast, UpcastFrom, elaborate,
51    inherent::{
52        Clause as _, GenericArg as _, GenericArgs as _, IntoKind as _, Region as _, Ty as _,
53    },
54    shift_vars,
55};
56use salsa::SalsaValue;
57use smallvec::SmallVec;
58use stdx::{impl_from, never};
59use thin_vec::ThinVec;
60use tracing::debug;
61
62pub use hir_def::LoweringMode;
63pub(crate) use hir_def::TrackedStructToken;
64
65use crate::{
66    ImplTraitId, Span, TyLoweringDiagnostic,
67    consteval::{create_anon_const, path_to_const},
68    db::{AnonConstId, GeneralConstId, HirDatabase, InternedOpaqueTyId},
69    generics::{Generics, SingleGenerics, generics},
70    infer::unify::InferenceTable,
71    next_solver::{
72        AliasTy, Binder, BoundConst, BoundExistentialPredicates, BoundTy, BoundVarKinds,
73        BoundVariableKind, Clause, ClauseKind, Clauses, Const, ConstKind, DbInterner, DefaultAny,
74        EarlyBinder, EarlyParamRegion, ErrorGuaranteed, FnSigKind, FxIndexMap, GenericArg,
75        GenericArgKind, GenericArgs, ParamConst, ParamEnv, PatList, Pattern, PolyFnSig, Predicate,
76        Region, RegionKind, StoredClauses, StoredConst, StoredEarlyBinder, StoredGenericArg,
77        StoredGenericArgs, StoredPolyFnSig, StoredTraitRef, StoredTy, TraitPredicate, TraitRef, Ty,
78        Tys, Unnormalized, abi::Safety, default_types, mk_param, util::BottomUpFolder,
79    },
80};
81
82pub(crate) struct PathDiagnosticCallbackData(pub(crate) TypeRefId);
83
84#[derive(PartialEq, Eq, Debug, Hash, SalsaValue)]
85pub struct WithDefinedOpaques<T> {
86    value: T,
87    impl_traits: ThinVec<SelfAndAssocBounds>,
88}
89
90pub enum ImplTrait {}
91
92pub type ImplTraitIdx = la_arena::Idx<ImplTrait>;
93
94#[derive(PartialEq, Eq, Debug, Hash, SalsaValue)]
95pub struct SelfAndAssocBounds {
96    bounds: StoredEarlyBinder<StoredClauses>,
97    assoc_ty_bounds_start: u32,
98}
99
100impl SelfAndAssocBounds {
101    #[inline]
102    pub fn all_bounds(&self) -> EarlyBinder<'_, &[Clause<'_>]> {
103        self.bounds.get().map_bound(|it| it.as_slice())
104    }
105
106    #[inline]
107    pub fn self_bounds(&self) -> EarlyBinder<'_, &[Clause<'_>]> {
108        self.bounds.get().map_bound(|it| &it.as_slice()[..self.assoc_ty_bounds_start as usize])
109    }
110}
111
112#[derive(Debug, Default)]
113struct ImplTraitLoweringState {
114    /// When turning `impl Trait` into opaque types, we have to collect the
115    /// bounds at the same time to get the IDs correct (without becoming too
116    /// complicated).
117    mode: ImplTraitLoweringMode,
118    // This is structured as a struct with fields and not as an enum because it helps with the borrow checker.
119    opaque_type_data: ThinVec<SelfAndAssocBounds>,
120}
121
122impl ImplTraitLoweringState {
123    fn new(mode: ImplTraitLoweringMode) -> ImplTraitLoweringState {
124        Self { mode, opaque_type_data: ThinVec::new() }
125    }
126}
127
128#[derive(Debug, Clone, Copy)]
129pub enum LifetimeElisionKind<'db> {
130    /// Create a new anonymous lifetime parameter and reference it.
131    ///
132    /// If `report_in_path`, report an error when encountering lifetime elision in a path:
133    /// ```compile_fail
134    /// struct Foo<'a> { x: &'a () }
135    /// async fn foo(x: Foo) {}
136    /// ```
137    ///
138    /// Note: the error should not trigger when the elided lifetime is in a pattern or
139    /// expression-position path:
140    /// ```
141    /// struct Foo<'a> { x: &'a () }
142    /// async fn foo(Foo { x: _ }: Foo<'_>) {}
143    /// ```
144    AnonymousCreateParameter { report_in_path: bool },
145
146    /// Replace all anonymous lifetimes by provided lifetime.
147    Elided(Region<'db>),
148
149    /// Give a hard error when either `&` or `'_` is written. Used to
150    /// rule out things like `where T: Foo<'_>`. Does not imply an
151    /// error on default object bounds (e.g., `Box<dyn Foo>`).
152    AnonymousReportError,
153
154    /// Resolves elided lifetimes to `'static` if there are no other lifetimes in scope,
155    /// otherwise give a warning that the previous behavior of introducing a new early-bound
156    /// lifetime is a bug and will be removed (if `only_lint` is enabled).
157    StaticIfNoLifetimeInScope { only_lint: bool },
158
159    /// Signal we cannot find which should be the anonymous lifetime.
160    ElisionFailure,
161
162    /// Infer all elided lifetimes.
163    Infer,
164}
165
166impl<'db> LifetimeElisionKind<'db> {
167    #[inline]
168    pub(crate) fn for_const(
169        interner: DbInterner<'db>,
170        const_parent: ItemContainerId,
171    ) -> LifetimeElisionKind<'db> {
172        match const_parent {
173            ItemContainerId::ExternBlockId(_) | ItemContainerId::ModuleId(_) => {
174                LifetimeElisionKind::Elided(Region::new_static(interner))
175            }
176            ItemContainerId::ImplId(_) => {
177                LifetimeElisionKind::StaticIfNoLifetimeInScope { only_lint: true }
178            }
179            ItemContainerId::TraitId(_) => {
180                LifetimeElisionKind::StaticIfNoLifetimeInScope { only_lint: false }
181            }
182        }
183    }
184
185    #[inline]
186    pub(crate) fn for_fn_params(data: &FunctionSignature) -> LifetimeElisionKind<'db> {
187        LifetimeElisionKind::AnonymousCreateParameter { report_in_path: data.is_async() }
188    }
189
190    #[inline]
191    pub(crate) fn for_fn_ret(interner: DbInterner<'db>) -> LifetimeElisionKind<'db> {
192        // FIXME: We should use the elided lifetime here, or `ElisionFailure`.
193        LifetimeElisionKind::Elided(Region::error(interner))
194    }
195}
196
197#[derive(Clone, Copy, PartialEq, Debug)]
198pub(crate) enum GenericPredicateSource {
199    SelfOnly,
200    AssocTyBound,
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub(crate) enum ForbidParamsAfterReason {
205    /// When lowering generic param defaults, you cannot refer to any param after
206    /// the currently lowered param, including the current param.
207    LoweringParamDefault,
208    /// Most anon const (except array repeat expressions) cannot refer to any generic
209    /// param.
210    AnonConst,
211    /// The type of a const param cannot refer to a type param.
212    ConstParamTy,
213}
214
215pub trait TyLoweringInferVarsCtx<'db> {
216    fn next_ty_var(&mut self, span: Span) -> Ty<'db>;
217    fn next_const_var(&mut self, span: Span) -> Const<'db>;
218    fn next_region_var(&mut self, span: Span) -> Region<'db>;
219
220    #[expect(private_interfaces)]
221    fn as_table(&mut self) -> Option<&mut InferenceTable<'db>> {
222        None
223    }
224}
225
226pub struct TyLoweringContext<'db, 'a> {
227    pub db: &'db dyn HirDatabase,
228    pub(crate) interner: DbInterner<'db>,
229    types: &'db crate::next_solver::DefaultAny<'db>,
230    lang_items: &'db LangItems,
231    resolver: &'a Resolver<'db>,
232    store: &'db ExpressionStore,
233    def: ExpressionStoreOwnerId,
234    generic_def: GenericDefId,
235    generics: &'a OnceCell<Generics<'db>>,
236    in_binders: DebruijnIndex,
237    impl_trait_mode: ImplTraitLoweringState,
238    interning_mode: LoweringMode,
239    /// Tracks types with explicit `?Sized` bounds.
240    pub(crate) unsized_types: FxHashSet<Ty<'db>>,
241    pub(crate) diagnostics: ThinVec<TyLoweringDiagnostic>,
242    lifetime_elision: LifetimeElisionKind<'db>,
243    forbid_params_after: Option<u32>,
244    forbid_params_after_reason: ForbidParamsAfterReason,
245    pub(crate) defined_anon_consts: ThinVec<AnonConstId<'db>>,
246    infer_vars: Option<&'a mut dyn TyLoweringInferVarsCtx<'db>>,
247    is_lowering_impl_trait_bounds: bool,
248    bound_vars: Vec<(Vec<Name>, BoundVarKinds<'db>)>,
249    lifetime_lowering_mode: LifetimeLoweringMode,
250}
251
252impl<'db, 'a> TyLoweringContext<'db, 'a> {
253    pub fn new(
254        db: &'db dyn HirDatabase,
255        resolver: &'a Resolver<'db>,
256        store: &'db ExpressionStore,
257        def: ExpressionStoreOwnerId,
258        generic_def: GenericDefId,
259        generics: &'a OnceCell<Generics<'db>>,
260        lifetime_elision: LifetimeElisionKind<'db>,
261        lifetime_lowering_mode: LifetimeLoweringMode,
262    ) -> Self {
263        let impl_trait_mode = ImplTraitLoweringState::new(ImplTraitLoweringMode::Disallowed);
264        let in_binders = DebruijnIndex::ZERO;
265        let interner = DbInterner::new_with(db, resolver.krate());
266        let bound_vars =
267            vec![(Vec::new(), TyLoweringContext::bound_vars(db, generic_def, generics))];
268        Self {
269            db,
270            // Can provide no block since we don't use it for trait solving.
271            interner,
272            types: crate::next_solver::default_types(),
273            lang_items: interner.lang_items(),
274            resolver,
275            def,
276            generic_def,
277            generics,
278            store,
279            in_binders,
280            impl_trait_mode,
281            interning_mode: LoweringMode::Analysis,
282            unsized_types: FxHashSet::default(),
283            diagnostics: ThinVec::new(),
284            lifetime_elision,
285            forbid_params_after: None,
286            forbid_params_after_reason: ForbidParamsAfterReason::AnonConst,
287            defined_anon_consts: ThinVec::new(),
288            infer_vars: None,
289            is_lowering_impl_trait_bounds: false,
290            bound_vars,
291            lifetime_lowering_mode,
292        }
293    }
294
295    pub(crate) fn set_lifetime_elision(&mut self, lifetime_elision: LifetimeElisionKind<'db>) {
296        self.lifetime_elision = lifetime_elision;
297    }
298
299    pub(crate) fn set_owner(&mut self, owner: &'a SingleGenerics<'db>) {
300        self.store = owner.store();
301        self.def = ExpressionStoreOwnerId::Signature(owner.def());
302    }
303
304    pub fn with_interning_mode(mut self, interning_mode: LoweringMode) -> Self {
305        self.interning_mode = interning_mode;
306        self
307    }
308
309    pub(crate) fn with_debruijn<T>(
310        &mut self,
311        debruijn: DebruijnIndex,
312        f: impl FnOnce(&mut TyLoweringContext<'db, '_>) -> T,
313    ) -> T {
314        let old_debruijn = mem::replace(&mut self.in_binders, debruijn);
315        let result = f(self);
316        self.in_binders = old_debruijn;
317        result
318    }
319
320    pub(crate) fn with_shifted_in<T>(
321        &mut self,
322        binder: &[Name],
323        f: impl FnOnce(&mut TyLoweringContext<'db, '_>) -> T,
324    ) -> (T, BoundVarKinds<'db>) {
325        self.push_bound_vars(binder);
326        let res = self.with_debruijn(self.in_binders.shifted_in(1), f);
327        let bound_vars = self.pop_bound_vars();
328        (res, bound_vars)
329    }
330
331    pub(crate) fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
332        Self { impl_trait_mode: ImplTraitLoweringState::new(impl_trait_mode), ..self }
333    }
334
335    pub(crate) fn forbid_params_after(&mut self, index: u32, reason: ForbidParamsAfterReason) {
336        self.forbid_params_after = Some(index);
337        self.forbid_params_after_reason = reason;
338    }
339
340    pub fn with_infer_vars_behavior(
341        mut self,
342        behavior: Option<&'a mut dyn TyLoweringInferVarsCtx<'db>>,
343    ) -> Self {
344        self.infer_vars = behavior;
345        self
346    }
347
348    pub(crate) fn push_diagnostic(&mut self, diagnostic: TyLoweringDiagnostic) {
349        self.diagnostics.push(diagnostic);
350    }
351
352    fn push_infer_vars_not_allowed(&mut self, span: Span) {
353        if !span.is_dummy() {
354            self.push_diagnostic(TyLoweringDiagnostic::InferVarsNotAllowed { source: span });
355        }
356    }
357
358    #[track_caller]
359    pub(crate) fn expect_table(&mut self) -> &mut InferenceTable<'db> {
360        self.infer_vars.as_mut().unwrap().as_table().unwrap()
361    }
362
363    fn next_ty_var(&mut self, span: Span) -> Ty<'db> {
364        match &mut self.infer_vars {
365            Some(infer_vars) => infer_vars.next_ty_var(span),
366            None => {
367                self.push_infer_vars_not_allowed(span);
368                self.types.types.error
369            }
370        }
371    }
372
373    fn next_const_var(&mut self, span: Span) -> Const<'db> {
374        match &mut self.infer_vars {
375            Some(infer_vars) => infer_vars.next_const_var(span),
376            None => {
377                self.push_infer_vars_not_allowed(span);
378                self.types.consts.error
379            }
380        }
381    }
382
383    fn next_region_var(&mut self, span: Span) -> Region<'db> {
384        match &mut self.infer_vars {
385            Some(infer_vars) => infer_vars.next_region_var(span),
386            None => {
387                self.push_infer_vars_not_allowed(span);
388                self.types.regions.error
389            }
390        }
391    }
392
393    fn push_bound_vars(&mut self, binder: &[Name]) {
394        let bound_vars =
395            BoundVarKinds::new_from_iter(binder.iter().map(|_| {
396                BoundVariableKind::Region(BoundRegionKind::Named(self.generic_def.into()))
397            }));
398        self.bound_vars.push((binder.to_vec(), bound_vars));
399    }
400
401    fn pop_bound_vars(&mut self) -> BoundVarKinds<'db> {
402        self.bound_vars.pop().unwrap().1
403    }
404
405    fn peek_bound_vars(&self) -> BoundVarKinds<'db> {
406        self.bound_vars.last().unwrap().1
407    }
408
409    fn bound_vars(
410        db: &'db dyn HirDatabase,
411        def: GenericDefId,
412        generic: &'a OnceCell<Generics<'db>>,
413    ) -> BoundVarKinds<'db> {
414        let def_id = def.into();
415
416        let generics = generic.get_or_init(|| generics(db, def));
417        let args = generics.iter_self_late_bound().map(|(_, data)| match data {
418            GenericParamDataRef::TypeParamData(..) => {
419                BoundVariableKind::Ty(BoundTyKind::Param(def_id))
420            }
421            GenericParamDataRef::ConstParamData(..) => BoundVariableKind::Const,
422            GenericParamDataRef::LifetimeParamData(..) => {
423                BoundVariableKind::Region(BoundRegionKind::Named(def_id))
424            }
425        });
426
427        BoundVarKinds::new_from_iter(args)
428    }
429
430    fn take_defined_opaques(&mut self) -> ThinVec<SelfAndAssocBounds> {
431        self.impl_trait_mode.opaque_type_data.shrink_to_fit();
432        mem::take(&mut self.impl_trait_mode.opaque_type_data)
433    }
434}
435
436#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
437pub(crate) enum ImplTraitLoweringMode {
438    /// `impl Trait` gets lowered into an opaque type that doesn't unify with
439    /// anything except itself. This is used in places where values flow 'out',
440    /// i.e. for arguments of the function we're currently checking, and return
441    /// types of functions we're calling.
442    Opaque,
443    /// `impl Trait` is disallowed and will be an error.
444    #[default]
445    Disallowed,
446}
447
448#[derive(Clone, Debug, PartialEq, Eq)]
449pub enum LifetimeLoweringMode {
450    /// Lowers the late bound lifetimes to `ReBound`, used in cases when lowering
451    /// from outside of function.
452    Bound,
453    /// Lowers the late bound lifetimes to `ReLateParam`, used in cases when lowering
454    /// inside the function itself
455    LateParam,
456}
457
458impl<'db, 'a> TyLoweringContext<'db, 'a> {
459    pub fn lower_ty(&mut self, type_ref: TypeRefId) -> Ty<'db> {
460        self.lower_ty_ext(type_ref).0
461    }
462
463    pub(crate) fn lower_const(
464        &mut self,
465        const_ref: ConstRef,
466        const_type: Ty<'db>,
467        allow_anon_const_using_generic_params: bool,
468    ) -> Const<'db> {
469        self.lower_expr_as_const(const_ref.expr, const_type, allow_anon_const_using_generic_params)
470    }
471
472    pub(crate) fn lower_expr_as_const(
473        &mut self,
474        expr_id: ExprId,
475        const_type: Ty<'db>,
476        allow_anon_const_using_generic_params: bool,
477    ) -> Const<'db> {
478        #[expect(clippy::manual_map, reason = "a `map()` here generates a borrowck error")]
479        let create_var = match &mut self.infer_vars {
480            Some(infer_vars) => Some(
481                (&mut |span| infer_vars.next_const_var(span)) as &mut dyn FnMut(Span) -> Const<'db>,
482            ),
483            None => None,
484        };
485        let konst = create_anon_const(
486            self.interner,
487            self.def,
488            self.store,
489            expr_id,
490            self.resolver,
491            const_type,
492            &|| self.generics.get_or_init(|| generics(self.db, self.generic_def)),
493            create_var,
494            self.interning_mode,
495            self.forbid_params_after,
496            allow_anon_const_using_generic_params,
497        );
498
499        if let Ok(konst) = konst
500            && let ConstKind::Unevaluated(konst) = konst.kind()
501            && let GeneralConstId::AnonConstId(konst) = konst.def.0
502        {
503            self.defined_anon_consts.push(konst);
504        }
505
506        konst.unwrap_or({
507            // FIXME: Report an error.
508            self.types.consts.error
509        })
510    }
511
512    pub(crate) fn lower_path_as_const(&mut self, path: &Path, _const_type: Ty<'db>) -> Const<'db> {
513        path_to_const(self.db, self.resolver, &|| self.generics(), self.forbid_params_after, path)
514            .unwrap_or({
515                // FIXME: Report an error.
516                self.types.consts.error
517            })
518    }
519
520    fn generics(&self) -> &Generics<'db> {
521        self.generics.get_or_init(|| generics(self.db, self.generic_def))
522    }
523
524    fn param_index_is_disallowed(&self, index: u32) -> bool {
525        self.forbid_params_after.is_some_and(|disallow_params_after| index >= disallow_params_after)
526    }
527
528    fn type_param(&mut self, id: TypeParamId, index: u32) -> Ty<'db> {
529        if self.param_index_is_disallowed(index) {
530            // FIXME: Report an error.
531            self.types.types.error
532        } else {
533            Ty::new_param(self.interner, id, index)
534        }
535    }
536
537    fn region_param(
538        &mut self,
539        id: LifetimeParamId,
540        index: u32,
541        is_late_bound: bool,
542    ) -> Region<'db> {
543        if self.param_index_is_disallowed(index) {
544            // FIXME: Report an error.
545            self.types.regions.error
546        } else {
547            if is_late_bound {
548                self.hrtb_region_param(
549                    index,
550                    DebruijnIndex::from_usize(self.in_binders.as_usize()),
551                    id.parent,
552                )
553            } else {
554                Region::new_early_param(self.interner, EarlyParamRegion { id, index })
555            }
556        }
557    }
558
559    fn hrtb_region_param(
560        &self,
561        index: u32,
562        debruijn: DebruijnIndex,
563        parent: GenericDefId,
564    ) -> Region<'db> {
565        if self.param_index_is_disallowed(index) {
566            // FIXME: Report an error.
567            self.types.regions.error
568        } else {
569            if self.lifetime_lowering_mode == LifetimeLoweringMode::Bound {
570                Region::new_bound(
571                    self.interner,
572                    debruijn,
573                    BoundRegion {
574                        var: BoundVar::from_u32(index),
575                        kind: BoundRegionKind::Named(parent.into()),
576                    },
577                )
578            } else {
579                let solver_def_id = parent.into();
580                Region::new_late_param(
581                    self.interner,
582                    solver_def_id,
583                    BoundRegion {
584                        var: BoundVar::from_u32(index),
585                        kind: BoundRegionKind::Named(solver_def_id),
586                    },
587                )
588            }
589        }
590    }
591
592    #[tracing::instrument(skip(self), ret)]
593    pub fn lower_ty_ext(&mut self, type_ref_id: TypeRefId) -> (Ty<'db>, Option<TypeNs>) {
594        let interner = self.interner;
595        let mut res = None;
596        let type_ref = &self.store[type_ref_id];
597        tracing::debug!(?type_ref);
598        let ty = match type_ref {
599            TypeRef::Never => self.types.types.never,
600            TypeRef::Tuple(inner) => {
601                let inner_tys = inner.iter().map(|&tr| self.lower_ty(tr));
602                Ty::new_tup_from_iter(interner, inner_tys)
603            }
604            TypeRef::Path(path) => {
605                let (ty, res_) =
606                    self.lower_path(path, PathId::from_type_ref_unchecked(type_ref_id));
607                res = res_;
608                ty
609            }
610            &TypeRef::TypeParam(type_param_id) => {
611                res = Some(TypeNs::GenericParam(type_param_id));
612
613                let generics = self.generics();
614                let idx = generics.type_or_const_param_idx(type_param_id.into());
615                self.type_param(type_param_id, idx)
616            }
617            &TypeRef::RawPtr(inner, mutability) => {
618                let inner_ty = self.lower_ty(inner);
619                Ty::new(interner, TyKind::RawPtr(inner_ty, lower_mutability(mutability)))
620            }
621            TypeRef::Array(array) => {
622                let inner_ty = self.lower_ty(array.ty);
623                let const_len = self.lower_const(array.len, self.types.types.usize, false);
624                Ty::new_array_with_const_len(interner, inner_ty, const_len)
625            }
626            &TypeRef::Slice(inner) => {
627                let inner_ty = self.lower_ty(inner);
628                Ty::new_slice(interner, inner_ty)
629            }
630            TypeRef::Reference(ref_) => {
631                let inner_ty = self.lower_ty(ref_.ty);
632                // FIXME: It should infer the eldided lifetimes instead of stubbing with error
633                let lifetime =
634                    ref_.lifetime.map_or(self.types.regions.error, |lr| self.lower_lifetime(lr));
635                Ty::new_ref(interner, lifetime, inner_ty, lower_mutability(ref_.mutability))
636            }
637            TypeRef::Placeholder => self.next_ty_var(type_ref_id.into()),
638            TypeRef::Fn(fn_) => self.lower_fn_ptr(fn_),
639            TypeRef::DynTrait(bounds) => self.lower_dyn_trait(bounds),
640            TypeRef::ImplTrait(bounds) => {
641                match self.impl_trait_mode.mode {
642                    ImplTraitLoweringMode::Opaque => {
643                        let origin = match self.resolver.generic_def() {
644                            Some(GenericDefId::FunctionId(it)) => Either::Left(it),
645                            Some(GenericDefId::TypeAliasId(it)) => Either::Right(it),
646                            _ => panic!(
647                                "opaque impl trait lowering must be in function or type alias"
648                            ),
649                        };
650
651                        // this dance is to make sure the data is in the right
652                        // place even if we encounter more opaque types while
653                        // lowering the bounds
654                        let idx = ImplTraitIdx::from_raw(la_arena::RawIdx::from_u32(
655                            self.impl_trait_mode.opaque_type_data.len() as u32,
656                        ));
657                        self.impl_trait_mode.opaque_type_data.push(SelfAndAssocBounds {
658                            bounds: StoredEarlyBinder::bind(Clauses::empty().store()),
659                            assoc_ty_bounds_start: 0,
660                        });
661
662                        let impl_trait_id = origin.either(
663                            |f| ImplTraitId::ReturnTypeImplTrait(f, idx),
664                            |a| ImplTraitId::TypeAliasImplTrait(a, idx),
665                        );
666                        let opaque_ty_id = InternedOpaqueTyId::new(self.db, impl_trait_id);
667
668                        // We don't want to lower the bounds inside the binders
669                        // we're currently in, because they don't end up inside
670                        // those binders. E.g. when we have `impl Trait<impl
671                        // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
672                        // to the self parameter from `impl Trait`, and the
673                        // bounds aren't actually stored nested within each
674                        // other, but separately. So if the `T` refers to a type
675                        // parameter of the outer function, it's just one binder
676                        // away instead of two.
677                        let actual_opaque_type_data = self
678                            .with_debruijn(DebruijnIndex::ZERO, |ctx| {
679                                ctx.lower_impl_trait(opaque_ty_id, bounds)
680                            });
681                        self.impl_trait_mode.opaque_type_data[idx.into_raw().into_u32() as usize] =
682                            actual_opaque_type_data;
683
684                        let mut late_bound_index = 0;
685                        let args = GenericArgs::for_item(
686                            self.interner,
687                            opaque_ty_id.into(),
688                            |index, param_id, lt_param, _| {
689                                if let Some(lt) = lt_param
690                                    && lt.is_late_bound()
691                                    && !self.is_lowering_impl_trait_bounds
692                                {
693                                    let GenericParamId::LifetimeParamId(id) = param_id else {
694                                        unreachable!()
695                                    };
696                                    let bound_region_kind =
697                                        BoundRegionKind::Named(id.parent.into());
698                                    let region = match self.lifetime_lowering_mode {
699                                        LifetimeLoweringMode::Bound => Region::new_bound(
700                                            interner,
701                                            self.in_binders,
702                                            BoundRegion {
703                                                var: BoundVar::from_u32(late_bound_index),
704                                                kind: bound_region_kind,
705                                            },
706                                        ),
707                                        LifetimeLoweringMode::LateParam => Region::new_late_param(
708                                            interner,
709                                            self.generic_def.into(),
710                                            BoundRegion {
711                                                var: BoundVar::from_u32(late_bound_index),
712                                                kind: bound_region_kind,
713                                            },
714                                        ),
715                                    };
716                                    late_bound_index += 1;
717                                    return region.into();
718                                }
719
720                                mk_param(interner, index - late_bound_index, param_id)
721                            },
722                        );
723                        Ty::new_alias(
724                            self.interner,
725                            AliasTy::new_from_args(
726                                self.interner,
727                                AliasTyKind::Opaque { def_id: opaque_ty_id.into() },
728                                args,
729                            ),
730                        )
731                    }
732                    ImplTraitLoweringMode::Disallowed => {
733                        // FIXME: report error
734                        self.types.types.error
735                    }
736                }
737            }
738            &TypeRef::PatternType(ty, pat) => {
739                let ty = self.lower_ty(ty);
740                let Some(pat) = self.lower_pattern_type(pat, ty) else {
741                    return (self.types.types.error, res);
742                };
743                Ty::new_pat(self.interner, ty, pat)
744            }
745            TypeRef::Error => self.types.types.error,
746        };
747        (ty, res)
748    }
749
750    fn lower_pattern_type(&mut self, pat: PatId, ty: Ty<'db>) -> Option<Pattern<'db>> {
751        let pat_kind = match self.store[pat] {
752            hir_def::hir::Pat::Range { start: Some(start), end: Some(end), range_type: _ } => {
753                // rustc allows using generic params in pattern types.
754                // In practice this does not matter since this feature is internal and I didn't find a way to actually use generic params,
755                // but it doesn't matter so...
756                rustc_type_ir::PatternKind::Range {
757                    start: self.lower_expr_as_const(start, ty, true),
758                    end: self.lower_expr_as_const(end, ty, true),
759                }
760            }
761            hir_def::hir::Pat::NotNull => rustc_type_ir::PatternKind::NotNull,
762            hir_def::hir::Pat::Or(ref pats) => rustc_type_ir::PatternKind::Or(
763                PatList::new_from_iter(
764                    pats.iter().map(|&pat| self.lower_pattern_type(pat, ty).ok_or(())),
765                )
766                .ok()?,
767            ),
768            hir_def::hir::Pat::Missing => return None,
769            _ => {
770                never!("pattern type can only be Range, NotNull or Or");
771                return None;
772            }
773        };
774        Some(Pattern::new(self.interner, pat_kind))
775    }
776
777    fn lower_fn_ptr(&mut self, fn_: &FnType) -> Ty<'db> {
778        let interner = self.interner;
779        let (params, ret_ty) = fn_.split_params_and_ret();
780        let old_lifetime_elision = self.lifetime_elision;
781        let mut args = Vec::with_capacity(fn_.params.len());
782        let binder = fn_.binder.as_ref().map(|b| b.as_ref()).unwrap_or_default();
783        let (_, binder) = self.with_shifted_in(binder, |ctx: &mut TyLoweringContext<'_, '_>| {
784            ctx.lifetime_elision =
785                LifetimeElisionKind::AnonymousCreateParameter { report_in_path: false };
786            args.extend(params.iter().map(|&(_, tr)| ctx.lower_ty(tr)));
787            ctx.lifetime_elision = LifetimeElisionKind::for_fn_ret(interner);
788            args.push(ctx.lower_ty(ret_ty));
789        });
790        self.lifetime_elision = old_lifetime_elision;
791
792        Ty::new_fn_ptr(
793            interner,
794            Binder::bind_with_vars(
795                FnSig {
796                    fn_sig_kind: FnSigKind::new(
797                        fn_.abi,
798                        if fn_.is_unsafe { Safety::Unsafe } else { Safety::Safe },
799                        fn_.is_varargs,
800                        // FIXME(splat): handle splatted arguments
801                    ),
802                    inputs_and_output: Tys::new_from_slice(&args),
803                },
804                binder,
805            ),
806        )
807    }
808
809    /// This is only for [`resolve_type_param_assoc_type_shorthand`], where we can't just
810    /// lower the self types of the predicates since that could lead to cycles.
811    /// So we just check here if the `type_ref` resolves to a generic param, and which.
812    fn lower_ty_only_param(&self, type_ref: TypeRefId) -> Option<TypeOrConstParamId> {
813        let type_ref = &self.store[type_ref];
814        let path = match type_ref {
815            TypeRef::Path(path) => path,
816            &TypeRef::TypeParam(idx) => return Some(idx.into()),
817            _ => return None,
818        };
819        if path.type_anchor().is_some() {
820            return None;
821        }
822        if path.segments().len() > 1 {
823            return None;
824        }
825        let resolution = match self.resolver.resolve_path_in_type_ns(self.db, path) {
826            Some((it, None, _)) => it,
827            _ => return None,
828        };
829        match resolution {
830            TypeNs::GenericParam(param_id) => Some(param_id.into()),
831            _ => None,
832        }
833    }
834
835    #[inline]
836    fn on_path_diagnostic_callback<'b>(type_ref: TypeRefId) -> PathDiagnosticCallback<'b, 'db> {
837        PathDiagnosticCallback {
838            data: Either::Left(PathDiagnosticCallbackData(type_ref)),
839            callback: |data, this, diag| {
840                let type_ref = data.as_ref().left().unwrap().0;
841                this.push_diagnostic(TyLoweringDiagnostic::PathDiagnostic {
842                    source: type_ref,
843                    diag,
844                })
845            },
846        }
847    }
848
849    #[inline]
850    fn at_path(&mut self, path_id: PathId) -> PathLoweringContext<'_, 'a, 'db> {
851        PathLoweringContext::new(
852            self,
853            Self::on_path_diagnostic_callback(path_id.type_ref()),
854            &self.store[path_id],
855        )
856    }
857
858    pub(crate) fn lower_path(&mut self, path: &Path, path_id: PathId) -> (Ty<'db>, Option<TypeNs>) {
859        // Resolve the path (in type namespace)
860        if let Some(type_ref) = path.type_anchor() {
861            let (ty, res) = self.lower_ty_ext(type_ref);
862            let mut ctx = self.at_path(path_id);
863            return ctx.lower_ty_relative_path(ty, res, false, path_id.type_ref().into());
864        }
865
866        let mut ctx = self.at_path(path_id);
867        let (resolution, remaining_index) = match ctx.resolve_path_in_type_ns() {
868            Some(it) => it,
869            None => return (self.types.types.error, None),
870        };
871
872        if matches!(resolution, TypeNs::TraitId(_)) && remaining_index.is_none() {
873            // trait object type without dyn
874            let bound = TypeBound::Path(path_id, TraitBoundModifier::None);
875            let ty = self.lower_dyn_trait(&[bound]);
876            return (ty, None);
877        }
878
879        ctx.lower_partly_resolved_path(resolution, false, path_id.type_ref().into())
880    }
881
882    fn lower_trait_ref_from_path(
883        &mut self,
884        path_id: PathId,
885        explicit_self_ty: Ty<'db>,
886    ) -> Option<(TraitRef<'db>, PathLoweringContext<'_, 'a, 'db>)> {
887        let mut ctx = self.at_path(path_id);
888        let resolved = match ctx.resolve_path_in_type_ns_fully()? {
889            // FIXME(trait_alias): We need to handle trait alias here.
890            TypeNs::TraitId(tr) => tr,
891            _ => return None,
892        };
893        Some((
894            ctx.lower_trait_ref_from_resolved_path(
895                resolved,
896                explicit_self_ty,
897                false,
898                path_id.type_ref().into(),
899            ),
900            ctx,
901        ))
902    }
903
904    fn lower_trait_ref(
905        &mut self,
906        trait_ref: HirTraitRef,
907        explicit_self_ty: Ty<'db>,
908    ) -> Option<TraitRef<'db>> {
909        self.lower_trait_ref_from_path(trait_ref.path, explicit_self_ty).map(|it| it.0)
910    }
911
912    pub(crate) fn lower_where_predicate<'b>(
913        &'b mut self,
914        where_predicate: &'b WherePredicate,
915        ignore_bindings: bool,
916    ) -> impl Iterator<Item = (Clause<'db>, GenericPredicateSource)> + use<'a, 'b, 'db> {
917        let lower_type_outlives = |ctx: &mut TyLoweringContext<'db, '_>,
918                                   target: &TypeRefId,
919                                   bound| {
920            let self_ty = ctx.lower_ty(*target);
921            let clause = ctx.lower_type_bound(bound, self_ty, ignore_bindings).collect::<Vec<_>>();
922            Either::Left(clause.into_iter())
923        };
924
925        match where_predicate {
926            WherePredicate::TypeBound { lifetimes, target, bound } => match lifetimes {
927                Some(lifetimes) => {
928                    self.with_shifted_in(lifetimes, |ctx| lower_type_outlives(ctx, target, bound)).0
929                }
930                None => lower_type_outlives(self, target, bound),
931            },
932            &WherePredicate::Lifetime { bound, target } => Either::Right(iter::once((
933                Clause(Predicate::new(
934                    self.interner,
935                    Binder::dummy(rustc_type_ir::PredicateKind::Clause(
936                        rustc_type_ir::ClauseKind::RegionOutlives(OutlivesPredicate(
937                            self.lower_lifetime(bound),
938                            self.lower_lifetime(target),
939                        )),
940                    )),
941                )),
942                GenericPredicateSource::SelfOnly,
943            ))),
944        }
945        .into_iter()
946    }
947
948    pub(crate) fn lower_type_bound<'b>(
949        &'b mut self,
950        bound: &'b TypeBound,
951        self_ty: Ty<'db>,
952        ignore_bindings: bool,
953    ) -> impl Iterator<Item = (Clause<'db>, GenericPredicateSource)> + use<'db> {
954        let interner = self.interner;
955        let meta_sized = self.lang_items.MetaSized;
956        let pointee_sized = self.lang_items.PointeeSized;
957
958        let mut assoc_bounds = None;
959        let mut clause = None;
960
961        let mut lower_path_bound = |ctx: &mut TyLoweringContext<'db, '_>, path| {
962            let binder = ctx.peek_bound_vars();
963
964            if let Some((trait_ref, mut ctx)) = ctx.lower_trait_ref_from_path(path, self_ty) {
965                // FIXME(sized-hierarchy): Remove this bound modifications once we have implemented
966                // sized-hierarchy correctly.
967                if meta_sized.is_some_and(|it| it == trait_ref.def_id.0) {
968                    // Ignore this bound
969                } else if pointee_sized.is_some_and(|it| it == trait_ref.def_id.0) {
970                    // Regard this as `?Sized` bound
971                    ctx.ty_ctx().unsized_types.insert(self_ty);
972                } else {
973                    if !ignore_bindings {
974                        assoc_bounds = ctx
975                            .assoc_type_bindings_from_type_bound(trait_ref, path.type_ref().into())
976                            .map(|iter| iter.collect::<Vec<_>>());
977                    }
978                    clause = Some(Clause(Predicate::new(
979                        interner,
980                        Binder::bind_with_vars(
981                            rustc_type_ir::PredicateKind::Clause(rustc_type_ir::ClauseKind::Trait(
982                                TraitPredicate {
983                                    trait_ref,
984                                    polarity: rustc_type_ir::PredicatePolarity::Positive,
985                                },
986                            )),
987                            binder,
988                        ),
989                    )));
990                }
991            }
992        };
993
994        match bound {
995            &TypeBound::ForLifetime(ref binder, path) => {
996                self.with_shifted_in(binder, |ctx| lower_path_bound(ctx, path)).0
997            }
998            &TypeBound::Path(path, TraitBoundModifier::None) => lower_path_bound(self, path),
999            &TypeBound::Path(path, TraitBoundModifier::Maybe) => {
1000                let sized_trait = self.lang_items.Sized;
1001                // Don't lower associated type bindings as the only possible relaxed trait bound
1002                // `?Sized` has no of them.
1003                // If we got another trait here ignore the bound completely.
1004                let trait_id = self
1005                    .lower_trait_ref_from_path(path, self_ty)
1006                    .map(|(trait_ref, _)| trait_ref.def_id.0);
1007                if trait_id == sized_trait {
1008                    self.unsized_types.insert(self_ty);
1009                }
1010            }
1011            &TypeBound::Lifetime(l) => {
1012                let lifetime = self.lower_lifetime(l);
1013                let binder = self.peek_bound_vars();
1014                clause = Some(Clause(Predicate::new(
1015                    self.interner,
1016                    Binder::bind_with_vars(
1017                        rustc_type_ir::PredicateKind::Clause(
1018                            rustc_type_ir::ClauseKind::TypeOutlives(OutlivesPredicate(
1019                                self_ty, lifetime,
1020                            )),
1021                        ),
1022                        binder,
1023                    ),
1024                )));
1025            }
1026            TypeBound::Use(_) | TypeBound::Error => {}
1027        }
1028        clause
1029            .into_iter()
1030            .map(|pred| (pred, GenericPredicateSource::SelfOnly))
1031            .chain(assoc_bounds.into_iter().flatten())
1032    }
1033
1034    fn lower_dyn_trait(&mut self, bounds: &[TypeBound]) -> Ty<'db> {
1035        let interner = self.interner;
1036        let dummy_self_ty = self.types.types.dyn_trait_dummy_self;
1037        let mut region = None;
1038        // INVARIANT: The principal trait bound, if present, must come first. Others may be in any
1039        // order but should be in the same order for the same set but possibly different order of
1040        // bounds in the input.
1041        // INVARIANT: If this function returns `DynTy`, there should be at least one trait bound.
1042        // These invariants are utilized by `TyExt::dyn_trait()` and chalk.
1043        let bounds = 'bounds: {
1044            let mut principal = None;
1045            let mut auto_traits = SmallVec::<[_; 3]>::new();
1046            let mut projections = Vec::new();
1047            let mut had_error = false;
1048
1049            for b in bounds {
1050                let db = self.db;
1051                match b {
1052                    TypeBound::Path(_, TraitBoundModifier::None) => {
1053                        // `dyn Trait<'a>` is an existential predicate that introduces a binder.
1054                        self.with_shifted_in(&[], |ctx| {
1055                            ctx.lower_type_bound(b, dummy_self_ty, false)
1056                        })
1057                        .0
1058                    }
1059                    _ => self.lower_type_bound(b, dummy_self_ty, false),
1060                }
1061                .for_each(|(b, _)| {
1062                    match b.kind().skip_binder() {
1063                        rustc_type_ir::ClauseKind::Trait(t) => {
1064                            let id = t.def_id();
1065                            let is_auto =
1066                                TraitSignature::of(db, id.0).flags.contains(TraitFlags::AUTO);
1067                            if is_auto {
1068                                auto_traits.push(t.def_id().0);
1069                            } else {
1070                                if principal.is_some() {
1071                                    // FIXME: Report an error.
1072                                    had_error = true;
1073                                }
1074                                principal = Some(b.kind().rebind(t.trait_ref));
1075                            }
1076                        }
1077                        rustc_type_ir::ClauseKind::Projection(p) => {
1078                            projections.push(b.kind().rebind(p));
1079                        }
1080                        rustc_type_ir::ClauseKind::TypeOutlives(outlives_predicate) => {
1081                            if region.is_some() {
1082                                // FIXME: Report an error.
1083                                had_error = true;
1084                            }
1085                            region = Some(outlives_predicate.1);
1086                        }
1087                        rustc_type_ir::ClauseKind::RegionOutlives(_)
1088                        | rustc_type_ir::ClauseKind::ConstArgHasType(_, _)
1089                        | rustc_type_ir::ClauseKind::WellFormed(_)
1090                        | rustc_type_ir::ClauseKind::ConstEvaluatable(_)
1091                        | rustc_type_ir::ClauseKind::HostEffect(_)
1092                        | rustc_type_ir::ClauseKind::UnstableFeature(_) => unreachable!(),
1093                    }
1094                })
1095            }
1096
1097            if had_error {
1098                break 'bounds None;
1099            }
1100
1101            if principal.is_none() && auto_traits.is_empty() {
1102                // No traits is not allowed.
1103                break 'bounds None;
1104            }
1105
1106            // `Send + Sync` is the same as `Sync + Send`.
1107            auto_traits.sort_unstable();
1108            // Duplicate auto traits are permitted.
1109            auto_traits.dedup();
1110
1111            // Map the projection bounds onto a key that makes it easy to remove redundant
1112            // bounds that are constrained by supertraits of the principal def id.
1113            //
1114            // Also make sure we detect conflicting bounds from expanding a trait alias and
1115            // also specifying it manually, like:
1116            // ```
1117            // type Alias = Trait<Assoc = i32>;
1118            // let _: &dyn Alias<Assoc = u32> = /* ... */;
1119            // ```
1120            let mut projection_bounds = FxIndexMap::default();
1121            for proj in projections {
1122                let key = (
1123                    proj.skip_binder().def_id().0,
1124                    interner.anonymize_bound_vars(
1125                        proj.map_bound(|proj| proj.projection_term.trait_ref(interner)),
1126                    ),
1127                );
1128                if let Some(old_proj) = projection_bounds.insert(key, proj)
1129                    && interner.anonymize_bound_vars(proj)
1130                        != interner.anonymize_bound_vars(old_proj)
1131                {
1132                    // FIXME: Report "conflicting associated type" error.
1133                }
1134            }
1135
1136            // A stable ordering of associated types from the principal trait and all its
1137            // supertraits. We use this to ensure that different substitutions of a trait
1138            // don't result in `dyn Trait` types with different projections lists, which
1139            // can be unsound: <https://github.com/rust-lang/rust/pull/136458>.
1140            // We achieve a stable ordering by walking over the unsubstituted principal
1141            // trait ref.
1142            let mut ordered_associated_types = vec![];
1143
1144            if let Some(principal_trait) = principal {
1145                // Generally we should not elaborate in lowering as this can lead to cycles, but
1146                // here rustc cycles as well.
1147                for clause in elaborate::elaborate(
1148                    interner,
1149                    [Clause::upcast_from(
1150                        TraitRef::identity(interner, principal_trait.def_id()),
1151                        interner,
1152                    )],
1153                )
1154                .filter_only_self()
1155                {
1156                    let clause = clause.instantiate_supertrait(interner, principal_trait);
1157                    debug!("observing object predicate `{clause:?}`");
1158
1159                    let bound_predicate = clause.kind();
1160                    match bound_predicate.skip_binder() {
1161                        ClauseKind::Trait(pred) => {
1162                            // FIXME(negative_bounds): Handle this correctly...
1163                            let trait_ref = interner
1164                                .anonymize_bound_vars(bound_predicate.rebind(pred.trait_ref));
1165                            ordered_associated_types.extend(
1166                                pred.trait_ref
1167                                    .def_id
1168                                    .0
1169                                    .trait_items(self.db)
1170                                    .associated_types()
1171                                    .map(|item| (item.into(), trait_ref)),
1172                            );
1173                        }
1174                        ClauseKind::Projection(pred) => {
1175                            let pred = bound_predicate.rebind(pred);
1176                            // A `Self` within the original bound will be instantiated with a
1177                            // `trait_object_dummy_self`, so check for that.
1178                            let references_self = match pred.skip_binder().term.kind() {
1179                                TermKind::Ty(ty) => {
1180                                    ty.walk().any(|arg| arg == dummy_self_ty.into())
1181                                }
1182                                // FIXME(mgca): We should walk the const instead of not doing anything
1183                                TermKind::Const(_) => false,
1184                            };
1185
1186                            // If the projection output contains `Self`, force the user to
1187                            // elaborate it explicitly to avoid a lot of complexity.
1188                            //
1189                            // The "classically useful" case is the following:
1190                            // ```
1191                            //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1192                            //         type MyOutput;
1193                            //     }
1194                            // ```
1195                            //
1196                            // Here, the user could theoretically write `dyn MyTrait<MyOutput = X>`,
1197                            // but actually supporting that would "expand" to an infinitely-long type
1198                            // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1199                            //
1200                            // Instead, we force the user to write
1201                            // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1202                            // the discussion in #56288 for alternatives.
1203                            if !references_self {
1204                                let key = (
1205                                    pred.skip_binder().def_id().0,
1206                                    interner.anonymize_bound_vars(pred.map_bound(|proj| {
1207                                        proj.projection_term.trait_ref(interner)
1208                                    })),
1209                                );
1210                                if !projection_bounds.contains_key(&key) {
1211                                    projection_bounds.insert(key, pred);
1212                                }
1213                            }
1214                        }
1215                        _ => (),
1216                    }
1217                }
1218            }
1219
1220            // We compute the list of projection bounds taking the ordered associated types,
1221            // and check if there was an entry in the collected `projection_bounds`. Those
1222            // are computed by first taking the user-written associated types, then elaborating
1223            // the principal trait ref, and only using those if there was no user-written.
1224            // See note below about how we handle missing associated types with `Self: Sized`,
1225            // which are not required to be provided, but are still used if they are provided.
1226            let mut projection_bounds: Vec<_> = ordered_associated_types
1227                .into_iter()
1228                .filter_map(|key| projection_bounds.get(&key).copied())
1229                .collect();
1230
1231            projection_bounds.sort_unstable_by_key(|proj| proj.skip_binder().def_id().0);
1232
1233            let principal = principal.map(|principal| {
1234                principal.map_bound(|principal| {
1235                    // Verify that `dummy_self` did not leak inside default type parameters.
1236                    let args: Vec<_> = principal
1237                        .args
1238                        .iter()
1239                        // Skip `Self`
1240                        .skip(1)
1241                        .map(|arg| {
1242                            if arg.walk().any(|arg| arg == dummy_self_ty.into()) {
1243                                // FIXME: Report an error.
1244                                self.types.types.error.into()
1245                            } else {
1246                                arg
1247                            }
1248                        })
1249                        .collect();
1250
1251                    ExistentialPredicate::Trait(ExistentialTraitRef::new(
1252                        interner,
1253                        principal.def_id,
1254                        args,
1255                    ))
1256                })
1257            });
1258
1259            let projections = projection_bounds.into_iter().map(|proj| {
1260                proj.map_bound(|mut proj| {
1261                    // Like for trait refs, verify that `dummy_self` did not leak inside default type
1262                    // parameters.
1263                    let references_self = proj.projection_term.args.iter().skip(1).any(|arg| {
1264                        if arg.walk().any(|arg| arg == dummy_self_ty.into()) {
1265                            return true;
1266                        }
1267                        false
1268                    });
1269                    if references_self {
1270                        proj.projection_term = replace_dummy_self_with_error(
1271                            interner,
1272                            self.types,
1273                            proj.projection_term,
1274                        );
1275                    }
1276
1277                    ExistentialPredicate::Projection(ExistentialProjection::erase_self_ty(
1278                        interner, proj,
1279                    ))
1280                })
1281            });
1282
1283            let auto_traits = auto_traits.into_iter().map(|auto_trait| {
1284                Binder::dummy(ExistentialPredicate::AutoTrait(auto_trait.into()))
1285            });
1286
1287            // N.b. principal, projections, auto traits
1288            Some(BoundExistentialPredicates::new_from_iter(
1289                principal.into_iter().chain(projections).chain(auto_traits),
1290            ))
1291        };
1292
1293        if let Some(bounds) = bounds {
1294            let region = match region {
1295                Some(it) => it,
1296                None => Region::new_static(self.interner),
1297            };
1298            Ty::new_dynamic(self.interner, bounds, region)
1299        } else {
1300            // FIXME: report error
1301            // (additional non-auto traits, associated type rebound, or no resolved trait)
1302            self.types.types.error
1303        }
1304    }
1305
1306    fn lower_impl_trait(
1307        &mut self,
1308        def_id: InternedOpaqueTyId<'db>,
1309        bounds: &[TypeBound],
1310    ) -> SelfAndAssocBounds {
1311        let interner = self.interner;
1312        cov_mark::hit!(lower_rpit);
1313        let args = GenericArgs::identity_for_item(interner, def_id.into());
1314        let self_ty = Ty::new_alias(
1315            self.interner,
1316            AliasTy::new_from_args(interner, rustc_type_ir::Opaque { def_id: def_id.into() }, args),
1317        );
1318        let prev_is_lowering_impl_trait_bounds =
1319            mem::replace(&mut self.is_lowering_impl_trait_bounds, true);
1320
1321        let mut predicates = Vec::new();
1322        let mut assoc_ty_bounds = Vec::new();
1323        for b in bounds {
1324            for (pred, source) in self.lower_type_bound(b, self_ty, false) {
1325                match source {
1326                    GenericPredicateSource::SelfOnly => predicates.push(pred),
1327                    GenericPredicateSource::AssocTyBound => assoc_ty_bounds.push(pred),
1328                }
1329            }
1330        }
1331
1332        if !self.unsized_types.contains(&self_ty) {
1333            let sized_trait = self.lang_items.Sized;
1334            let sized_clause = sized_trait.map(|trait_id| {
1335                let trait_ref = TraitRef::new_from_args(
1336                    interner,
1337                    trait_id.into(),
1338                    GenericArgs::new_from_slice(&[self_ty.into()]),
1339                );
1340                Clause(Predicate::new(
1341                    interner,
1342                    Binder::dummy(rustc_type_ir::PredicateKind::Clause(
1343                        rustc_type_ir::ClauseKind::Trait(TraitPredicate {
1344                            trait_ref,
1345                            polarity: rustc_type_ir::PredicatePolarity::Positive,
1346                        }),
1347                    )),
1348                ))
1349            });
1350            predicates.extend(sized_clause);
1351        }
1352
1353        let assoc_ty_bounds_start = predicates.len() as u32;
1354        predicates.extend(assoc_ty_bounds);
1355
1356        self.is_lowering_impl_trait_bounds = prev_is_lowering_impl_trait_bounds;
1357        SelfAndAssocBounds {
1358            bounds: StoredEarlyBinder::bind(Clauses::new_from_slice(&predicates).store()),
1359            assoc_ty_bounds_start,
1360        }
1361    }
1362
1363    pub(crate) fn lower_lifetime(&mut self, lifetime: LifetimeRefId) -> Region<'db> {
1364        if let Some(region) = self.find_and_lower_hrtb_lifetime(lifetime) {
1365            return region;
1366        };
1367
1368        match self.resolver.resolve_lifetime(&self.store[lifetime]) {
1369            Some(resolution) => match resolution {
1370                LifetimeNs::Static => Region::new_static(self.interner),
1371                LifetimeNs::LifetimeParam(id) => {
1372                    let (idx, is_late_bound) =
1373                        self.generics().lifetime_param_idx(id, self.is_lowering_impl_trait_bounds);
1374                    self.region_param(id, idx, is_late_bound)
1375                }
1376            },
1377            None => Region::error(self.interner),
1378        }
1379    }
1380
1381    fn find_and_lower_hrtb_lifetime(&mut self, lifetime: LifetimeRefId) -> Option<Region<'db>> {
1382        if let LifetimeRef::Named(lt_name) = &self.store[lifetime] {
1383            self.bound_vars.iter().rev().enumerate().find_map(|(debruijn, (binder, _))| {
1384                binder.iter().enumerate().find_map(|(index, l)| {
1385                    (l == lt_name).then(|| {
1386                        self.hrtb_region_param(
1387                            index as u32,
1388                            DebruijnIndex::from_usize(debruijn),
1389                            self.generic_def,
1390                        )
1391                    })
1392                })
1393            })
1394        } else {
1395            None
1396        }
1397    }
1398}
1399
1400#[derive(Clone, PartialEq, Eq, SalsaValue)]
1401pub struct TyLoweringResult<'db, T> {
1402    pub value: T,
1403    info: Option<Box<TyLoweringResultInfo<'db>>>,
1404}
1405
1406#[derive(Clone, PartialEq, Eq, SalsaValue)]
1407struct TyLoweringResultInfo<'db> {
1408    diagnostics: ThinVec<TyLoweringDiagnostic>,
1409    anon_consts: ThinVec<AnonConstId<'db>>,
1410}
1411
1412impl<T: std::fmt::Debug> std::fmt::Debug for TyLoweringResult<'_, T> {
1413    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1414        let mut debug = f.debug_struct("TyLoweringResult");
1415        debug.field("value", &self.value);
1416        let diagnostics = self.diagnostics();
1417        if !diagnostics.is_empty() {
1418            debug.field("diagnostics", &diagnostics);
1419        }
1420        let defined_anon_consts = self.defined_anon_consts();
1421        if !defined_anon_consts.is_empty() {
1422            debug.field("defined_anon_consts", &defined_anon_consts);
1423        }
1424        debug.finish()
1425    }
1426}
1427
1428impl<'db, T> TyLoweringResult<'db, T> {
1429    fn new(
1430        value: T,
1431        mut diagnostics: ThinVec<TyLoweringDiagnostic>,
1432        mut defined_anon_consts: ThinVec<AnonConstId<'db>>,
1433    ) -> Self {
1434        let info = if diagnostics.is_empty() && defined_anon_consts.is_empty() {
1435            None
1436        } else {
1437            diagnostics.shrink_to_fit();
1438            defined_anon_consts.shrink_to_fit();
1439            Some(Box::new(TyLoweringResultInfo { diagnostics, anon_consts: defined_anon_consts }))
1440        };
1441        Self { value, info }
1442    }
1443
1444    fn from_ctx(value: T, ctx: TyLoweringContext<'db, '_>) -> Self {
1445        Self::new(value, ctx.diagnostics, ctx.defined_anon_consts)
1446    }
1447
1448    fn empty(value: T) -> Self {
1449        Self { value, info: None }
1450    }
1451
1452    #[inline]
1453    pub fn diagnostics(&self) -> &[TyLoweringDiagnostic] {
1454        match &self.info {
1455            Some(info) => &info.diagnostics,
1456            None => &[],
1457        }
1458    }
1459
1460    #[inline]
1461    pub fn defined_anon_consts(&self) -> &[AnonConstId<'db>] {
1462        match &self.info {
1463            Some(info) => &info.anon_consts,
1464            None => &[],
1465        }
1466    }
1467}
1468
1469fn replace_dummy_self_with_error<'db, T: TypeFoldable<DbInterner<'db>>>(
1470    interner: DbInterner<'db>,
1471    types: &DefaultAny<'db>,
1472    t: T,
1473) -> T {
1474    t.fold_with(&mut BottomUpFolder {
1475        interner,
1476        ty_op: |ty| {
1477            if ty == types.types.dyn_trait_dummy_self { types.types.error } else { ty }
1478        },
1479        lt_op: |lt| lt,
1480        ct_op: |ct| ct,
1481    })
1482}
1483
1484pub(crate) fn lower_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1485    match m {
1486        hir_def::type_ref::Mutability::Shared => Mutability::Not,
1487        hir_def::type_ref::Mutability::Mut => Mutability::Mut,
1488    }
1489}
1490
1491pub(crate) fn impl_trait_query<'db>(
1492    db: &'db dyn HirDatabase,
1493    impl_id: ImplId,
1494) -> Option<EarlyBinder<'db, TraitRef<'db>>> {
1495    impl_trait_with_diagnostics(db, impl_id)
1496        .as_ref()
1497        .map(|it| it.value.get(DbInterner::new_no_crate(db)))
1498}
1499
1500#[salsa::tracked(returns(ref), cycle_result = impl_trait_with_diagnostics_cycle_result)]
1501pub(crate) fn impl_trait_with_diagnostics<'db>(
1502    db: &'db dyn HirDatabase,
1503    impl_id: ImplId,
1504) -> Option<TyLoweringResult<'db, StoredEarlyBinder<StoredTraitRef>>> {
1505    let impl_data = ImplSignature::of(db, impl_id);
1506    let resolver = impl_id.resolver(db);
1507    let generics = OnceCell::new();
1508    let mut ctx = TyLoweringContext::new(
1509        db,
1510        &resolver,
1511        &impl_data.store,
1512        ExpressionStoreOwnerId::Signature(impl_id.into()),
1513        impl_id.into(),
1514        &generics,
1515        LifetimeElisionKind::AnonymousCreateParameter { report_in_path: true },
1516        LifetimeLoweringMode::Bound,
1517    );
1518    let self_ty = db.impl_self_ty(impl_id).skip_binder();
1519    let target_trait = impl_data.target_trait?;
1520    let trait_ref = ctx.lower_trait_ref(target_trait, self_ty)?;
1521    Some(TyLoweringResult::from_ctx(StoredEarlyBinder::bind(StoredTraitRef::new(trait_ref)), ctx))
1522}
1523
1524pub(crate) fn impl_trait_with_diagnostics_cycle_result<'db>(
1525    _db: &'db dyn HirDatabase,
1526    _: salsa::Id,
1527    _impl_id: ImplId,
1528) -> Option<TyLoweringResult<'db, StoredEarlyBinder<StoredTraitRef>>> {
1529    None
1530}
1531
1532impl ImplTraitId {
1533    #[inline]
1534    pub fn bounds(self, db: &dyn HirDatabase) -> &SelfAndAssocBounds {
1535        let (impl_traits, idx) = match self {
1536            ImplTraitId::ReturnTypeImplTrait(owner, idx) => {
1537                (SelfAndAssocBounds::return_type_impl_traits(db, owner), idx)
1538            }
1539            ImplTraitId::TypeAliasImplTrait(owner, idx) => {
1540                (SelfAndAssocBounds::type_alias_impl_traits(db, owner), idx)
1541            }
1542        };
1543        &impl_traits[idx.into_raw().into_u32() as usize]
1544    }
1545
1546    #[inline]
1547    pub fn all_bounds<'db>(self, db: &'db dyn HirDatabase) -> EarlyBinder<'db, &'db [Clause<'db>]> {
1548        self.bounds(db).all_bounds()
1549    }
1550
1551    #[inline]
1552    pub fn self_bounds<'db>(
1553        self,
1554        db: &'db dyn HirDatabase,
1555    ) -> EarlyBinder<'db, &'db [Clause<'db>]> {
1556        self.bounds(db).self_bounds()
1557    }
1558}
1559
1560impl InternedOpaqueTyId<'_> {
1561    #[inline]
1562    pub fn predicates<'db>(self, db: &'db dyn HirDatabase) -> EarlyBinder<'db, &'db [Clause<'db>]> {
1563        self.loc(db).all_bounds(db)
1564    }
1565
1566    #[inline]
1567    pub fn self_predicates<'db>(
1568        self,
1569        db: &'db dyn HirDatabase,
1570    ) -> EarlyBinder<'db, &'db [Clause<'db>]> {
1571        self.loc(db).self_bounds(db)
1572    }
1573}
1574
1575impl SelfAndAssocBounds {
1576    #[inline]
1577    pub(crate) fn return_type_impl_traits(
1578        db: &dyn HirDatabase,
1579        def: FunctionId,
1580    ) -> &[SelfAndAssocBounds] {
1581        &fn_sig_for_fn(db, def).value.impl_traits
1582    }
1583
1584    #[inline]
1585    pub(crate) fn type_alias_impl_traits(
1586        db: &dyn HirDatabase,
1587        def: TypeAliasId,
1588    ) -> &[SelfAndAssocBounds] {
1589        &type_for_type_alias_with_diagnostics(db, def).value.impl_traits
1590    }
1591}
1592
1593#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1594pub enum TyDefId {
1595    BuiltinType(BuiltinType),
1596    AdtId(AdtId),
1597    TypeAliasId(TypeAliasId),
1598}
1599impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1600
1601#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)]
1602pub enum ValueTyDefId {
1603    FunctionId(FunctionId),
1604    StructId(StructId),
1605    UnionId(UnionId),
1606    EnumVariantId(EnumVariantId),
1607    ConstId(ConstId),
1608    StaticId(StaticId),
1609}
1610impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1611
1612impl ValueTyDefId {
1613    pub(crate) fn to_generic_def_id(self, db: &dyn HirDatabase) -> GenericDefId {
1614        match self {
1615            Self::FunctionId(id) => id.into(),
1616            Self::StructId(id) => id.into(),
1617            Self::UnionId(id) => id.into(),
1618            Self::EnumVariantId(var) => var.lookup(db).parent.into(),
1619            Self::ConstId(id) => id.into(),
1620            Self::StaticId(id) => id.into(),
1621        }
1622    }
1623}
1624
1625/// Build the declared type of an item. This depends on the namespace; e.g. for
1626/// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1627/// the constructor function `(usize) -> Foo` which lives in the values
1628/// namespace.
1629pub(crate) fn ty_query<'db>(db: &'db dyn HirDatabase, def: TyDefId) -> EarlyBinder<'db, Ty<'db>> {
1630    let interner = DbInterner::new_no_crate(db);
1631    match def {
1632        TyDefId::BuiltinType(it) => EarlyBinder::bind(Ty::from_builtin_type(interner, it)),
1633        TyDefId::AdtId(it) => EarlyBinder::bind(Ty::new_adt(
1634            interner,
1635            it,
1636            GenericArgs::identity_for_item(interner, it.into()),
1637        )),
1638        TyDefId::TypeAliasId(it) => db.type_for_type_alias_with_diagnostics(it).value.value.get(),
1639    }
1640}
1641
1642/// Build the declared type of a function. This should not need to look at the
1643/// function body.
1644fn type_for_fn<'db>(db: &'db dyn HirDatabase, def: FunctionId) -> EarlyBinder<'db, Ty<'db>> {
1645    let interner = DbInterner::new_no_crate(db);
1646    EarlyBinder::bind(Ty::new_fn_def(
1647        interner,
1648        CallableDefId::FunctionId(def).into(),
1649        GenericArgs::identity_for_item(interner, def.into()),
1650    ))
1651}
1652
1653pub(crate) fn type_for_const<'db>(
1654    db: &'db dyn HirDatabase,
1655    def: ConstId,
1656) -> EarlyBinder<'db, Ty<'db>> {
1657    type_for_const_with_diagnostics(db, def).value.get()
1658}
1659
1660/// Build the declared type of a const.
1661#[salsa::tracked(returns(ref))]
1662pub(crate) fn type_for_const_with_diagnostics<'db>(
1663    db: &'db dyn HirDatabase,
1664    def: ConstId,
1665) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> {
1666    let resolver = def.resolver(db);
1667    let data = ConstSignature::of(db, def);
1668    let parent = def.loc(db).container;
1669    let generics = OnceCell::new();
1670    let mut ctx = TyLoweringContext::new(
1671        db,
1672        &resolver,
1673        &data.store,
1674        ExpressionStoreOwnerId::Signature(def.into()),
1675        def.into(),
1676        &generics,
1677        LifetimeElisionKind::AnonymousReportError,
1678        LifetimeLoweringMode::Bound,
1679    );
1680    ctx.set_lifetime_elision(LifetimeElisionKind::for_const(ctx.interner, parent));
1681    let result = StoredEarlyBinder::bind(ctx.lower_ty(data.type_ref).store());
1682    TyLoweringResult::from_ctx(result, ctx)
1683}
1684
1685pub(crate) fn type_for_static<'db>(
1686    db: &'db dyn HirDatabase,
1687    def: StaticId,
1688) -> EarlyBinder<'db, Ty<'db>> {
1689    type_for_static_with_diagnostics(db, def).value.get()
1690}
1691
1692/// Build the declared type of a static.
1693#[salsa::tracked(returns(ref))]
1694pub(crate) fn type_for_static_with_diagnostics<'db>(
1695    db: &'db dyn HirDatabase,
1696    def: StaticId,
1697) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> {
1698    let resolver = def.resolver(db);
1699    let data = StaticSignature::of(db, def);
1700    let generics = OnceCell::new();
1701    let mut ctx = TyLoweringContext::new(
1702        db,
1703        &resolver,
1704        &data.store,
1705        ExpressionStoreOwnerId::Signature(def.into()),
1706        def.into(),
1707        &generics,
1708        LifetimeElisionKind::AnonymousReportError,
1709        LifetimeLoweringMode::Bound,
1710    );
1711    ctx.set_lifetime_elision(LifetimeElisionKind::Elided(Region::new_static(ctx.interner)));
1712    let result = StoredEarlyBinder::bind(ctx.lower_ty(data.type_ref).store());
1713    TyLoweringResult::from_ctx(result, ctx)
1714}
1715
1716/// Build the type of a tuple struct constructor.
1717fn type_for_struct_constructor<'db>(
1718    db: &'db dyn HirDatabase,
1719    def: StructId,
1720) -> Option<EarlyBinder<'db, Ty<'db>>> {
1721    let struct_data = StructSignature::of(db, def);
1722    match struct_data.shape {
1723        FieldsShape::Record => None,
1724        FieldsShape::Unit => Some(type_for_adt(db, def.into())),
1725        FieldsShape::Tuple => {
1726            let interner = DbInterner::new_no_crate(db);
1727            let def = CallableDefId::StructId(def);
1728            Some(EarlyBinder::bind(Ty::new_fn_def(
1729                interner,
1730                def.into(),
1731                GenericArgs::identity_for_item(interner, def.into()),
1732            )))
1733        }
1734    }
1735}
1736
1737/// Build the type of a tuple enum variant constructor.
1738fn type_for_enum_variant_constructor<'db>(
1739    db: &'db dyn HirDatabase,
1740    def: EnumVariantId,
1741) -> Option<EarlyBinder<'db, Ty<'db>>> {
1742    let struct_data = def.fields(db);
1743    match struct_data.shape {
1744        FieldsShape::Record => None,
1745        FieldsShape::Unit => Some(type_for_adt(db, def.loc(db).parent.into())),
1746        FieldsShape::Tuple => {
1747            let interner = DbInterner::new_no_crate(db);
1748            let def = CallableDefId::EnumVariantId(def);
1749            Some(EarlyBinder::bind(Ty::new_fn_def(
1750                interner,
1751                def.into(),
1752                GenericArgs::identity_for_item(interner, def.into()),
1753            )))
1754        }
1755    }
1756}
1757
1758pub(crate) fn value_ty<'db>(
1759    db: &'db dyn HirDatabase,
1760    def: ValueTyDefId,
1761) -> Option<EarlyBinder<'db, Ty<'db>>> {
1762    match def {
1763        ValueTyDefId::FunctionId(it) => Some(type_for_fn(db, it)),
1764        ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1765        ValueTyDefId::UnionId(it) => Some(type_for_adt(db, it.into())),
1766        ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1767        ValueTyDefId::ConstId(it) => Some(type_for_const(db, it)),
1768        ValueTyDefId::StaticId(it) => Some(type_for_static(db, it)),
1769    }
1770}
1771
1772#[salsa::tracked(returns(ref), cycle_result = type_for_type_alias_with_diagnostics_cycle_result)]
1773pub(crate) fn type_for_type_alias_with_diagnostics<'db>(
1774    db: &'db dyn HirDatabase,
1775    t: TypeAliasId,
1776) -> TyLoweringResult<'db, WithDefinedOpaques<StoredEarlyBinder<StoredTy>>> {
1777    let type_alias_data = TypeAliasSignature::of(db, t);
1778    let interner = DbInterner::new_no_crate(db);
1779    if type_alias_data.flags.contains(TypeAliasFlags::IS_EXTERN) {
1780        TyLoweringResult::empty(WithDefinedOpaques {
1781            value: StoredEarlyBinder::bind(Ty::new_foreign(interner, t.into()).store()),
1782            impl_traits: ThinVec::new(),
1783        })
1784    } else {
1785        let resolver = t.resolver(db);
1786        let generics = OnceCell::new();
1787        let mut ctx = TyLoweringContext::new(
1788            db,
1789            &resolver,
1790            &type_alias_data.store,
1791            ExpressionStoreOwnerId::Signature(t.into()),
1792            t.into(),
1793            &generics,
1794            LifetimeElisionKind::AnonymousReportError,
1795            LifetimeLoweringMode::Bound,
1796        )
1797        .with_impl_trait_mode(ImplTraitLoweringMode::Opaque);
1798        let res = StoredEarlyBinder::bind(
1799            type_alias_data
1800                .ty
1801                .map(|type_ref| ctx.lower_ty(type_ref))
1802                .unwrap_or_else(|| Ty::new_error(interner, ErrorGuaranteed))
1803                .store(),
1804        );
1805        TyLoweringResult::from_ctx(
1806            WithDefinedOpaques { value: res, impl_traits: ctx.take_defined_opaques() },
1807            ctx,
1808        )
1809    }
1810}
1811
1812pub(crate) fn type_for_type_alias_with_diagnostics_cycle_result<'db>(
1813    db: &'db dyn HirDatabase,
1814    _: salsa::Id,
1815    _adt: TypeAliasId,
1816) -> TyLoweringResult<'db, WithDefinedOpaques<StoredEarlyBinder<StoredTy>>> {
1817    TyLoweringResult::empty(WithDefinedOpaques {
1818        value: StoredEarlyBinder::bind(
1819            Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed).store(),
1820        ),
1821        impl_traits: ThinVec::new(),
1822    })
1823}
1824
1825pub(crate) fn impl_self_ty_query<'db>(
1826    db: &'db dyn HirDatabase,
1827    impl_id: ImplId,
1828) -> EarlyBinder<'db, Ty<'db>> {
1829    impl_self_ty_with_diagnostics(db, impl_id).value.get()
1830}
1831
1832#[salsa::tracked(returns(ref), cycle_result = impl_self_ty_with_diagnostics_cycle_result)]
1833pub(crate) fn impl_self_ty_with_diagnostics<'db>(
1834    db: &'db dyn HirDatabase,
1835    impl_id: ImplId,
1836) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> {
1837    let resolver = impl_id.resolver(db);
1838    let generics = OnceCell::new();
1839    let impl_data = ImplSignature::of(db, impl_id);
1840    let mut ctx = TyLoweringContext::new(
1841        db,
1842        &resolver,
1843        &impl_data.store,
1844        ExpressionStoreOwnerId::Signature(impl_id.into()),
1845        impl_id.into(),
1846        &generics,
1847        LifetimeElisionKind::AnonymousCreateParameter { report_in_path: true },
1848        LifetimeLoweringMode::Bound,
1849    );
1850    let ty = ctx.lower_ty(impl_data.self_ty);
1851    assert!(!ty.has_escaping_bound_vars());
1852    TyLoweringResult::from_ctx(StoredEarlyBinder::bind(ty.store()), ctx)
1853}
1854
1855pub(crate) fn impl_self_ty_with_diagnostics_cycle_result<'db>(
1856    db: &'db dyn HirDatabase,
1857    _: salsa::Id,
1858    _impl_id: ImplId,
1859) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> {
1860    TyLoweringResult::empty(StoredEarlyBinder::bind(
1861        Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed).store(),
1862    ))
1863}
1864
1865pub(crate) fn const_param_ty<'db>(db: &'db dyn HirDatabase, def: ConstParamId) -> Ty<'db> {
1866    const_param_types(db, def.parent()).get(def.local_id())
1867}
1868
1869/// Wrapper struct around `ArenaMap` which implements [`SalsaValue`].
1870///
1871/// Required to make the `SalsaValue` derive for [`TyLoweringResult`] work.
1872#[derive(Debug, Default, PartialEq, Eq, SalsaValue)]
1873pub struct ConstParamTypes {
1874    map: ArenaMap<LocalTypeOrConstParamId, StoredTy>,
1875}
1876
1877impl ConstParamTypes {
1878    #[inline]
1879    pub fn get(&self, local_id: LocalTypeOrConstParamId) -> Ty<'_> {
1880        match self.map.get(local_id) {
1881            Some(ty) => ty.as_ref(),
1882            None => default_types().types.error,
1883        }
1884    }
1885}
1886
1887pub(crate) fn const_param_types(db: &dyn HirDatabase, def: GenericDefId) -> &ConstParamTypes {
1888    &const_param_types_with_diagnostics(db, def).value
1889}
1890
1891#[salsa::tracked(returns(ref), cycle_result = const_param_types_with_diagnostics_cycle_result)]
1892pub(crate) fn const_param_types_with_diagnostics<'db>(
1893    db: &'db dyn HirDatabase,
1894    def: GenericDefId,
1895) -> TyLoweringResult<'db, ConstParamTypes> {
1896    let mut result = ArenaMap::new();
1897    let (data, store) = GenericParams::with_store(db, def);
1898    let resolver = def.resolver(db);
1899    let generics = OnceCell::new();
1900    let mut ctx = TyLoweringContext::new(
1901        db,
1902        &resolver,
1903        store,
1904        ExpressionStoreOwnerId::Signature(def),
1905        def,
1906        &generics,
1907        LifetimeElisionKind::AnonymousReportError,
1908        LifetimeLoweringMode::Bound,
1909    );
1910    ctx.forbid_params_after(0, ForbidParamsAfterReason::ConstParamTy);
1911    for (local_id, param_data) in data.iter_type_or_consts() {
1912        if let TypeOrConstParamData::ConstParamData(param_data) = param_data {
1913            result.insert(local_id, ctx.lower_ty(param_data.ty).store());
1914        }
1915    }
1916    result.shrink_to_fit();
1917    TyLoweringResult::from_ctx(ConstParamTypes { map: result }, ctx)
1918}
1919
1920fn const_param_types_with_diagnostics_cycle_result<'db>(
1921    _db: &'db dyn HirDatabase,
1922    _: salsa::Id,
1923    _def: GenericDefId,
1924) -> TyLoweringResult<'db, ConstParamTypes> {
1925    TyLoweringResult::empty(ConstParamTypes::default())
1926}
1927
1928/// Wrapper struct around `ArenaMap` which implements [`SalsaValue`].
1929///
1930/// Required to make the `SalsaValue` derive for [`TyLoweringResult`] work.
1931#[derive(Default, PartialEq, Eq, SalsaValue)]
1932pub struct FieldTypes {
1933    map: ArenaMap<LocalFieldId, FieldType>,
1934}
1935
1936impl Deref for FieldTypes {
1937    type Target = ArenaMap<LocalFieldId, FieldType>;
1938
1939    fn deref(&self) -> &Self::Target {
1940        &self.map
1941    }
1942}
1943
1944pub(crate) fn field_types_query(db: &dyn HirDatabase, variant_id: VariantId) -> &FieldTypes {
1945    &field_types_with_diagnostics(db, variant_id).value
1946}
1947
1948#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1949pub struct FieldType {
1950    ty: StoredEarlyBinder<StoredTy>,
1951    default: Option<StoredEarlyBinder<StoredConst>>,
1952}
1953
1954impl FieldType {
1955    #[inline]
1956    pub fn ty<'db>(&self) -> EarlyBinder<'db, Ty<'db>> {
1957        self.ty.get()
1958    }
1959
1960    #[inline]
1961    pub fn default<'db>(&self) -> Option<EarlyBinder<'db, Const<'db>>> {
1962        self.default.as_ref().map(|default| default.get_with(|it| it.as_ref()))
1963    }
1964}
1965
1966/// Build the type of all specific fields of a struct or enum variant.
1967#[salsa::tracked(returns(ref))]
1968pub(crate) fn field_types_with_diagnostics<'db>(
1969    db: &'db dyn HirDatabase,
1970    variant_id: VariantId,
1971) -> TyLoweringResult<'db, FieldTypes> {
1972    let var_data = variant_id.fields(db);
1973    let fields = var_data.fields();
1974    if fields.is_empty() {
1975        return TyLoweringResult::empty(FieldTypes::default());
1976    }
1977
1978    let (resolver, generic_def): (_, GenericDefId) = match variant_id {
1979        VariantId::StructId(it) => (it.resolver(db), it.into()),
1980        VariantId::UnionId(it) => (it.resolver(db), it.into()),
1981        VariantId::EnumVariantId(it) => (it.resolver(db), it.lookup(db).parent.into()),
1982    };
1983    let generics = OnceCell::new();
1984    let mut res = ArenaMap::default();
1985    let mut ctx = TyLoweringContext::new(
1986        db,
1987        &resolver,
1988        &var_data.store,
1989        ExpressionStoreOwnerId::VariantFields(variant_id),
1990        generic_def,
1991        &generics,
1992        LifetimeElisionKind::AnonymousReportError,
1993        LifetimeLoweringMode::Bound,
1994    );
1995    for (field_id, field_data) in var_data.fields().iter() {
1996        let ty = ctx.lower_ty(field_data.type_ref);
1997        let default = field_data.default_value.map(|default| ctx.lower_const(default, ty, true));
1998        res.insert(
1999            field_id,
2000            FieldType {
2001                ty: StoredEarlyBinder::bind(ty.store()),
2002                default: default.map(|default| StoredEarlyBinder::bind(default.store())),
2003            },
2004        );
2005    }
2006    TyLoweringResult::from_ctx(FieldTypes { map: res }, ctx)
2007}
2008
2009#[derive(Debug, PartialEq, Eq, Default)]
2010pub(crate) struct SupertraitsInfo {
2011    /// This includes the trait itself.
2012    pub(crate) all_supertraits: Box<[TraitId]>,
2013    pub(crate) direct_supertraits: Box<[TraitId]>,
2014    pub(crate) defined_assoc_types: Box<[(Name, TypeAliasId)]>,
2015}
2016
2017impl SupertraitsInfo {
2018    #[inline]
2019    pub(crate) fn query(db: &dyn HirDatabase, trait_: TraitId) -> &Self {
2020        return supertraits_info(db, trait_);
2021
2022        #[salsa::tracked(returns(ref), cycle_result = supertraits_info_cycle)]
2023        fn supertraits_info(db: &dyn HirDatabase, trait_: TraitId) -> SupertraitsInfo {
2024            let mut all_supertraits = FxHashSet::default();
2025            let mut direct_supertraits = FxHashSet::default();
2026            let mut defined_assoc_types = FxHashSet::default();
2027
2028            all_supertraits.insert(trait_);
2029            defined_assoc_types.extend(trait_.trait_items(db).items.iter().filter_map(
2030                |(name, id)| match *id {
2031                    AssocItemId::TypeAliasId(id) => Some((name.clone(), id)),
2032                    _ => None,
2033                },
2034            ));
2035
2036            let resolver = trait_.resolver(db);
2037            let signature = TraitSignature::of(db, trait_);
2038            for pred in signature.generic_params.where_predicates() {
2039                let WherePredicate::TypeBound { lifetimes: _, target, bound } = pred else {
2040                    continue;
2041                };
2042                let (TypeBound::Path(bounded_trait, TraitBoundModifier::None)
2043                | TypeBound::ForLifetime(_, bounded_trait)) = *bound
2044                else {
2045                    continue;
2046                };
2047                let target = &signature.store[*target];
2048                match target {
2049                    TypeRef::TypeParam(param)
2050                        if param.local_id() == GenericParams::SELF_PARAM_ID_IN_SELF => {}
2051                    TypeRef::Path(path) if path.is_self_type() => {}
2052                    _ => continue,
2053                }
2054                let Some(TypeNs::TraitId(bounded_trait)) =
2055                    resolver.resolve_path_in_type_ns_fully(db, &signature.store[bounded_trait])
2056                else {
2057                    continue;
2058                };
2059                let SupertraitsInfo {
2060                    all_supertraits: bounded_trait_all_supertraits,
2061                    direct_supertraits: _,
2062                    defined_assoc_types: bounded_traits_defined_assoc_types,
2063                } = SupertraitsInfo::query(db, bounded_trait);
2064                all_supertraits.extend(bounded_trait_all_supertraits);
2065                direct_supertraits.insert(bounded_trait);
2066                defined_assoc_types.extend(bounded_traits_defined_assoc_types.iter().cloned());
2067            }
2068
2069            SupertraitsInfo {
2070                all_supertraits: Box::from_iter(all_supertraits),
2071                direct_supertraits: Box::from_iter(direct_supertraits),
2072                defined_assoc_types: Box::from_iter(defined_assoc_types),
2073            }
2074        }
2075
2076        fn supertraits_info_cycle(
2077            _db: &dyn HirDatabase,
2078            _: salsa::Id,
2079            _trait_: TraitId,
2080        ) -> SupertraitsInfo {
2081            SupertraitsInfo::default()
2082        }
2083    }
2084}
2085
2086#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2087enum AssocTypeShorthandResolution {
2088    Resolved(StoredEarlyBinder<(TypeAliasId, StoredGenericArgs)>),
2089    Ambiguous {
2090        /// If one resolution belongs to a sub-trait and one to a supertrait, this contains
2091        /// the sub-trait's resolution. This can be `None` if there is no trait inheritance
2092        /// relationship between the resolutions.
2093        sub_trait_resolution: Option<StoredEarlyBinder<(TypeAliasId, StoredGenericArgs)>>,
2094    },
2095    NotFound,
2096    Cycle,
2097}
2098
2099/// Predicates for `param_id` of the form `P: SomeTrait`. If
2100/// `assoc_name` is provided, only return predicates referencing traits
2101/// that have an associated type of that name.
2102///
2103/// This query exists only to be used when resolving short-hand associated types
2104/// like `T::Item`.
2105///
2106/// See the analogous query in rustc and its comment:
2107/// <https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46>
2108///
2109/// This is a query mostly to handle cycles somewhat gracefully; e.g. the
2110/// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
2111/// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
2112#[tracing::instrument(skip(db), ret)]
2113#[salsa::tracked(returns(ref), cycle_result = resolve_type_param_assoc_type_shorthand_cycle_result)]
2114fn resolve_type_param_assoc_type_shorthand(
2115    db: &dyn HirDatabase,
2116    def: GenericDefId,
2117    param: TypeParamId,
2118    assoc_name: Name,
2119) -> AssocTypeShorthandResolution {
2120    let generics = generics(db, def);
2121    let store = generics.store();
2122    let generics = &OnceCell::from(generics);
2123    let resolver = def.resolver(db);
2124    let mut ctx = TyLoweringContext::new(
2125        db,
2126        &resolver,
2127        store,
2128        ExpressionStoreOwnerId::Signature(def),
2129        def,
2130        generics,
2131        LifetimeElisionKind::AnonymousReportError,
2132        LifetimeLoweringMode::Bound,
2133    );
2134    let interner = ctx.interner;
2135    let generics = generics.get().unwrap();
2136    let param_ty = Ty::new_param(interner, param, generics.type_or_const_param_idx(param.into()));
2137
2138    let mut this_trait_resolution = None;
2139    if let GenericDefId::TraitId(containing_trait) = param.parent()
2140        && param.local_id() == GenericParams::SELF_PARAM_ID_IN_SELF
2141    {
2142        // Add the trait's own associated types.
2143        if let Some(assoc_type) =
2144            containing_trait.trait_items(db).associated_type_by_name(&assoc_name)
2145        {
2146            let args = GenericArgs::identity_for_item(interner, containing_trait.into());
2147            this_trait_resolution = Some(StoredEarlyBinder::bind((assoc_type, args.store())));
2148        }
2149    }
2150
2151    let mut supertraits_resolution = None;
2152    for maybe_parent_generics in generics.iter_owners().rev() {
2153        ctx.set_owner(maybe_parent_generics);
2154        for pred in maybe_parent_generics.where_predicates() {
2155            let WherePredicate::TypeBound { lifetimes: _, target, bound } = pred else {
2156                continue;
2157            };
2158            let (TypeBound::Path(bounded_trait_path, TraitBoundModifier::None)
2159            | TypeBound::ForLifetime(_, bounded_trait_path)) = *bound
2160            else {
2161                continue;
2162            };
2163            let Some(target) = ctx.lower_ty_only_param(*target) else { continue };
2164            if target != param.into() {
2165                continue;
2166            }
2167            let mut ctx = ctx.at_path(bounded_trait_path);
2168            let Some(TypeNs::TraitId(bounded_trait)) = ctx.resolve_path_in_type_ns_fully() else {
2169                continue;
2170            };
2171            if !SupertraitsInfo::query(db, bounded_trait)
2172                .defined_assoc_types
2173                .iter()
2174                .any(|(name, _)| *name == assoc_name)
2175            {
2176                continue;
2177            }
2178
2179            let bounded_trait_ref =
2180                ctx.lower_trait_ref_from_resolved_path(bounded_trait, param_ty, false, Span::Dummy);
2181            // Now, search from the start on the *bounded* trait like if we wrote `Self::Assoc`. Eventually, we'll get
2182            // the correct trait ref (or a cycle).
2183            let lookup_on_bounded_trait = resolve_type_param_assoc_type_shorthand(
2184                db,
2185                bounded_trait.into(),
2186                TypeParamId::trait_self(bounded_trait),
2187                assoc_name.clone(),
2188            );
2189            let assoc_type_and_args = match &lookup_on_bounded_trait {
2190                AssocTypeShorthandResolution::Resolved(trait_ref) => trait_ref,
2191                AssocTypeShorthandResolution::Ambiguous {
2192                    sub_trait_resolution: Some(trait_ref),
2193                } => trait_ref,
2194                AssocTypeShorthandResolution::Ambiguous { sub_trait_resolution: None } => {
2195                    return AssocTypeShorthandResolution::Ambiguous {
2196                        sub_trait_resolution: this_trait_resolution,
2197                    };
2198                }
2199                AssocTypeShorthandResolution::NotFound => {
2200                    never!("we checked that the trait defines this assoc type");
2201                    continue;
2202                }
2203                AssocTypeShorthandResolution::Cycle => return AssocTypeShorthandResolution::Cycle,
2204            };
2205            let (assoc_type, args) = assoc_type_and_args
2206                .get_with(|(assoc_type, args)| (*assoc_type, args.as_ref()))
2207                .skip_binder();
2208            let args = EarlyBinder::bind(args)
2209                .instantiate(interner, bounded_trait_ref.args)
2210                .skip_norm_wip();
2211            let current_result = StoredEarlyBinder::bind((assoc_type, args.store()));
2212            if let Some(this_trait_resolution) = &this_trait_resolution {
2213                if *this_trait_resolution == current_result {
2214                    continue;
2215                } else {
2216                    return AssocTypeShorthandResolution::Ambiguous {
2217                        sub_trait_resolution: Some(this_trait_resolution.clone()),
2218                    };
2219                }
2220            } else if let Some(prev_resolution) = &supertraits_resolution {
2221                if let AssocTypeShorthandResolution::Ambiguous {
2222                    sub_trait_resolution: Some(prev_resolution),
2223                }
2224                | AssocTypeShorthandResolution::Resolved(prev_resolution) = prev_resolution
2225                    && *prev_resolution == current_result
2226                {
2227                    continue;
2228                } else {
2229                    return AssocTypeShorthandResolution::Ambiguous { sub_trait_resolution: None };
2230                }
2231            } else {
2232                supertraits_resolution = Some(match lookup_on_bounded_trait {
2233                    AssocTypeShorthandResolution::Resolved(_) => {
2234                        AssocTypeShorthandResolution::Resolved(current_result)
2235                    }
2236                    AssocTypeShorthandResolution::Ambiguous { .. } => {
2237                        AssocTypeShorthandResolution::Ambiguous {
2238                            sub_trait_resolution: Some(current_result),
2239                        }
2240                    }
2241                    AssocTypeShorthandResolution::NotFound
2242                    | AssocTypeShorthandResolution::Cycle => unreachable!(),
2243                });
2244            }
2245        }
2246    }
2247
2248    supertraits_resolution
2249        .or_else(|| this_trait_resolution.map(AssocTypeShorthandResolution::Resolved))
2250        .unwrap_or(AssocTypeShorthandResolution::NotFound)
2251}
2252
2253fn resolve_type_param_assoc_type_shorthand_cycle_result(
2254    _db: &dyn HirDatabase,
2255    _: salsa::Id,
2256    _def: GenericDefId,
2257    _param: TypeParamId,
2258    _assoc_name: Name,
2259) -> AssocTypeShorthandResolution {
2260    AssocTypeShorthandResolution::Cycle
2261}
2262
2263#[inline]
2264pub(crate) fn type_alias_bounds<'db>(
2265    db: &'db dyn HirDatabase,
2266    type_alias: TypeAliasId,
2267) -> EarlyBinder<'db, &'db [Clause<'db>]> {
2268    type_alias_bounds_with_diagnostics(db, type_alias).value.all_bounds()
2269}
2270
2271#[inline]
2272pub(crate) fn type_alias_self_bounds<'db>(
2273    db: &'db dyn HirDatabase,
2274    type_alias: TypeAliasId,
2275) -> EarlyBinder<'db, &'db [Clause<'db>]> {
2276    type_alias_bounds_with_diagnostics(db, type_alias).value.self_bounds()
2277}
2278
2279#[salsa::tracked(returns(ref))]
2280pub(crate) fn type_alias_bounds_with_diagnostics<'db>(
2281    db: &'db dyn HirDatabase,
2282    type_alias: TypeAliasId,
2283) -> TyLoweringResult<'db, SelfAndAssocBounds> {
2284    let type_alias_data = TypeAliasSignature::of(db, type_alias);
2285    let resolver = type_alias.resolver(db);
2286    let generics = OnceCell::new();
2287    let mut ctx = TyLoweringContext::new(
2288        db,
2289        &resolver,
2290        &type_alias_data.store,
2291        ExpressionStoreOwnerId::Signature(type_alias.into()),
2292        type_alias.into(),
2293        &generics,
2294        LifetimeElisionKind::AnonymousReportError,
2295        LifetimeLoweringMode::Bound,
2296    );
2297    let interner = ctx.interner;
2298
2299    let item_args = GenericArgs::identity_for_item(interner, type_alias.into());
2300    let interner_ty = Ty::new_projection_from_args(interner, type_alias.into(), item_args);
2301
2302    let mut bounds = Vec::new();
2303    let mut assoc_ty_bounds = Vec::new();
2304    for bound in &type_alias_data.bounds {
2305        ctx.lower_type_bound(bound, interner_ty, false).for_each(|(pred, source)| match source {
2306            GenericPredicateSource::SelfOnly => {
2307                bounds.push(pred);
2308            }
2309            GenericPredicateSource::AssocTyBound => {
2310                assoc_ty_bounds.push(pred);
2311            }
2312        });
2313    }
2314
2315    if let ItemContainerId::TraitId(parent_trait) = type_alias.loc(db).container {
2316        let item_trait_ref = TraitRef::identity(interner, parent_trait.into());
2317        let parent_predicates = GenericPredicates::query_explicit(db, parent_trait.into());
2318        parent_predicates.iter_identity().for_each(|parent_predicate| {
2319            let parent_predicate = parent_predicate.skip_norm_wip();
2320            let Some((predicate, source)) = remap_gat_vars_and_recurse_into_nested_projections(
2321                interner,
2322                item_trait_ref,
2323                type_alias,
2324                &generics,
2325                parent_predicate,
2326            ) else {
2327                return;
2328            };
2329            match source {
2330                GenericPredicateSource::SelfOnly => bounds.push(predicate),
2331                GenericPredicateSource::AssocTyBound => assoc_ty_bounds.push(predicate),
2332            }
2333        });
2334    }
2335
2336    if !ctx.unsized_types.contains(&interner_ty) {
2337        let sized_trait = ctx.lang_items.Sized;
2338        if let Some(sized_trait) = sized_trait {
2339            let trait_ref = TraitRef::new_from_args(
2340                interner,
2341                sized_trait.into(),
2342                GenericArgs::new_from_slice(&[interner_ty.into()]),
2343            );
2344            bounds.push(trait_ref.upcast(interner));
2345        };
2346    }
2347
2348    let assoc_ty_bounds_start = bounds.len() as u32;
2349    bounds.extend(assoc_ty_bounds);
2350
2351    TyLoweringResult::from_ctx(
2352        SelfAndAssocBounds {
2353            bounds: StoredEarlyBinder::bind(Clauses::new_from_slice(&bounds).store()),
2354            assoc_ty_bounds_start,
2355        },
2356        ctx,
2357    )
2358}
2359
2360/// The code below is quite involved, so let me explain.
2361///
2362/// We loop here, because we also want to collect vars for nested associated items as
2363/// well. For example, given a clause like `Self::A::B`, we want to add that to the
2364/// item bounds for `A`, so that we may use that bound in the case that `Self::A::B` is
2365/// rigid.
2366///
2367/// Secondly, regarding bound vars, when we see a where clause that mentions a GAT
2368/// like `for<'a, ...> Self::Assoc<'a, ...>: Bound<'b, ...>`, we want to turn that into
2369/// an item bound on the GAT, where all of the GAT args are substituted with the GAT's
2370/// param regions, and then keep all of the other late-bound vars in the bound around.
2371/// We need to "compress" the binder so that it doesn't mention any of those vars that
2372/// were mapped to params.
2373fn remap_gat_vars_and_recurse_into_nested_projections<'db>(
2374    interner: DbInterner<'db>,
2375    item_trait_ref: TraitRef<'db>,
2376    assoc_item_def_id: TypeAliasId,
2377    generics: &OnceCell<Generics<'db>>,
2378    clause: Clause<'db>,
2379) -> Option<(Clause<'db>, GenericPredicateSource)> {
2380    let mut clause_ty = match clause.kind().skip_binder() {
2381        ClauseKind::Trait(tr) => tr.self_ty(),
2382        ClauseKind::Projection(proj) => proj.projection_term.self_ty(),
2383        ClauseKind::TypeOutlives(outlives) => outlives.0,
2384        ClauseKind::HostEffect(host) => host.self_ty(),
2385        _ => return None,
2386    };
2387
2388    let mut predicate_source = GenericPredicateSource::SelfOnly;
2389    let gat_vars = loop {
2390        if let TyKind::Alias(
2391            alias_ty @ AliasTy { kind: AliasTyKind::Projection { def_id: alias_ty_def_id }, .. },
2392        ) = clause_ty.kind()
2393        {
2394            if alias_ty.trait_ref(interner) == item_trait_ref
2395                && alias_ty_def_id.0 == assoc_item_def_id
2396            {
2397                // We have found the GAT in question...
2398                // Return the vars, since we may need to remap them.
2399                break &alias_ty.args.as_slice()[item_trait_ref.args.len()..];
2400            } else {
2401                predicate_source = GenericPredicateSource::AssocTyBound;
2402
2403                clause_ty = alias_ty.self_ty();
2404                continue;
2405            }
2406        }
2407
2408        return None;
2409    };
2410
2411    // Special-case: No GAT vars, no mapping needed.
2412    if gat_vars.is_empty() {
2413        return Some((clause, predicate_source));
2414    }
2415
2416    // First, check that all of the GAT args are substituted with a unique late-bound arg.
2417    // If we find a duplicate, then it can't be mapped to the definition's params.
2418    let mut mapping = FxIndexMap::default();
2419    let generics = generics
2420        .get_or_init(|| crate::generics::generics(interner.db, assoc_item_def_id.into()))
2421        .owner();
2422    for ((param_idx, param, _), var) in std::iter::zip(generics.iter_with_idx(), gat_vars) {
2423        let existing = match var.kind() {
2424            GenericArgKind::Lifetime(re) => {
2425                let RegionKind::ReBound(BoundVarIndexKind::Bound(debruijn), bv) = re.kind() else {
2426                    return None;
2427                };
2428                if debruijn != rustc_type_ir::INNERMOST {
2429                    return None;
2430                }
2431                mapping.insert(bv.var, mk_param(interner, param_idx, param))
2432            }
2433            GenericArgKind::Type(ty) => {
2434                let TyKind::Bound(BoundVarIndexKind::Bound(debruijn), bv) = ty.kind() else {
2435                    return None;
2436                };
2437                if debruijn != rustc_type_ir::INNERMOST {
2438                    return None;
2439                }
2440                mapping.insert(bv.var, mk_param(interner, param_idx, param))
2441            }
2442            GenericArgKind::Const(ct) => {
2443                let ConstKind::Bound(BoundVarIndexKind::Bound(debruijn), bv) = ct.kind() else {
2444                    return None;
2445                };
2446                if debruijn != rustc_type_ir::INNERMOST {
2447                    return None;
2448                }
2449                mapping.insert(bv.var, mk_param(interner, param_idx, param))
2450            }
2451        };
2452
2453        if existing.is_some() {
2454            return None;
2455        }
2456    }
2457
2458    // Finally, map all of the args in the GAT to the params we expect, and compress
2459    // the remaining late-bound vars so that they count up from var 0.
2460    let mut folder = MapAndCompressBoundVars {
2461        tcx: interner,
2462        binder: rustc_type_ir::INNERMOST,
2463        still_bound_vars: vec![],
2464        mapping,
2465    };
2466    let pred = clause.kind().skip_binder().fold_with(&mut folder);
2467
2468    Some((
2469        Binder::bind_with_vars(pred, BoundVarKinds::new_from_slice(&folder.still_bound_vars))
2470            .upcast(interner),
2471        predicate_source,
2472    ))
2473}
2474
2475/// Given some where clause like `for<'b, 'c> <Self as Trait<'a_identity>>::Gat<'b>: Bound<'c>`,
2476/// the mapping will map `'b` back to the GAT's `'b_identity`. Then we need to compress the
2477/// remaining bound var `'c` to index 0.
2478///
2479/// This folder gives us: `for<'c> <Self as Trait<'a_identity>>::Gat<'b_identity>: Bound<'c>`,
2480/// which is sufficient for an item bound for `Gat`, since all of the GAT's args are identity.
2481struct MapAndCompressBoundVars<'db> {
2482    tcx: DbInterner<'db>,
2483    /// How deep are we? Makes sure we don't touch the vars of nested binders.
2484    binder: DebruijnIndex,
2485    /// List of bound vars that remain unsubstituted because they were not
2486    /// mentioned in the GAT's args.
2487    still_bound_vars: Vec<BoundVariableKind<'db>>,
2488    /// Subtle invariant: If the `GenericArg` is bound, then it should be
2489    /// stored with the debruijn index of `INNERMOST` so it can be shifted
2490    /// correctly during substitution.
2491    mapping: FxIndexMap<BoundVar, GenericArg<'db>>,
2492}
2493
2494impl<'db> TypeFolder<DbInterner<'db>> for MapAndCompressBoundVars<'db> {
2495    fn cx(&self) -> DbInterner<'db> {
2496        self.tcx
2497    }
2498
2499    fn fold_binder<T>(&mut self, t: Binder<'db, T>) -> Binder<'db, T>
2500    where
2501        Binder<'db, T>: TypeSuperFoldable<DbInterner<'db>>,
2502    {
2503        self.binder.shift_in(1);
2504        let out = t.super_fold_with(self);
2505        self.binder.shift_out(1);
2506        out
2507    }
2508
2509    fn fold_ty(&mut self, ty: Ty<'db>) -> Ty<'db> {
2510        if !ty.has_bound_vars() {
2511            return ty;
2512        }
2513
2514        if let TyKind::Bound(BoundVarIndexKind::Bound(binder), old_bound) = ty.kind()
2515            && self.binder == binder
2516        {
2517            let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
2518                mapped.expect_ty()
2519            } else {
2520                // If we didn't find a mapped generic, then make a new one.
2521                // Allocate a new var idx, and insert a new bound ty.
2522                let var = BoundVar::from_usize(self.still_bound_vars.len());
2523                self.still_bound_vars.push(BoundVariableKind::Ty(old_bound.kind));
2524                let mapped = Ty::new_bound(
2525                    self.tcx,
2526                    rustc_type_ir::INNERMOST,
2527                    BoundTy { var, kind: old_bound.kind },
2528                );
2529                self.mapping.insert(old_bound.var, mapped.into());
2530                mapped
2531            };
2532
2533            shift_vars(self.tcx, mapped, self.binder.as_u32())
2534        } else {
2535            ty.super_fold_with(self)
2536        }
2537    }
2538
2539    fn fold_region(&mut self, re: Region<'db>) -> Region<'db> {
2540        if let RegionKind::ReBound(BoundVarIndexKind::Bound(binder), old_bound) = re.kind()
2541            && self.binder == binder
2542        {
2543            let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
2544                mapped.expect_region()
2545            } else {
2546                let var = BoundVar::from_usize(self.still_bound_vars.len());
2547                self.still_bound_vars.push(BoundVariableKind::Region(old_bound.kind));
2548                let mapped = Region::new_bound(
2549                    self.tcx,
2550                    rustc_type_ir::INNERMOST,
2551                    BoundRegion { var, kind: old_bound.kind },
2552                );
2553                self.mapping.insert(old_bound.var, mapped.into());
2554                mapped
2555            };
2556
2557            shift_vars(self.tcx, mapped, self.binder.as_u32())
2558        } else {
2559            re
2560        }
2561    }
2562
2563    fn fold_const(&mut self, ct: Const<'db>) -> Const<'db> {
2564        if !ct.has_bound_vars() {
2565            return ct;
2566        }
2567
2568        if let ConstKind::Bound(BoundVarIndexKind::Bound(binder), old_bound) = ct.kind()
2569            && self.binder == binder
2570        {
2571            let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
2572                mapped.expect_const()
2573            } else {
2574                let var = BoundVar::from_usize(self.still_bound_vars.len());
2575                self.still_bound_vars.push(BoundVariableKind::Const);
2576                let mapped =
2577                    Const::new_bound(self.tcx, rustc_type_ir::INNERMOST, BoundConst::new(var));
2578                self.mapping.insert(old_bound.var, mapped.into());
2579                mapped
2580            };
2581
2582            shift_vars(self.tcx, mapped, self.binder.as_u32())
2583        } else {
2584            ct.super_fold_with(self)
2585        }
2586    }
2587
2588    fn fold_predicate(&mut self, p: Predicate<'db>) -> Predicate<'db> {
2589        if !p.has_bound_vars() { p } else { p.super_fold_with(self) }
2590    }
2591}
2592
2593#[derive(Debug, Clone, PartialEq, Eq, Hash, SalsaValue)]
2594pub struct GenericPredicates {
2595    // The order is the following:
2596    //
2597    // 1. If `has_trait_implied_predicate == true`, the implicit trait predicate.
2598    // 2. The explicit, self-only predicates for the parent.
2599    // 3. The bounds of the associated types of the parents, coming from `Trait<Assoc: Trait>`.
2600    //    Note: associated type bounds from `Self::Assoc: Trait` on traits *won't* be included
2601    //    here, they are in 3.
2602    // 4. The explicit, self-only trait predicate for the child,
2603    // 5. The bounds of the associated types of the child.
2604    predicates: StoredEarlyBinder<StoredClauses>,
2605    // Keep this ordered according to the above.
2606    has_trait_implied_predicate: bool,
2607    parent_assoc_ty_bounds_start: u32,
2608    own_predicates_start: u32,
2609    own_assoc_ty_bounds_start: u32,
2610}
2611
2612#[salsa::tracked]
2613impl<'db> GenericPredicates {
2614    /// Resolve the where clause(s) of an item with generics.
2615    ///
2616    /// Diagnostics are computed only for this item's predicates, not for parents.
2617    #[salsa::tracked(returns(ref), cycle_result=generic_predicates_cycle_result)]
2618    pub fn query_with_diagnostics(
2619        db: &'db dyn HirDatabase,
2620        def: GenericDefId,
2621    ) -> TyLoweringResult<'db, GenericPredicates> {
2622        generic_predicates(db, def)
2623    }
2624}
2625
2626/// A cycle can occur from malformed code.
2627fn generic_predicates_cycle_result<'db>(
2628    _db: &'db dyn HirDatabase,
2629    _: salsa::Id,
2630    _def: GenericDefId,
2631) -> TyLoweringResult<'db, GenericPredicates> {
2632    TyLoweringResult::empty(GenericPredicates::from_explicit_own_predicates(
2633        StoredEarlyBinder::bind(Clauses::empty().store()),
2634    ))
2635}
2636
2637impl GenericPredicates {
2638    #[inline]
2639    pub fn empty() -> &'static GenericPredicates {
2640        static EMPTY: OnceLock<GenericPredicates> = OnceLock::new();
2641        EMPTY.get_or_init(|| GenericPredicates {
2642            predicates: StoredEarlyBinder::bind(Clauses::default().store()),
2643            has_trait_implied_predicate: false,
2644            parent_assoc_ty_bounds_start: 0,
2645            own_predicates_start: 0,
2646            own_assoc_ty_bounds_start: 0,
2647        })
2648    }
2649
2650    #[inline]
2651    pub(crate) fn from_explicit_own_predicates(
2652        predicates: StoredEarlyBinder<StoredClauses>,
2653    ) -> Self {
2654        let len = predicates.get().skip_binder().len() as u32;
2655        Self {
2656            predicates,
2657            has_trait_implied_predicate: false,
2658            parent_assoc_ty_bounds_start: 0,
2659            own_predicates_start: 0,
2660            own_assoc_ty_bounds_start: len,
2661        }
2662    }
2663
2664    #[inline]
2665    pub fn query(db: &dyn HirDatabase, def: GenericDefId) -> &GenericPredicates {
2666        &Self::query_with_diagnostics(db, def).value
2667    }
2668
2669    #[inline]
2670    pub fn query_all<'db>(
2671        db: &'db dyn HirDatabase,
2672        def: GenericDefId,
2673    ) -> EarlyBinder<'db, impl Iterator<Item = Clause<'db>>> {
2674        Self::query(db, def).all_predicates()
2675    }
2676
2677    #[inline]
2678    pub fn query_own_explicit<'db>(
2679        db: &'db dyn HirDatabase,
2680        def: GenericDefId,
2681    ) -> EarlyBinder<'db, impl Iterator<Item = Clause<'db>>> {
2682        Self::query(db, def).own_explicit_predicates()
2683    }
2684
2685    #[inline]
2686    pub fn query_explicit<'db>(
2687        db: &'db dyn HirDatabase,
2688        def: GenericDefId,
2689    ) -> EarlyBinder<'db, impl Iterator<Item = Clause<'db>>> {
2690        Self::query(db, def).explicit_predicates()
2691    }
2692
2693    #[inline]
2694    pub fn all_predicates(&self) -> EarlyBinder<'_, impl Iterator<Item = Clause<'_>>> {
2695        self.predicates.get().map_bound(|it| it.as_slice().iter().copied())
2696    }
2697
2698    #[inline]
2699    pub fn own_explicit_predicates(&self) -> EarlyBinder<'_, impl Iterator<Item = Clause<'_>>> {
2700        self.predicates
2701            .get()
2702            .map_bound(|it| it.as_slice()[self.own_predicates_start as usize..].iter().copied())
2703    }
2704
2705    #[inline]
2706    pub fn explicit_predicates(&self) -> EarlyBinder<'_, impl Iterator<Item = Clause<'_>>> {
2707        self.predicates.get().map_bound(|it| {
2708            it.as_slice()[usize::from(self.has_trait_implied_predicate)..].iter().copied()
2709        })
2710    }
2711
2712    #[inline]
2713    pub fn explicit_non_assoc_types_predicates(
2714        &self,
2715    ) -> EarlyBinder<'_, impl Iterator<Item = Clause<'_>>> {
2716        self.predicates.get().map_bound(|it| {
2717            std::iter::chain(
2718                it.as_slice()[usize::from(self.has_trait_implied_predicate)
2719                    ..self.parent_assoc_ty_bounds_start as usize]
2720                    .iter()
2721                    .copied(),
2722                it.as_slice()
2723                    [self.own_predicates_start as usize..self.own_assoc_ty_bounds_start as usize]
2724                    .iter()
2725                    .copied(),
2726            )
2727        })
2728    }
2729
2730    #[inline]
2731    pub fn explicit_assoc_types_predicates(
2732        &self,
2733    ) -> EarlyBinder<'_, impl Iterator<Item = Clause<'_>>> {
2734        self.predicates.get().map_bound(|it| {
2735            std::iter::chain(
2736                it.as_slice()[self.parent_assoc_ty_bounds_start as usize
2737                    ..self.own_predicates_start as usize]
2738                    .iter()
2739                    .copied(),
2740                it.as_slice()[self.own_assoc_ty_bounds_start as usize..].iter().copied(),
2741            )
2742        })
2743    }
2744}
2745
2746pub(crate) fn param_env_from_predicates<'db>(
2747    interner: DbInterner<'db>,
2748    predicates: &'db GenericPredicates,
2749) -> ParamEnv<'db> {
2750    let clauses = rustc_type_ir::elaborate::elaborate(
2751        interner,
2752        predicates.all_predicates().iter_identity().map(Unnormalized::skip_norm_wip),
2753    );
2754    let clauses = Clauses::new_from_iter(clauses);
2755
2756    // FIXME: We should normalize projections here, like rustc does.
2757    ParamEnv { clauses }
2758}
2759
2760pub(crate) fn trait_environment<'db>(db: &'db dyn HirDatabase, def: GenericDefId) -> ParamEnv<'db> {
2761    return ParamEnv { clauses: trait_environment_query(db, def).as_ref() };
2762
2763    #[salsa::tracked(returns(ref))]
2764    pub(crate) fn trait_environment_query(
2765        db: &dyn HirDatabase,
2766        def: GenericDefId,
2767    ) -> StoredClauses {
2768        let module = def.module(db);
2769        let interner = DbInterner::new_with(db, module.krate(db));
2770        let predicates = GenericPredicates::query(db, def);
2771        param_env_from_predicates(interner, predicates).clauses.store()
2772    }
2773}
2774
2775/// Resolve the where clause(s) of an item with generics,
2776/// with a given filter
2777#[tracing::instrument(skip(db), ret)]
2778fn generic_predicates<'db>(
2779    db: &'db dyn HirDatabase,
2780    def: GenericDefId,
2781) -> TyLoweringResult<'db, GenericPredicates> {
2782    let generics = generics(db, def);
2783    let store = generics.store();
2784    let generics = &OnceCell::from(generics);
2785    let resolver = def.resolver(db);
2786    let interner = DbInterner::new_no_crate(db);
2787    let mut ctx = TyLoweringContext::new(
2788        db,
2789        &resolver,
2790        store,
2791        ExpressionStoreOwnerId::Signature(def),
2792        def,
2793        generics,
2794        LifetimeElisionKind::AnonymousReportError,
2795        LifetimeLoweringMode::Bound,
2796    );
2797    let generics = generics.get().unwrap();
2798    let sized_trait = ctx.lang_items.Sized;
2799    let myself = generics.owner();
2800
2801    let mut own_predicates = Vec::new();
2802    let mut own_assoc_ty_bounds = Vec::new();
2803    let own_implicit_trait_predicate = implicit_trait_predicate(interner, def);
2804    let parent = if let Some(parent) = generics.parent() {
2805        &GenericPredicates::query_with_diagnostics(db, parent.def()).value
2806    } else {
2807        GenericPredicates::empty()
2808    };
2809
2810    let generics = myself;
2811
2812    for pred in generics.where_predicates() {
2813        tracing::debug!(?pred);
2814        for (pred, source) in ctx.lower_where_predicate(pred, false) {
2815            match source {
2816                GenericPredicateSource::SelfOnly => own_predicates.push(pred),
2817                GenericPredicateSource::AssocTyBound => own_assoc_ty_bounds.push(pred),
2818            }
2819        }
2820    }
2821
2822    push_const_arg_has_type_predicates(db, &mut own_predicates, generics);
2823
2824    if let Some(sized_trait) = sized_trait {
2825        let mut add_sized_clause = |param_idx, param_id, param_data| {
2826            let (
2827                GenericParamId::TypeParamId(param_id),
2828                GenericParamDataRef::TypeParamData(param_data),
2829            ) = (param_id, param_data)
2830            else {
2831                return;
2832            };
2833
2834            if param_data.provenance == TypeParamProvenance::TraitSelf {
2835                return;
2836            }
2837
2838            let param_ty = Ty::new_param(interner, param_id, param_idx);
2839            if ctx.unsized_types.contains(&param_ty) {
2840                return;
2841            }
2842            let trait_ref = TraitRef::new_from_args(
2843                interner,
2844                sized_trait.into(),
2845                GenericArgs::new_from_slice(&[param_ty.into()]),
2846            );
2847            let clause = Clause(Predicate::new(
2848                interner,
2849                Binder::dummy(rustc_type_ir::PredicateKind::Clause(
2850                    rustc_type_ir::ClauseKind::Trait(TraitPredicate {
2851                        trait_ref,
2852                        polarity: rustc_type_ir::PredicatePolarity::Positive,
2853                    }),
2854                )),
2855            ));
2856            own_predicates.push(clause);
2857        };
2858        generics.iter_with_idx().for_each(|(param_idx, param_id, param_data)| {
2859            add_sized_clause(param_idx, param_id, param_data);
2860        });
2861    }
2862
2863    let diagnostics = mem::take(&mut ctx.diagnostics);
2864    let defined_anon_consts = mem::take(&mut ctx.defined_anon_consts);
2865
2866    let parent_predicates = parent.predicates.get().skip_binder().as_slice();
2867    let predicates = parent_predicates
2868        .iter()
2869        .chain(own_implicit_trait_predicate.iter())
2870        .chain(own_predicates.iter())
2871        .chain(own_assoc_ty_bounds.iter())
2872        .copied()
2873        .collect::<Vec<_>>();
2874    let has_trait_implied_predicate =
2875        parent.has_trait_implied_predicate || own_implicit_trait_predicate.is_some();
2876    let parent_assoc_ty_bounds_start =
2877        parent.own_assoc_ty_bounds_start + u32::from(own_implicit_trait_predicate.is_some());
2878    let own_predicates_start =
2879        parent_predicates.len() as u32 + u32::from(own_implicit_trait_predicate.is_some());
2880    let own_assoc_ty_bounds_start = own_predicates_start + own_predicates.len() as u32;
2881
2882    let predicates = GenericPredicates {
2883        has_trait_implied_predicate,
2884        parent_assoc_ty_bounds_start,
2885        own_predicates_start,
2886        own_assoc_ty_bounds_start,
2887        predicates: StoredEarlyBinder::bind(Clauses::new_from_slice(&predicates).store()),
2888    };
2889    return TyLoweringResult::new(predicates, diagnostics, defined_anon_consts);
2890
2891    fn implicit_trait_predicate<'db>(
2892        interner: DbInterner<'db>,
2893        def: GenericDefId,
2894    ) -> Option<Clause<'db>> {
2895        // For traits, add `Self: Trait` predicate. This is
2896        // not part of the predicates that a user writes, but it
2897        // is something that one must prove in order to invoke a
2898        // method or project an associated type.
2899        //
2900        // In the chalk setup, this predicate is not part of the
2901        // "predicates" for a trait item. But it is useful in
2902        // rustc because if you directly (e.g.) invoke a trait
2903        // method like `Trait::method(...)`, you must naturally
2904        // prove that the trait applies to the types that were
2905        // used, and adding the predicate into this list ensures
2906        // that this is done.
2907        if let GenericDefId::TraitId(def_id) = def {
2908            Some(TraitRef::identity(interner, def_id.into()).upcast(interner))
2909        } else {
2910            None
2911        }
2912    }
2913}
2914
2915fn push_const_arg_has_type_predicates<'db>(
2916    db: &'db dyn HirDatabase,
2917    predicates: &mut Vec<Clause<'db>>,
2918    generics: &SingleGenerics<'db>,
2919) {
2920    let mut const_param_tys = None;
2921    let interner = DbInterner::new_no_crate(db);
2922    generics.iter_with_idx().for_each(|(param_index, param_id, _)| {
2923        let GenericParamId::ConstParamId(param_id) = param_id else { return };
2924
2925        let const_param_tys =
2926            *const_param_tys.get_or_insert_with(|| const_param_types(db, generics.def()));
2927        predicates.push(Clause(
2928            ClauseKind::ConstArgHasType(
2929                Const::new_param(interner, ParamConst { id: param_id, index: param_index }),
2930                const_param_tys.get(param_id.local_id()),
2931            )
2932            .upcast(interner),
2933        ));
2934    });
2935}
2936
2937#[derive(Debug, Clone, PartialEq, Eq, Hash, SalsaValue)]
2938pub struct GenericDefaults(ThinVec<Option<StoredEarlyBinder<StoredGenericArg>>>);
2939
2940impl GenericDefaults {
2941    #[inline]
2942    pub fn as_ref(&self) -> GenericDefaultsRef<'_> {
2943        GenericDefaultsRef(&self.0)
2944    }
2945
2946    fn push(&mut self, index: usize, default: StoredEarlyBinder<StoredGenericArg>) {
2947        self.0.extend((0..index - self.0.len()).map(|_| None));
2948        self.0.push(Some(default));
2949    }
2950}
2951
2952#[derive(Debug, Clone, Copy)]
2953pub struct GenericDefaultsRef<'db>(&'db [Option<StoredEarlyBinder<StoredGenericArg>>]);
2954
2955impl<'db> GenericDefaultsRef<'db> {
2956    #[inline]
2957    pub fn get(self, idx: usize) -> Option<EarlyBinder<'db, GenericArg<'db>>> {
2958        Some(self.0.get(idx)?.as_ref()?.get())
2959    }
2960}
2961
2962pub(crate) fn generic_defaults(db: &dyn HirDatabase, def: GenericDefId) -> GenericDefaultsRef<'_> {
2963    generic_defaults_with_diagnostics(db, def).value.as_ref()
2964}
2965
2966/// Resolve the default type params from generics.
2967///
2968/// Diagnostics are only returned for this `GenericDefId` (returned defaults include parents).
2969#[salsa::tracked(returns(ref), cycle_result = generic_defaults_with_diagnostics_cycle_result)]
2970pub(crate) fn generic_defaults_with_diagnostics<'db>(
2971    db: &'db dyn HirDatabase,
2972    def: GenericDefId,
2973) -> TyLoweringResult<'db, GenericDefaults> {
2974    let generics = generics(db, def);
2975    if generics.has_no_params() {
2976        return TyLoweringResult::empty(GenericDefaults(ThinVec::new()));
2977    }
2978    let resolver = def.resolver(db);
2979
2980    let store_for_self = generics.store();
2981    let generics = &OnceCell::from(generics);
2982    let mut ctx = TyLoweringContext::new(
2983        db,
2984        &resolver,
2985        store_for_self,
2986        ExpressionStoreOwnerId::Signature(def),
2987        def,
2988        generics,
2989        LifetimeElisionKind::AnonymousReportError,
2990        LifetimeLoweringMode::Bound,
2991    )
2992    .with_impl_trait_mode(ImplTraitLoweringMode::Disallowed);
2993    let generics = generics.get().unwrap();
2994
2995    let mut defaults = if let Some(parent) = generics.parent() {
2996        generic_defaults_with_diagnostics(db, parent.def()).value.clone()
2997    } else {
2998        GenericDefaults(ThinVec::new())
2999    };
3000
3001    generics
3002        .iter_self_with_idx()
3003        .filter_map(|(idx, _id, p)| Some((idx as usize, handle_generic_param(&mut ctx, idx, p)?)))
3004        .for_each(|(idx, default)| defaults.push(idx, default));
3005    defaults.0.shrink_to_fit();
3006    return TyLoweringResult::from_ctx(defaults, ctx);
3007
3008    fn handle_generic_param<'db>(
3009        ctx: &mut TyLoweringContext<'db, '_>,
3010        idx: u32,
3011        p: GenericParamDataRef<'_>,
3012    ) -> Option<StoredEarlyBinder<StoredGenericArg>> {
3013        ctx.forbid_params_after(idx, ForbidParamsAfterReason::LoweringParamDefault);
3014        match p {
3015            GenericParamDataRef::TypeParamData(p) => {
3016                let ty = p.default.map(|ty| ctx.lower_ty(ty));
3017                ty.map(|ty| StoredEarlyBinder::bind(GenericArg::from(ty).store()))
3018            }
3019            GenericParamDataRef::ConstParamData(p) => {
3020                let val = p.default.map(|c| {
3021                    let param_ty = ctx.lower_ty(p.ty);
3022                    let c = ctx.lower_const(c, param_ty, false);
3023                    GenericArg::from(c).store()
3024                });
3025                val.map(StoredEarlyBinder::bind)
3026            }
3027            GenericParamDataRef::LifetimeParamData(_) => None,
3028        }
3029    }
3030}
3031
3032fn generic_defaults_with_diagnostics_cycle_result<'db>(
3033    _db: &'db dyn HirDatabase,
3034    _: salsa::Id,
3035    _def: GenericDefId,
3036) -> TyLoweringResult<'db, GenericDefaults> {
3037    TyLoweringResult::empty(GenericDefaults(ThinVec::new()))
3038}
3039
3040/// Build the signature of a callable item (function, struct or enum variant).
3041pub(crate) fn callable_item_signature<'db>(
3042    db: &'db dyn HirDatabase,
3043    def: CallableDefId,
3044) -> EarlyBinder<'db, PolyFnSig<'db>> {
3045    match def {
3046        CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f).value.value.get(),
3047        CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s).get(),
3048        CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e).get(),
3049    }
3050}
3051
3052#[salsa::tracked(returns(ref))]
3053pub(crate) fn fn_sig_for_fn<'db>(
3054    db: &'db dyn HirDatabase,
3055    def: FunctionId,
3056) -> TyLoweringResult<'db, WithDefinedOpaques<StoredEarlyBinder<StoredPolyFnSig>>> {
3057    let data = FunctionSignature::of(db, def);
3058    let resolver = def.resolver(db);
3059    let interner = DbInterner::new_no_crate(db);
3060    let generics = OnceCell::new();
3061    let mut ctx_params = TyLoweringContext::new(
3062        db,
3063        &resolver,
3064        &data.store,
3065        ExpressionStoreOwnerId::Signature(def.into()),
3066        def.into(),
3067        &generics,
3068        LifetimeElisionKind::for_fn_params(data),
3069        LifetimeLoweringMode::Bound,
3070    );
3071    let params = data.params.iter().map(|&tr| ctx_params.lower_ty(tr));
3072
3073    let mut ctx_ret = TyLoweringContext::new(
3074        db,
3075        &resolver,
3076        &data.store,
3077        ExpressionStoreOwnerId::Signature(def.into()),
3078        def.into(),
3079        &generics,
3080        LifetimeElisionKind::for_fn_ret(interner),
3081        LifetimeLoweringMode::Bound,
3082    )
3083    .with_impl_trait_mode(ImplTraitLoweringMode::Opaque);
3084    let ret = match data.ret_type {
3085        Some(ret_type) => ctx_ret.lower_ty(ret_type),
3086        None => Ty::new_unit(interner),
3087    };
3088    let impl_traits = ctx_ret.take_defined_opaques();
3089
3090    let inputs_and_output = Tys::new_from_iter(params.chain(Some(ret)));
3091    ctx_params.diagnostics.extend(ctx_ret.diagnostics);
3092    ctx_params.defined_anon_consts.extend(ctx_ret.defined_anon_consts);
3093
3094    let binder = TyLoweringContext::bound_vars(db, def.into(), &generics);
3095    let result = StoredEarlyBinder::bind(StoredPolyFnSig::new(Binder::bind_with_vars(
3096        FnSig {
3097            inputs_and_output,
3098            fn_sig_kind: FnSigKind::new(
3099                data.abi,
3100                if data.is_unsafe() { Safety::Unsafe } else { Safety::Safe },
3101                data.is_varargs(),
3102            ),
3103        },
3104        binder,
3105    )));
3106    TyLoweringResult::from_ctx(WithDefinedOpaques { value: result, impl_traits }, ctx_params)
3107}
3108
3109fn type_for_adt<'db>(db: &'db dyn HirDatabase, adt: AdtId) -> EarlyBinder<'db, Ty<'db>> {
3110    let interner = DbInterner::new_no_crate(db);
3111    let args = GenericArgs::identity_for_item(interner, adt.into());
3112    let ty = Ty::new_adt(interner, adt, args);
3113    EarlyBinder::bind(ty)
3114}
3115
3116fn ctor_signature(
3117    db: &dyn HirDatabase,
3118    variant: VariantId,
3119    adt: AdtId,
3120) -> StoredEarlyBinder<StoredPolyFnSig> {
3121    let field_tys = db.field_types(variant);
3122    let params = field_tys.iter().map(|(_, field)| field.ty().skip_binder());
3123    let ret = type_for_adt(db, adt).skip_binder();
3124
3125    let inputs_and_output = Tys::new_from_iter(params.chain(Some(ret)));
3126    StoredEarlyBinder::bind(StoredPolyFnSig::new(Binder::dummy(FnSig {
3127        fn_sig_kind: FnSigKind::new(ExternAbi::Rust, Safety::Safe, false),
3128        inputs_and_output,
3129    })))
3130}
3131
3132#[salsa::tracked(returns(ref))]
3133fn fn_sig_for_struct_constructor(
3134    db: &dyn HirDatabase,
3135    def: StructId,
3136) -> StoredEarlyBinder<StoredPolyFnSig> {
3137    ctor_signature(db, def.into(), def.into())
3138}
3139
3140#[salsa::tracked(returns(ref))]
3141fn fn_sig_for_enum_variant_constructor(
3142    db: &dyn HirDatabase,
3143    def: EnumVariantId,
3144) -> StoredEarlyBinder<StoredPolyFnSig> {
3145    ctor_signature(db, def.into(), def.lookup(db).parent.into())
3146}
3147
3148pub(crate) fn associated_type_by_name_including_super_traits_allow_ambiguity<'db>(
3149    db: &'db dyn HirDatabase,
3150    trait_ref: TraitRef<'db>,
3151    name: Name,
3152) -> Option<(TypeAliasId, GenericArgs<'db>)> {
3153    let (AssocTypeShorthandResolution::Resolved(assoc_type)
3154    | AssocTypeShorthandResolution::Ambiguous { sub_trait_resolution: Some(assoc_type) }) =
3155        resolve_type_param_assoc_type_shorthand(
3156            db,
3157            trait_ref.def_id.0.into(),
3158            TypeParamId::trait_self(trait_ref.def_id.0),
3159            name.clone(),
3160        )
3161    else {
3162        return None;
3163    };
3164    let (assoc_type, trait_args) = assoc_type
3165        .get_with(|(assoc_type, trait_args)| (*assoc_type, trait_args.as_ref()))
3166        .skip_binder();
3167    let interner = DbInterner::new_no_crate(db);
3168    Some((
3169        assoc_type,
3170        EarlyBinder::bind(trait_args).instantiate(interner, trait_ref.args).skip_norm_wip(),
3171    ))
3172}