]> git.lizzy.rs Git - rust.git/blob - src/librustc_infer/infer/type_variable.rs
1de820cdb6209be8b403974d8cbc928d721b74b2
[rust.git] / src / librustc_infer / infer / type_variable.rs
1 use rustc_hir::def_id::DefId;
2 use rustc_middle::ty::{self, Ty, TyVid};
3 use rustc_span::symbol::Symbol;
4 use rustc_span::Span;
5
6 use rustc_data_structures::snapshot_vec as sv;
7 use rustc_data_structures::unify as ut;
8 use std::cmp;
9 use std::marker::PhantomData;
10 use std::ops::Range;
11
12 pub struct TypeVariableTable<'tcx> {
13     values: sv::SnapshotVec<Delegate>,
14
15     /// Two variables are unified in `eq_relations` when we have a
16     /// constraint `?X == ?Y`. This table also stores, for each key,
17     /// the known value.
18     eq_relations: ut::UnificationTable<ut::InPlace<TyVidEqKey<'tcx>>>,
19
20     /// Two variables are unified in `sub_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
24     /// violation:
25     ///
26     ///     ?1 <: ?3
27     ///     Box<?3> <: ?1
28     ///
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.
33     ///
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>>,
38 }
39
40 #[derive(Copy, Clone, Debug)]
41 pub struct TypeVariableOrigin {
42     pub kind: TypeVariableOriginKind,
43     pub span: Span,
44 }
45
46 /// Reasons to create a type inference variable
47 #[derive(Copy, Clone, Debug)]
48 pub enum TypeVariableOriginKind {
49     MiscVariable,
50     NormalizeProjectionType,
51     TypeInference,
52     TypeParameterDefinition(Symbol, Option<DefId>),
53
54     /// One of the upvars or closure kind parameters in a `ClosureSubsts`
55     /// (before it has been determined).
56     // FIXME(eddyb) distinguish upvar inference variables from the rest.
57     ClosureSynthetic,
58     SubstitutionPlaceholder,
59     AutoDeref,
60     AdjustmentType,
61     DivergingFn,
62     LatticeVariable,
63 }
64
65 struct TypeVariableData {
66     origin: TypeVariableOrigin,
67     diverging: bool,
68 }
69
70 #[derive(Copy, Clone, Debug)]
71 pub enum TypeVariableValue<'tcx> {
72     Known { value: Ty<'tcx> },
73     Unknown { universe: ty::UniverseIndex },
74 }
75
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>> {
80         match *self {
81             TypeVariableValue::Unknown { .. } => None,
82             TypeVariableValue::Known { value } => Some(value),
83         }
84     }
85
86     pub fn is_unknown(&self) -> bool {
87         match *self {
88             TypeVariableValue::Unknown { .. } => true,
89             TypeVariableValue::Known { .. } => false,
90         }
91     }
92 }
93
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>>,
98 }
99
100 struct Instantiate {
101     vid: ty::TyVid,
102 }
103
104 struct Delegate;
105
106 impl<'tcx> TypeVariableTable<'tcx> {
107     pub fn new() -> TypeVariableTable<'tcx> {
108         TypeVariableTable {
109             values: sv::SnapshotVec::new(),
110             eq_relations: ut::UnificationTable::new(),
111             sub_relations: ut::UnificationTable::new(),
112         }
113     }
114
115     /// Returns the diverges flag given when `vid` was created.
116     ///
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
121     }
122
123     /// Returns the origin that was given when `vid` was created.
124     ///
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
129     }
130
131     /// Records that `a == b`, depending on `dir`.
132     ///
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);
139     }
140
141     /// Records that `a <: b`, depending on `dir`.
142     ///
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);
148     }
149
150     /// Instantiates `vid` with the type `ty`.
151     ///
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());
156         debug_assert!(
157             self.eq_relations.probe_value(vid).is_unknown(),
158             "instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}",
159             vid,
160             ty,
161             self.eq_relations.probe_value(vid)
162         );
163         self.eq_relations.union_value(vid, TypeVariableValue::Known { value: ty });
164
165         // Hack: we only need this so that `types_escaping_snapshot`
166         // can see what has been unified; see the Delegate impl for
167         // more details.
168         self.values.record(Instantiate { vid });
169     }
170
171     /// Creates a new type variable.
172     ///
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.
181     pub fn new_var(
182         &mut self,
183         universe: ty::UniverseIndex,
184         diverging: bool,
185         origin: TypeVariableOrigin,
186     ) -> ty::TyVid {
187         let eq_key = self.eq_relations.new_key(TypeVariableValue::Unknown { universe });
188
189         let sub_key = self.sub_relations.new_key(());
190         assert_eq!(eq_key.vid, sub_key);
191
192         let index = self.values.push(TypeVariableData { origin, diverging });
193         assert_eq!(eq_key.vid.index, index as u32);
194
195         debug!(
196             "new_var(index={:?}, universe={:?}, diverging={:?}, origin={:?}",
197             eq_key.vid, universe, diverging, origin,
198         );
199
200         eq_key.vid
201     }
202
203     /// Returns the number of type variables created thus far.
204     pub fn num_vars(&self) -> usize {
205         self.values.len()
206     }
207
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
215     }
216
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:
222     ///
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)
226     }
227
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)
232     }
233
234     /// Retrieves the type to which `vid` has been instantiated, if
235     /// any.
236     pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
237         self.inlined_probe(vid)
238     }
239
240     /// An always-inlined variant of `probe`, for very hot call sites.
241     #[inline(always)]
242     pub fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
243         self.eq_relations.inlined_probe_value(vid)
244     }
245
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> {
250         match t.kind {
251             ty::Infer(ty::TyVar(v)) => match self.probe(v) {
252                 TypeVariableValue::Unknown { .. } => t,
253                 TypeVariableValue::Known { value } => value,
254             },
255             _ => t,
256         }
257     }
258
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> {
264         Snapshot {
265             snapshot: self.values.start_snapshot(),
266             eq_snapshot: self.eq_relations.snapshot(),
267             sub_snapshot: self.sub_relations.snapshot(),
268         }
269     }
270
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)
279                 }
280             }
281         });
282
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);
287     }
288
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);
298     }
299
300     /// Returns a range of the type variables created during the snapshot.
301     pub fn vars_since_snapshot(
302         &mut self,
303         s: &Snapshot<'tcx>,
304     ) -> (Range<TyVid>, Vec<TypeVariableOrigin>) {
305         let range = self.eq_relations.vars_since_snapshot(&s.eq_snapshot);
306         (
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)
310                 .collect(),
311         )
312     }
313
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 {
326             match *action {
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
332                     // specified.
333                     new_elem_threshold = cmp::min(new_elem_threshold, index as u32);
334                     debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold);
335                 }
336
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,
344                         };
345                         escaping_types.push(escaping_type);
346                     }
347                     debug!("SpecifyVar({:?}) new_elem_threshold={}", vid, new_elem_threshold);
348                 }
349
350                 _ => {}
351             }
352         }
353
354         escaping_types
355     }
356
357     /// Returns indices of all variables that are not yet
358     /// instantiated.
359     pub fn unsolved_variables(&mut self) -> Vec<ty::TyVid> {
360         (0..self.values.len())
361             .filter_map(|i| {
362                 let vid = ty::TyVid { index: i as u32 };
363                 match self.probe(vid) {
364                     TypeVariableValue::Unknown { .. } => Some(vid),
365                     TypeVariableValue::Known { .. } => None,
366                 }
367             })
368             .collect()
369     }
370 }
371
372 impl sv::SnapshotVecDelegate for Delegate {
373     type Value = TypeVariableData;
374     type Undo = Instantiate;
375
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`.
385         //
386         // (If we extended the `UnificationTable` to let us see which
387         // values have been unified and so forth, that might also
388         // suffice.)
389     }
390 }
391
392 ///////////////////////////////////////////////////////////////////////////
393
394 /// These structs (a newtyped TyVid) are used as the unification key
395 /// for the `eq_relations`; they carry a `TypeVariableValue` along
396 /// with them.
397 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
398 struct TyVidEqKey<'tcx> {
399     vid: ty::TyVid,
400
401     // in the table, we map each ty-vid to one of these:
402     phantom: PhantomData<TypeVariableValue<'tcx>>,
403 }
404
405 impl<'tcx> From<ty::TyVid> for TyVidEqKey<'tcx> {
406     fn from(vid: ty::TyVid) -> Self {
407         TyVidEqKey { vid, phantom: PhantomData }
408     }
409 }
410
411 impl<'tcx> ut::UnifyKey for TyVidEqKey<'tcx> {
412     type Value = TypeVariableValue<'tcx>;
413     fn index(&self) -> u32 {
414         self.vid.index
415     }
416     fn from_index(i: u32) -> Self {
417         TyVidEqKey::from(ty::TyVid { index: i })
418     }
419     fn tag() -> &'static str {
420         "TyVidEqKey"
421     }
422 }
423
424 impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> {
425     type Error = ut::NoError;
426
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
431             // those types.
432             (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => {
433                 bug!("equating two type variables, both of which have known types")
434             }
435
436             // If one side is known, prefer that one.
437             (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1),
438             (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2),
439
440             // If both sides are *unknown*, it hardly matters, does it?
441             (
442                 &TypeVariableValue::Unknown { universe: universe1 },
443                 &TypeVariableValue::Unknown { universe: universe2 },
444             ) => {
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 })
452             }
453         }
454     }
455 }