Skip to main content

rustc_infer/infer/
type_variable.rs

1use std::cmp;
2use std::marker::PhantomData;
3use std::ops::Range;
4
5use rustc_data_structures::undo_log::Rollback;
6use rustc_data_structures::{snapshot_vec as sv, unify as ut};
7use rustc_hir::HirId;
8use rustc_hir::def_id::DefId;
9use rustc_index::IndexVec;
10use rustc_middle::bug;
11use rustc_middle::ty::{self, Ty, TyVid};
12use rustc_span::Span;
13use tracing::debug;
14
15use crate::infer::InferCtxtUndoLogs;
16
17/// Represents a single undo-able action that affects a type inference variable.
18#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for UndoLog<'tcx> {
    #[inline]
    fn clone(&self) -> UndoLog<'tcx> {
        match self {
            UndoLog::EqRelation(__self_0) =>
                UndoLog::EqRelation(::core::clone::Clone::clone(__self_0)),
            UndoLog::SubRelation(__self_0) =>
                UndoLog::SubRelation(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
19pub(crate) enum UndoLog<'tcx> {
20    EqRelation(sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>),
21    SubRelation(sv::UndoLog<ut::Delegate<TyVidSubKey>>),
22}
23
24/// Convert from a specific kind of undo to the more general UndoLog
25impl<'tcx> From<sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>> for UndoLog<'tcx> {
26    fn from(l: sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>) -> Self {
27        UndoLog::EqRelation(l)
28    }
29}
30
31/// Convert from a specific kind of undo to the more general UndoLog
32impl<'tcx> From<sv::UndoLog<ut::Delegate<TyVidSubKey>>> for UndoLog<'tcx> {
33    fn from(l: sv::UndoLog<ut::Delegate<TyVidSubKey>>) -> Self {
34        UndoLog::SubRelation(l)
35    }
36}
37
38impl<'tcx> Rollback<sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>> for TypeVariableStorage<'tcx> {
39    fn reverse(&mut self, undo: sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>) {
40        self.eq_relations.reverse(undo)
41    }
42}
43
44impl<'tcx> Rollback<sv::UndoLog<ut::Delegate<TyVidSubKey>>> for TypeVariableStorage<'tcx> {
45    fn reverse(&mut self, undo: sv::UndoLog<ut::Delegate<TyVidSubKey>>) {
46        self.sub_unification_table.reverse(undo)
47    }
48}
49
50impl<'tcx> Rollback<UndoLog<'tcx>> for TypeVariableStorage<'tcx> {
51    fn reverse(&mut self, undo: UndoLog<'tcx>) {
52        match undo {
53            UndoLog::EqRelation(undo) => self.eq_relations.reverse(undo),
54            UndoLog::SubRelation(undo) => self.sub_unification_table.reverse(undo),
55        }
56    }
57}
58
59#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeVariableStorage<'tcx> {
    #[inline]
    fn clone(&self) -> TypeVariableStorage<'tcx> {
        TypeVariableStorage {
            values: ::core::clone::Clone::clone(&self.values),
            eq_relations: ::core::clone::Clone::clone(&self.eq_relations),
            sub_unification_table: ::core::clone::Clone::clone(&self.sub_unification_table),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::default::Default for TypeVariableStorage<'tcx> {
    #[inline]
    fn default() -> TypeVariableStorage<'tcx> {
        TypeVariableStorage {
            values: ::core::default::Default::default(),
            eq_relations: ::core::default::Default::default(),
            sub_unification_table: ::core::default::Default::default(),
        }
    }
}Default)]
60pub(crate) struct TypeVariableStorage<'tcx> {
61    /// The origins of each type variable.
62    values: IndexVec<TyVid, TypeVariableData>,
63    /// Two variables are unified in `eq_relations` when we have a
64    /// constraint `?X == ?Y`. This table also stores, for each key,
65    /// the known value.
66    eq_relations: ut::UnificationTableStorage<TyVidEqKey<'tcx>>,
67    /// Only used by `-Znext-solver` and for diagnostics. Tracks whether
68    /// type variables are related via subtyping at all, ignoring which of
69    /// the two is the subtype.
70    ///
71    /// When reporting ambiguity errors, we sometimes want to
72    /// treat all inference vars which are subtypes of each
73    /// others as if they are equal. For this case we compute
74    /// the transitive closure of our subtype obligations here.
75    ///
76    /// E.g. when encountering ambiguity errors, we want to suggest
77    /// specifying some method argument or to add a type annotation
78    /// to a local variable. Because subtyping cannot change the
79    /// shape of a type, it's fine if the cause of the ambiguity error
80    /// is only related to the suggested variable via subtyping.
81    ///
82    /// Even for something like `let x = returns_arg(); x.method();` the
83    /// type of `x` is only a supertype of the argument of `returns_arg`. We
84    /// still want to suggest specifying the type of the argument.
85    sub_unification_table: ut::UnificationTableStorage<TyVidSubKey>,
86}
87
88pub(crate) struct TypeVariableTable<'a, 'tcx> {
89    storage: &'a mut TypeVariableStorage<'tcx>,
90
91    undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
92}
93
94#[derive(#[automatically_derived]
impl ::core::marker::Copy for TypeVariableOrigin { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TypeVariableOrigin {
    #[inline]
    fn clone(&self) -> TypeVariableOrigin {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<Option<DefId>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TypeVariableOrigin {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TypeVariableOrigin", "span", &self.span, "param_def_id",
            &&self.param_def_id)
    }
}Debug)]
95pub struct TypeVariableOrigin {
96    pub span: Span,
97    /// `DefId` of the type parameter this was instantiated for, if any.
98    ///
99    /// This should only be used for diagnostics.
100    pub param_def_id: Option<DefId>,
101}
102
103#[derive(#[automatically_derived]
impl ::core::marker::Copy for FloatVariableOrigin { }Copy, #[automatically_derived]
impl ::core::clone::Clone for FloatVariableOrigin {
    #[inline]
    fn clone(&self) -> FloatVariableOrigin {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<Option<HirId>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for FloatVariableOrigin {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "FloatVariableOrigin", "span", &self.span, "lint_id",
            &&self.lint_id)
    }
}Debug)]
104pub struct FloatVariableOrigin {
105    pub span: Span,
106
107    /// `HirId` to lint at for this float variable, if any.
108    ///
109    /// This should only be used for diagnostics.
110    pub lint_id: Option<HirId>,
111}
112
113#[derive(#[automatically_derived]
impl ::core::clone::Clone for TypeVariableData {
    #[inline]
    fn clone(&self) -> TypeVariableData {
        TypeVariableData { origin: ::core::clone::Clone::clone(&self.origin) }
    }
}Clone)]
114pub(crate) struct TypeVariableData {
115    origin: TypeVariableOrigin,
116}
117
118#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeVariableValue<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeVariableValue<'tcx> {
    #[inline]
    fn clone(&self) -> TypeVariableValue<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ty::UniverseIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeVariableValue<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TypeVariableValue::Known { value: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Known",
                    "value", &__self_0),
            TypeVariableValue::Unknown { universe: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Unknown", "universe", &__self_0),
        }
    }
}Debug)]
119pub(crate) enum TypeVariableValue<'tcx> {
120    Known { value: Ty<'tcx> },
121    Unknown { universe: ty::UniverseIndex },
122}
123
124impl<'tcx> TypeVariableValue<'tcx> {
125    /// If this value is known, returns the type it is known to be.
126    /// Otherwise, `None`.
127    pub(crate) fn known(&self) -> Option<Ty<'tcx>> {
128        match *self {
129            TypeVariableValue::Unknown { .. } => None,
130            TypeVariableValue::Known { value } => Some(value),
131        }
132    }
133
134    pub(crate) fn is_unknown(&self) -> bool {
135        match *self {
136            TypeVariableValue::Unknown { .. } => true,
137            TypeVariableValue::Known { .. } => false,
138        }
139    }
140}
141
142impl<'tcx> TypeVariableStorage<'tcx> {
143    #[inline]
144    pub(crate) fn with_log<'a>(
145        &'a mut self,
146        undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
147    ) -> TypeVariableTable<'a, 'tcx> {
148        TypeVariableTable { storage: self, undo_log }
149    }
150
151    #[inline]
152    pub(crate) fn eq_relations_ref(&self) -> &ut::UnificationTableStorage<TyVidEqKey<'tcx>> {
153        &self.eq_relations
154    }
155
156    pub(super) fn finalize_rollback(&mut self) {
157        if true {
    if !(self.values.len() >= self.eq_relations.len()) {
        ::core::panicking::panic("assertion failed: self.values.len() >= self.eq_relations.len()")
    };
};debug_assert!(self.values.len() >= self.eq_relations.len());
158        self.values.truncate(self.eq_relations.len());
159    }
160}
161
162impl<'tcx> TypeVariableTable<'_, 'tcx> {
163    /// Returns the origin that was given when `vid` was created.
164    ///
165    /// Note that this function does not return care whether
166    /// `vid` has been unified with something else or not.
167    pub(crate) fn var_origin(&self, vid: ty::TyVid) -> TypeVariableOrigin {
168        self.storage.values[vid].origin
169    }
170
171    /// Records that `a == b`.
172    ///
173    /// Precondition: neither `a` nor `b` are known.
174    pub(crate) fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) {
175        if true {
    if !self.probe(a).is_unknown() {
        ::core::panicking::panic("assertion failed: self.probe(a).is_unknown()")
    };
};debug_assert!(self.probe(a).is_unknown());
176        if true {
    if !self.probe(b).is_unknown() {
        ::core::panicking::panic("assertion failed: self.probe(b).is_unknown()")
    };
};debug_assert!(self.probe(b).is_unknown());
177        self.eq_relations().union(a, b);
178        self.sub_unification_table().union(a, b);
179    }
180
181    /// Records that `a` and `b` are related via subtyping. We don't track
182    /// which of the two is the subtype.
183    ///
184    /// Precondition: neither `a` nor `b` are known.
185    pub(crate) fn sub_unify(&mut self, a: ty::TyVid, b: ty::TyVid) {
186        if true {
    if !self.probe(a).is_unknown() {
        ::core::panicking::panic("assertion failed: self.probe(a).is_unknown()")
    };
};debug_assert!(self.probe(a).is_unknown());
187        if true {
    if !self.probe(b).is_unknown() {
        ::core::panicking::panic("assertion failed: self.probe(b).is_unknown()")
    };
};debug_assert!(self.probe(b).is_unknown());
188        self.sub_unification_table().union(a, b);
189    }
190
191    /// Instantiates `vid` with the type `ty`.
192    ///
193    /// Precondition: `vid` must not have been previously instantiated.
194    pub(crate) fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) {
195        let vid = self.root_var(vid);
196        if true {
    if !!ty.is_ty_var() {
        {
            ::core::panicking::panic_fmt(format_args!("instantiating ty var with var: {0:?} {1:?}",
                    vid, ty));
        }
    };
};debug_assert!(!ty.is_ty_var(), "instantiating ty var with var: {vid:?} {ty:?}");
197        if true {
    if !self.probe(vid).is_unknown() {
        ::core::panicking::panic("assertion failed: self.probe(vid).is_unknown()")
    };
};debug_assert!(self.probe(vid).is_unknown());
198        if true {
    if !self.eq_relations().probe_value(vid).is_unknown() {
        {
            ::core::panicking::panic_fmt(format_args!("instantiating type variable `{1:?}` twice: new-value = {2:?}, old-value={0:?}",
                    self.eq_relations().probe_value(vid), vid, ty));
        }
    };
};debug_assert!(
199            self.eq_relations().probe_value(vid).is_unknown(),
200            "instantiating type variable `{vid:?}` twice: new-value = {ty:?}, old-value={:?}",
201            self.eq_relations().probe_value(vid)
202        );
203        self.eq_relations().union_value(vid, TypeVariableValue::Known { value: ty });
204    }
205
206    /// Creates a new type variable.
207    ///
208    /// - `diverging`: indicates if this is a "diverging" type
209    ///   variable, e.g.,  one created as the type of a `return`
210    ///   expression. The code in this module doesn't care if a
211    ///   variable is diverging, but the main Rust type-checker will
212    ///   sometimes "unify" such variables with the `!` or `()` types.
213    /// - `origin`: indicates *why* the type variable was created.
214    ///   The code in this module doesn't care, but it can be useful
215    ///   for improving error messages.
216    pub(crate) fn new_var(
217        &mut self,
218        universe: ty::UniverseIndex,
219        origin: TypeVariableOrigin,
220    ) -> ty::TyVid {
221        let eq_key = self.eq_relations().new_key(TypeVariableValue::Unknown { universe });
222
223        let sub_key = self.sub_unification_table().new_key(());
224        if true {
    {
        match (&eq_key.vid, &sub_key.vid) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(eq_key.vid, sub_key.vid);
225
226        let index = self.storage.values.push(TypeVariableData { origin });
227        if true {
    {
        match (&eq_key.vid, &index) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(eq_key.vid, index);
228
229        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/type_variable.rs:229",
                        "rustc_infer::infer::type_variable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/type_variable.rs"),
                        ::tracing_core::__macro_support::Option::Some(229u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::type_variable"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("new_var(index={0:?}, universe={1:?}, origin={2:?})",
                                                    eq_key.vid, universe, origin) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("new_var(index={:?}, universe={:?}, origin={:?})", eq_key.vid, universe, origin);
230
231        index
232    }
233
234    /// Returns the number of type variables created thus far.
235    pub(crate) fn num_vars(&self) -> usize {
236        self.storage.values.len()
237    }
238
239    /// Returns the "root" variable of `vid` in the `eq_relations`
240    /// equivalence table. All type variables that have been equated
241    /// will yield the same root variable (per the union-find
242    /// algorithm), so `root_var(a) == root_var(b)` implies that `a ==
243    /// b` (transitively).
244    pub(crate) fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
245        self.eq_relations().find(vid).vid
246    }
247
248    /// Returns the "root" variable of `vid` in the `sub_unification_table`
249    /// equivalence table. All type variables that have been related via
250    /// equality or subtyping will yield the same root variable (per the
251    /// union-find algorithm), so `sub_unification_table_root_var(a)
252    /// == sub_unification_table_root_var(b)` implies that `a` and `b` are
253    /// transitively related via subtyping.
254    pub(crate) fn sub_unification_table_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
255        self.sub_unification_table().find(vid).vid
256    }
257
258    /// Retrieves the type to which `vid` has been instantiated, if
259    /// any.
260    pub(crate) fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
261        self.inlined_probe(vid)
262    }
263
264    /// An always-inlined variant of `probe`, for very hot call sites.
265    #[inline(always)]
266    pub(crate) fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
267        self.eq_relations().inlined_probe_value(vid)
268    }
269
270    /// Retrieves the type to which `vid` has been instantiated, if
271    /// any, along with the root `vid`.
272    pub(crate) fn probe_with_root_vid(
273        &mut self,
274        vid: ty::TyVid,
275    ) -> (ty::TyVid, TypeVariableValue<'tcx>) {
276        self.inlined_probe_with_vid(vid)
277    }
278
279    /// An always-inlined variant of `probe_with_root_vid`, for very hot call sites.
280    #[inline(always)]
281    pub(crate) fn inlined_probe_with_vid(
282        &mut self,
283        vid: ty::TyVid,
284    ) -> (ty::TyVid, TypeVariableValue<'tcx>) {
285        let (id, value) = self.eq_relations().inlined_probe_key_value(vid);
286        (id.vid, value)
287    }
288
289    #[inline]
290    fn eq_relations(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidEqKey<'tcx>> {
291        self.storage.eq_relations.with_log(self.undo_log)
292    }
293
294    #[inline]
295    fn sub_unification_table(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidSubKey> {
296        self.storage.sub_unification_table.with_log(self.undo_log)
297    }
298
299    /// Returns a range of the type variables created during the snapshot.
300    pub(crate) fn vars_since_snapshot(
301        &mut self,
302        value_count: usize,
303    ) -> (Range<TyVid>, Vec<TypeVariableOrigin>) {
304        let range = TyVid::from_usize(value_count)..TyVid::from_usize(self.num_vars());
305        (range.clone(), range.map(|index| self.var_origin(index)).collect())
306    }
307
308    /// Returns indices of all root variables that are not yet instantiated.
309    pub(crate) fn unresolved_root_variables(&mut self) -> Vec<ty::TyVid> {
310        (0..self.num_vars())
311            .map(ty::TyVid::from_usize)
312            .filter(|&vid| {
313                let (root, value) = self.probe_with_root_vid(vid);
314                root == vid && value.is_unknown()
315            })
316            .collect()
317    }
318}
319
320///////////////////////////////////////////////////////////////////////////
321
322/// These structs (a newtyped TyVid) are used as the unification key
323/// for the `eq_relations`; they carry a `TypeVariableValue` along
324/// with them.
325#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TyVidEqKey<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TyVidEqKey<'tcx> {
    #[inline]
    fn clone(&self) -> TyVidEqKey<'tcx> {
        let _: ::core::clone::AssertParamIsClone<ty::TyVid>;
        let _:
                ::core::clone::AssertParamIsClone<PhantomData<TypeVariableValue<'tcx>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TyVidEqKey<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "TyVidEqKey",
            "vid", &self.vid, "phantom", &&self.phantom)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for TyVidEqKey<'tcx> {
    #[inline]
    fn eq(&self, other: &TyVidEqKey<'tcx>) -> bool {
        self.vid == other.vid && self.phantom == other.phantom
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for TyVidEqKey<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ty::TyVid>;
        let _:
                ::core::cmp::AssertParamIsEq<PhantomData<TypeVariableValue<'tcx>>>;
    }
}Eq)]
326pub(crate) struct TyVidEqKey<'tcx> {
327    vid: ty::TyVid,
328
329    // in the table, we map each ty-vid to one of these:
330    phantom: PhantomData<TypeVariableValue<'tcx>>,
331}
332
333impl<'tcx> From<ty::TyVid> for TyVidEqKey<'tcx> {
334    #[inline] // make this function eligible for inlining - it is quite hot.
335    fn from(vid: ty::TyVid) -> Self {
336        TyVidEqKey { vid, phantom: PhantomData }
337    }
338}
339
340impl<'tcx> ut::UnifyKey for TyVidEqKey<'tcx> {
341    type Value = TypeVariableValue<'tcx>;
342    #[inline(always)]
343    fn index(&self) -> u32 {
344        self.vid.as_u32()
345    }
346    #[inline]
347    fn from_index(i: u32) -> Self {
348        TyVidEqKey::from(ty::TyVid::from_u32(i))
349    }
350    fn tag() -> &'static str {
351        "TyVidEqKey"
352    }
353    fn order_roots(a: Self, _: &Self::Value, b: Self, _: &Self::Value) -> Option<(Self, Self)> {
354        if a.vid.as_u32() < b.vid.as_u32() { Some((a, b)) } else { Some((b, a)) }
355    }
356}
357
358#[derive(#[automatically_derived]
impl ::core::marker::Copy for TyVidSubKey { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TyVidSubKey {
    #[inline]
    fn clone(&self) -> TyVidSubKey {
        let _: ::core::clone::AssertParamIsClone<ty::TyVid>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TyVidSubKey {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "TyVidSubKey",
            "vid", &&self.vid)
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for TyVidSubKey {
    #[inline]
    fn eq(&self, other: &TyVidSubKey) -> bool { self.vid == other.vid }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TyVidSubKey {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ty::TyVid>;
    }
}Eq)]
359pub(crate) struct TyVidSubKey {
360    vid: ty::TyVid,
361}
362
363impl From<ty::TyVid> for TyVidSubKey {
364    #[inline] // make this function eligible for inlining - it is quite hot.
365    fn from(vid: ty::TyVid) -> Self {
366        TyVidSubKey { vid }
367    }
368}
369
370impl ut::UnifyKey for TyVidSubKey {
371    type Value = ();
372    #[inline]
373    fn index(&self) -> u32 {
374        self.vid.as_u32()
375    }
376    #[inline]
377    fn from_index(i: u32) -> TyVidSubKey {
378        TyVidSubKey { vid: ty::TyVid::from_u32(i) }
379    }
380    fn tag() -> &'static str {
381        "TyVidSubKey"
382    }
383}
384
385impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> {
386    type Error = ut::NoError;
387
388    fn unify_values(value1: &Self, value2: &Self) -> Result<Self, ut::NoError> {
389        match (value1, value2) {
390            // We never equate two type variables, both of which
391            // have known types. Instead, we recursively equate
392            // those types.
393            (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => {
394                ::rustc_middle::util::bug::bug_fmt(format_args!("equating two type variables, both of which have known types"))bug!("equating two type variables, both of which have known types")
395            }
396
397            // If one side is known, prefer that one.
398            (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1),
399            (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2),
400
401            // If both sides are *unknown*, it hardly matters, does it?
402            (
403                &TypeVariableValue::Unknown { universe: universe1 },
404                &TypeVariableValue::Unknown { universe: universe2 },
405            ) => {
406                // If we unify two unbound variables, ?T and ?U, then whatever
407                // value they wind up taking (which must be the same value) must
408                // be nameable by both universes. Therefore, the resulting
409                // universe is the minimum of the two universes, because that is
410                // the one which contains the fewest names in scope.
411                let universe = cmp::min(universe1, universe2);
412                Ok(TypeVariableValue::Unknown { universe })
413            }
414        }
415    }
416}