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