1//! This crate is an abstraction layer, shared between rustc and rust-analyzer, to help with the
2//! overlapping responsibilities (like type inference and trait solving), reduce duplication, and
3//! maintain consistent behavior between the two implementations.
4//!
5//! It defines fundamental interfaces for types, predicates, and the context required by the next
6//! trait solver.
7//!
8//! Both rustc and rust-analyzer immplement these traits for their own concrete implementations, and
9//! `rustc_next_trait_solver` is written to be generic over these abstractions.
10//!
11//! In addition to these interfaces, it also contains components built on top of the abstraction
12//! layer, for example elaboration logic, and the search graph machinery used by the solver, as well
13//! as items that do not need compiler-specific implementations.
14//!
15//! Note that rust-analyzer is built with a stable compiler, while rustc uses unstable features, so
16//! this crate and some of its dependencies need to separate unstable code under the `nightly`
17//! feature.
18//!
19//! There are more details available in a [dedicated dev-guide
20//! chapter](https://rustc-dev-guide.rust-lang.org/solve/sharing-crates-with-rust-analyzer.html).
2122#![cfg_attr(feature = "nightly", rustc_diagnostic_item = "type_ir")]
23// tidy-alphabetical-start
24#![allow(rustc::direct_use_of_rustc_type_ir)]
25#![allow(rustc::usage_of_ty_tykind)]
26#![allow(rustc::usage_of_type_ir_inherent)]
27#![allow(rustc::usage_of_type_ir_traits)]
28#![cfg_attr(feature = "nightly", allow(internal_features))]
29#![cfg_attr(feature = "nightly", feature(associated_type_defaults, rustc_attrs, negative_impls))]
30#![deny(rustc::missing_generic_type_visitable_derive)]
31// tidy-alphabetical-end
3233extern crate self as rustc_type_ir;
3435use std::fmt;
36use std::hash::Hash;
3738use rustc_abi::{FieldIdx, VariantIdx};
39#[cfg(feature = "nightly")]
40use rustc_macros::{Decodable, Encodable, StableHash};
4142// These modules are `pub` since they are not glob-imported.
43pub mod data_structures;
44pub mod elaborate;
45pub mod error;
46pub mod fast_reject;
47#[cfg_attr(feature = "nightly", rustc_diagnostic_item = "type_ir_inherent")]
48pub mod inherent;
49pub mod intern;
50pub mod ir_print;
51pub mod lang_items;
52pub mod lift;
53pub mod outlives;
54pub mod region_constraint;
55pub mod relate;
56pub mod search_graph;
57pub mod solve;
58pub mod sty;
59pub mod transmute;
60pub mod walk;
6162// These modules are not `pub` since they are glob-imported.
63#[macro_use]
64mod macros;
65mod binder;
66mod canonical;
67mod const_kind;
68mod flags;
69mod fold;
70mod generic_arg;
71mod generic_visit;
72mod infer_ctxt;
73mod interner;
74mod opaque_ty;
75mod param_env;
76mod pattern;
77mod predicate;
78mod predicate_kind;
79mod region_kind;
80#[cfg(feature = "nightly")]
81mod serialize;
82mod term_kind;
83mod ty;
84mod ty_info;
85mod ty_kind;
86mod universe;
87mod unnormalized;
88mod upcast;
89mod visit;
9091pub use AliasTyKind::*;
92pub use InferTy::*;
93pub use RegionKind::*;
94pub use TyKind::*;
95pub use Variance::*;
96pub use binder::{Placeholder, *};
97pub use canonical::*;
98pub use const_kind::*;
99pub use flags::*;
100pub use fold::*;
101pub use generic_arg::*;
102pub use generic_visit::*;
103pub use infer_ctxt::*;
104pub use interner::*;
105pub use opaque_ty::*;
106pub use param_env::*;
107pub use pattern::*;
108pub use predicate::*;
109pub use predicate_kind::*;
110pub use region_kind::*;
111pub use rustc_ast_ir::{FloatTy, IntTy, Movability, Mutability, Pinnedness, UintTy};
112#[cfg(feature = "nightly")]
113pub use serialize::*;
114pub use sty::*;
115pub use term_kind::*;
116pub use ty::{Alias, *};
117pub use ty_info::*;
118pub use ty_kind::*;
119pub use universe::*;
120pub use unnormalized::Unnormalized;
121pub use upcast::*;
122pub use visit::*;
123124#[automatically_derived]impl ::core::marker::Copy for DebruijnIndex { }
pub const INNERMOST: DebruijnIndex = DebruijnIndex::from_u32(0);
impl DebruijnIndex {
#[doc = r" Maximum value the index can take, as a `u32`."]
pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
#[doc = r" Maximum value the index can take."]
pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
#[doc = r" Zero value of the index."]
pub const ZERO: Self = Self::from_u32(0);
#[doc = r" Creates a new index from a given `usize`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_usize(value: usize) -> Self {
if !(value <= (0xFFFF_FF00 as usize)) {
::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
};
unsafe { Self::from_u32_unchecked(value as u32) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u32(value: u32) -> Self {
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u16`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u16(value: u16) -> Self {
let value = value as u32;
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc =
r" The provided value must be less than or equal to the maximum value for the newtype."]
#[doc =
r" Providing a value outside this range is undefined due to layout restrictions."]
#[doc = r""]
#[doc = r" Prefer using `from_u32`."]
#[inline]
pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
Self {
private_use_as_methods_instead: unsafe {
std::mem::transmute(value)
},
}
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn index(self) -> usize { self.as_usize() }
#[doc = r" Extracts the value of this index as a `u32`."]
#[inline]
pub const fn as_u32(self) -> u32 {
unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for DebruijnIndex {
type Output = Self;
#[inline]
fn add(self, other: usize) -> Self {
Self::from_usize(self.index() + other)
}
}
impl std::ops::AddAssign<usize> for DebruijnIndex {
#[inline]
fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for DebruijnIndex {
#[inline]
fn new(value: usize) -> Self { Self::from_usize(value) }
#[inline]
fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for DebruijnIndex {
#[inline]
fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
<usize as
::std::iter::Step>::steps_between(&Self::index(*start),
&Self::index(*end))
}
#[inline]
fn forward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_add(u).map(Self::from_usize)
}
#[inline]
fn backward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_sub(u).map(Self::from_usize)
}
#[inline]
fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_add(u);
(Self::from_usize(s), o)
}
#[inline]
fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_sub(u);
(Self::from_usize(s), o)
}
}
impl ::std::cmp::Ord for DebruijnIndex {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_u32().cmp(&other.as_u32())
}
}
impl ::std::cmp::PartialOrd for DebruijnIndex {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl ::rustc_data_structures::stable_hash::StableHash for DebruijnIndex {
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
hcx: &mut __Hcx,
hasher: &mut ::rustc_data_structures::stable_hash::StableHasher) {
self.as_u32().stable_hash(hcx, hasher)
}
}
impl From<DebruijnIndex> for u32 {
#[inline]
fn from(v: DebruijnIndex) -> u32 { v.as_u32() }
}
impl From<DebruijnIndex> for usize {
#[inline]
fn from(v: DebruijnIndex) -> usize { v.as_usize() }
}
impl From<usize> for DebruijnIndex {
#[inline]
fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for DebruijnIndex {
#[inline]
fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for DebruijnIndex {}
impl ::std::cmp::PartialEq for DebruijnIndex {
fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for DebruijnIndex { }
impl ::std::hash::Hash for DebruijnIndex {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.as_u32().hash(state)
}
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
DebruijnIndex {
fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
DebruijnIndex {
fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::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! {
125/// A [De Bruijn index][dbi] is a standard means of representing
126 /// regions (and perhaps later types) in a higher-ranked setting. In
127 /// particular, imagine a type like this:
128 /// ```ignore (illustrative)
129 /// for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
130 /// // ^ ^ | | |
131 /// // | | | | |
132 /// // | +------------+ 0 | |
133 /// // | | |
134 /// // +----------------------------------+ 1 |
135 /// // | |
136 /// // +----------------------------------------------+ 0
137 /// ```
138 /// In this type, there are two binders (the outer fn and the inner
139 /// fn). We need to be able to determine, for any given region, which
140 /// fn type it is bound by, the inner or the outer one. There are
141 /// various ways you can do this, but a De Bruijn index is one of the
142 /// more convenient and has some nice properties. The basic idea is to
143 /// count the number of binders, inside out. Some examples should help
144 /// clarify what I mean.
145 ///
146 /// Let's start with the reference type `&'b isize` that is the first
147 /// argument to the inner function. This region `'b` is assigned a De
148 /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
149 /// fn). The region `'a` that appears in the second argument type (`&'a
150 /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
151 /// second-innermost binder". (These indices are written on the arrows
152 /// in the diagram).
153 ///
154 /// What is interesting is that De Bruijn index attached to a particular
155 /// variable will vary depending on where it appears. For example,
156 /// the final type `&'a char` also refers to the region `'a` declared on
157 /// the outermost fn. But this time, this reference is not nested within
158 /// any other binders (i.e., it is not an argument to the inner fn, but
159 /// rather the outer one). Therefore, in this case, it is assigned a
160 /// De Bruijn index of 0, because the innermost binder in that location
161 /// is the outer fn.
162 ///
163 /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index
164#[stable_hash]
165 #[encodable]
166 #[orderable]
167 #[debug_format = "DebruijnIndex({})"]
168 #[gate_rustc_only]
169pub struct DebruijnIndex {
170const INNERMOST = 0;
171 }
172}173174impl DebruijnIndex {
175/// Returns the resulting index when this value is moved into
176 /// `amount` number of new binders. So, e.g., if you had
177 ///
178 /// for<'a> fn(&'a x)
179 ///
180 /// and you wanted to change it to
181 ///
182 /// for<'a> fn(for<'b> fn(&'a x))
183 ///
184 /// you would need to shift the index for `'a` into a new binder.
185#[inline]
186 #[must_use]
187pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
188DebruijnIndex::from_u32(self.as_u32() + amount)
189 }
190191/// Update this index in place by shifting it "in" through
192 /// `amount` number of binders.
193#[inline]
194pub fn shift_in(&mut self, amount: u32) {
195*self = self.shifted_in(amount);
196 }
197198/// Returns the resulting index when this value is moved out from
199 /// `amount` number of new binders.
200#[inline]
201 #[must_use]
202pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
203DebruijnIndex::from_u32(self.as_u32() - amount)
204 }
205206/// Update in place by shifting out from `amount` binders.
207#[inline]
208pub fn shift_out(&mut self, amount: u32) {
209*self = self.shifted_out(amount);
210 }
211212/// Adjusts any De Bruijn indices so as to make `to_binder` the
213 /// innermost binder. That is, if we have something bound at `to_binder`,
214 /// it will now be bound at INNERMOST. This is an appropriate thing to do
215 /// when moving a region out from inside binders:
216 ///
217 /// ```ignore (illustrative)
218 /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _)
219 /// // Binder: D3 D2 D1 ^^
220 /// ```
221 ///
222 /// Here, the region `'a` would have the De Bruijn index D3,
223 /// because it is the bound 3 binders out. However, if we wanted
224 /// to refer to that region `'a` in the second argument (the `_`),
225 /// those two binders would not be in scope. In that case, we
226 /// might invoke `shift_out_to_binder(D3)`. This would adjust the
227 /// De Bruijn index of `'a` to D1 (the innermost binder).
228 ///
229 /// If we invoke `shift_out_to_binder` and the region is in fact
230 /// bound by one of the binders we are shifting out of, that is an
231 /// error (and should fail an assertion failure).
232#[inline]
233pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
234self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
235 }
236}
237238pub fn debug_bound_var<T: std::fmt::Write>(
239 fmt: &mut T,
240 bound_index: BoundVarIndexKind,
241 var: impl std::fmt::Debug,
242) -> Result<(), std::fmt::Error> {
243match bound_index {
244 BoundVarIndexKind::Bound(debruijn) => {
245if debruijn == INNERMOST {
246fmt.write_fmt(format_args!("^{0:?}", var))write!(fmt, "^{var:?}")247 } else {
248fmt.write_fmt(format_args!("^{0}_{1:?}", debruijn.index(), var))write!(fmt, "^{}_{:?}", debruijn.index(), var)249 }
250 }
251 BoundVarIndexKind::Canonical => {
252fmt.write_fmt(format_args!("^c_{0:?}", var))write!(fmt, "^c_{:?}", var)253 }
254 }
255}
256257#[derive(#[automatically_derived]impl ::core::marker::Copy for Variance { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Variance {
}
#[automatically_derived]impl ::core::clone::Clone for Variance {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Variance
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for Variance {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Variance { }Eq, #[automatically_derived]impl ::core::hash::Hash for Variance {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash)]
258#[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);
}
}
};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) {
match *self {
Variance::Covariant => 0u8.stable_hash(__hcx, __hasher),
Variance::Invariant => 1u8.stable_hash(__hcx, __hasher),
Variance::Contravariant => 2u8.stable_hash(__hcx, __hasher),
Variance::Bivariant => 3u8.stable_hash(__hcx, __hasher),
}
match *self {
Variance::Covariant => {}
Variance::Invariant => {}
Variance::Contravariant => {}
Variance::Bivariant => {}
}
}
}
};StableHash))]
259#[cfg_attr(feature = "nightly", rustc_pass_by_value)]
260pub enum Variance {
261 Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
262Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
263Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
264Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
265}
266267impl Variance {
268/// `a.xform(b)` combines the variance of a context with the
269 /// variance of a type with the following meaning. If we are in a
270 /// context with variance `a`, and we encounter a type argument in
271 /// a position with variance `b`, then `a.xform(b)` is the new
272 /// variance with which the argument appears.
273 ///
274 /// Example 1:
275 /// ```ignore (illustrative)
276 /// *mut Vec<i32>
277 /// ```
278 /// Here, the "ambient" variance starts as covariant. `*mut T` is
279 /// invariant with respect to `T`, so the variance in which the
280 /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
281 /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
282 /// respect to its type argument `T`, and hence the variance of
283 /// the `i32` here is `Invariant.xform(Covariant)`, which results
284 /// (again) in `Invariant`.
285 ///
286 /// Example 2:
287 /// ```ignore (illustrative)
288 /// fn(*const Vec<i32>, *mut Vec<i32)
289 /// ```
290 /// The ambient variance is covariant. A `fn` type is
291 /// contravariant with respect to its parameters, so the variance
292 /// within which both pointer types appear is
293 /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
294 /// T` is covariant with respect to `T`, so the variance within
295 /// which the first `Vec<i32>` appears is
296 /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
297 /// is true for its `i32` argument. In the `*mut T` case, the
298 /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
299 /// and hence the outermost type is `Invariant` with respect to
300 /// `Vec<i32>` (and its `i32` argument).
301 ///
302 /// Source: Figure 1 of "Taming the Wildcards:
303 /// Combining Definition- and Use-Site Variance" published in PLDI'11.
304pub fn xform(self, v: Variance) -> Variance {
305match (self, v) {
306// Figure 1, column 1.
307(Variance::Covariant, Variance::Covariant) => Variance::Covariant,
308 (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
309 (Variance::Covariant, Variance::Invariant) => Variance::Invariant,
310 (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant,
311312// Figure 1, column 2.
313(Variance::Contravariant, Variance::Covariant) => Variance::Contravariant,
314 (Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
315 (Variance::Contravariant, Variance::Invariant) => Variance::Invariant,
316 (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant,
317318// Figure 1, column 3.
319(Variance::Invariant, _) => Variance::Invariant,
320321// Figure 1, column 4.
322(Variance::Bivariant, _) => Variance::Bivariant,
323 }
324 }
325}
326327impl fmt::Debugfor Variance {
328fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329f.write_str(match *self {
330 Variance::Covariant => "+",
331 Variance::Contravariant => "-",
332 Variance::Invariant => "o",
333 Variance::Bivariant => "*",
334 })
335 }
336}
337338#[automatically_derived]impl ::core::marker::Copy for UniverseIndex { }
impl UniverseIndex {
#[doc = r" Maximum value the index can take, as a `u32`."]
pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
#[doc = r" Maximum value the index can take."]
pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
#[doc = r" Zero value of the index."]
pub const ZERO: Self = Self::from_u32(0);
#[doc = r" Creates a new index from a given `usize`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_usize(value: usize) -> Self {
if !(value <= (0xFFFF_FF00 as usize)) {
::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
};
unsafe { Self::from_u32_unchecked(value as u32) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u32(value: u32) -> Self {
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u16`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u16(value: u16) -> Self {
let value = value as u32;
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc =
r" The provided value must be less than or equal to the maximum value for the newtype."]
#[doc =
r" Providing a value outside this range is undefined due to layout restrictions."]
#[doc = r""]
#[doc = r" Prefer using `from_u32`."]
#[inline]
pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
Self {
private_use_as_methods_instead: unsafe {
std::mem::transmute(value)
},
}
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn index(self) -> usize { self.as_usize() }
#[doc = r" Extracts the value of this index as a `u32`."]
#[inline]
pub const fn as_u32(self) -> u32 {
unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for UniverseIndex {
type Output = Self;
#[inline]
fn add(self, other: usize) -> Self {
Self::from_usize(self.index() + other)
}
}
impl std::ops::AddAssign<usize> for UniverseIndex {
#[inline]
fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for UniverseIndex {
#[inline]
fn new(value: usize) -> Self { Self::from_usize(value) }
#[inline]
fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for UniverseIndex {
#[inline]
fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
<usize as
::std::iter::Step>::steps_between(&Self::index(*start),
&Self::index(*end))
}
#[inline]
fn forward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_add(u).map(Self::from_usize)
}
#[inline]
fn backward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_sub(u).map(Self::from_usize)
}
#[inline]
fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_add(u);
(Self::from_usize(s), o)
}
#[inline]
fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_sub(u);
(Self::from_usize(s), o)
}
}
impl ::std::cmp::Ord for UniverseIndex {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_u32().cmp(&other.as_u32())
}
}
impl ::std::cmp::PartialOrd for UniverseIndex {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl ::rustc_data_structures::stable_hash::StableHash for UniverseIndex {
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
hcx: &mut __Hcx,
hasher: &mut ::rustc_data_structures::stable_hash::StableHasher) {
self.as_u32().stable_hash(hcx, hasher)
}
}
impl std::default::Default for UniverseIndex {
#[inline]
fn default() -> Self { Self::ZERO }
}
impl From<UniverseIndex> for u32 {
#[inline]
fn from(v: UniverseIndex) -> u32 { v.as_u32() }
}
impl From<UniverseIndex> for usize {
#[inline]
fn from(v: UniverseIndex) -> usize { v.as_usize() }
}
impl From<usize> for UniverseIndex {
#[inline]
fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for UniverseIndex {
#[inline]
fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for UniverseIndex {}
impl ::std::cmp::PartialEq for UniverseIndex {
fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for UniverseIndex { }
impl ::std::hash::Hash for UniverseIndex {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.as_u32().hash(state)
}
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
UniverseIndex {
fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
UniverseIndex {
fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::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! {
339/// "Universes" are used during type- and trait-checking in the
340 /// presence of `for<..>` binders to control what sets of names are
341 /// visible. Universes are arranged into a tree: the root universe
342 /// contains names that are always visible. Each child then adds a new
343 /// set of names that are visible, in addition to those of its parent.
344 /// We say that the child universe "extends" the parent universe with
345 /// new names.
346 ///
347 /// To make this more concrete, consider this program:
348 ///
349 /// ```ignore (illustrative)
350 /// struct Foo { }
351 /// fn bar<T>(x: T) {
352 /// let y: for<'a> fn(&'a u8, Foo) = ...;
353 /// }
354 /// ```
355 ///
356 /// The struct name `Foo` is in the root universe U0. But the type
357 /// parameter `T`, introduced on `bar`, is in an extended universe U1
358 /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
359 /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
360 /// region `'a` is in a universe U2 that extends U1, because we can
361 /// name it inside the fn type but not outside.
362 ///
363 /// Universes are used to do type- and trait-checking around these
364 /// "forall" binders (also called **universal quantification**). The
365 /// idea is that when, in the body of `bar`, we refer to `T` as a
366 /// type, we aren't referring to any type in particular, but rather a
367 /// kind of "fresh" type that is distinct from all other types we have
368 /// actually declared. This is called a **placeholder** type, and we
369 /// use universes to talk about this. In other words, a type name in
370 /// universe 0 always corresponds to some "ground" type that the user
371 /// declared, but a type name in a non-zero universe is a placeholder
372 /// type -- an idealized representative of "types in general" that we
373 /// use for checking generic functions.
374#[stable_hash]
375 #[default]
376 #[encodable]
377 #[orderable]
378 #[debug_format = "U{}"]
379 #[gate_rustc_only]
380pub struct UniverseIndex {}
381}382383impl UniverseIndex {
384pub const ROOT: UniverseIndex = UniverseIndex::ZERO;
385386/// Returns the "next" universe index in order -- this new index
387 /// is considered to extend all previous universes. This
388 /// corresponds to entering a `forall` quantifier. So, for
389 /// example, suppose we have this type in universe `U`:
390 ///
391 /// ```ignore (illustrative)
392 /// for<'a> fn(&'a u32)
393 /// ```
394 ///
395 /// Once we "enter" into this `for<'a>` quantifier, we are in a
396 /// new universe that extends `U` -- in this new universe, we can
397 /// name the region `'a`, but that region was not nameable from
398 /// `U` because it was not in scope there.
399pub fn next_universe(self) -> UniverseIndex {
400UniverseIndex::from_u32(self.as_u32().checked_add(1).unwrap())
401 }
402403/// Returns `true` if `self` can name a name from `other` -- in other words,
404 /// if the set of names in `self` is a superset of those in
405 /// `other` (`self >= other`).
406pub fn can_name(self, other: UniverseIndex) -> bool {
407self >= other408 }
409410/// Returns `true` if `self` cannot name some names from `other` -- in other
411 /// words, if the set of names in `self` is a strict subset of
412 /// those in `other` (`self < other`).
413pub fn cannot_name(self, other: UniverseIndex) -> bool {
414self < other415 }
416417/// Returns `true` if `self` is the root universe, otherwise false.
418pub fn is_root(self) -> bool {
419self == Self::ROOT420 }
421}
422423#[automatically_derived]impl ::core::marker::Copy for BoundVar { }
impl BoundVar {
#[doc = r" Maximum value the index can take, as a `u32`."]
pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
#[doc = r" Maximum value the index can take."]
pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
#[doc = r" Zero value of the index."]
pub const ZERO: Self = Self::from_u32(0);
#[doc = r" Creates a new index from a given `usize`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_usize(value: usize) -> Self {
if !(value <= (0xFFFF_FF00 as usize)) {
::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
};
unsafe { Self::from_u32_unchecked(value as u32) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u32(value: u32) -> Self {
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u16`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u16(value: u16) -> Self {
let value = value as u32;
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc =
r" The provided value must be less than or equal to the maximum value for the newtype."]
#[doc =
r" Providing a value outside this range is undefined due to layout restrictions."]
#[doc = r""]
#[doc = r" Prefer using `from_u32`."]
#[inline]
pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
Self {
private_use_as_methods_instead: unsafe {
std::mem::transmute(value)
},
}
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn index(self) -> usize { self.as_usize() }
#[doc = r" Extracts the value of this index as a `u32`."]
#[inline]
pub const fn as_u32(self) -> u32 {
unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for BoundVar {
type Output = Self;
#[inline]
fn add(self, other: usize) -> Self {
Self::from_usize(self.index() + other)
}
}
impl std::ops::AddAssign<usize> for BoundVar {
#[inline]
fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for BoundVar {
#[inline]
fn new(value: usize) -> Self { Self::from_usize(value) }
#[inline]
fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for BoundVar {
#[inline]
fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
<usize as
::std::iter::Step>::steps_between(&Self::index(*start),
&Self::index(*end))
}
#[inline]
fn forward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_add(u).map(Self::from_usize)
}
#[inline]
fn backward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_sub(u).map(Self::from_usize)
}
#[inline]
fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_add(u);
(Self::from_usize(s), o)
}
#[inline]
fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_sub(u);
(Self::from_usize(s), o)
}
}
impl ::std::cmp::Ord for BoundVar {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_u32().cmp(&other.as_u32())
}
}
impl ::std::cmp::PartialOrd for BoundVar {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl ::rustc_data_structures::stable_hash::StableHash for BoundVar {
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
hcx: &mut __Hcx,
hasher: &mut ::rustc_data_structures::stable_hash::StableHasher) {
self.as_u32().stable_hash(hcx, hasher)
}
}
impl From<BoundVar> for u32 {
#[inline]
fn from(v: BoundVar) -> u32 { v.as_u32() }
}
impl From<BoundVar> for usize {
#[inline]
fn from(v: BoundVar) -> usize { v.as_usize() }
}
impl From<usize> for BoundVar {
#[inline]
fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for BoundVar {
#[inline]
fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for BoundVar {}
impl ::std::cmp::PartialEq for BoundVar {
fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for BoundVar { }
impl ::std::hash::Hash for BoundVar {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.as_u32().hash(state)
}
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
BoundVar {
fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
BoundVar {
fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::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! {
424#[stable_hash]
425 #[encodable]
426 #[orderable]
427 #[debug_format = "{}"]
428 #[gate_rustc_only]
429pub struct BoundVar {}
430}431432/// Represents the various closure traits in the language. This
433/// will determine the type of the environment (`self`, in the
434/// desugaring) argument that the closure expects.
435///
436/// You can get the environment type of a closure using
437/// `tcx.closure_env_ty()`.
438#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ClosureKind {
}
#[automatically_derived]impl ::core::clone::Clone for ClosureKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ClosureKind { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ClosureKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ClosureKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ClosureKind { }Eq, #[automatically_derived]impl ::core::hash::Hash for ClosureKind {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, #[automatically_derived]impl ::core::fmt::Debug for ClosureKind {
#[inline]
#[rustc_trivial_field_reads]
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)]
439#[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);
}
}
};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) {
match *self {
ClosureKind::Fn => 0u8.stable_hash(__hcx, __hasher),
ClosureKind::FnMut => 1u8.stable_hash(__hcx, __hasher),
ClosureKind::FnOnce => 2u8.stable_hash(__hcx, __hasher),
}
match *self {
ClosureKind::Fn => {}
ClosureKind::FnMut => {}
ClosureKind::FnOnce => {}
}
}
}
};StableHash))]
440pub enum ClosureKind {
441 Fn,
442 FnMut,
443 FnOnce,
444}
445446impl ClosureKind {
447/// This is the initial value used when doing upvar inference.
448pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
449450pub const fn as_str(self) -> &'static str {
451match self {
452 ClosureKind::Fn => "Fn",
453 ClosureKind::FnMut => "FnMut",
454 ClosureKind::FnOnce => "FnOnce",
455 }
456 }
457458/// Returns `true` if a type that impls this closure kind
459 /// must also implement `other`.
460#[rustfmt::skip]
461pub fn extends(self, other: ClosureKind) -> bool {
462use ClosureKind::*;
463match (self, other) {
464 (Fn, Fn | FnMut | FnOnce)
465 | (FnMut, FnMut | FnOnce)
466 | (FnOnce, FnOnce) => true,
467_ => false,
468 }
469 }
470}
471472impl fmt::Displayfor ClosureKind {
473fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474self.as_str().fmt(f)
475 }
476}
477478pub struct FieldInfo<I: Interner> {
479pub base: I::Ty,
480pub ty: I::Ty,
481pub variant: Option<I::Symbol>,
482pub variant_idx: VariantIdx,
483pub name: I::Symbol,
484pub field_idx: FieldIdx,
485}