1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::RelationDir::*;
12 use self::TypeVariableValue::*;
13 use self::UndoEntry::*;
14 use middle::def_id::{DefId};
15 use middle::ty::{self, Ty};
16 use syntax::codemap::Span;
19 use std::marker::PhantomData;
22 use rustc_data_structures::snapshot_vec as sv;
24 pub struct TypeVariableTable<'tcx> {
25 values: sv::SnapshotVec<Delegate<'tcx>>,
28 struct TypeVariableData<'tcx> {
29 value: TypeVariableValue<'tcx>,
33 enum TypeVariableValue<'tcx> {
36 relations: Vec<Relation>,
37 default: Option<Default<'tcx>>
41 // We will use this to store the required information to recapitulate what happened when
43 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
44 pub struct Default<'tcx> {
46 /// The span where the default was incurred
47 pub origin_span: Span,
48 /// The definition that the default originates from
53 snapshot: sv::Snapshot
56 enum UndoEntry<'tcx> {
57 // The type of the var was specified.
58 SpecifyVar(ty::TyVid, Vec<Relation>, Option<Default<'tcx>>),
59 Relate(ty::TyVid, ty::TyVid),
62 struct Delegate<'tcx>(PhantomData<&'tcx ()>);
64 type Relation = (RelationDir, ty::TyVid);
66 #[derive(Copy, Clone, PartialEq, Debug)]
67 pub enum RelationDir {
68 SubtypeOf, SupertypeOf, EqTo, BiTo
72 fn opposite(self) -> RelationDir {
74 SubtypeOf => SupertypeOf,
75 SupertypeOf => SubtypeOf,
82 impl<'tcx> TypeVariableTable<'tcx> {
83 pub fn new() -> TypeVariableTable<'tcx> {
84 TypeVariableTable { values: sv::SnapshotVec::new() }
87 fn relations<'a>(&'a mut self, a: ty::TyVid) -> &'a mut Vec<Relation> {
88 relations(self.values.get_mut(a.index as usize))
91 pub fn default(&self, vid: ty::TyVid) -> Option<Default<'tcx>> {
92 match &self.values.get(vid.index as usize).value {
94 &Bounded { ref default, .. } => default.clone()
98 pub fn var_diverges<'a>(&'a self, vid: ty::TyVid) -> bool {
99 self.values.get(vid.index as usize).diverging
102 /// Records that `a <: b`, `a :> b`, or `a == b`, depending on `dir`.
104 /// Precondition: neither `a` nor `b` are known.
105 pub fn relate_vars(&mut self, a: ty::TyVid, dir: RelationDir, b: ty::TyVid) {
107 self.relations(a).push((dir, b));
108 self.relations(b).push((dir.opposite(), a));
109 self.values.record(Relate(a, b));
113 /// Instantiates `vid` with the type `ty` and then pushes an entry onto `stack` for each of the
114 /// relations of `vid` to other variables. The relations will have the form `(ty, dir, vid1)`
115 /// where `vid1` is some other variable id.
116 pub fn instantiate_and_push(
120 stack: &mut Vec<(Ty<'tcx>, RelationDir, ty::TyVid)>)
123 let value_ptr = &mut self.values.get_mut(vid.index as usize).value;
124 mem::replace(value_ptr, Known(ty))
127 let (relations, default) = match old_value {
128 Bounded { relations, default } => (relations, default),
129 Known(_) => panic!("Asked to instantiate variable that is \
130 already instantiated")
133 for &(dir, vid) in &relations {
134 stack.push((ty, dir, vid));
137 self.values.record(SpecifyVar(vid, relations, default));
140 pub fn new_var(&mut self,
142 default: Option<Default<'tcx>>) -> ty::TyVid {
143 let index = self.values.push(TypeVariableData {
144 value: Bounded { relations: vec![], default: default },
147 ty::TyVid { index: index as u32 }
150 pub fn probe(&self, vid: ty::TyVid) -> Option<Ty<'tcx>> {
151 match self.values.get(vid.index as usize).value {
152 Bounded { .. } => None,
157 pub fn replace_if_possible(&self, t: Ty<'tcx>) -> Ty<'tcx> {
159 ty::TyInfer(ty::TyVar(v)) => {
160 match self.probe(v) {
169 pub fn snapshot(&mut self) -> Snapshot {
170 Snapshot { snapshot: self.values.start_snapshot() }
173 pub fn rollback_to(&mut self, s: Snapshot) {
174 self.values.rollback_to(s.snapshot);
177 pub fn commit(&mut self, s: Snapshot) {
178 self.values.commit(s.snapshot);
181 pub fn types_escaping_snapshot(&self, s: &Snapshot) -> Vec<Ty<'tcx>> {
183 * Find the set of type variables that existed *before* `s`
184 * but which have only been unified since `s` started, and
185 * return the types with which they were unified. So if we had
186 * a type variable `V0`, then we started the snapshot, then we
187 * created a type variable `V1`, unifed `V0` with `T0`, and
188 * unified `V1` with `T1`, this function would return `{T0}`.
191 let mut new_elem_threshold = u32::MAX;
192 let mut escaping_types = Vec::new();
193 let actions_since_snapshot = self.values.actions_since_snapshot(&s.snapshot);
194 debug!("actions_since_snapshot.len() = {}", actions_since_snapshot.len());
195 for action in actions_since_snapshot {
197 sv::UndoLog::NewElem(index) => {
198 // if any new variables were created during the
199 // snapshot, remember the lower index (which will
200 // always be the first one we see). Note that this
201 // action must precede those variables being
203 new_elem_threshold = min(new_elem_threshold, index as u32);
204 debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold);
207 sv::UndoLog::Other(SpecifyVar(vid, _, _)) => {
208 if vid.index < new_elem_threshold {
209 // quick check to see if this variable was
210 // created since the snapshot started or not.
211 let escaping_type = self.probe(vid).unwrap();
212 escaping_types.push(escaping_type);
214 debug!("SpecifyVar({:?}) new_elem_threshold={}", vid, new_elem_threshold);
224 pub fn unsolved_variables(&self) -> Vec<ty::TyVid> {
228 .filter_map(|(i, value)| match &value.value {
229 &TypeVariableValue::Known(_) => None,
230 &TypeVariableValue::Bounded { .. } => Some(ty::TyVid { index: i as u32 })
236 impl<'tcx> sv::SnapshotVecDelegate for Delegate<'tcx> {
237 type Value = TypeVariableData<'tcx>;
238 type Undo = UndoEntry<'tcx>;
240 fn reverse(values: &mut Vec<TypeVariableData<'tcx>>, action: UndoEntry<'tcx>) {
242 SpecifyVar(vid, relations, default) => {
243 values[vid.index as usize].value = Bounded {
244 relations: relations,
250 relations(&mut (*values)[a.index as usize]).pop();
251 relations(&mut (*values)[b.index as usize]).pop();
257 fn relations<'a>(v: &'a mut TypeVariableData) -> &'a mut Vec<Relation> {
259 Known(_) => panic!("var_sub_var: variable is known"),
260 Bounded { ref mut relations, .. } => relations