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