1 #![feature(fmt_helpers_for_derive)]
2 #![feature(min_specialization)]
3 #![feature(rustc_attrs)]
8 extern crate rustc_macros;
10 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
11 use rustc_data_structures::unify::{EqUnifyValue, UnifyKey};
12 use smallvec::SmallVec;
16 use std::mem::discriminant;
25 type AdtDef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
26 type SubstsRef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
27 type DefId: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
28 type Ty: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
29 type Const: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
30 type Region: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
31 type TypeAndMut: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
32 type Mutability: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
33 type Movability: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
34 type PolyFnSig: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
35 type ListBinderExistentialPredicate: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
36 type BinderListTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
37 type ListTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
38 type ProjectionTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
39 type ParamTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
40 type BoundTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
41 type PlaceholderType: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
42 type InferTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
43 type DelaySpanBugEmitted: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
44 type PredicateKind: Clone + Debug + Hash + PartialEq + Eq;
45 type AllocId: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
47 type EarlyBoundRegion: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
48 type BoundRegion: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
49 type FreeRegion: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
50 type RegionVid: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
51 type PlaceholderRegion: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
54 pub trait InternAs<T: ?Sized, R> {
56 fn intern_with<F>(self, f: F) -> Self::Output
61 impl<I, T, R, E> InternAs<[T], R> for I
63 E: InternIteratorElement<T, R>,
64 I: Iterator<Item = E>,
66 type Output = E::Output;
67 fn intern_with<F>(self, f: F) -> Self::Output
71 E::intern_with(self, f)
75 pub trait InternIteratorElement<T, R>: Sized {
77 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
80 impl<T, R> InternIteratorElement<T, R> for T {
82 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
86 // This code is hot enough that it's worth specializing for the most
87 // common length lists, to avoid the overhead of `SmallVec` creation.
88 // Lengths 0, 1, and 2 typically account for ~95% of cases. If
89 // `size_hint` is incorrect a panic will occur via an `unwrap` or an
91 match iter.size_hint() {
93 assert!(iter.next().is_none());
97 let t0 = iter.next().unwrap();
98 assert!(iter.next().is_none());
102 let t0 = iter.next().unwrap();
103 let t1 = iter.next().unwrap();
104 assert!(iter.next().is_none());
107 _ => f(&iter.collect::<SmallVec<[_; 8]>>()),
112 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
117 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
118 // This code isn't hot.
119 f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
123 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
124 type Output = Result<R, E>;
125 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
129 // This code is hot enough that it's worth specializing for the most
130 // common length lists, to avoid the overhead of `SmallVec` creation.
131 // Lengths 0, 1, and 2 typically account for ~95% of cases. If
132 // `size_hint` is incorrect a panic will occur via an `unwrap` or an
133 // `assert`, unless a failure happens first, in which case the result
134 // will be an error anyway.
135 Ok(match iter.size_hint() {
137 assert!(iter.next().is_none());
141 let t0 = iter.next().unwrap()?;
142 assert!(iter.next().is_none());
146 let t0 = iter.next().unwrap()?;
147 let t1 = iter.next().unwrap()?;
148 assert!(iter.next().is_none());
151 _ => f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?),
157 /// Flags that we track on types. These flags are propagated upwards
158 /// through the type during type construction, so that we can quickly check
159 /// whether the type has various kinds of types in it without recursing
160 /// over the type itself.
161 pub struct TypeFlags: u32 {
162 // Does this have parameters? Used to determine whether substitution is
164 /// Does this have `Param`?
165 const HAS_TY_PARAM = 1 << 0;
166 /// Does this have `ReEarlyBound`?
167 const HAS_RE_PARAM = 1 << 1;
168 /// Does this have `ConstKind::Param`?
169 const HAS_CT_PARAM = 1 << 2;
171 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
172 | TypeFlags::HAS_RE_PARAM.bits
173 | TypeFlags::HAS_CT_PARAM.bits;
175 /// Does this have `Infer`?
176 const HAS_TY_INFER = 1 << 3;
177 /// Does this have `ReVar`?
178 const HAS_RE_INFER = 1 << 4;
179 /// Does this have `ConstKind::Infer`?
180 const HAS_CT_INFER = 1 << 5;
182 /// Does this have inference variables? Used to determine whether
183 /// inference is required.
184 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
185 | TypeFlags::HAS_RE_INFER.bits
186 | TypeFlags::HAS_CT_INFER.bits;
188 /// Does this have `Placeholder`?
189 const HAS_TY_PLACEHOLDER = 1 << 6;
190 /// Does this have `RePlaceholder`?
191 const HAS_RE_PLACEHOLDER = 1 << 7;
192 /// Does this have `ConstKind::Placeholder`?
193 const HAS_CT_PLACEHOLDER = 1 << 8;
195 /// `true` if there are "names" of regions and so forth
196 /// that are local to a particular fn/inferctxt
197 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
199 /// `true` if there are "names" of types and regions and so forth
200 /// that are local to a particular fn
201 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
202 | TypeFlags::HAS_CT_PARAM.bits
203 | TypeFlags::HAS_TY_INFER.bits
204 | TypeFlags::HAS_CT_INFER.bits
205 | TypeFlags::HAS_TY_PLACEHOLDER.bits
206 | TypeFlags::HAS_CT_PLACEHOLDER.bits
207 // We consider 'freshened' types and constants
208 // to depend on a particular fn.
209 // The freshening process throws away information,
210 // which can make things unsuitable for use in a global
211 // cache. Note that there is no 'fresh lifetime' flag -
212 // freshening replaces all lifetimes with `ReErased`,
213 // which is different from how types/const are freshened.
214 | TypeFlags::HAS_TY_FRESH.bits
215 | TypeFlags::HAS_CT_FRESH.bits
216 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
218 /// Does this have `Projection`?
219 const HAS_TY_PROJECTION = 1 << 10;
220 /// Does this have `Opaque`?
221 const HAS_TY_OPAQUE = 1 << 11;
222 /// Does this have `ConstKind::Unevaluated`?
223 const HAS_CT_PROJECTION = 1 << 12;
225 /// Could this type be normalized further?
226 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
227 | TypeFlags::HAS_TY_OPAQUE.bits
228 | TypeFlags::HAS_CT_PROJECTION.bits;
230 /// Is an error type/const reachable?
231 const HAS_ERROR = 1 << 13;
233 /// Does this have any region that "appears free" in the type?
234 /// Basically anything but `ReLateBound` and `ReErased`.
235 const HAS_FREE_REGIONS = 1 << 14;
237 /// Does this have any `ReLateBound` regions? Used to check
238 /// if a global bound is safe to evaluate.
239 const HAS_RE_LATE_BOUND = 1 << 15;
241 /// Does this have any `ReErased` regions?
242 const HAS_RE_ERASED = 1 << 16;
244 /// Does this value have parameters/placeholders/inference variables which could be
245 /// replaced later, in a way that would change the results of `impl` specialization?
246 const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
248 /// Does this value have `InferTy::FreshTy/FreshIntTy/FreshFloatTy`?
249 const HAS_TY_FRESH = 1 << 18;
251 /// Does this value have `InferConst::Fresh`?
252 const HAS_CT_FRESH = 1 << 19;
256 rustc_index::newtype_index! {
257 /// A [De Bruijn index][dbi] is a standard means of representing
258 /// regions (and perhaps later types) in a higher-ranked setting. In
259 /// particular, imagine a type like this:
260 /// ```ignore (illustrative)
261 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
264 /// // | +------------+ 0 | |
266 /// // +----------------------------------+ 1 |
268 /// // +----------------------------------------------+ 0
270 /// In this type, there are two binders (the outer fn and the inner
271 /// fn). We need to be able to determine, for any given region, which
272 /// fn type it is bound by, the inner or the outer one. There are
273 /// various ways you can do this, but a De Bruijn index is one of the
274 /// more convenient and has some nice properties. The basic idea is to
275 /// count the number of binders, inside out. Some examples should help
276 /// clarify what I mean.
278 /// Let's start with the reference type `&'b isize` that is the first
279 /// argument to the inner function. This region `'b` is assigned a De
280 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
281 /// fn). The region `'a` that appears in the second argument type (`&'a
282 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
283 /// second-innermost binder". (These indices are written on the arrows
286 /// What is interesting is that De Bruijn index attached to a particular
287 /// variable will vary depending on where it appears. For example,
288 /// the final type `&'a char` also refers to the region `'a` declared on
289 /// the outermost fn. But this time, this reference is not nested within
290 /// any other binders (i.e., it is not an argument to the inner fn, but
291 /// rather the outer one). Therefore, in this case, it is assigned a
292 /// De Bruijn index of 0, because the innermost binder in that location
295 /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index
296 pub struct DebruijnIndex {
297 DEBUG_FORMAT = "DebruijnIndex({})",
303 /// Returns the resulting index when this value is moved into
304 /// `amount` number of new binders. So, e.g., if you had
306 /// for<'a> fn(&'a x)
308 /// and you wanted to change it to
310 /// for<'a> fn(for<'b> fn(&'a x))
312 /// you would need to shift the index for `'a` into a new binder.
314 pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
315 DebruijnIndex::from_u32(self.as_u32() + amount)
318 /// Update this index in place by shifting it "in" through
319 /// `amount` number of binders.
320 pub fn shift_in(&mut self, amount: u32) {
321 *self = self.shifted_in(amount);
324 /// Returns the resulting index when this value is moved out from
325 /// `amount` number of new binders.
327 pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
328 DebruijnIndex::from_u32(self.as_u32() - amount)
331 /// Update in place by shifting out from `amount` binders.
332 pub fn shift_out(&mut self, amount: u32) {
333 *self = self.shifted_out(amount);
336 /// Adjusts any De Bruijn indices so as to make `to_binder` the
337 /// innermost binder. That is, if we have something bound at `to_binder`,
338 /// it will now be bound at INNERMOST. This is an appropriate thing to do
339 /// when moving a region out from inside binders:
341 /// ```ignore (illustrative)
342 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
343 /// // Binder: D3 D2 D1 ^^
346 /// Here, the region `'a` would have the De Bruijn index D3,
347 /// because it is the bound 3 binders out. However, if we wanted
348 /// to refer to that region `'a` in the second argument (the `_`),
349 /// those two binders would not be in scope. In that case, we
350 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
351 /// De Bruijn index of `'a` to D1 (the innermost binder).
353 /// If we invoke `shift_out_to_binder` and the region is in fact
354 /// bound by one of the binders we are shifting out of, that is an
355 /// error (and should fail an assertion failure).
356 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
357 self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
361 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
362 #[derive(Encodable, Decodable)]
373 pub fn name_str(&self) -> &'static str {
375 IntTy::Isize => "isize",
380 IntTy::I128 => "i128",
384 pub fn bit_width(&self) -> Option<u64> {
386 IntTy::Isize => return None,
395 pub fn normalize(&self, target_width: u32) -> Self {
397 IntTy::Isize => match target_width {
408 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
409 #[derive(Encodable, Decodable)]
420 pub fn name_str(&self) -> &'static str {
422 UintTy::Usize => "usize",
424 UintTy::U16 => "u16",
425 UintTy::U32 => "u32",
426 UintTy::U64 => "u64",
427 UintTy::U128 => "u128",
431 pub fn bit_width(&self) -> Option<u64> {
433 UintTy::Usize => return None,
442 pub fn normalize(&self, target_width: u32) -> Self {
444 UintTy::Usize => match target_width {
455 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
456 #[derive(Encodable, Decodable)]
463 pub fn name_str(self) -> &'static str {
465 FloatTy::F32 => "f32",
466 FloatTy::F64 => "f64",
470 pub fn bit_width(self) -> u64 {
478 #[derive(Clone, Copy, PartialEq, Eq)]
479 pub enum IntVarValue {
484 #[derive(Clone, Copy, PartialEq, Eq)]
485 pub struct FloatVarValue(pub FloatTy);
487 rustc_index::newtype_index! {
488 /// A **ty**pe **v**ariable **ID**.
490 DEBUG_FORMAT = "_#{}t"
494 /// An **int**egral (`u32`, `i32`, `usize`, etc.) type **v**ariable **ID**.
495 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
500 /// An **float**ing-point (`f32` or `f64`) type **v**ariable **ID**.
501 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
502 pub struct FloatVid {
506 /// A placeholder for a type that hasn't been inferred yet.
508 /// E.g., if we have an empty array (`[]`), then we create a fresh
509 /// type variable for the element type since we won't know until it's
510 /// used what the element type is supposed to be.
511 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
515 /// An integral type variable (`{integer}`).
517 /// These are created when the compiler sees an integer literal like
518 /// `1` that could be several different types (`u8`, `i32`, `u32`, etc.).
519 /// We don't know until it's used what type it's supposed to be, so
520 /// we create a fresh type variable.
522 /// A floating-point type variable (`{float}`).
524 /// These are created when the compiler sees an float literal like
525 /// `1.0` that could be either an `f32` or an `f64`.
526 /// We don't know until it's used what type it's supposed to be, so
527 /// we create a fresh type variable.
530 /// A [`FreshTy`][Self::FreshTy] is one that is generated as a replacement
531 /// for an unbound type variable. This is convenient for caching etc. See
532 /// `rustc_infer::infer::freshen` for more details.
534 /// Compare with [`TyVar`][Self::TyVar].
536 /// Like [`FreshTy`][Self::FreshTy], but as a replacement for [`IntVar`][Self::IntVar].
538 /// Like [`FreshTy`][Self::FreshTy], but as a replacement for [`FloatVar`][Self::FloatVar].
542 /// Raw `TyVid` are used as the unification key for `sub_relations`;
543 /// they carry no values.
544 impl UnifyKey for TyVid {
547 fn index(&self) -> u32 {
551 fn from_index(i: u32) -> TyVid {
554 fn tag() -> &'static str {
559 impl EqUnifyValue for IntVarValue {}
561 impl UnifyKey for IntVid {
562 type Value = Option<IntVarValue>;
563 #[inline] // make this function eligible for inlining - it is quite hot.
564 fn index(&self) -> u32 {
568 fn from_index(i: u32) -> IntVid {
571 fn tag() -> &'static str {
576 impl EqUnifyValue for FloatVarValue {}
578 impl UnifyKey for FloatVid {
579 type Value = Option<FloatVarValue>;
581 fn index(&self) -> u32 {
585 fn from_index(i: u32) -> FloatVid {
586 FloatVid { index: i }
588 fn tag() -> &'static str {
593 #[derive(Copy, Clone, PartialEq, Decodable, Encodable, Hash)]
594 #[rustc_pass_by_value]
596 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
597 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
598 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
599 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
603 /// `a.xform(b)` combines the variance of a context with the
604 /// variance of a type with the following meaning. If we are in a
605 /// context with variance `a`, and we encounter a type argument in
606 /// a position with variance `b`, then `a.xform(b)` is the new
607 /// variance with which the argument appears.
610 /// ```ignore (illustrative)
613 /// Here, the "ambient" variance starts as covariant. `*mut T` is
614 /// invariant with respect to `T`, so the variance in which the
615 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
616 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
617 /// respect to its type argument `T`, and hence the variance of
618 /// the `i32` here is `Invariant.xform(Covariant)`, which results
619 /// (again) in `Invariant`.
622 /// ```ignore (illustrative)
623 /// fn(*const Vec<i32>, *mut Vec<i32)
625 /// The ambient variance is covariant. A `fn` type is
626 /// contravariant with respect to its parameters, so the variance
627 /// within which both pointer types appear is
628 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
629 /// T` is covariant with respect to `T`, so the variance within
630 /// which the first `Vec<i32>` appears is
631 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
632 /// is true for its `i32` argument. In the `*mut T` case, the
633 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
634 /// and hence the outermost type is `Invariant` with respect to
635 /// `Vec<i32>` (and its `i32` argument).
637 /// Source: Figure 1 of "Taming the Wildcards:
638 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
639 pub fn xform(self, v: Variance) -> Variance {
641 // Figure 1, column 1.
642 (Variance::Covariant, Variance::Covariant) => Variance::Covariant,
643 (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
644 (Variance::Covariant, Variance::Invariant) => Variance::Invariant,
645 (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant,
647 // Figure 1, column 2.
648 (Variance::Contravariant, Variance::Covariant) => Variance::Contravariant,
649 (Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
650 (Variance::Contravariant, Variance::Invariant) => Variance::Invariant,
651 (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant,
653 // Figure 1, column 3.
654 (Variance::Invariant, _) => Variance::Invariant,
656 // Figure 1, column 4.
657 (Variance::Bivariant, _) => Variance::Bivariant,
662 impl<CTX> HashStable<CTX> for DebruijnIndex {
663 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
664 self.as_u32().hash_stable(ctx, hasher);
668 impl<CTX> HashStable<CTX> for IntTy {
669 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
670 discriminant(self).hash_stable(ctx, hasher);
674 impl<CTX> HashStable<CTX> for UintTy {
675 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
676 discriminant(self).hash_stable(ctx, hasher);
680 impl<CTX> HashStable<CTX> for FloatTy {
681 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
682 discriminant(self).hash_stable(ctx, hasher);
686 impl<CTX> HashStable<CTX> for InferTy {
687 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
689 discriminant(self).hash_stable(ctx, hasher);
691 TyVar(v) => v.as_u32().hash_stable(ctx, hasher),
692 IntVar(v) => v.index.hash_stable(ctx, hasher),
693 FloatVar(v) => v.index.hash_stable(ctx, hasher),
694 FreshTy(v) | FreshIntTy(v) | FreshFloatTy(v) => v.hash_stable(ctx, hasher),
699 impl<CTX> HashStable<CTX> for Variance {
700 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
701 discriminant(self).hash_stable(ctx, hasher);
705 impl fmt::Debug for IntVarValue {
706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
708 IntVarValue::IntType(ref v) => v.fmt(f),
709 IntVarValue::UintType(ref v) => v.fmt(f),
714 impl fmt::Debug for FloatVarValue {
715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
720 impl fmt::Debug for IntVid {
721 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
722 write!(f, "_#{}i", self.index)
726 impl fmt::Debug for FloatVid {
727 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
728 write!(f, "_#{}f", self.index)
732 impl fmt::Debug for InferTy {
733 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736 TyVar(ref v) => v.fmt(f),
737 IntVar(ref v) => v.fmt(f),
738 FloatVar(ref v) => v.fmt(f),
739 FreshTy(v) => write!(f, "FreshTy({:?})", v),
740 FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
741 FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v),
746 impl fmt::Debug for Variance {
747 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748 f.write_str(match *self {
749 Variance::Covariant => "+",
750 Variance::Contravariant => "-",
751 Variance::Invariant => "o",
752 Variance::Bivariant => "*",
757 impl fmt::Display for InferTy {
758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761 TyVar(_) => write!(f, "_"),
762 IntVar(_) => write!(f, "{}", "{integer}"),
763 FloatVar(_) => write!(f, "{}", "{float}"),
764 FreshTy(v) => write!(f, "FreshTy({})", v),
765 FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
766 FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v),
771 rustc_index::newtype_index! {
772 /// "Universes" are used during type- and trait-checking in the
773 /// presence of `for<..>` binders to control what sets of names are
774 /// visible. Universes are arranged into a tree: the root universe
775 /// contains names that are always visible. Each child then adds a new
776 /// set of names that are visible, in addition to those of its parent.
777 /// We say that the child universe "extends" the parent universe with
780 /// To make this more concrete, consider this program:
782 /// ```ignore (illustrative)
784 /// fn bar<T>(x: T) {
785 /// let y: for<'a> fn(&'a u8, Foo) = ...;
789 /// The struct name `Foo` is in the root universe U0. But the type
790 /// parameter `T`, introduced on `bar`, is in an extended universe U1
791 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
792 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
793 /// region `'a` is in a universe U2 that extends U1, because we can
794 /// name it inside the fn type but not outside.
796 /// Universes are used to do type- and trait-checking around these
797 /// "forall" binders (also called **universal quantification**). The
798 /// idea is that when, in the body of `bar`, we refer to `T` as a
799 /// type, we aren't referring to any type in particular, but rather a
800 /// kind of "fresh" type that is distinct from all other types we have
801 /// actually declared. This is called a **placeholder** type, and we
802 /// use universes to talk about this. In other words, a type name in
803 /// universe 0 always corresponds to some "ground" type that the user
804 /// declared, but a type name in a non-zero universe is a placeholder
805 /// type -- an idealized representative of "types in general" that we
806 /// use for checking generic functions.
807 pub struct UniverseIndex {
808 DEBUG_FORMAT = "U{}",
813 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
815 /// Returns the "next" universe index in order -- this new index
816 /// is considered to extend all previous universes. This
817 /// corresponds to entering a `forall` quantifier. So, for
818 /// example, suppose we have this type in universe `U`:
820 /// ```ignore (illustrative)
821 /// for<'a> fn(&'a u32)
824 /// Once we "enter" into this `for<'a>` quantifier, we are in a
825 /// new universe that extends `U` -- in this new universe, we can
826 /// name the region `'a`, but that region was not nameable from
827 /// `U` because it was not in scope there.
828 pub fn next_universe(self) -> UniverseIndex {
829 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
832 /// Returns `true` if `self` can name a name from `other` -- in other words,
833 /// if the set of names in `self` is a superset of those in
834 /// `other` (`self >= other`).
835 pub fn can_name(self, other: UniverseIndex) -> bool {
836 self.private >= other.private
839 /// Returns `true` if `self` cannot name some names from `other` -- in other
840 /// words, if the set of names in `self` is a strict subset of
841 /// those in `other` (`self < other`).
842 pub fn cannot_name(self, other: UniverseIndex) -> bool {
843 self.private < other.private
847 impl<CTX> HashStable<CTX> for UniverseIndex {
848 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
849 self.private.hash_stable(ctx, hasher);