]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/combine.rs
rustdoc: Hide `self: Box<Self>` in list of deref methods
[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 hir::def_id::DefId;
43 use ty::{IntType, UintType};
44 use ty::{self, Ty, TyCtxt};
45 use ty::error::TypeError;
46 use ty::relate::{self, Relate, RelateResult, TypeRelation};
47 use ty::subst::Substs;
48 use traits::{Obligation, PredicateObligations};
49
50 use syntax::ast;
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     /// Here dir is either EqTo, SubtypeOf, or SupertypeOf. The
178     /// idea is that we should ensure that the type `a_ty` is equal
179     /// to, a subtype of, or a supertype of (respectively) the type
180     /// to which `b_vid` is bound.
181     ///
182     /// Since `b_vid` has not yet been instantiated with a type, we
183     /// will first instantiate `b_vid` with a *generalized* version
184     /// of `a_ty`. Generalization introduces other inference
185     /// variables wherever subtyping could occur.
186     pub fn instantiate(&mut self,
187                        a_ty: Ty<'tcx>,
188                        dir: RelationDir,
189                        b_vid: ty::TyVid,
190                        a_is_expected: bool)
191                        -> RelateResult<'tcx, ()>
192     {
193         use self::RelationDir::*;
194
195         // Get the actual variable that b_vid has been inferred to
196         debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_none());
197
198         debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
199
200         // Generalize type of `a_ty` appropriately depending on the
201         // direction.  As an example, assume:
202         //
203         // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
204         //   inference variable,
205         // - and `dir` == `SubtypeOf`.
206         //
207         // Then the generalized form `b_ty` would be `&'?2 ?3`, where
208         // `'?2` and `?3` are fresh region/type inference
209         // variables. (Down below, we will relate `a_ty <: b_ty`,
210         // adding constraints like `'x: '?2` and `?1 <: ?3`.)
211         let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
212         debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
213                a_ty, dir, b_vid, b_ty);
214         self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
215
216         if needs_wf {
217             self.obligations.push(Obligation::new(self.trace.cause.clone(),
218                                                   ty::Predicate::WellFormed(b_ty)));
219         }
220
221         // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
222         //
223         // FIXME(#16847): This code is non-ideal because all these subtype
224         // relations wind up attributed to the same spans. We need
225         // to associate causes/spans with each of the relations in
226         // the stack to get this right.
227         match dir {
228             EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
229             SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
230             SupertypeOf => self.sub(a_is_expected).relate_with_variance(
231                 ty::Contravariant, &a_ty, &b_ty),
232         }?;
233
234         Ok(())
235     }
236
237     /// Attempts to generalize `ty` for the type variable `for_vid`.
238     /// This checks for cycle -- that is, whether the type `ty`
239     /// references `for_vid`. The `dir` is the "direction" for which we
240     /// a performing the generalization (i.e., are we producing a type
241     /// that can be used as a supertype etc).
242     ///
243     /// Preconditions:
244     ///
245     /// - `for_vid` is a "root vid"
246     fn generalize(&self,
247                   ty: Ty<'tcx>,
248                   for_vid: ty::TyVid,
249                   dir: RelationDir)
250                   -> RelateResult<'tcx, Generalization<'tcx>>
251     {
252         // Determine the ambient variance within which `ty` appears.
253         // The surrounding equation is:
254         //
255         //     ty [op] ty2
256         //
257         // where `op` is either `==`, `<:`, or `:>`. This maps quite
258         // naturally.
259         let ambient_variance = match dir {
260             RelationDir::EqTo => ty::Invariant,
261             RelationDir::SubtypeOf => ty::Covariant,
262             RelationDir::SupertypeOf => ty::Contravariant,
263         };
264
265         let mut generalize = Generalizer {
266             infcx: self.infcx,
267             span: self.trace.cause.span,
268             for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
269             ambient_variance: ambient_variance,
270             needs_wf: false,
271         };
272
273         let ty = generalize.relate(&ty, &ty)?;
274         let needs_wf = generalize.needs_wf;
275         Ok(Generalization { ty, needs_wf })
276     }
277 }
278
279 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
280     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
281     span: Span,
282     for_vid_sub_root: ty::TyVid,
283     ambient_variance: ty::Variance,
284     needs_wf: bool, // see the field `needs_wf` in `Generalization`
285 }
286
287 /// Result from a generalization operation. This includes
288 /// not only the generalized type, but also a bool flag
289 /// indicating whether further WF checks are needed.q
290 struct Generalization<'tcx> {
291     ty: Ty<'tcx>,
292
293     /// If true, then the generalized type may not be well-formed,
294     /// even if the source type is well-formed, so we should add an
295     /// additional check to enforce that it is. This arises in
296     /// particular around 'bivariant' type parameters that are only
297     /// constrained by a where-clause. As an example, imagine a type:
298     ///
299     ///     struct Foo<A, B> where A: Iterator<Item=B> {
300     ///         data: A
301     ///     }
302     ///
303     /// here, `A` will be covariant, but `B` is
304     /// unconstrained. However, whatever it is, for `Foo` to be WF, it
305     /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
306     /// then after generalization we will wind up with a type like
307     /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
308     /// ?D>` (or `>:`), we will wind up with the requirement that `?A
309     /// <: ?C`, but no particular relationship between `?B` and `?D`
310     /// (after all, we do not know the variance of the normalized form
311     /// of `A::Item` with respect to `A`). If we do nothing else, this
312     /// may mean that `?D` goes unconstrained (as in #41677).  So, in
313     /// this scenario where we create a new type variable in a
314     /// bivariant context, we set the `needs_wf` flag to true. This
315     /// will force the calling code to check that `WF(Foo<?C, ?D>)`
316     /// holds, which in turn implies that `?C::Item == ?D`. So once
317     /// `?C` is constrained, that should suffice to restrict `?D`.
318     needs_wf: bool,
319 }
320
321 impl<'cx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
322     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
323         self.infcx.tcx
324     }
325
326     fn tag(&self) -> &'static str {
327         "Generalizer"
328     }
329
330     fn a_is_expected(&self) -> bool {
331         true
332     }
333
334     fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
335                   -> RelateResult<'tcx, ty::Binder<T>>
336         where T: Relate<'tcx>
337     {
338         Ok(ty::Binder(self.relate(a.skip_binder(), b.skip_binder())?))
339     }
340
341     fn relate_item_substs(&mut self,
342                           item_def_id: DefId,
343                           a_subst: &'tcx Substs<'tcx>,
344                           b_subst: &'tcx Substs<'tcx>)
345                           -> RelateResult<'tcx, &'tcx Substs<'tcx>>
346     {
347         if self.ambient_variance == ty::Variance::Invariant {
348             // Avoid fetching the variance if we are in an invariant
349             // context; no need, and it can induce dependency cycles
350             // (e.g. #41849).
351             relate::relate_substs(self, None, a_subst, b_subst)
352         } else {
353             let opt_variances = self.tcx().variances_of(item_def_id);
354             relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
355         }
356     }
357
358     fn relate_with_variance<T: Relate<'tcx>>(&mut self,
359                                              variance: ty::Variance,
360                                              a: &T,
361                                              b: &T)
362                                              -> RelateResult<'tcx, T>
363     {
364         let old_ambient_variance = self.ambient_variance;
365         self.ambient_variance = self.ambient_variance.xform(variance);
366
367         let result = self.relate(a, b);
368         self.ambient_variance = old_ambient_variance;
369         result
370     }
371
372     fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
373         assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
374
375         // Check to see whether the type we are genealizing references
376         // any other type variable related to `vid` via
377         // subtyping. This is basically our "occurs check", preventing
378         // us from creating infinitely sized types.
379         match t.sty {
380             ty::TyInfer(ty::TyVar(vid)) => {
381                 let mut variables = self.infcx.type_variables.borrow_mut();
382                 let vid = variables.root_var(vid);
383                 let sub_vid = variables.sub_root_var(vid);
384                 if sub_vid == self.for_vid_sub_root {
385                     // If sub-roots are equal, then `for_vid` and
386                     // `vid` are related via subtyping.
387                     return Err(TypeError::CyclicTy);
388                 } else {
389                     match variables.probe_root(vid) {
390                         Some(u) => {
391                             drop(variables);
392                             self.relate(&u, &u)
393                         }
394                         None => {
395                             match self.ambient_variance {
396                                 // Invariant: no need to make a fresh type variable.
397                                 ty::Invariant => return Ok(t),
398
399                                 // Bivariant: make a fresh var, but we
400                                 // may need a WF predicate. See
401                                 // comment on `needs_wf` field for
402                                 // more info.
403                                 ty::Bivariant => self.needs_wf = true,
404
405                                 // Co/contravariant: this will be
406                                 // sufficiently constrained later on.
407                                 ty::Covariant | ty::Contravariant => (),
408                             }
409
410                             let origin = variables.origin(vid);
411                             let new_var_id = variables.new_var(false, origin, None);
412                             let u = self.tcx().mk_var(new_var_id);
413                             debug!("generalize: replacing original vid={:?} with new={:?}",
414                                    vid, u);
415                             return Ok(u);
416                         }
417                     }
418                 }
419             }
420             ty::TyInfer(ty::IntVar(_)) |
421             ty::TyInfer(ty::FloatVar(_)) => {
422                 // No matter what mode we are in,
423                 // integer/floating-point types must be equal to be
424                 // relatable.
425                 Ok(t)
426             }
427             _ => {
428                 relate::super_relate_tys(self, t, t)
429             }
430         }
431     }
432
433     fn regions(&mut self, r: ty::Region<'tcx>, r2: ty::Region<'tcx>)
434                -> RelateResult<'tcx, ty::Region<'tcx>> {
435         assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
436
437         match *r {
438             // Never make variables for regions bound within the type itself,
439             // nor for erased regions.
440             ty::ReLateBound(..) |
441             ty::ReErased => {
442                 return Ok(r);
443             }
444
445             // Always make a fresh region variable for skolemized regions;
446             // the higher-ranked decision procedures rely on this.
447             ty::ReSkolemized(..) => { }
448
449             // For anything else, we make a region variable, unless we
450             // are *equating*, in which case it's just wasteful.
451             ty::ReEmpty |
452             ty::ReStatic |
453             ty::ReScope(..) |
454             ty::ReVar(..) |
455             ty::ReEarlyBound(..) |
456             ty::ReFree(..) => {
457                 match self.ambient_variance {
458                     ty::Invariant => return Ok(r),
459                     ty::Bivariant | ty::Covariant | ty::Contravariant => (),
460                 }
461             }
462         }
463
464         // FIXME: This is non-ideal because we don't give a
465         // very descriptive origin for this region variable.
466         Ok(self.infcx.next_region_var(MiscVariable(self.span)))
467     }
468 }
469
470 pub trait RelateResultCompare<'tcx, T> {
471     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
472         F: FnOnce() -> TypeError<'tcx>;
473 }
474
475 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
476     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
477         F: FnOnce() -> TypeError<'tcx>,
478     {
479         self.clone().and_then(|s| {
480             if s == t {
481                 self.clone()
482             } else {
483                 Err(f())
484             }
485         })
486     }
487 }
488
489 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
490                                -> TypeError<'tcx>
491 {
492     let (a, b) = v;
493     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
494 }
495
496 fn float_unification_error<'tcx>(a_is_expected: bool,
497                                  v: (ast::FloatTy, ast::FloatTy))
498                                  -> TypeError<'tcx>
499 {
500     let (a, b) = v;
501     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
502 }