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 ty_info;
56mod ty_kind;
57mod unnormalized;
58mod upcast;
59mod visit;
6061pub use AliasTyKind::*;
62pub use InferTy::*;
63pub use RegionKind::*;
64pub use TyKind::*;
65pub use Variance::*;
66pub use binder::{Placeholder, *};
67pub use canonical::*;
68pub use const_kind::*;
69pub use flags::*;
70pub use fold::*;
71pub use generic_arg::*;
72#[cfg(not(feature = "nightly"))]
73pub use generic_visit::*;
74pub use infer_ctxt::*;
75pub use interner::*;
76pub use opaque_ty::*;
77pub use pattern::*;
78pub use predicate::*;
79pub use predicate_kind::*;
80pub use region_kind::*;
81pub use rustc_ast_ir::{FloatTy, IntTy, Movability, Mutability, Pinnedness, UintTy};
82use rustc_type_ir_macros::GenericTypeVisitable;
83pub use ty_info::*;
84pub use ty_kind::*;
85pub use unnormalized::Unnormalized;
86pub use upcast::*;
87pub use visit::*;
8889impl ::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! {
90/// A [De Bruijn index][dbi] is a standard means of representing
91 /// regions (and perhaps later types) in a higher-ranked setting. In
92 /// particular, imagine a type like this:
93 /// ```ignore (illustrative)
94 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
95 /// // ^ ^ | | |
96 /// // | | | | |
97 /// // | +------------+ 0 | |
98 /// // | | |
99 /// // +----------------------------------+ 1 |
100 /// // | |
101 /// // +----------------------------------------------+ 0
102 /// ```
103 /// In this type, there are two binders (the outer fn and the inner
104 /// fn). We need to be able to determine, for any given region, which
105 /// fn type it is bound by, the inner or the outer one. There are
106 /// various ways you can do this, but a De Bruijn index is one of the
107 /// more convenient and has some nice properties. The basic idea is to
108 /// count the number of binders, inside out. Some examples should help
109 /// clarify what I mean.
110 ///
111 /// Let's start with the reference type `&'b isize` that is the first
112 /// argument to the inner function. This region `'b` is assigned a De
113 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
114 /// fn). The region `'a` that appears in the second argument type (`&'a
115 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
116 /// second-innermost binder". (These indices are written on the arrows
117 /// in the diagram).
118 ///
119 /// What is interesting is that De Bruijn index attached to a particular
120 /// variable will vary depending on where it appears. For example,
121 /// the final type `&'a char` also refers to the region `'a` declared on
122 /// the outermost fn. But this time, this reference is not nested within
123 /// any other binders (i.e., it is not an argument to the inner fn, but
124 /// rather the outer one). Therefore, in this case, it is assigned a
125 /// De Bruijn index of 0, because the innermost binder in that location
126 /// is the outer fn.
127 ///
128 /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index
129#[stable_hash]
130 #[encodable]
131 #[orderable]
132 #[debug_format = "DebruijnIndex({})"]
133 #[gate_rustc_only]
134pub struct DebruijnIndex {
135const INNERMOST = 0;
136 }
137}138139impl DebruijnIndex {
140/// Returns the resulting index when this value is moved into
141 /// `amount` number of new binders. So, e.g., if you had
142 ///
143 /// for<'a> fn(&'a x)
144 ///
145 /// and you wanted to change it to
146 ///
147 /// for<'a> fn(for<'b> fn(&'a x))
148 ///
149 /// you would need to shift the index for `'a` into a new binder.
150#[inline]
151 #[must_use]
152pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
153DebruijnIndex::from_u32(self.as_u32() + amount)
154 }
155156/// Update this index in place by shifting it "in" through
157 /// `amount` number of binders.
158#[inline]
159pub fn shift_in(&mut self, amount: u32) {
160*self = self.shifted_in(amount);
161 }
162163/// Returns the resulting index when this value is moved out from
164 /// `amount` number of new binders.
165#[inline]
166 #[must_use]
167pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
168DebruijnIndex::from_u32(self.as_u32() - amount)
169 }
170171/// Update in place by shifting out from `amount` binders.
172#[inline]
173pub fn shift_out(&mut self, amount: u32) {
174*self = self.shifted_out(amount);
175 }
176177/// Adjusts any De Bruijn indices so as to make `to_binder` the
178 /// innermost binder. That is, if we have something bound at `to_binder`,
179 /// it will now be bound at INNERMOST. This is an appropriate thing to do
180 /// when moving a region out from inside binders:
181 ///
182 /// ```ignore (illustrative)
183 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
184 /// // Binder: D3 D2 D1 ^^
185 /// ```
186 ///
187 /// Here, the region `'a` would have the De Bruijn index D3,
188 /// because it is the bound 3 binders out. However, if we wanted
189 /// to refer to that region `'a` in the second argument (the `_`),
190 /// those two binders would not be in scope. In that case, we
191 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
192 /// De Bruijn index of `'a` to D1 (the innermost binder).
193 ///
194 /// If we invoke `shift_out_to_binder` and the region is in fact
195 /// bound by one of the binders we are shifting out of, that is an
196 /// error (and should fail an assertion failure).
197#[inline]
198pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
199self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
200 }
201}
202203pub fn debug_bound_var<T: std::fmt::Write>(
204 fmt: &mut T,
205 bound_index: BoundVarIndexKind,
206 var: impl std::fmt::Debug,
207) -> Result<(), std::fmt::Error> {
208match bound_index {
209 BoundVarIndexKind::Bound(debruijn) => {
210if debruijn == INNERMOST {
211fmt.write_fmt(format_args!("^{0:?}", var))write!(fmt, "^{var:?}")212 } else {
213fmt.write_fmt(format_args!("^{0}_{1:?}", debruijn.index(), var))write!(fmt, "^{}_{:?}", debruijn.index(), var)214 }
215 }
216 BoundVarIndexKind::Canonical => {
217fmt.write_fmt(format_args!("^c_{0:?}", var))write!(fmt, "^c_{:?}", var)218 }
219 }
220}
221222#[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)]
223#[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))]
224#[cfg_attr(feature = "nightly", rustc_pass_by_value)]
225pub enum Variance {
226 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
227Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
228Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
229Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
230}
231232impl Variance {
233/// `a.xform(b)` combines the variance of a context with the
234 /// variance of a type with the following meaning. If we are in a
235 /// context with variance `a`, and we encounter a type argument in
236 /// a position with variance `b`, then `a.xform(b)` is the new
237 /// variance with which the argument appears.
238 ///
239 /// Example 1:
240 /// ```ignore (illustrative)
241 /// *mut Vec<i32>
242 /// ```
243 /// Here, the "ambient" variance starts as covariant. `*mut T` is
244 /// invariant with respect to `T`, so the variance in which the
245 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
246 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
247 /// respect to its type argument `T`, and hence the variance of
248 /// the `i32` here is `Invariant.xform(Covariant)`, which results
249 /// (again) in `Invariant`.
250 ///
251 /// Example 2:
252 /// ```ignore (illustrative)
253 /// fn(*const Vec<i32>, *mut Vec<i32)
254 /// ```
255 /// The ambient variance is covariant. A `fn` type is
256 /// contravariant with respect to its parameters, so the variance
257 /// within which both pointer types appear is
258 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
259 /// T` is covariant with respect to `T`, so the variance within
260 /// which the first `Vec<i32>` appears is
261 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
262 /// is true for its `i32` argument. In the `*mut T` case, the
263 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
264 /// and hence the outermost type is `Invariant` with respect to
265 /// `Vec<i32>` (and its `i32` argument).
266 ///
267 /// Source: Figure 1 of "Taming the Wildcards:
268 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
269pub fn xform(self, v: Variance) -> Variance {
270match (self, v) {
271// Figure 1, column 1.
272(Variance::Covariant, Variance::Covariant) => Variance::Covariant,
273 (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
274 (Variance::Covariant, Variance::Invariant) => Variance::Invariant,
275 (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant,
276277// Figure 1, column 2.
278(Variance::Contravariant, Variance::Covariant) => Variance::Contravariant,
279 (Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
280 (Variance::Contravariant, Variance::Invariant) => Variance::Invariant,
281 (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant,
282283// Figure 1, column 3.
284(Variance::Invariant, _) => Variance::Invariant,
285286// Figure 1, column 4.
287(Variance::Bivariant, _) => Variance::Bivariant,
288 }
289 }
290}
291292impl fmt::Debugfor Variance {
293fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294f.write_str(match *self {
295 Variance::Covariant => "+",
296 Variance::Contravariant => "-",
297 Variance::Invariant => "o",
298 Variance::Bivariant => "*",
299 })
300 }
301}
302303impl ::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! {
304/// "Universes" are used during type- and trait-checking in the
305 /// presence of `for<..>` binders to control what sets of names are
306 /// visible. Universes are arranged into a tree: the root universe
307 /// contains names that are always visible. Each child then adds a new
308 /// set of names that are visible, in addition to those of its parent.
309 /// We say that the child universe "extends" the parent universe with
310 /// new names.
311 ///
312 /// To make this more concrete, consider this program:
313 ///
314 /// ```ignore (illustrative)
315 /// struct Foo { }
316 /// fn bar<T>(x: T) {
317 /// let y: for<'a> fn(&'a u8, Foo) = ...;
318 /// }
319 /// ```
320 ///
321 /// The struct name `Foo` is in the root universe U0. But the type
322 /// parameter `T`, introduced on `bar`, is in an extended universe U1
323 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
324 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
325 /// region `'a` is in a universe U2 that extends U1, because we can
326 /// name it inside the fn type but not outside.
327 ///
328 /// Universes are used to do type- and trait-checking around these
329 /// "forall" binders (also called **universal quantification**). The
330 /// idea is that when, in the body of `bar`, we refer to `T` as a
331 /// type, we aren't referring to any type in particular, but rather a
332 /// kind of "fresh" type that is distinct from all other types we have
333 /// actually declared. This is called a **placeholder** type, and we
334 /// use universes to talk about this. In other words, a type name in
335 /// universe 0 always corresponds to some "ground" type that the user
336 /// declared, but a type name in a non-zero universe is a placeholder
337 /// type -- an idealized representative of "types in general" that we
338 /// use for checking generic functions.
339#[stable_hash]
340 #[encodable]
341 #[orderable]
342 #[debug_format = "U{}"]
343 #[gate_rustc_only]
344pub struct UniverseIndex {}
345}346347impl UniverseIndex {
348pub const ROOT: UniverseIndex = UniverseIndex::ZERO;
349350/// Returns the "next" universe index in order -- this new index
351 /// is considered to extend all previous universes. This
352 /// corresponds to entering a `forall` quantifier. So, for
353 /// example, suppose we have this type in universe `U`:
354 ///
355 /// ```ignore (illustrative)
356 /// for<'a> fn(&'a u32)
357 /// ```
358 ///
359 /// Once we "enter" into this `for<'a>` quantifier, we are in a
360 /// new universe that extends `U` -- in this new universe, we can
361 /// name the region `'a`, but that region was not nameable from
362 /// `U` because it was not in scope there.
363pub fn next_universe(self) -> UniverseIndex {
364UniverseIndex::from_u32(self.as_u32().checked_add(1).unwrap())
365 }
366367/// Returns `true` if `self` can name a name from `other` -- in other words,
368 /// if the set of names in `self` is a superset of those in
369 /// `other` (`self >= other`).
370pub fn can_name(self, other: UniverseIndex) -> bool {
371self >= other372 }
373374/// Returns `true` if `self` cannot name some names from `other` -- in other
375 /// words, if the set of names in `self` is a strict subset of
376 /// those in `other` (`self < other`).
377pub fn cannot_name(self, other: UniverseIndex) -> bool {
378self < other379 }
380381/// Returns `true` if `self` is the root universe, otherwise false.
382pub fn is_root(self) -> bool {
383self == Self::ROOT384 }
385}
386387impl Defaultfor UniverseIndex {
388fn default() -> Self {
389Self::ROOT390 }
391}
392393impl ::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! {
394#[stable_hash]
395 #[encodable]
396 #[orderable]
397 #[debug_format = "{}"]
398 #[gate_rustc_only]
399pub struct BoundVar {}
400}401402/// Represents the various closure traits in the language. This
403/// will determine the type of the environment (`self`, in the
404/// desugaring) argument that the closure expects.
405///
406/// You can get the environment type of a closure using
407/// `tcx.closure_env_ty()`.
408#[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)]
409#[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))]
410pub enum ClosureKind {
411 Fn,
412 FnMut,
413 FnOnce,
414}
415416impl ClosureKind {
417/// This is the initial value used when doing upvar inference.
418pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
419420pub const fn as_str(self) -> &'static str {
421match self {
422 ClosureKind::Fn => "Fn",
423 ClosureKind::FnMut => "FnMut",
424 ClosureKind::FnOnce => "FnOnce",
425 }
426 }
427428/// Returns `true` if a type that impls this closure kind
429 /// must also implement `other`.
430#[rustfmt::skip]
431pub fn extends(self, other: ClosureKind) -> bool {
432use ClosureKind::*;
433match (self, other) {
434 (Fn, Fn | FnMut | FnOnce)
435 | (FnMut, FnMut | FnOnce)
436 | (FnOnce, FnOnce) => true,
437_ => false,
438 }
439 }
440}
441442impl fmt::Displayfor ClosureKind {
443fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444self.as_str().fmt(f)
445 }
446}
447448pub struct FieldInfo<I: Interner> {
449pub base: I::Ty,
450pub ty: I::Ty,
451pub variant: Option<I::Symbol>,
452pub variant_idx: VariantIdx,
453pub name: I::Symbol,
454pub field_idx: FieldIdx,
455}