]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/combine.rs
add FIXME to #18653
[rust.git] / src / librustc / infer / combine.rs
1 // Copyright 2012 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 ///////////////////////////////////////////////////////////////////////////
12 // # Type combining
13 //
14 // There are four type combiners: equate, sub, lub, and glb.  Each
15 // implements the trait `Combine` and contains methods for combining
16 // two instances of various things and yielding a new instance.  These
17 // combiner methods always yield a `Result<T>`.  There is a lot of
18 // common code for these operations, implemented as default methods on
19 // the `Combine` trait.
20 //
21 // Each operation may have side-effects on the inference context,
22 // though these can be unrolled using snapshots. On success, the
23 // LUB/GLB operations return the appropriate bound. The Eq and Sub
24 // operations generally return the first operand.
25 //
26 // ## Contravariance
27 //
28 // When you are relating two things which have a contravariant
29 // relationship, you should use `contratys()` or `contraregions()`,
30 // rather than inversing the order of arguments!  This is necessary
31 // because the order of arguments is not relevant for LUB and GLB.  It
32 // is also useful to track which value is the "expected" value in
33 // terms of error reporting.
34
35 use super::equate::Equate;
36 use super::glb::Glb;
37 use super::lub::Lub;
38 use super::sub::Sub;
39 use super::InferCtxt;
40 use super::{MiscVariable, TypeTrace};
41
42 use ty::{IntType, UintType};
43 use ty::{self, Ty, TyCtxt};
44 use ty::error::TypeError;
45 use ty::fold::TypeFoldable;
46 use ty::relate::{RelateResult, TypeRelation};
47 use traits::PredicateObligations;
48
49 use syntax::ast;
50 use syntax::util::small_vector::SmallVector;
51 use syntax_pos::Span;
52
53 #[derive(Clone)]
54 pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
55     pub infcx: &'infcx InferCtxt<'infcx, 'gcx, 'tcx>,
56     pub trace: TypeTrace<'tcx>,
57     pub cause: Option<ty::relate::Cause>,
58     pub obligations: PredicateObligations<'tcx>,
59 }
60
61 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
62 pub enum RelationDir {
63     SubtypeOf, SupertypeOf, EqTo
64 }
65
66 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
67     pub fn super_combine_tys<R>(&self,
68                                 relation: &mut R,
69                                 a: Ty<'tcx>,
70                                 b: Ty<'tcx>)
71                                 -> RelateResult<'tcx, Ty<'tcx>>
72         where R: TypeRelation<'infcx, 'gcx, 'tcx>
73     {
74         let a_is_expected = relation.a_is_expected();
75
76         match (&a.sty, &b.sty) {
77             // Relate integral variables to other types
78             (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
79                 self.int_unification_table
80                     .borrow_mut()
81                     .unify_var_var(a_id, b_id)
82                     .map_err(|e| int_unification_error(a_is_expected, e))?;
83                 Ok(a)
84             }
85             (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
86                 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
87             }
88             (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => {
89                 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
90             }
91             (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => {
92                 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
93             }
94             (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => {
95                 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
96             }
97
98             // Relate floating-point variables to other types
99             (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
100                 self.float_unification_table
101                     .borrow_mut()
102                     .unify_var_var(a_id, b_id)
103                     .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
104                 Ok(a)
105             }
106             (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
107                 self.unify_float_variable(a_is_expected, v_id, v)
108             }
109             (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => {
110                 self.unify_float_variable(!a_is_expected, v_id, v)
111             }
112
113             // All other cases of inference are errors
114             (&ty::TyInfer(_), _) |
115             (_, &ty::TyInfer(_)) => {
116                 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
117             }
118
119
120             _ => {
121                 ty::relate::super_relate_tys(relation, a, b)
122             }
123         }
124     }
125
126     fn unify_integral_variable(&self,
127                                vid_is_expected: bool,
128                                vid: ty::IntVid,
129                                val: ty::IntVarValue)
130                                -> RelateResult<'tcx, Ty<'tcx>>
131     {
132         self.int_unification_table
133             .borrow_mut()
134             .unify_var_value(vid, val)
135             .map_err(|e| int_unification_error(vid_is_expected, e))?;
136         match val {
137             IntType(v) => Ok(self.tcx.mk_mach_int(v)),
138             UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
139         }
140     }
141
142     fn unify_float_variable(&self,
143                             vid_is_expected: bool,
144                             vid: ty::FloatVid,
145                             val: ast::FloatTy)
146                             -> RelateResult<'tcx, Ty<'tcx>>
147     {
148         self.float_unification_table
149             .borrow_mut()
150             .unify_var_value(vid, val)
151             .map_err(|e| float_unification_error(vid_is_expected, e))?;
152         Ok(self.tcx.mk_mach_float(val))
153     }
154 }
155
156 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
157     pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
158         self.infcx.tcx
159     }
160
161     pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
162         Equate::new(self, a_is_expected)
163     }
164
165     pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
166         Sub::new(self, a_is_expected)
167     }
168
169     pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
170         Lub::new(self, a_is_expected)
171     }
172
173     pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
174         Glb::new(self, a_is_expected)
175     }
176
177     pub fn instantiate(&mut self,
178                        a_ty: Ty<'tcx>,
179                        dir: RelationDir,
180                        b_vid: ty::TyVid,
181                        a_is_expected: bool)
182                        -> RelateResult<'tcx, ()>
183     {
184         use self::RelationDir::*;
185
186         // We use SmallVector here instead of Vec because this code is hot and
187         // it's rare that the stack length exceeds 1.
188         let mut stack = SmallVector::new();
189         stack.push((a_ty, dir, b_vid));
190         loop {
191             // For each turn of the loop, we extract a tuple
192             //
193             //     (a_ty, dir, b_vid)
194             //
195             // to relate. Here dir is either SubtypeOf or
196             // SupertypeOf. The idea is that we should ensure that
197             // the type `a_ty` is a subtype or supertype (respectively) of the
198             // type to which `b_vid` is bound.
199             //
200             // If `b_vid` has not yet been instantiated with a type
201             // (which is always true on the first iteration, but not
202             // necessarily true on later iterations), we will first
203             // instantiate `b_vid` with a *generalized* version of
204             // `a_ty`. Generalization introduces other inference
205             // variables wherever subtyping could occur (at time of
206             // this writing, this means replacing free regions with
207             // region variables).
208             let (a_ty, dir, b_vid) = match stack.pop() {
209                 None => break,
210                 Some(e) => e,
211             };
212             // Get the actual variable that b_vid has been inferred to
213             let (b_vid, b_ty) = {
214                 let mut variables = self.infcx.type_variables.borrow_mut();
215                 let b_vid = variables.root_var(b_vid);
216                 (b_vid, variables.probe_root(b_vid))
217             };
218
219             debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})",
220                    a_ty,
221                    dir,
222                    b_vid);
223
224             // Check whether `vid` has been instantiated yet.  If not,
225             // make a generalized form of `ty` and instantiate with
226             // that.
227             //
228             // FIXME(#18653) -- we need to generalize nested type
229             // variables too.
230             let b_ty = match b_ty {
231                 Some(t) => t, // ...already instantiated.
232                 None => {     // ...not yet instantiated:
233                     // Generalize type if necessary.
234                     let generalized_ty = match dir {
235                         EqTo => self.generalize(a_ty, b_vid, false),
236                         SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true),
237                     }?;
238                     debug!("instantiate(a_ty={:?}, dir={:?}, \
239                                         b_vid={:?}, generalized_ty={:?})",
240                            a_ty, dir, b_vid,
241                            generalized_ty);
242                     self.infcx.type_variables
243                         .borrow_mut()
244                         .instantiate(b_vid, generalized_ty);
245                     generalized_ty
246                 }
247             };
248
249             // The original triple was `(a_ty, dir, b_vid)` -- now we have
250             // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`:
251             //
252             // FIXME(#16847): This code is non-ideal because all these subtype
253             // relations wind up attributed to the same spans. We need
254             // to associate causes/spans with each of the relations in
255             // the stack to get this right.
256             match dir {
257                 EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
258                 SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
259                 SupertypeOf => self.sub(a_is_expected).relate_with_variance(
260                     ty::Contravariant, &a_ty, &b_ty),
261             }?;
262         }
263
264         Ok(())
265     }
266
267     /// Attempts to generalize `ty` for the type variable `for_vid`.  This checks for cycle -- that
268     /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also
269     /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok`
270     /// otherwise.
271     fn generalize(&self,
272                   ty: Ty<'tcx>,
273                   for_vid: ty::TyVid,
274                   make_region_vars: bool)
275                   -> RelateResult<'tcx, Ty<'tcx>>
276     {
277         let mut generalize = Generalizer {
278             infcx: self.infcx,
279             span: self.trace.cause.span,
280             for_vid: for_vid,
281             make_region_vars: make_region_vars,
282             cycle_detected: false
283         };
284         let u = ty.fold_with(&mut generalize);
285         if generalize.cycle_detected {
286             Err(TypeError::CyclicTy)
287         } else {
288             Ok(u)
289         }
290     }
291 }
292
293 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
294     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
295     span: Span,
296     for_vid: ty::TyVid,
297     make_region_vars: bool,
298     cycle_detected: bool,
299 }
300
301 impl<'cx, 'gcx, 'tcx> ty::fold::TypeFolder<'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
302     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
303         self.infcx.tcx
304     }
305
306     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
307         // Check to see whether the type we are genealizing references
308         // `vid`. At the same time, also update any type variables to
309         // the values that they are bound to. This is needed to truly
310         // check for cycles, but also just makes things readable.
311         //
312         // (In particular, you could have something like `$0 = Box<$1>`
313         //  where `$1` has already been instantiated with `Box<$0>`)
314         match t.sty {
315             ty::TyInfer(ty::TyVar(vid)) => {
316                 let mut variables = self.infcx.type_variables.borrow_mut();
317                 let vid = variables.root_var(vid);
318                 if vid == self.for_vid {
319                     self.cycle_detected = true;
320                     self.tcx().types.err
321                 } else {
322                     match variables.probe_root(vid) {
323                         Some(u) => {
324                             drop(variables);
325                             self.fold_ty(u)
326                         }
327                         None => t,
328                     }
329                 }
330             }
331             _ => {
332                 t.super_fold_with(self)
333             }
334         }
335     }
336
337     fn fold_region(&mut self, r: &'tcx ty::Region) -> &'tcx ty::Region {
338         match *r {
339             // Never make variables for regions bound within the type itself,
340             // nor for erased regions.
341             ty::ReLateBound(..) |
342             ty::ReErased => { return r; }
343
344             // Early-bound regions should really have been substituted away before
345             // we get to this point.
346             ty::ReEarlyBound(..) => {
347                 span_bug!(
348                     self.span,
349                     "Encountered early bound region when generalizing: {:?}",
350                     r);
351             }
352
353             // Always make a fresh region variable for skolemized regions;
354             // the higher-ranked decision procedures rely on this.
355             ty::ReSkolemized(..) => { }
356
357             // For anything else, we make a region variable, unless we
358             // are *equating*, in which case it's just wasteful.
359             ty::ReEmpty |
360             ty::ReStatic |
361             ty::ReScope(..) |
362             ty::ReVar(..) |
363             ty::ReFree(..) => {
364                 if !self.make_region_vars {
365                     return r;
366                 }
367             }
368         }
369
370         // FIXME: This is non-ideal because we don't give a
371         // very descriptive origin for this region variable.
372         self.infcx.next_region_var(MiscVariable(self.span))
373     }
374 }
375
376 pub trait RelateResultCompare<'tcx, T> {
377     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
378         F: FnOnce() -> TypeError<'tcx>;
379 }
380
381 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
382     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
383         F: FnOnce() -> TypeError<'tcx>,
384     {
385         self.clone().and_then(|s| {
386             if s == t {
387                 self.clone()
388             } else {
389                 Err(f())
390             }
391         })
392     }
393 }
394
395 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
396                                -> TypeError<'tcx>
397 {
398     let (a, b) = v;
399     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
400 }
401
402 fn float_unification_error<'tcx>(a_is_expected: bool,
403                                  v: (ast::FloatTy, ast::FloatTy))
404                                  -> TypeError<'tcx>
405 {
406     let (a, b) = v;
407     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
408 }