]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/combine.rs
Rollup merge of #61554 - spastorino:change_visit_api, r=oli-obk
[rust.git] / src / librustc / infer / combine.rs
1 ///////////////////////////////////////////////////////////////////////////
2 // # Type combining
3 //
4 // There are four type combiners: equate, sub, lub, and glb.  Each
5 // implements the trait `Combine` and contains methods for combining
6 // two instances of various things and yielding a new instance.  These
7 // combiner methods always yield a `Result<T>`.  There is a lot of
8 // common code for these operations, implemented as default methods on
9 // the `Combine` trait.
10 //
11 // Each operation may have side-effects on the inference context,
12 // though these can be unrolled using snapshots. On success, the
13 // LUB/GLB operations return the appropriate bound. The Eq and Sub
14 // operations generally return the first operand.
15 //
16 // ## Contravariance
17 //
18 // When you are relating two things which have a contravariant
19 // relationship, you should use `contratys()` or `contraregions()`,
20 // rather than inversing the order of arguments!  This is necessary
21 // because the order of arguments is not relevant for LUB and GLB.  It
22 // is also useful to track which value is the "expected" value in
23 // terms of error reporting.
24
25 use super::equate::Equate;
26 use super::glb::Glb;
27 use super::{InferCtxt, MiscVariable, TypeTrace};
28 use super::lub::Lub;
29 use super::sub::Sub;
30 use super::type_variable::TypeVariableValue;
31 use super::unify_key::{ConstVarValue, ConstVariableValue};
32 use super::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
33
34 use crate::hir::def_id::DefId;
35 use crate::mir::interpret::ConstValue;
36 use crate::ty::{IntType, UintType};
37 use crate::ty::{self, Ty, TyCtxt, InferConst};
38 use crate::ty::error::TypeError;
39 use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
40 use crate::ty::subst::SubstsRef;
41 use crate::traits::{Obligation, PredicateObligations};
42
43 use syntax::ast;
44 use syntax_pos::{Span, DUMMY_SP};
45
46 #[derive(Clone)]
47 pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
48     pub infcx: &'infcx InferCtxt<'infcx, 'gcx, 'tcx>,
49     pub trace: TypeTrace<'tcx>,
50     pub cause: Option<ty::relate::Cause>,
51     pub param_env: ty::ParamEnv<'tcx>,
52     pub obligations: PredicateObligations<'tcx>,
53 }
54
55 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
56 pub enum RelationDir {
57     SubtypeOf, SupertypeOf, EqTo
58 }
59
60 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
61     pub fn super_combine_tys<R>(&self,
62                                 relation: &mut R,
63                                 a: Ty<'tcx>,
64                                 b: Ty<'tcx>)
65                                 -> RelateResult<'tcx, Ty<'tcx>>
66         where R: TypeRelation<'infcx, 'gcx, 'tcx>
67     {
68         let a_is_expected = relation.a_is_expected();
69
70         match (&a.sty, &b.sty) {
71             // Relate integral variables to other types
72             (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => {
73                 self.int_unification_table
74                     .borrow_mut()
75                     .unify_var_var(a_id, b_id)
76                     .map_err(|e| int_unification_error(a_is_expected, e))?;
77                 Ok(a)
78             }
79             (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
80                 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
81             }
82             (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
83                 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
84             }
85             (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
86                 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
87             }
88             (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
89                 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
90             }
91
92             // Relate floating-point variables to other types
93             (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
94                 self.float_unification_table
95                     .borrow_mut()
96                     .unify_var_var(a_id, b_id)
97                     .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
98                 Ok(a)
99             }
100             (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
101                 self.unify_float_variable(a_is_expected, v_id, v)
102             }
103             (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
104                 self.unify_float_variable(!a_is_expected, v_id, v)
105             }
106
107             // All other cases of inference are errors
108             (&ty::Infer(_), _) |
109             (_, &ty::Infer(_)) => {
110                 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
111             }
112
113             _ => {
114                 ty::relate::super_relate_tys(relation, a, b)
115             }
116         }
117     }
118
119     pub fn super_combine_consts<R>(
120         &self,
121         relation: &mut R,
122         a: &'tcx ty::Const<'tcx>,
123         b: &'tcx ty::Const<'tcx>,
124     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>
125     where
126         R: TypeRelation<'infcx, 'gcx, 'tcx>,
127     {
128         let a_is_expected = relation.a_is_expected();
129
130         match (a.val, b.val) {
131             (ConstValue::Infer(InferConst::Var(a_vid)),
132                 ConstValue::Infer(InferConst::Var(b_vid))) => {
133                 self.const_unification_table
134                     .borrow_mut()
135                     .unify_var_var(a_vid, b_vid)
136                     .map_err(|e| const_unification_error(a_is_expected, e))?;
137                 return Ok(a);
138             }
139
140             // All other cases of inference with other variables are errors.
141             (ConstValue::Infer(InferConst::Var(_)), ConstValue::Infer(_)) |
142             (ConstValue::Infer(_), ConstValue::Infer(InferConst::Var(_))) => {
143                 bug!("tried to combine ConstValue::Infer/ConstValue::Infer(InferConst::Var)")
144             }
145
146             (ConstValue::Infer(InferConst::Var(vid)), _) => {
147                 return self.unify_const_variable(a_is_expected, vid, b);
148             }
149
150             (_, ConstValue::Infer(InferConst::Var(vid))) => {
151                 return self.unify_const_variable(!a_is_expected, vid, a);
152             }
153
154             _ => {}
155         }
156
157         ty::relate::super_relate_consts(relation, a, b)
158     }
159
160     pub fn unify_const_variable(
161         &self,
162         vid_is_expected: bool,
163         vid: ty::ConstVid<'tcx>,
164         value: &'tcx ty::Const<'tcx>,
165     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
166         self.const_unification_table
167             .borrow_mut()
168             .unify_var_value(vid, ConstVarValue {
169                 origin: ConstVariableOrigin {
170                     kind: ConstVariableOriginKind::ConstInference,
171                     span: DUMMY_SP,
172                 },
173                 val: ConstVariableValue::Known { value },
174             })
175             .map_err(|e| const_unification_error(vid_is_expected, e))?;
176         Ok(value)
177     }
178
179     fn unify_integral_variable(&self,
180                                vid_is_expected: bool,
181                                vid: ty::IntVid,
182                                val: ty::IntVarValue)
183                                -> RelateResult<'tcx, Ty<'tcx>>
184     {
185         self.int_unification_table
186             .borrow_mut()
187             .unify_var_value(vid, Some(val))
188             .map_err(|e| int_unification_error(vid_is_expected, e))?;
189         match val {
190             IntType(v) => Ok(self.tcx.mk_mach_int(v)),
191             UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
192         }
193     }
194
195     fn unify_float_variable(&self,
196                             vid_is_expected: bool,
197                             vid: ty::FloatVid,
198                             val: ast::FloatTy)
199                             -> RelateResult<'tcx, Ty<'tcx>>
200     {
201         self.float_unification_table
202             .borrow_mut()
203             .unify_var_value(vid, Some(ty::FloatVarValue(val)))
204             .map_err(|e| float_unification_error(vid_is_expected, e))?;
205         Ok(self.tcx.mk_mach_float(val))
206     }
207 }
208
209 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
210     pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
211         self.infcx.tcx
212     }
213
214     pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
215         Equate::new(self, a_is_expected)
216     }
217
218     pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
219         Sub::new(self, a_is_expected)
220     }
221
222     pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
223         Lub::new(self, a_is_expected)
224     }
225
226     pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
227         Glb::new(self, a_is_expected)
228     }
229
230     /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
231     /// The idea is that we should ensure that the type `a_ty` is equal
232     /// to, a subtype of, or a supertype of (respectively) the type
233     /// to which `b_vid` is bound.
234     ///
235     /// Since `b_vid` has not yet been instantiated with a type, we
236     /// will first instantiate `b_vid` with a *generalized* version
237     /// of `a_ty`. Generalization introduces other inference
238     /// variables wherever subtyping could occur.
239     pub fn instantiate(&mut self,
240                        a_ty: Ty<'tcx>,
241                        dir: RelationDir,
242                        b_vid: ty::TyVid,
243                        a_is_expected: bool)
244                        -> RelateResult<'tcx, ()>
245     {
246         use self::RelationDir::*;
247
248         // Get the actual variable that b_vid has been inferred to
249         debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_unknown());
250
251         debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
252
253         // Generalize type of `a_ty` appropriately depending on the
254         // direction.  As an example, assume:
255         //
256         // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
257         //   inference variable,
258         // - and `dir` == `SubtypeOf`.
259         //
260         // Then the generalized form `b_ty` would be `&'?2 ?3`, where
261         // `'?2` and `?3` are fresh region/type inference
262         // variables. (Down below, we will relate `a_ty <: b_ty`,
263         // adding constraints like `'x: '?2` and `?1 <: ?3`.)
264         let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
265         debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
266                a_ty, dir, b_vid, b_ty);
267         self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
268
269         if needs_wf {
270             self.obligations.push(Obligation::new(self.trace.cause.clone(),
271                                                   self.param_env,
272                                                   ty::Predicate::WellFormed(b_ty)));
273         }
274
275         // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
276         //
277         // FIXME(#16847): This code is non-ideal because all these subtype
278         // relations wind up attributed to the same spans. We need
279         // to associate causes/spans with each of the relations in
280         // the stack to get this right.
281         match dir {
282             EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
283             SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
284             SupertypeOf => self.sub(a_is_expected).relate_with_variance(
285                 ty::Contravariant, &a_ty, &b_ty),
286         }?;
287
288         Ok(())
289     }
290
291     /// Attempts to generalize `ty` for the type variable `for_vid`.
292     /// This checks for cycle -- that is, whether the type `ty`
293     /// references `for_vid`. The `dir` is the "direction" for which we
294     /// a performing the generalization (i.e., are we producing a type
295     /// that can be used as a supertype etc).
296     ///
297     /// Preconditions:
298     ///
299     /// - `for_vid` is a "root vid"
300     fn generalize(&self,
301                   ty: Ty<'tcx>,
302                   for_vid: ty::TyVid,
303                   dir: RelationDir)
304                   -> RelateResult<'tcx, Generalization<'tcx>>
305     {
306         debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
307         // Determine the ambient variance within which `ty` appears.
308         // The surrounding equation is:
309         //
310         //     ty [op] ty2
311         //
312         // where `op` is either `==`, `<:`, or `:>`. This maps quite
313         // naturally.
314         let ambient_variance = match dir {
315             RelationDir::EqTo => ty::Invariant,
316             RelationDir::SubtypeOf => ty::Covariant,
317             RelationDir::SupertypeOf => ty::Contravariant,
318         };
319
320         debug!("generalize: ambient_variance = {:?}", ambient_variance);
321
322         let for_universe = match self.infcx.type_variables.borrow_mut().probe(for_vid) {
323             v @ TypeVariableValue::Known { .. } => panic!(
324                 "instantiating {:?} which has a known value {:?}",
325                 for_vid,
326                 v,
327             ),
328             TypeVariableValue::Unknown { universe } => universe,
329         };
330
331         debug!("generalize: for_universe = {:?}", for_universe);
332
333         let mut generalize = Generalizer {
334             infcx: self.infcx,
335             span: self.trace.cause.span,
336             for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
337             for_universe,
338             ambient_variance,
339             needs_wf: false,
340             root_ty: ty,
341         };
342
343         let ty = match generalize.relate(&ty, &ty) {
344             Ok(ty) => ty,
345             Err(e) => {
346                 debug!("generalize: failure {:?}", e);
347                 return Err(e);
348             }
349         };
350         let needs_wf = generalize.needs_wf;
351         debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
352         Ok(Generalization { ty, needs_wf })
353     }
354 }
355
356 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
357     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
358
359     /// The span, used when creating new type variables and things.
360     span: Span,
361
362     /// The vid of the type variable that is in the process of being
363     /// instantiated; if we find this within the type we are folding,
364     /// that means we would have created a cyclic type.
365     for_vid_sub_root: ty::TyVid,
366
367     /// The universe of the type variable that is in the process of
368     /// being instantiated. Any fresh variables that we create in this
369     /// process should be in that same universe.
370     for_universe: ty::UniverseIndex,
371
372     /// Track the variance as we descend into the type.
373     ambient_variance: ty::Variance,
374
375     /// See the field `needs_wf` in `Generalization`.
376     needs_wf: bool,
377
378     /// The root type that we are generalizing. Used when reporting cycles.
379     root_ty: Ty<'tcx>,
380 }
381
382 /// Result from a generalization operation. This includes
383 /// not only the generalized type, but also a bool flag
384 /// indicating whether further WF checks are needed.
385 struct Generalization<'tcx> {
386     ty: Ty<'tcx>,
387
388     /// If true, then the generalized type may not be well-formed,
389     /// even if the source type is well-formed, so we should add an
390     /// additional check to enforce that it is. This arises in
391     /// particular around 'bivariant' type parameters that are only
392     /// constrained by a where-clause. As an example, imagine a type:
393     ///
394     ///     struct Foo<A, B> where A: Iterator<Item = B> {
395     ///         data: A
396     ///     }
397     ///
398     /// here, `A` will be covariant, but `B` is
399     /// unconstrained. However, whatever it is, for `Foo` to be WF, it
400     /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
401     /// then after generalization we will wind up with a type like
402     /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
403     /// ?D>` (or `>:`), we will wind up with the requirement that `?A
404     /// <: ?C`, but no particular relationship between `?B` and `?D`
405     /// (after all, we do not know the variance of the normalized form
406     /// of `A::Item` with respect to `A`). If we do nothing else, this
407     /// may mean that `?D` goes unconstrained (as in #41677). So, in
408     /// this scenario where we create a new type variable in a
409     /// bivariant context, we set the `needs_wf` flag to true. This
410     /// will force the calling code to check that `WF(Foo<?C, ?D>)`
411     /// holds, which in turn implies that `?C::Item == ?D`. So once
412     /// `?C` is constrained, that should suffice to restrict `?D`.
413     needs_wf: bool,
414 }
415
416 impl<'cx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
417     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
418         self.infcx.tcx
419     }
420
421     fn tag(&self) -> &'static str {
422         "Generalizer"
423     }
424
425     fn a_is_expected(&self) -> bool {
426         true
427     }
428
429     fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
430                   -> RelateResult<'tcx, ty::Binder<T>>
431         where T: Relate<'tcx>
432     {
433         Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))
434     }
435
436     fn relate_item_substs(&mut self,
437                           item_def_id: DefId,
438                           a_subst: SubstsRef<'tcx>,
439                           b_subst: SubstsRef<'tcx>)
440                           -> RelateResult<'tcx, SubstsRef<'tcx>>
441     {
442         if self.ambient_variance == ty::Variance::Invariant {
443             // Avoid fetching the variance if we are in an invariant
444             // context; no need, and it can induce dependency cycles
445             // (e.g., #41849).
446             relate::relate_substs(self, None, a_subst, b_subst)
447         } else {
448             let opt_variances = self.tcx().variances_of(item_def_id);
449             relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
450         }
451     }
452
453     fn relate_with_variance<T: Relate<'tcx>>(&mut self,
454                                              variance: ty::Variance,
455                                              a: &T,
456                                              b: &T)
457                                              -> RelateResult<'tcx, T>
458     {
459         let old_ambient_variance = self.ambient_variance;
460         self.ambient_variance = self.ambient_variance.xform(variance);
461
462         let result = self.relate(a, b);
463         self.ambient_variance = old_ambient_variance;
464         result
465     }
466
467     fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
468         assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
469
470         debug!("generalize: t={:?}", t);
471
472         // Check to see whether the type we are generalizing references
473         // any other type variable related to `vid` via
474         // subtyping. This is basically our "occurs check", preventing
475         // us from creating infinitely sized types.
476         match t.sty {
477             ty::Infer(ty::TyVar(vid)) => {
478                 let mut variables = self.infcx.type_variables.borrow_mut();
479                 let vid = variables.root_var(vid);
480                 let sub_vid = variables.sub_root_var(vid);
481                 if sub_vid == self.for_vid_sub_root {
482                     // If sub-roots are equal, then `for_vid` and
483                     // `vid` are related via subtyping.
484                     return Err(TypeError::CyclicTy(self.root_ty));
485                 } else {
486                     match variables.probe(vid) {
487                         TypeVariableValue::Known { value: u } => {
488                             drop(variables);
489                             debug!("generalize: known value {:?}", u);
490                             self.relate(&u, &u)
491                         }
492                         TypeVariableValue::Unknown { universe } => {
493                             match self.ambient_variance {
494                                 // Invariant: no need to make a fresh type variable.
495                                 ty::Invariant => {
496                                     if self.for_universe.can_name(universe) {
497                                         return Ok(t);
498                                     }
499                                 }
500
501                                 // Bivariant: make a fresh var, but we
502                                 // may need a WF predicate. See
503                                 // comment on `needs_wf` field for
504                                 // more info.
505                                 ty::Bivariant => self.needs_wf = true,
506
507                                 // Co/contravariant: this will be
508                                 // sufficiently constrained later on.
509                                 ty::Covariant | ty::Contravariant => (),
510                             }
511
512                             let origin = *variables.var_origin(vid);
513                             let new_var_id = variables.new_var(self.for_universe, false, origin);
514                             let u = self.tcx().mk_ty_var(new_var_id);
515                             debug!("generalize: replacing original vid={:?} with new={:?}",
516                                    vid, u);
517                             return Ok(u);
518                         }
519                     }
520                 }
521             }
522             ty::Infer(ty::IntVar(_)) |
523             ty::Infer(ty::FloatVar(_)) => {
524                 // No matter what mode we are in,
525                 // integer/floating-point types must be equal to be
526                 // relatable.
527                 Ok(t)
528             }
529             _ => {
530                 relate::super_relate_tys(self, t, t)
531             }
532         }
533     }
534
535     fn regions(&mut self, r: ty::Region<'tcx>, r2: ty::Region<'tcx>)
536                -> RelateResult<'tcx, ty::Region<'tcx>> {
537         assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
538
539         debug!("generalize: regions r={:?}", r);
540
541         match *r {
542             // Never make variables for regions bound within the type itself,
543             // nor for erased regions.
544             ty::ReLateBound(..) |
545             ty::ReErased => {
546                 return Ok(r);
547             }
548
549             ty::ReClosureBound(..) => {
550                 span_bug!(
551                     self.span,
552                     "encountered unexpected ReClosureBound: {:?}",
553                     r,
554                 );
555             }
556
557             ty::RePlaceholder(..) |
558             ty::ReVar(..) |
559             ty::ReEmpty |
560             ty::ReStatic |
561             ty::ReScope(..) |
562             ty::ReEarlyBound(..) |
563             ty::ReFree(..) => {
564                 // see common code below
565             }
566         }
567
568         // If we are in an invariant context, we can re-use the region
569         // as is, unless it happens to be in some universe that we
570         // can't name. (In the case of a region *variable*, we could
571         // use it if we promoted it into our universe, but we don't
572         // bother.)
573         if let ty::Invariant = self.ambient_variance {
574             let r_universe = self.infcx.universe_of_region(r);
575             if self.for_universe.can_name(r_universe) {
576                 return Ok(r);
577             }
578         }
579
580         // FIXME: This is non-ideal because we don't give a
581         // very descriptive origin for this region variable.
582         Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
583     }
584
585     fn consts(
586         &mut self,
587         c: &'tcx ty::Const<'tcx>,
588         c2: &'tcx ty::Const<'tcx>
589     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
590         assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
591
592         match c {
593             ty::Const { val: ConstValue::Infer(InferConst::Var(vid)), .. } => {
594                 let mut variable_table = self.infcx.const_unification_table.borrow_mut();
595                 match variable_table.probe_value(*vid).val.known() {
596                     Some(u) => {
597                         self.relate(&u, &u)
598                     }
599                     None => Ok(c),
600                 }
601             }
602             _ => {
603                 relate::super_relate_consts(self, c, c)
604             }
605         }
606     }
607 }
608
609 pub trait RelateResultCompare<'tcx, T> {
610     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
611         F: FnOnce() -> TypeError<'tcx>;
612 }
613
614 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
615     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
616         F: FnOnce() -> TypeError<'tcx>,
617     {
618         self.clone().and_then(|s| {
619             if s == t {
620                 self.clone()
621             } else {
622                 Err(f())
623             }
624         })
625     }
626 }
627
628 pub fn const_unification_error<'tcx>(
629     a_is_expected: bool,
630     (a, b): (&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>),
631 ) -> TypeError<'tcx> {
632     TypeError::ConstMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
633 }
634
635 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
636                                -> TypeError<'tcx>
637 {
638     let (a, b) = v;
639     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
640 }
641
642 fn float_unification_error<'tcx>(a_is_expected: bool,
643                                  v: (ty::FloatVarValue, ty::FloatVarValue))
644                                  -> TypeError<'tcx>
645 {
646     let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
647     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
648 }