]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/infer/type_variable.rs
6f1de3ee63597cf24f94a0b08951f5d13ae08062
[rustc.git] / src / librustc / middle / infer / type_variable.rs
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.
4 //
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.
10
11 pub use self::RelationDir::*;
12 use self::TypeVariableValue::*;
13 use self::UndoEntry::*;
14
15 use middle::ty::{self, Ty};
16 use std::cmp::min;
17 use std::marker::PhantomData;
18 use std::mem;
19 use std::u32;
20 use rustc_data_structures::snapshot_vec as sv;
21
22 pub struct TypeVariableTable<'tcx> {
23 values: sv::SnapshotVec<Delegate<'tcx>>,
24 }
25
26 struct TypeVariableData<'tcx> {
27 value: TypeVariableValue<'tcx>,
28 diverging: bool
29 }
30
31 enum TypeVariableValue<'tcx> {
32 Known(Ty<'tcx>),
33 Bounded(Vec<Relation>),
34 }
35
36 pub struct Snapshot {
37 snapshot: sv::Snapshot
38 }
39
40 enum UndoEntry {
41 // The type of the var was specified.
42 SpecifyVar(ty::TyVid, Vec<Relation>),
43 Relate(ty::TyVid, ty::TyVid),
44 }
45
46 struct Delegate<'tcx>(PhantomData<&'tcx ()>);
47
48 type Relation = (RelationDir, ty::TyVid);
49
50 #[derive(Copy, Clone, PartialEq, Debug)]
51 pub enum RelationDir {
52 SubtypeOf, SupertypeOf, EqTo, BiTo
53 }
54
55 impl RelationDir {
56 fn opposite(self) -> RelationDir {
57 match self {
58 SubtypeOf => SupertypeOf,
59 SupertypeOf => SubtypeOf,
60 EqTo => EqTo,
61 BiTo => BiTo,
62 }
63 }
64 }
65
66 impl<'tcx> TypeVariableTable<'tcx> {
67 pub fn new() -> TypeVariableTable<'tcx> {
68 TypeVariableTable { values: sv::SnapshotVec::new() }
69 }
70
71 fn relations<'a>(&'a mut self, a: ty::TyVid) -> &'a mut Vec<Relation> {
72 relations(self.values.get_mut(a.index as usize))
73 }
74
75 pub fn var_diverges<'a>(&'a self, vid: ty::TyVid) -> bool {
76 self.values.get(vid.index as usize).diverging
77 }
78
79 /// Records that `a <: b`, `a :> b`, or `a == b`, depending on `dir`.
80 ///
81 /// Precondition: neither `a` nor `b` are known.
82 pub fn relate_vars(&mut self, a: ty::TyVid, dir: RelationDir, b: ty::TyVid) {
83 if a != b {
84 self.relations(a).push((dir, b));
85 self.relations(b).push((dir.opposite(), a));
86 self.values.record(Relate(a, b));
87 }
88 }
89
90 /// Instantiates `vid` with the type `ty` and then pushes an entry onto `stack` for each of the
91 /// relations of `vid` to other variables. The relations will have the form `(ty, dir, vid1)`
92 /// where `vid1` is some other variable id.
93 pub fn instantiate_and_push(
94 &mut self,
95 vid: ty::TyVid,
96 ty: Ty<'tcx>,
97 stack: &mut Vec<(Ty<'tcx>, RelationDir, ty::TyVid)>)
98 {
99 let old_value = {
100 let value_ptr = &mut self.values.get_mut(vid.index as usize).value;
101 mem::replace(value_ptr, Known(ty))
102 };
103
104 let relations = match old_value {
105 Bounded(b) => b,
106 Known(_) => panic!("Asked to instantiate variable that is \
107 already instantiated")
108 };
109
110 for &(dir, vid) in &relations {
111 stack.push((ty, dir, vid));
112 }
113
114 self.values.record(SpecifyVar(vid, relations));
115 }
116
117 pub fn new_var(&mut self, diverging: bool) -> ty::TyVid {
118 let index = self.values.push(TypeVariableData {
119 value: Bounded(vec![]),
120 diverging: diverging
121 });
122 ty::TyVid { index: index as u32 }
123 }
124
125 pub fn probe(&self, vid: ty::TyVid) -> Option<Ty<'tcx>> {
126 match self.values.get(vid.index as usize).value {
127 Bounded(..) => None,
128 Known(t) => Some(t)
129 }
130 }
131
132 pub fn replace_if_possible(&self, t: Ty<'tcx>) -> Ty<'tcx> {
133 match t.sty {
134 ty::TyInfer(ty::TyVar(v)) => {
135 match self.probe(v) {
136 None => t,
137 Some(u) => u
138 }
139 }
140 _ => t,
141 }
142 }
143
144 pub fn snapshot(&mut self) -> Snapshot {
145 Snapshot { snapshot: self.values.start_snapshot() }
146 }
147
148 pub fn rollback_to(&mut self, s: Snapshot) {
149 self.values.rollback_to(s.snapshot);
150 }
151
152 pub fn commit(&mut self, s: Snapshot) {
153 self.values.commit(s.snapshot);
154 }
155
156 pub fn types_escaping_snapshot(&self, s: &Snapshot) -> Vec<Ty<'tcx>> {
157 /*!
158 * Find the set of type variables that existed *before* `s`
159 * but which have only been unified since `s` started, and
160 * return the types with which they were unified. So if we had
161 * a type variable `V0`, then we started the snapshot, then we
162 * created a type variable `V1`, unifed `V0` with `T0`, and
163 * unified `V1` with `T1`, this function would return `{T0}`.
164 */
165
166 let mut new_elem_threshold = u32::MAX;
167 let mut escaping_types = Vec::new();
168 let actions_since_snapshot = self.values.actions_since_snapshot(&s.snapshot);
169 debug!("actions_since_snapshot.len() = {}", actions_since_snapshot.len());
170 for action in actions_since_snapshot {
171 match *action {
172 sv::UndoLog::NewElem(index) => {
173 // if any new variables were created during the
174 // snapshot, remember the lower index (which will
175 // always be the first one we see). Note that this
176 // action must precede those variables being
177 // specified.
178 new_elem_threshold = min(new_elem_threshold, index as u32);
179 debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold);
180 }
181
182 sv::UndoLog::Other(SpecifyVar(vid, _)) => {
183 if vid.index < new_elem_threshold {
184 // quick check to see if this variable was
185 // created since the snapshot started or not.
186 let escaping_type = self.probe(vid).unwrap();
187 escaping_types.push(escaping_type);
188 }
189 debug!("SpecifyVar({:?}) new_elem_threshold={}", vid, new_elem_threshold);
190 }
191
192 _ => { }
193 }
194 }
195
196 escaping_types
197 }
198 }
199
200 impl<'tcx> sv::SnapshotVecDelegate for Delegate<'tcx> {
201 type Value = TypeVariableData<'tcx>;
202 type Undo = UndoEntry;
203
204 fn reverse(values: &mut Vec<TypeVariableData<'tcx>>, action: UndoEntry) {
205 match action {
206 SpecifyVar(vid, relations) => {
207 values[vid.index as usize].value = Bounded(relations);
208 }
209
210 Relate(a, b) => {
211 relations(&mut (*values)[a.index as usize]).pop();
212 relations(&mut (*values)[b.index as usize]).pop();
213 }
214 }
215 }
216 }
217
218 fn relations<'a>(v: &'a mut TypeVariableData) -> &'a mut Vec<Relation> {
219 match v.value {
220 Known(_) => panic!("var_sub_var: variable is known"),
221 Bounded(ref mut relations) => relations
222 }
223 }