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 debruijn: DebruijnIndex,
200 var: impl std::fmt::Debug,
201) -> Result<(), std::fmt::Error> {
202 if debruijn == INNERMOST {
203 write!(fmt, "^{var:?}")
204 } else {
205 write!(fmt, "^{}_{:?}", debruijn.index(), var)
206 }
207}
208
209#[derive(Copy, Clone, PartialEq, Eq, Hash)]
210#[cfg_attr(feature = "nightly", derive(Decodable, Encodable, HashStable_NoContext))]
211#[cfg_attr(feature = "nightly", rustc_pass_by_value)]
212pub enum Variance {
213 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
214 Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
215 Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
216 Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
217}
218
219impl Variance {
220 /// `a.xform(b)` combines the variance of a context with the
221 /// variance of a type with the following meaning. If we are in a
222 /// context with variance `a`, and we encounter a type argument in
223 /// a position with variance `b`, then `a.xform(b)` is the new
224 /// variance with which the argument appears.
225 ///
226 /// Example 1:
227 /// ```ignore (illustrative)
228 /// *mut Vec<i32>
229 /// ```
230 /// Here, the "ambient" variance starts as covariant. `*mut T` is
231 /// invariant with respect to `T`, so the variance in which the
232 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
233 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
234 /// respect to its type argument `T`, and hence the variance of
235 /// the `i32` here is `Invariant.xform(Covariant)`, which results
236 /// (again) in `Invariant`.
237 ///
238 /// Example 2:
239 /// ```ignore (illustrative)
240 /// fn(*const Vec<i32>, *mut Vec<i32)
241 /// ```
242 /// The ambient variance is covariant. A `fn` type is
243 /// contravariant with respect to its parameters, so the variance
244 /// within which both pointer types appear is
245 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
246 /// T` is covariant with respect to `T`, so the variance within
247 /// which the first `Vec<i32>` appears is
248 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
249 /// is true for its `i32` argument. In the `*mut T` case, the
250 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
251 /// and hence the outermost type is `Invariant` with respect to
252 /// `Vec<i32>` (and its `i32` argument).
253 ///
254 /// Source: Figure 1 of "Taming the Wildcards:
255 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
256 pub fn xform(self, v: Variance) -> Variance {
257 match (self, v) {
258 // Figure 1, column 1.
259 (Variance::Covariant, Variance::Covariant) => Variance::Covariant,
260 (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
261 (Variance::Covariant, Variance::Invariant) => Variance::Invariant,
262 (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant,
263
264 // Figure 1, column 2.
265 (Variance::Contravariant, Variance::Covariant) => Variance::Contravariant,
266 (Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
267 (Variance::Contravariant, Variance::Invariant) => Variance::Invariant,
268 (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant,
269
270 // Figure 1, column 3.
271 (Variance::Invariant, _) => Variance::Invariant,
272
273 // Figure 1, column 4.
274 (Variance::Bivariant, _) => Variance::Bivariant,
275 }
276 }
277}
278
279impl fmt::Debug for Variance {
280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 f.write_str(match *self {
282 Variance::Covariant => "+",
283 Variance::Contravariant => "-",
284 Variance::Invariant => "o",
285 Variance::Bivariant => "*",
286 })
287 }
288}
289
290rustc_index::newtype_index! {
291 /// "Universes" are used during type- and trait-checking in the
292 /// presence of `for<..>` binders to control what sets of names are
293 /// visible. Universes are arranged into a tree: the root universe
294 /// contains names that are always visible. Each child then adds a new
295 /// set of names that are visible, in addition to those of its parent.
296 /// We say that the child universe "extends" the parent universe with
297 /// new names.
298 ///
299 /// To make this more concrete, consider this program:
300 ///
301 /// ```ignore (illustrative)
302 /// struct Foo { }
303 /// fn bar<T>(x: T) {
304 /// let y: for<'a> fn(&'a u8, Foo) = ...;
305 /// }
306 /// ```
307 ///
308 /// The struct name `Foo` is in the root universe U0. But the type
309 /// parameter `T`, introduced on `bar`, is in an extended universe U1
310 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
311 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
312 /// region `'a` is in a universe U2 that extends U1, because we can
313 /// name it inside the fn type but not outside.
314 ///
315 /// Universes are used to do type- and trait-checking around these
316 /// "forall" binders (also called **universal quantification**). The
317 /// idea is that when, in the body of `bar`, we refer to `T` as a
318 /// type, we aren't referring to any type in particular, but rather a
319 /// kind of "fresh" type that is distinct from all other types we have
320 /// actually declared. This is called a **placeholder** type, and we
321 /// use universes to talk about this. In other words, a type name in
322 /// universe 0 always corresponds to some "ground" type that the user
323 /// declared, but a type name in a non-zero universe is a placeholder
324 /// type -- an idealized representative of "types in general" that we
325 /// use for checking generic functions.
326 #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
327 #[encodable]
328 #[orderable]
329 #[debug_format = "U{}"]
330 #[gate_rustc_only]
331 pub struct UniverseIndex {}
332}
333
334impl UniverseIndex {
335 pub const ROOT: UniverseIndex = UniverseIndex::ZERO;
336
337 /// Returns the "next" universe index in order -- this new index
338 /// is considered to extend all previous universes. This
339 /// corresponds to entering a `forall` quantifier. So, for
340 /// example, suppose we have this type in universe `U`:
341 ///
342 /// ```ignore (illustrative)
343 /// for<'a> fn(&'a u32)
344 /// ```
345 ///
346 /// Once we "enter" into this `for<'a>` quantifier, we are in a
347 /// new universe that extends `U` -- in this new universe, we can
348 /// name the region `'a`, but that region was not nameable from
349 /// `U` because it was not in scope there.
350 pub fn next_universe(self) -> UniverseIndex {
351 UniverseIndex::from_u32(self.as_u32().checked_add(1).unwrap())
352 }
353
354 /// Returns `true` if `self` can name a name from `other` -- in other words,
355 /// if the set of names in `self` is a superset of those in
356 /// `other` (`self >= other`).
357 pub fn can_name(self, other: UniverseIndex) -> bool {
358 self >= other
359 }
360
361 /// Returns `true` if `self` cannot name some names from `other` -- in other
362 /// words, if the set of names in `self` is a strict subset of
363 /// those in `other` (`self < other`).
364 pub fn cannot_name(self, other: UniverseIndex) -> bool {
365 self < other
366 }
367
368 /// Returns `true` if `self` is the root universe, otherwise false.
369 pub fn is_root(self) -> bool {
370 self == Self::ROOT
371 }
372}
373
374impl Default for UniverseIndex {
375 fn default() -> Self {
376 Self::ROOT
377 }
378}
379
380rustc_index::newtype_index! {
381 #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
382 #[encodable]
383 #[orderable]
384 #[debug_format = "{}"]
385 #[gate_rustc_only]
386 pub struct BoundVar {}
387}
388
389/// Represents the various closure traits in the language. This
390/// will determine the type of the environment (`self`, in the
391/// desugaring) argument that the closure expects.
392///
393/// You can get the environment type of a closure using
394/// `tcx.closure_env_ty()`.
395#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
396#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))]
397pub enum ClosureKind {
398 Fn,
399 FnMut,
400 FnOnce,
401}
402
403impl ClosureKind {
404 /// This is the initial value used when doing upvar inference.
405 pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
406
407 pub const fn as_str(self) -> &'static str {
408 match self {
409 ClosureKind::Fn => "Fn",
410 ClosureKind::FnMut => "FnMut",
411 ClosureKind::FnOnce => "FnOnce",
412 }
413 }
414
415 /// Returns `true` if a type that impls this closure kind
416 /// must also implement `other`.
417 #[rustfmt::skip]
418 pub fn extends(self, other: ClosureKind) -> bool {
419 use ClosureKind::*;
420 match (self, other) {
421 (Fn, Fn | FnMut | FnOnce)
422 | (FnMut, FnMut | FnOnce)
423 | (FnOnce, FnOnce) => true,
424 _ => false,
425 }
426 }
427}
428
429impl fmt::Display for ClosureKind {
430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431 self.as_str().fmt(f)
432 }
433}