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