rustc_type_ir/
lib.rs

1#![cfg_attr(feature = "nightly", rustc_diagnostic_item = "type_ir")]
2// tidy-alphabetical-start
3#![allow(rustc::direct_use_of_rustc_type_ir)]
4#![allow(rustc::usage_of_ty_tykind)]
5#![allow(rustc::usage_of_type_ir_inherent)]
6#![allow(rustc::usage_of_type_ir_traits)]
7#![cfg_attr(
8    feature = "nightly",
9    feature(associated_type_defaults, never_type, rustc_attrs, negative_impls)
10)]
11#![cfg_attr(feature = "nightly", allow(internal_features))]
12// tidy-alphabetical-end
13
14extern crate self as rustc_type_ir;
15
16use std::fmt;
17use std::hash::Hash;
18
19#[cfg(feature = "nightly")]
20use rustc_macros::{Decodable, Encodable, HashStable_NoContext};
21
22// These modules are `pub` since they are not glob-imported.
23pub mod data_structures;
24pub mod elaborate;
25pub mod error;
26pub mod fast_reject;
27#[cfg_attr(feature = "nightly", rustc_diagnostic_item = "type_ir_inherent")]
28pub mod inherent;
29pub mod ir_print;
30pub mod lang_items;
31pub mod lift;
32pub mod outlives;
33pub mod relate;
34pub mod search_graph;
35pub mod solve;
36pub mod walk;
37
38// These modules are not `pub` since they are glob-imported.
39#[macro_use]
40mod macros;
41mod binder;
42mod canonical;
43mod const_kind;
44mod flags;
45mod fold;
46mod generic_arg;
47mod infer_ctxt;
48mod interner;
49mod opaque_ty;
50mod pattern;
51mod predicate;
52mod predicate_kind;
53mod region_kind;
54mod ty_info;
55mod ty_kind;
56mod upcast;
57mod visit;
58
59pub use AliasTyKind::*;
60pub use InferTy::*;
61pub use RegionKind::*;
62pub use TyKind::*;
63pub use Variance::*;
64pub use binder::*;
65pub use canonical::*;
66pub use const_kind::*;
67pub use flags::*;
68pub use fold::*;
69pub use generic_arg::*;
70pub use infer_ctxt::*;
71pub use interner::*;
72pub use opaque_ty::*;
73pub use pattern::*;
74pub use predicate::*;
75pub use predicate_kind::*;
76pub use region_kind::*;
77pub use rustc_ast_ir::{FloatTy, IntTy, Movability, Mutability, Pinnedness, UintTy};
78pub use ty_info::*;
79pub use ty_kind::*;
80pub use upcast::*;
81pub use visit::*;
82
83rustc_index::newtype_index! {
84    /// A [De Bruijn index][dbi] is a standard means of representing
85    /// regions (and perhaps later types) in a higher-ranked setting. In
86    /// particular, imagine a type like this:
87    /// ```ignore (illustrative)
88    ///    for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
89    /// // ^          ^            |          |           |
90    /// // |          |            |          |           |
91    /// // |          +------------+ 0        |           |
92    /// // |                                  |           |
93    /// // +----------------------------------+ 1         |
94    /// // |                                              |
95    /// // +----------------------------------------------+ 0
96    /// ```
97    /// In this type, there are two binders (the outer fn and the inner
98    /// fn). We need to be able to determine, for any given region, which
99    /// fn type it is bound by, the inner or the outer one. There are
100    /// various ways you can do this, but a De Bruijn index is one of the
101    /// more convenient and has some nice properties. The basic idea is to
102    /// count the number of binders, inside out. Some examples should help
103    /// clarify what I mean.
104    ///
105    /// Let's start with the reference type `&'b isize` that is the first
106    /// argument to the inner function. This region `'b` is assigned a De
107    /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
108    /// fn). The region `'a` that appears in the second argument type (`&'a
109    /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
110    /// second-innermost binder". (These indices are written on the arrows
111    /// in the diagram).
112    ///
113    /// What is interesting is that De Bruijn index attached to a particular
114    /// variable will vary depending on where it appears. For example,
115    /// the final type `&'a char` also refers to the region `'a` declared on
116    /// the outermost fn. But this time, this reference is not nested within
117    /// any other binders (i.e., it is not an argument to the inner fn, but
118    /// rather the outer one). Therefore, in this case, it is assigned a
119    /// De Bruijn index of 0, because the innermost binder in that location
120    /// is the outer fn.
121    ///
122    /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index
123    #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
124    #[encodable]
125    #[orderable]
126    #[debug_format = "DebruijnIndex({})"]
127    #[gate_rustc_only]
128    pub struct DebruijnIndex {
129        const INNERMOST = 0;
130    }
131}
132
133impl DebruijnIndex {
134    /// Returns the resulting index when this value is moved into
135    /// `amount` number of new binders. So, e.g., if you had
136    ///
137    ///    for<'a> fn(&'a x)
138    ///
139    /// and you wanted to change it to
140    ///
141    ///    for<'a> fn(for<'b> fn(&'a x))
142    ///
143    /// you would need to shift the index for `'a` into a new binder.
144    #[inline]
145    #[must_use]
146    pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
147        DebruijnIndex::from_u32(self.as_u32() + amount)
148    }
149
150    /// Update this index in place by shifting it "in" through
151    /// `amount` number of binders.
152    #[inline]
153    pub fn shift_in(&mut self, amount: u32) {
154        *self = self.shifted_in(amount);
155    }
156
157    /// Returns the resulting index when this value is moved out from
158    /// `amount` number of new binders.
159    #[inline]
160    #[must_use]
161    pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
162        DebruijnIndex::from_u32(self.as_u32() - amount)
163    }
164
165    /// Update in place by shifting out from `amount` binders.
166    #[inline]
167    pub fn shift_out(&mut self, amount: u32) {
168        *self = self.shifted_out(amount);
169    }
170
171    /// Adjusts any De Bruijn indices so as to make `to_binder` the
172    /// innermost binder. That is, if we have something bound at `to_binder`,
173    /// it will now be bound at INNERMOST. This is an appropriate thing to do
174    /// when moving a region out from inside binders:
175    ///
176    /// ```ignore (illustrative)
177    ///             for<'a>   fn(for<'b>   for<'c>   fn(&'a u32), _)
178    /// // Binder:  D3           D2        D1            ^^
179    /// ```
180    ///
181    /// Here, the region `'a` would have the De Bruijn index D3,
182    /// because it is the bound 3 binders out. However, if we wanted
183    /// to refer to that region `'a` in the second argument (the `_`),
184    /// those two binders would not be in scope. In that case, we
185    /// might invoke `shift_out_to_binder(D3)`. This would adjust the
186    /// De Bruijn index of `'a` to D1 (the innermost binder).
187    ///
188    /// If we invoke `shift_out_to_binder` and the region is in fact
189    /// bound by one of the binders we are shifting out of, that is an
190    /// error (and should fail an assertion failure).
191    #[inline]
192    pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
193        self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
194    }
195}
196
197pub fn debug_bound_var<T: std::fmt::Write>(
198    fmt: &mut T,
199    bound_index: BoundVarIndexKind,
200    var: impl std::fmt::Debug,
201) -> Result<(), std::fmt::Error> {
202    match bound_index {
203        BoundVarIndexKind::Bound(debruijn) => {
204            if debruijn == INNERMOST {
205                write!(fmt, "^{var:?}")
206            } else {
207                write!(fmt, "^{}_{:?}", debruijn.index(), var)
208            }
209        }
210        BoundVarIndexKind::Canonical => {
211            write!(fmt, "^c_{:?}", var)
212        }
213    }
214}
215
216#[derive(Copy, Clone, PartialEq, Eq, Hash)]
217#[cfg_attr(feature = "nightly", derive(Decodable, Encodable, HashStable_NoContext))]
218#[cfg_attr(feature = "nightly", rustc_pass_by_value)]
219pub enum Variance {
220    Covariant,     // T<A> <: T<B> iff A <: B -- e.g., function return type
221    Invariant,     // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
222    Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
223    Bivariant,     // T<A> <: T<B>            -- e.g., unused type parameter
224}
225
226impl Variance {
227    /// `a.xform(b)` combines the variance of a context with the
228    /// variance of a type with the following meaning. If we are in a
229    /// context with variance `a`, and we encounter a type argument in
230    /// a position with variance `b`, then `a.xform(b)` is the new
231    /// variance with which the argument appears.
232    ///
233    /// Example 1:
234    /// ```ignore (illustrative)
235    /// *mut Vec<i32>
236    /// ```
237    /// Here, the "ambient" variance starts as covariant. `*mut T` is
238    /// invariant with respect to `T`, so the variance in which the
239    /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
240    /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
241    /// respect to its type argument `T`, and hence the variance of
242    /// the `i32` here is `Invariant.xform(Covariant)`, which results
243    /// (again) in `Invariant`.
244    ///
245    /// Example 2:
246    /// ```ignore (illustrative)
247    /// fn(*const Vec<i32>, *mut Vec<i32)
248    /// ```
249    /// The ambient variance is covariant. A `fn` type is
250    /// contravariant with respect to its parameters, so the variance
251    /// within which both pointer types appear is
252    /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
253    /// T` is covariant with respect to `T`, so the variance within
254    /// which the first `Vec<i32>` appears is
255    /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
256    /// is true for its `i32` argument. In the `*mut T` case, the
257    /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
258    /// and hence the outermost type is `Invariant` with respect to
259    /// `Vec<i32>` (and its `i32` argument).
260    ///
261    /// Source: Figure 1 of "Taming the Wildcards:
262    /// Combining Definition- and Use-Site Variance" published in PLDI'11.
263    pub fn xform(self, v: Variance) -> Variance {
264        match (self, v) {
265            // Figure 1, column 1.
266            (Variance::Covariant, Variance::Covariant) => Variance::Covariant,
267            (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
268            (Variance::Covariant, Variance::Invariant) => Variance::Invariant,
269            (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant,
270
271            // Figure 1, column 2.
272            (Variance::Contravariant, Variance::Covariant) => Variance::Contravariant,
273            (Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
274            (Variance::Contravariant, Variance::Invariant) => Variance::Invariant,
275            (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant,
276
277            // Figure 1, column 3.
278            (Variance::Invariant, _) => Variance::Invariant,
279
280            // Figure 1, column 4.
281            (Variance::Bivariant, _) => Variance::Bivariant,
282        }
283    }
284}
285
286impl fmt::Debug for Variance {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        f.write_str(match *self {
289            Variance::Covariant => "+",
290            Variance::Contravariant => "-",
291            Variance::Invariant => "o",
292            Variance::Bivariant => "*",
293        })
294    }
295}
296
297rustc_index::newtype_index! {
298    /// "Universes" are used during type- and trait-checking in the
299    /// presence of `for<..>` binders to control what sets of names are
300    /// visible. Universes are arranged into a tree: the root universe
301    /// contains names that are always visible. Each child then adds a new
302    /// set of names that are visible, in addition to those of its parent.
303    /// We say that the child universe "extends" the parent universe with
304    /// new names.
305    ///
306    /// To make this more concrete, consider this program:
307    ///
308    /// ```ignore (illustrative)
309    /// struct Foo { }
310    /// fn bar<T>(x: T) {
311    ///   let y: for<'a> fn(&'a u8, Foo) = ...;
312    /// }
313    /// ```
314    ///
315    /// The struct name `Foo` is in the root universe U0. But the type
316    /// parameter `T`, introduced on `bar`, is in an extended universe U1
317    /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
318    /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
319    /// region `'a` is in a universe U2 that extends U1, because we can
320    /// name it inside the fn type but not outside.
321    ///
322    /// Universes are used to do type- and trait-checking around these
323    /// "forall" binders (also called **universal quantification**). The
324    /// idea is that when, in the body of `bar`, we refer to `T` as a
325    /// type, we aren't referring to any type in particular, but rather a
326    /// kind of "fresh" type that is distinct from all other types we have
327    /// actually declared. This is called a **placeholder** type, and we
328    /// use universes to talk about this. In other words, a type name in
329    /// universe 0 always corresponds to some "ground" type that the user
330    /// declared, but a type name in a non-zero universe is a placeholder
331    /// type -- an idealized representative of "types in general" that we
332    /// use for checking generic functions.
333    #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
334    #[encodable]
335    #[orderable]
336    #[debug_format = "U{}"]
337    #[gate_rustc_only]
338    pub struct UniverseIndex {}
339}
340
341impl UniverseIndex {
342    pub const ROOT: UniverseIndex = UniverseIndex::ZERO;
343
344    /// Returns the "next" universe index in order -- this new index
345    /// is considered to extend all previous universes. This
346    /// corresponds to entering a `forall` quantifier. So, for
347    /// example, suppose we have this type in universe `U`:
348    ///
349    /// ```ignore (illustrative)
350    /// for<'a> fn(&'a u32)
351    /// ```
352    ///
353    /// Once we "enter" into this `for<'a>` quantifier, we are in a
354    /// new universe that extends `U` -- in this new universe, we can
355    /// name the region `'a`, but that region was not nameable from
356    /// `U` because it was not in scope there.
357    pub fn next_universe(self) -> UniverseIndex {
358        UniverseIndex::from_u32(self.as_u32().checked_add(1).unwrap())
359    }
360
361    /// Returns `true` if `self` can name a name from `other` -- in other words,
362    /// if the set of names in `self` is a superset of those in
363    /// `other` (`self >= other`).
364    pub fn can_name(self, other: UniverseIndex) -> bool {
365        self >= other
366    }
367
368    /// Returns `true` if `self` cannot name some names from `other` -- in other
369    /// words, if the set of names in `self` is a strict subset of
370    /// those in `other` (`self < other`).
371    pub fn cannot_name(self, other: UniverseIndex) -> bool {
372        self < other
373    }
374
375    /// Returns `true` if `self` is the root universe, otherwise false.
376    pub fn is_root(self) -> bool {
377        self == Self::ROOT
378    }
379}
380
381impl Default for UniverseIndex {
382    fn default() -> Self {
383        Self::ROOT
384    }
385}
386
387rustc_index::newtype_index! {
388    #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
389    #[encodable]
390    #[orderable]
391    #[debug_format = "{}"]
392    #[gate_rustc_only]
393    pub struct BoundVar {}
394}
395
396/// Represents the various closure traits in the language. This
397/// will determine the type of the environment (`self`, in the
398/// desugaring) argument that the closure expects.
399///
400/// You can get the environment type of a closure using
401/// `tcx.closure_env_ty()`.
402#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
403#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))]
404pub enum ClosureKind {
405    Fn,
406    FnMut,
407    FnOnce,
408}
409
410impl ClosureKind {
411    /// This is the initial value used when doing upvar inference.
412    pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
413
414    pub const fn as_str(self) -> &'static str {
415        match self {
416            ClosureKind::Fn => "Fn",
417            ClosureKind::FnMut => "FnMut",
418            ClosureKind::FnOnce => "FnOnce",
419        }
420    }
421
422    /// Returns `true` if a type that impls this closure kind
423    /// must also implement `other`.
424    #[rustfmt::skip]
425    pub fn extends(self, other: ClosureKind) -> bool {
426        use ClosureKind::*;
427        match (self, other) {
428              (Fn, Fn | FnMut | FnOnce)
429            | (FnMut,   FnMut | FnOnce)
430            | (FnOnce,          FnOnce) => true,
431            _ => false,
432        }
433    }
434}
435
436impl fmt::Display for ClosureKind {
437    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438        self.as_str().fmt(f)
439    }
440}