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).
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].
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].
16 //! On success, the LUB/GLB operations return the appropriate bound. The
17 //! return value of `Equate` or `Sub` shouldn't really be used.
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.
25 use super::equate::Equate;
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};
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
56 pub define_opaque_types: bool,
59 #[derive(Copy, Clone, Debug)]
60 pub enum RelationDir {
66 impl<'tcx> InferCtxt<'tcx> {
67 pub fn super_combine_tys<R>(
72 ) -> RelateResult<'tcx, Ty<'tcx>>
74 R: TypeRelation<'tcx>,
76 let a_is_expected = relation.a_is_expected();
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))) => {
83 .int_unification_table()
84 .unify_var_var(a_id, b_id)
85 .map_err(|e| int_unification_error(a_is_expected, e))?;
88 (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
89 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
91 (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
92 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
94 (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
95 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
97 (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
98 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
101 // Relate floating-point variables to other types
102 (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
105 .float_unification_table()
106 .unify_var_var(a_id, b_id)
107 .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
110 (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
111 self.unify_float_variable(a_is_expected, v_id, v)
113 (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
114 self.unify_float_variable(!a_is_expected, v_id, v)
117 // All other cases of inference are errors
118 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
119 Err(TypeError::Sorts(ty::relate::expected_found(relation, a, b)))
122 _ => ty::relate::super_relate_tys(relation, a, b),
126 pub fn super_combine_consts<R>(
131 ) -> RelateResult<'tcx, ty::Const<'tcx>>
133 R: ConstEquateRelation<'tcx>,
135 debug!("{}.consts({:?}, {:?})", relation.tag(), a, b);
140 let a = self.shallow_resolve(a);
141 let b = self.shallow_resolve(b);
143 let a_is_expected = relation.a_is_expected();
145 match (a.kind(), b.kind()) {
147 ty::ConstKind::Infer(InferConst::Var(a_vid)),
148 ty::ConstKind::Infer(InferConst::Var(b_vid)),
150 self.inner.borrow_mut().const_unification_table().union(a_vid, b_vid);
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)")
160 (ty::ConstKind::Infer(InferConst::Var(vid)), _) => {
161 return self.unify_const_variable(relation.param_env(), vid, b, a_is_expected);
164 (_, ty::ConstKind::Infer(InferConst::Var(vid))) => {
165 return self.unify_const_variable(relation.param_env(), vid, a, !a_is_expected);
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);
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);
186 ty::relate::super_relate_consts(relation, a, b)
189 /// Unifies the const variable `target_vid` with the given constant.
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.
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.
199 /// A good example of this is the following:
201 /// ```compile_fail,E0308
202 /// #![feature(generic_const_exprs)]
204 /// fn bind<const N: usize>(value: [u8; N]) -> [u8; 3 + 4] {
209 /// let mut arr = Default::default();
214 /// Here `3 + 4` ends up as `ConstKind::Unevaluated` which uses the generics
215 /// of `fn bind` (meaning that its substs contain `N`).
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`.
220 /// As `3 + 4` contains `N` in its substs, this must not succeed.
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(
226 param_env: ty::ParamEnv<'tcx>,
227 target_vid: ty::ConstVid<'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)
239 ConstVariableValue::Unknown { universe } => (universe, var_value.origin.span),
242 let value = ConstInferUnifier { infcx: self, span, param_env, for_universe, target_vid }
245 self.inner.borrow_mut().const_unification_table().union_value(
248 origin: ConstVariableOrigin {
249 kind: ConstVariableOriginKind::ConstInference,
252 val: ConstVariableValue::Known { value },
258 fn unify_integral_variable(
260 vid_is_expected: bool,
262 val: ty::IntVarValue,
263 ) -> RelateResult<'tcx, Ty<'tcx>> {
266 .int_unification_table()
267 .unify_var_value(vid, Some(val))
268 .map_err(|e| int_unification_error(vid_is_expected, e))?;
270 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
271 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
275 fn unify_float_variable(
277 vid_is_expected: bool,
280 ) -> RelateResult<'tcx, Ty<'tcx>> {
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))
290 impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
291 pub fn tcx(&self) -> TyCtxt<'tcx> {
295 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'tcx> {
296 Equate::new(self, a_is_expected)
299 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'tcx> {
300 Sub::new(self, a_is_expected)
303 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'tcx> {
304 Lub::new(self, a_is_expected)
307 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'tcx> {
308 Glb::new(self, a_is_expected)
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.
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")]
327 ) -> RelateResult<'tcx, ()> {
328 use self::RelationDir::*;
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());
333 // Generalize type of `a_ty` appropriately depending on the
334 // direction. As an example, assume:
336 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
337 // inference variable,
338 // - and `dir` == `SubtypeOf`.
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)?;
346 self.infcx.inner.borrow_mut().type_variables().instantiate(b_vid, b_ty);
349 self.obligations.push(Obligation::new(
351 self.trace.cause.clone(),
353 ty::Binder::dummy(ty::PredicateKind::WellFormed(b_ty.into())),
357 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
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.
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(
368 ty::VarianceDiagInfo::default(),
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).
385 /// - `for_vid` is a "root vid"
386 #[instrument(skip(self), level = "trace", ret)]
392 ) -> RelateResult<'tcx, Generalization<'tcx>> {
393 // Determine the ambient variance within which `ty` appears.
394 // The surrounding equation is:
398 // where `op` is either `==`, `<:`, or `:>`. This maps quite
400 let ambient_variance = match dir {
401 RelationDir::EqTo => ty::Invariant,
402 RelationDir::SubtypeOf => ty::Covariant,
403 RelationDir::SupertypeOf => ty::Contravariant,
406 trace!(?ambient_variance);
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,)
412 TypeVariableValue::Unknown { universe } => universe,
415 trace!(?for_universe);
418 let mut generalize = Generalizer {
420 cause: &self.trace.cause,
421 for_vid_sub_root: self.infcx.inner.borrow_mut().type_variables().sub_root_var(for_vid),
426 param_env: self.param_env,
427 cache: SsoHashMap::new(),
430 let ty = generalize.relate(ty, ty)?;
431 let needs_wf = generalize.needs_wf;
432 Ok(Generalization { ty, needs_wf })
435 pub fn add_const_equate_obligation(
441 let predicate = if a_is_expected {
442 ty::PredicateKind::ConstEquate(a, b)
444 ty::PredicateKind::ConstEquate(b, a)
446 self.obligations.push(Obligation::new(
448 self.trace.cause.clone(),
450 ty::Binder::dummy(predicate),
455 struct Generalizer<'cx, 'tcx> {
456 infcx: &'cx InferCtxt<'tcx>,
458 /// The span, used when creating new type variables and things.
459 cause: &'cx ObligationCause<'tcx>,
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,
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,
471 /// Track the variance as we descend into the type.
472 ambient_variance: ty::Variance,
474 /// See the field `needs_wf` in `Generalization`.
477 /// The root type that we are generalizing. Used when reporting cycles.
480 param_env: ty::ParamEnv<'tcx>,
482 cache: SsoHashMap<Ty<'tcx>, Ty<'tcx>>,
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.
489 struct Generalization<'tcx> {
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:
498 /// struct Foo<A, B> where A: Iterator<Item = B> {
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`.
520 impl<'tcx> TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
521 fn tcx(&self) -> TyCtxt<'tcx> {
524 fn param_env(&self) -> ty::ParamEnv<'tcx> {
528 fn tag(&self) -> &'static str {
532 fn a_is_expected(&self) -> bool {
538 a: ty::Binder<'tcx, T>,
539 b: ty::Binder<'tcx, T>,
540 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
544 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
547 fn relate_item_substs(
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
557 relate::relate_substs(self, a_subst, b_subst)
559 let tcx = self.tcx();
560 let opt_variances = tcx.variances_of(item_def_id);
561 relate::relate_substs_with_variances(
571 fn relate_with_variance<T: Relate<'tcx>>(
573 variance: ty::Variance,
574 _info: ty::VarianceDiagInfo<'tcx>,
577 ) -> RelateResult<'tcx, T> {
578 let old_ambient_variance = self.ambient_variance;
579 self.ambient_variance = self.ambient_variance.xform(variance);
581 let result = self.relate(a, b);
582 self.ambient_variance = old_ambient_variance;
586 fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
587 assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
589 if let Some(&result) = self.cache.get(&t) {
592 debug!("generalize: t={:?}", t);
594 // Check to see whether the type we are generalizing references
595 // any other type variable related to `vid` via
596 // subtyping. This is basically our "occurs check", preventing
597 // us from creating infinitely sized types.
598 let result = match *t.kind() {
599 ty::Infer(ty::TyVar(vid)) => {
600 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
601 let sub_vid = self.infcx.inner.borrow_mut().type_variables().sub_root_var(vid);
602 if sub_vid == self.for_vid_sub_root {
603 // If sub-roots are equal, then `for_vid` and
604 // `vid` are related via subtyping.
605 Err(TypeError::CyclicTy(self.root_ty))
607 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
609 TypeVariableValue::Known { value: u } => {
610 debug!("generalize: known value {:?}", u);
613 TypeVariableValue::Unknown { universe } => {
614 match self.ambient_variance {
615 // Invariant: no need to make a fresh type variable.
617 if self.for_universe.can_name(universe) {
622 // Bivariant: make a fresh var, but we
623 // may need a WF predicate. See
624 // comment on `needs_wf` field for
626 ty::Bivariant => self.needs_wf = true,
628 // Co/contravariant: this will be
629 // sufficiently constrained later on.
630 ty::Covariant | ty::Contravariant => (),
634 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
635 let new_var_id = self
640 .new_var(self.for_universe, origin);
641 let u = self.tcx().mk_ty_var(new_var_id);
643 // Record that we replaced `vid` with `new_var_id` as part of a generalization
644 // operation. This is needed to detect cyclic types. To see why, see the
645 // docs in the `type_variables` module.
646 self.infcx.inner.borrow_mut().type_variables().sub(vid, new_var_id);
647 debug!("generalize: replacing original vid={:?} with new={:?}", vid, u);
653 ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
654 // No matter what mode we are in,
655 // integer/floating-point types must be equal to be
659 _ => relate::super_relate_tys(self, t, t),
662 self.cache.insert(t, result);
669 r2: ty::Region<'tcx>,
670 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
671 assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
673 debug!("generalize: regions r={:?}", r);
676 // Never make variables for regions bound within the type itself,
677 // nor for erased regions.
678 ty::ReLateBound(..) | ty::ReErased => {
682 ty::RePlaceholder(..)
685 | ty::ReEarlyBound(..)
686 | ty::ReFree(..) => {
687 // see common code below
691 // If we are in an invariant context, we can re-use the region
692 // as is, unless it happens to be in some universe that we
693 // can't name. (In the case of a region *variable*, we could
694 // use it if we promoted it into our universe, but we don't
696 if let ty::Invariant = self.ambient_variance {
697 let r_universe = self.infcx.universe_of_region(r);
698 if self.for_universe.can_name(r_universe) {
703 // FIXME: This is non-ideal because we don't give a
704 // very descriptive origin for this region variable.
705 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.cause.span), self.for_universe))
712 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
713 assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
716 ty::ConstKind::Infer(InferConst::Var(vid)) => {
717 let mut inner = self.infcx.inner.borrow_mut();
718 let variable_table = &mut inner.const_unification_table();
719 let var_value = variable_table.probe_value(vid);
720 match var_value.val {
721 ConstVariableValue::Known { value: u } => {
725 ConstVariableValue::Unknown { universe } => {
726 if self.for_universe.can_name(universe) {
729 let new_var_id = variable_table.new_key(ConstVarValue {
730 origin: var_value.origin,
731 val: ConstVariableValue::Unknown { universe: self.for_universe },
733 Ok(self.tcx().mk_const_var(new_var_id, c.ty()))
738 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
739 let substs = self.relate_with_variance(
740 ty::Variance::Invariant,
741 ty::VarianceDiagInfo::default(),
745 Ok(self.tcx().mk_const(
746 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }),
750 _ => relate::super_relate_consts(self, c, c),
755 pub trait ConstEquateRelation<'tcx>: TypeRelation<'tcx> {
756 /// Register an obligation that both constants must be equal to each other.
758 /// If they aren't equal then the relation doesn't hold.
759 fn const_equate_obligation(&mut self, a: ty::Const<'tcx>, b: ty::Const<'tcx>);
762 fn int_unification_error<'tcx>(
764 v: (ty::IntVarValue, ty::IntVarValue),
765 ) -> TypeError<'tcx> {
767 TypeError::IntMismatch(ExpectedFound::new(a_is_expected, a, b))
770 fn float_unification_error<'tcx>(
772 v: (ty::FloatVarValue, ty::FloatVarValue),
773 ) -> TypeError<'tcx> {
774 let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
775 TypeError::FloatMismatch(ExpectedFound::new(a_is_expected, a, b))
778 struct ConstInferUnifier<'cx, 'tcx> {
779 infcx: &'cx InferCtxt<'tcx>,
783 param_env: ty::ParamEnv<'tcx>,
785 for_universe: ty::UniverseIndex,
787 /// The vid of the const variable that is in the process of being
788 /// instantiated; if we find this within the const we are folding,
789 /// that means we would have created a cyclic const.
790 target_vid: ty::ConstVid<'tcx>,
793 // We use `TypeRelation` here to propagate `RelateResult` upwards.
795 // Both inputs are expected to be the same.
796 impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> {
797 fn tcx(&self) -> TyCtxt<'tcx> {
801 fn param_env(&self) -> ty::ParamEnv<'tcx> {
805 fn tag(&self) -> &'static str {
809 fn a_is_expected(&self) -> bool {
813 fn relate_with_variance<T: Relate<'tcx>>(
815 _variance: ty::Variance,
816 _info: ty::VarianceDiagInfo<'tcx>,
819 ) -> RelateResult<'tcx, T> {
820 // We don't care about variance here.
826 a: ty::Binder<'tcx, T>,
827 b: ty::Binder<'tcx, T>,
828 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
832 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
835 #[instrument(level = "debug", skip(self), ret)]
836 fn tys(&mut self, t: Ty<'tcx>, _t: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
837 debug_assert_eq!(t, _t);
840 &ty::Infer(ty::TyVar(vid)) => {
841 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
842 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
844 TypeVariableValue::Known { value: u } => {
845 debug!("ConstOccursChecker: known value {:?}", u);
848 TypeVariableValue::Unknown { universe } => {
849 if self.for_universe.can_name(universe) {
854 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
855 let new_var_id = self
860 .new_var(self.for_universe, origin);
861 Ok(self.tcx().mk_ty_var(new_var_id))
865 ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => Ok(t),
866 _ => relate::super_relate_tys(self, t, t),
873 _r: ty::Region<'tcx>,
874 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
875 debug_assert_eq!(r, _r);
876 debug!("ConstInferUnifier: r={:?}", r);
879 // Never make variables for regions bound within the type itself,
880 // nor for erased regions.
881 ty::ReLateBound(..) | ty::ReErased => {
885 ty::RePlaceholder(..)
888 | ty::ReEarlyBound(..)
889 | ty::ReFree(..) => {
890 // see common code below
894 let r_universe = self.infcx.universe_of_region(r);
895 if self.for_universe.can_name(r_universe) {
898 // FIXME: This is non-ideal because we don't give a
899 // very descriptive origin for this region variable.
900 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
904 #[instrument(level = "debug", skip(self))]
909 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
910 debug_assert_eq!(c, _c);
913 ty::ConstKind::Infer(InferConst::Var(vid)) => {
914 // Check if the current unification would end up
915 // unifying `target_vid` with a const which contains
916 // an inference variable which is unioned with `target_vid`.
918 // Not doing so can easily result in stack overflows.
923 .const_unification_table()
924 .unioned(self.target_vid, vid)
926 return Err(TypeError::CyclicConst(c));
930 self.infcx.inner.borrow_mut().const_unification_table().probe_value(vid);
931 match var_value.val {
932 ConstVariableValue::Known { value: u } => self.consts(u, u),
933 ConstVariableValue::Unknown { universe } => {
934 if self.for_universe.can_name(universe) {
938 self.infcx.inner.borrow_mut().const_unification_table().new_key(
940 origin: var_value.origin,
941 val: ConstVariableValue::Unknown {
942 universe: self.for_universe,
946 Ok(self.tcx().mk_const_var(new_var_id, c.ty()))
951 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
952 let substs = self.relate_with_variance(
953 ty::Variance::Invariant,
954 ty::VarianceDiagInfo::default(),
959 Ok(self.tcx().mk_const(
960 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }),
964 _ => relate::super_relate_consts(self, c, c),