]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/type_variable.rs
Rollup merge of #61554 - spastorino:change_visit_api, r=oli-obk
[rust.git] / src / librustc / infer / type_variable.rs
1 use syntax::symbol::InternedString;
2 use syntax_pos::Span;
3 use crate::ty::{self, Ty, TyVid};
4
5 use std::cmp;
6 use std::marker::PhantomData;
7 use std::u32;
8 use std::ops::Range;
9 use rustc_data_structures::snapshot_vec as sv;
10 use rustc_data_structures::unify as ut;
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(InternedString),
53
54     /// One of the upvars or closure kind parameters in a `ClosureSubsts`
55     /// (before it has been determined).
56     ClosureSynthetic,
57     SubstitutionPlaceholder,
58     AutoDeref,
59     AdjustmentType,
60     DivergingFn,
61     LatticeVariable,
62 }
63
64 struct TypeVariableData {
65     origin: TypeVariableOrigin,
66     diverging: bool,
67 }
68
69 #[derive(Copy, Clone, Debug)]
70 pub enum TypeVariableValue<'tcx> {
71     Known { value: Ty<'tcx> },
72     Unknown { universe: ty::UniverseIndex },
73 }
74
75 impl<'tcx> TypeVariableValue<'tcx> {
76     /// If this value is known, returns the type it is known to be.
77     /// Otherwise, `None`.
78     pub fn known(&self) -> Option<Ty<'tcx>> {
79         match *self {
80             TypeVariableValue::Unknown { .. } => None,
81             TypeVariableValue::Known { value } => Some(value),
82         }
83     }
84
85     pub fn is_unknown(&self) -> bool {
86         match *self {
87             TypeVariableValue::Unknown { .. } => true,
88             TypeVariableValue::Known { .. } => false,
89         }
90     }
91 }
92
93 pub struct Snapshot<'tcx> {
94     snapshot: sv::Snapshot,
95     eq_snapshot: ut::Snapshot<ut::InPlace<TyVidEqKey<'tcx>>>,
96     sub_snapshot: ut::Snapshot<ut::InPlace<ty::TyVid>>,
97 }
98
99 struct Instantiate {
100     vid: ty::TyVid,
101 }
102
103 struct Delegate;
104
105 impl<'tcx> TypeVariableTable<'tcx> {
106     pub fn new() -> TypeVariableTable<'tcx> {
107         TypeVariableTable {
108             values: sv::SnapshotVec::new(),
109             eq_relations: ut::UnificationTable::new(),
110             sub_relations: ut::UnificationTable::new(),
111         }
112     }
113
114     /// Returns the diverges flag given when `vid` was created.
115     ///
116     /// Note that this function does not return care whether
117     /// `vid` has been unified with something else or not.
118     pub fn var_diverges<'a>(&'a self, vid: ty::TyVid) -> bool {
119         self.values.get(vid.index as usize).diverging
120     }
121
122     /// Returns the origin that was given when `vid` was created.
123     ///
124     /// Note that this function does not return care whether
125     /// `vid` has been unified with something else or not.
126     pub fn var_origin(&self, vid: ty::TyVid) -> &TypeVariableOrigin {
127         &self.values.get(vid.index as usize).origin
128     }
129
130     /// Records that `a == b`, depending on `dir`.
131     ///
132     /// Precondition: neither `a` nor `b` are known.
133     pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) {
134         debug_assert!(self.probe(a).is_unknown());
135         debug_assert!(self.probe(b).is_unknown());
136         self.eq_relations.union(a, b);
137         self.sub_relations.union(a, b);
138     }
139
140     /// Records that `a <: b`, depending on `dir`.
141     ///
142     /// Precondition: neither `a` nor `b` are known.
143     pub fn sub(&mut self, a: ty::TyVid, b: ty::TyVid) {
144         debug_assert!(self.probe(a).is_unknown());
145         debug_assert!(self.probe(b).is_unknown());
146         self.sub_relations.union(a, b);
147     }
148
149     /// Instantiates `vid` with the type `ty`.
150     ///
151     /// Precondition: `vid` must not have been previously instantiated.
152     pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) {
153         let vid = self.root_var(vid);
154         debug_assert!(self.probe(vid).is_unknown());
155         debug_assert!(self.eq_relations.probe_value(vid).is_unknown(),
156                       "instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}",
157                       vid, ty, self.eq_relations.probe_value(vid));
158         self.eq_relations.union_value(vid, TypeVariableValue::Known { value: ty });
159
160         // Hack: we only need this so that `types_escaping_snapshot`
161         // can see what has been unified; see the Delegate impl for
162         // more details.
163         self.values.record(Instantiate { vid });
164     }
165
166     /// Creates a new type variable.
167     ///
168     /// - `diverging`: indicates if this is a "diverging" type
169     ///   variable, e.g.,  one created as the type of a `return`
170     ///   expression. The code in this module doesn't care if a
171     ///   variable is diverging, but the main Rust type-checker will
172     ///   sometimes "unify" such variables with the `!` or `()` types.
173     /// - `origin`: indicates *why* the type variable was created.
174     ///   The code in this module doesn't care, but it can be useful
175     ///   for improving error messages.
176     pub fn new_var(&mut self,
177                    universe: ty::UniverseIndex,
178                    diverging: bool,
179                    origin: TypeVariableOrigin)
180                    -> ty::TyVid {
181         let eq_key = self.eq_relations.new_key(TypeVariableValue::Unknown { universe });
182
183         let sub_key = self.sub_relations.new_key(());
184         assert_eq!(eq_key.vid, sub_key);
185
186         let index = self.values.push(TypeVariableData {
187             origin,
188             diverging,
189         });
190         assert_eq!(eq_key.vid.index, index as u32);
191
192         debug!(
193             "new_var(index={:?}, universe={:?}, diverging={:?}, origin={:?}",
194             eq_key.vid,
195             universe,
196             diverging,
197             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.eq_relations.probe_value(vid)
238     }
239
240     /// If `t` is a type-inference variable, and it has been
241     /// instantiated, then return the with which it was
242     /// instantiated. Otherwise, returns `t`.
243     pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
244         match t.sty {
245             ty::Infer(ty::TyVar(v)) => {
246                 match self.probe(v) {
247                     TypeVariableValue::Unknown { .. } => t,
248                     TypeVariableValue::Known { value } => value,
249                 }
250             }
251             _ => t,
252         }
253     }
254
255     /// Creates a snapshot of the type variable state. This snapshot
256     /// must later be committed (`commit()`) or rolled back
257     /// (`rollback_to()`). Nested snapshots are permitted, but must
258     /// be processed in a stack-like fashion.
259     pub fn snapshot(&mut self) -> Snapshot<'tcx> {
260         Snapshot {
261             snapshot: self.values.start_snapshot(),
262             eq_snapshot: self.eq_relations.snapshot(),
263             sub_snapshot: self.sub_relations.snapshot(),
264         }
265     }
266
267     /// Undoes all changes since the snapshot was created. Any
268     /// snapshots created since that point must already have been
269     /// committed or rolled back.
270     pub fn rollback_to(&mut self, s: Snapshot<'tcx>) {
271         debug!("rollback_to{:?}", {
272             for action in self.values.actions_since_snapshot(&s.snapshot) {
273                 if let sv::UndoLog::NewElem(index) = *action {
274                     debug!("inference variable _#{}t popped", index)
275                 }
276             }
277         });
278
279         let Snapshot { snapshot, eq_snapshot, sub_snapshot } = s;
280         self.values.rollback_to(snapshot);
281         self.eq_relations.rollback_to(eq_snapshot);
282         self.sub_relations.rollback_to(sub_snapshot);
283     }
284
285     /// Commits all changes since the snapshot was created, making
286     /// them permanent (unless this snapshot was created within
287     /// another snapshot). Any snapshots created since that point
288     /// must already have been committed or rolled back.
289     pub fn commit(&mut self, s: Snapshot<'tcx>) {
290         let Snapshot { snapshot, eq_snapshot, sub_snapshot } = s;
291         self.values.commit(snapshot);
292         self.eq_relations.commit(eq_snapshot);
293         self.sub_relations.commit(sub_snapshot);
294     }
295
296     /// Returns a range of the type variables created during the snapshot.
297     pub fn vars_since_snapshot(
298         &mut self,
299         s: &Snapshot<'tcx>,
300     ) -> (Range<TyVid>, Vec<TypeVariableOrigin>) {
301         let range = self.eq_relations.vars_since_snapshot(&s.eq_snapshot);
302         (range.start.vid..range.end.vid, (range.start.vid.index..range.end.vid.index).map(|index| {
303             self.values.get(index as usize).origin.clone()
304         }).collect())
305     }
306
307     /// Finds the set of type variables that existed *before* `s`
308     /// but which have only been unified since `s` started, and
309     /// return the types with which they were unified. So if we had
310     /// a type variable `V0`, then we started the snapshot, then we
311     /// created a type variable `V1`, unified `V0` with `T0`, and
312     /// unified `V1` with `T1`, this function would return `{T0}`.
313     pub fn types_escaping_snapshot(&mut self, s: &Snapshot<'tcx>) -> Vec<Ty<'tcx>> {
314         let mut new_elem_threshold = u32::MAX;
315         let mut escaping_types = Vec::new();
316         let actions_since_snapshot = self.values.actions_since_snapshot(&s.snapshot);
317         debug!("actions_since_snapshot.len() = {}", actions_since_snapshot.len());
318         for action in actions_since_snapshot {
319             match *action {
320                 sv::UndoLog::NewElem(index) => {
321                     // if any new variables were created during the
322                     // snapshot, remember the lower index (which will
323                     // always be the first one we see). Note that this
324                     // action must precede those variables being
325                     // specified.
326                     new_elem_threshold = cmp::min(new_elem_threshold, index as u32);
327                     debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold);
328                 }
329
330                 sv::UndoLog::Other(Instantiate { vid, .. }) => {
331                     if vid.index < new_elem_threshold {
332                         // quick check to see if this variable was
333                         // created since the snapshot started or not.
334                         let escaping_type = match self.eq_relations.probe_value(vid) {
335                             TypeVariableValue::Unknown { .. } => bug!(),
336                             TypeVariableValue::Known { value } => value,
337                         };
338                         escaping_types.push(escaping_type);
339                     }
340                     debug!("SpecifyVar({:?}) new_elem_threshold={}", vid, new_elem_threshold);
341                 }
342
343                 _ => { }
344             }
345         }
346
347         escaping_types
348     }
349
350     /// Returns indices of all variables that are not yet
351     /// instantiated.
352     pub fn unsolved_variables(&mut self) -> Vec<ty::TyVid> {
353         (0..self.values.len())
354             .filter_map(|i| {
355                 let vid = ty::TyVid { index: i as u32 };
356                 match self.probe(vid) {
357                     TypeVariableValue::Unknown { .. } => Some(vid),
358                     TypeVariableValue::Known { .. } => None,
359                 }
360             })
361             .collect()
362     }
363 }
364
365 impl sv::SnapshotVecDelegate for Delegate {
366     type Value = TypeVariableData;
367     type Undo = Instantiate;
368
369     fn reverse(_values: &mut Vec<TypeVariableData>, _action: Instantiate) {
370         // We don't actually have to *do* anything to reverse an
371         // instantiation; the value for a variable is stored in the
372         // `eq_relations` and hence its rollback code will handle
373         // it. In fact, we could *almost* just remove the
374         // `SnapshotVec` entirely, except that we would have to
375         // reproduce *some* of its logic, since we want to know which
376         // type variables have been instantiated since the snapshot
377         // was started, so we can implement `types_escaping_snapshot`.
378         //
379         // (If we extended the `UnificationTable` to let us see which
380         // values have been unified and so forth, that might also
381         // suffice.)
382     }
383 }
384
385 ///////////////////////////////////////////////////////////////////////////
386
387 /// These structs (a newtyped TyVid) are used as the unification key
388 /// for the `eq_relations`; they carry a `TypeVariableValue` along
389 /// with them.
390 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
391 struct TyVidEqKey<'tcx> {
392     vid: ty::TyVid,
393
394     // in the table, we map each ty-vid to one of these:
395     phantom: PhantomData<TypeVariableValue<'tcx>>,
396 }
397
398 impl<'tcx> From<ty::TyVid> for TyVidEqKey<'tcx> {
399     fn from(vid: ty::TyVid) -> Self {
400         TyVidEqKey { vid, phantom: PhantomData }
401     }
402 }
403
404 impl<'tcx> ut::UnifyKey for TyVidEqKey<'tcx> {
405     type Value = TypeVariableValue<'tcx>;
406     fn index(&self) -> u32 { self.vid.index }
407     fn from_index(i: u32) -> Self { TyVidEqKey::from(ty::TyVid { index: i }) }
408     fn tag() -> &'static str { "TyVidEqKey" }
409 }
410
411 impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> {
412     type Error = ut::NoError;
413
414     fn unify_values(value1: &Self, value2: &Self) -> Result<Self, ut::NoError> {
415         match (value1, value2) {
416             // We never equate two type variables, both of which
417             // have known types.  Instead, we recursively equate
418             // those types.
419             (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => {
420                 bug!("equating two type variables, both of which have known types")
421             }
422
423             // If one side is known, prefer that one.
424             (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1),
425             (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2),
426
427             // If both sides are *unknown*, it hardly matters, does it?
428             (&TypeVariableValue::Unknown { universe: universe1 },
429              &TypeVariableValue::Unknown { universe: universe2 }) =>  {
430                 // If we unify two unbound variables, ?T and ?U, then whatever
431                 // value they wind up taking (which must be the same value) must
432                 // be nameable by both universes. Therefore, the resulting
433                 // universe is the minimum of the two universes, because that is
434                 // the one which contains the fewest names in scope.
435                 let universe = cmp::min(universe1, universe2);
436                 Ok(TypeVariableValue::Unknown { universe })
437             }
438         }
439     }
440 }
441
442 /// Raw `TyVid` are used as the unification key for `sub_relations`;
443 /// they carry no values.
444 impl ut::UnifyKey for ty::TyVid {
445     type Value = ();
446     fn index(&self) -> u32 { self.index }
447     fn from_index(i: u32) -> ty::TyVid { ty::TyVid { index: i } }
448     fn tag() -> &'static str { "TyVid" }
449 }