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