rustc_type_ir/
ty_kind.rs

1use std::fmt;
2use std::ops::Deref;
3
4use derive_where::derive_where;
5use rustc_ast_ir::Mutability;
6#[cfg(feature = "nightly")]
7use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8#[cfg(feature = "nightly")]
9use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext};
10use rustc_type_ir::data_structures::{NoError, UnifyKey, UnifyValue};
11use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic};
12
13use self::TyKind::*;
14pub use self::closure::*;
15use crate::inherent::*;
16#[cfg(feature = "nightly")]
17use crate::visit::TypeVisitable;
18use crate::{self as ty, DebruijnIndex, FloatTy, IntTy, Interner, UintTy};
19
20mod closure;
21
22/// Specifies how a trait object is represented.
23///
24/// This used to have a variant `DynStar`, but that variant has been removed,
25/// and it's likely this whole enum will be removed soon.
26#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
27#[cfg_attr(
28    feature = "nightly",
29    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
30)]
31pub enum DynKind {
32    /// An unsized `dyn Trait` object
33    Dyn,
34}
35
36#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
37#[cfg_attr(
38    feature = "nightly",
39    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
40)]
41pub enum AliasTyKind {
42    /// A projection `<Type as Trait>::AssocType`.
43    /// Can get normalized away if monomorphic enough.
44    Projection,
45    /// An associated type in an inherent `impl`
46    Inherent,
47    /// An opaque type (usually from `impl Trait` in type aliases or function return types)
48    /// Can only be normalized away in PostAnalysis mode or its defining scope.
49    Opaque,
50    /// A type alias that actually checks its trait bounds.
51    /// Currently only used if the type alias references opaque types.
52    /// Can always be normalized away.
53    Free,
54}
55
56impl AliasTyKind {
57    pub fn descr(self) -> &'static str {
58        match self {
59            AliasTyKind::Projection => "associated type",
60            AliasTyKind::Inherent => "inherent associated type",
61            AliasTyKind::Opaque => "opaque type",
62            AliasTyKind::Free => "type alias",
63        }
64    }
65}
66
67/// Defines the kinds of types used by the type system.
68///
69/// Types written by the user start out as `hir::TyKind` and get
70/// converted to this representation using `<dyn HirTyLowerer>::lower_ty`.
71#[cfg_attr(feature = "nightly", rustc_diagnostic_item = "IrTyKind")]
72#[derive_where(Clone, Copy, Hash, PartialEq; I: Interner)]
73#[cfg_attr(
74    feature = "nightly",
75    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
76)]
77pub enum TyKind<I: Interner> {
78    /// The primitive boolean type. Written as `bool`.
79    Bool,
80
81    /// The primitive character type; holds a Unicode scalar value
82    /// (a non-surrogate code point). Written as `char`.
83    Char,
84
85    /// A primitive signed integer type. For example, `i32`.
86    Int(IntTy),
87
88    /// A primitive unsigned integer type. For example, `u32`.
89    Uint(UintTy),
90
91    /// A primitive floating-point type. For example, `f64`.
92    Float(FloatTy),
93
94    /// Algebraic data types (ADT). For example: structures, enumerations and unions.
95    ///
96    /// For example, the type `List<i32>` would be represented using the `AdtDef`
97    /// for `struct List<T>` and the args `[i32]`.
98    ///
99    /// Note that generic parameters in fields only get lazily instantiated
100    /// by using something like `adt_def.all_fields().map(|field| field.ty(interner, args))`.
101    Adt(I::AdtDef, I::GenericArgs),
102
103    /// An unsized FFI type that is opaque to Rust. Written as `extern type T`.
104    Foreign(I::ForeignId),
105
106    /// The pointee of a string slice. Written as `str`.
107    Str,
108
109    /// An array with the given length. Written as `[T; N]`.
110    Array(I::Ty, I::Const),
111
112    /// A pattern newtype. Takes any type and restricts its valid values to its pattern.
113    /// This will also change the layout to take advantage of this restriction.
114    /// Only `Copy` and `Clone` will automatically get implemented for pattern types.
115    /// Auto-traits treat this as if it were an aggregate with a single nested type.
116    /// Only supports integer range patterns for now.
117    Pat(I::Ty, I::Pat),
118
119    /// The pointee of an array slice. Written as `[T]`.
120    Slice(I::Ty),
121
122    /// A raw pointer. Written as `*mut T` or `*const T`
123    RawPtr(I::Ty, Mutability),
124
125    /// A reference; a pointer with an associated lifetime. Written as
126    /// `&'a mut T` or `&'a T`.
127    Ref(I::Region, I::Ty, Mutability),
128
129    /// The anonymous type of a function declaration/definition. Each
130    /// function has a unique type.
131    ///
132    /// For the function `fn foo() -> i32 { 3 }` this type would be
133    /// shown to the user as `fn() -> i32 {foo}`.
134    ///
135    /// For example the type of `bar` here:
136    /// ```rust
137    /// fn foo() -> i32 { 1 }
138    /// let bar = foo; // bar: fn() -> i32 {foo}
139    /// ```
140    FnDef(I::FunctionId, I::GenericArgs),
141
142    /// A pointer to a function. Written as `fn() -> i32`.
143    ///
144    /// Note that both functions and closures start out as either
145    /// [FnDef] or [Closure] which can be then be coerced to this variant.
146    ///
147    /// For example the type of `bar` here:
148    ///
149    /// ```rust
150    /// fn foo() -> i32 { 1 }
151    /// let bar: fn() -> i32 = foo;
152    /// ```
153    ///
154    /// These two fields are equivalent to a `ty::Binder<I, FnSig<I>>`. But by
155    /// splitting that into two pieces, we get a more compact data layout that
156    /// reduces the size of `TyKind` by 8 bytes. It is a very hot type, so it's
157    /// worth the mild inconvenience.
158    FnPtr(ty::Binder<I, FnSigTys<I>>, FnHeader<I>),
159
160    /// An unsafe binder type.
161    ///
162    /// A higher-ranked type used to represent a type which has had some of its
163    /// lifetimes erased. This can be used to represent types in positions where
164    /// a lifetime is literally inexpressible, such as self-referential types.
165    UnsafeBinder(UnsafeBinderInner<I>),
166
167    /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`.
168    Dynamic(I::BoundExistentialPredicates, I::Region, DynKind),
169
170    /// The anonymous type of a closure. Used to represent the type of `|a| a`.
171    ///
172    /// Closure args contain both the - potentially instantiated - generic parameters
173    /// of its parent and some synthetic parameters. See the documentation for
174    /// `ClosureArgs` for more details.
175    Closure(I::ClosureId, I::GenericArgs),
176
177    /// The anonymous type of a closure. Used to represent the type of `async |a| a`.
178    ///
179    /// Coroutine-closure args contain both the - potentially instantiated - generic
180    /// parameters of its parent and some synthetic parameters. See the documentation
181    /// for `CoroutineClosureArgs` for more details.
182    CoroutineClosure(I::CoroutineClosureId, I::GenericArgs),
183
184    /// The anonymous type of a coroutine. Used to represent the type of
185    /// `|a| yield a`.
186    ///
187    /// For more info about coroutine args, visit the documentation for
188    /// `CoroutineArgs`.
189    Coroutine(I::CoroutineId, I::GenericArgs),
190
191    /// A type representing the types stored inside a coroutine.
192    /// This should only appear as part of the `CoroutineArgs`.
193    ///
194    /// Unlike upvars, the witness can reference lifetimes from
195    /// inside of the coroutine itself. To deal with them in
196    /// the type of the coroutine, we convert them to higher ranked
197    /// lifetimes bound by the witness itself.
198    ///
199    /// This contains the `DefId` and the `GenericArgsRef` of the coroutine.
200    /// The actual witness types are computed on MIR by the `mir_coroutine_witnesses` query.
201    ///
202    /// Looking at the following example, the witness for this coroutine
203    /// may end up as something like `for<'a> [Vec<i32>, &'a Vec<i32>]`:
204    ///
205    /// ```
206    /// #![feature(coroutines)]
207    /// #[coroutine] static |a| {
208    ///     let x = &vec![3];
209    ///     yield a;
210    ///     yield x[0];
211    /// }
212    /// # ;
213    /// ```
214    CoroutineWitness(I::CoroutineId, I::GenericArgs),
215
216    /// The never type `!`.
217    Never,
218
219    /// A tuple type. For example, `(i32, bool)`.
220    Tuple(I::Tys),
221
222    /// A projection, opaque type, free type alias, or inherent associated type.
223    /// All of these types are represented as pairs of def-id and args, and can
224    /// be normalized, so they are grouped conceptually.
225    Alias(AliasTyKind, AliasTy<I>),
226
227    /// A type parameter; for example, `T` in `fn f<T>(x: T) {}`.
228    Param(I::ParamTy),
229
230    /// Bound type variable, used to represent the `'a` in `for<'a> fn(&'a ())`.
231    ///
232    /// For canonical queries, we replace inference variables with bound variables,
233    /// so e.g. when checking whether `&'_ (): Trait<_>` holds, we canonicalize that to
234    /// `for<'a, T> &'a (): Trait<T>` and then convert the introduced bound variables
235    /// back to inference variables in a new inference context when inside of the query.
236    ///
237    /// It is conventional to render anonymous bound types like `^N` or `^D_N`,
238    /// where `N` is the bound variable's anonymous index into the binder, and
239    /// `D` is the debruijn index, or totally omitted if the debruijn index is zero.
240    ///
241    /// See the `rustc-dev-guide` for more details about
242    /// [higher-ranked trait bounds][1] and [canonical queries][2].
243    ///
244    /// [1]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html
245    /// [2]: https://rustc-dev-guide.rust-lang.org/traits/canonical-queries.html
246    Bound(DebruijnIndex, I::BoundTy),
247
248    /// A placeholder type, used during higher ranked subtyping to instantiate
249    /// bound variables.
250    ///
251    /// It is conventional to render anonymous placeholder types like `!N` or `!U_N`,
252    /// where `N` is the placeholder variable's anonymous index (which corresponds
253    /// to the bound variable's index from the binder from which it was instantiated),
254    /// and `U` is the universe index in which it is instantiated, or totally omitted
255    /// if the universe index is zero.
256    Placeholder(I::PlaceholderTy),
257
258    /// A type variable used during type checking.
259    ///
260    /// Similar to placeholders, inference variables also live in a universe to
261    /// correctly deal with higher ranked types. Though unlike placeholders,
262    /// that universe is stored in the `InferCtxt` instead of directly
263    /// inside of the type.
264    Infer(InferTy),
265
266    /// A placeholder for a type which could not be computed; this is
267    /// propagated to avoid useless error messages.
268    Error(I::ErrorGuaranteed),
269}
270
271impl<I: Interner> Eq for TyKind<I> {}
272
273impl<I: Interner> TyKind<I> {
274    pub fn fn_sig(self, interner: I) -> ty::Binder<I, ty::FnSig<I>> {
275        match self {
276            ty::FnPtr(sig_tys, hdr) => sig_tys.with(hdr),
277            ty::FnDef(def_id, args) => interner.fn_sig(def_id).instantiate(interner, args),
278            ty::Error(_) => {
279                // ignore errors (#54954)
280                ty::Binder::dummy(ty::FnSig {
281                    inputs_and_output: Default::default(),
282                    c_variadic: false,
283                    safety: I::Safety::safe(),
284                    abi: I::Abi::rust(),
285                })
286            }
287            ty::Closure(..) => panic!(
288                "to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`",
289            ),
290            _ => panic!("Ty::fn_sig() called on non-fn type: {:?}", self),
291        }
292    }
293
294    /// Returns `true` when the outermost type cannot be further normalized,
295    /// resolved, or instantiated. This includes all primitive types, but also
296    /// things like ADTs and trait objects, since even if their arguments or
297    /// nested types may be further simplified, the outermost [`ty::TyKind`] or
298    /// type constructor remains the same.
299    pub fn is_known_rigid(self) -> bool {
300        match self {
301            ty::Bool
302            | ty::Char
303            | ty::Int(_)
304            | ty::Uint(_)
305            | ty::Float(_)
306            | ty::Adt(_, _)
307            | ty::Foreign(_)
308            | ty::Str
309            | ty::Array(_, _)
310            | ty::Pat(_, _)
311            | ty::Slice(_)
312            | ty::RawPtr(_, _)
313            | ty::Ref(_, _, _)
314            | ty::FnDef(_, _)
315            | ty::FnPtr(..)
316            | ty::UnsafeBinder(_)
317            | ty::Dynamic(_, _, _)
318            | ty::Closure(_, _)
319            | ty::CoroutineClosure(_, _)
320            | ty::Coroutine(_, _)
321            | ty::CoroutineWitness(..)
322            | ty::Never
323            | ty::Tuple(_) => true,
324
325            ty::Error(_)
326            | ty::Infer(_)
327            | ty::Alias(_, _)
328            | ty::Param(_)
329            | ty::Bound(_, _)
330            | ty::Placeholder(_) => false,
331        }
332    }
333}
334
335// This is manually implemented because a derive would require `I: Debug`
336impl<I: Interner> fmt::Debug for TyKind<I> {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        match self {
339            Bool => write!(f, "bool"),
340            Char => write!(f, "char"),
341            Int(i) => write!(f, "{i:?}"),
342            Uint(u) => write!(f, "{u:?}"),
343            Float(float) => write!(f, "{float:?}"),
344            Adt(d, s) => {
345                write!(f, "{d:?}")?;
346                let mut s = s.iter();
347                let first = s.next();
348                match first {
349                    Some(first) => write!(f, "<{:?}", first)?,
350                    None => return Ok(()),
351                };
352
353                for arg in s {
354                    write!(f, ", {:?}", arg)?;
355                }
356
357                write!(f, ">")
358            }
359            Foreign(d) => f.debug_tuple("Foreign").field(d).finish(),
360            Str => write!(f, "str"),
361            Array(t, c) => write!(f, "[{t:?}; {c:?}]"),
362            Pat(t, p) => write!(f, "pattern_type!({t:?} is {p:?})"),
363            Slice(t) => write!(f, "[{:?}]", &t),
364            RawPtr(ty, mutbl) => write!(f, "*{} {:?}", mutbl.ptr_str(), ty),
365            Ref(r, t, m) => write!(f, "&{:?} {}{:?}", r, m.prefix_str(), t),
366            FnDef(d, s) => f.debug_tuple("FnDef").field(d).field(&s).finish(),
367            FnPtr(sig_tys, hdr) => write!(f, "{:?}", sig_tys.with(*hdr)),
368            // FIXME(unsafe_binder): print this like `unsafe<'a> T<'a>`.
369            UnsafeBinder(binder) => write!(f, "{:?}", binder),
370            Dynamic(p, r, repr) => match repr {
371                DynKind::Dyn => write!(f, "dyn {p:?} + {r:?}"),
372            },
373            Closure(d, s) => f.debug_tuple("Closure").field(d).field(&s).finish(),
374            CoroutineClosure(d, s) => f.debug_tuple("CoroutineClosure").field(d).field(&s).finish(),
375            Coroutine(d, s) => f.debug_tuple("Coroutine").field(d).field(&s).finish(),
376            CoroutineWitness(d, s) => f.debug_tuple("CoroutineWitness").field(d).field(&s).finish(),
377            Never => write!(f, "!"),
378            Tuple(t) => {
379                write!(f, "(")?;
380                let mut count = 0;
381                for ty in t.iter() {
382                    if count > 0 {
383                        write!(f, ", ")?;
384                    }
385                    write!(f, "{ty:?}")?;
386                    count += 1;
387                }
388                // unary tuples need a trailing comma
389                if count == 1 {
390                    write!(f, ",")?;
391                }
392                write!(f, ")")
393            }
394            Alias(i, a) => f.debug_tuple("Alias").field(i).field(&a).finish(),
395            Param(p) => write!(f, "{p:?}"),
396            Bound(d, b) => crate::debug_bound_var(f, *d, b),
397            Placeholder(p) => write!(f, "{p:?}"),
398            Infer(t) => write!(f, "{:?}", t),
399            TyKind::Error(_) => write!(f, "{{type error}}"),
400        }
401    }
402}
403
404/// Represents the projection of an associated, opaque, or lazy-type-alias type.
405///
406/// * For a projection, this would be `<Ty as Trait<...>>::N<...>`.
407/// * For an inherent projection, this would be `Ty::N<...>`.
408/// * For an opaque type, there is no explicit syntax.
409#[derive_where(Clone, Copy, Hash, PartialEq, Debug; I: Interner)]
410#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
411#[cfg_attr(
412    feature = "nightly",
413    derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext)
414)]
415pub struct AliasTy<I: Interner> {
416    /// The parameters of the associated or opaque type.
417    ///
418    /// For a projection, these are the generic parameters for the trait and the
419    /// GAT parameters, if there are any.
420    ///
421    /// For an inherent projection, they consist of the self type and the GAT parameters,
422    /// if there are any.
423    ///
424    /// For RPIT the generic parameters are for the generics of the function,
425    /// while for TAIT it is used for the generic parameters of the alias.
426    pub args: I::GenericArgs,
427
428    /// The `DefId` of the `TraitItem` or `ImplItem` for the associated type `N` depending on whether
429    /// this is a projection or an inherent projection or the `DefId` of the `OpaqueType` item if
430    /// this is an opaque.
431    ///
432    /// During codegen, `interner.type_of(def_id)` can be used to get the type of the
433    /// underlying type if the type is an opaque.
434    ///
435    /// Note that if this is an associated type, this is not the `DefId` of the
436    /// `TraitRef` containing this associated type, which is in `interner.associated_item(def_id).container`,
437    /// aka. `interner.parent(def_id)`.
438    pub def_id: I::DefId,
439
440    /// This field exists to prevent the creation of `AliasTy` without using [`AliasTy::new_from_args`].
441    #[derive_where(skip(Debug))]
442    pub(crate) _use_alias_ty_new_instead: (),
443}
444
445impl<I: Interner> Eq for AliasTy<I> {}
446
447impl<I: Interner> AliasTy<I> {
448    pub fn new_from_args(interner: I, def_id: I::DefId, args: I::GenericArgs) -> AliasTy<I> {
449        interner.debug_assert_args_compatible(def_id, args);
450        AliasTy { def_id, args, _use_alias_ty_new_instead: () }
451    }
452
453    pub fn new(
454        interner: I,
455        def_id: I::DefId,
456        args: impl IntoIterator<Item: Into<I::GenericArg>>,
457    ) -> AliasTy<I> {
458        let args = interner.mk_args_from_iter(args.into_iter().map(Into::into));
459        Self::new_from_args(interner, def_id, args)
460    }
461
462    pub fn kind(self, interner: I) -> AliasTyKind {
463        interner.alias_ty_kind(self)
464    }
465
466    /// Whether this alias type is an opaque.
467    pub fn is_opaque(self, interner: I) -> bool {
468        matches!(self.kind(interner), AliasTyKind::Opaque)
469    }
470
471    pub fn to_ty(self, interner: I) -> I::Ty {
472        Ty::new_alias(interner, self.kind(interner), self)
473    }
474}
475
476/// The following methods work only with (trait) associated type projections.
477impl<I: Interner> AliasTy<I> {
478    pub fn self_ty(self) -> I::Ty {
479        self.args.type_at(0)
480    }
481
482    pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> Self {
483        AliasTy::new(
484            interner,
485            self.def_id,
486            [self_ty.into()].into_iter().chain(self.args.iter().skip(1)),
487        )
488    }
489
490    pub fn trait_def_id(self, interner: I) -> I::DefId {
491        assert_eq!(self.kind(interner), AliasTyKind::Projection, "expected a projection");
492        interner.parent(self.def_id)
493    }
494
495    /// Extracts the underlying trait reference and own args from this projection.
496    /// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`,
497    /// then this function would return a `T: StreamingIterator` trait reference and
498    /// `['a]` as the own args.
499    pub fn trait_ref_and_own_args(self, interner: I) -> (ty::TraitRef<I>, I::GenericArgsSlice) {
500        debug_assert_eq!(self.kind(interner), AliasTyKind::Projection);
501        interner.trait_ref_and_own_args_for_alias(self.def_id, self.args)
502    }
503
504    /// Extracts the underlying trait reference from this projection.
505    /// For example, if this is a projection of `<T as Iterator>::Item`,
506    /// then this function would return a `T: Iterator` trait reference.
507    ///
508    /// WARNING: This will drop the args for generic associated types
509    /// consider calling [Self::trait_ref_and_own_args] to get those
510    /// as well.
511    pub fn trait_ref(self, interner: I) -> ty::TraitRef<I> {
512        self.trait_ref_and_own_args(interner).0
513    }
514}
515
516#[derive(Clone, Copy, PartialEq, Eq, Debug)]
517pub enum IntVarValue {
518    Unknown,
519    IntType(IntTy),
520    UintType(UintTy),
521}
522
523impl IntVarValue {
524    pub fn is_known(self) -> bool {
525        match self {
526            IntVarValue::IntType(_) | IntVarValue::UintType(_) => true,
527            IntVarValue::Unknown => false,
528        }
529    }
530
531    pub fn is_unknown(self) -> bool {
532        !self.is_known()
533    }
534}
535
536#[derive(Clone, Copy, PartialEq, Eq, Debug)]
537pub enum FloatVarValue {
538    Unknown,
539    Known(FloatTy),
540}
541
542impl FloatVarValue {
543    pub fn is_known(self) -> bool {
544        match self {
545            FloatVarValue::Known(_) => true,
546            FloatVarValue::Unknown => false,
547        }
548    }
549
550    pub fn is_unknown(self) -> bool {
551        !self.is_known()
552    }
553}
554
555rustc_index::newtype_index! {
556    /// A **ty**pe **v**ariable **ID**.
557    #[encodable]
558    #[orderable]
559    #[debug_format = "?{}t"]
560    #[gate_rustc_only]
561    pub struct TyVid {}
562}
563
564rustc_index::newtype_index! {
565    /// An **int**egral (`u32`, `i32`, `usize`, etc.) type **v**ariable **ID**.
566    #[encodable]
567    #[orderable]
568    #[debug_format = "?{}i"]
569    #[gate_rustc_only]
570    pub struct IntVid {}
571}
572
573rustc_index::newtype_index! {
574    /// A **float**ing-point (`f32` or `f64`) type **v**ariable **ID**.
575    #[encodable]
576    #[orderable]
577    #[debug_format = "?{}f"]
578    #[gate_rustc_only]
579    pub struct FloatVid {}
580}
581
582/// A placeholder for a type that hasn't been inferred yet.
583///
584/// E.g., if we have an empty array (`[]`), then we create a fresh
585/// type variable for the element type since we won't know until it's
586/// used what the element type is supposed to be.
587#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
588#[cfg_attr(feature = "nightly", derive(Encodable_NoContext, Decodable_NoContext))]
589pub enum InferTy {
590    /// A type variable.
591    TyVar(TyVid),
592    /// An integral type variable (`{integer}`).
593    ///
594    /// These are created when the compiler sees an integer literal like
595    /// `1` that could be several different types (`u8`, `i32`, `u32`, etc.).
596    /// We don't know until it's used what type it's supposed to be, so
597    /// we create a fresh type variable.
598    IntVar(IntVid),
599    /// A floating-point type variable (`{float}`).
600    ///
601    /// These are created when the compiler sees an float literal like
602    /// `1.0` that could be either an `f32` or an `f64`.
603    /// We don't know until it's used what type it's supposed to be, so
604    /// we create a fresh type variable.
605    FloatVar(FloatVid),
606
607    /// A [`FreshTy`][Self::FreshTy] is one that is generated as a replacement
608    /// for an unbound type variable. This is convenient for caching etc. See
609    /// `rustc_infer::infer::freshen` for more details.
610    ///
611    /// Compare with [`TyVar`][Self::TyVar].
612    FreshTy(u32),
613    /// Like [`FreshTy`][Self::FreshTy], but as a replacement for [`IntVar`][Self::IntVar].
614    FreshIntTy(u32),
615    /// Like [`FreshTy`][Self::FreshTy], but as a replacement for [`FloatVar`][Self::FloatVar].
616    FreshFloatTy(u32),
617}
618
619impl UnifyValue for IntVarValue {
620    type Error = NoError;
621
622    fn unify_values(value1: &Self, value2: &Self) -> Result<Self, Self::Error> {
623        match (*value1, *value2) {
624            (IntVarValue::Unknown, IntVarValue::Unknown) => Ok(IntVarValue::Unknown),
625            (
626                IntVarValue::Unknown,
627                known @ (IntVarValue::UintType(_) | IntVarValue::IntType(_)),
628            )
629            | (
630                known @ (IntVarValue::UintType(_) | IntVarValue::IntType(_)),
631                IntVarValue::Unknown,
632            ) => Ok(known),
633            _ => panic!("differing ints should have been resolved first"),
634        }
635    }
636}
637
638impl UnifyKey for IntVid {
639    type Value = IntVarValue;
640    #[inline] // make this function eligible for inlining - it is quite hot.
641    fn index(&self) -> u32 {
642        self.as_u32()
643    }
644    #[inline]
645    fn from_index(i: u32) -> IntVid {
646        IntVid::from_u32(i)
647    }
648    fn tag() -> &'static str {
649        "IntVid"
650    }
651}
652
653impl UnifyValue for FloatVarValue {
654    type Error = NoError;
655
656    fn unify_values(value1: &Self, value2: &Self) -> Result<Self, Self::Error> {
657        match (*value1, *value2) {
658            (FloatVarValue::Unknown, FloatVarValue::Unknown) => Ok(FloatVarValue::Unknown),
659            (FloatVarValue::Unknown, FloatVarValue::Known(known))
660            | (FloatVarValue::Known(known), FloatVarValue::Unknown) => {
661                Ok(FloatVarValue::Known(known))
662            }
663            (FloatVarValue::Known(_), FloatVarValue::Known(_)) => {
664                panic!("differing floats should have been resolved first")
665            }
666        }
667    }
668}
669
670impl UnifyKey for FloatVid {
671    type Value = FloatVarValue;
672    #[inline]
673    fn index(&self) -> u32 {
674        self.as_u32()
675    }
676    #[inline]
677    fn from_index(i: u32) -> FloatVid {
678        FloatVid::from_u32(i)
679    }
680    fn tag() -> &'static str {
681        "FloatVid"
682    }
683}
684
685#[cfg(feature = "nightly")]
686impl<CTX> HashStable<CTX> for InferTy {
687    fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
688        use InferTy::*;
689        std::mem::discriminant(self).hash_stable(ctx, hasher);
690        match self {
691            TyVar(_) | IntVar(_) | FloatVar(_) => {
692                panic!("type variables should not be hashed: {self:?}")
693            }
694            FreshTy(v) | FreshIntTy(v) | FreshFloatTy(v) => v.hash_stable(ctx, hasher),
695        }
696    }
697}
698
699impl fmt::Display for InferTy {
700    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
701        use InferTy::*;
702        match *self {
703            TyVar(_) => write!(f, "_"),
704            IntVar(_) => write!(f, "{}", "{integer}"),
705            FloatVar(_) => write!(f, "{}", "{float}"),
706            FreshTy(v) => write!(f, "FreshTy({v})"),
707            FreshIntTy(v) => write!(f, "FreshIntTy({v})"),
708            FreshFloatTy(v) => write!(f, "FreshFloatTy({v})"),
709        }
710    }
711}
712
713impl fmt::Debug for InferTy {
714    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715        use InferTy::*;
716        match *self {
717            TyVar(ref v) => v.fmt(f),
718            IntVar(ref v) => v.fmt(f),
719            FloatVar(ref v) => v.fmt(f),
720            FreshTy(v) => write!(f, "FreshTy({v:?})"),
721            FreshIntTy(v) => write!(f, "FreshIntTy({v:?})"),
722            FreshFloatTy(v) => write!(f, "FreshFloatTy({v:?})"),
723        }
724    }
725}
726
727#[derive_where(Clone, Copy, PartialEq, Hash, Debug; I: Interner)]
728#[cfg_attr(
729    feature = "nightly",
730    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
731)]
732#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
733pub struct TypeAndMut<I: Interner> {
734    pub ty: I::Ty,
735    pub mutbl: Mutability,
736}
737
738impl<I: Interner> Eq for TypeAndMut<I> {}
739
740#[derive_where(Clone, Copy, PartialEq, Hash; I: Interner)]
741#[cfg_attr(
742    feature = "nightly",
743    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
744)]
745#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
746pub struct FnSig<I: Interner> {
747    pub inputs_and_output: I::Tys,
748    pub c_variadic: bool,
749    #[type_visitable(ignore)]
750    #[type_foldable(identity)]
751    pub safety: I::Safety,
752    #[type_visitable(ignore)]
753    #[type_foldable(identity)]
754    pub abi: I::Abi,
755}
756
757impl<I: Interner> Eq for FnSig<I> {}
758
759impl<I: Interner> FnSig<I> {
760    pub fn inputs(self) -> I::FnInputTys {
761        self.inputs_and_output.inputs()
762    }
763
764    pub fn output(self) -> I::Ty {
765        self.inputs_and_output.output()
766    }
767
768    pub fn is_fn_trait_compatible(self) -> bool {
769        let FnSig { safety, abi, c_variadic, .. } = self;
770        !c_variadic && safety.is_safe() && abi.is_rust()
771    }
772}
773
774impl<I: Interner> ty::Binder<I, FnSig<I>> {
775    #[inline]
776    pub fn inputs(self) -> ty::Binder<I, I::FnInputTys> {
777        self.map_bound(|fn_sig| fn_sig.inputs())
778    }
779
780    #[inline]
781    #[track_caller]
782    pub fn input(self, index: usize) -> ty::Binder<I, I::Ty> {
783        self.map_bound(|fn_sig| fn_sig.inputs().get(index).unwrap())
784    }
785
786    pub fn inputs_and_output(self) -> ty::Binder<I, I::Tys> {
787        self.map_bound(|fn_sig| fn_sig.inputs_and_output)
788    }
789
790    #[inline]
791    pub fn output(self) -> ty::Binder<I, I::Ty> {
792        self.map_bound(|fn_sig| fn_sig.output())
793    }
794
795    pub fn c_variadic(self) -> bool {
796        self.skip_binder().c_variadic
797    }
798
799    pub fn safety(self) -> I::Safety {
800        self.skip_binder().safety
801    }
802
803    pub fn abi(self) -> I::Abi {
804        self.skip_binder().abi
805    }
806
807    pub fn is_fn_trait_compatible(&self) -> bool {
808        self.skip_binder().is_fn_trait_compatible()
809    }
810
811    // Used to split a single value into the two fields in `TyKind::FnPtr`.
812    pub fn split(self) -> (ty::Binder<I, FnSigTys<I>>, FnHeader<I>) {
813        let hdr =
814            FnHeader { c_variadic: self.c_variadic(), safety: self.safety(), abi: self.abi() };
815        (self.map_bound(|sig| FnSigTys { inputs_and_output: sig.inputs_and_output }), hdr)
816    }
817}
818
819impl<I: Interner> fmt::Debug for FnSig<I> {
820    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
821        let sig = self;
822        let FnSig { inputs_and_output: _, c_variadic, safety, abi } = sig;
823
824        write!(f, "{}", safety.prefix_str())?;
825        if !abi.is_rust() {
826            write!(f, "extern \"{abi:?}\" ")?;
827        }
828
829        write!(f, "fn(")?;
830        let inputs = sig.inputs();
831        for (i, ty) in inputs.iter().enumerate() {
832            if i > 0 {
833                write!(f, ", ")?;
834            }
835            write!(f, "{ty:?}")?;
836        }
837        if *c_variadic {
838            if inputs.is_empty() {
839                write!(f, "...")?;
840            } else {
841                write!(f, ", ...")?;
842            }
843        }
844        write!(f, ")")?;
845
846        let output = sig.output();
847        match output.kind() {
848            Tuple(list) if list.is_empty() => Ok(()),
849            _ => write!(f, " -> {:?}", sig.output()),
850        }
851    }
852}
853
854// FIXME: this is a distinct type because we need to define `Encode`/`Decode`
855// impls in this crate for `Binder<I, I::Ty>`.
856#[derive_where(Clone, Copy, PartialEq, Hash; I: Interner)]
857#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
858#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
859pub struct UnsafeBinderInner<I: Interner>(ty::Binder<I, I::Ty>);
860
861impl<I: Interner> Eq for UnsafeBinderInner<I> {}
862
863impl<I: Interner> From<ty::Binder<I, I::Ty>> for UnsafeBinderInner<I> {
864    fn from(value: ty::Binder<I, I::Ty>) -> Self {
865        UnsafeBinderInner(value)
866    }
867}
868
869impl<I: Interner> From<UnsafeBinderInner<I>> for ty::Binder<I, I::Ty> {
870    fn from(value: UnsafeBinderInner<I>) -> Self {
871        value.0
872    }
873}
874
875impl<I: Interner> fmt::Debug for UnsafeBinderInner<I> {
876    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
877        self.0.fmt(f)
878    }
879}
880
881impl<I: Interner> Deref for UnsafeBinderInner<I> {
882    type Target = ty::Binder<I, I::Ty>;
883
884    fn deref(&self) -> &Self::Target {
885        &self.0
886    }
887}
888
889#[cfg(feature = "nightly")]
890impl<I: Interner, E: rustc_serialize::Encoder> rustc_serialize::Encodable<E>
891    for UnsafeBinderInner<I>
892where
893    I::Ty: rustc_serialize::Encodable<E>,
894    I::BoundVarKinds: rustc_serialize::Encodable<E>,
895{
896    fn encode(&self, e: &mut E) {
897        self.bound_vars().encode(e);
898        self.as_ref().skip_binder().encode(e);
899    }
900}
901
902#[cfg(feature = "nightly")]
903impl<I: Interner, D: rustc_serialize::Decoder> rustc_serialize::Decodable<D>
904    for UnsafeBinderInner<I>
905where
906    I::Ty: TypeVisitable<I> + rustc_serialize::Decodable<D>,
907    I::BoundVarKinds: rustc_serialize::Decodable<D>,
908{
909    fn decode(decoder: &mut D) -> Self {
910        let bound_vars = rustc_serialize::Decodable::decode(decoder);
911        UnsafeBinderInner(ty::Binder::bind_with_vars(
912            rustc_serialize::Decodable::decode(decoder),
913            bound_vars,
914        ))
915    }
916}
917
918// This is just a `FnSig` without the `FnHeader` fields.
919#[derive_where(Clone, Copy, Debug, PartialEq, Hash; I: Interner)]
920#[cfg_attr(
921    feature = "nightly",
922    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
923)]
924#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
925pub struct FnSigTys<I: Interner> {
926    pub inputs_and_output: I::Tys,
927}
928
929impl<I: Interner> Eq for FnSigTys<I> {}
930
931impl<I: Interner> FnSigTys<I> {
932    pub fn inputs(self) -> I::FnInputTys {
933        self.inputs_and_output.inputs()
934    }
935
936    pub fn output(self) -> I::Ty {
937        self.inputs_and_output.output()
938    }
939}
940
941impl<I: Interner> ty::Binder<I, FnSigTys<I>> {
942    // Used to combine the two fields in `TyKind::FnPtr` into a single value.
943    pub fn with(self, hdr: FnHeader<I>) -> ty::Binder<I, FnSig<I>> {
944        self.map_bound(|sig_tys| FnSig {
945            inputs_and_output: sig_tys.inputs_and_output,
946            c_variadic: hdr.c_variadic,
947            safety: hdr.safety,
948            abi: hdr.abi,
949        })
950    }
951
952    #[inline]
953    pub fn inputs(self) -> ty::Binder<I, I::FnInputTys> {
954        self.map_bound(|sig_tys| sig_tys.inputs())
955    }
956
957    #[inline]
958    #[track_caller]
959    pub fn input(self, index: usize) -> ty::Binder<I, I::Ty> {
960        self.map_bound(|sig_tys| sig_tys.inputs().get(index).unwrap())
961    }
962
963    pub fn inputs_and_output(self) -> ty::Binder<I, I::Tys> {
964        self.map_bound(|sig_tys| sig_tys.inputs_and_output)
965    }
966
967    #[inline]
968    pub fn output(self) -> ty::Binder<I, I::Ty> {
969        self.map_bound(|sig_tys| sig_tys.output())
970    }
971}
972
973#[derive_where(Clone, Copy, Debug, PartialEq, Hash; I: Interner)]
974#[cfg_attr(
975    feature = "nightly",
976    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
977)]
978#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
979pub struct FnHeader<I: Interner> {
980    pub c_variadic: bool,
981    pub safety: I::Safety,
982    pub abi: I::Abi,
983}
984
985impl<I: Interner> Eq for FnHeader<I> {}
986
987#[derive_where(Clone, Copy, Debug, PartialEq, Hash; I: Interner)]
988#[cfg_attr(
989    feature = "nightly",
990    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
991)]
992#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
993pub struct CoroutineWitnessTypes<I: Interner> {
994    pub types: I::Tys,
995    pub assumptions: I::RegionAssumptions,
996}
997
998impl<I: Interner> Eq for CoroutineWitnessTypes<I> {}