1 use crate::ty::{self, Ty, TyVid};
2 use rustc_hir::def_id::DefId;
3 use rustc_span::symbol::Symbol;
6 use rustc_data_structures::snapshot_vec as sv;
7 use rustc_data_structures::unify as ut;
9 use std::marker::PhantomData;
13 pub struct TypeVariableTable<'tcx> {
14 values: sv::SnapshotVec<Delegate>,
16 /// Two variables are unified in `eq_relations` when we have a
17 /// constraint `?X == ?Y`. This table also stores, for each key,
19 eq_relations: ut::UnificationTable<ut::InPlace<TyVidEqKey<'tcx>>>,
21 /// Two variables are unified in `sub_relations` when we have a
22 /// constraint `?X <: ?Y` *or* a constraint `?Y <: ?X`. This second
23 /// table exists only to help with the occurs check. In particular,
24 /// we want to report constraints like these as an occurs check
30 /// This works because `?1` and `?3` are unified in the
31 /// `sub_relations` relation (not in `eq_relations`). Then when we
32 /// process the `Box<?3> <: ?1` constraint, we do an occurs check
33 /// on `Box<?3>` and find a potential cycle.
35 /// This is reasonable because, in Rust, subtypes have the same
36 /// "skeleton" and hence there is no possible type such that
37 /// (e.g.) `Box<?3> <: ?3` for any `?3`.
38 sub_relations: ut::UnificationTable<ut::InPlace<ty::TyVid>>,
41 #[derive(Copy, Clone, Debug)]
42 pub struct TypeVariableOrigin {
43 pub kind: TypeVariableOriginKind,
47 /// Reasons to create a type inference variable
48 #[derive(Copy, Clone, Debug)]
49 pub enum TypeVariableOriginKind {
51 NormalizeProjectionType,
53 TypeParameterDefinition(Symbol, Option<DefId>),
55 /// One of the upvars or closure kind parameters in a `ClosureSubsts`
56 /// (before it has been determined).
58 SubstitutionPlaceholder,
65 struct TypeVariableData {
66 origin: TypeVariableOrigin,
70 #[derive(Copy, Clone, Debug)]
71 pub enum TypeVariableValue<'tcx> {
72 Known { value: Ty<'tcx> },
73 Unknown { universe: ty::UniverseIndex },
76 impl<'tcx> TypeVariableValue<'tcx> {
77 /// If this value is known, returns the type it is known to be.
78 /// Otherwise, `None`.
79 pub fn known(&self) -> Option<Ty<'tcx>> {
81 TypeVariableValue::Unknown { .. } => None,
82 TypeVariableValue::Known { value } => Some(value),
86 pub fn is_unknown(&self) -> bool {
88 TypeVariableValue::Unknown { .. } => true,
89 TypeVariableValue::Known { .. } => false,
94 pub struct Snapshot<'tcx> {
95 snapshot: sv::Snapshot,
96 eq_snapshot: ut::Snapshot<ut::InPlace<TyVidEqKey<'tcx>>>,
97 sub_snapshot: ut::Snapshot<ut::InPlace<ty::TyVid>>,
106 impl<'tcx> TypeVariableTable<'tcx> {
107 pub fn new() -> TypeVariableTable<'tcx> {
109 values: sv::SnapshotVec::new(),
110 eq_relations: ut::UnificationTable::new(),
111 sub_relations: ut::UnificationTable::new(),
115 /// Returns the diverges flag given when `vid` was created.
117 /// Note that this function does not return care whether
118 /// `vid` has been unified with something else or not.
119 pub fn var_diverges(&self, vid: ty::TyVid) -> bool {
120 self.values.get(vid.index as usize).diverging
123 /// Returns the origin that was given when `vid` was created.
125 /// Note that this function does not return care whether
126 /// `vid` has been unified with something else or not.
127 pub fn var_origin(&self, vid: ty::TyVid) -> &TypeVariableOrigin {
128 &self.values.get(vid.index as usize).origin
131 /// Records that `a == b`, depending on `dir`.
133 /// Precondition: neither `a` nor `b` are known.
134 pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) {
135 debug_assert!(self.probe(a).is_unknown());
136 debug_assert!(self.probe(b).is_unknown());
137 self.eq_relations.union(a, b);
138 self.sub_relations.union(a, b);
141 /// Records that `a <: b`, depending on `dir`.
143 /// Precondition: neither `a` nor `b` are known.
144 pub fn sub(&mut self, a: ty::TyVid, b: ty::TyVid) {
145 debug_assert!(self.probe(a).is_unknown());
146 debug_assert!(self.probe(b).is_unknown());
147 self.sub_relations.union(a, b);
150 /// Instantiates `vid` with the type `ty`.
152 /// Precondition: `vid` must not have been previously instantiated.
153 pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) {
154 let vid = self.root_var(vid);
155 debug_assert!(self.probe(vid).is_unknown());
157 self.eq_relations.probe_value(vid).is_unknown(),
158 "instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}",
161 self.eq_relations.probe_value(vid)
163 self.eq_relations.union_value(vid, TypeVariableValue::Known { value: ty });
165 // Hack: we only need this so that `types_escaping_snapshot`
166 // can see what has been unified; see the Delegate impl for
168 self.values.record(Instantiate { vid });
171 /// Creates a new type variable.
173 /// - `diverging`: indicates if this is a "diverging" type
174 /// variable, e.g., one created as the type of a `return`
175 /// expression. The code in this module doesn't care if a
176 /// variable is diverging, but the main Rust type-checker will
177 /// sometimes "unify" such variables with the `!` or `()` types.
178 /// - `origin`: indicates *why* the type variable was created.
179 /// The code in this module doesn't care, but it can be useful
180 /// for improving error messages.
183 universe: ty::UniverseIndex,
185 origin: TypeVariableOrigin,
187 let eq_key = self.eq_relations.new_key(TypeVariableValue::Unknown { universe });
189 let sub_key = self.sub_relations.new_key(());
190 assert_eq!(eq_key.vid, sub_key);
192 let index = self.values.push(TypeVariableData { origin, diverging });
193 assert_eq!(eq_key.vid.index, index as u32);
196 "new_var(index={:?}, universe={:?}, diverging={:?}, origin={:?}",
197 eq_key.vid, universe, diverging, origin,
203 /// Returns the number of type variables created thus far.
204 pub fn num_vars(&self) -> usize {
208 /// Returns the "root" variable of `vid` in the `eq_relations`
209 /// equivalence table. All type variables that have been equated
210 /// will yield the same root variable (per the union-find
211 /// algorithm), so `root_var(a) == root_var(b)` implies that `a ==
212 /// b` (transitively).
213 pub fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
214 self.eq_relations.find(vid).vid
217 /// Returns the "root" variable of `vid` in the `sub_relations`
218 /// equivalence table. All type variables that have been are
219 /// related via equality or subtyping will yield the same root
220 /// variable (per the union-find algorithm), so `sub_root_var(a)
221 /// == sub_root_var(b)` implies that:
223 /// exists X. (a <: X || X <: a) && (b <: X || X <: b)
224 pub fn sub_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
225 self.sub_relations.find(vid)
228 /// Returns `true` if `a` and `b` have same "sub-root" (i.e., exists some
229 /// type X such that `forall i in {a, b}. (i <: X || X <: i)`.
230 pub fn sub_unified(&mut self, a: ty::TyVid, b: ty::TyVid) -> bool {
231 self.sub_root_var(a) == self.sub_root_var(b)
234 /// Retrieves the type to which `vid` has been instantiated, if
236 pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
237 self.inlined_probe(vid)
240 /// An always-inlined variant of `probe`, for very hot call sites.
242 pub fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
243 self.eq_relations.inlined_probe_value(vid)
246 /// If `t` is a type-inference variable, and it has been
247 /// instantiated, then return the with which it was
248 /// instantiated. Otherwise, returns `t`.
249 pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
251 ty::Infer(ty::TyVar(v)) => match self.probe(v) {
252 TypeVariableValue::Unknown { .. } => t,
253 TypeVariableValue::Known { value } => value,
259 /// Creates a snapshot of the type variable state. This snapshot
260 /// must later be committed (`commit()`) or rolled back
261 /// (`rollback_to()`). Nested snapshots are permitted, but must
262 /// be processed in a stack-like fashion.
263 pub fn snapshot(&mut self) -> Snapshot<'tcx> {
265 snapshot: self.values.start_snapshot(),
266 eq_snapshot: self.eq_relations.snapshot(),
267 sub_snapshot: self.sub_relations.snapshot(),
271 /// Undoes all changes since the snapshot was created. Any
272 /// snapshots created since that point must already have been
273 /// committed or rolled back.
274 pub fn rollback_to(&mut self, s: Snapshot<'tcx>) {
275 debug!("rollback_to{:?}", {
276 for action in self.values.actions_since_snapshot(&s.snapshot) {
277 if let sv::UndoLog::NewElem(index) = *action {
278 debug!("inference variable _#{}t popped", index)
283 let Snapshot { snapshot, eq_snapshot, sub_snapshot } = s;
284 self.values.rollback_to(snapshot);
285 self.eq_relations.rollback_to(eq_snapshot);
286 self.sub_relations.rollback_to(sub_snapshot);
289 /// Commits all changes since the snapshot was created, making
290 /// them permanent (unless this snapshot was created within
291 /// another snapshot). Any snapshots created since that point
292 /// must already have been committed or rolled back.
293 pub fn commit(&mut self, s: Snapshot<'tcx>) {
294 let Snapshot { snapshot, eq_snapshot, sub_snapshot } = s;
295 self.values.commit(snapshot);
296 self.eq_relations.commit(eq_snapshot);
297 self.sub_relations.commit(sub_snapshot);
300 /// Returns a range of the type variables created during the snapshot.
301 pub fn vars_since_snapshot(
304 ) -> (Range<TyVid>, Vec<TypeVariableOrigin>) {
305 let range = self.eq_relations.vars_since_snapshot(&s.eq_snapshot);
307 range.start.vid..range.end.vid,
308 (range.start.vid.index..range.end.vid.index)
309 .map(|index| self.values.get(index as usize).origin.clone())
314 /// Finds the set of type variables that existed *before* `s`
315 /// but which have only been unified since `s` started, and
316 /// return the types with which they were unified. So if we had
317 /// a type variable `V0`, then we started the snapshot, then we
318 /// created a type variable `V1`, unified `V0` with `T0`, and
319 /// unified `V1` with `T1`, this function would return `{T0}`.
320 pub fn types_escaping_snapshot(&mut self, s: &Snapshot<'tcx>) -> Vec<Ty<'tcx>> {
321 let mut new_elem_threshold = u32::MAX;
322 let mut escaping_types = Vec::new();
323 let actions_since_snapshot = self.values.actions_since_snapshot(&s.snapshot);
324 debug!("actions_since_snapshot.len() = {}", actions_since_snapshot.len());
325 for action in actions_since_snapshot {
327 sv::UndoLog::NewElem(index) => {
328 // if any new variables were created during the
329 // snapshot, remember the lower index (which will
330 // always be the first one we see). Note that this
331 // action must precede those variables being
333 new_elem_threshold = cmp::min(new_elem_threshold, index as u32);
334 debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold);
337 sv::UndoLog::Other(Instantiate { vid, .. }) => {
338 if vid.index < new_elem_threshold {
339 // quick check to see if this variable was
340 // created since the snapshot started or not.
341 let escaping_type = match self.eq_relations.probe_value(vid) {
342 TypeVariableValue::Unknown { .. } => bug!(),
343 TypeVariableValue::Known { value } => value,
345 escaping_types.push(escaping_type);
347 debug!("SpecifyVar({:?}) new_elem_threshold={}", vid, new_elem_threshold);
357 /// Returns indices of all variables that are not yet
359 pub fn unsolved_variables(&mut self) -> Vec<ty::TyVid> {
360 (0..self.values.len())
362 let vid = ty::TyVid { index: i as u32 };
363 match self.probe(vid) {
364 TypeVariableValue::Unknown { .. } => Some(vid),
365 TypeVariableValue::Known { .. } => None,
372 impl sv::SnapshotVecDelegate for Delegate {
373 type Value = TypeVariableData;
374 type Undo = Instantiate;
376 fn reverse(_values: &mut Vec<TypeVariableData>, _action: Instantiate) {
377 // We don't actually have to *do* anything to reverse an
378 // instantiation; the value for a variable is stored in the
379 // `eq_relations` and hence its rollback code will handle
380 // it. In fact, we could *almost* just remove the
381 // `SnapshotVec` entirely, except that we would have to
382 // reproduce *some* of its logic, since we want to know which
383 // type variables have been instantiated since the snapshot
384 // was started, so we can implement `types_escaping_snapshot`.
386 // (If we extended the `UnificationTable` to let us see which
387 // values have been unified and so forth, that might also
392 ///////////////////////////////////////////////////////////////////////////
394 /// These structs (a newtyped TyVid) are used as the unification key
395 /// for the `eq_relations`; they carry a `TypeVariableValue` along
397 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
398 struct TyVidEqKey<'tcx> {
401 // in the table, we map each ty-vid to one of these:
402 phantom: PhantomData<TypeVariableValue<'tcx>>,
405 impl<'tcx> From<ty::TyVid> for TyVidEqKey<'tcx> {
406 fn from(vid: ty::TyVid) -> Self {
407 TyVidEqKey { vid, phantom: PhantomData }
411 impl<'tcx> ut::UnifyKey for TyVidEqKey<'tcx> {
412 type Value = TypeVariableValue<'tcx>;
413 fn index(&self) -> u32 {
416 fn from_index(i: u32) -> Self {
417 TyVidEqKey::from(ty::TyVid { index: i })
419 fn tag() -> &'static str {
424 impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> {
425 type Error = ut::NoError;
427 fn unify_values(value1: &Self, value2: &Self) -> Result<Self, ut::NoError> {
428 match (value1, value2) {
429 // We never equate two type variables, both of which
430 // have known types. Instead, we recursively equate
432 (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => {
433 bug!("equating two type variables, both of which have known types")
436 // If one side is known, prefer that one.
437 (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1),
438 (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2),
440 // If both sides are *unknown*, it hardly matters, does it?
442 &TypeVariableValue::Unknown { universe: universe1 },
443 &TypeVariableValue::Unknown { universe: universe2 },
445 // If we unify two unbound variables, ?T and ?U, then whatever
446 // value they wind up taking (which must be the same value) must
447 // be nameable by both universes. Therefore, the resulting
448 // universe is the minimum of the two universes, because that is
449 // the one which contains the fewest names in scope.
450 let universe = cmp::min(universe1, universe2);
451 Ok(TypeVariableValue::Unknown { universe })
457 /// Raw `TyVid` are used as the unification key for `sub_relations`;
458 /// they carry no values.
459 impl ut::UnifyKey for ty::TyVid {
461 fn index(&self) -> u32 {
464 fn from_index(i: u32) -> ty::TyVid {
465 ty::TyVid { index: i }
467 fn tag() -> &'static str {