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 `tests/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),
454 pub fn mark_ambiguous(&mut self) {
455 self.obligations.push(Obligation::new(
457 self.trace.cause.clone(),
459 ty::Binder::dummy(ty::PredicateKind::Ambiguous),
464 struct Generalizer<'cx, 'tcx> {
465 infcx: &'cx InferCtxt<'tcx>,
467 /// The span, used when creating new type variables and things.
468 cause: &'cx ObligationCause<'tcx>,
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,
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,
480 /// Track the variance as we descend into the type.
481 ambient_variance: ty::Variance,
483 /// See the field `needs_wf` in `Generalization`.
486 /// The root type that we are generalizing. Used when reporting cycles.
489 param_env: ty::ParamEnv<'tcx>,
491 cache: SsoHashMap<Ty<'tcx>, Ty<'tcx>>,
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.
498 struct Generalization<'tcx> {
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:
507 /// struct Foo<A, B> where A: Iterator<Item = B> {
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`.
529 impl<'tcx> TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
530 fn tcx(&self) -> TyCtxt<'tcx> {
534 fn intercrate(&self) -> bool {
535 self.infcx.intercrate
538 fn param_env(&self) -> ty::ParamEnv<'tcx> {
542 fn tag(&self) -> &'static str {
546 fn a_is_expected(&self) -> bool {
550 fn mark_ambiguous(&mut self) {
551 span_bug!(self.cause.span, "opaque types are handled in `tys`");
556 a: ty::Binder<'tcx, T>,
557 b: ty::Binder<'tcx, T>,
558 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
562 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
565 fn relate_item_substs(
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
575 relate::relate_substs(self, a_subst, b_subst)
577 let tcx = self.tcx();
578 let opt_variances = tcx.variances_of(item_def_id);
579 relate::relate_substs_with_variances(
590 fn relate_with_variance<T: Relate<'tcx>>(
592 variance: ty::Variance,
593 _info: ty::VarianceDiagInfo<'tcx>,
596 ) -> RelateResult<'tcx, T> {
597 let old_ambient_variance = self.ambient_variance;
598 self.ambient_variance = self.ambient_variance.xform(variance);
600 let result = self.relate(a, b);
601 self.ambient_variance = old_ambient_variance;
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 ==
608 if let Some(&result) = self.cache.get(&t) {
611 debug!("generalize: t={:?}", t);
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))
626 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
628 TypeVariableValue::Known { value: u } => {
629 debug!("generalize: known value {:?}", u);
632 TypeVariableValue::Unknown { universe } => {
633 match self.ambient_variance {
634 // Invariant: no need to make a fresh type variable.
636 if self.for_universe.can_name(universe) {
641 // Bivariant: make a fresh var, but we
642 // may need a WF predicate. See
643 // comment on `needs_wf` field for
645 ty::Bivariant => self.needs_wf = true,
647 // Co/contravariant: this will be
648 // sufficiently constrained later on.
649 ty::Covariant | ty::Contravariant => (),
653 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
654 let new_var_id = self
659 .new_var(self.for_universe, origin);
660 let u = self.tcx().mk_ty_var(new_var_id);
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);
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
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) })
682 _ => relate::super_relate_tys(self, t, t),
685 self.cache.insert(t, result);
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 ==
696 debug!("generalize: regions r={:?}", r);
699 // Never make variables for regions bound within the type itself,
700 // nor for erased regions.
701 ty::ReLateBound(..) | ty::ReErased => {
705 ty::RePlaceholder(..)
708 | ty::ReEarlyBound(..)
709 | ty::ReFree(..) => {
710 // see common code below
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
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) {
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))
735 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
736 assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
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 } => {
748 ConstVariableValue::Unknown { universe } => {
749 if self.for_universe.can_name(universe) {
752 let new_var_id = variable_table.new_key(ConstVarValue {
753 origin: var_value.origin,
754 val: ConstVariableValue::Unknown { universe: self.for_universe },
756 Ok(self.tcx().mk_const(new_var_id, c.ty()))
761 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
762 let substs = self.relate_with_variance(
763 ty::Variance::Invariant,
764 ty::VarianceDiagInfo::default(),
768 Ok(self.tcx().mk_const(ty::UnevaluatedConst { def, substs }, c.ty()))
770 _ => relate::super_relate_consts(self, c, c),
775 pub trait ConstEquateRelation<'tcx>: TypeRelation<'tcx> {
776 /// Register an obligation that both constants must be equal to each other.
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>);
782 fn int_unification_error<'tcx>(
784 v: (ty::IntVarValue, ty::IntVarValue),
785 ) -> TypeError<'tcx> {
787 TypeError::IntMismatch(ExpectedFound::new(a_is_expected, a, b))
790 fn float_unification_error<'tcx>(
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))
798 struct ConstInferUnifier<'cx, 'tcx> {
799 infcx: &'cx InferCtxt<'tcx>,
803 param_env: ty::ParamEnv<'tcx>,
805 for_universe: ty::UniverseIndex,
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>,
813 // We use `TypeRelation` here to propagate `RelateResult` upwards.
815 // Both inputs are expected to be the same.
816 impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> {
817 fn tcx(&self) -> TyCtxt<'tcx> {
821 fn intercrate(&self) -> bool {
822 assert!(!self.infcx.intercrate);
826 fn param_env(&self) -> ty::ParamEnv<'tcx> {
830 fn tag(&self) -> &'static str {
834 fn a_is_expected(&self) -> bool {
838 fn mark_ambiguous(&mut self) {
842 fn relate_with_variance<T: Relate<'tcx>>(
844 _variance: ty::Variance,
845 _info: ty::VarianceDiagInfo<'tcx>,
848 ) -> RelateResult<'tcx, T> {
849 // We don't care about variance here.
855 a: ty::Binder<'tcx, T>,
856 b: ty::Binder<'tcx, T>,
857 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
861 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
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);
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);
873 TypeVariableValue::Known { value: u } => {
874 debug!("ConstOccursChecker: known value {:?}", u);
877 TypeVariableValue::Unknown { universe } => {
878 if self.for_universe.can_name(universe) {
883 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
884 let new_var_id = self
889 .new_var(self.for_universe, origin);
890 Ok(self.tcx().mk_ty_var(new_var_id))
894 ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => Ok(t),
895 _ => relate::super_relate_tys(self, t, t),
902 _r: ty::Region<'tcx>,
903 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
904 debug_assert_eq!(r, _r);
905 debug!("ConstInferUnifier: r={:?}", r);
908 // Never make variables for regions bound within the type itself,
909 // nor for erased regions.
910 ty::ReLateBound(..) | ty::ReErased => {
914 ty::RePlaceholder(..)
917 | ty::ReEarlyBound(..)
918 | ty::ReFree(..) => {
919 // see common code below
923 let r_universe = self.infcx.universe_of_region(r);
924 if self.for_universe.can_name(r_universe) {
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))
933 #[instrument(level = "debug", skip(self))]
938 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
939 debug_assert_eq!(c, _c);
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`.
947 // Not doing so can easily result in stack overflows.
952 .const_unification_table()
953 .unioned(self.target_vid, vid)
955 return Err(TypeError::CyclicConst(c));
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) {
967 self.infcx.inner.borrow_mut().const_unification_table().new_key(
969 origin: var_value.origin,
970 val: ConstVariableValue::Unknown {
971 universe: self.for_universe,
975 Ok(self.tcx().mk_const(new_var_id, c.ty()))
980 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
981 let substs = self.relate_with_variance(
982 ty::Variance::Invariant,
983 ty::VarianceDiagInfo::default(),
988 Ok(self.tcx().mk_const(ty::UnevaluatedConst { def, substs }, c.ty()))
990 _ => relate::super_relate_consts(self, c, c),