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