]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/combine.rs
Various minor/cosmetic improvements to code
[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::{InferCtxt, MiscVariable, TypeTrace};
38 use super::lub::Lub;
39 use super::sub::Sub;
40 use super::type_variable::TypeVariableValue;
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 param_env: ty::ParamEnv<'tcx>,
59     pub obligations: PredicateObligations<'tcx>,
60 }
61
62 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
63 pub enum RelationDir {
64     SubtypeOf, SupertypeOf, EqTo
65 }
66
67 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
68     pub fn super_combine_tys<R>(&self,
69                                 relation: &mut R,
70                                 a: Ty<'tcx>,
71                                 b: Ty<'tcx>)
72                                 -> RelateResult<'tcx, Ty<'tcx>>
73         where R: TypeRelation<'infcx, 'gcx, 'tcx>
74     {
75         let a_is_expected = relation.a_is_expected();
76
77         match (&a.sty, &b.sty) {
78             // Relate integral variables to other types
79             (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => {
80                 self.int_unification_table
81                     .borrow_mut()
82                     .unify_var_var(a_id, b_id)
83                     .map_err(|e| int_unification_error(a_is_expected, e))?;
84                 Ok(a)
85             }
86             (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
87                 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
88             }
89             (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
90                 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
91             }
92             (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
93                 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
94             }
95             (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
96                 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
97             }
98
99             // Relate floating-point variables to other types
100             (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
101                 self.float_unification_table
102                     .borrow_mut()
103                     .unify_var_var(a_id, b_id)
104                     .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
105                 Ok(a)
106             }
107             (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
108                 self.unify_float_variable(a_is_expected, v_id, v)
109             }
110             (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
111                 self.unify_float_variable(!a_is_expected, v_id, v)
112             }
113
114             // All other cases of inference are errors
115             (&ty::Infer(_), _) |
116             (_, &ty::Infer(_)) => {
117                 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
118             }
119
120
121             _ => {
122                 ty::relate::super_relate_tys(relation, a, b)
123             }
124         }
125     }
126
127     fn unify_integral_variable(&self,
128                                vid_is_expected: bool,
129                                vid: ty::IntVid,
130                                val: ty::IntVarValue)
131                                -> RelateResult<'tcx, Ty<'tcx>>
132     {
133         self.int_unification_table
134             .borrow_mut()
135             .unify_var_value(vid, Some(val))
136             .map_err(|e| int_unification_error(vid_is_expected, e))?;
137         match val {
138             IntType(v) => Ok(self.tcx.mk_mach_int(v)),
139             UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
140         }
141     }
142
143     fn unify_float_variable(&self,
144                             vid_is_expected: bool,
145                             vid: ty::FloatVid,
146                             val: ast::FloatTy)
147                             -> RelateResult<'tcx, Ty<'tcx>>
148     {
149         self.float_unification_table
150             .borrow_mut()
151             .unify_var_value(vid, Some(ty::FloatVarValue(val)))
152             .map_err(|e| float_unification_error(vid_is_expected, e))?;
153         Ok(self.tcx.mk_mach_float(val))
154     }
155 }
156
157 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
158     pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
159         self.infcx.tcx
160     }
161
162     pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
163         Equate::new(self, a_is_expected)
164     }
165
166     pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
167         Sub::new(self, a_is_expected)
168     }
169
170     pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
171         Lub::new(self, a_is_expected)
172     }
173
174     pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
175         Glb::new(self, a_is_expected)
176     }
177
178     /// Here dir is either EqTo, SubtypeOf, or SupertypeOf. The
179     /// idea is that we should ensure that the type `a_ty` is equal
180     /// to, a subtype of, or a supertype of (respectively) the type
181     /// to which `b_vid` is bound.
182     ///
183     /// Since `b_vid` has not yet been instantiated with a type, we
184     /// will first instantiate `b_vid` with a *generalized* version
185     /// of `a_ty`. Generalization introduces other inference
186     /// variables wherever subtyping could occur.
187     pub fn instantiate(&mut self,
188                        a_ty: Ty<'tcx>,
189                        dir: RelationDir,
190                        b_vid: ty::TyVid,
191                        a_is_expected: bool)
192                        -> RelateResult<'tcx, ()>
193     {
194         use self::RelationDir::*;
195
196         // Get the actual variable that b_vid has been inferred to
197         debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_unknown());
198
199         debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
200
201         // Generalize type of `a_ty` appropriately depending on the
202         // direction.  As an example, assume:
203         //
204         // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
205         //   inference variable,
206         // - and `dir` == `SubtypeOf`.
207         //
208         // Then the generalized form `b_ty` would be `&'?2 ?3`, where
209         // `'?2` and `?3` are fresh region/type inference
210         // variables. (Down below, we will relate `a_ty <: b_ty`,
211         // adding constraints like `'x: '?2` and `?1 <: ?3`.)
212         let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
213         debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
214                a_ty, dir, b_vid, b_ty);
215         self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
216
217         if needs_wf {
218             self.obligations.push(Obligation::new(self.trace.cause.clone(),
219                                                   self.param_env,
220                                                   ty::Predicate::WellFormed(b_ty)));
221         }
222
223         // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
224         //
225         // FIXME(#16847): This code is non-ideal because all these subtype
226         // relations wind up attributed to the same spans. We need
227         // to associate causes/spans with each of the relations in
228         // the stack to get this right.
229         match dir {
230             EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
231             SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
232             SupertypeOf => self.sub(a_is_expected).relate_with_variance(
233                 ty::Contravariant, &a_ty, &b_ty),
234         }?;
235
236         Ok(())
237     }
238
239     /// Attempts to generalize `ty` for the type variable `for_vid`.
240     /// This checks for cycle -- that is, whether the type `ty`
241     /// references `for_vid`. The `dir` is the "direction" for which we
242     /// a performing the generalization (i.e., are we producing a type
243     /// that can be used as a supertype etc).
244     ///
245     /// Preconditions:
246     ///
247     /// - `for_vid` is a "root vid"
248     fn generalize(&self,
249                   ty: Ty<'tcx>,
250                   for_vid: ty::TyVid,
251                   dir: RelationDir)
252                   -> RelateResult<'tcx, Generalization<'tcx>>
253     {
254         debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
255         // Determine the ambient variance within which `ty` appears.
256         // The surrounding equation is:
257         //
258         //     ty [op] ty2
259         //
260         // where `op` is either `==`, `<:`, or `:>`. This maps quite
261         // naturally.
262         let ambient_variance = match dir {
263             RelationDir::EqTo => ty::Invariant,
264             RelationDir::SubtypeOf => ty::Covariant,
265             RelationDir::SupertypeOf => ty::Contravariant,
266         };
267
268         let mut generalize = Generalizer {
269             infcx: self.infcx,
270             span: self.trace.cause.span,
271             for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
272             ambient_variance,
273             needs_wf: false,
274             root_ty: ty,
275         };
276
277         let ty = match generalize.relate(&ty, &ty) {
278             Ok(ty) => ty,
279             Err(e) => {
280                 debug!("generalize: failure {:?}", e);
281                 return Err(e);
282             }
283         };
284         let needs_wf = generalize.needs_wf;
285         debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
286         Ok(Generalization { ty, needs_wf })
287     }
288 }
289
290 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
291     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
292
293     /// Span, used when creating new type variables and things.
294     span: Span,
295
296     /// The vid of the type variable that is in the process of being
297     /// instantiated; if we find this within the type we are folding,
298     /// that means we would have created a cyclic type.
299     for_vid_sub_root: ty::TyVid,
300
301     /// Track the variance as we descend into the type.
302     ambient_variance: ty::Variance,
303
304     /// See the field `needs_wf` in `Generalization`.
305     needs_wf: bool,
306
307     /// The root type that we are generalizing. Used when reporting cycles.
308     root_ty: Ty<'tcx>,
309 }
310
311 /// Result from a generalization operation. This includes
312 /// not only the generalized type, but also a bool flag
313 /// indicating whether further WF checks are needed.
314 struct Generalization<'tcx> {
315     ty: Ty<'tcx>,
316
317     /// If true, then the generalized type may not be well-formed,
318     /// even if the source type is well-formed, so we should add an
319     /// additional check to enforce that it is. This arises in
320     /// particular around 'bivariant' type parameters that are only
321     /// constrained by a where-clause. As an example, imagine a type:
322     ///
323     ///     struct Foo<A, B> where A: Iterator<Item=B> {
324     ///         data: A
325     ///     }
326     ///
327     /// here, `A` will be covariant, but `B` is
328     /// unconstrained. However, whatever it is, for `Foo` to be WF, it
329     /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
330     /// then after generalization we will wind up with a type like
331     /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
332     /// ?D>` (or `>:`), we will wind up with the requirement that `?A
333     /// <: ?C`, but no particular relationship between `?B` and `?D`
334     /// (after all, we do not know the variance of the normalized form
335     /// of `A::Item` with respect to `A`). If we do nothing else, this
336     /// may mean that `?D` goes unconstrained (as in #41677).  So, in
337     /// this scenario where we create a new type variable in a
338     /// bivariant context, we set the `needs_wf` flag to true. This
339     /// will force the calling code to check that `WF(Foo<?C, ?D>)`
340     /// holds, which in turn implies that `?C::Item == ?D`. So once
341     /// `?C` is constrained, that should suffice to restrict `?D`.
342     needs_wf: bool,
343 }
344
345 impl<'cx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
346     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
347         self.infcx.tcx
348     }
349
350     fn tag(&self) -> &'static str {
351         "Generalizer"
352     }
353
354     fn a_is_expected(&self) -> bool {
355         true
356     }
357
358     fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
359                   -> RelateResult<'tcx, ty::Binder<T>>
360         where T: Relate<'tcx>
361     {
362         Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))
363     }
364
365     fn relate_item_substs(&mut self,
366                           item_def_id: DefId,
367                           a_subst: &'tcx Substs<'tcx>,
368                           b_subst: &'tcx Substs<'tcx>)
369                           -> RelateResult<'tcx, &'tcx Substs<'tcx>>
370     {
371         if self.ambient_variance == ty::Variance::Invariant {
372             // Avoid fetching the variance if we are in an invariant
373             // context; no need, and it can induce dependency cycles
374             // (e.g., #41849).
375             relate::relate_substs(self, None, a_subst, b_subst)
376         } else {
377             let opt_variances = self.tcx().variances_of(item_def_id);
378             relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
379         }
380     }
381
382     fn relate_with_variance<T: Relate<'tcx>>(&mut self,
383                                              variance: ty::Variance,
384                                              a: &T,
385                                              b: &T)
386                                              -> RelateResult<'tcx, T>
387     {
388         let old_ambient_variance = self.ambient_variance;
389         self.ambient_variance = self.ambient_variance.xform(variance);
390
391         let result = self.relate(a, b);
392         self.ambient_variance = old_ambient_variance;
393         result
394     }
395
396     fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
397         assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
398
399         // Check to see whether the type we are genealizing references
400         // any other type variable related to `vid` via
401         // subtyping. This is basically our "occurs check", preventing
402         // us from creating infinitely sized types.
403         match t.sty {
404             ty::Infer(ty::TyVar(vid)) => {
405                 let mut variables = self.infcx.type_variables.borrow_mut();
406                 let vid = variables.root_var(vid);
407                 let sub_vid = variables.sub_root_var(vid);
408                 if sub_vid == self.for_vid_sub_root {
409                     // If sub-roots are equal, then `for_vid` and
410                     // `vid` are related via subtyping.
411                     return Err(TypeError::CyclicTy(self.root_ty));
412                 } else {
413                     match variables.probe(vid) {
414                         TypeVariableValue::Known { value: u } => {
415                             drop(variables);
416                             self.relate(&u, &u)
417                         }
418                         TypeVariableValue::Unknown { universe } => {
419                             match self.ambient_variance {
420                                 // Invariant: no need to make a fresh type variable.
421                                 ty::Invariant => return Ok(t),
422
423                                 // Bivariant: make a fresh var, but we
424                                 // may need a WF predicate. See
425                                 // comment on `needs_wf` field for
426                                 // more info.
427                                 ty::Bivariant => self.needs_wf = true,
428
429                                 // Co/contravariant: this will be
430                                 // sufficiently constrained later on.
431                                 ty::Covariant | ty::Contravariant => (),
432                             }
433
434                             let origin = *variables.var_origin(vid);
435                             let new_var_id = variables.new_var(universe, false, origin);
436                             let u = self.tcx().mk_var(new_var_id);
437                             debug!("generalize: replacing original vid={:?} with new={:?}",
438                                    vid, u);
439                             return Ok(u);
440                         }
441                     }
442                 }
443             }
444             ty::Infer(ty::IntVar(_)) |
445             ty::Infer(ty::FloatVar(_)) => {
446                 // No matter what mode we are in,
447                 // integer/floating-point types must be equal to be
448                 // relatable.
449                 Ok(t)
450             }
451             _ => {
452                 relate::super_relate_tys(self, t, t)
453             }
454         }
455     }
456
457     fn regions(&mut self, r: ty::Region<'tcx>, r2: ty::Region<'tcx>)
458                -> RelateResult<'tcx, ty::Region<'tcx>> {
459         assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
460
461         match *r {
462             // Never make variables for regions bound within the type itself,
463             // nor for erased regions.
464             ty::ReLateBound(..) |
465             ty::ReErased => {
466                 return Ok(r);
467             }
468
469             // Always make a fresh region variable for placeholder
470             // regions; the higher-ranked decision procedures rely on
471             // this.
472             ty::RePlaceholder(..) => { }
473
474             // For anything else, we make a region variable, unless we
475             // are *equating*, in which case it's just wasteful.
476             ty::ReEmpty |
477             ty::ReStatic |
478             ty::ReScope(..) |
479             ty::ReVar(..) |
480             ty::ReEarlyBound(..) |
481             ty::ReFree(..) => {
482                 match self.ambient_variance {
483                     ty::Invariant => return Ok(r),
484                     ty::Bivariant | ty::Covariant | ty::Contravariant => (),
485                 }
486             }
487
488             ty::ReClosureBound(..) => {
489                 span_bug!(
490                     self.span,
491                     "encountered unexpected ReClosureBound: {:?}",
492                     r,
493                 );
494             }
495         }
496
497         // FIXME: This is non-ideal because we don't give a
498         // very descriptive origin for this region variable.
499         Ok(self.infcx.next_region_var(MiscVariable(self.span)))
500     }
501 }
502
503 pub trait RelateResultCompare<'tcx, T> {
504     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
505         F: FnOnce() -> TypeError<'tcx>;
506 }
507
508 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
509     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
510         F: FnOnce() -> TypeError<'tcx>,
511     {
512         self.clone().and_then(|s| {
513             if s == t {
514                 self.clone()
515             } else {
516                 Err(f())
517             }
518         })
519     }
520 }
521
522 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
523                                -> TypeError<'tcx>
524 {
525     let (a, b) = v;
526     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
527 }
528
529 fn float_unification_error<'tcx>(a_is_expected: bool,
530                                  v: (ty::FloatVarValue, ty::FloatVarValue))
531                                  -> TypeError<'tcx>
532 {
533     let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
534     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
535 }