Skip to main content

hir_ty/next_solver/
ty.rs

1//! Things related to tys in the next-trait-solver.
2
3mod erase_regions;
4
5use std::ops::ControlFlow;
6
7use hir_def::{
8    AdtId, HasModule, TypeParamId,
9    hir::generics::{GenericParams, TypeOrConstParamData, TypeParamProvenance},
10};
11use hir_def::{TraitId, type_ref::Rawness};
12use intern::{Interned, InternedRef, impl_internable};
13use macros::GenericTypeVisitable;
14use rustc_abi::{ExternAbi, Float, Integer, Size};
15use rustc_ast_ir::{Mutability, try_visit, visit::VisitorResult};
16use rustc_type_ir::{
17    BoundVar, BoundVarIndexKind, ClosureKind, DebruijnIndex, FlagComputation, Flags, FloatTy,
18    FloatVid, GenericTypeVisitable, InferTy, IntTy, IntVid, Interner, TyVid, TypeFoldable,
19    TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, UintTy,
20    Upcast, WithCachedTypeInfo,
21    inherent::{
22        AdtDef as _, BoundExistentialPredicates, GenericArgs as _, IntoKind, ParamLike,
23        Safety as _, SliceLike, Ty as _,
24    },
25    relate::Relate,
26    solve::SizedTraitKind,
27    walk::TypeWalker,
28};
29
30use crate::{
31    db::{HirDatabase, InternedOpaqueTyId},
32    lower::GenericPredicates,
33    next_solver::{
34        AdtDef, AliasTy, Binder, CallableIdWrapper, Clause, ClauseKind, ClosureIdWrapper, Const,
35        CoroutineClosureIdWrapper, CoroutineIdWrapper, FnSig, GenericArgKind, PolyFnSig, Predicate,
36        Region, TraitRef, TypeAliasIdWrapper, Unnormalized,
37        abi::Safety,
38        impl_foldable_for_interned_slice, impl_foldable_for_stored_type, impl_stored_interned,
39        interned_slice,
40        util::{CoroutineArgsExt, IntegerTypeExt},
41    },
42};
43
44use super::{
45    DbInterner, GenericArgs, SolverDefId,
46    util::{FloatExt, IntegerExt},
47};
48
49pub type SimplifiedType<'db> = rustc_type_ir::fast_reject::SimplifiedType<SolverDefId<'db>>;
50pub type TyKind<'db> = rustc_type_ir::TyKind<DbInterner<'db>>;
51pub type FnHeader<'db> = rustc_type_ir::FnHeader<DbInterner<'db>>;
52pub type AliasTyKind<'db> = rustc_type_ir::AliasTyKind<DbInterner<'db>>;
53pub type AliasTermKind<'db> = rustc_type_ir::AliasTermKind<DbInterner<'db>>;
54pub type FnSigKind<'db> = rustc_type_ir::FnSigKind<DbInterner<'db>>;
55
56#[derive(Clone, Copy, PartialEq, Eq, Hash)]
57pub struct Ty<'db> {
58    pub(super) interned: InternedRef<'db, TyInterned>,
59}
60
61#[derive(PartialEq, Eq, Hash, GenericTypeVisitable)]
62#[repr(align(4))] // Required for `GenericArg` bit-tagging.
63pub(super) struct TyInterned(WithCachedTypeInfo<TyKind<'static>>);
64
65impl_internable!(gc; TyInterned);
66impl_stored_interned!(TyInterned, Ty, StoredTy);
67impl_foldable_for_stored_type!(StoredTy);
68
69const _: () = {
70    const fn is_copy<T: Copy>() {}
71    is_copy::<Ty<'static>>();
72};
73
74impl<'db> Ty<'db> {
75    /// You should avoid using this if you can, since we want `Const` to be defined in `rustc_type_ir` and then this method
76    /// will become more difficult to use.
77    #[inline]
78    pub fn new_without_interner(kind: TyKind<'db>) -> Self {
79        let kind = unsafe { std::mem::transmute::<TyKind<'db>, TyKind<'static>>(kind) };
80        let flags = FlagComputation::for_kind(&kind);
81        let cached = WithCachedTypeInfo {
82            internee: kind,
83            flags: flags.flags,
84            outer_exclusive_binder: flags.outer_exclusive_binder,
85        };
86        Self { interned: Interned::new_gc(TyInterned(cached)) }
87    }
88
89    #[inline]
90    pub fn new(_interner: DbInterner<'db>, kind: TyKind<'db>) -> Self {
91        Self::new_without_interner(kind)
92    }
93
94    #[inline]
95    pub fn inner(&self) -> &WithCachedTypeInfo<TyKind<'db>> {
96        let inner = &self.interned.0;
97        unsafe {
98            std::mem::transmute::<
99                &WithCachedTypeInfo<TyKind<'static>>,
100                &WithCachedTypeInfo<TyKind<'db>>,
101            >(inner)
102        }
103    }
104
105    pub fn new_adt(interner: DbInterner<'db>, adt_id: AdtId, args: GenericArgs<'db>) -> Self {
106        Ty::new(interner, TyKind::Adt(AdtDef::new(adt_id, interner), args))
107    }
108
109    pub fn new_param(interner: DbInterner<'db>, id: TypeParamId, index: u32) -> Self {
110        Ty::new(interner, TyKind::Param(ParamTy { id, index }))
111    }
112
113    pub fn new_placeholder(interner: DbInterner<'db>, placeholder: PlaceholderType<'db>) -> Self {
114        Ty::new(interner, TyKind::Placeholder(placeholder))
115    }
116
117    pub fn new_infer(interner: DbInterner<'db>, infer: InferTy) -> Self {
118        if let InferTy::TyVar(vid) = infer {
119            return Ty::new_var(interner, vid);
120        }
121        Ty::new(interner, TyKind::Infer(infer))
122    }
123
124    pub fn new_int_var(interner: DbInterner<'db>, v: IntVid) -> Self {
125        Ty::new_infer(interner, InferTy::IntVar(v))
126    }
127
128    pub fn new_float_var(interner: DbInterner<'db>, v: FloatVid) -> Self {
129        Ty::new_infer(interner, InferTy::FloatVar(v))
130    }
131
132    #[inline]
133    pub fn new_int(interner: DbInterner<'db>, i: IntTy) -> Self {
134        let types = interner.default_types();
135        match i {
136            IntTy::Isize => types.types.isize,
137            IntTy::I8 => types.types.i8,
138            IntTy::I16 => types.types.i16,
139            IntTy::I32 => types.types.i32,
140            IntTy::I64 => types.types.i64,
141            IntTy::I128 => types.types.i128,
142        }
143    }
144
145    pub fn new_uint(interner: DbInterner<'db>, ui: UintTy) -> Self {
146        let types = interner.default_types();
147        match ui {
148            UintTy::Usize => types.types.usize,
149            UintTy::U8 => types.types.u8,
150            UintTy::U16 => types.types.u16,
151            UintTy::U32 => types.types.u32,
152            UintTy::U64 => types.types.u64,
153            UintTy::U128 => types.types.u128,
154        }
155    }
156
157    pub fn new_float(interner: DbInterner<'db>, f: FloatTy) -> Self {
158        let types = interner.default_types();
159        match f {
160            FloatTy::F16 => types.types.f16,
161            FloatTy::F32 => types.types.f32,
162            FloatTy::F64 => types.types.f64,
163            FloatTy::F128 => types.types.f128,
164        }
165    }
166
167    pub fn new_fresh(interner: DbInterner<'db>, n: u32) -> Self {
168        Ty::new_infer(interner, InferTy::FreshTy(n))
169    }
170
171    pub fn new_fresh_int(interner: DbInterner<'db>, n: u32) -> Self {
172        Ty::new_infer(interner, InferTy::FreshIntTy(n))
173    }
174
175    pub fn new_fresh_float(interner: DbInterner<'db>, n: u32) -> Self {
176        Ty::new_infer(interner, InferTy::FreshFloatTy(n))
177    }
178
179    pub fn new_empty_tuple(interner: DbInterner<'db>) -> Self {
180        interner.default_types().types.unit
181    }
182
183    pub fn new_imm_ptr(interner: DbInterner<'db>, ty: Ty<'db>) -> Self {
184        Ty::new_ptr(interner, ty, Mutability::Not)
185    }
186
187    pub fn new_imm_ref(interner: DbInterner<'db>, region: Region<'db>, ty: Ty<'db>) -> Self {
188        Ty::new_ref(interner, region, ty, Mutability::Not)
189    }
190
191    pub fn new_opaque(
192        interner: DbInterner<'db>,
193        def_id: InternedOpaqueTyId<'db>,
194        args: GenericArgs<'db>,
195    ) -> Self {
196        Ty::new_alias(
197            interner,
198            AliasTy::new_from_args(interner, AliasTyKind::Opaque { def_id: def_id.into() }, args),
199        )
200    }
201
202    /// Note: this needs an interner with crate.
203    pub fn new_array(interner: DbInterner<'db>, ty: Ty<'db>, n: u64) -> Ty<'db> {
204        Ty::new(interner, TyKind::Array(ty, Const::from_target_usize(interner, n)))
205    }
206
207    pub fn new_array_opt(interner: DbInterner<'db>, ty: Ty<'db>, n: Option<u128>) -> Ty<'db> {
208        Ty::new(
209            interner,
210            TyKind::Array(
211                ty,
212                crate::consteval::usize_const(interner.db, n, interner.expect_crate()),
213            ),
214        )
215    }
216
217    fn new_generic_adt(interner: DbInterner<'db>, adt_id: AdtId, ty_param: Ty<'db>) -> Ty<'db> {
218        let args = GenericArgs::fill_with_defaults(
219            interner,
220            adt_id.into(),
221            [ty_param.into()],
222            |_, _, _| panic!("all params except the first should have defaults"),
223        );
224        Ty::new_adt(interner, adt_id, args)
225    }
226
227    /// Note: Unlike most other constructors, this require the interner to have a crate, because this needs lang items.
228    pub fn new_box(interner: DbInterner<'db>, ty: Ty<'db>) -> Ty<'db> {
229        let Some(def_id) = interner.lang_items().OwnedBox else {
230            return Ty::new_error(interner, ErrorGuaranteed);
231        };
232        Ty::new_generic_adt(interner, def_id.into(), ty)
233    }
234
235    /// Returns the `Size` for primitive types (bool, uint, int, char, float).
236    pub fn primitive_size(self, interner: DbInterner<'db>) -> Size {
237        match self.kind() {
238            TyKind::Bool => Size::from_bytes(1),
239            TyKind::Char => Size::from_bytes(4),
240            TyKind::Int(ity) => Integer::from_int_ty(&interner, ity).size(),
241            TyKind::Uint(uty) => Integer::from_uint_ty(&interner, uty).size(),
242            TyKind::Float(fty) => Float::from_float_ty(fty).size(),
243            _ => panic!("non primitive type"),
244        }
245    }
246
247    pub fn int_size_and_signed(self, interner: DbInterner<'db>) -> (Size, bool) {
248        match self.kind() {
249            TyKind::Int(ity) => (Integer::from_int_ty(&interner, ity).size(), true),
250            TyKind::Uint(uty) => (Integer::from_uint_ty(&interner, uty).size(), false),
251            _ => panic!("non integer discriminant"),
252        }
253    }
254
255    pub fn walk(self) -> TypeWalker<DbInterner<'db>> {
256        TypeWalker::new(self.into())
257    }
258
259    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
260    ///
261    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
262    /// means nothing -- could be sized, might not be.
263    ///
264    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
265    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
266    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
267    /// This is why this method doesn't return `Option<bool>`.
268    #[tracing::instrument(skip(tcx), level = "debug")]
269    pub fn has_trivial_sizedness(self, tcx: DbInterner<'db>, sizedness: SizedTraitKind) -> bool {
270        match self.kind() {
271            TyKind::Infer(InferTy::IntVar(_) | InferTy::FloatVar(_))
272            | TyKind::Uint(_)
273            | TyKind::Int(_)
274            | TyKind::Bool
275            | TyKind::Float(_)
276            | TyKind::FnDef(..)
277            | TyKind::FnPtr(..)
278            | TyKind::UnsafeBinder(_)
279            | TyKind::RawPtr(..)
280            | TyKind::Char
281            | TyKind::Ref(..)
282            | TyKind::Coroutine(..)
283            | TyKind::CoroutineWitness(..)
284            | TyKind::Array(..)
285            | TyKind::Pat(..)
286            | TyKind::Closure(..)
287            | TyKind::CoroutineClosure(..)
288            | TyKind::Never
289            | TyKind::Error(_) => true,
290
291            TyKind::Str | TyKind::Slice(_) | TyKind::Dynamic(_, _) => match sizedness {
292                SizedTraitKind::Sized => false,
293                SizedTraitKind::MetaSized => true,
294            },
295
296            TyKind::Foreign(..) => match sizedness {
297                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
298            },
299
300            TyKind::Tuple(tys) => {
301                tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness))
302            }
303
304            TyKind::Adt(def, args) => def.sizedness_constraint(tcx, sizedness).is_none_or(|ty| {
305                ty.instantiate(tcx, args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness)
306            }),
307
308            TyKind::Alias(..) | TyKind::Param(_) | TyKind::Placeholder(..) | TyKind::Bound(..) => {
309                false
310            }
311
312            TyKind::Infer(InferTy::TyVar(_)) => false,
313
314            TyKind::Infer(
315                InferTy::FreshTy(_) | InferTy::FreshIntTy(_) | InferTy::FreshFloatTy(_),
316            ) => {
317                panic!("`has_trivial_sizedness` applied to unexpected type: {self:?}")
318            }
319        }
320    }
321
322    /// Fast path helper for primitives which are always `Copy` and which
323    /// have a side-effect-free `Clone` impl.
324    ///
325    /// Returning true means the type is known to be pure and `Copy+Clone`.
326    /// Returning `false` means nothing -- could be `Copy`, might not be.
327    ///
328    /// This is mostly useful for optimizations, as these are the types
329    /// on which we can replace cloning with dereferencing.
330    pub fn is_trivially_pure_clone_copy(self) -> bool {
331        match self.kind() {
332            TyKind::Bool | TyKind::Char | TyKind::Never => true,
333
334            // These aren't even `Clone`
335            TyKind::Str | TyKind::Slice(..) | TyKind::Foreign(..) | TyKind::Dynamic(..) => false,
336
337            TyKind::Infer(InferTy::FloatVar(_) | InferTy::IntVar(_))
338            | TyKind::Int(..)
339            | TyKind::Uint(..)
340            | TyKind::Float(..) => true,
341
342            // ZST which can't be named are fine.
343            TyKind::FnDef(..) => true,
344
345            TyKind::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
346
347            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
348            TyKind::Tuple(field_tys) => {
349                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
350            }
351
352            TyKind::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
353
354            // Sometimes traits aren't implemented for every ABI or arity,
355            // because we can't be generic over everything yet.
356            TyKind::FnPtr(..) => false,
357
358            // Definitely absolutely not copy.
359            TyKind::Ref(_, _, Mutability::Mut) => false,
360
361            // The standard library has a blanket Copy impl for shared references and raw pointers,
362            // for all unsized types.
363            TyKind::Ref(_, _, Mutability::Not) | TyKind::RawPtr(..) => true,
364
365            TyKind::Coroutine(..) | TyKind::CoroutineWitness(..) => false,
366
367            // Might be, but not "trivial" so just giving the safe answer.
368            TyKind::Adt(..) | TyKind::Closure(..) | TyKind::CoroutineClosure(..) => false,
369
370            TyKind::UnsafeBinder(_) => false,
371
372            // Needs normalization or revealing to determine, so no is the safe answer.
373            TyKind::Alias(..) => false,
374
375            TyKind::Param(..)
376            | TyKind::Placeholder(..)
377            | TyKind::Bound(..)
378            | TyKind::Infer(..)
379            | TyKind::Error(..) => false,
380        }
381    }
382
383    pub fn is_trivially_wf(self, tcx: DbInterner<'db>) -> bool {
384        match self.kind() {
385            TyKind::Bool
386            | TyKind::Char
387            | TyKind::Int(_)
388            | TyKind::Uint(_)
389            | TyKind::Float(_)
390            | TyKind::Str
391            | TyKind::Never
392            | TyKind::Param(_)
393            | TyKind::Placeholder(_)
394            | TyKind::Bound(..) => true,
395
396            TyKind::Slice(ty) => {
397                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
398            }
399            TyKind::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
400
401            TyKind::FnPtr(sig_tys, _) => {
402                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
403            }
404            TyKind::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
405
406            TyKind::Infer(infer) => match infer {
407                InferTy::TyVar(_) => false,
408                InferTy::IntVar(_) | InferTy::FloatVar(_) => true,
409                InferTy::FreshTy(_) | InferTy::FreshIntTy(_) | InferTy::FreshFloatTy(_) => true,
410            },
411
412            TyKind::Adt(_, _)
413            | TyKind::Tuple(_)
414            | TyKind::Array(..)
415            | TyKind::Foreign(_)
416            | TyKind::Pat(_, _)
417            | TyKind::FnDef(..)
418            | TyKind::UnsafeBinder(..)
419            | TyKind::Dynamic(..)
420            | TyKind::Closure(..)
421            | TyKind::CoroutineClosure(..)
422            | TyKind::Coroutine(..)
423            | TyKind::CoroutineWitness(..)
424            | TyKind::Alias(..)
425            | TyKind::Error(_) => false,
426        }
427    }
428
429    #[inline]
430    pub fn is_param(self, index: u32) -> bool {
431        match self.kind() {
432            TyKind::Param(data) => data.index == index,
433            _ => false,
434        }
435    }
436
437    #[inline]
438    pub fn is_never(self) -> bool {
439        matches!(self.kind(), TyKind::Never)
440    }
441
442    #[inline]
443    pub fn is_bool(self) -> bool {
444        matches!(self.kind(), TyKind::Bool)
445    }
446
447    /// Check if type is an `usize`.
448    #[inline]
449    pub fn is_usize(self) -> bool {
450        matches!(self.kind(), TyKind::Uint(UintTy::Usize))
451    }
452
453    #[inline]
454    pub fn is_char(self) -> bool {
455        matches!(self.kind(), TyKind::Char)
456    }
457
458    #[inline]
459    pub fn is_coroutine_closure(self) -> bool {
460        matches!(self.kind(), TyKind::CoroutineClosure(..))
461    }
462
463    /// A scalar type is one that denotes an atomic datum, with no sub-components.
464    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
465    /// contents are abstract to rustc.)
466    #[inline]
467    pub fn is_scalar(self) -> bool {
468        matches!(
469            self.kind(),
470            TyKind::Bool
471                | TyKind::Char
472                | TyKind::Int(_)
473                | TyKind::Float(_)
474                | TyKind::Uint(_)
475                | TyKind::FnDef(..)
476                | TyKind::FnPtr(..)
477                | TyKind::RawPtr(_, _)
478                | TyKind::Infer(InferTy::IntVar(_) | InferTy::FloatVar(_))
479        )
480    }
481
482    #[inline]
483    pub fn is_infer(self) -> bool {
484        matches!(self.kind(), TyKind::Infer(..))
485    }
486
487    #[inline]
488    pub fn is_numeric(self) -> bool {
489        self.is_integral() || self.is_floating_point()
490    }
491
492    #[inline]
493    pub fn is_str(self) -> bool {
494        matches!(self.kind(), TyKind::Str)
495    }
496
497    #[inline]
498    pub fn is_unit(self) -> bool {
499        matches!(self.kind(), TyKind::Tuple(tys) if tys.is_empty())
500    }
501
502    #[inline]
503    pub fn is_u8(self) -> bool {
504        matches!(self.kind(), TyKind::Uint(UintTy::U8))
505    }
506
507    #[inline]
508    pub fn is_raw_ptr(self) -> bool {
509        matches!(self.kind(), TyKind::RawPtr(..))
510    }
511
512    #[inline]
513    pub fn is_ref(self) -> bool {
514        matches!(self.kind(), TyKind::Ref(..))
515    }
516
517    #[inline]
518    pub fn is_array(self) -> bool {
519        matches!(self.kind(), TyKind::Array(..))
520    }
521
522    #[inline]
523    pub fn is_slice(self) -> bool {
524        matches!(self.kind(), TyKind::Slice(..))
525    }
526
527    pub fn is_union(self) -> bool {
528        self.as_adt().is_some_and(|(adt, _)| matches!(adt, AdtId::UnionId(_)))
529    }
530
531    pub fn boxed_ty(self) -> Option<Ty<'db>> {
532        match self.kind() {
533            TyKind::Adt(adt_def, args) if adt_def.is_box() => Some(args.type_at(0)),
534            _ => None,
535        }
536    }
537
538    pub fn is_box(self) -> bool {
539        matches!(self.kind(), TyKind::Adt(adt_def, _) if adt_def.is_box())
540    }
541
542    #[inline]
543    pub fn as_adt(self) -> Option<(AdtId, GenericArgs<'db>)> {
544        match self.kind() {
545            TyKind::Adt(adt_def, args) => Some((adt_def.def_id(), args)),
546            _ => None,
547        }
548    }
549
550    #[inline]
551    pub fn as_slice(self) -> Option<Ty<'db>> {
552        match self.kind() {
553            TyKind::Slice(ty) => Some(ty),
554            _ => None,
555        }
556    }
557
558    #[inline]
559    pub fn ty_vid(self) -> Option<TyVid> {
560        match self.kind() {
561            TyKind::Infer(rustc_type_ir::TyVar(vid)) => Some(vid),
562            _ => None,
563        }
564    }
565
566    /// Given a `fn` type, returns an equivalent `unsafe fn` type;
567    /// that is, a `fn` type that is equivalent in every way for being
568    /// unsafe.
569    pub fn safe_to_unsafe_fn_ty(interner: DbInterner<'db>, sig: PolyFnSig<'db>) -> Ty<'db> {
570        assert!(sig.safety().is_safe());
571        Ty::new_fn_ptr(interner, sig.map_bound(|sig| sig.set_safety(Safety::Unsafe)))
572    }
573
574    /// Returns the type of `*ty`.
575    ///
576    /// The parameter `explicit` indicates if this is an *explicit* dereference.
577    /// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
578    pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'db>> {
579        match self.kind() {
580            TyKind::Adt(adt, substs) if adt.is_box() => Some(substs.as_slice()[0].expect_ty()),
581            TyKind::Ref(_, ty, _) => Some(ty),
582            TyKind::RawPtr(ty, _) if explicit => Some(ty),
583            _ => None,
584        }
585    }
586
587    /// Returns the type of `ty[i]`.
588    pub fn builtin_index(self) -> Option<Ty<'db>> {
589        match self.kind() {
590            TyKind::Array(ty, _) | TyKind::Slice(ty) => Some(ty),
591            _ => None,
592        }
593    }
594
595    /// Whether the type contains some non-lifetime, aka. type or const, error type.
596    pub fn references_non_lt_error(self) -> bool {
597        references_non_lt_error(&self)
598    }
599
600    /// Whether the type contains a type error (ignoring const and lifetime errors).
601    pub fn references_only_ty_error(self) -> bool {
602        references_only_ty_error(&self)
603    }
604
605    pub fn callable_sig(self, interner: DbInterner<'db>) -> Option<Binder<'db, FnSig<'db>>> {
606        match self.kind() {
607            TyKind::FnDef(callable, args) => {
608                Some(interner.fn_sig(callable).instantiate(interner, args).skip_norm_wip())
609            }
610            TyKind::FnPtr(sig, hdr) => Some(sig.with(hdr)),
611            TyKind::Closure(_, closure_args) => {
612                Some(interner.signature_unclosure(closure_args.as_closure().sig(), Safety::Safe))
613            }
614            TyKind::CoroutineClosure(coroutine_id, args) => {
615                Some(args.as_coroutine_closure().coroutine_closure_sig().map_bound(|sig| {
616                    let closure_args = args.as_coroutine_closure();
617                    let return_ty = sig.to_coroutine(
618                        interner,
619                        closure_args.parent_args(),
620                        closure_args.kind_ty(),
621                        interner.coroutine_for_closure(coroutine_id),
622                        closure_args.tupled_upvars_ty(),
623                    );
624                    FnSig {
625                        inputs_and_output: Tys::new_from_iter(
626                            sig.tupled_inputs_ty
627                                .tuple_fields()
628                                .iter()
629                                .chain(std::iter::once(return_ty)),
630                        ),
631                        fn_sig_kind: sig.fn_sig_kind,
632                    }
633                }))
634            }
635            _ => None,
636        }
637    }
638
639    pub fn as_reference(self) -> Option<(Ty<'db>, Region<'db>, Mutability)> {
640        match self.kind() {
641            TyKind::Ref(region, ty, mutability) => Some((ty, region, mutability)),
642            _ => None,
643        }
644    }
645
646    pub fn as_reference_or_ptr(self) -> Option<(Ty<'db>, Rawness, Mutability)> {
647        match self.kind() {
648            TyKind::Ref(_, ty, mutability) => Some((ty, Rawness::Ref, mutability)),
649            TyKind::RawPtr(ty, mutability) => Some((ty, Rawness::RawPtr, mutability)),
650            _ => None,
651        }
652    }
653
654    pub fn is_tuple(self) -> bool {
655        matches!(self.kind(), TyKind::Tuple(_))
656    }
657
658    pub fn as_tuple(self) -> Option<Tys<'db>> {
659        match self.kind() {
660            TyKind::Tuple(tys) => Some(tys),
661            _ => None,
662        }
663    }
664
665    pub fn dyn_trait(self) -> Option<TraitId> {
666        let TyKind::Dynamic(bounds, _) = self.kind() else { return None };
667        Some(bounds.principal_def_id()?.0)
668    }
669
670    pub fn strip_references(self) -> Ty<'db> {
671        let mut t = self;
672        while let TyKind::Ref(_lifetime, ty, _mutability) = t.kind() {
673            t = ty;
674        }
675        t
676    }
677
678    pub fn strip_reference(self) -> Ty<'db> {
679        self.as_reference().map_or(self, |(ty, _, _)| ty)
680    }
681
682    /// Replace infer vars with errors.
683    ///
684    /// This needs to be called for every type that may contain infer vars and is yielded to outside inference,
685    /// as things other than inference do not expect to see infer vars.
686    pub fn replace_infer_with_error(self, interner: DbInterner<'db>) -> Ty<'db> {
687        self.fold_with(&mut crate::next_solver::infer::resolve::ReplaceInferWithError::new(
688            interner,
689        ))
690    }
691
692    pub fn from_builtin_type(
693        interner: DbInterner<'db>,
694        ty: hir_def::builtin_type::BuiltinType,
695    ) -> Ty<'db> {
696        let types = interner.default_types();
697        match ty {
698            hir_def::builtin_type::BuiltinType::Char => types.types.char,
699            hir_def::builtin_type::BuiltinType::Bool => types.types.bool,
700            hir_def::builtin_type::BuiltinType::Str => types.types.str,
701            hir_def::builtin_type::BuiltinType::Int(int) => match int {
702                hir_def::builtin_type::BuiltinInt::Isize => types.types.isize,
703                hir_def::builtin_type::BuiltinInt::I8 => types.types.i8,
704                hir_def::builtin_type::BuiltinInt::I16 => types.types.i16,
705                hir_def::builtin_type::BuiltinInt::I32 => types.types.i32,
706                hir_def::builtin_type::BuiltinInt::I64 => types.types.i64,
707                hir_def::builtin_type::BuiltinInt::I128 => types.types.i128,
708            },
709            hir_def::builtin_type::BuiltinType::Uint(uint) => match uint {
710                hir_def::builtin_type::BuiltinUint::Usize => types.types.usize,
711                hir_def::builtin_type::BuiltinUint::U8 => types.types.u8,
712                hir_def::builtin_type::BuiltinUint::U16 => types.types.u16,
713                hir_def::builtin_type::BuiltinUint::U32 => types.types.u32,
714                hir_def::builtin_type::BuiltinUint::U64 => types.types.u64,
715                hir_def::builtin_type::BuiltinUint::U128 => types.types.u128,
716            },
717            hir_def::builtin_type::BuiltinType::Float(float) => match float {
718                hir_def::builtin_type::BuiltinFloat::F16 => types.types.f16,
719                hir_def::builtin_type::BuiltinFloat::F32 => types.types.f32,
720                hir_def::builtin_type::BuiltinFloat::F64 => types.types.f64,
721                hir_def::builtin_type::BuiltinFloat::F128 => types.types.f128,
722            },
723        }
724    }
725
726    pub fn as_builtin(self) -> Option<hir_def::builtin_type::BuiltinType> {
727        let builtin = match self.kind() {
728            TyKind::Char => hir_def::builtin_type::BuiltinType::Char,
729            TyKind::Bool => hir_def::builtin_type::BuiltinType::Bool,
730            TyKind::Str => hir_def::builtin_type::BuiltinType::Str,
731            TyKind::Int(int) => hir_def::builtin_type::BuiltinType::Int(match int {
732                rustc_type_ir::IntTy::Isize => hir_def::builtin_type::BuiltinInt::Isize,
733                rustc_type_ir::IntTy::I8 => hir_def::builtin_type::BuiltinInt::I8,
734                rustc_type_ir::IntTy::I16 => hir_def::builtin_type::BuiltinInt::I16,
735                rustc_type_ir::IntTy::I32 => hir_def::builtin_type::BuiltinInt::I32,
736                rustc_type_ir::IntTy::I64 => hir_def::builtin_type::BuiltinInt::I64,
737                rustc_type_ir::IntTy::I128 => hir_def::builtin_type::BuiltinInt::I128,
738            }),
739            TyKind::Uint(uint) => hir_def::builtin_type::BuiltinType::Uint(match uint {
740                rustc_type_ir::UintTy::Usize => hir_def::builtin_type::BuiltinUint::Usize,
741                rustc_type_ir::UintTy::U8 => hir_def::builtin_type::BuiltinUint::U8,
742                rustc_type_ir::UintTy::U16 => hir_def::builtin_type::BuiltinUint::U16,
743                rustc_type_ir::UintTy::U32 => hir_def::builtin_type::BuiltinUint::U32,
744                rustc_type_ir::UintTy::U64 => hir_def::builtin_type::BuiltinUint::U64,
745                rustc_type_ir::UintTy::U128 => hir_def::builtin_type::BuiltinUint::U128,
746            }),
747            TyKind::Float(float) => hir_def::builtin_type::BuiltinType::Float(match float {
748                rustc_type_ir::FloatTy::F16 => hir_def::builtin_type::BuiltinFloat::F16,
749                rustc_type_ir::FloatTy::F32 => hir_def::builtin_type::BuiltinFloat::F32,
750                rustc_type_ir::FloatTy::F64 => hir_def::builtin_type::BuiltinFloat::F64,
751                rustc_type_ir::FloatTy::F128 => hir_def::builtin_type::BuiltinFloat::F128,
752            }),
753            _ => return None,
754        };
755        Some(builtin)
756    }
757
758    // FIXME: Should this be here?
759    pub fn impl_trait_bounds(self, db: &'db dyn HirDatabase) -> Option<Vec<Clause<'db>>> {
760        let interner = DbInterner::new_no_crate(db);
761
762        match self.kind() {
763            TyKind::Alias(AliasTy { kind: AliasTyKind::Opaque { def_id }, args, .. }) => Some(
764                def_id
765                    .0
766                    .predicates(db)
767                    .iter_instantiated_copied(interner, args.as_slice())
768                    .map(Unnormalized::skip_norm_wip)
769                    .collect(),
770            ),
771            TyKind::Param(param) => {
772                // FIXME: We shouldn't use `param.id` here.
773                let generic_params = GenericParams::of(db, param.id.parent());
774                let param_data = &generic_params[param.id.local_id()];
775                match param_data {
776                    TypeOrConstParamData::TypeParamData(p) => match p.provenance {
777                        TypeParamProvenance::ArgumentImplTrait => {
778                            let predicates = GenericPredicates::query_all(db, param.id.parent())
779                                .iter_identity()
780                                .map(Unnormalized::skip_norm_wip)
781                                .filter(|wc| match wc.kind().skip_binder() {
782                                    ClauseKind::Trait(tr) => tr.self_ty() == self,
783                                    ClauseKind::Projection(pred) => pred.self_ty() == self,
784                                    ClauseKind::TypeOutlives(pred) => pred.0 == self,
785                                    _ => false,
786                                })
787                                .collect::<Vec<_>>();
788
789                            Some(predicates)
790                        }
791                        _ => None,
792                    },
793                    _ => None,
794                }
795            }
796            TyKind::Coroutine(coroutine_id, _args) => {
797                let owner = coroutine_id.0.loc(db).owner;
798                let krate = owner.krate(db);
799                if let Some(future_trait) = hir_def::lang_item::lang_items(db, krate).Future {
800                    // This is only used by type walking.
801                    // Parameters will be walked outside, and projection predicate is not used.
802                    // So just provide the Future trait.
803                    let impl_bound = TraitRef::new_from_args(
804                        interner,
805                        future_trait.into(),
806                        GenericArgs::empty(),
807                    )
808                    .upcast(interner);
809                    Some(vec![impl_bound])
810                } else {
811                    None
812                }
813            }
814            _ => None,
815        }
816    }
817}
818
819pub fn references_non_lt_error<'db, T: TypeVisitableExt<DbInterner<'db>>>(t: &T) -> bool {
820    t.has_non_region_error()
821}
822
823pub fn references_only_ty_error<'db, T: TypeVisitableExt<DbInterner<'db>>>(t: &T) -> bool {
824    references_non_lt_error(t) && t.visit_with(&mut ReferencesOnlyTyError).is_break()
825}
826
827struct ReferencesOnlyTyError;
828
829impl<'db> TypeVisitor<DbInterner<'db>> for ReferencesOnlyTyError {
830    type Result = ControlFlow<()>;
831
832    fn visit_ty(&mut self, ty: Ty<'db>) -> Self::Result {
833        if !ty.references_non_lt_error() {
834            ControlFlow::Continue(())
835        } else if ty.is_ty_error() {
836            ControlFlow::Break(())
837        } else {
838            ty.super_visit_with(self)
839        }
840    }
841
842    fn visit_const(&mut self, c: Const<'db>) -> Self::Result {
843        if !references_non_lt_error(&c) {
844            ControlFlow::Continue(())
845        } else {
846            c.super_visit_with(self)
847        }
848    }
849
850    fn visit_predicate(&mut self, p: Predicate<'db>) -> Self::Result {
851        if !references_non_lt_error(&p) {
852            ControlFlow::Continue(())
853        } else {
854            p.super_visit_with(self)
855        }
856    }
857}
858
859impl<'db> std::fmt::Debug for Ty<'db> {
860    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
861        self.inner().internee.fmt(f)
862    }
863}
864
865impl<'db> IntoKind for Ty<'db> {
866    type Kind = TyKind<'db>;
867
868    #[inline]
869    fn kind(self) -> Self::Kind {
870        self.inner().internee
871    }
872}
873
874impl<'db, V: super::WorldExposer> GenericTypeVisitable<V> for Ty<'db> {
875    fn generic_visit_with(&self, visitor: &mut V) {
876        if visitor.on_interned(self.interned).is_continue() {
877            self.kind().generic_visit_with(visitor);
878        }
879    }
880}
881
882impl<'db> TypeVisitable<DbInterner<'db>> for Ty<'db> {
883    fn visit_with<V: rustc_type_ir::TypeVisitor<DbInterner<'db>>>(
884        &self,
885        visitor: &mut V,
886    ) -> V::Result {
887        visitor.visit_ty(*self)
888    }
889}
890
891impl<'db> TypeSuperVisitable<DbInterner<'db>> for Ty<'db> {
892    fn super_visit_with<V: rustc_type_ir::TypeVisitor<DbInterner<'db>>>(
893        &self,
894        visitor: &mut V,
895    ) -> V::Result {
896        match (*self).kind() {
897            TyKind::RawPtr(ty, _mutbl) => ty.visit_with(visitor),
898            TyKind::Array(typ, sz) => {
899                try_visit!(typ.visit_with(visitor));
900                sz.visit_with(visitor)
901            }
902            TyKind::Slice(typ) => typ.visit_with(visitor),
903            TyKind::Adt(_, args) => args.visit_with(visitor),
904            TyKind::Dynamic(ref trait_ty, ref reg) => {
905                try_visit!(trait_ty.visit_with(visitor));
906                reg.visit_with(visitor)
907            }
908            TyKind::Tuple(ts) => ts.visit_with(visitor),
909            TyKind::FnDef(_, args) => args.visit_with(visitor),
910            TyKind::FnPtr(ref sig_tys, _) => sig_tys.visit_with(visitor),
911            TyKind::UnsafeBinder(f) => f.visit_with(visitor),
912            TyKind::Ref(r, ty, _) => {
913                try_visit!(r.visit_with(visitor));
914                ty.visit_with(visitor)
915            }
916            TyKind::Coroutine(_did, ref args) => args.visit_with(visitor),
917            TyKind::CoroutineWitness(_did, ref args) => args.visit_with(visitor),
918            TyKind::Closure(_did, ref args) => args.visit_with(visitor),
919            TyKind::CoroutineClosure(_did, ref args) => args.visit_with(visitor),
920            TyKind::Alias(ref data) => data.visit_with(visitor),
921
922            TyKind::Pat(ty, pat) => {
923                try_visit!(ty.visit_with(visitor));
924                pat.visit_with(visitor)
925            }
926
927            TyKind::Error(guar) => guar.visit_with(visitor),
928
929            TyKind::Bool
930            | TyKind::Char
931            | TyKind::Str
932            | TyKind::Int(_)
933            | TyKind::Uint(_)
934            | TyKind::Float(_)
935            | TyKind::Infer(_)
936            | TyKind::Bound(..)
937            | TyKind::Placeholder(..)
938            | TyKind::Param(..)
939            | TyKind::Never
940            | TyKind::Foreign(..) => V::Result::output(),
941        }
942    }
943}
944
945impl<'db> TypeFoldable<DbInterner<'db>> for Ty<'db> {
946    fn try_fold_with<F: rustc_type_ir::FallibleTypeFolder<DbInterner<'db>>>(
947        self,
948        folder: &mut F,
949    ) -> Result<Self, F::Error> {
950        folder.try_fold_ty(self)
951    }
952    fn fold_with<F: rustc_type_ir::TypeFolder<DbInterner<'db>>>(self, folder: &mut F) -> Self {
953        folder.fold_ty(self)
954    }
955}
956
957impl<'db> TypeSuperFoldable<DbInterner<'db>> for Ty<'db> {
958    fn try_super_fold_with<F: rustc_type_ir::FallibleTypeFolder<DbInterner<'db>>>(
959        self,
960        folder: &mut F,
961    ) -> Result<Self, F::Error> {
962        let kind = match self.kind() {
963            TyKind::RawPtr(ty, mutbl) => TyKind::RawPtr(ty.try_fold_with(folder)?, mutbl),
964            TyKind::Array(typ, sz) => {
965                TyKind::Array(typ.try_fold_with(folder)?, sz.try_fold_with(folder)?)
966            }
967            TyKind::Slice(typ) => TyKind::Slice(typ.try_fold_with(folder)?),
968            TyKind::Adt(tid, args) => TyKind::Adt(tid, args.try_fold_with(folder)?),
969            TyKind::Dynamic(trait_ty, region) => {
970                TyKind::Dynamic(trait_ty.try_fold_with(folder)?, region.try_fold_with(folder)?)
971            }
972            TyKind::Tuple(ts) => TyKind::Tuple(ts.try_fold_with(folder)?),
973            TyKind::FnDef(def_id, args) => TyKind::FnDef(def_id, args.try_fold_with(folder)?),
974            TyKind::FnPtr(sig_tys, hdr) => TyKind::FnPtr(sig_tys.try_fold_with(folder)?, hdr),
975            TyKind::UnsafeBinder(f) => TyKind::UnsafeBinder(f.try_fold_with(folder)?),
976            TyKind::Ref(r, ty, mutbl) => {
977                TyKind::Ref(r.try_fold_with(folder)?, ty.try_fold_with(folder)?, mutbl)
978            }
979            TyKind::Coroutine(did, args) => TyKind::Coroutine(did, args.try_fold_with(folder)?),
980            TyKind::CoroutineWitness(did, args) => {
981                TyKind::CoroutineWitness(did, args.try_fold_with(folder)?)
982            }
983            TyKind::Closure(did, args) => TyKind::Closure(did, args.try_fold_with(folder)?),
984            TyKind::CoroutineClosure(did, args) => {
985                TyKind::CoroutineClosure(did, args.try_fold_with(folder)?)
986            }
987            TyKind::Alias(data) => TyKind::Alias(data.try_fold_with(folder)?),
988            TyKind::Pat(ty, pat) => {
989                TyKind::Pat(ty.try_fold_with(folder)?, pat.try_fold_with(folder)?)
990            }
991
992            TyKind::Bool
993            | TyKind::Char
994            | TyKind::Str
995            | TyKind::Int(_)
996            | TyKind::Uint(_)
997            | TyKind::Float(_)
998            | TyKind::Error(_)
999            | TyKind::Infer(_)
1000            | TyKind::Param(..)
1001            | TyKind::Bound(..)
1002            | TyKind::Placeholder(..)
1003            | TyKind::Never
1004            | TyKind::Foreign(..) => return Ok(self),
1005        };
1006
1007        Ok(if self.kind() == kind { self } else { Ty::new(folder.cx(), kind) })
1008    }
1009    fn super_fold_with<F: rustc_type_ir::TypeFolder<DbInterner<'db>>>(
1010        self,
1011        folder: &mut F,
1012    ) -> Self {
1013        let kind = match self.kind() {
1014            TyKind::RawPtr(ty, mutbl) => TyKind::RawPtr(ty.fold_with(folder), mutbl),
1015            TyKind::Array(typ, sz) => TyKind::Array(typ.fold_with(folder), sz.fold_with(folder)),
1016            TyKind::Slice(typ) => TyKind::Slice(typ.fold_with(folder)),
1017            TyKind::Adt(tid, args) => TyKind::Adt(tid, args.fold_with(folder)),
1018            TyKind::Dynamic(trait_ty, region) => {
1019                TyKind::Dynamic(trait_ty.fold_with(folder), region.fold_with(folder))
1020            }
1021            TyKind::Tuple(ts) => TyKind::Tuple(ts.fold_with(folder)),
1022            TyKind::FnDef(def_id, args) => TyKind::FnDef(def_id, args.fold_with(folder)),
1023            TyKind::FnPtr(sig_tys, hdr) => TyKind::FnPtr(sig_tys.fold_with(folder), hdr),
1024            TyKind::UnsafeBinder(f) => TyKind::UnsafeBinder(f.fold_with(folder)),
1025            TyKind::Ref(r, ty, mutbl) => {
1026                TyKind::Ref(r.fold_with(folder), ty.fold_with(folder), mutbl)
1027            }
1028            TyKind::Coroutine(did, args) => TyKind::Coroutine(did, args.fold_with(folder)),
1029            TyKind::CoroutineWitness(did, args) => {
1030                TyKind::CoroutineWitness(did, args.fold_with(folder))
1031            }
1032            TyKind::Closure(did, args) => TyKind::Closure(did, args.fold_with(folder)),
1033            TyKind::CoroutineClosure(did, args) => {
1034                TyKind::CoroutineClosure(did, args.fold_with(folder))
1035            }
1036            TyKind::Alias(data) => TyKind::Alias(data.fold_with(folder)),
1037            TyKind::Pat(ty, pat) => TyKind::Pat(ty.fold_with(folder), pat.fold_with(folder)),
1038
1039            TyKind::Bool
1040            | TyKind::Char
1041            | TyKind::Str
1042            | TyKind::Int(_)
1043            | TyKind::Uint(_)
1044            | TyKind::Float(_)
1045            | TyKind::Error(_)
1046            | TyKind::Infer(_)
1047            | TyKind::Param(..)
1048            | TyKind::Bound(..)
1049            | TyKind::Placeholder(..)
1050            | TyKind::Never
1051            | TyKind::Foreign(..) => return self,
1052        };
1053
1054        if self.kind() == kind { self } else { Ty::new(folder.cx(), kind) }
1055    }
1056}
1057
1058impl<'db> Relate<DbInterner<'db>> for Ty<'db> {
1059    fn relate<R: rustc_type_ir::relate::TypeRelation<DbInterner<'db>>>(
1060        relation: &mut R,
1061        a: Self,
1062        b: Self,
1063    ) -> rustc_type_ir::relate::RelateResult<DbInterner<'db>, Self> {
1064        relation.tys(a, b)
1065    }
1066}
1067
1068impl<'db> Flags for Ty<'db> {
1069    fn flags(&self) -> rustc_type_ir::TypeFlags {
1070        self.inner().flags
1071    }
1072
1073    fn outer_exclusive_binder(&self) -> rustc_type_ir::DebruijnIndex {
1074        self.inner().outer_exclusive_binder
1075    }
1076}
1077
1078impl<'db> rustc_type_ir::inherent::Ty<DbInterner<'db>> for Ty<'db> {
1079    fn new_unit(interner: DbInterner<'db>) -> Self {
1080        interner.default_types().types.unit
1081    }
1082
1083    fn new_bool(interner: DbInterner<'db>) -> Self {
1084        interner.default_types().types.bool
1085    }
1086
1087    fn new_u8(interner: DbInterner<'db>) -> Self {
1088        interner.default_types().types.u8
1089    }
1090
1091    fn new_usize(interner: DbInterner<'db>) -> Self {
1092        interner.default_types().types.usize
1093    }
1094
1095    fn new_infer(interner: DbInterner<'db>, var: InferTy) -> Self {
1096        Ty::new_infer(interner, var)
1097    }
1098
1099    fn new_var(interner: DbInterner<'db>, var: TyVid) -> Self {
1100        let Some(ty) = interner.preinterned_ty_var(var) else {
1101            return Ty::new(interner, TyKind::Infer(InferTy::TyVar(var)));
1102        };
1103        ty
1104    }
1105
1106    fn new_param(interner: DbInterner<'db>, param: ParamTy) -> Self {
1107        Ty::new(interner, TyKind::Param(param))
1108    }
1109
1110    fn new_placeholder(interner: DbInterner<'db>, param: PlaceholderType<'db>) -> Self {
1111        Ty::new(interner, TyKind::Placeholder(param))
1112    }
1113
1114    fn new_bound(interner: DbInterner<'db>, debruijn: DebruijnIndex, var: BoundTy<'db>) -> Self {
1115        Ty::new(interner, TyKind::Bound(BoundVarIndexKind::Bound(debruijn), var))
1116    }
1117
1118    fn new_anon_bound(interner: DbInterner<'db>, debruijn: DebruijnIndex, var: BoundVar) -> Self {
1119        Ty::new(
1120            interner,
1121            TyKind::Bound(
1122                BoundVarIndexKind::Bound(debruijn),
1123                BoundTy { var, kind: BoundTyKind::Anon },
1124            ),
1125        )
1126    }
1127
1128    fn new_canonical_bound(interner: DbInterner<'db>, var: BoundVar) -> Self {
1129        let Some(ty) = interner.preinterned_canonical_bound_ty(var) else {
1130            return Ty::new(
1131                interner,
1132                TyKind::Bound(
1133                    BoundVarIndexKind::Canonical,
1134                    BoundTy { var, kind: BoundTyKind::Anon },
1135                ),
1136            );
1137        };
1138        ty
1139    }
1140
1141    fn new_alias(interner: DbInterner<'db>, alias_ty: AliasTy<'db>) -> Self {
1142        Ty::new(interner, TyKind::Alias(alias_ty))
1143    }
1144
1145    // NOTE: don't remove the `guar` param, as it will most likely be present in the `Ty::new_error`
1146    // method when `Ty` gets upstreamed
1147    fn new_error(interner: DbInterner<'db>, _guar: ErrorGuaranteed) -> Self {
1148        interner.default_types().types.error
1149    }
1150
1151    fn new_adt(
1152        interner: DbInterner<'db>,
1153        adt_def: <DbInterner<'db> as Interner>::AdtDef,
1154        args: GenericArgs<'db>,
1155    ) -> Self {
1156        Ty::new(interner, TyKind::Adt(adt_def, args))
1157    }
1158
1159    fn new_foreign(interner: DbInterner<'db>, def_id: TypeAliasIdWrapper) -> Self {
1160        Ty::new(interner, TyKind::Foreign(def_id))
1161    }
1162
1163    fn new_dynamic(
1164        interner: DbInterner<'db>,
1165        preds: <DbInterner<'db> as Interner>::BoundExistentialPredicates,
1166        region: <DbInterner<'db> as Interner>::Region,
1167    ) -> Self {
1168        Ty::new(interner, TyKind::Dynamic(preds, region))
1169    }
1170
1171    fn new_coroutine(
1172        interner: DbInterner<'db>,
1173        def_id: CoroutineIdWrapper<'db>,
1174        args: <DbInterner<'db> as Interner>::GenericArgs,
1175    ) -> Self {
1176        Ty::new(interner, TyKind::Coroutine(def_id, args))
1177    }
1178
1179    fn new_coroutine_closure(
1180        interner: DbInterner<'db>,
1181        def_id: CoroutineClosureIdWrapper<'db>,
1182        args: <DbInterner<'db> as Interner>::GenericArgs,
1183    ) -> Self {
1184        Ty::new(interner, TyKind::CoroutineClosure(def_id, args))
1185    }
1186
1187    fn new_closure(
1188        interner: DbInterner<'db>,
1189        def_id: ClosureIdWrapper<'db>,
1190        args: <DbInterner<'db> as Interner>::GenericArgs,
1191    ) -> Self {
1192        Ty::new(interner, TyKind::Closure(def_id, args))
1193    }
1194
1195    fn new_coroutine_witness(
1196        interner: DbInterner<'db>,
1197        def_id: CoroutineIdWrapper<'db>,
1198        args: <DbInterner<'db> as Interner>::GenericArgs,
1199    ) -> Self {
1200        Ty::new(interner, TyKind::CoroutineWitness(def_id, args))
1201    }
1202
1203    fn new_coroutine_witness_for_coroutine(
1204        interner: DbInterner<'db>,
1205        def_id: CoroutineIdWrapper<'db>,
1206        coroutine_args: <DbInterner<'db> as Interner>::GenericArgs,
1207    ) -> Self {
1208        // HACK: Coroutine witness types are lifetime erased, so they
1209        // never reference any lifetime args from the coroutine. We erase
1210        // the regions here since we may get into situations where a
1211        // coroutine is recursively contained within itself, leading to
1212        // witness types that differ by region args. This means that
1213        // cycle detection in fulfillment will not kick in, which leads
1214        // to unnecessary overflows in async code. See the issue:
1215        // <https://github.com/rust-lang/rust/issues/145151>.
1216        let coroutine_args =
1217            interner.mk_args_from_iter(coroutine_args.iter().map(|arg| match arg.kind() {
1218                GenericArgKind::Type(_) | GenericArgKind::Const(_) => arg,
1219                GenericArgKind::Lifetime(_) => Region::new_erased(interner).into(),
1220            }));
1221        Ty::new_coroutine_witness(interner, def_id, coroutine_args)
1222    }
1223
1224    fn new_ptr(interner: DbInterner<'db>, ty: Self, mutbl: rustc_ast_ir::Mutability) -> Self {
1225        Ty::new(interner, TyKind::RawPtr(ty, mutbl))
1226    }
1227
1228    fn new_ref(
1229        interner: DbInterner<'db>,
1230        region: <DbInterner<'db> as Interner>::Region,
1231        ty: Self,
1232        mutbl: rustc_ast_ir::Mutability,
1233    ) -> Self {
1234        Ty::new(interner, TyKind::Ref(region, ty, mutbl))
1235    }
1236
1237    fn new_array_with_const_len(
1238        interner: DbInterner<'db>,
1239        ty: Self,
1240        len: <DbInterner<'db> as Interner>::Const,
1241    ) -> Self {
1242        Ty::new(interner, TyKind::Array(ty, len))
1243    }
1244
1245    fn new_slice(interner: DbInterner<'db>, ty: Self) -> Self {
1246        Ty::new(interner, TyKind::Slice(ty))
1247    }
1248
1249    fn new_tup(interner: DbInterner<'db>, tys: &[<DbInterner<'db> as Interner>::Ty]) -> Self {
1250        Ty::new(interner, TyKind::Tuple(Tys::new_from_slice(tys)))
1251    }
1252
1253    fn new_tup_from_iter<It, T>(interner: DbInterner<'db>, iter: It) -> T::Output
1254    where
1255        It: Iterator<Item = T>,
1256        T: rustc_type_ir::CollectAndApply<Self, Self>,
1257    {
1258        T::collect_and_apply(iter, |ts| Ty::new_tup(interner, ts))
1259    }
1260
1261    fn new_fn_def(
1262        interner: DbInterner<'db>,
1263        def_id: CallableIdWrapper,
1264        args: <DbInterner<'db> as Interner>::GenericArgs,
1265    ) -> Self {
1266        Ty::new(interner, TyKind::FnDef(def_id, args))
1267    }
1268
1269    fn new_fn_ptr(
1270        interner: DbInterner<'db>,
1271        sig: rustc_type_ir::Binder<DbInterner<'db>, rustc_type_ir::FnSig<DbInterner<'db>>>,
1272    ) -> Self {
1273        let (sig_tys, header) = sig.split();
1274        Ty::new(interner, TyKind::FnPtr(sig_tys, header))
1275    }
1276
1277    fn new_pat(
1278        interner: DbInterner<'db>,
1279        ty: Self,
1280        pat: <DbInterner<'db> as Interner>::Pat,
1281    ) -> Self {
1282        Ty::new(interner, TyKind::Pat(ty, pat))
1283    }
1284
1285    fn new_unsafe_binder(
1286        interner: DbInterner<'db>,
1287        ty: rustc_type_ir::Binder<DbInterner<'db>, <DbInterner<'db> as Interner>::Ty>,
1288    ) -> Self {
1289        Ty::new(interner, TyKind::UnsafeBinder(ty.into()))
1290    }
1291
1292    fn tuple_fields(self) -> <DbInterner<'db> as Interner>::Tys {
1293        match self.kind() {
1294            TyKind::Tuple(args) => args,
1295            _ => panic!("tuple_fields called on non-tuple: {self:?}"),
1296        }
1297    }
1298
1299    fn to_opt_closure_kind(self) -> Option<rustc_type_ir::ClosureKind> {
1300        match self.kind() {
1301            TyKind::Int(int_ty) => match int_ty {
1302                IntTy::I8 => Some(ClosureKind::Fn),
1303                IntTy::I16 => Some(ClosureKind::FnMut),
1304                IntTy::I32 => Some(ClosureKind::FnOnce),
1305                _ => unreachable!("cannot convert type `{:?}` to a closure kind", self),
1306            },
1307
1308            // "Bound" types appear in canonical queries when the
1309            // closure type is not yet known, and `Placeholder` and `Param`
1310            // may be encountered in generic `AsyncFnKindHelper` goals.
1311            TyKind::Bound(..) | TyKind::Placeholder(_) | TyKind::Param(_) | TyKind::Infer(_) => {
1312                None
1313            }
1314
1315            TyKind::Error(_) => Some(ClosureKind::Fn),
1316
1317            _ => unreachable!("cannot convert type `{:?}` to a closure kind", self),
1318        }
1319    }
1320
1321    fn from_closure_kind(interner: DbInterner<'db>, kind: rustc_type_ir::ClosureKind) -> Self {
1322        let types = interner.default_types();
1323        match kind {
1324            ClosureKind::Fn => types.types.i8,
1325            ClosureKind::FnMut => types.types.i16,
1326            ClosureKind::FnOnce => types.types.i32,
1327        }
1328    }
1329
1330    fn from_coroutine_closure_kind(
1331        interner: DbInterner<'db>,
1332        kind: rustc_type_ir::ClosureKind,
1333    ) -> Self {
1334        let types = interner.default_types();
1335        match kind {
1336            ClosureKind::Fn | ClosureKind::FnMut => types.types.i16,
1337            ClosureKind::FnOnce => types.types.i32,
1338        }
1339    }
1340
1341    fn has_unsafe_fields(self) -> bool {
1342        false
1343    }
1344
1345    fn discriminant_ty(self, interner: DbInterner<'db>) -> Ty<'db> {
1346        match self.kind() {
1347            TyKind::Adt(adt, _) if adt.is_enum() => {
1348                adt.repr(interner.db).discr_type().to_ty(interner)
1349            }
1350            TyKind::Coroutine(_, args) => args.as_coroutine().discr_ty(interner),
1351
1352            TyKind::Param(_) | TyKind::Alias(..) | TyKind::Infer(InferTy::TyVar(_)) => {
1353                /*
1354                let assoc_items = tcx.associated_item_def_ids(
1355                    tcx.require_lang_item(hir::LangItem::DiscriminantKind, None),
1356                );
1357                TyKind::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1358                */
1359                unimplemented!()
1360            }
1361
1362            TyKind::Pat(ty, _) => ty.discriminant_ty(interner),
1363
1364            TyKind::Bool
1365            | TyKind::Char
1366            | TyKind::Int(_)
1367            | TyKind::Uint(_)
1368            | TyKind::Float(_)
1369            | TyKind::Adt(..)
1370            | TyKind::Foreign(_)
1371            | TyKind::Str
1372            | TyKind::Array(..)
1373            | TyKind::Slice(_)
1374            | TyKind::RawPtr(_, _)
1375            | TyKind::Ref(..)
1376            | TyKind::FnDef(..)
1377            | TyKind::FnPtr(..)
1378            | TyKind::Dynamic(..)
1379            | TyKind::Closure(..)
1380            | TyKind::CoroutineClosure(..)
1381            | TyKind::CoroutineWitness(..)
1382            | TyKind::Never
1383            | TyKind::Tuple(_)
1384            | TyKind::Error(_)
1385            | TyKind::Infer(InferTy::IntVar(_) | InferTy::FloatVar(_)) => {
1386                interner.default_types().types.u8
1387            }
1388
1389            TyKind::Bound(..)
1390            | TyKind::Placeholder(_)
1391            | TyKind::Infer(
1392                InferTy::FreshTy(_) | InferTy::FreshIntTy(_) | InferTy::FreshFloatTy(_),
1393            ) => {
1394                panic!(
1395                    "`dself.iter().map(|v| v.try_fold_with(folder)).collect::<Result<_, _>>()?iscriminant_ty` applied to unexpected type: {self:?}"
1396                )
1397            }
1398            TyKind::UnsafeBinder(..) => unimplemented!(),
1399        }
1400    }
1401}
1402
1403interned_slice!(TysStorage, Tys, StoredTys, tys, Ty<'db>, Ty<'static>);
1404impl_foldable_for_interned_slice!(Tys);
1405impl_foldable_for_stored_type!(StoredTys);
1406
1407impl<'db> Tys<'db> {
1408    #[inline]
1409    pub fn inputs(self) -> &'db [Ty<'db>] {
1410        self.as_slice().split_last().unwrap().1
1411    }
1412}
1413
1414impl<'db> rustc_type_ir::inherent::Tys<DbInterner<'db>> for Tys<'db> {
1415    fn inputs(self) -> <DbInterner<'db> as Interner>::FnInputTys {
1416        self.as_slice().split_last().unwrap().1
1417    }
1418
1419    fn output(self) -> <DbInterner<'db> as Interner>::Ty {
1420        *self.as_slice().split_last().unwrap().0
1421    }
1422}
1423
1424pub type PlaceholderType<'db> = rustc_type_ir::PlaceholderType<DbInterner<'db>>;
1425
1426#[derive(Copy, Clone, PartialEq, Eq, Hash)]
1427pub struct ParamTy {
1428    // FIXME: I'm not pleased with this. Ideally a `Param` should only know its index - the defining item
1429    // is known from the `EarlyBinder`. This should also be beneficial for memory usage. But code currently
1430    // assumes it can get the definition from `Param` alone - so that's what we got.
1431    pub id: TypeParamId,
1432    pub index: u32,
1433}
1434
1435impl ParamTy {
1436    pub fn to_ty<'db>(self, interner: DbInterner<'db>) -> Ty<'db> {
1437        Ty::new_param(interner, self.id, self.index)
1438    }
1439}
1440
1441impl std::fmt::Debug for ParamTy {
1442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1443        write!(f, "#{}", self.index)
1444    }
1445}
1446
1447pub type BoundTy<'db> = rustc_type_ir::BoundTy<DbInterner<'db>>;
1448pub type BoundTyKind<'db> = rustc_type_ir::BoundTyKind<DbInterner<'db>>;
1449
1450#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1451pub struct ErrorGuaranteed;
1452
1453impl<V> GenericTypeVisitable<V> for ErrorGuaranteed {
1454    fn generic_visit_with(&self, _visitor: &mut V) {}
1455}
1456
1457impl<'db> TypeVisitable<DbInterner<'db>> for ErrorGuaranteed {
1458    fn visit_with<V: rustc_type_ir::TypeVisitor<DbInterner<'db>>>(
1459        &self,
1460        visitor: &mut V,
1461    ) -> V::Result {
1462        visitor.visit_error(*self)
1463    }
1464}
1465
1466impl<'db> TypeFoldable<DbInterner<'db>> for ErrorGuaranteed {
1467    fn try_fold_with<F: rustc_type_ir::FallibleTypeFolder<DbInterner<'db>>>(
1468        self,
1469        _folder: &mut F,
1470    ) -> Result<Self, F::Error> {
1471        Ok(self)
1472    }
1473    fn fold_with<F: rustc_type_ir::TypeFolder<DbInterner<'db>>>(self, _folder: &mut F) -> Self {
1474        self
1475    }
1476}
1477
1478impl ParamLike for ParamTy {
1479    fn index(self) -> u32 {
1480        self.index
1481    }
1482}
1483
1484impl<'db> DbInterner<'db> {
1485    /// Given a closure signature, returns an equivalent fn signature. Detuples
1486    /// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then
1487    /// you would get a `fn(u32, i32)`.
1488    /// `unsafety` determines the unsafety of the fn signature. If you pass
1489    /// `Safety::Unsafe` in the previous example, then you would get
1490    /// an `unsafe fn (u32, i32)`.
1491    /// It cannot convert a closure that requires unsafe.
1492    pub fn signature_unclosure(self, sig: PolyFnSig<'db>, safety: Safety) -> PolyFnSig<'db> {
1493        sig.map_bound(|s| {
1494            let params = match s.inputs()[0].kind() {
1495                TyKind::Tuple(params) => params,
1496                _ => panic!(),
1497            };
1498            // Ignore splatting, it is unsupported on closures.
1499            self.mk_fn_sig(params, s.output(), s.c_variadic(), safety, ExternAbi::Rust)
1500        })
1501    }
1502}