1 #![feature(fmt_helpers_for_derive)]
2 #![feature(min_specialization)]
3 #![feature(rustc_attrs)]
4 #![deny(rustc::untranslatable_diagnostic)]
5 #![deny(rustc::diagnostic_outside_of_impl)]
10 extern crate rustc_macros;
12 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
13 use rustc_data_structures::unify::{EqUnifyValue, UnifyKey};
14 use smallvec::SmallVec;
18 use std::mem::discriminant;
28 /// Needed so we can use #[derive(HashStable_Generic)]
29 pub trait HashStableContext {}
32 type AdtDef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
33 type SubstsRef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
34 type DefId: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
35 type Ty: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
36 type Const: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
37 type Region: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
38 type TypeAndMut: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
39 type Mutability: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
40 type Movability: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
41 type PolyFnSig: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
42 type ListBinderExistentialPredicate: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
43 type BinderListTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
44 type ListTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
45 type AliasTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
46 type ParamTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
47 type BoundTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
48 type PlaceholderType: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
49 type InferTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
50 type ErrorGuaranteed: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
51 type PredicateKind: Clone + Debug + Hash + PartialEq + Eq;
52 type AllocId: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
54 type EarlyBoundRegion: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
55 type BoundRegion: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
56 type FreeRegion: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
57 type RegionVid: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
58 type PlaceholderRegion: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord;
61 pub trait InternAs<T: ?Sized, R> {
63 fn intern_with<F>(self, f: F) -> Self::Output
68 impl<I, T, R, E> InternAs<T, R> for I
70 E: InternIteratorElement<T, R>,
71 I: Iterator<Item = E>,
73 type Output = E::Output;
74 fn intern_with<F>(self, f: F) -> Self::Output
78 E::intern_with(self, f)
82 pub trait InternIteratorElement<T, R>: Sized {
84 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output;
87 impl<T, R> InternIteratorElement<T, R> for T {
89 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
93 // This code is hot enough that it's worth specializing for the most
94 // common length lists, to avoid the overhead of `SmallVec` creation.
95 // Lengths 0, 1, and 2 typically account for ~95% of cases. If
96 // `size_hint` is incorrect a panic will occur via an `unwrap` or an
98 match iter.size_hint() {
100 assert!(iter.next().is_none());
104 let t0 = iter.next().unwrap();
105 assert!(iter.next().is_none());
109 let t0 = iter.next().unwrap();
110 let t1 = iter.next().unwrap();
111 assert!(iter.next().is_none());
114 _ => f(&iter.collect::<SmallVec<[_; 8]>>()),
119 impl<'a, T, R> InternIteratorElement<T, R> for &'a T
124 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output {
125 // This code isn't hot.
126 f(&iter.cloned().collect::<SmallVec<[_; 8]>>())
130 impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
131 type Output = Result<R, E>;
132 fn intern_with<I: Iterator<Item = Self>, F: FnOnce(&[T]) -> R>(
136 // This code is hot enough that it's worth specializing for the most
137 // common length lists, to avoid the overhead of `SmallVec` creation.
138 // Lengths 0, 1, and 2 typically account for ~95% of cases. If
139 // `size_hint` is incorrect a panic will occur via an `unwrap` or an
140 // `assert`, unless a failure happens first, in which case the result
141 // will be an error anyway.
142 Ok(match iter.size_hint() {
144 assert!(iter.next().is_none());
148 let t0 = iter.next().unwrap()?;
149 assert!(iter.next().is_none());
153 let t0 = iter.next().unwrap()?;
154 let t1 = iter.next().unwrap()?;
155 assert!(iter.next().is_none());
158 _ => f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?),
164 /// Flags that we track on types. These flags are propagated upwards
165 /// through the type during type construction, so that we can quickly check
166 /// whether the type has various kinds of types in it without recursing
167 /// over the type itself.
168 pub struct TypeFlags: u32 {
169 // Does this have parameters? Used to determine whether substitution is
171 /// Does this have `Param`?
172 const HAS_TY_PARAM = 1 << 0;
173 /// Does this have `ReEarlyBound`?
174 const HAS_RE_PARAM = 1 << 1;
175 /// Does this have `ConstKind::Param`?
176 const HAS_CT_PARAM = 1 << 2;
178 const NEEDS_SUBST = TypeFlags::HAS_TY_PARAM.bits
179 | TypeFlags::HAS_RE_PARAM.bits
180 | TypeFlags::HAS_CT_PARAM.bits;
182 /// Does this have `Infer`?
183 const HAS_TY_INFER = 1 << 3;
184 /// Does this have `ReVar`?
185 const HAS_RE_INFER = 1 << 4;
186 /// Does this have `ConstKind::Infer`?
187 const HAS_CT_INFER = 1 << 5;
189 /// Does this have inference variables? Used to determine whether
190 /// inference is required.
191 const NEEDS_INFER = TypeFlags::HAS_TY_INFER.bits
192 | TypeFlags::HAS_RE_INFER.bits
193 | TypeFlags::HAS_CT_INFER.bits;
195 /// Does this have `Placeholder`?
196 const HAS_TY_PLACEHOLDER = 1 << 6;
197 /// Does this have `RePlaceholder`?
198 const HAS_RE_PLACEHOLDER = 1 << 7;
199 /// Does this have `ConstKind::Placeholder`?
200 const HAS_CT_PLACEHOLDER = 1 << 8;
202 /// `true` if there are "names" of regions and so forth
203 /// that are local to a particular fn/inferctxt
204 const HAS_FREE_LOCAL_REGIONS = 1 << 9;
206 /// `true` if there are "names" of types and regions and so forth
207 /// that are local to a particular fn
208 const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_PARAM.bits
209 | TypeFlags::HAS_CT_PARAM.bits
210 | TypeFlags::HAS_TY_INFER.bits
211 | TypeFlags::HAS_CT_INFER.bits
212 | TypeFlags::HAS_TY_PLACEHOLDER.bits
213 | TypeFlags::HAS_CT_PLACEHOLDER.bits
214 // We consider 'freshened' types and constants
215 // to depend on a particular fn.
216 // The freshening process throws away information,
217 // which can make things unsuitable for use in a global
218 // cache. Note that there is no 'fresh lifetime' flag -
219 // freshening replaces all lifetimes with `ReErased`,
220 // which is different from how types/const are freshened.
221 | TypeFlags::HAS_TY_FRESH.bits
222 | TypeFlags::HAS_CT_FRESH.bits
223 | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
225 /// Does this have `Projection`?
226 const HAS_TY_PROJECTION = 1 << 10;
227 /// Does this have `Opaque`?
228 const HAS_TY_OPAQUE = 1 << 11;
229 /// Does this have `ConstKind::Unevaluated`?
230 const HAS_CT_PROJECTION = 1 << 12;
232 /// Could this type be normalized further?
233 const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
234 | TypeFlags::HAS_TY_OPAQUE.bits
235 | TypeFlags::HAS_CT_PROJECTION.bits;
237 /// Is an error type/const reachable?
238 const HAS_ERROR = 1 << 13;
240 /// Does this have any region that "appears free" in the type?
241 /// Basically anything but `ReLateBound` and `ReErased`.
242 const HAS_FREE_REGIONS = 1 << 14;
244 /// Does this have any `ReLateBound` regions?
245 const HAS_RE_LATE_BOUND = 1 << 15;
246 /// Does this have any `Bound` types?
247 const HAS_TY_LATE_BOUND = 1 << 16;
248 /// Does this have any `ConstKind::Bound` consts?
249 const HAS_CT_LATE_BOUND = 1 << 17;
250 /// Does this have any bound variables?
251 /// Used to check if a global bound is safe to evaluate.
252 const HAS_LATE_BOUND = TypeFlags::HAS_RE_LATE_BOUND.bits
253 | TypeFlags::HAS_TY_LATE_BOUND.bits
254 | TypeFlags::HAS_CT_LATE_BOUND.bits;
256 /// Does this have any `ReErased` regions?
257 const HAS_RE_ERASED = 1 << 18;
259 /// Does this value have parameters/placeholders/inference variables which could be
260 /// replaced later, in a way that would change the results of `impl` specialization?
261 const STILL_FURTHER_SPECIALIZABLE = 1 << 19;
263 /// Does this value have `InferTy::FreshTy/FreshIntTy/FreshFloatTy`?
264 const HAS_TY_FRESH = 1 << 20;
266 /// Does this value have `InferConst::Fresh`?
267 const HAS_CT_FRESH = 1 << 21;
271 rustc_index::newtype_index! {
272 /// A [De Bruijn index][dbi] is a standard means of representing
273 /// regions (and perhaps later types) in a higher-ranked setting. In
274 /// particular, imagine a type like this:
275 /// ```ignore (illustrative)
276 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
279 /// // | +------------+ 0 | |
281 /// // +----------------------------------+ 1 |
283 /// // +----------------------------------------------+ 0
285 /// In this type, there are two binders (the outer fn and the inner
286 /// fn). We need to be able to determine, for any given region, which
287 /// fn type it is bound by, the inner or the outer one. There are
288 /// various ways you can do this, but a De Bruijn index is one of the
289 /// more convenient and has some nice properties. The basic idea is to
290 /// count the number of binders, inside out. Some examples should help
291 /// clarify what I mean.
293 /// Let's start with the reference type `&'b isize` that is the first
294 /// argument to the inner function. This region `'b` is assigned a De
295 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
296 /// fn). The region `'a` that appears in the second argument type (`&'a
297 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
298 /// second-innermost binder". (These indices are written on the arrows
301 /// What is interesting is that De Bruijn index attached to a particular
302 /// variable will vary depending on where it appears. For example,
303 /// the final type `&'a char` also refers to the region `'a` declared on
304 /// the outermost fn. But this time, this reference is not nested within
305 /// any other binders (i.e., it is not an argument to the inner fn, but
306 /// rather the outer one). Therefore, in this case, it is assigned a
307 /// De Bruijn index of 0, because the innermost binder in that location
310 /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index
311 #[derive(HashStable_Generic)]
312 #[debug_format = "DebruijnIndex({})"]
313 pub struct DebruijnIndex {
319 /// Returns the resulting index when this value is moved into
320 /// `amount` number of new binders. So, e.g., if you had
322 /// for<'a> fn(&'a x)
324 /// and you wanted to change it to
326 /// for<'a> fn(for<'b> fn(&'a x))
328 /// you would need to shift the index for `'a` into a new binder.
331 pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
332 DebruijnIndex::from_u32(self.as_u32() + amount)
335 /// Update this index in place by shifting it "in" through
336 /// `amount` number of binders.
338 pub fn shift_in(&mut self, amount: u32) {
339 *self = self.shifted_in(amount);
342 /// Returns the resulting index when this value is moved out from
343 /// `amount` number of new binders.
346 pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
347 DebruijnIndex::from_u32(self.as_u32() - amount)
350 /// Update in place by shifting out from `amount` binders.
352 pub fn shift_out(&mut self, amount: u32) {
353 *self = self.shifted_out(amount);
356 /// Adjusts any De Bruijn indices so as to make `to_binder` the
357 /// innermost binder. That is, if we have something bound at `to_binder`,
358 /// it will now be bound at INNERMOST. This is an appropriate thing to do
359 /// when moving a region out from inside binders:
361 /// ```ignore (illustrative)
362 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
363 /// // Binder: D3 D2 D1 ^^
366 /// Here, the region `'a` would have the De Bruijn index D3,
367 /// because it is the bound 3 binders out. However, if we wanted
368 /// to refer to that region `'a` in the second argument (the `_`),
369 /// those two binders would not be in scope. In that case, we
370 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
371 /// De Bruijn index of `'a` to D1 (the innermost binder).
373 /// If we invoke `shift_out_to_binder` and the region is in fact
374 /// bound by one of the binders we are shifting out of, that is an
375 /// error (and should fail an assertion failure).
377 pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
378 self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
382 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
383 #[derive(Encodable, Decodable, HashStable_Generic)]
394 pub fn name_str(&self) -> &'static str {
396 IntTy::Isize => "isize",
401 IntTy::I128 => "i128",
405 pub fn bit_width(&self) -> Option<u64> {
407 IntTy::Isize => return None,
416 pub fn normalize(&self, target_width: u32) -> Self {
418 IntTy::Isize => match target_width {
429 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
430 #[derive(Encodable, Decodable, HashStable_Generic)]
441 pub fn name_str(&self) -> &'static str {
443 UintTy::Usize => "usize",
445 UintTy::U16 => "u16",
446 UintTy::U32 => "u32",
447 UintTy::U64 => "u64",
448 UintTy::U128 => "u128",
452 pub fn bit_width(&self) -> Option<u64> {
454 UintTy::Usize => return None,
463 pub fn normalize(&self, target_width: u32) -> Self {
465 UintTy::Usize => match target_width {
476 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
477 #[derive(Encodable, Decodable, HashStable_Generic)]
484 pub fn name_str(self) -> &'static str {
486 FloatTy::F32 => "f32",
487 FloatTy::F64 => "f64",
491 pub fn bit_width(self) -> u64 {
499 #[derive(Clone, Copy, PartialEq, Eq)]
500 pub enum IntVarValue {
505 #[derive(Clone, Copy, PartialEq, Eq)]
506 pub struct FloatVarValue(pub FloatTy);
508 rustc_index::newtype_index! {
509 /// A **ty**pe **v**ariable **ID**.
510 #[debug_format = "_#{}t"]
514 /// An **int**egral (`u32`, `i32`, `usize`, etc.) type **v**ariable **ID**.
515 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
520 /// An **float**ing-point (`f32` or `f64`) type **v**ariable **ID**.
521 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
522 pub struct FloatVid {
526 /// A placeholder for a type that hasn't been inferred yet.
528 /// E.g., if we have an empty array (`[]`), then we create a fresh
529 /// type variable for the element type since we won't know until it's
530 /// used what the element type is supposed to be.
531 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
535 /// An integral type variable (`{integer}`).
537 /// These are created when the compiler sees an integer literal like
538 /// `1` that could be several different types (`u8`, `i32`, `u32`, etc.).
539 /// We don't know until it's used what type it's supposed to be, so
540 /// we create a fresh type variable.
542 /// A floating-point type variable (`{float}`).
544 /// These are created when the compiler sees an float literal like
545 /// `1.0` that could be either an `f32` or an `f64`.
546 /// We don't know until it's used what type it's supposed to be, so
547 /// we create a fresh type variable.
550 /// A [`FreshTy`][Self::FreshTy] is one that is generated as a replacement
551 /// for an unbound type variable. This is convenient for caching etc. See
552 /// `rustc_infer::infer::freshen` for more details.
554 /// Compare with [`TyVar`][Self::TyVar].
556 /// Like [`FreshTy`][Self::FreshTy], but as a replacement for [`IntVar`][Self::IntVar].
558 /// Like [`FreshTy`][Self::FreshTy], but as a replacement for [`FloatVar`][Self::FloatVar].
562 /// Raw `TyVid` are used as the unification key for `sub_relations`;
563 /// they carry no values.
564 impl UnifyKey for TyVid {
567 fn index(&self) -> u32 {
571 fn from_index(i: u32) -> TyVid {
574 fn tag() -> &'static str {
579 impl EqUnifyValue for IntVarValue {}
581 impl UnifyKey for IntVid {
582 type Value = Option<IntVarValue>;
583 #[inline] // make this function eligible for inlining - it is quite hot.
584 fn index(&self) -> u32 {
588 fn from_index(i: u32) -> IntVid {
591 fn tag() -> &'static str {
596 impl EqUnifyValue for FloatVarValue {}
598 impl UnifyKey for FloatVid {
599 type Value = Option<FloatVarValue>;
601 fn index(&self) -> u32 {
605 fn from_index(i: u32) -> FloatVid {
606 FloatVid { index: i }
608 fn tag() -> &'static str {
613 #[derive(Copy, Clone, PartialEq, Decodable, Encodable, Hash, HashStable_Generic)]
614 #[rustc_pass_by_value]
616 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
617 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
618 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
619 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
623 /// `a.xform(b)` combines the variance of a context with the
624 /// variance of a type with the following meaning. If we are in a
625 /// context with variance `a`, and we encounter a type argument in
626 /// a position with variance `b`, then `a.xform(b)` is the new
627 /// variance with which the argument appears.
630 /// ```ignore (illustrative)
633 /// Here, the "ambient" variance starts as covariant. `*mut T` is
634 /// invariant with respect to `T`, so the variance in which the
635 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
636 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
637 /// respect to its type argument `T`, and hence the variance of
638 /// the `i32` here is `Invariant.xform(Covariant)`, which results
639 /// (again) in `Invariant`.
642 /// ```ignore (illustrative)
643 /// fn(*const Vec<i32>, *mut Vec<i32)
645 /// The ambient variance is covariant. A `fn` type is
646 /// contravariant with respect to its parameters, so the variance
647 /// within which both pointer types appear is
648 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
649 /// T` is covariant with respect to `T`, so the variance within
650 /// which the first `Vec<i32>` appears is
651 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
652 /// is true for its `i32` argument. In the `*mut T` case, the
653 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
654 /// and hence the outermost type is `Invariant` with respect to
655 /// `Vec<i32>` (and its `i32` argument).
657 /// Source: Figure 1 of "Taming the Wildcards:
658 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
659 pub fn xform(self, v: Variance) -> Variance {
661 // Figure 1, column 1.
662 (Variance::Covariant, Variance::Covariant) => Variance::Covariant,
663 (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
664 (Variance::Covariant, Variance::Invariant) => Variance::Invariant,
665 (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant,
667 // Figure 1, column 2.
668 (Variance::Contravariant, Variance::Covariant) => Variance::Contravariant,
669 (Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
670 (Variance::Contravariant, Variance::Invariant) => Variance::Invariant,
671 (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant,
673 // Figure 1, column 3.
674 (Variance::Invariant, _) => Variance::Invariant,
676 // Figure 1, column 4.
677 (Variance::Bivariant, _) => Variance::Bivariant,
682 impl<CTX> HashStable<CTX> for InferTy {
683 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
685 discriminant(self).hash_stable(ctx, hasher);
687 TyVar(_) | IntVar(_) | FloatVar(_) => {
688 panic!("type variables should not be hashed: {self:?}")
690 FreshTy(v) | FreshIntTy(v) | FreshFloatTy(v) => v.hash_stable(ctx, hasher),
695 impl fmt::Debug for IntVarValue {
696 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698 IntVarValue::IntType(ref v) => v.fmt(f),
699 IntVarValue::UintType(ref v) => v.fmt(f),
704 impl fmt::Debug for FloatVarValue {
705 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
710 impl fmt::Debug for IntVid {
711 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
712 write!(f, "_#{}i", self.index)
716 impl fmt::Debug for FloatVid {
717 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
718 write!(f, "_#{}f", self.index)
722 impl fmt::Debug for InferTy {
723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726 TyVar(ref v) => v.fmt(f),
727 IntVar(ref v) => v.fmt(f),
728 FloatVar(ref v) => v.fmt(f),
729 FreshTy(v) => write!(f, "FreshTy({v:?})"),
730 FreshIntTy(v) => write!(f, "FreshIntTy({v:?})"),
731 FreshFloatTy(v) => write!(f, "FreshFloatTy({v:?})"),
736 impl fmt::Debug for Variance {
737 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
738 f.write_str(match *self {
739 Variance::Covariant => "+",
740 Variance::Contravariant => "-",
741 Variance::Invariant => "o",
742 Variance::Bivariant => "*",
747 impl fmt::Display for InferTy {
748 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
751 TyVar(_) => write!(f, "_"),
752 IntVar(_) => write!(f, "{}", "{integer}"),
753 FloatVar(_) => write!(f, "{}", "{float}"),
754 FreshTy(v) => write!(f, "FreshTy({v})"),
755 FreshIntTy(v) => write!(f, "FreshIntTy({v})"),
756 FreshFloatTy(v) => write!(f, "FreshFloatTy({v})"),
761 rustc_index::newtype_index! {
762 /// "Universes" are used during type- and trait-checking in the
763 /// presence of `for<..>` binders to control what sets of names are
764 /// visible. Universes are arranged into a tree: the root universe
765 /// contains names that are always visible. Each child then adds a new
766 /// set of names that are visible, in addition to those of its parent.
767 /// We say that the child universe "extends" the parent universe with
770 /// To make this more concrete, consider this program:
772 /// ```ignore (illustrative)
774 /// fn bar<T>(x: T) {
775 /// let y: for<'a> fn(&'a u8, Foo) = ...;
779 /// The struct name `Foo` is in the root universe U0. But the type
780 /// parameter `T`, introduced on `bar`, is in an extended universe U1
781 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
782 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
783 /// region `'a` is in a universe U2 that extends U1, because we can
784 /// name it inside the fn type but not outside.
786 /// Universes are used to do type- and trait-checking around these
787 /// "forall" binders (also called **universal quantification**). The
788 /// idea is that when, in the body of `bar`, we refer to `T` as a
789 /// type, we aren't referring to any type in particular, but rather a
790 /// kind of "fresh" type that is distinct from all other types we have
791 /// actually declared. This is called a **placeholder** type, and we
792 /// use universes to talk about this. In other words, a type name in
793 /// universe 0 always corresponds to some "ground" type that the user
794 /// declared, but a type name in a non-zero universe is a placeholder
795 /// type -- an idealized representative of "types in general" that we
796 /// use for checking generic functions.
797 #[derive(HashStable_Generic)]
798 #[debug_format = "U{}"]
799 pub struct UniverseIndex {}
803 pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
805 /// Returns the "next" universe index in order -- this new index
806 /// is considered to extend all previous universes. This
807 /// corresponds to entering a `forall` quantifier. So, for
808 /// example, suppose we have this type in universe `U`:
810 /// ```ignore (illustrative)
811 /// for<'a> fn(&'a u32)
814 /// Once we "enter" into this `for<'a>` quantifier, we are in a
815 /// new universe that extends `U` -- in this new universe, we can
816 /// name the region `'a`, but that region was not nameable from
817 /// `U` because it was not in scope there.
818 pub fn next_universe(self) -> UniverseIndex {
819 UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
822 /// Returns `true` if `self` can name a name from `other` -- in other words,
823 /// if the set of names in `self` is a superset of those in
824 /// `other` (`self >= other`).
825 pub fn can_name(self, other: UniverseIndex) -> bool {
826 self.private >= other.private
829 /// Returns `true` if `self` cannot name some names from `other` -- in other
830 /// words, if the set of names in `self` is a strict subset of
831 /// those in `other` (`self < other`).
832 pub fn cannot_name(self, other: UniverseIndex) -> bool {
833 self.private < other.private