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