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