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