]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/combine.rs
Rollup merge of #105598 - RalfJung:more-comments, r=the8472
[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     pub fn mark_ambiguous(&mut self) {
455         self.obligations.push(Obligation::new(
456             self.tcx(),
457             self.trace.cause.clone(),
458             self.param_env,
459             ty::Binder::dummy(ty::PredicateKind::Ambiguous),
460         ));
461     }
462 }
463
464 struct Generalizer<'cx, 'tcx> {
465     infcx: &'cx InferCtxt<'tcx>,
466
467     /// The span, used when creating new type variables and things.
468     cause: &'cx ObligationCause<'tcx>,
469
470     /// The vid of the type variable that is in the process of being
471     /// instantiated; if we find this within the type we are folding,
472     /// that means we would have created a cyclic type.
473     for_vid_sub_root: ty::TyVid,
474
475     /// The universe of the type variable that is in the process of
476     /// being instantiated. Any fresh variables that we create in this
477     /// process should be in that same universe.
478     for_universe: ty::UniverseIndex,
479
480     /// Track the variance as we descend into the type.
481     ambient_variance: ty::Variance,
482
483     /// See the field `needs_wf` in `Generalization`.
484     needs_wf: bool,
485
486     /// The root type that we are generalizing. Used when reporting cycles.
487     root_ty: Ty<'tcx>,
488
489     param_env: ty::ParamEnv<'tcx>,
490
491     cache: SsoHashMap<Ty<'tcx>, Ty<'tcx>>,
492 }
493
494 /// Result from a generalization operation. This includes
495 /// not only the generalized type, but also a bool flag
496 /// indicating whether further WF checks are needed.
497 #[derive(Debug)]
498 struct Generalization<'tcx> {
499     ty: Ty<'tcx>,
500
501     /// If true, then the generalized type may not be well-formed,
502     /// even if the source type is well-formed, so we should add an
503     /// additional check to enforce that it is. This arises in
504     /// particular around 'bivariant' type parameters that are only
505     /// constrained by a where-clause. As an example, imagine a type:
506     ///
507     ///     struct Foo<A, B> where A: Iterator<Item = B> {
508     ///         data: A
509     ///     }
510     ///
511     /// here, `A` will be covariant, but `B` is
512     /// unconstrained. However, whatever it is, for `Foo` to be WF, it
513     /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
514     /// then after generalization we will wind up with a type like
515     /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
516     /// ?D>` (or `>:`), we will wind up with the requirement that `?A
517     /// <: ?C`, but no particular relationship between `?B` and `?D`
518     /// (after all, we do not know the variance of the normalized form
519     /// of `A::Item` with respect to `A`). If we do nothing else, this
520     /// may mean that `?D` goes unconstrained (as in #41677). So, in
521     /// this scenario where we create a new type variable in a
522     /// bivariant context, we set the `needs_wf` flag to true. This
523     /// will force the calling code to check that `WF(Foo<?C, ?D>)`
524     /// holds, which in turn implies that `?C::Item == ?D`. So once
525     /// `?C` is constrained, that should suffice to restrict `?D`.
526     needs_wf: bool,
527 }
528
529 impl<'tcx> TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
530     fn tcx(&self) -> TyCtxt<'tcx> {
531         self.infcx.tcx
532     }
533
534     fn intercrate(&self) -> bool {
535         self.infcx.intercrate
536     }
537
538     fn param_env(&self) -> ty::ParamEnv<'tcx> {
539         self.param_env
540     }
541
542     fn tag(&self) -> &'static str {
543         "Generalizer"
544     }
545
546     fn a_is_expected(&self) -> bool {
547         true
548     }
549
550     fn mark_ambiguous(&mut self) {
551         span_bug!(self.cause.span, "opaque types are handled in `tys`");
552     }
553
554     fn binders<T>(
555         &mut self,
556         a: ty::Binder<'tcx, T>,
557         b: ty::Binder<'tcx, T>,
558     ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
559     where
560         T: Relate<'tcx>,
561     {
562         Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
563     }
564
565     fn relate_item_substs(
566         &mut self,
567         item_def_id: DefId,
568         a_subst: SubstsRef<'tcx>,
569         b_subst: SubstsRef<'tcx>,
570     ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
571         if self.ambient_variance == ty::Variance::Invariant {
572             // Avoid fetching the variance if we are in an invariant
573             // context; no need, and it can induce dependency cycles
574             // (e.g., #41849).
575             relate::relate_substs(self, a_subst, b_subst)
576         } else {
577             let tcx = self.tcx();
578             let opt_variances = tcx.variances_of(item_def_id);
579             relate::relate_substs_with_variances(
580                 self,
581                 item_def_id,
582                 &opt_variances,
583                 a_subst,
584                 b_subst,
585                 true,
586             )
587         }
588     }
589
590     fn relate_with_variance<T: Relate<'tcx>>(
591         &mut self,
592         variance: ty::Variance,
593         _info: ty::VarianceDiagInfo<'tcx>,
594         a: T,
595         b: T,
596     ) -> RelateResult<'tcx, T> {
597         let old_ambient_variance = self.ambient_variance;
598         self.ambient_variance = self.ambient_variance.xform(variance);
599
600         let result = self.relate(a, b);
601         self.ambient_variance = old_ambient_variance;
602         result
603     }
604
605     fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
606         assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
607
608         if let Some(&result) = self.cache.get(&t) {
609             return Ok(result);
610         }
611         debug!("generalize: t={:?}", t);
612
613         // Check to see whether the type we are generalizing references
614         // any other type variable related to `vid` via
615         // subtyping. This is basically our "occurs check", preventing
616         // us from creating infinitely sized types.
617         let result = match *t.kind() {
618             ty::Infer(ty::TyVar(vid)) => {
619                 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
620                 let sub_vid = self.infcx.inner.borrow_mut().type_variables().sub_root_var(vid);
621                 if sub_vid == self.for_vid_sub_root {
622                     // If sub-roots are equal, then `for_vid` and
623                     // `vid` are related via subtyping.
624                     Err(TypeError::CyclicTy(self.root_ty))
625                 } else {
626                     let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
627                     match probe {
628                         TypeVariableValue::Known { value: u } => {
629                             debug!("generalize: known value {:?}", u);
630                             self.relate(u, u)
631                         }
632                         TypeVariableValue::Unknown { universe } => {
633                             match self.ambient_variance {
634                                 // Invariant: no need to make a fresh type variable.
635                                 ty::Invariant => {
636                                     if self.for_universe.can_name(universe) {
637                                         return Ok(t);
638                                     }
639                                 }
640
641                                 // Bivariant: make a fresh var, but we
642                                 // may need a WF predicate. See
643                                 // comment on `needs_wf` field for
644                                 // more info.
645                                 ty::Bivariant => self.needs_wf = true,
646
647                                 // Co/contravariant: this will be
648                                 // sufficiently constrained later on.
649                                 ty::Covariant | ty::Contravariant => (),
650                             }
651
652                             let origin =
653                                 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
654                             let new_var_id = self
655                                 .infcx
656                                 .inner
657                                 .borrow_mut()
658                                 .type_variables()
659                                 .new_var(self.for_universe, origin);
660                             let u = self.tcx().mk_ty_var(new_var_id);
661
662                             // Record that we replaced `vid` with `new_var_id` as part of a generalization
663                             // operation. This is needed to detect cyclic types. To see why, see the
664                             // docs in the `type_variables` module.
665                             self.infcx.inner.borrow_mut().type_variables().sub(vid, new_var_id);
666                             debug!("generalize: replacing original vid={:?} with new={:?}", vid, u);
667                             Ok(u)
668                         }
669                     }
670                 }
671             }
672             ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
673                 // No matter what mode we are in,
674                 // integer/floating-point types must be equal to be
675                 // relatable.
676                 Ok(t)
677             }
678             ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs }) => {
679                 let s = self.relate(substs, substs)?;
680                 Ok(if s == substs { t } else { self.infcx.tcx.mk_opaque(def_id, s) })
681             }
682             _ => relate::super_relate_tys(self, t, t),
683         }?;
684
685         self.cache.insert(t, result);
686         Ok(result)
687     }
688
689     fn regions(
690         &mut self,
691         r: ty::Region<'tcx>,
692         r2: ty::Region<'tcx>,
693     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
694         assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
695
696         debug!("generalize: regions r={:?}", r);
697
698         match *r {
699             // Never make variables for regions bound within the type itself,
700             // nor for erased regions.
701             ty::ReLateBound(..) | ty::ReErased => {
702                 return Ok(r);
703             }
704
705             ty::RePlaceholder(..)
706             | ty::ReVar(..)
707             | ty::ReStatic
708             | ty::ReEarlyBound(..)
709             | ty::ReFree(..) => {
710                 // see common code below
711             }
712         }
713
714         // If we are in an invariant context, we can re-use the region
715         // as is, unless it happens to be in some universe that we
716         // can't name. (In the case of a region *variable*, we could
717         // use it if we promoted it into our universe, but we don't
718         // bother.)
719         if let ty::Invariant = self.ambient_variance {
720             let r_universe = self.infcx.universe_of_region(r);
721             if self.for_universe.can_name(r_universe) {
722                 return Ok(r);
723             }
724         }
725
726         // FIXME: This is non-ideal because we don't give a
727         // very descriptive origin for this region variable.
728         Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.cause.span), self.for_universe))
729     }
730
731     fn consts(
732         &mut self,
733         c: ty::Const<'tcx>,
734         c2: ty::Const<'tcx>,
735     ) -> RelateResult<'tcx, ty::Const<'tcx>> {
736         assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
737
738         match c.kind() {
739             ty::ConstKind::Infer(InferConst::Var(vid)) => {
740                 let mut inner = self.infcx.inner.borrow_mut();
741                 let variable_table = &mut inner.const_unification_table();
742                 let var_value = variable_table.probe_value(vid);
743                 match var_value.val {
744                     ConstVariableValue::Known { value: u } => {
745                         drop(inner);
746                         self.relate(u, u)
747                     }
748                     ConstVariableValue::Unknown { universe } => {
749                         if self.for_universe.can_name(universe) {
750                             Ok(c)
751                         } else {
752                             let new_var_id = variable_table.new_key(ConstVarValue {
753                                 origin: var_value.origin,
754                                 val: ConstVariableValue::Unknown { universe: self.for_universe },
755                             });
756                             Ok(self.tcx().mk_const(new_var_id, c.ty()))
757                         }
758                     }
759                 }
760             }
761             ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
762                 let substs = self.relate_with_variance(
763                     ty::Variance::Invariant,
764                     ty::VarianceDiagInfo::default(),
765                     substs,
766                     substs,
767                 )?;
768                 Ok(self.tcx().mk_const(ty::UnevaluatedConst { def, substs }, c.ty()))
769             }
770             _ => relate::super_relate_consts(self, c, c),
771         }
772     }
773 }
774
775 pub trait ConstEquateRelation<'tcx>: TypeRelation<'tcx> {
776     /// Register an obligation that both constants must be equal to each other.
777     ///
778     /// If they aren't equal then the relation doesn't hold.
779     fn const_equate_obligation(&mut self, a: ty::Const<'tcx>, b: ty::Const<'tcx>);
780 }
781
782 fn int_unification_error<'tcx>(
783     a_is_expected: bool,
784     v: (ty::IntVarValue, ty::IntVarValue),
785 ) -> TypeError<'tcx> {
786     let (a, b) = v;
787     TypeError::IntMismatch(ExpectedFound::new(a_is_expected, a, b))
788 }
789
790 fn float_unification_error<'tcx>(
791     a_is_expected: bool,
792     v: (ty::FloatVarValue, ty::FloatVarValue),
793 ) -> TypeError<'tcx> {
794     let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
795     TypeError::FloatMismatch(ExpectedFound::new(a_is_expected, a, b))
796 }
797
798 struct ConstInferUnifier<'cx, 'tcx> {
799     infcx: &'cx InferCtxt<'tcx>,
800
801     span: Span,
802
803     param_env: ty::ParamEnv<'tcx>,
804
805     for_universe: ty::UniverseIndex,
806
807     /// The vid of the const variable that is in the process of being
808     /// instantiated; if we find this within the const we are folding,
809     /// that means we would have created a cyclic const.
810     target_vid: ty::ConstVid<'tcx>,
811 }
812
813 // We use `TypeRelation` here to propagate `RelateResult` upwards.
814 //
815 // Both inputs are expected to be the same.
816 impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> {
817     fn tcx(&self) -> TyCtxt<'tcx> {
818         self.infcx.tcx
819     }
820
821     fn intercrate(&self) -> bool {
822         assert!(!self.infcx.intercrate);
823         false
824     }
825
826     fn param_env(&self) -> ty::ParamEnv<'tcx> {
827         self.param_env
828     }
829
830     fn tag(&self) -> &'static str {
831         "ConstInferUnifier"
832     }
833
834     fn a_is_expected(&self) -> bool {
835         true
836     }
837
838     fn mark_ambiguous(&mut self) {
839         bug!()
840     }
841
842     fn relate_with_variance<T: Relate<'tcx>>(
843         &mut self,
844         _variance: ty::Variance,
845         _info: ty::VarianceDiagInfo<'tcx>,
846         a: T,
847         b: T,
848     ) -> RelateResult<'tcx, T> {
849         // We don't care about variance here.
850         self.relate(a, b)
851     }
852
853     fn binders<T>(
854         &mut self,
855         a: ty::Binder<'tcx, T>,
856         b: ty::Binder<'tcx, T>,
857     ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
858     where
859         T: Relate<'tcx>,
860     {
861         Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
862     }
863
864     #[instrument(level = "debug", skip(self), ret)]
865     fn tys(&mut self, t: Ty<'tcx>, _t: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
866         debug_assert_eq!(t, _t);
867
868         match t.kind() {
869             &ty::Infer(ty::TyVar(vid)) => {
870                 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
871                 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
872                 match probe {
873                     TypeVariableValue::Known { value: u } => {
874                         debug!("ConstOccursChecker: known value {:?}", u);
875                         self.tys(u, u)
876                     }
877                     TypeVariableValue::Unknown { universe } => {
878                         if self.for_universe.can_name(universe) {
879                             return Ok(t);
880                         }
881
882                         let origin =
883                             *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
884                         let new_var_id = self
885                             .infcx
886                             .inner
887                             .borrow_mut()
888                             .type_variables()
889                             .new_var(self.for_universe, origin);
890                         Ok(self.tcx().mk_ty_var(new_var_id))
891                     }
892                 }
893             }
894             ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => Ok(t),
895             _ => relate::super_relate_tys(self, t, t),
896         }
897     }
898
899     fn regions(
900         &mut self,
901         r: ty::Region<'tcx>,
902         _r: ty::Region<'tcx>,
903     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
904         debug_assert_eq!(r, _r);
905         debug!("ConstInferUnifier: r={:?}", r);
906
907         match *r {
908             // Never make variables for regions bound within the type itself,
909             // nor for erased regions.
910             ty::ReLateBound(..) | ty::ReErased => {
911                 return Ok(r);
912             }
913
914             ty::RePlaceholder(..)
915             | ty::ReVar(..)
916             | ty::ReStatic
917             | ty::ReEarlyBound(..)
918             | ty::ReFree(..) => {
919                 // see common code below
920             }
921         }
922
923         let r_universe = self.infcx.universe_of_region(r);
924         if self.for_universe.can_name(r_universe) {
925             return Ok(r);
926         } else {
927             // FIXME: This is non-ideal because we don't give a
928             // very descriptive origin for this region variable.
929             Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
930         }
931     }
932
933     #[instrument(level = "debug", skip(self))]
934     fn consts(
935         &mut self,
936         c: ty::Const<'tcx>,
937         _c: ty::Const<'tcx>,
938     ) -> RelateResult<'tcx, ty::Const<'tcx>> {
939         debug_assert_eq!(c, _c);
940
941         match c.kind() {
942             ty::ConstKind::Infer(InferConst::Var(vid)) => {
943                 // Check if the current unification would end up
944                 // unifying `target_vid` with a const which contains
945                 // an inference variable which is unioned with `target_vid`.
946                 //
947                 // Not doing so can easily result in stack overflows.
948                 if self
949                     .infcx
950                     .inner
951                     .borrow_mut()
952                     .const_unification_table()
953                     .unioned(self.target_vid, vid)
954                 {
955                     return Err(TypeError::CyclicConst(c));
956                 }
957
958                 let var_value =
959                     self.infcx.inner.borrow_mut().const_unification_table().probe_value(vid);
960                 match var_value.val {
961                     ConstVariableValue::Known { value: u } => self.consts(u, u),
962                     ConstVariableValue::Unknown { universe } => {
963                         if self.for_universe.can_name(universe) {
964                             Ok(c)
965                         } else {
966                             let new_var_id =
967                                 self.infcx.inner.borrow_mut().const_unification_table().new_key(
968                                     ConstVarValue {
969                                         origin: var_value.origin,
970                                         val: ConstVariableValue::Unknown {
971                                             universe: self.for_universe,
972                                         },
973                                     },
974                                 );
975                             Ok(self.tcx().mk_const(new_var_id, c.ty()))
976                         }
977                     }
978                 }
979             }
980             ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
981                 let substs = self.relate_with_variance(
982                     ty::Variance::Invariant,
983                     ty::VarianceDiagInfo::default(),
984                     substs,
985                     substs,
986                 )?;
987
988                 Ok(self.tcx().mk_const(ty::UnevaluatedConst { def, substs }, c.ty()))
989             }
990             _ => relate::super_relate_consts(self, c, c),
991         }
992     }
993 }