]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/combine.rs
ac78d53c02c50006c37f99d013b32acaeda88bc2
[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::relate::{self, Relate, RelateResult, TypeRelation};
46 use traits::PredicateObligations;
47
48 use syntax::ast;
49 use syntax_pos::Span;
50
51 #[derive(Clone)]
52 pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
53     pub infcx: &'infcx InferCtxt<'infcx, 'gcx, 'tcx>,
54     pub trace: TypeTrace<'tcx>,
55     pub cause: Option<ty::relate::Cause>,
56     pub obligations: PredicateObligations<'tcx>,
57 }
58
59 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
60 pub enum RelationDir {
61     SubtypeOf, SupertypeOf, EqTo
62 }
63
64 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
65     pub fn super_combine_tys<R>(&self,
66                                 relation: &mut R,
67                                 a: Ty<'tcx>,
68                                 b: Ty<'tcx>)
69                                 -> RelateResult<'tcx, Ty<'tcx>>
70         where R: TypeRelation<'infcx, 'gcx, 'tcx>
71     {
72         let a_is_expected = relation.a_is_expected();
73
74         match (&a.sty, &b.sty) {
75             // Relate integral variables to other types
76             (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
77                 self.int_unification_table
78                     .borrow_mut()
79                     .unify_var_var(a_id, b_id)
80                     .map_err(|e| int_unification_error(a_is_expected, e))?;
81                 Ok(a)
82             }
83             (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
84                 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
85             }
86             (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => {
87                 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
88             }
89             (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => {
90                 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
91             }
92             (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => {
93                 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
94             }
95
96             // Relate floating-point variables to other types
97             (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
98                 self.float_unification_table
99                     .borrow_mut()
100                     .unify_var_var(a_id, b_id)
101                     .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
102                 Ok(a)
103             }
104             (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
105                 self.unify_float_variable(a_is_expected, v_id, v)
106             }
107             (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => {
108                 self.unify_float_variable(!a_is_expected, v_id, v)
109             }
110
111             // All other cases of inference are errors
112             (&ty::TyInfer(_), _) |
113             (_, &ty::TyInfer(_)) => {
114                 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
115             }
116
117
118             _ => {
119                 ty::relate::super_relate_tys(relation, a, b)
120             }
121         }
122     }
123
124     fn unify_integral_variable(&self,
125                                vid_is_expected: bool,
126                                vid: ty::IntVid,
127                                val: ty::IntVarValue)
128                                -> RelateResult<'tcx, Ty<'tcx>>
129     {
130         self.int_unification_table
131             .borrow_mut()
132             .unify_var_value(vid, val)
133             .map_err(|e| int_unification_error(vid_is_expected, e))?;
134         match val {
135             IntType(v) => Ok(self.tcx.mk_mach_int(v)),
136             UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
137         }
138     }
139
140     fn unify_float_variable(&self,
141                             vid_is_expected: bool,
142                             vid: ty::FloatVid,
143                             val: ast::FloatTy)
144                             -> RelateResult<'tcx, Ty<'tcx>>
145     {
146         self.float_unification_table
147             .borrow_mut()
148             .unify_var_value(vid, val)
149             .map_err(|e| float_unification_error(vid_is_expected, e))?;
150         Ok(self.tcx.mk_mach_float(val))
151     }
152 }
153
154 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
155     pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
156         self.infcx.tcx
157     }
158
159     pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
160         Equate::new(self, a_is_expected)
161     }
162
163     pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
164         Sub::new(self, a_is_expected)
165     }
166
167     pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
168         Lub::new(self, a_is_expected)
169     }
170
171     pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
172         Glb::new(self, a_is_expected)
173     }
174
175     /// Here dir is either EqTo, SubtypeOf, or SupertypeOf. The
176     /// idea is that we should ensure that the type `a_ty` is equal
177     /// to, a subtype of, or a supertype of (respectively) the type
178     /// to which `b_vid` is bound.
179     ///
180     /// Since `b_vid` has not yet been instantiated with a type, we
181     /// will first instantiate `b_vid` with a *generalized* version
182     /// of `a_ty`. Generalization introduces other inference
183     /// variables wherever subtyping could occur.
184     pub fn instantiate(&mut self,
185                        a_ty: Ty<'tcx>,
186                        dir: RelationDir,
187                        b_vid: ty::TyVid,
188                        a_is_expected: bool)
189                        -> RelateResult<'tcx, ()>
190     {
191         use self::RelationDir::*;
192
193         // Get the actual variable that b_vid has been inferred to
194         debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_none());
195
196         debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
197
198         // Generalize type of `a_ty` appropriately depending on the
199         // direction.  As an example, assume:
200         //
201         // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
202         //   inference variable,
203         // - and `dir` == `SubtypeOf`.
204         //
205         // Then the generalized form `b_ty` would be `&'?2 ?3`, where
206         // `'?2` and `?3` are fresh region/type inference
207         // variables. (Down below, we will relate `a_ty <: b_ty`,
208         // adding constraints like `'x: '?2` and `?1 <: ?3`.)
209         let b_ty = self.generalize(a_ty, b_vid, dir)?;
210         debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
211                a_ty, dir, b_vid, b_ty);
212         self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
213
214         // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
215         //
216         // FIXME(#16847): This code is non-ideal because all these subtype
217         // relations wind up attributed to the same spans. We need
218         // to associate causes/spans with each of the relations in
219         // the stack to get this right.
220         match dir {
221             EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
222             SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
223             SupertypeOf => self.sub(a_is_expected).relate_with_variance(
224                 ty::Contravariant, &a_ty, &b_ty),
225         }?;
226
227         Ok(())
228     }
229
230     /// Attempts to generalize `ty` for the type variable `for_vid`.
231     /// This checks for cycle -- that is, whether the type `ty`
232     /// references `for_vid`. If `is_eq_relation` is false, it will
233     /// also replace all regions/unbound-type-variables with fresh
234     /// variables. Returns `TyError` in the case of a cycle, `Ok`
235     /// otherwise.
236     ///
237     /// Preconditions:
238     ///
239     /// - `for_vid` is a "root vid"
240     fn generalize(&self,
241                   ty: Ty<'tcx>,
242                   for_vid: ty::TyVid,
243                   dir: RelationDir)
244                   -> RelateResult<'tcx, Ty<'tcx>>
245     {
246         // Determine the ambient variance within which `ty` appears.
247         // The surrounding equation is:
248         //
249         //     ty [op] ty2
250         //
251         // where `op` is either `==`, `<:`, or `:>`. This maps quite
252         // naturally.
253         let ambient_variance = match dir {
254             RelationDir::EqTo => ty::Invariant,
255             RelationDir::SubtypeOf => ty::Covariant,
256             RelationDir::SupertypeOf => ty::Contravariant,
257         };
258
259         let mut generalize = Generalizer {
260             infcx: self.infcx,
261             span: self.trace.cause.span,
262             for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
263             ambient_variance: ambient_variance,
264         };
265
266         generalize.relate(&ty, &ty)
267     }
268 }
269
270 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
271     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
272     span: Span,
273     for_vid_sub_root: ty::TyVid,
274     ambient_variance: ty::Variance,
275 }
276
277 impl<'cx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
278     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
279         self.infcx.tcx
280     }
281
282     fn tag(&self) -> &'static str {
283         "Generalizer"
284     }
285
286     fn a_is_expected(&self) -> bool {
287         true
288     }
289
290     fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
291                   -> RelateResult<'tcx, ty::Binder<T>>
292         where T: Relate<'tcx>
293     {
294         Ok(ty::Binder(self.relate(a.skip_binder(), b.skip_binder())?))
295     }
296
297     fn relate_with_variance<T: Relate<'tcx>>(&mut self,
298                                              variance: ty::Variance,
299                                              a: &T,
300                                              b: &T)
301                                              -> RelateResult<'tcx, T>
302     {
303         let old_ambient_variance = self.ambient_variance;
304         self.ambient_variance = self.ambient_variance.xform(variance);
305
306         let result = self.relate(a, b);
307         self.ambient_variance = old_ambient_variance;
308         result
309     }
310
311     fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
312         assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
313
314         // Check to see whether the type we are genealizing references
315         // any other type variable related to `vid` via
316         // subtyping. This is basically our "occurs check", preventing
317         // us from creating infinitely sized types.
318         match t.sty {
319             ty::TyInfer(ty::TyVar(vid)) => {
320                 let mut variables = self.infcx.type_variables.borrow_mut();
321                 let vid = variables.root_var(vid);
322                 let sub_vid = variables.sub_root_var(vid);
323                 if sub_vid == self.for_vid_sub_root {
324                     // If sub-roots are equal, then `for_vid` and
325                     // `vid` are related via subtyping.
326                     return Err(TypeError::CyclicTy);
327                 } else {
328                     match variables.probe_root(vid) {
329                         Some(u) => {
330                             drop(variables);
331                             self.relate(&u, &u)
332                         }
333                         None => {
334                             match self.ambient_variance {
335                                 ty::Invariant => Ok(t),
336
337                                 ty::Bivariant | ty::Covariant | ty::Contravariant => {
338                                     let origin = variables.origin(vid);
339                                     let new_var_id = variables.new_var(false, origin, None);
340                                     let u = self.tcx().mk_var(new_var_id);
341                                     debug!("generalize: replacing original vid={:?} with new={:?}",
342                                            vid, u);
343                                     Ok(u)
344                                 }
345                             }
346                         }
347                     }
348                 }
349             }
350             ty::TyInfer(ty::IntVar(_)) |
351             ty::TyInfer(ty::FloatVar(_)) => {
352                 // No matter what mode we are in,
353                 // integer/floating-point types must be equal to be
354                 // relatable.
355                 Ok(t)
356             }
357             _ => {
358                 relate::super_relate_tys(self, t, t)
359             }
360         }
361     }
362
363     fn regions(&mut self, r: ty::Region<'tcx>, r2: ty::Region<'tcx>)
364                -> RelateResult<'tcx, ty::Region<'tcx>> {
365         assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
366
367         match *r {
368             // Never make variables for regions bound within the type itself,
369             // nor for erased regions.
370             ty::ReLateBound(..) |
371             ty::ReErased => {
372                 return Ok(r);
373             }
374
375             // Early-bound regions should really have been substituted away before
376             // we get to this point.
377             ty::ReEarlyBound(..) => {
378                 span_bug!(
379                     self.span,
380                     "Encountered early bound region when generalizing: {:?}",
381                     r);
382             }
383
384             // Always make a fresh region variable for skolemized regions;
385             // the higher-ranked decision procedures rely on this.
386             ty::ReSkolemized(..) => { }
387
388             // For anything else, we make a region variable, unless we
389             // are *equating*, in which case it's just wasteful.
390             ty::ReEmpty |
391             ty::ReStatic |
392             ty::ReScope(..) |
393             ty::ReVar(..) |
394             ty::ReFree(..) => {
395                 match self.ambient_variance {
396                     ty::Invariant => return Ok(r),
397                     ty::Bivariant | ty::Covariant | ty::Contravariant => (),
398                 }
399             }
400         }
401
402         // FIXME: This is non-ideal because we don't give a
403         // very descriptive origin for this region variable.
404         Ok(self.infcx.next_region_var(MiscVariable(self.span)))
405     }
406 }
407
408 pub trait RelateResultCompare<'tcx, T> {
409     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
410         F: FnOnce() -> TypeError<'tcx>;
411 }
412
413 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
414     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
415         F: FnOnce() -> TypeError<'tcx>,
416     {
417         self.clone().and_then(|s| {
418             if s == t {
419                 self.clone()
420             } else {
421                 Err(f())
422             }
423         })
424     }
425 }
426
427 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
428                                -> TypeError<'tcx>
429 {
430     let (a, b) = v;
431     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
432 }
433
434 fn float_unification_error<'tcx>(a_is_expected: bool,
435                                  v: (ast::FloatTy, ast::FloatTy))
436                                  -> TypeError<'tcx>
437 {
438     let (a, b) = v;
439     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
440 }