1 use syntax::symbol::InternedString;
3 use crate::ty::{self, Ty};
6 use std::marker::PhantomData;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::snapshot_vec as sv;
10 use rustc_data_structures::unify as ut;
12 pub struct TypeVariableTable<'tcx> {
13 values: sv::SnapshotVec<Delegate>,
15 /// Two variables are unified in `eq_relations` when we have a
16 /// constraint `?X == ?Y`. This table also stores, for each key,
18 eq_relations: ut::UnificationTable<ut::InPlace<TyVidEqKey<'tcx>>>,
20 /// Two variables are unified in `eq_relations` when we have a
21 /// constraint `?X <: ?Y` *or* a constraint `?Y <: ?X`. This second
22 /// table exists only to help with the occurs check. In particular,
23 /// we want to report constraints like these as an occurs check
29 /// This works because `?1` and `?3` are unified in the
30 /// `sub_relations` relation (not in `eq_relations`). Then when we
31 /// process the `Box<?3> <: ?1` constraint, we do an occurs check
32 /// on `Box<?3>` and find a potential cycle.
34 /// This is reasonable because, in Rust, subtypes have the same
35 /// "skeleton" and hence there is no possible type such that
36 /// (e.g.) `Box<?3> <: ?3` for any `?3`.
37 sub_relations: ut::UnificationTable<ut::InPlace<ty::TyVid>>,
40 /// Reasons to create a type inference variable
41 #[derive(Copy, Clone, Debug)]
42 pub enum TypeVariableOrigin {
44 NormalizeProjectionType(Span),
46 TypeParameterDefinition(Span, InternedString),
48 /// one of the upvars or closure kind parameters in a `ClosureSubsts`
49 /// (before it has been determined)
50 ClosureSynthetic(Span),
51 SubstitutionPlaceholder(Span),
55 DivergingBlockExpr(Span),
57 LatticeVariable(Span),
58 Generalized(ty::TyVid),
61 pub type TypeVariableMap = FxHashMap<ty::TyVid, TypeVariableOrigin>;
63 struct TypeVariableData {
64 origin: TypeVariableOrigin,
68 #[derive(Copy, Clone, Debug)]
69 pub enum TypeVariableValue<'tcx> {
70 Known { value: Ty<'tcx> },
71 Unknown { universe: ty::UniverseIndex },
74 impl<'tcx> TypeVariableValue<'tcx> {
75 /// If this value is known, returns the type it is known to be.
76 /// Otherwise, `None`.
77 pub fn known(&self) -> Option<Ty<'tcx>> {
79 TypeVariableValue::Unknown { .. } => None,
80 TypeVariableValue::Known { value } => Some(value),
84 pub fn is_unknown(&self) -> bool {
86 TypeVariableValue::Unknown { .. } => true,
87 TypeVariableValue::Known { .. } => false,
92 pub struct Snapshot<'tcx> {
93 snapshot: sv::Snapshot,
94 eq_snapshot: ut::Snapshot<ut::InPlace<TyVidEqKey<'tcx>>>,
95 sub_snapshot: ut::Snapshot<ut::InPlace<ty::TyVid>>,
104 impl<'tcx> TypeVariableTable<'tcx> {
105 pub fn new() -> TypeVariableTable<'tcx> {
107 values: sv::SnapshotVec::new(),
108 eq_relations: ut::UnificationTable::new(),
109 sub_relations: ut::UnificationTable::new(),
113 /// Returns the diverges flag given when `vid` was created.
115 /// Note that this function does not return care whether
116 /// `vid` has been unified with something else or not.
117 pub fn var_diverges<'a>(&'a self, vid: ty::TyVid) -> bool {
118 self.values.get(vid.index as usize).diverging
121 /// Returns the origin that was given when `vid` was created.
123 /// Note that this function does not return care whether
124 /// `vid` has been unified with something else or not.
125 pub fn var_origin(&self, vid: ty::TyVid) -> &TypeVariableOrigin {
126 &self.values.get(vid.index as usize).origin
129 /// Records that `a == b`, depending on `dir`.
131 /// Precondition: neither `a` nor `b` are known.
132 pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) {
133 debug_assert!(self.probe(a).is_unknown());
134 debug_assert!(self.probe(b).is_unknown());
135 self.eq_relations.union(a, b);
136 self.sub_relations.union(a, b);
139 /// Records that `a <: b`, depending on `dir`.
141 /// Precondition: neither `a` nor `b` are known.
142 pub fn sub(&mut self, a: ty::TyVid, b: ty::TyVid) {
143 debug_assert!(self.probe(a).is_unknown());
144 debug_assert!(self.probe(b).is_unknown());
145 self.sub_relations.union(a, b);
148 /// Instantiates `vid` with the type `ty`.
150 /// Precondition: `vid` must not have been previously instantiated.
151 pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) {
152 let vid = self.root_var(vid);
153 debug_assert!(self.probe(vid).is_unknown());
154 debug_assert!(self.eq_relations.probe_value(vid).is_unknown(),
155 "instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}",
156 vid, ty, self.eq_relations.probe_value(vid));
157 self.eq_relations.union_value(vid, TypeVariableValue::Known { value: ty });
159 // Hack: we only need this so that `types_escaping_snapshot`
160 // can see what has been unified; see the Delegate impl for
162 self.values.record(Instantiate { vid });
165 /// Creates a new type variable.
167 /// - `diverging`: indicates if this is a "diverging" type
168 /// variable, e.g., one created as the type of a `return`
169 /// expression. The code in this module doesn't care if a
170 /// variable is diverging, but the main Rust type-checker will
171 /// sometimes "unify" such variables with the `!` or `()` types.
172 /// - `origin`: indicates *why* the type variable was created.
173 /// The code in this module doesn't care, but it can be useful
174 /// for improving error messages.
175 pub fn new_var(&mut self,
176 universe: ty::UniverseIndex,
178 origin: TypeVariableOrigin)
180 let eq_key = self.eq_relations.new_key(TypeVariableValue::Unknown { universe });
182 let sub_key = self.sub_relations.new_key(());
183 assert_eq!(eq_key.vid, sub_key);
185 let index = self.values.push(TypeVariableData {
189 assert_eq!(eq_key.vid.index, index as u32);
191 debug!("new_var(index={:?}, diverging={:?}, origin={:?}", eq_key.vid, diverging, origin);
196 /// Returns the number of type variables created thus far.
197 pub fn num_vars(&self) -> usize {
201 /// Returns the "root" variable of `vid` in the `eq_relations`
202 /// equivalence table. All type variables that have been equated
203 /// will yield the same root variable (per the union-find
204 /// algorithm), so `root_var(a) == root_var(b)` implies that `a ==
205 /// b` (transitively).
206 pub fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
207 self.eq_relations.find(vid).vid
210 /// Returns the "root" variable of `vid` in the `sub_relations`
211 /// equivalence table. All type variables that have been are
212 /// related via equality or subtyping will yield the same root
213 /// variable (per the union-find algorithm), so `sub_root_var(a)
214 /// == sub_root_var(b)` implies that:
216 /// exists X. (a <: X || X <: a) && (b <: X || X <: b)
217 pub fn sub_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
218 self.sub_relations.find(vid)
221 /// True if `a` and `b` have same "sub-root" (i.e., exists some
222 /// type X such that `forall i in {a, b}. (i <: X || X <: i)`.
223 pub fn sub_unified(&mut self, a: ty::TyVid, b: ty::TyVid) -> bool {
224 self.sub_root_var(a) == self.sub_root_var(b)
227 /// Retrieves the type to which `vid` has been instantiated, if
229 pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
230 self.eq_relations.probe_value(vid)
233 /// If `t` is a type-inference variable, and it has been
234 /// instantiated, then return the with which it was
235 /// instantiated. Otherwise, returns `t`.
236 pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
238 ty::Infer(ty::TyVar(v)) => {
239 match self.probe(v) {
240 TypeVariableValue::Unknown { .. } => t,
241 TypeVariableValue::Known { value } => value,
248 /// Creates a snapshot of the type variable state. This snapshot
249 /// must later be committed (`commit()`) or rolled back
250 /// (`rollback_to()`). Nested snapshots are permitted, but must
251 /// be processed in a stack-like fashion.
252 pub fn snapshot(&mut self) -> Snapshot<'tcx> {
254 snapshot: self.values.start_snapshot(),
255 eq_snapshot: self.eq_relations.snapshot(),
256 sub_snapshot: self.sub_relations.snapshot(),
260 /// Undoes all changes since the snapshot was created. Any
261 /// snapshots created since that point must already have been
262 /// committed or rolled back.
263 pub fn rollback_to(&mut self, s: Snapshot<'tcx>) {
264 debug!("rollback_to{:?}", {
265 for action in self.values.actions_since_snapshot(&s.snapshot) {
266 if let sv::UndoLog::NewElem(index) = *action {
267 debug!("inference variable _#{}t popped", index)
272 let Snapshot { snapshot, eq_snapshot, sub_snapshot } = s;
273 self.values.rollback_to(snapshot);
274 self.eq_relations.rollback_to(eq_snapshot);
275 self.sub_relations.rollback_to(sub_snapshot);
278 /// Commits all changes since the snapshot was created, making
279 /// them permanent (unless this snapshot was created within
280 /// another snapshot). Any snapshots created since that point
281 /// must already have been committed or rolled back.
282 pub fn commit(&mut self, s: Snapshot<'tcx>) {
283 let Snapshot { snapshot, eq_snapshot, sub_snapshot } = s;
284 self.values.commit(snapshot);
285 self.eq_relations.commit(eq_snapshot);
286 self.sub_relations.commit(sub_snapshot);
289 /// Returns a map `{V1 -> V2}`, where the keys `{V1}` are
290 /// ty-variables created during the snapshot, and the values
291 /// `{V2}` are the root variables that they were unified with,
292 /// along with their origin.
293 pub fn types_created_since_snapshot(&mut self, s: &Snapshot<'tcx>) -> TypeVariableMap {
294 let actions_since_snapshot = self.values.actions_since_snapshot(&s.snapshot);
296 actions_since_snapshot
298 .filter_map(|action| match action {
299 &sv::UndoLog::NewElem(index) => Some(ty::TyVid { index: index as u32 }),
303 let origin = self.values.get(vid.index as usize).origin.clone();
309 /// Find the set of type variables that existed *before* `s`
310 /// but which have only been unified since `s` started, and
311 /// return the types with which they were unified. So if we had
312 /// a type variable `V0`, then we started the snapshot, then we
313 /// created a type variable `V1`, unified `V0` with `T0`, and
314 /// unified `V1` with `T1`, this function would return `{T0}`.
315 pub fn types_escaping_snapshot(&mut self, s: &Snapshot<'tcx>) -> Vec<Ty<'tcx>> {
316 let mut new_elem_threshold = u32::MAX;
317 let mut escaping_types = Vec::new();
318 let actions_since_snapshot = self.values.actions_since_snapshot(&s.snapshot);
319 debug!("actions_since_snapshot.len() = {}", actions_since_snapshot.len());
320 for action in actions_since_snapshot {
322 sv::UndoLog::NewElem(index) => {
323 // if any new variables were created during the
324 // snapshot, remember the lower index (which will
325 // always be the first one we see). Note that this
326 // action must precede those variables being
328 new_elem_threshold = cmp::min(new_elem_threshold, index as u32);
329 debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold);
332 sv::UndoLog::Other(Instantiate { vid, .. }) => {
333 if vid.index < new_elem_threshold {
334 // quick check to see if this variable was
335 // created since the snapshot started or not.
336 let escaping_type = match self.eq_relations.probe_value(vid) {
337 TypeVariableValue::Unknown { .. } => bug!(),
338 TypeVariableValue::Known { value } => value,
340 escaping_types.push(escaping_type);
342 debug!("SpecifyVar({:?}) new_elem_threshold={}", vid, new_elem_threshold);
352 /// Returns indices of all variables that are not yet
354 pub fn unsolved_variables(&mut self) -> Vec<ty::TyVid> {
355 (0..self.values.len())
357 let vid = ty::TyVid { index: i as u32 };
358 match self.probe(vid) {
359 TypeVariableValue::Unknown { .. } => Some(vid),
360 TypeVariableValue::Known { .. } => None,
367 impl sv::SnapshotVecDelegate for Delegate {
368 type Value = TypeVariableData;
369 type Undo = Instantiate;
371 fn reverse(_values: &mut Vec<TypeVariableData>, _action: Instantiate) {
372 // We don't actually have to *do* anything to reverse an
373 // instanation; the value for a variable is stored in the
374 // `eq_relations` and hence its rollback code will handle
375 // it. In fact, we could *almost* just remove the
376 // `SnapshotVec` entirely, except that we would have to
377 // reproduce *some* of its logic, since we want to know which
378 // type variables have been instantiated since the snapshot
379 // was started, so we can implement `types_escaping_snapshot`.
381 // (If we extended the `UnificationTable` to let us see which
382 // values have been unified and so forth, that might also
387 ///////////////////////////////////////////////////////////////////////////
389 /// These structs (a newtyped TyVid) are used as the unification key
390 /// for the `eq_relations`; they carry a `TypeVariableValue` along
392 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
393 struct TyVidEqKey<'tcx> {
396 // in the table, we map each ty-vid to one of these:
397 phantom: PhantomData<TypeVariableValue<'tcx>>,
400 impl<'tcx> From<ty::TyVid> for TyVidEqKey<'tcx> {
401 fn from(vid: ty::TyVid) -> Self {
402 TyVidEqKey { vid, phantom: PhantomData }
406 impl<'tcx> ut::UnifyKey for TyVidEqKey<'tcx> {
407 type Value = TypeVariableValue<'tcx>;
408 fn index(&self) -> u32 { self.vid.index }
409 fn from_index(i: u32) -> Self { TyVidEqKey::from(ty::TyVid { index: i }) }
410 fn tag() -> &'static str { "TyVidEqKey" }
413 impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> {
414 type Error = ut::NoError;
416 fn unify_values(value1: &Self, value2: &Self) -> Result<Self, ut::NoError> {
417 match (value1, value2) {
418 // We never equate two type variables, both of which
419 // have known types. Instead, we recursively equate
421 (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => {
422 bug!("equating two type variables, both of which have known types")
425 // If one side is known, prefer that one.
426 (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1),
427 (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2),
429 // If both sides are *unknown*, it hardly matters, does it?
430 (&TypeVariableValue::Unknown { universe: universe1 },
431 &TypeVariableValue::Unknown { universe: universe2 }) => {
432 // If we unify two unbound variables, ?T and ?U, then whatever
433 // value they wind up taking (which must be the same value) must
434 // be nameable by both universes. Therefore, the resulting
435 // universe is the minimum of the two universes, because that is
436 // the one which contains the fewest names in scope.
437 let universe = cmp::min(universe1, universe2);
438 Ok(TypeVariableValue::Unknown { universe })
444 /// Raw `TyVid` are used as the unification key for `sub_relations`;
445 /// they carry no values.
446 impl ut::UnifyKey for ty::TyVid {
448 fn index(&self) -> u32 { self.index }
449 fn from_index(i: u32) -> ty::TyVid { ty::TyVid { index: i } }
450 fn tag() -> &'static str { "TyVid" }