Skip to main content

rustc_type_ir/
lib.rs

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).
21
22#![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// NOTE: the outer `cfg_attr` is only there so that r-a doesn't see the nightly-only `bootstrap`
31// in the inner `cfg_attr`. When the latter is removed, the former can be removed as well.
32#![cfg_attr(
33    feature = "nightly",
34    cfg_attr(not(bootstrap), deny(rustc::missing_generic_type_visitable_derive))
35)]
36// tidy-alphabetical-end
37
38extern crate self as rustc_type_ir;
39
40use std::fmt;
41use std::hash::Hash;
42
43use rustc_abi::{FieldIdx, VariantIdx};
44#[cfg(feature = "nightly")]
45use rustc_macros::{Decodable, Encodable, StableHash};
46
47// These modules are `pub` since they are not glob-imported.
48pub mod data_structures;
49pub mod elaborate;
50pub mod error;
51pub mod fast_reject;
52#[cfg_attr(feature = "nightly", rustc_diagnostic_item = "type_ir_inherent")]
53pub mod inherent;
54pub mod intern;
55pub mod ir_print;
56pub mod lang_items;
57pub mod lift;
58pub mod outlives;
59pub mod region_constraint;
60pub mod relate;
61pub mod search_graph;
62pub mod solve;
63pub mod sty;
64pub mod transmute;
65pub mod walk;
66
67// These modules are not `pub` since they are glob-imported.
68#[macro_use]
69mod macros;
70mod binder;
71mod canonical;
72mod const_kind;
73mod flags;
74mod fold;
75mod generic_arg;
76mod generic_visit;
77mod infer_ctxt;
78mod interner;
79mod opaque_ty;
80mod param_env;
81mod pattern;
82mod predicate;
83mod predicate_kind;
84mod region_kind;
85#[cfg(feature = "nightly")]
86mod serialize;
87mod term_kind;
88mod ty;
89mod ty_info;
90mod ty_kind;
91mod universe;
92mod unnormalized;
93mod upcast;
94mod visit;
95
96pub use AliasTyKind::*;
97pub use InferTy::*;
98pub use RegionKind::*;
99pub use TyKind::*;
100pub use Variance::*;
101pub use binder::{Placeholder, *};
102pub use canonical::*;
103pub use const_kind::*;
104pub use flags::*;
105pub use fold::*;
106pub use generic_arg::*;
107pub use generic_visit::*;
108pub use infer_ctxt::*;
109pub use interner::*;
110pub use opaque_ty::*;
111pub use param_env::*;
112pub use pattern::*;
113pub use predicate::*;
114pub use predicate_kind::*;
115pub use region_kind::*;
116pub use rustc_ast_ir::{FloatTy, IntTy, Movability, Mutability, Pinnedness, UintTy};
117#[cfg(feature = "nightly")]
118pub use serialize::*;
119pub use sty::*;
120pub use term_kind::*;
121pub use ty::{Alias, *};
122pub use ty_info::*;
123pub use ty_kind::*;
124pub use universe::*;
125pub use unnormalized::Unnormalized;
126pub use upcast::*;
127pub use visit::*;
128
129#[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! {
130    /// A [De Bruijn index][dbi] is a standard means of representing
131    /// regions (and perhaps later types) in a higher-ranked setting. In
132    /// particular, imagine a type like this:
133    /// ```ignore (illustrative)
134    ///    for<'a> fn(for<'b> fn(&'b isize, &'a isize), &'a char)
135    /// // ^          ^            |          |           |
136    /// // |          |            |          |           |
137    /// // |          +------------+ 0        |           |
138    /// // |                                  |           |
139    /// // +----------------------------------+ 1         |
140    /// // |                                              |
141    /// // +----------------------------------------------+ 0
142    /// ```
143    /// In this type, there are two binders (the outer fn and the inner
144    /// fn). We need to be able to determine, for any given region, which
145    /// fn type it is bound by, the inner or the outer one. There are
146    /// various ways you can do this, but a De Bruijn index is one of the
147    /// more convenient and has some nice properties. The basic idea is to
148    /// count the number of binders, inside out. Some examples should help
149    /// clarify what I mean.
150    ///
151    /// Let's start with the reference type `&'b isize` that is the first
152    /// argument to the inner function. This region `'b` is assigned a De
153    /// Bruijn index of 0, meaning "the innermost binder" (in this case, a
154    /// fn). The region `'a` that appears in the second argument type (`&'a
155    /// isize`) would then be assigned a De Bruijn index of 1, meaning "the
156    /// second-innermost binder". (These indices are written on the arrows
157    /// in the diagram).
158    ///
159    /// What is interesting is that De Bruijn index attached to a particular
160    /// variable will vary depending on where it appears. For example,
161    /// the final type `&'a char` also refers to the region `'a` declared on
162    /// the outermost fn. But this time, this reference is not nested within
163    /// any other binders (i.e., it is not an argument to the inner fn, but
164    /// rather the outer one). Therefore, in this case, it is assigned a
165    /// De Bruijn index of 0, because the innermost binder in that location
166    /// is the outer fn.
167    ///
168    /// [dbi]: https://en.wikipedia.org/wiki/De_Bruijn_index
169    #[stable_hash]
170    #[encodable]
171    #[orderable]
172    #[debug_format = "DebruijnIndex({})"]
173    #[gate_rustc_only]
174    pub struct DebruijnIndex {
175        const INNERMOST = 0;
176    }
177}
178
179impl DebruijnIndex {
180    /// Returns the resulting index when this value is moved into
181    /// `amount` number of new binders. So, e.g., if you had
182    ///
183    ///    for<'a> fn(&'a x)
184    ///
185    /// and you wanted to change it to
186    ///
187    ///    for<'a> fn(for<'b> fn(&'a x))
188    ///
189    /// you would need to shift the index for `'a` into a new binder.
190    #[inline]
191    #[must_use]
192    pub fn shifted_in(self, amount: u32) -> DebruijnIndex {
193        DebruijnIndex::from_u32(self.as_u32() + amount)
194    }
195
196    /// Update this index in place by shifting it "in" through
197    /// `amount` number of binders.
198    #[inline]
199    pub fn shift_in(&mut self, amount: u32) {
200        *self = self.shifted_in(amount);
201    }
202
203    /// Returns the resulting index when this value is moved out from
204    /// `amount` number of new binders.
205    #[inline]
206    #[must_use]
207    pub fn shifted_out(self, amount: u32) -> DebruijnIndex {
208        DebruijnIndex::from_u32(self.as_u32() - amount)
209    }
210
211    /// Update in place by shifting out from `amount` binders.
212    #[inline]
213    pub fn shift_out(&mut self, amount: u32) {
214        *self = self.shifted_out(amount);
215    }
216
217    /// Adjusts any De Bruijn indices so as to make `to_binder` the
218    /// innermost binder. That is, if we have something bound at `to_binder`,
219    /// it will now be bound at INNERMOST. This is an appropriate thing to do
220    /// when moving a region out from inside binders:
221    ///
222    /// ```ignore (illustrative)
223    ///             for<'a>   fn(for<'b>   for<'c>   fn(&'a u32), _)
224    /// // Binder:  D3           D2        D1            ^^
225    /// ```
226    ///
227    /// Here, the region `'a` would have the De Bruijn index D3,
228    /// because it is the bound 3 binders out. However, if we wanted
229    /// to refer to that region `'a` in the second argument (the `_`),
230    /// those two binders would not be in scope. In that case, we
231    /// might invoke `shift_out_to_binder(D3)`. This would adjust the
232    /// De Bruijn index of `'a` to D1 (the innermost binder).
233    ///
234    /// If we invoke `shift_out_to_binder` and the region is in fact
235    /// bound by one of the binders we are shifting out of, that is an
236    /// error (and should fail an assertion failure).
237    #[inline]
238    pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self {
239        self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32())
240    }
241}
242
243pub fn debug_bound_var<T: std::fmt::Write>(
244    fmt: &mut T,
245    bound_index: BoundVarIndexKind,
246    var: impl std::fmt::Debug,
247) -> Result<(), std::fmt::Error> {
248    match bound_index {
249        BoundVarIndexKind::Bound(debruijn) => {
250            if debruijn == INNERMOST {
251                fmt.write_fmt(format_args!("^{0:?}", var))write!(fmt, "^{var:?}")
252            } else {
253                fmt.write_fmt(format_args!("^{0}_{1:?}", debruijn.index(), var))write!(fmt, "^{}_{:?}", debruijn.index(), var)
254            }
255        }
256        BoundVarIndexKind::Canonical => {
257            fmt.write_fmt(format_args!("^c_{0:?}", var))write!(fmt, "^c_{:?}", var)
258        }
259    }
260}
261
262#[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]
    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)]
263#[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))]
264#[cfg_attr(feature = "nightly", rustc_pass_by_value)]
265pub enum Variance {
266    Covariant,     // T<A> <: T<B> iff A <: B -- e.g., function return type
267    Invariant,     // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
268    Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
269    Bivariant,     // T<A> <: T<B>            -- e.g., unused type parameter
270}
271
272impl Variance {
273    /// `a.xform(b)` combines the variance of a context with the
274    /// variance of a type with the following meaning. If we are in a
275    /// context with variance `a`, and we encounter a type argument in
276    /// a position with variance `b`, then `a.xform(b)` is the new
277    /// variance with which the argument appears.
278    ///
279    /// Example 1:
280    /// ```ignore (illustrative)
281    /// *mut Vec<i32>
282    /// ```
283    /// Here, the "ambient" variance starts as covariant. `*mut T` is
284    /// invariant with respect to `T`, so the variance in which the
285    /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
286    /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
287    /// respect to its type argument `T`, and hence the variance of
288    /// the `i32` here is `Invariant.xform(Covariant)`, which results
289    /// (again) in `Invariant`.
290    ///
291    /// Example 2:
292    /// ```ignore (illustrative)
293    /// fn(*const Vec<i32>, *mut Vec<i32)
294    /// ```
295    /// The ambient variance is covariant. A `fn` type is
296    /// contravariant with respect to its parameters, so the variance
297    /// within which both pointer types appear is
298    /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
299    /// T` is covariant with respect to `T`, so the variance within
300    /// which the first `Vec<i32>` appears is
301    /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
302    /// is true for its `i32` argument. In the `*mut T` case, the
303    /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
304    /// and hence the outermost type is `Invariant` with respect to
305    /// `Vec<i32>` (and its `i32` argument).
306    ///
307    /// Source: Figure 1 of "Taming the Wildcards:
308    /// Combining Definition- and Use-Site Variance" published in PLDI'11.
309    pub fn xform(self, v: Variance) -> Variance {
310        match (self, v) {
311            // Figure 1, column 1.
312            (Variance::Covariant, Variance::Covariant) => Variance::Covariant,
313            (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
314            (Variance::Covariant, Variance::Invariant) => Variance::Invariant,
315            (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant,
316
317            // Figure 1, column 2.
318            (Variance::Contravariant, Variance::Covariant) => Variance::Contravariant,
319            (Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
320            (Variance::Contravariant, Variance::Invariant) => Variance::Invariant,
321            (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant,
322
323            // Figure 1, column 3.
324            (Variance::Invariant, _) => Variance::Invariant,
325
326            // Figure 1, column 4.
327            (Variance::Bivariant, _) => Variance::Bivariant,
328        }
329    }
330}
331
332impl fmt::Debug for Variance {
333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334        f.write_str(match *self {
335            Variance::Covariant => "+",
336            Variance::Contravariant => "-",
337            Variance::Invariant => "o",
338            Variance::Bivariant => "*",
339        })
340    }
341}
342
343#[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! {
344    /// "Universes" are used during type- and trait-checking in the
345    /// presence of `for<..>` binders to control what sets of names are
346    /// visible. Universes are arranged into a tree: the root universe
347    /// contains names that are always visible. Each child then adds a new
348    /// set of names that are visible, in addition to those of its parent.
349    /// We say that the child universe "extends" the parent universe with
350    /// new names.
351    ///
352    /// To make this more concrete, consider this program:
353    ///
354    /// ```ignore (illustrative)
355    /// struct Foo { }
356    /// fn bar<T>(x: T) {
357    ///   let y: for<'a> fn(&'a u8, Foo) = ...;
358    /// }
359    /// ```
360    ///
361    /// The struct name `Foo` is in the root universe U0. But the type
362    /// parameter `T`, introduced on `bar`, is in an extended universe U1
363    /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
364    /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
365    /// region `'a` is in a universe U2 that extends U1, because we can
366    /// name it inside the fn type but not outside.
367    ///
368    /// Universes are used to do type- and trait-checking around these
369    /// "forall" binders (also called **universal quantification**). The
370    /// idea is that when, in the body of `bar`, we refer to `T` as a
371    /// type, we aren't referring to any type in particular, but rather a
372    /// kind of "fresh" type that is distinct from all other types we have
373    /// actually declared. This is called a **placeholder** type, and we
374    /// use universes to talk about this. In other words, a type name in
375    /// universe 0 always corresponds to some "ground" type that the user
376    /// declared, but a type name in a non-zero universe is a placeholder
377    /// type -- an idealized representative of "types in general" that we
378    /// use for checking generic functions.
379    #[stable_hash]
380    #[default]
381    #[encodable]
382    #[orderable]
383    #[debug_format = "U{}"]
384    #[gate_rustc_only]
385    pub struct UniverseIndex {}
386}
387
388impl UniverseIndex {
389    pub const ROOT: UniverseIndex = UniverseIndex::ZERO;
390
391    /// Returns the "next" universe index in order -- this new index
392    /// is considered to extend all previous universes. This
393    /// corresponds to entering a `forall` quantifier. So, for
394    /// example, suppose we have this type in universe `U`:
395    ///
396    /// ```ignore (illustrative)
397    /// for<'a> fn(&'a u32)
398    /// ```
399    ///
400    /// Once we "enter" into this `for<'a>` quantifier, we are in a
401    /// new universe that extends `U` -- in this new universe, we can
402    /// name the region `'a`, but that region was not nameable from
403    /// `U` because it was not in scope there.
404    pub fn next_universe(self) -> UniverseIndex {
405        UniverseIndex::from_u32(self.as_u32().checked_add(1).unwrap())
406    }
407
408    /// Returns `true` if `self` can name a name from `other` -- in other words,
409    /// if the set of names in `self` is a superset of those in
410    /// `other` (`self >= other`).
411    pub fn can_name(self, other: UniverseIndex) -> bool {
412        self >= other
413    }
414
415    /// Returns `true` if `self` cannot name some names from `other` -- in other
416    /// words, if the set of names in `self` is a strict subset of
417    /// those in `other` (`self < other`).
418    pub fn cannot_name(self, other: UniverseIndex) -> bool {
419        self < other
420    }
421
422    /// Returns `true` if `self` is the root universe, otherwise false.
423    pub fn is_root(self) -> bool {
424        self == Self::ROOT
425    }
426}
427
428#[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! {
429    #[stable_hash]
430    #[encodable]
431    #[orderable]
432    #[debug_format = "{}"]
433    #[gate_rustc_only]
434    pub struct BoundVar {}
435}
436
437/// Represents the various closure traits in the language. This
438/// will determine the type of the environment (`self`, in the
439/// desugaring) argument that the closure expects.
440///
441/// You can get the environment type of a closure using
442/// `tcx.closure_env_ty()`.
443#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ClosureKind {
}
#[automatically_derived]impl ::core::clone::Clone for ClosureKind {
    #[inline]
    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]
    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)]
444#[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))]
445pub enum ClosureKind {
446    Fn,
447    FnMut,
448    FnOnce,
449}
450
451impl ClosureKind {
452    /// This is the initial value used when doing upvar inference.
453    pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
454
455    pub const fn as_str(self) -> &'static str {
456        match self {
457            ClosureKind::Fn => "Fn",
458            ClosureKind::FnMut => "FnMut",
459            ClosureKind::FnOnce => "FnOnce",
460        }
461    }
462
463    /// Returns `true` if a type that impls this closure kind
464    /// must also implement `other`.
465    #[rustfmt::skip]
466    pub fn extends(self, other: ClosureKind) -> bool {
467        use ClosureKind::*;
468        match (self, other) {
469              (Fn, Fn | FnMut | FnOnce)
470            | (FnMut,   FnMut | FnOnce)
471            | (FnOnce,          FnOnce) => true,
472            _ => false,
473        }
474    }
475}
476
477impl fmt::Display for ClosureKind {
478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479        self.as_str().fmt(f)
480    }
481}
482
483pub struct FieldInfo<I: Interner> {
484    pub base: I::Ty,
485    pub ty: I::Ty,
486    pub variant: Option<I::Symbol>,
487    pub variant_idx: VariantIdx,
488    pub name: I::Symbol,
489    pub field_idx: FieldIdx,
490}