1 use rustc_hir::def_id::DefId;
2 use rustc_middle::ty::{self, Ty, TyVid};
3 use rustc_span::symbol::Symbol;
6 use crate::infer::InferCtxtUndoLogs;
8 use rustc_data_structures::snapshot_vec as sv;
9 use rustc_data_structures::unify as ut;
11 use std::marker::PhantomData;
14 use rustc_data_structures::undo_log::{Rollback, UndoLogs};
16 /// Represents a single undo-able action that affects a type inference variable.
17 pub(crate) enum UndoLog<'tcx> {
18 EqRelation(sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>),
19 SubRelation(sv::UndoLog<ut::Delegate<ty::TyVid>>),
20 Values(sv::UndoLog<Delegate>),
23 /// Convert from a specific kind of undo to the more general UndoLog
24 impl<'tcx> From<sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>> for UndoLog<'tcx> {
25 fn from(l: sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>) -> Self {
26 UndoLog::EqRelation(l)
30 /// Convert from a specific kind of undo to the more general UndoLog
31 impl<'tcx> From<sv::UndoLog<ut::Delegate<ty::TyVid>>> for UndoLog<'tcx> {
32 fn from(l: sv::UndoLog<ut::Delegate<ty::TyVid>>) -> Self {
33 UndoLog::SubRelation(l)
37 /// Convert from a specific kind of undo to the more general UndoLog
38 impl<'tcx> From<sv::UndoLog<Delegate>> for UndoLog<'tcx> {
39 fn from(l: sv::UndoLog<Delegate>) -> Self {
44 /// Convert from a specific kind of undo to the more general UndoLog
45 impl<'tcx> From<Instantiate> for UndoLog<'tcx> {
46 fn from(l: Instantiate) -> Self {
47 UndoLog::Values(sv::UndoLog::Other(l))
51 impl<'tcx> Rollback<UndoLog<'tcx>> for TypeVariableStorage<'tcx> {
52 fn reverse(&mut self, undo: UndoLog<'tcx>) {
54 UndoLog::EqRelation(undo) => self.eq_relations.reverse(undo),
55 UndoLog::SubRelation(undo) => self.sub_relations.reverse(undo),
56 UndoLog::Values(undo) => self.values.reverse(undo),
61 pub struct TypeVariableStorage<'tcx> {
62 values: sv::SnapshotVecStorage<Delegate>,
64 /// Two variables are unified in `eq_relations` when we have a
65 /// constraint `?X == ?Y`. This table also stores, for each key,
67 eq_relations: ut::UnificationTableStorage<TyVidEqKey<'tcx>>,
69 /// Two variables are unified in `sub_relations` when we have a
70 /// constraint `?X <: ?Y` *or* a constraint `?Y <: ?X`. This second
71 /// table exists only to help with the occurs check. In particular,
72 /// we want to report constraints like these as an occurs check
78 /// Without this second table, what would happen in a case like
79 /// this is that we would instantiate `?1` with a generalized
80 /// type like `Box<?6>`. We would then relate `Box<?3> <: Box<?6>`
81 /// and infer that `?3 <: ?6`. Next, since `?1` was instantiated,
82 /// we would process `?1 <: ?3`, generalize `?1 = Box<?6>` to `Box<?9>`,
83 /// and instantiate `?3` with `Box<?9>`. Finally, we would relate
84 /// `?6 <: ?9`. But now that we instantiated `?3`, we can process
85 /// `?3 <: ?6`, which gives us `Box<?9> <: ?6`... and the cycle
86 /// continues. (This is `occurs-check-2.rs`.)
88 /// What prevents this cycle is that when we generalize
89 /// `Box<?3>` to `Box<?6>`, we also sub-unify `?3` and `?6`
90 /// (in the generalizer). When we then process `Box<?6> <: ?3`,
91 /// the occurs check then fails because `?6` and `?3` are sub-unified,
92 /// and hence generalization fails.
94 /// This is reasonable because, in Rust, subtypes have the same
95 /// "skeleton" and hence there is no possible type such that
96 /// (e.g.) `Box<?3> <: ?3` for any `?3`.
98 /// In practice, we sometimes sub-unify variables in other spots, such
99 /// as when processing subtype predicates. This is not necessary but is
100 /// done to aid diagnostics, as it allows us to be more effective when
101 /// we guide the user towards where they should insert type hints.
102 sub_relations: ut::UnificationTableStorage<ty::TyVid>,
105 pub struct TypeVariableTable<'a, 'tcx> {
106 storage: &'a mut TypeVariableStorage<'tcx>,
108 undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
111 #[derive(Copy, Clone, Debug)]
112 pub struct TypeVariableOrigin {
113 pub kind: TypeVariableOriginKind,
117 /// Reasons to create a type inference variable
118 #[derive(Copy, Clone, Debug)]
119 pub enum TypeVariableOriginKind {
121 NormalizeProjectionType,
123 TypeParameterDefinition(Symbol, Option<DefId>),
125 /// One of the upvars or closure kind parameters in a `ClosureSubsts`
126 /// (before it has been determined).
127 // FIXME(eddyb) distinguish upvar inference variables from the rest.
129 SubstitutionPlaceholder,
133 /// In type check, when we are type checking a function that
134 /// returns `-> dyn Foo`, we substitute a type variable for the
135 /// return type for diagnostic purposes.
140 pub(crate) struct TypeVariableData {
141 origin: TypeVariableOrigin,
144 #[derive(Copy, Clone, Debug)]
145 pub enum TypeVariableValue<'tcx> {
146 Known { value: Ty<'tcx> },
147 Unknown { universe: ty::UniverseIndex },
150 impl<'tcx> TypeVariableValue<'tcx> {
151 /// If this value is known, returns the type it is known to be.
152 /// Otherwise, `None`.
153 pub fn known(&self) -> Option<Ty<'tcx>> {
155 TypeVariableValue::Unknown { .. } => None,
156 TypeVariableValue::Known { value } => Some(value),
160 pub fn is_unknown(&self) -> bool {
162 TypeVariableValue::Unknown { .. } => true,
163 TypeVariableValue::Known { .. } => false,
168 pub(crate) struct Instantiate;
170 pub(crate) struct Delegate;
172 impl<'tcx> TypeVariableStorage<'tcx> {
173 pub fn new() -> TypeVariableStorage<'tcx> {
174 TypeVariableStorage {
175 values: sv::SnapshotVecStorage::new(),
176 eq_relations: ut::UnificationTableStorage::new(),
177 sub_relations: ut::UnificationTableStorage::new(),
182 pub(crate) fn with_log<'a>(
184 undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
185 ) -> TypeVariableTable<'a, 'tcx> {
186 TypeVariableTable { storage: self, undo_log }
190 impl<'tcx> TypeVariableTable<'_, 'tcx> {
191 /// Returns the origin that was given when `vid` was created.
193 /// Note that this function does not return care whether
194 /// `vid` has been unified with something else or not.
195 pub fn var_origin(&self, vid: ty::TyVid) -> &TypeVariableOrigin {
196 &self.storage.values.get(vid.as_usize()).origin
199 /// Records that `a == b`, depending on `dir`.
201 /// Precondition: neither `a` nor `b` are known.
202 pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) {
203 debug_assert!(self.probe(a).is_unknown());
204 debug_assert!(self.probe(b).is_unknown());
205 self.eq_relations().union(a, b);
206 self.sub_relations().union(a, b);
209 /// Records that `a <: b`, depending on `dir`.
211 /// Precondition: neither `a` nor `b` are known.
212 pub fn sub(&mut self, a: ty::TyVid, b: ty::TyVid) {
213 debug_assert!(self.probe(a).is_unknown());
214 debug_assert!(self.probe(b).is_unknown());
215 self.sub_relations().union(a, b);
218 /// Instantiates `vid` with the type `ty`.
220 /// Precondition: `vid` must not have been previously instantiated.
221 pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) {
222 let vid = self.root_var(vid);
223 debug_assert!(self.probe(vid).is_unknown());
225 self.eq_relations().probe_value(vid).is_unknown(),
226 "instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}",
229 self.eq_relations().probe_value(vid)
231 self.eq_relations().union_value(vid, TypeVariableValue::Known { value: ty });
233 // Hack: we only need this so that `types_escaping_snapshot`
234 // can see what has been unified; see the Delegate impl for
236 self.undo_log.push(Instantiate);
239 /// Creates a new type variable.
241 /// - `diverging`: indicates if this is a "diverging" type
242 /// variable, e.g., one created as the type of a `return`
243 /// expression. The code in this module doesn't care if a
244 /// variable is diverging, but the main Rust type-checker will
245 /// sometimes "unify" such variables with the `!` or `()` types.
246 /// - `origin`: indicates *why* the type variable was created.
247 /// The code in this module doesn't care, but it can be useful
248 /// for improving error messages.
251 universe: ty::UniverseIndex,
252 origin: TypeVariableOrigin,
254 let eq_key = self.eq_relations().new_key(TypeVariableValue::Unknown { universe });
256 let sub_key = self.sub_relations().new_key(());
257 assert_eq!(eq_key.vid, sub_key);
259 let index = self.values().push(TypeVariableData { origin });
260 assert_eq!(eq_key.vid.as_u32(), index as u32);
262 debug!("new_var(index={:?}, universe={:?}, origin={:?}", eq_key.vid, universe, origin,);
267 /// Returns the number of type variables created thus far.
268 pub fn num_vars(&self) -> usize {
269 self.storage.values.len()
272 /// Returns the "root" variable of `vid` in the `eq_relations`
273 /// equivalence table. All type variables that have been equated
274 /// will yield the same root variable (per the union-find
275 /// algorithm), so `root_var(a) == root_var(b)` implies that `a ==
276 /// b` (transitively).
277 pub fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
278 self.eq_relations().find(vid).vid
281 /// Returns the "root" variable of `vid` in the `sub_relations`
282 /// equivalence table. All type variables that have been are
283 /// related via equality or subtyping will yield the same root
284 /// variable (per the union-find algorithm), so `sub_root_var(a)
285 /// == sub_root_var(b)` implies that:
287 /// exists X. (a <: X || X <: a) && (b <: X || X <: b)
288 pub fn sub_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
289 self.sub_relations().find(vid)
292 /// Returns `true` if `a` and `b` have same "sub-root" (i.e., exists some
293 /// type X such that `forall i in {a, b}. (i <: X || X <: i)`.
294 pub fn sub_unified(&mut self, a: ty::TyVid, b: ty::TyVid) -> bool {
295 self.sub_root_var(a) == self.sub_root_var(b)
298 /// Retrieves the type to which `vid` has been instantiated, if
300 pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
301 self.inlined_probe(vid)
304 /// An always-inlined variant of `probe`, for very hot call sites.
306 pub fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
307 self.eq_relations().inlined_probe_value(vid)
310 /// If `t` is a type-inference variable, and it has been
311 /// instantiated, then return the with which it was
312 /// instantiated. Otherwise, returns `t`.
313 pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
315 ty::Infer(ty::TyVar(v)) => match self.probe(v) {
316 TypeVariableValue::Unknown { .. } => t,
317 TypeVariableValue::Known { value } => value,
326 ) -> sv::SnapshotVec<Delegate, &mut Vec<TypeVariableData>, &mut InferCtxtUndoLogs<'tcx>> {
327 self.storage.values.with_log(self.undo_log)
331 fn eq_relations(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidEqKey<'tcx>> {
332 self.storage.eq_relations.with_log(self.undo_log)
336 fn sub_relations(&mut self) -> super::UnificationTable<'_, 'tcx, ty::TyVid> {
337 self.storage.sub_relations.with_log(self.undo_log)
340 /// Returns a range of the type variables created during the snapshot.
341 pub fn vars_since_snapshot(
344 ) -> (Range<TyVid>, Vec<TypeVariableOrigin>) {
345 let range = TyVid::from_usize(value_count)..TyVid::from_usize(self.num_vars());
347 range.start..range.end,
348 (range.start.as_usize()..range.end.as_usize())
349 .map(|index| self.storage.values.get(index).origin)
354 /// Returns indices of all variables that are not yet
356 pub fn unsolved_variables(&mut self) -> Vec<ty::TyVid> {
357 (0..self.storage.values.len())
359 let vid = ty::TyVid::from_usize(i);
360 match self.probe(vid) {
361 TypeVariableValue::Unknown { .. } => Some(vid),
362 TypeVariableValue::Known { .. } => None,
369 impl sv::SnapshotVecDelegate for Delegate {
370 type Value = TypeVariableData;
371 type Undo = Instantiate;
373 fn reverse(_values: &mut Vec<TypeVariableData>, _action: Instantiate) {
374 // We don't actually have to *do* anything to reverse an
375 // instantiation; the value for a variable is stored in the
376 // `eq_relations` and hence its rollback code will handle
377 // it. In fact, we could *almost* just remove the
378 // `SnapshotVec` entirely, except that we would have to
379 // reproduce *some* of its logic, since we want to know which
380 // type variables have been instantiated since the snapshot
381 // was started, so we can implement `types_escaping_snapshot`.
383 // (If we extended the `UnificationTable` to let us see which
384 // values have been unified and so forth, that might also
389 ///////////////////////////////////////////////////////////////////////////
391 /// These structs (a newtyped TyVid) are used as the unification key
392 /// for the `eq_relations`; they carry a `TypeVariableValue` along
394 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
395 pub(crate) struct TyVidEqKey<'tcx> {
398 // in the table, we map each ty-vid to one of these:
399 phantom: PhantomData<TypeVariableValue<'tcx>>,
402 impl<'tcx> From<ty::TyVid> for TyVidEqKey<'tcx> {
403 #[inline] // make this function eligible for inlining - it is quite hot.
404 fn from(vid: ty::TyVid) -> Self {
405 TyVidEqKey { vid, phantom: PhantomData }
409 impl<'tcx> ut::UnifyKey for TyVidEqKey<'tcx> {
410 type Value = TypeVariableValue<'tcx>;
412 fn index(&self) -> u32 {
415 fn from_index(i: u32) -> Self {
416 TyVidEqKey::from(ty::TyVid::from_u32(i))
418 fn tag() -> &'static str {
423 impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> {
424 type Error = ut::NoError;
426 fn unify_values(value1: &Self, value2: &Self) -> Result<Self, ut::NoError> {
427 match (value1, value2) {
428 // We never equate two type variables, both of which
429 // have known types. Instead, we recursively equate
431 (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => {
432 bug!("equating two type variables, both of which have known types")
435 // If one side is known, prefer that one.
436 (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1),
437 (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2),
439 // If both sides are *unknown*, it hardly matters, does it?
441 &TypeVariableValue::Unknown { universe: universe1 },
442 &TypeVariableValue::Unknown { universe: universe2 },
444 // If we unify two unbound variables, ?T and ?U, then whatever
445 // value they wind up taking (which must be the same value) must
446 // be nameable by both universes. Therefore, the resulting
447 // universe is the minimum of the two universes, because that is
448 // the one which contains the fewest names in scope.
449 let universe = cmp::min(universe1, universe2);
450 Ok(TypeVariableValue::Unknown { universe })