]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/combine.rs
combine: stop eagerly evaluating consts
[rust.git] / compiler / rustc_infer / src / 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_data_structures::sso::SsoHashMap;
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::{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(relation.param_env(), vid, b, a_is_expected);
163             }
164
165             (_, ty::ConstKind::Infer(InferConst::Var(vid))) => {
166                 return self.unify_const_variable(relation.param_env(), vid, a, !a_is_expected);
167             }
168             (ty::ConstKind::Unevaluated(..), _) if self.tcx.lazy_normalization() => {
169                 // FIXME(#59490): Need to remove the leak check to accommodate
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 accommodate
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     /// Unifies the const variable `target_vid` with the given constant.
191     ///
192     /// This also tests if the given const `ct` contains an inference variable which was previously
193     /// unioned with `target_vid`. If this is the case, inferring `target_vid` to `ct`
194     /// would result in an infinite type as we continously replace an inference variable
195     /// in `ct` with `ct` itself.
196     ///
197     /// This is especially important as unevaluated consts use their parents generics.
198     /// They therefore often contain unused substs, making these errors far more likely.
199     ///
200     /// A good example of this is the following:
201     ///
202     /// ```rust
203     /// #![feature(const_generics)]
204     ///
205     /// fn bind<const N: usize>(value: [u8; N]) -> [u8; 3 + 4] {
206     ///     todo!()
207     /// }
208     ///
209     /// fn main() {
210     ///     let mut arr = Default::default();
211     ///     arr = bind(arr);
212     /// }
213     /// ```
214     ///
215     /// Here `3 + 4` ends up as `ConstKind::Unevaluated` which uses the generics
216     /// of `fn bind` (meaning that its substs contain `N`).
217     ///
218     /// `bind(arr)` now infers that the type of `arr` must be `[u8; N]`.
219     /// The assignment `arr = bind(arr)` now tries to equate `N` with `3 + 4`.
220     ///
221     /// As `3 + 4` contains `N` in its substs, this must not succeed.
222     ///
223     /// See `src/test/ui/const-generics/occurs-check/` for more examples where this is relevant.
224     #[instrument(level = "debug", skip(self))]
225     fn unify_const_variable(
226         &self,
227         param_env: ty::ParamEnv<'tcx>,
228         target_vid: ty::ConstVid<'tcx>,
229         ct: &'tcx ty::Const<'tcx>,
230         vid_is_expected: bool,
231     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
232         let (for_universe, span) = {
233             let mut inner = self.inner.borrow_mut();
234             let variable_table = &mut inner.const_unification_table();
235             let var_value = variable_table.probe_value(target_vid);
236             match var_value.val {
237                 ConstVariableValue::Known { value } => {
238                     bug!("instantiating {:?} which has a known value {:?}", target_vid, value)
239                 }
240                 ConstVariableValue::Unknown { universe } => (universe, var_value.origin.span),
241             }
242         };
243         let value = ConstInferUnifier { infcx: self, span, param_env, for_universe, target_vid }
244             .relate(ct, ct)?;
245
246         self.inner
247             .borrow_mut()
248             .const_unification_table()
249             .unify_var_value(
250                 target_vid,
251                 ConstVarValue {
252                     origin: ConstVariableOrigin {
253                         kind: ConstVariableOriginKind::ConstInference,
254                         span: DUMMY_SP,
255                     },
256                     val: ConstVariableValue::Known { value },
257                 },
258             )
259             .map(|()| value)
260             .map_err(|e| const_unification_error(vid_is_expected, e))
261     }
262
263     fn unify_integral_variable(
264         &self,
265         vid_is_expected: bool,
266         vid: ty::IntVid,
267         val: ty::IntVarValue,
268     ) -> RelateResult<'tcx, Ty<'tcx>> {
269         self.inner
270             .borrow_mut()
271             .int_unification_table()
272             .unify_var_value(vid, Some(val))
273             .map_err(|e| int_unification_error(vid_is_expected, e))?;
274         match val {
275             IntType(v) => Ok(self.tcx.mk_mach_int(v)),
276             UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
277         }
278     }
279
280     fn unify_float_variable(
281         &self,
282         vid_is_expected: bool,
283         vid: ty::FloatVid,
284         val: ty::FloatTy,
285     ) -> RelateResult<'tcx, Ty<'tcx>> {
286         self.inner
287             .borrow_mut()
288             .float_unification_table()
289             .unify_var_value(vid, Some(ty::FloatVarValue(val)))
290             .map_err(|e| float_unification_error(vid_is_expected, e))?;
291         Ok(self.tcx.mk_mach_float(val))
292     }
293 }
294
295 impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
296     pub fn tcx(&self) -> TyCtxt<'tcx> {
297         self.infcx.tcx
298     }
299
300     pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'tcx> {
301         Equate::new(self, a_is_expected)
302     }
303
304     pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'tcx> {
305         Sub::new(self, a_is_expected)
306     }
307
308     pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'tcx> {
309         Lub::new(self, a_is_expected)
310     }
311
312     pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'tcx> {
313         Glb::new(self, a_is_expected)
314     }
315
316     /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
317     /// The idea is that we should ensure that the type `a_ty` is equal
318     /// to, a subtype of, or a supertype of (respectively) the type
319     /// to which `b_vid` is bound.
320     ///
321     /// Since `b_vid` has not yet been instantiated with a type, we
322     /// will first instantiate `b_vid` with a *generalized* version
323     /// of `a_ty`. Generalization introduces other inference
324     /// variables wherever subtyping could occur.
325     pub fn instantiate(
326         &mut self,
327         a_ty: Ty<'tcx>,
328         dir: RelationDir,
329         b_vid: ty::TyVid,
330         a_is_expected: bool,
331     ) -> RelateResult<'tcx, ()> {
332         use self::RelationDir::*;
333
334         // Get the actual variable that b_vid has been inferred to
335         debug_assert!(self.infcx.inner.borrow_mut().type_variables().probe(b_vid).is_unknown());
336
337         debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
338
339         // Generalize type of `a_ty` appropriately depending on the
340         // direction.  As an example, assume:
341         //
342         // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
343         //   inference variable,
344         // - and `dir` == `SubtypeOf`.
345         //
346         // Then the generalized form `b_ty` would be `&'?2 ?3`, where
347         // `'?2` and `?3` are fresh region/type inference
348         // variables. (Down below, we will relate `a_ty <: b_ty`,
349         // adding constraints like `'x: '?2` and `?1 <: ?3`.)
350         let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
351         debug!(
352             "instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
353             a_ty, dir, b_vid, b_ty
354         );
355         self.infcx.inner.borrow_mut().type_variables().instantiate(b_vid, b_ty);
356
357         if needs_wf {
358             self.obligations.push(Obligation::new(
359                 self.trace.cause.clone(),
360                 self.param_env,
361                 ty::PredicateKind::WellFormed(b_ty.into()).to_predicate(self.infcx.tcx),
362             ));
363         }
364
365         // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
366         //
367         // FIXME(#16847): This code is non-ideal because all these subtype
368         // relations wind up attributed to the same spans. We need
369         // to associate causes/spans with each of the relations in
370         // the stack to get this right.
371         match dir {
372             EqTo => self.equate(a_is_expected).relate(a_ty, b_ty),
373             SubtypeOf => self.sub(a_is_expected).relate(a_ty, b_ty),
374             SupertypeOf => {
375                 self.sub(a_is_expected).relate_with_variance(ty::Contravariant, a_ty, b_ty)
376             }
377         }?;
378
379         Ok(())
380     }
381
382     /// Attempts to generalize `ty` for the type variable `for_vid`.
383     /// This checks for cycle -- that is, whether the type `ty`
384     /// references `for_vid`. The `dir` is the "direction" for which we
385     /// a performing the generalization (i.e., are we producing a type
386     /// that can be used as a supertype etc).
387     ///
388     /// Preconditions:
389     ///
390     /// - `for_vid` is a "root vid"
391     fn generalize(
392         &self,
393         ty: Ty<'tcx>,
394         for_vid: ty::TyVid,
395         dir: RelationDir,
396     ) -> RelateResult<'tcx, Generalization<'tcx>> {
397         debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
398         // Determine the ambient variance within which `ty` appears.
399         // The surrounding equation is:
400         //
401         //     ty [op] ty2
402         //
403         // where `op` is either `==`, `<:`, or `:>`. This maps quite
404         // naturally.
405         let ambient_variance = match dir {
406             RelationDir::EqTo => ty::Invariant,
407             RelationDir::SubtypeOf => ty::Covariant,
408             RelationDir::SupertypeOf => ty::Contravariant,
409         };
410
411         debug!("generalize: ambient_variance = {:?}", ambient_variance);
412
413         let for_universe = match self.infcx.inner.borrow_mut().type_variables().probe(for_vid) {
414             v @ TypeVariableValue::Known { .. } => {
415                 bug!("instantiating {:?} which has a known value {:?}", for_vid, v,)
416             }
417             TypeVariableValue::Unknown { universe } => universe,
418         };
419
420         debug!("generalize: for_universe = {:?}", for_universe);
421         debug!("generalize: trace = {:?}", self.trace);
422
423         let mut generalize = Generalizer {
424             infcx: self.infcx,
425             cause: &self.trace.cause,
426             for_vid_sub_root: self.infcx.inner.borrow_mut().type_variables().sub_root_var(for_vid),
427             for_universe,
428             ambient_variance,
429             needs_wf: false,
430             root_ty: ty,
431             param_env: self.param_env,
432             cache: SsoHashMap::new(),
433         };
434
435         let ty = match generalize.relate(ty, ty) {
436             Ok(ty) => ty,
437             Err(e) => {
438                 debug!("generalize: failure {:?}", e);
439                 return Err(e);
440             }
441         };
442         let needs_wf = generalize.needs_wf;
443         debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
444         Ok(Generalization { ty, needs_wf })
445     }
446
447     pub fn add_const_equate_obligation(
448         &mut self,
449         a_is_expected: bool,
450         a: &'tcx ty::Const<'tcx>,
451         b: &'tcx ty::Const<'tcx>,
452     ) {
453         let predicate = if a_is_expected {
454             ty::PredicateKind::ConstEquate(a, b)
455         } else {
456             ty::PredicateKind::ConstEquate(b, a)
457         };
458         self.obligations.push(Obligation::new(
459             self.trace.cause.clone(),
460             self.param_env,
461             predicate.to_predicate(self.tcx()),
462         ));
463     }
464 }
465
466 struct Generalizer<'cx, 'tcx> {
467     infcx: &'cx InferCtxt<'cx, 'tcx>,
468
469     /// The span, used when creating new type variables and things.
470     cause: &'cx ObligationCause<'tcx>,
471
472     /// The vid of the type variable that is in the process of being
473     /// instantiated; if we find this within the type we are folding,
474     /// that means we would have created a cyclic type.
475     for_vid_sub_root: ty::TyVid,
476
477     /// The universe of the type variable that is in the process of
478     /// being instantiated. Any fresh variables that we create in this
479     /// process should be in that same universe.
480     for_universe: ty::UniverseIndex,
481
482     /// Track the variance as we descend into the type.
483     ambient_variance: ty::Variance,
484
485     /// See the field `needs_wf` in `Generalization`.
486     needs_wf: bool,
487
488     /// The root type that we are generalizing. Used when reporting cycles.
489     root_ty: Ty<'tcx>,
490
491     param_env: ty::ParamEnv<'tcx>,
492
493     cache: SsoHashMap<Ty<'tcx>, RelateResult<'tcx, Ty<'tcx>>>,
494 }
495
496 /// Result from a generalization operation. This includes
497 /// not only the generalized type, but also a bool flag
498 /// indicating whether further WF checks are needed.
499 struct Generalization<'tcx> {
500     ty: Ty<'tcx>,
501
502     /// If true, then the generalized type may not be well-formed,
503     /// even if the source type is well-formed, so we should add an
504     /// additional check to enforce that it is. This arises in
505     /// particular around 'bivariant' type parameters that are only
506     /// constrained by a where-clause. As an example, imagine a type:
507     ///
508     ///     struct Foo<A, B> where A: Iterator<Item = B> {
509     ///         data: A
510     ///     }
511     ///
512     /// here, `A` will be covariant, but `B` is
513     /// unconstrained. However, whatever it is, for `Foo` to be WF, it
514     /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
515     /// then after generalization we will wind up with a type like
516     /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
517     /// ?D>` (or `>:`), we will wind up with the requirement that `?A
518     /// <: ?C`, but no particular relationship between `?B` and `?D`
519     /// (after all, we do not know the variance of the normalized form
520     /// of `A::Item` with respect to `A`). If we do nothing else, this
521     /// may mean that `?D` goes unconstrained (as in #41677). So, in
522     /// this scenario where we create a new type variable in a
523     /// bivariant context, we set the `needs_wf` flag to true. This
524     /// will force the calling code to check that `WF(Foo<?C, ?D>)`
525     /// holds, which in turn implies that `?C::Item == ?D`. So once
526     /// `?C` is constrained, that should suffice to restrict `?D`.
527     needs_wf: bool,
528 }
529
530 impl TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
531     fn tcx(&self) -> TyCtxt<'tcx> {
532         self.infcx.tcx
533     }
534     fn param_env(&self) -> ty::ParamEnv<'tcx> {
535         self.param_env
536     }
537
538     fn tag(&self) -> &'static str {
539         "Generalizer"
540     }
541
542     fn a_is_expected(&self) -> bool {
543         true
544     }
545
546     fn binders<T>(
547         &mut self,
548         a: ty::Binder<T>,
549         b: ty::Binder<T>,
550     ) -> RelateResult<'tcx, ty::Binder<T>>
551     where
552         T: Relate<'tcx>,
553     {
554         Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
555     }
556
557     fn relate_item_substs(
558         &mut self,
559         item_def_id: DefId,
560         a_subst: SubstsRef<'tcx>,
561         b_subst: SubstsRef<'tcx>,
562     ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
563         if self.ambient_variance == ty::Variance::Invariant {
564             // Avoid fetching the variance if we are in an invariant
565             // context; no need, and it can induce dependency cycles
566             // (e.g., #41849).
567             relate::relate_substs(self, None, a_subst, b_subst)
568         } else {
569             let opt_variances = self.tcx().variances_of(item_def_id);
570             relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
571         }
572     }
573
574     fn relate_with_variance<T: Relate<'tcx>>(
575         &mut self,
576         variance: ty::Variance,
577         a: T,
578         b: T,
579     ) -> RelateResult<'tcx, T> {
580         let old_ambient_variance = self.ambient_variance;
581         self.ambient_variance = self.ambient_variance.xform(variance);
582
583         let result = self.relate(a, b);
584         self.ambient_variance = old_ambient_variance;
585         result
586     }
587
588     fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
589         assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
590
591         if let Some(result) = self.cache.get(&t) {
592             return result.clone();
593         }
594         debug!("generalize: t={:?}", t);
595
596         // Check to see whether the type we are generalizing references
597         // any other type variable related to `vid` via
598         // subtyping. This is basically our "occurs check", preventing
599         // us from creating infinitely sized types.
600         let result = match *t.kind() {
601             ty::Infer(ty::TyVar(vid)) => {
602                 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
603                 let sub_vid = self.infcx.inner.borrow_mut().type_variables().sub_root_var(vid);
604                 if sub_vid == self.for_vid_sub_root {
605                     // If sub-roots are equal, then `for_vid` and
606                     // `vid` are related via subtyping.
607                     Err(TypeError::CyclicTy(self.root_ty))
608                 } else {
609                     let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
610                     match probe {
611                         TypeVariableValue::Known { value: u } => {
612                             debug!("generalize: known value {:?}", u);
613                             self.relate(u, u)
614                         }
615                         TypeVariableValue::Unknown { universe } => {
616                             match self.ambient_variance {
617                                 // Invariant: no need to make a fresh type variable.
618                                 ty::Invariant => {
619                                     if self.for_universe.can_name(universe) {
620                                         return Ok(t);
621                                     }
622                                 }
623
624                                 // Bivariant: make a fresh var, but we
625                                 // may need a WF predicate. See
626                                 // comment on `needs_wf` field for
627                                 // more info.
628                                 ty::Bivariant => self.needs_wf = true,
629
630                                 // Co/contravariant: this will be
631                                 // sufficiently constrained later on.
632                                 ty::Covariant | ty::Contravariant => (),
633                             }
634
635                             let origin =
636                                 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
637                             let new_var_id = self
638                                 .infcx
639                                 .inner
640                                 .borrow_mut()
641                                 .type_variables()
642                                 .new_var(self.for_universe, false, origin);
643                             let u = self.tcx().mk_ty_var(new_var_id);
644                             debug!("generalize: replacing original vid={:?} with new={:?}", vid, u);
645                             Ok(u)
646                         }
647                     }
648                 }
649             }
650             ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
651                 // No matter what mode we are in,
652                 // integer/floating-point types must be equal to be
653                 // relatable.
654                 Ok(t)
655             }
656             _ => relate::super_relate_tys(self, t, t),
657         };
658
659         self.cache.insert(t, result.clone());
660         return result;
661     }
662
663     fn regions(
664         &mut self,
665         r: ty::Region<'tcx>,
666         r2: ty::Region<'tcx>,
667     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
668         assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
669
670         debug!("generalize: regions r={:?}", r);
671
672         match *r {
673             // Never make variables for regions bound within the type itself,
674             // nor for erased regions.
675             ty::ReLateBound(..) | ty::ReErased => {
676                 return Ok(r);
677             }
678
679             ty::RePlaceholder(..)
680             | ty::ReVar(..)
681             | ty::ReEmpty(_)
682             | ty::ReStatic
683             | ty::ReEarlyBound(..)
684             | ty::ReFree(..) => {
685                 // see common code below
686             }
687         }
688
689         // If we are in an invariant context, we can re-use the region
690         // as is, unless it happens to be in some universe that we
691         // can't name. (In the case of a region *variable*, we could
692         // use it if we promoted it into our universe, but we don't
693         // bother.)
694         if let ty::Invariant = self.ambient_variance {
695             let r_universe = self.infcx.universe_of_region(r);
696             if self.for_universe.can_name(r_universe) {
697                 return Ok(r);
698             }
699         }
700
701         // FIXME: This is non-ideal because we don't give a
702         // very descriptive origin for this region variable.
703         Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.cause.span), self.for_universe))
704     }
705
706     fn consts(
707         &mut self,
708         c: &'tcx ty::Const<'tcx>,
709         c2: &'tcx ty::Const<'tcx>,
710     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
711         assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
712
713         match c.val {
714             ty::ConstKind::Infer(InferConst::Var(vid)) => {
715                 let mut inner = self.infcx.inner.borrow_mut();
716                 let variable_table = &mut inner.const_unification_table();
717                 let var_value = variable_table.probe_value(vid);
718                 match var_value.val {
719                     ConstVariableValue::Known { value: u } => {
720                         drop(inner);
721                         self.relate(u, u)
722                     }
723                     ConstVariableValue::Unknown { universe } => {
724                         if self.for_universe.can_name(universe) {
725                             Ok(c)
726                         } else {
727                             let new_var_id = variable_table.new_key(ConstVarValue {
728                                 origin: var_value.origin,
729                                 val: ConstVariableValue::Unknown { universe: self.for_universe },
730                             });
731                             Ok(self.tcx().mk_const_var(new_var_id, c.ty))
732                         }
733                     }
734                 }
735             }
736             ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted })
737                 if self.tcx().lazy_normalization() =>
738             {
739                 assert_eq!(promoted, None);
740                 let substs = self.relate_with_variance(ty::Variance::Invariant, substs, substs)?;
741                 Ok(self.tcx().mk_const(ty::Const {
742                     ty: c.ty,
743                     val: ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }),
744                 }))
745             }
746             _ => relate::super_relate_consts(self, c, c),
747         }
748     }
749 }
750
751 pub trait ConstEquateRelation<'tcx>: TypeRelation<'tcx> {
752     /// Register an obligation that both constants must be equal to each other.
753     ///
754     /// If they aren't equal then the relation doesn't hold.
755     fn const_equate_obligation(&mut self, a: &'tcx ty::Const<'tcx>, b: &'tcx ty::Const<'tcx>);
756 }
757
758 pub trait RelateResultCompare<'tcx, T> {
759     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
760     where
761         F: FnOnce() -> TypeError<'tcx>;
762 }
763
764 impl<'tcx, T: Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
765     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
766     where
767         F: FnOnce() -> TypeError<'tcx>,
768     {
769         self.clone().and_then(|s| if s == t { self.clone() } else { Err(f()) })
770     }
771 }
772
773 pub fn const_unification_error<'tcx>(
774     a_is_expected: bool,
775     (a, b): (&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>),
776 ) -> TypeError<'tcx> {
777     TypeError::ConstMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))
778 }
779
780 fn int_unification_error<'tcx>(
781     a_is_expected: bool,
782     v: (ty::IntVarValue, ty::IntVarValue),
783 ) -> TypeError<'tcx> {
784     let (a, b) = v;
785     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))
786 }
787
788 fn float_unification_error<'tcx>(
789     a_is_expected: bool,
790     v: (ty::FloatVarValue, ty::FloatVarValue),
791 ) -> TypeError<'tcx> {
792     let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
793     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))
794 }
795
796 struct ConstInferUnifier<'cx, 'tcx> {
797     infcx: &'cx InferCtxt<'cx, 'tcx>,
798
799     span: Span,
800
801     param_env: ty::ParamEnv<'tcx>,
802
803     for_universe: ty::UniverseIndex,
804
805     /// The vid of the const variable that is in the process of being
806     /// instantiated; if we find this within the const we are folding,
807     /// that means we would have created a cyclic const.
808     target_vid: ty::ConstVid<'tcx>,
809 }
810
811 // We use `TypeRelation` here to propagate `RelateResult` upwards.
812 //
813 // Both inputs are expected to be the same.
814 impl TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> {
815     fn tcx(&self) -> TyCtxt<'tcx> {
816         self.infcx.tcx
817     }
818
819     fn param_env(&self) -> ty::ParamEnv<'tcx> {
820         self.param_env
821     }
822
823     fn tag(&self) -> &'static str {
824         "ConstInferUnifier"
825     }
826
827     fn a_is_expected(&self) -> bool {
828         true
829     }
830
831     fn relate_with_variance<T: Relate<'tcx>>(
832         &mut self,
833         _variance: ty::Variance,
834         a: T,
835         b: T,
836     ) -> RelateResult<'tcx, T> {
837         // We don't care about variance here.
838         self.relate(a, b)
839     }
840
841     fn binders<T>(
842         &mut self,
843         a: ty::Binder<T>,
844         b: ty::Binder<T>,
845     ) -> RelateResult<'tcx, ty::Binder<T>>
846     where
847         T: Relate<'tcx>,
848     {
849         Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
850     }
851
852     fn tys(&mut self, t: Ty<'tcx>, _t: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
853         debug_assert_eq!(t, _t);
854         debug!("ConstInferUnifier: t={:?}", t);
855
856         match t.kind() {
857             &ty::Infer(ty::TyVar(vid)) => {
858                 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
859                 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
860                 match probe {
861                     TypeVariableValue::Known { value: u } => {
862                         debug!("ConstOccursChecker: known value {:?}", u);
863                         self.tys(u, u)
864                     }
865                     TypeVariableValue::Unknown { universe } => {
866                         if self.for_universe.can_name(universe) {
867                             return Ok(t);
868                         }
869
870                         let origin =
871                             *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
872                         let new_var_id = self.infcx.inner.borrow_mut().type_variables().new_var(
873                             self.for_universe,
874                             false,
875                             origin,
876                         );
877                         let u = self.tcx().mk_ty_var(new_var_id);
878                         debug!(
879                             "ConstInferUnifier: replacing original vid={:?} with new={:?}",
880                             vid, u
881                         );
882                         Ok(u)
883                     }
884                 }
885             }
886             ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => Ok(t),
887             _ => relate::super_relate_tys(self, t, t),
888         }
889     }
890
891     fn regions(
892         &mut self,
893         r: ty::Region<'tcx>,
894         _r: ty::Region<'tcx>,
895     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
896         debug_assert_eq!(r, _r);
897         debug!("ConstInferUnifier: r={:?}", r);
898
899         match r {
900             // Never make variables for regions bound within the type itself,
901             // nor for erased regions.
902             ty::ReLateBound(..) | ty::ReErased => {
903                 return Ok(r);
904             }
905
906             ty::RePlaceholder(..)
907             | ty::ReVar(..)
908             | ty::ReEmpty(_)
909             | ty::ReStatic
910             | ty::ReEarlyBound(..)
911             | ty::ReFree(..) => {
912                 // see common code below
913             }
914         }
915
916         let r_universe = self.infcx.universe_of_region(r);
917         if self.for_universe.can_name(r_universe) {
918             return Ok(r);
919         } else {
920             // FIXME: This is non-ideal because we don't give a
921             // very descriptive origin for this region variable.
922             Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
923         }
924     }
925
926     fn consts(
927         &mut self,
928         c: &'tcx ty::Const<'tcx>,
929         _c: &'tcx ty::Const<'tcx>,
930     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
931         debug_assert_eq!(c, _c);
932         debug!("ConstInferUnifier: c={:?}", c);
933
934         match c.val {
935             ty::ConstKind::Infer(InferConst::Var(vid)) => {
936                 let mut inner = self.infcx.inner.borrow_mut();
937                 let variable_table = &mut inner.const_unification_table();
938
939                 // Check if the current unification would end up
940                 // unifying `target_vid` with a const which contains
941                 // an inference variable which is unioned with `target_vid`.
942                 //
943                 // Not doing so can easily result in stack overflows.
944                 if variable_table.unioned(self.target_vid, vid) {
945                     return Err(TypeError::CyclicConst(c));
946                 }
947
948                 let var_value = variable_table.probe_value(vid);
949                 match var_value.val {
950                     ConstVariableValue::Known { value: u } => self.consts(u, u),
951                     ConstVariableValue::Unknown { universe } => {
952                         if self.for_universe.can_name(universe) {
953                             Ok(c)
954                         } else {
955                             let new_var_id = variable_table.new_key(ConstVarValue {
956                                 origin: var_value.origin,
957                                 val: ConstVariableValue::Unknown { universe: self.for_universe },
958                             });
959                             Ok(self.tcx().mk_const_var(new_var_id, c.ty))
960                         }
961                     }
962                 }
963             }
964             ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted })
965                 if self.tcx().lazy_normalization() =>
966             {
967                 assert_eq!(promoted, None);
968                 let substs = self.relate_with_variance(ty::Variance::Invariant, substs, substs)?;
969                 Ok(self.tcx().mk_const(ty::Const {
970                     ty: c.ty,
971                     val: ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }),
972                 }))
973             }
974             _ => relate::super_relate_consts(self, c, c),
975         }
976     }
977 }