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