Skip to main content

hir_ty/next_solver/
generic_arg.rs

1//! Things related to generic args in the next-trait-solver (`GenericArg`, `GenericArgs`, `Term`).
2//!
3//! Implementations of `GenericArg` and `Term` are pointer-tagged instead of an enum (rustc does
4//! the same). This is done to save memory (which also helps speed) - one `GenericArg` is a machine
5//! word instead of two, while matching on it is basically as cheap. The implementation for both
6//! `GenericArg` and `Term` is shared in [`GenericArgImpl`]. This both simplifies the implementation,
7//! as well as enables a noop conversion from `Term` to `GenericArg`.
8
9use std::{hint::unreachable_unchecked, marker::PhantomData, ptr::NonNull};
10
11use arrayvec::ArrayVec;
12use hir_def::{GenericDefId, GenericParamId, hir::generics::LifetimeParamData};
13use intern::InternedRef;
14use rustc_type_ir::{
15    ClosureArgs, ConstVid, CoroutineArgs, CoroutineClosureArgs, FallibleTypeFolder,
16    GenericTypeVisitable, Interner, TyVid, TypeFoldable, TypeFolder, TypeVisitable, TypeVisitor,
17    Variance,
18    inherent::{GenericArg as _, GenericsOf, IntoKind, SliceLike, Term as _, Ty as _},
19    relate::{Relate, VarianceDiagInfo},
20    walk::TypeWalker,
21};
22
23use crate::next_solver::{
24    ConstInterned, RegionInterned, TyInterned, impl_foldable_for_interned_slice,
25    impl_foldable_for_stored_type, interned_slice,
26};
27
28use super::{
29    Const, DbInterner, EarlyParamRegion, ErrorGuaranteed, ParamConst, Region, SolverDefId, Ty,
30    generics::Generics,
31};
32
33pub type GenericArgKind<'db> = rustc_type_ir::GenericArgKind<DbInterner<'db>>;
34pub type TermKind<'db> = rustc_type_ir::TermKind<DbInterner<'db>>;
35
36#[derive(Clone, Copy, PartialEq, Eq, Hash)]
37struct GenericArgImpl<'db> {
38    /// # Invariant
39    ///
40    /// Contains an [`InternedRef`] of a [`Ty`], [`Const`] or [`Region`], bit-tagged as per the consts below.
41    ptr: NonNull<()>,
42    _marker: PhantomData<(Ty<'db>, Const<'db>, Region<'db>)>,
43}
44
45// SAFETY: We essentially own the `Ty`, `Const` or `Region`, and they are `Send + Sync`.
46unsafe impl Send for GenericArgImpl<'_> {}
47unsafe impl Sync for GenericArgImpl<'_> {}
48
49impl<'db> GenericArgImpl<'db> {
50    const KIND_MASK: usize = 0b11;
51    const PTR_MASK: usize = !Self::KIND_MASK;
52    const TY_TAG: usize = 0b00;
53    const CONST_TAG: usize = 0b01;
54    const REGION_TAG: usize = 0b10;
55
56    #[inline]
57    fn new_ty(ty: Ty<'db>) -> Self {
58        Self {
59            // SAFETY: We create it from an `InternedRef`, and it's never null.
60            ptr: unsafe {
61                NonNull::new_unchecked(
62                    ty.interned
63                        .as_raw()
64                        .cast::<()>()
65                        .cast_mut()
66                        .map_addr(|addr| addr | Self::TY_TAG),
67                )
68            },
69            _marker: PhantomData,
70        }
71    }
72
73    #[inline]
74    fn new_const(ty: Const<'db>) -> Self {
75        Self {
76            // SAFETY: We create it from an `InternedRef`, and it's never null.
77            ptr: unsafe {
78                NonNull::new_unchecked(
79                    ty.interned
80                        .as_raw()
81                        .cast::<()>()
82                        .cast_mut()
83                        .map_addr(|addr| addr | Self::CONST_TAG),
84                )
85            },
86            _marker: PhantomData,
87        }
88    }
89
90    #[inline]
91    fn new_region(ty: Region<'db>) -> Self {
92        Self {
93            // SAFETY: We create it from an `InternedRef`, and it's never null.
94            ptr: unsafe {
95                NonNull::new_unchecked(
96                    ty.interned
97                        .as_raw()
98                        .cast::<()>()
99                        .cast_mut()
100                        .map_addr(|addr| addr | Self::REGION_TAG),
101                )
102            },
103            _marker: PhantomData,
104        }
105    }
106
107    #[inline]
108    fn kind(self) -> GenericArgKind<'db> {
109        let ptr = self.ptr.as_ptr().map_addr(|addr| addr & Self::PTR_MASK);
110        // SAFETY: We can only be created from a `Ty`, a `Const` or a `Region`, and the tag will match.
111        unsafe {
112            match self.ptr.addr().get() & Self::KIND_MASK {
113                Self::TY_TAG => GenericArgKind::Type(Ty {
114                    interned: InternedRef::from_raw(ptr.cast::<TyInterned>()),
115                }),
116                Self::CONST_TAG => GenericArgKind::Const(Const {
117                    interned: InternedRef::from_raw(ptr.cast::<ConstInterned>()),
118                }),
119                Self::REGION_TAG => GenericArgKind::Lifetime(Region {
120                    interned: InternedRef::from_raw(ptr.cast::<RegionInterned>()),
121                }),
122                _ => unreachable_unchecked(),
123            }
124        }
125    }
126
127    #[inline]
128    fn term_kind(self) -> TermKind<'db> {
129        let ptr = self.ptr.as_ptr().map_addr(|addr| addr & Self::PTR_MASK);
130        // SAFETY: We can only be created from a `Ty`, a `Const` or a `Region`, and the tag will match.
131        // It is the caller's responsibility (encapsulated within this module) to only call this with
132        // `Term`, which cannot be constructed from a `Region`.
133        unsafe {
134            match self.ptr.addr().get() & Self::KIND_MASK {
135                Self::TY_TAG => {
136                    TermKind::Ty(Ty { interned: InternedRef::from_raw(ptr.cast::<TyInterned>()) })
137                }
138                Self::CONST_TAG => TermKind::Const(Const {
139                    interned: InternedRef::from_raw(ptr.cast::<ConstInterned>()),
140                }),
141                _ => unreachable_unchecked(),
142            }
143        }
144    }
145}
146
147#[derive(PartialEq, Eq, Hash)]
148pub struct StoredGenericArg {
149    ptr: GenericArgImpl<'static>,
150}
151
152impl Clone for StoredGenericArg {
153    #[inline]
154    fn clone(&self) -> Self {
155        match self.ptr.kind() {
156            GenericArgKind::Lifetime(it) => std::mem::forget(it.interned.to_owned()),
157            GenericArgKind::Type(it) => std::mem::forget(it.interned.to_owned()),
158            GenericArgKind::Const(it) => std::mem::forget(it.interned.to_owned()),
159        }
160        Self { ptr: self.ptr }
161    }
162}
163
164impl Drop for StoredGenericArg {
165    #[inline]
166    fn drop(&mut self) {
167        unsafe {
168            match self.ptr.kind() {
169                GenericArgKind::Lifetime(it) => it.interned.decrement_refcount(),
170                GenericArgKind::Type(it) => it.interned.decrement_refcount(),
171                GenericArgKind::Const(it) => it.interned.decrement_refcount(),
172            }
173        }
174    }
175}
176
177impl StoredGenericArg {
178    #[inline]
179    fn new(value: GenericArg<'_>) -> Self {
180        let result = Self { ptr: GenericArgImpl { ptr: value.ptr.ptr, _marker: PhantomData } };
181        // Increase refcount.
182        std::mem::forget(result.clone());
183        result
184    }
185
186    #[inline]
187    pub fn as_ref<'db>(&self) -> GenericArg<'db> {
188        GenericArg { ptr: self.ptr }
189    }
190}
191
192impl std::fmt::Debug for StoredGenericArg {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        self.as_ref().fmt(f)
195    }
196}
197
198impl_foldable_for_stored_type!(StoredGenericArg);
199
200#[derive(Copy, Clone, PartialEq, Eq, Hash)]
201pub struct GenericArg<'db> {
202    ptr: GenericArgImpl<'db>,
203}
204
205impl<'db> std::fmt::Debug for GenericArg<'db> {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        match self.kind() {
208            GenericArgKind::Type(t) => std::fmt::Debug::fmt(&t, f),
209            GenericArgKind::Lifetime(r) => std::fmt::Debug::fmt(&r, f),
210            GenericArgKind::Const(c) => std::fmt::Debug::fmt(&c, f),
211        }
212    }
213}
214
215impl<'db> GenericArg<'db> {
216    #[inline]
217    pub fn store(self) -> StoredGenericArg {
218        StoredGenericArg::new(self)
219    }
220
221    #[inline]
222    pub fn kind(self) -> GenericArgKind<'db> {
223        self.ptr.kind()
224    }
225
226    pub fn ty(self) -> Option<Ty<'db>> {
227        match self.kind() {
228            GenericArgKind::Type(ty) => Some(ty),
229            _ => None,
230        }
231    }
232
233    pub fn expect_ty(self) -> Ty<'db> {
234        match self.kind() {
235            GenericArgKind::Type(ty) => ty,
236            _ => panic!("Expected ty, got {self:?}"),
237        }
238    }
239
240    pub fn konst(self) -> Option<Const<'db>> {
241        match self.kind() {
242            GenericArgKind::Const(konst) => Some(konst),
243            _ => None,
244        }
245    }
246
247    pub fn region(self) -> Option<Region<'db>> {
248        match self.kind() {
249            GenericArgKind::Lifetime(r) => Some(r),
250            _ => None,
251        }
252    }
253
254    #[inline]
255    pub(crate) fn expect_region(self) -> Region<'db> {
256        match self.kind() {
257            GenericArgKind::Lifetime(region) => region,
258            _ => panic!("expected a region, got {self:?}"),
259        }
260    }
261
262    pub fn error_from_id(interner: DbInterner<'db>, id: GenericParamId) -> GenericArg<'db> {
263        match id {
264            GenericParamId::TypeParamId(_) => Ty::new_error(interner, ErrorGuaranteed).into(),
265            GenericParamId::ConstParamId(_) => Const::error(interner).into(),
266            GenericParamId::LifetimeParamId(_) => Region::error(interner).into(),
267        }
268    }
269
270    #[inline]
271    pub fn walk(self) -> TypeWalker<DbInterner<'db>> {
272        TypeWalker::new(self)
273    }
274}
275
276impl<'db> From<Term<'db>> for GenericArg<'db> {
277    #[inline]
278    fn from(value: Term<'db>) -> Self {
279        GenericArg { ptr: value.ptr }
280    }
281}
282
283#[derive(PartialEq, Eq, Hash)]
284pub struct StoredTerm {
285    ptr: GenericArgImpl<'static>,
286}
287
288impl Clone for StoredTerm {
289    #[inline]
290    fn clone(&self) -> Self {
291        match self.ptr.term_kind() {
292            TermKind::Ty(it) => std::mem::forget(it.interned.to_owned()),
293            TermKind::Const(it) => std::mem::forget(it.interned.to_owned()),
294        }
295        Self { ptr: self.ptr }
296    }
297}
298
299impl Drop for StoredTerm {
300    #[inline]
301    fn drop(&mut self) {
302        unsafe {
303            match self.ptr.term_kind() {
304                TermKind::Ty(it) => it.interned.decrement_refcount(),
305                TermKind::Const(it) => it.interned.decrement_refcount(),
306            }
307        }
308    }
309}
310
311impl StoredTerm {
312    #[inline]
313    fn new(value: Term<'_>) -> Self {
314        let result = Self { ptr: GenericArgImpl { ptr: value.ptr.ptr, _marker: PhantomData } };
315        // Increase refcount.
316        std::mem::forget(result.clone());
317        result
318    }
319
320    #[inline]
321    pub fn as_ref<'db>(&self) -> Term<'db> {
322        Term { ptr: self.ptr }
323    }
324}
325
326impl std::fmt::Debug for StoredTerm {
327    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328        self.as_ref().fmt(f)
329    }
330}
331
332impl_foldable_for_stored_type!(StoredTerm);
333
334#[derive(Copy, Clone, PartialEq, Eq, Hash)]
335pub struct Term<'db> {
336    ptr: GenericArgImpl<'db>,
337}
338
339impl<'db> std::fmt::Debug for Term<'db> {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        match self.kind() {
342            TermKind::Ty(t) => std::fmt::Debug::fmt(&t, f),
343            TermKind::Const(c) => std::fmt::Debug::fmt(&c, f),
344        }
345    }
346}
347
348impl<'db> Term<'db> {
349    #[inline]
350    pub fn store(self) -> StoredTerm {
351        StoredTerm::new(self)
352    }
353
354    #[inline]
355    pub fn kind(self) -> TermKind<'db> {
356        self.ptr.term_kind()
357    }
358
359    pub fn expect_type(&self) -> Ty<'db> {
360        self.as_type().expect("expected a type, but found a const")
361    }
362
363    pub fn is_trivially_wf(&self, tcx: DbInterner<'db>) -> bool {
364        match self.kind() {
365            TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
366            TermKind::Const(ct) => ct.is_trivially_wf(),
367        }
368    }
369}
370
371impl<'db> From<Ty<'db>> for GenericArg<'db> {
372    #[inline]
373    fn from(value: Ty<'db>) -> Self {
374        GenericArg { ptr: GenericArgImpl::new_ty(value) }
375    }
376}
377
378impl<'db> From<Region<'db>> for GenericArg<'db> {
379    #[inline]
380    fn from(value: Region<'db>) -> Self {
381        GenericArg { ptr: GenericArgImpl::new_region(value) }
382    }
383}
384
385impl<'db> From<Const<'db>> for GenericArg<'db> {
386    #[inline]
387    fn from(value: Const<'db>) -> Self {
388        GenericArg { ptr: GenericArgImpl::new_const(value) }
389    }
390}
391
392impl<'db> IntoKind for GenericArg<'db> {
393    type Kind = GenericArgKind<'db>;
394
395    #[inline]
396    fn kind(self) -> Self::Kind {
397        self.ptr.kind()
398    }
399}
400
401impl<'db, V> GenericTypeVisitable<V> for GenericArg<'db>
402where
403    GenericArgKind<'db>: GenericTypeVisitable<V>,
404{
405    fn generic_visit_with(&self, visitor: &mut V) {
406        self.kind().generic_visit_with(visitor);
407    }
408}
409
410impl<'db, V> GenericTypeVisitable<V> for Term<'db>
411where
412    TermKind<'db>: GenericTypeVisitable<V>,
413{
414    fn generic_visit_with(&self, visitor: &mut V) {
415        self.kind().generic_visit_with(visitor);
416    }
417}
418
419impl<'db> TypeVisitable<DbInterner<'db>> for GenericArg<'db> {
420    fn visit_with<V: TypeVisitor<DbInterner<'db>>>(&self, visitor: &mut V) -> V::Result {
421        match self.kind() {
422            GenericArgKind::Lifetime(it) => it.visit_with(visitor),
423            GenericArgKind::Type(it) => it.visit_with(visitor),
424            GenericArgKind::Const(it) => it.visit_with(visitor),
425        }
426    }
427}
428
429impl<'db> TypeVisitable<DbInterner<'db>> for Term<'db> {
430    fn visit_with<V: TypeVisitor<DbInterner<'db>>>(&self, visitor: &mut V) -> V::Result {
431        match self.kind() {
432            TermKind::Ty(it) => it.visit_with(visitor),
433            TermKind::Const(it) => it.visit_with(visitor),
434        }
435    }
436}
437
438impl<'db> TypeFoldable<DbInterner<'db>> for GenericArg<'db> {
439    fn try_fold_with<F: FallibleTypeFolder<DbInterner<'db>>>(
440        self,
441        folder: &mut F,
442    ) -> Result<Self, F::Error> {
443        Ok(match self.kind() {
444            GenericArgKind::Lifetime(it) => it.try_fold_with(folder)?.into(),
445            GenericArgKind::Type(it) => it.try_fold_with(folder)?.into(),
446            GenericArgKind::Const(it) => it.try_fold_with(folder)?.into(),
447        })
448    }
449
450    fn fold_with<F: TypeFolder<DbInterner<'db>>>(self, folder: &mut F) -> Self {
451        match self.kind() {
452            GenericArgKind::Lifetime(it) => it.fold_with(folder).into(),
453            GenericArgKind::Type(it) => it.fold_with(folder).into(),
454            GenericArgKind::Const(it) => it.fold_with(folder).into(),
455        }
456    }
457}
458
459impl<'db> TypeFoldable<DbInterner<'db>> for Term<'db> {
460    fn try_fold_with<F: FallibleTypeFolder<DbInterner<'db>>>(
461        self,
462        folder: &mut F,
463    ) -> Result<Self, F::Error> {
464        Ok(match self.kind() {
465            TermKind::Ty(it) => it.try_fold_with(folder)?.into(),
466            TermKind::Const(it) => it.try_fold_with(folder)?.into(),
467        })
468    }
469
470    fn fold_with<F: TypeFolder<DbInterner<'db>>>(self, folder: &mut F) -> Self {
471        match self.kind() {
472            TermKind::Ty(it) => it.fold_with(folder).into(),
473            TermKind::Const(it) => it.fold_with(folder).into(),
474        }
475    }
476}
477
478impl<'db> Relate<DbInterner<'db>> for GenericArg<'db> {
479    fn relate<R: rustc_type_ir::relate::TypeRelation<DbInterner<'db>>>(
480        relation: &mut R,
481        a: Self,
482        b: Self,
483    ) -> rustc_type_ir::relate::RelateResult<DbInterner<'db>, Self> {
484        match (a.kind(), b.kind()) {
485            (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
486                Ok(relation.relate(a_lt, b_lt)?.into())
487            }
488            (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
489                Ok(relation.relate(a_ty, b_ty)?.into())
490            }
491            (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
492                Ok(relation.relate(a_ct, b_ct)?.into())
493            }
494            (GenericArgKind::Lifetime(unpacked), x) => {
495                unreachable!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
496            }
497            (GenericArgKind::Type(unpacked), x) => {
498                unreachable!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
499            }
500            (GenericArgKind::Const(unpacked), x) => {
501                unreachable!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
502            }
503        }
504    }
505}
506
507interned_slice!(
508    GenericArgsStorage,
509    GenericArgs,
510    StoredGenericArgs,
511    generic_args,
512    GenericArg<'db>,
513    GenericArg<'static>,
514);
515impl_foldable_for_interned_slice!(GenericArgs);
516impl_foldable_for_stored_type!(StoredGenericArgs);
517
518impl<'db> rustc_type_ir::inherent::GenericArg<DbInterner<'db>> for GenericArg<'db> {}
519
520trait GenericArgsBuilder<'db>: AsRef<[GenericArg<'db>]> {
521    fn push(&mut self, arg: GenericArg<'db>);
522}
523
524impl<'db, const N: usize> GenericArgsBuilder<'db> for ArrayVec<GenericArg<'db>, N> {
525    fn push(&mut self, arg: GenericArg<'db>) {
526        self.push(arg);
527    }
528}
529
530impl<'db> GenericArgsBuilder<'db> for Vec<GenericArg<'db>> {
531    fn push(&mut self, arg: GenericArg<'db>) {
532        self.push(arg);
533    }
534}
535
536impl<'db> GenericArgs<'db> {
537    #[inline(always)]
538    fn fill_builder<F>(
539        args: &mut impl GenericArgsBuilder<'db>,
540        defs: &Generics<'db>,
541        mut mk_kind: F,
542    ) where
543        F: FnMut(
544            u32,
545            GenericParamId,
546            Option<&LifetimeParamData>,
547            &[GenericArg<'db>],
548        ) -> GenericArg<'db>,
549    {
550        defs.iter().enumerate().for_each(|(idx, (param, lt_data))| {
551            let new_arg = mk_kind(idx as u32, param, lt_data, args.as_ref());
552            args.push(new_arg);
553        });
554    }
555
556    #[cold]
557    fn fill_vec_builder<F>(defs: &Generics<'db>, count: usize, mk_kind: F) -> GenericArgs<'db>
558    where
559        F: FnMut(
560            u32,
561            GenericParamId,
562            Option<&LifetimeParamData>,
563            &[GenericArg<'db>],
564        ) -> GenericArg<'db>,
565    {
566        let mut args = Vec::with_capacity(count);
567        Self::fill_builder(&mut args, defs, mk_kind);
568        GenericArgs::new_from_slice(&args)
569    }
570
571    /// Creates an `GenericArgs` for generic parameter definitions,
572    /// by calling closures to obtain each kind.
573    /// The closures get to observe the `GenericArgs` as they're
574    /// being built, which can be used to correctly
575    /// replace defaults of generic parameters.
576    pub fn for_item<F>(
577        interner: DbInterner<'db>,
578        def_id: SolverDefId<'db>,
579        mk_kind: F,
580    ) -> GenericArgs<'db>
581    where
582        F: FnMut(
583            u32,
584            GenericParamId,
585            Option<&LifetimeParamData>,
586            &[GenericArg<'db>],
587        ) -> GenericArg<'db>,
588    {
589        let defs = interner.generics_of(def_id);
590        let count = defs.count();
591
592        if count == 0 {
593            GenericArgs::default()
594        } else if count <= 10 {
595            let mut args = ArrayVec::<_, 10>::new();
596            Self::fill_builder(&mut args, &defs, mk_kind);
597            GenericArgs::new_from_slice(&args)
598        } else {
599            Self::fill_vec_builder(&defs, count, mk_kind)
600        }
601    }
602
603    /// Creates an all-error `GenericArgs`.
604    pub fn error_for_item(interner: DbInterner<'db>, def_id: SolverDefId<'db>) -> GenericArgs<'db> {
605        GenericArgs::for_item(interner, def_id, |_, id, _, _| {
606            GenericArg::error_from_id(interner, id)
607        })
608    }
609
610    /// Like `for_item`, but prefers the default of a parameter if it has any.
611    pub fn for_item_with_defaults<F>(
612        interner: DbInterner<'db>,
613        def_id: GenericDefId,
614        mut fallback: F,
615    ) -> GenericArgs<'db>
616    where
617        F: FnMut(u32, GenericParamId, &[GenericArg<'db>]) -> GenericArg<'db>,
618    {
619        let defaults = interner.db.generic_defaults(def_id);
620        Self::for_item(interner, def_id.into(), |idx, id, _, prev| {
621            match defaults.get(idx as usize) {
622                Some(default) => default.instantiate(interner, prev).skip_norm_wip(),
623                None => fallback(idx, id, prev),
624            }
625        })
626    }
627
628    /// Like `for_item()`, but calls first uses the args from `first`.
629    pub fn fill_rest<F>(
630        interner: DbInterner<'db>,
631        def_id: SolverDefId<'db>,
632        first: impl IntoIterator<Item = GenericArg<'db>>,
633        mut fallback: F,
634    ) -> GenericArgs<'db>
635    where
636        F: FnMut(u32, GenericParamId, &[GenericArg<'db>]) -> GenericArg<'db>,
637    {
638        let mut iter = first.into_iter();
639        Self::for_item(interner, def_id, |idx, id, _, prev| {
640            iter.next().unwrap_or_else(|| fallback(idx, id, prev))
641        })
642    }
643
644    /// Appends default param values to `first` if needed. Params without default will call `fallback()`.
645    pub fn fill_with_defaults<F>(
646        interner: DbInterner<'db>,
647        def_id: GenericDefId,
648        first: impl IntoIterator<Item = GenericArg<'db>>,
649        mut fallback: F,
650    ) -> GenericArgs<'db>
651    where
652        F: FnMut(u32, GenericParamId, &[GenericArg<'db>]) -> GenericArg<'db>,
653    {
654        let defaults = interner.db.generic_defaults(def_id);
655        Self::fill_rest(interner, def_id.into(), first, |idx, id, prev| {
656            defaults
657                .get(idx as usize)
658                .map(|default| default.instantiate(interner, prev).skip_norm_wip())
659                .unwrap_or_else(|| fallback(idx, id, prev))
660        })
661    }
662
663    pub fn types(self) -> impl Iterator<Item = Ty<'db>> {
664        self.iter().filter_map(|it| it.as_type())
665    }
666
667    pub fn consts(self) -> impl Iterator<Item = Const<'db>> {
668        self.iter().filter_map(|it| it.as_const())
669    }
670
671    pub fn regions(self) -> impl Iterator<Item = Region<'db>> {
672        self.iter().filter_map(|it| it.as_region())
673    }
674}
675
676impl<'db> rustc_type_ir::relate::Relate<DbInterner<'db>> for GenericArgs<'db> {
677    fn relate<R: rustc_type_ir::relate::TypeRelation<DbInterner<'db>>>(
678        relation: &mut R,
679        a: Self,
680        b: Self,
681    ) -> rustc_type_ir::relate::RelateResult<DbInterner<'db>, Self> {
682        GenericArgs::new_from_iter(std::iter::zip(a.iter(), b.iter()).map(|(a, b)| {
683            relation.relate_with_variance(Variance::Invariant, VarianceDiagInfo::default(), a, b)
684        }))
685    }
686}
687
688impl<'db> rustc_type_ir::inherent::GenericArgs<DbInterner<'db>> for GenericArgs<'db> {
689    fn as_closure(self) -> ClosureArgs<DbInterner<'db>> {
690        ClosureArgs { args: self }
691    }
692    fn as_coroutine(self) -> CoroutineArgs<DbInterner<'db>> {
693        CoroutineArgs { args: self }
694    }
695    fn as_coroutine_closure(self) -> CoroutineClosureArgs<DbInterner<'db>> {
696        CoroutineClosureArgs { args: self }
697    }
698    fn rebase_onto(
699        self,
700        interner: DbInterner<'db>,
701        source_def_id: <DbInterner<'db> as rustc_type_ir::Interner>::DefId,
702        target: <DbInterner<'db> as rustc_type_ir::Interner>::GenericArgs,
703    ) -> <DbInterner<'db> as rustc_type_ir::Interner>::GenericArgs {
704        let defs = interner.generics_of(source_def_id);
705        interner.mk_args_from_iter(target.iter().chain(self.iter().skip(defs.count())))
706    }
707
708    fn identity_for_item(
709        interner: DbInterner<'db>,
710        def_id: <DbInterner<'db> as rustc_type_ir::Interner>::DefId,
711    ) -> <DbInterner<'db> as rustc_type_ir::Interner>::GenericArgs {
712        Self::for_item(interner, def_id, |index, kind, _, _| mk_param(interner, index, kind))
713    }
714
715    fn extend_with_error(
716        interner: DbInterner<'db>,
717        def_id: <DbInterner<'db> as rustc_type_ir::Interner>::DefId,
718        original_args: &[<DbInterner<'db> as rustc_type_ir::Interner>::GenericArg],
719    ) -> <DbInterner<'db> as rustc_type_ir::Interner>::GenericArgs {
720        Self::for_item(interner, def_id, |index, kind, _, _| {
721            if let Some(arg) = original_args.get(index as usize) {
722                *arg
723            } else {
724                error_for_param_kind(kind, interner)
725            }
726        })
727    }
728    fn type_at(self, i: usize) -> <DbInterner<'db> as rustc_type_ir::Interner>::Ty {
729        self.get(i)
730            .and_then(|g| g.as_type())
731            .unwrap_or_else(|| crate::next_solver::default_types().types.error)
732    }
733
734    fn region_at(self, i: usize) -> <DbInterner<'db> as rustc_type_ir::Interner>::Region {
735        self.get(i)
736            .and_then(|g| g.as_region())
737            .unwrap_or_else(|| crate::next_solver::default_types().regions.error)
738    }
739
740    fn const_at(self, i: usize) -> <DbInterner<'db> as rustc_type_ir::Interner>::Const {
741        self.get(i)
742            .and_then(|g| g.as_const())
743            .unwrap_or_else(|| crate::next_solver::default_types().consts.error)
744    }
745
746    fn split_closure_args(self) -> rustc_type_ir::ClosureArgsParts<DbInterner<'db>> {
747        // FIXME: should use `ClosureSubst` when possible
748        match self.as_slice() {
749            [parent_args @ .., closure_kind_ty, sig_ty, tupled_upvars_ty] => {
750                rustc_type_ir::ClosureArgsParts {
751                    parent_args,
752                    closure_sig_as_fn_ptr_ty: sig_ty.expect_ty(),
753                    closure_kind_ty: closure_kind_ty.expect_ty(),
754                    tupled_upvars_ty: tupled_upvars_ty.expect_ty(),
755                }
756            }
757            _ => {
758                unreachable!("unexpected closure sig");
759            }
760        }
761    }
762
763    fn split_coroutine_closure_args(
764        self,
765    ) -> rustc_type_ir::CoroutineClosureArgsParts<DbInterner<'db>> {
766        match self.as_slice() {
767            [
768                parent_args @ ..,
769                closure_kind_ty,
770                signature_parts_ty,
771                tupled_upvars_ty,
772                coroutine_captures_by_ref_ty,
773            ] => rustc_type_ir::CoroutineClosureArgsParts {
774                parent_args,
775                closure_kind_ty: closure_kind_ty.expect_ty(),
776                signature_parts_ty: signature_parts_ty.expect_ty(),
777                tupled_upvars_ty: tupled_upvars_ty.expect_ty(),
778                coroutine_captures_by_ref_ty: coroutine_captures_by_ref_ty.expect_ty(),
779            },
780            _ => panic!("GenericArgs were likely not for a CoroutineClosure."),
781        }
782    }
783
784    fn split_coroutine_args(self) -> rustc_type_ir::CoroutineArgsParts<DbInterner<'db>> {
785        match self.as_slice() {
786            [parent_args @ .., kind_ty, resume_ty, yield_ty, return_ty, tupled_upvars_ty] => {
787                rustc_type_ir::CoroutineArgsParts {
788                    parent_args,
789                    kind_ty: kind_ty.expect_ty(),
790                    resume_ty: resume_ty.expect_ty(),
791                    yield_ty: yield_ty.expect_ty(),
792                    return_ty: return_ty.expect_ty(),
793                    tupled_upvars_ty: tupled_upvars_ty.expect_ty(),
794                }
795            }
796            _ => panic!("GenericArgs were likely not for a Coroutine."),
797        }
798    }
799}
800
801pub fn mk_param<'db>(interner: DbInterner<'db>, index: u32, id: GenericParamId) -> GenericArg<'db> {
802    match id {
803        GenericParamId::LifetimeParamId(id) => {
804            Region::new_early_param(interner, EarlyParamRegion { index, id }).into()
805        }
806        GenericParamId::TypeParamId(id) => Ty::new_param(interner, id, index).into(),
807        GenericParamId::ConstParamId(id) => {
808            Const::new_param(interner, ParamConst { index, id }).into()
809        }
810    }
811}
812
813pub fn error_for_param_kind<'db>(id: GenericParamId, interner: DbInterner<'db>) -> GenericArg<'db> {
814    match id {
815        GenericParamId::LifetimeParamId(_) => Region::error(interner).into(),
816        GenericParamId::TypeParamId(_) => Ty::new_error(interner, ErrorGuaranteed).into(),
817        GenericParamId::ConstParamId(_) => Const::error(interner).into(),
818    }
819}
820
821impl<'db> IntoKind for Term<'db> {
822    type Kind = TermKind<'db>;
823
824    #[inline]
825    fn kind(self) -> Self::Kind {
826        self.ptr.term_kind()
827    }
828}
829
830impl<'db> From<Ty<'db>> for Term<'db> {
831    #[inline]
832    fn from(value: Ty<'db>) -> Self {
833        Term { ptr: GenericArgImpl::new_ty(value) }
834    }
835}
836
837impl<'db> From<Const<'db>> for Term<'db> {
838    #[inline]
839    fn from(value: Const<'db>) -> Self {
840        Term { ptr: GenericArgImpl::new_const(value) }
841    }
842}
843
844impl<'db> Relate<DbInterner<'db>> for Term<'db> {
845    fn relate<R: rustc_type_ir::relate::TypeRelation<DbInterner<'db>>>(
846        relation: &mut R,
847        a: Self,
848        b: Self,
849    ) -> rustc_type_ir::relate::RelateResult<DbInterner<'db>, Self> {
850        match (a.kind(), b.kind()) {
851            (TermKind::Ty(a_ty), TermKind::Ty(b_ty)) => Ok(relation.relate(a_ty, b_ty)?.into()),
852            (TermKind::Const(a_ct), TermKind::Const(b_ct)) => {
853                Ok(relation.relate(a_ct, b_ct)?.into())
854            }
855            (TermKind::Ty(unpacked), x) => {
856                unreachable!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
857            }
858            (TermKind::Const(unpacked), x) => {
859                unreachable!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
860            }
861        }
862    }
863}
864
865impl<'db> rustc_type_ir::inherent::Term<DbInterner<'db>> for Term<'db> {}
866
867#[derive(Clone, Eq, PartialEq, Debug)]
868pub enum TermVid {
869    Ty(TyVid),
870    Const(ConstVid),
871}
872
873impl From<TyVid> for TermVid {
874    fn from(value: TyVid) -> Self {
875        TermVid::Ty(value)
876    }
877}
878
879impl From<ConstVid> for TermVid {
880    fn from(value: ConstVid) -> Self {
881        TermVid::Const(value)
882    }
883}
884
885impl<'db> DbInterner<'db> {
886    pub(super) fn mk_args(self, args: &[GenericArg<'db>]) -> GenericArgs<'db> {
887        GenericArgs::new_from_slice(args)
888    }
889
890    pub(super) fn mk_args_from_iter<I, T>(self, iter: I) -> T::Output
891    where
892        I: Iterator<Item = T>,
893        T: rustc_type_ir::CollectAndApply<GenericArg<'db>, GenericArgs<'db>>,
894    {
895        T::collect_and_apply(iter, |xs| self.mk_args(xs))
896    }
897}