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