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(feature = "nightly", allow(internal_features))]
8#![cfg_attr(feature = "nightly", feature(associated_type_defaults, rustc_attrs, negative_impls))]
9// tidy-alphabetical-end
1011extern crate self as rustc_type_ir;
1213use std::fmt;
14use std::hash::Hash;
1516use rustc_abi::{FieldIdx, VariantIdx};
17#[cfg(feature = "nightly")]
18use rustc_macros::{Decodable, Encodable, StableHash};
1920// 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 region_constraint;
32pub mod relate;
33pub mod search_graph;
34pub mod solve;
35pub mod walk;
3637// These modules are not `pub` since they are glob-imported.
38#[macro_use]
39mod macros;
40mod binder;
41mod canonical;
42mod const_kind;
43mod flags;
44mod fold;
45mod generic_arg;
46#[cfg(not(feature = "nightly"))]
47mod generic_visit;
48mod infer_ctxt;
49mod interner;
50mod opaque_ty;
51mod pattern;
52mod predicate;
53mod predicate_kind;
54mod region_kind;
55mod term_kind;
56mod ty;
57mod ty_info;
58mod ty_kind;
59mod unnormalized;
60mod upcast;
61mod visit;
6263pub use AliasTyKind::*;
64pub use InferTy::*;
65pub use RegionKind::*;
66pub use TyKind::*;
67pub use Variance::*;
68pub use binder::{Placeholder, *};
69pub use canonical::*;
70pub use const_kind::*;
71pub use flags::*;
72pub use fold::*;
73pub use generic_arg::*;
74#[cfg(not(feature = "nightly"))]
75pub use generic_visit::*;
76pub use infer_ctxt::*;
77pub use interner::*;
78pub use opaque_ty::*;
79pub use pattern::*;
80pub use predicate::*;
81pub use predicate_kind::*;
82pub use region_kind::*;
83pub use rustc_ast_ir::{FloatTy, IntTy, Movability, Mutability, Pinnedness, UintTy};
84use rustc_type_ir_macros::GenericTypeVisitable;
85pub use term_kind::*;
86pub use ty::{Alias, *};
87pub use ty_info::*;
88pub use ty_kind::*;
89pub use unnormalized::Unnormalized;
90pub use upcast::*;
91pub use visit::*;
9293impl ::std::fmt::Debug for DebruijnIndex {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("DebruijnIndex({0})", self.as_u32()))
}
}rustc_index::newtype_index! {
94/// A [De Bruijn index][dbi] is a standard means of representing
95 /// regions (and perhaps later types) in a higher-ranked setting. In
96 /// particular, imagine a type like this:
97 /// ```ignore (illustrative)
98 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
99 /// // ^ ^ | | |
100 /// // | | | | |
101 /// // | +------------+ 0 | |
102 /// // | | |
103 /// // +----------------------------------+ 1 |
104 /// // | |
105 /// // +----------------------------------------------+ 0
106 /// ```
107 /// In this type, there are two binders (the outer fn and the inner
108 /// fn). We need to be able to determine, for any given region, which
109 /// fn type it is bound by, the inner or the outer one. There are
110 /// various ways you can do this, but a De Bruijn index is one of the
111 /// more convenient and has some nice properties. The basic idea is to
112 /// count the number of binders, inside out. Some examples should help
113 /// clarify what I mean.
114 ///
115 /// Let's start with the reference type `&'b isize` that is the first
116 /// argument to the inner function. This region `'b` is assigned a De
117 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
118 /// fn). The region `'a` that appears in the second argument type (`&'a
119 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
120 /// second-innermost binder". (These indices are written on the arrows
121 /// in the diagram).
122 ///
123 /// What is interesting is that De Bruijn index attached to a particular
124 /// variable will vary depending on where it appears. For example,
125 /// the final type `&'a char` also refers to the region `'a` declared on
126 /// the outermost fn. But this time, this reference is not nested within
127 /// any other binders (i.e., it is not an argument to the inner fn, but
128 /// rather the outer one). Therefore, in this case, it is assigned a
129 /// De Bruijn index of 0, because the innermost binder in that location
130 /// is the outer fn.
131 ///
132 /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index
133#[stable_hash]
134 #[encodable]
135 #[orderable]
136 #[debug_format = "DebruijnIndex({})"]
137 #[gate_rustc_only]
138pub struct DebruijnIndex {
139const INNERMOST = 0;
140 }
141}142143impl DebruijnIndex {
144/// Returns the resulting index when this value is moved into
145 /// `amount` number of new binders. So, e.g., if you had
146 ///
147 /// for<'a> fn(&'a x)
148 ///
149 /// and you wanted to change it to
150 ///
151 /// for<'a> fn(for<'b> fn(&'a x))
152 ///
153 /// you would need to shift the index for `'a` into a new binder.
154#[inline]
155 #[must_use]
156pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
157DebruijnIndex::from_u32(self.as_u32() + amount)
158 }
159160/// Update this index in place by shifting it "in" through
161 /// `amount` number of binders.
162#[inline]
163pub fn shift_in(&mut self, amount: u32) {
164*self = self.shifted_in(amount);
165 }
166167/// Returns the resulting index when this value is moved out from
168 /// `amount` number of new binders.
169#[inline]
170 #[must_use]
171pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
172DebruijnIndex::from_u32(self.as_u32() - amount)
173 }
174175/// Update in place by shifting out from `amount` binders.
176#[inline]
177pub fn shift_out(&mut self, amount: u32) {
178*self = self.shifted_out(amount);
179 }
180181/// Adjusts any De Bruijn indices so as to make `to_binder` the
182 /// innermost binder. That is, if we have something bound at `to_binder`,
183 /// it will now be bound at INNERMOST. This is an appropriate thing to do
184 /// when moving a region out from inside binders:
185 ///
186 /// ```ignore (illustrative)
187 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
188 /// // Binder: D3 D2 D1 ^^
189 /// ```
190 ///
191 /// Here, the region `'a` would have the De Bruijn index D3,
192 /// because it is the bound 3 binders out. However, if we wanted
193 /// to refer to that region `'a` in the second argument (the `_`),
194 /// those two binders would not be in scope. In that case, we
195 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
196 /// De Bruijn index of `'a` to D1 (the innermost binder).
197 ///
198 /// If we invoke `shift_out_to_binder` and the region is in fact
199 /// bound by one of the binders we are shifting out of, that is an
200 /// error (and should fail an assertion failure).
201#[inline]
202pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
203self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
204 }
205}
206207pub fn debug_bound_var<T: std::fmt::Write>(
208 fmt: &mut T,
209 bound_index: BoundVarIndexKind,
210 var: impl std::fmt::Debug,
211) -> Result<(), std::fmt::Error> {
212match bound_index {
213 BoundVarIndexKind::Bound(debruijn) => {
214if debruijn == INNERMOST {
215fmt.write_fmt(format_args!("^{0:?}", var))write!(fmt, "^{var:?}")216 } else {
217fmt.write_fmt(format_args!("^{0}_{1:?}", debruijn.index(), var))write!(fmt, "^{}_{:?}", debruijn.index(), var)218 }
219 }
220 BoundVarIndexKind::Canonical => {
221fmt.write_fmt(format_args!("^c_{0:?}", var))write!(fmt, "^c_{:?}", var)222 }
223 }
224}
225226#[derive(#[automatically_derived]
impl ::core::marker::Copy for Variance { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Variance {
#[inline]
fn clone(&self) -> Variance { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Variance {
#[inline]
fn eq(&self, other: &Variance) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Variance {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Variance {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash, GenericTypeVisitable)]
227#[cfg_attr(feature = "nightly", derive(const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for Variance {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { Variance::Covariant }
1usize => { Variance::Invariant }
2usize => { Variance::Contravariant }
3usize => { Variance::Bivariant }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Variance`, expected 0..4, actual {0}",
n));
}
}
}
}
};Decodable, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for Variance {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
Variance::Covariant => { 0usize }
Variance::Invariant => { 1usize }
Variance::Contravariant => { 2usize }
Variance::Bivariant => { 3usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
Variance::Covariant => {}
Variance::Invariant => {}
Variance::Contravariant => {}
Variance::Bivariant => {}
}
}
}
};Encodable, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for Variance {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
Variance::Covariant => {}
Variance::Invariant => {}
Variance::Contravariant => {}
Variance::Bivariant => {}
}
}
}
};StableHash))]
228#[cfg_attr(feature = "nightly", rustc_pass_by_value)]
229pub enum Variance {
230 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
231Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
232Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
233Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
234}
235236impl Variance {
237/// `a.xform(b)` combines the variance of a context with the
238 /// variance of a type with the following meaning. If we are in a
239 /// context with variance `a`, and we encounter a type argument in
240 /// a position with variance `b`, then `a.xform(b)` is the new
241 /// variance with which the argument appears.
242 ///
243 /// Example 1:
244 /// ```ignore (illustrative)
245 /// *mut Vec<i32>
246 /// ```
247 /// Here, the "ambient" variance starts as covariant. `*mut T` is
248 /// invariant with respect to `T`, so the variance in which the
249 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
250 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
251 /// respect to its type argument `T`, and hence the variance of
252 /// the `i32` here is `Invariant.xform(Covariant)`, which results
253 /// (again) in `Invariant`.
254 ///
255 /// Example 2:
256 /// ```ignore (illustrative)
257 /// fn(*const Vec<i32>, *mut Vec<i32)
258 /// ```
259 /// The ambient variance is covariant. A `fn` type is
260 /// contravariant with respect to its parameters, so the variance
261 /// within which both pointer types appear is
262 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
263 /// T` is covariant with respect to `T`, so the variance within
264 /// which the first `Vec<i32>` appears is
265 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
266 /// is true for its `i32` argument. In the `*mut T` case, the
267 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
268 /// and hence the outermost type is `Invariant` with respect to
269 /// `Vec<i32>` (and its `i32` argument).
270 ///
271 /// Source: Figure 1 of "Taming the Wildcards:
272 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
273pub fn xform(self, v: Variance) -> Variance {
274match (self, v) {
275// Figure 1, column 1.
276(Variance::Covariant, Variance::Covariant) => Variance::Covariant,
277 (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
278 (Variance::Covariant, Variance::Invariant) => Variance::Invariant,
279 (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant,
280281// Figure 1, column 2.
282(Variance::Contravariant, Variance::Covariant) => Variance::Contravariant,
283 (Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
284 (Variance::Contravariant, Variance::Invariant) => Variance::Invariant,
285 (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant,
286287// Figure 1, column 3.
288(Variance::Invariant, _) => Variance::Invariant,
289290// Figure 1, column 4.
291(Variance::Bivariant, _) => Variance::Bivariant,
292 }
293 }
294}
295296impl fmt::Debugfor Variance {
297fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298f.write_str(match *self {
299 Variance::Covariant => "+",
300 Variance::Contravariant => "-",
301 Variance::Invariant => "o",
302 Variance::Bivariant => "*",
303 })
304 }
305}
306307impl ::std::fmt::Debug for UniverseIndex {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("U{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
308/// "Universes" are used during type- and trait-checking in the
309 /// presence of `for<..>` binders to control what sets of names are
310 /// visible. Universes are arranged into a tree: the root universe
311 /// contains names that are always visible. Each child then adds a new
312 /// set of names that are visible, in addition to those of its parent.
313 /// We say that the child universe "extends" the parent universe with
314 /// new names.
315 ///
316 /// To make this more concrete, consider this program:
317 ///
318 /// ```ignore (illustrative)
319 /// struct Foo { }
320 /// fn bar<T>(x: T) {
321 /// let y: for<'a> fn(&'a u8, Foo) = ...;
322 /// }
323 /// ```
324 ///
325 /// The struct name `Foo` is in the root universe U0. But the type
326 /// parameter `T`, introduced on `bar`, is in an extended universe U1
327 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
328 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
329 /// region `'a` is in a universe U2 that extends U1, because we can
330 /// name it inside the fn type but not outside.
331 ///
332 /// Universes are used to do type- and trait-checking around these
333 /// "forall" binders (also called **universal quantification**). The
334 /// idea is that when, in the body of `bar`, we refer to `T` as a
335 /// type, we aren't referring to any type in particular, but rather a
336 /// kind of "fresh" type that is distinct from all other types we have
337 /// actually declared. This is called a **placeholder** type, and we
338 /// use universes to talk about this. In other words, a type name in
339 /// universe 0 always corresponds to some "ground" type that the user
340 /// declared, but a type name in a non-zero universe is a placeholder
341 /// type -- an idealized representative of "types in general" that we
342 /// use for checking generic functions.
343#[stable_hash]
344 #[encodable]
345 #[orderable]
346 #[debug_format = "U{}"]
347 #[gate_rustc_only]
348pub struct UniverseIndex {}
349}350351impl UniverseIndex {
352pub const ROOT: UniverseIndex = UniverseIndex::ZERO;
353354/// Returns the "next" universe index in order -- this new index
355 /// is considered to extend all previous universes. This
356 /// corresponds to entering a `forall` quantifier. So, for
357 /// example, suppose we have this type in universe `U`:
358 ///
359 /// ```ignore (illustrative)
360 /// for<'a> fn(&'a u32)
361 /// ```
362 ///
363 /// Once we "enter" into this `for<'a>` quantifier, we are in a
364 /// new universe that extends `U` -- in this new universe, we can
365 /// name the region `'a`, but that region was not nameable from
366 /// `U` because it was not in scope there.
367pub fn next_universe(self) -> UniverseIndex {
368UniverseIndex::from_u32(self.as_u32().checked_add(1).unwrap())
369 }
370371/// Returns `true` if `self` can name a name from `other` -- in other words,
372 /// if the set of names in `self` is a superset of those in
373 /// `other` (`self >= other`).
374pub fn can_name(self, other: UniverseIndex) -> bool {
375self >= other376 }
377378/// Returns `true` if `self` cannot name some names from `other` -- in other
379 /// words, if the set of names in `self` is a strict subset of
380 /// those in `other` (`self < other`).
381pub fn cannot_name(self, other: UniverseIndex) -> bool {
382self < other383 }
384385/// Returns `true` if `self` is the root universe, otherwise false.
386pub fn is_root(self) -> bool {
387self == Self::ROOT388 }
389}
390391impl Defaultfor UniverseIndex {
392fn default() -> Self {
393Self::ROOT394 }
395}
396397impl ::std::fmt::Debug for BoundVar {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
398#[stable_hash]
399 #[encodable]
400 #[orderable]
401 #[debug_format = "{}"]
402 #[gate_rustc_only]
403pub struct BoundVar {}
404}405406/// Represents the various closure traits in the language. This
407/// will determine the type of the environment (`self`, in the
408/// desugaring) argument that the closure expects.
409///
410/// You can get the environment type of a closure using
411/// `tcx.closure_env_ty()`.
412#[derive(#[automatically_derived]
impl ::core::clone::Clone for ClosureKind {
#[inline]
fn clone(&self) -> ClosureKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ClosureKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for ClosureKind {
#[inline]
fn eq(&self, other: &ClosureKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ClosureKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ClosureKind {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for ClosureKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ClosureKind::Fn => "Fn",
ClosureKind::FnMut => "FnMut",
ClosureKind::FnOnce => "FnOnce",
})
}
}Debug)]
413#[cfg_attr(feature = "nightly", derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for ClosureKind {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
ClosureKind::Fn => { 0usize }
ClosureKind::FnMut => { 1usize }
ClosureKind::FnOnce => { 2usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
ClosureKind::Fn => {}
ClosureKind::FnMut => {}
ClosureKind::FnOnce => {}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for ClosureKind {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { ClosureKind::Fn }
1usize => { ClosureKind::FnMut }
2usize => { ClosureKind::FnOnce }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `ClosureKind`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for ClosureKind
{
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
ClosureKind::Fn => {}
ClosureKind::FnMut => {}
ClosureKind::FnOnce => {}
}
}
}
};StableHash))]
414pub enum ClosureKind {
415 Fn,
416 FnMut,
417 FnOnce,
418}
419420impl ClosureKind {
421/// This is the initial value used when doing upvar inference.
422pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
423424pub const fn as_str(self) -> &'static str {
425match self {
426 ClosureKind::Fn => "Fn",
427 ClosureKind::FnMut => "FnMut",
428 ClosureKind::FnOnce => "FnOnce",
429 }
430 }
431432/// Returns `true` if a type that impls this closure kind
433 /// must also implement `other`.
434#[rustfmt::skip]
435pub fn extends(self, other: ClosureKind) -> bool {
436use ClosureKind::*;
437match (self, other) {
438 (Fn, Fn | FnMut | FnOnce)
439 | (FnMut, FnMut | FnOnce)
440 | (FnOnce, FnOnce) => true,
441_ => false,
442 }
443 }
444}
445446impl fmt::Displayfor ClosureKind {
447fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448self.as_str().fmt(f)
449 }
450}
451452pub struct FieldInfo<I: Interner> {
453pub base: I::Ty,
454pub ty: I::Ty,
455pub variant: Option<I::Symbol>,
456pub variant_idx: VariantIdx,
457pub name: I::Symbol,
458pub field_idx: FieldIdx,
459}