summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_infer/src/infer/combine.rs
diff options
context:
space:
mode:
Diffstat (limited to 'compiler/rustc_infer/src/infer/combine.rs')
-rw-r--r--compiler/rustc_infer/src/infer/combine.rs620
1 files changed, 53 insertions, 567 deletions
diff --git a/compiler/rustc_infer/src/infer/combine.rs b/compiler/rustc_infer/src/infer/combine.rs
index fe45b5ebe..b6b935de6 100644
--- a/compiler/rustc_infer/src/infer/combine.rs
+++ b/compiler/rustc_infer/src/infer/combine.rs
@@ -26,24 +26,17 @@ use super::equate::Equate;
use super::glb::Glb;
use super::lub::Lub;
use super::sub::Sub;
-use super::type_variable::TypeVariableValue;
-use super::{DefineOpaqueTypes, InferCtxt, MiscVariable, TypeTrace};
+use super::{DefineOpaqueTypes, InferCtxt, TypeTrace};
+use crate::infer::generalize::{self, CombineDelegate, Generalization};
use crate::traits::{Obligation, PredicateObligations};
-use rustc_data_structures::sso::SsoHashMap;
-use rustc_hir::def_id::DefId;
use rustc_middle::infer::canonical::OriginalQueryValues;
use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
-use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
-use rustc_middle::ty::relate::{self, Relate, RelateResult, TypeRelation};
-use rustc_middle::ty::subst::SubstsRef;
-use rustc_middle::ty::{
- self, AliasKind, FallibleTypeFolder, InferConst, ToPredicate, Ty, TyCtxt, TypeFoldable,
- TypeSuperFoldable, TypeVisitableExt,
-};
+use rustc_middle::ty::relate::{RelateResult, TypeRelation};
+use rustc_middle::ty::{self, AliasKind, InferConst, ToPredicate, Ty, TyCtxt, TypeVisitableExt};
use rustc_middle::ty::{IntType, UintType};
-use rustc_span::{Span, DUMMY_SP};
+use rustc_span::DUMMY_SP;
#[derive(Clone)]
pub struct CombineFields<'infcx, 'tcx> {
@@ -55,13 +48,6 @@ pub struct CombineFields<'infcx, 'tcx> {
pub define_opaque_types: DefineOpaqueTypes,
}
-#[derive(Copy, Clone, Debug)]
-pub enum RelationDir {
- SubtypeOf,
- SupertypeOf,
- EqTo,
-}
-
impl<'tcx> InferCtxt<'tcx> {
pub fn super_combine_tys<R>(
&self,
@@ -73,6 +59,8 @@ impl<'tcx> InferCtxt<'tcx> {
R: ObligationEmittingRelation<'tcx>,
{
let a_is_expected = relation.a_is_expected();
+ debug_assert!(!a.has_escaping_bound_vars());
+ debug_assert!(!b.has_escaping_bound_vars());
match (a.kind(), b.kind()) {
// Relate integral variables to other types
@@ -125,9 +113,7 @@ impl<'tcx> InferCtxt<'tcx> {
bug!()
}
- (_, ty::Alias(AliasKind::Projection, _)) | (ty::Alias(AliasKind::Projection, _), _)
- if self.tcx.trait_solver_next() =>
- {
+ (_, ty::Alias(..)) | (ty::Alias(..), _) if self.tcx.trait_solver_next() => {
relation.register_type_relate_obligation(a, b);
Ok(a)
}
@@ -149,7 +135,7 @@ impl<'tcx> InferCtxt<'tcx> {
Ok(a)
}
- _ => ty::relate::super_relate_tys(relation, a, b),
+ _ => ty::relate::structurally_relate_tys(relation, a, b),
}
}
@@ -163,6 +149,8 @@ impl<'tcx> InferCtxt<'tcx> {
R: ObligationEmittingRelation<'tcx>,
{
debug!("{}.consts({:?}, {:?})", relation.tag(), a, b);
+ debug_assert!(!a.has_escaping_bound_vars());
+ debug_assert!(!b.has_escaping_bound_vars());
if a == b {
return Ok(a);
}
@@ -192,7 +180,7 @@ impl<'tcx> InferCtxt<'tcx> {
self.tcx.check_tys_might_be_eq(canonical).map_err(|_| {
self.tcx.sess.delay_span_bug(
DUMMY_SP,
- &format!("cannot relate consts of different types (a={:?}, b={:?})", a, b,),
+ format!("cannot relate consts of different types (a={:?}, b={:?})", a, b,),
)
})
});
@@ -204,13 +192,13 @@ impl<'tcx> InferCtxt<'tcx> {
// HACK: equating both sides with `[const error]` eagerly prevents us
// from leaving unconstrained inference vars during things like impl
// matching in the solver.
- let a_error = self.tcx.const_error_with_guaranteed(a.ty(), guar);
+ let a_error = self.tcx.const_error(a.ty(), guar);
if let ty::ConstKind::Infer(InferConst::Var(vid)) = a.kind() {
- return self.unify_const_variable(vid, a_error);
+ return self.unify_const_variable(vid, a_error, relation.param_env());
}
- let b_error = self.tcx.const_error_with_guaranteed(b.ty(), guar);
+ let b_error = self.tcx.const_error(b.ty(), guar);
if let ty::ConstKind::Infer(InferConst::Var(vid)) = b.kind() {
- return self.unify_const_variable(vid, b_error);
+ return self.unify_const_variable(vid, b_error, relation.param_env());
}
return Ok(if relation.a_is_expected() { a_error } else { b_error });
@@ -232,32 +220,22 @@ impl<'tcx> InferCtxt<'tcx> {
}
(ty::ConstKind::Infer(InferConst::Var(vid)), _) => {
- return self.unify_const_variable(vid, b);
+ return self.unify_const_variable(vid, b, relation.param_env());
}
(_, ty::ConstKind::Infer(InferConst::Var(vid))) => {
- return self.unify_const_variable(vid, a);
+ return self.unify_const_variable(vid, a, relation.param_env());
}
- (ty::ConstKind::Unevaluated(..), _) if self.tcx.lazy_normalization() => {
- // FIXME(#59490): Need to remove the leak check to accommodate
- // escaping bound variables here.
- if !a.has_escaping_bound_vars() && !b.has_escaping_bound_vars() {
- relation.register_const_equate_obligation(a, b);
- }
+ (ty::ConstKind::Unevaluated(..), _) | (_, ty::ConstKind::Unevaluated(..))
+ if self.tcx.lazy_normalization() =>
+ {
+ relation.register_const_equate_obligation(a, b);
return Ok(b);
}
- (_, ty::ConstKind::Unevaluated(..)) if self.tcx.lazy_normalization() => {
- // FIXME(#59490): Need to remove the leak check to accommodate
- // escaping bound variables here.
- if !a.has_escaping_bound_vars() && !b.has_escaping_bound_vars() {
- relation.register_const_equate_obligation(a, b);
- }
- return Ok(a);
- }
_ => {}
}
- ty::relate::super_relate_consts(relation, a, b)
+ ty::relate::structurally_relate_consts(relation, a, b)
}
/// Unifies the const variable `target_vid` with the given constant.
@@ -299,24 +277,17 @@ impl<'tcx> InferCtxt<'tcx> {
&self,
target_vid: ty::ConstVid<'tcx>,
ct: ty::Const<'tcx>,
+ param_env: ty::ParamEnv<'tcx>,
) -> RelateResult<'tcx, ty::Const<'tcx>> {
- let (for_universe, span) = {
- let mut inner = self.inner.borrow_mut();
- let variable_table = &mut inner.const_unification_table();
- let var_value = variable_table.probe_value(target_vid);
- match var_value.val {
- ConstVariableValue::Known { value } => {
- bug!("instantiating {:?} which has a known value {:?}", target_vid, value)
- }
- ConstVariableValue::Unknown { universe } => (universe, var_value.origin.span),
- }
- };
- let value = ct.try_fold_with(&mut ConstInferUnifier {
- infcx: self,
- span,
- for_universe,
+ let span =
+ self.inner.borrow_mut().const_unification_table().probe_value(target_vid).origin.span;
+ let Generalization { value, needs_wf: _ } = generalize::generalize(
+ self,
+ &mut CombineDelegate { infcx: self, span, param_env },
+ ct,
target_vid,
- })?;
+ ty::Variance::Invariant,
+ )?;
self.inner.borrow_mut().const_unification_table().union_value(
target_vid,
@@ -397,12 +368,10 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
pub fn instantiate(
&mut self,
a_ty: Ty<'tcx>,
- dir: RelationDir,
+ ambient_variance: ty::Variance,
b_vid: ty::TyVid,
a_is_expected: bool,
) -> RelateResult<'tcx, ()> {
- use self::RelationDir::*;
-
// Get the actual variable that b_vid has been inferred to
debug_assert!(self.infcx.inner.borrow_mut().type_variables().probe(b_vid).is_unknown());
@@ -417,7 +386,18 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
// `'?2` and `?3` are fresh region/type inference
// variables. (Down below, we will relate `a_ty <: b_ty`,
// adding constraints like `'x: '?2` and `?1 <: ?3`.)
- let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
+ let Generalization { value: b_ty, needs_wf } = generalize::generalize(
+ self.infcx,
+ &mut CombineDelegate {
+ infcx: self.infcx,
+ param_env: self.param_env,
+ span: self.trace.span(),
+ },
+ a_ty,
+ b_vid,
+ ambient_variance,
+ )?;
+
debug!(?b_ty);
self.infcx.inner.borrow_mut().type_variables().instantiate(b_vid, b_ty);
@@ -436,78 +416,23 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
// relations wind up attributed to the same spans. We need
// to associate causes/spans with each of the relations in
// the stack to get this right.
- match dir {
- EqTo => self.equate(a_is_expected).relate(a_ty, b_ty),
- SubtypeOf => self.sub(a_is_expected).relate(a_ty, b_ty),
- SupertypeOf => self.sub(a_is_expected).relate_with_variance(
+ match ambient_variance {
+ ty::Variance::Invariant => self.equate(a_is_expected).relate(a_ty, b_ty),
+ ty::Variance::Covariant => self.sub(a_is_expected).relate(a_ty, b_ty),
+ ty::Variance::Contravariant => self.sub(a_is_expected).relate_with_variance(
ty::Contravariant,
ty::VarianceDiagInfo::default(),
a_ty,
b_ty,
),
+ ty::Variance::Bivariant => {
+ unreachable!("no code should be generalizing bivariantly (currently)")
+ }
}?;
Ok(())
}
- /// Attempts to generalize `ty` for the type variable `for_vid`.
- /// This checks for cycle -- that is, whether the type `ty`
- /// references `for_vid`. The `dir` is the "direction" for which we
- /// a performing the generalization (i.e., are we producing a type
- /// that can be used as a supertype etc).
- ///
- /// Preconditions:
- ///
- /// - `for_vid` is a "root vid"
- #[instrument(skip(self), level = "trace", ret)]
- fn generalize(
- &self,
- ty: Ty<'tcx>,
- for_vid: ty::TyVid,
- dir: RelationDir,
- ) -> RelateResult<'tcx, Generalization<'tcx>> {
- // Determine the ambient variance within which `ty` appears.
- // The surrounding equation is:
- //
- // ty [op] ty2
- //
- // where `op` is either `==`, `<:`, or `:>`. This maps quite
- // naturally.
- let ambient_variance = match dir {
- RelationDir::EqTo => ty::Invariant,
- RelationDir::SubtypeOf => ty::Covariant,
- RelationDir::SupertypeOf => ty::Contravariant,
- };
-
- trace!(?ambient_variance);
-
- let for_universe = match self.infcx.inner.borrow_mut().type_variables().probe(for_vid) {
- v @ TypeVariableValue::Known { .. } => {
- bug!("instantiating {:?} which has a known value {:?}", for_vid, v,)
- }
- TypeVariableValue::Unknown { universe } => universe,
- };
-
- trace!(?for_universe);
- trace!(?self.trace);
-
- let mut generalize = Generalizer {
- infcx: self.infcx,
- cause: &self.trace.cause,
- for_vid_sub_root: self.infcx.inner.borrow_mut().type_variables().sub_root_var(for_vid),
- for_universe,
- ambient_variance,
- needs_wf: false,
- root_ty: ty,
- param_env: self.param_env,
- cache: SsoHashMap::new(),
- };
-
- let ty = generalize.relate(ty, ty)?;
- let needs_wf = generalize.needs_wf;
- Ok(Generalization { ty, needs_wf })
- }
-
pub fn register_obligations(&mut self, obligations: PredicateObligations<'tcx>) {
self.obligations.extend(obligations.into_iter());
}
@@ -519,320 +444,13 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
}
}
-struct Generalizer<'cx, 'tcx> {
- infcx: &'cx InferCtxt<'tcx>,
-
- /// The span, used when creating new type variables and things.
- cause: &'cx ObligationCause<'tcx>,
-
- /// The vid of the type variable that is in the process of being
- /// instantiated; if we find this within the type we are folding,
- /// that means we would have created a cyclic type.
- for_vid_sub_root: ty::TyVid,
-
- /// The universe of the type variable that is in the process of
- /// being instantiated. Any fresh variables that we create in this
- /// process should be in that same universe.
- for_universe: ty::UniverseIndex,
-
- /// Track the variance as we descend into the type.
- ambient_variance: ty::Variance,
-
- /// See the field `needs_wf` in `Generalization`.
- needs_wf: bool,
-
- /// The root type that we are generalizing. Used when reporting cycles.
- root_ty: Ty<'tcx>,
-
- param_env: ty::ParamEnv<'tcx>,
-
- cache: SsoHashMap<Ty<'tcx>, Ty<'tcx>>,
-}
-
-/// Result from a generalization operation. This includes
-/// not only the generalized type, but also a bool flag
-/// indicating whether further WF checks are needed.
-#[derive(Debug)]
-struct Generalization<'tcx> {
- ty: Ty<'tcx>,
-
- /// If true, then the generalized type may not be well-formed,
- /// even if the source type is well-formed, so we should add an
- /// additional check to enforce that it is. This arises in
- /// particular around 'bivariant' type parameters that are only
- /// constrained by a where-clause. As an example, imagine a type:
- ///
- /// struct Foo<A, B> where A: Iterator<Item = B> {
- /// data: A
- /// }
- ///
- /// here, `A` will be covariant, but `B` is
- /// unconstrained. However, whatever it is, for `Foo` to be WF, it
- /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
- /// then after generalization we will wind up with a type like
- /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
- /// ?D>` (or `>:`), we will wind up with the requirement that `?A
- /// <: ?C`, but no particular relationship between `?B` and `?D`
- /// (after all, we do not know the variance of the normalized form
- /// of `A::Item` with respect to `A`). If we do nothing else, this
- /// may mean that `?D` goes unconstrained (as in #41677). So, in
- /// this scenario where we create a new type variable in a
- /// bivariant context, we set the `needs_wf` flag to true. This
- /// will force the calling code to check that `WF(Foo<?C, ?D>)`
- /// holds, which in turn implies that `?C::Item == ?D`. So once
- /// `?C` is constrained, that should suffice to restrict `?D`.
- needs_wf: bool,
-}
-
-impl<'tcx> TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
- fn tcx(&self) -> TyCtxt<'tcx> {
- self.infcx.tcx
- }
-
- fn param_env(&self) -> ty::ParamEnv<'tcx> {
- self.param_env
- }
-
- fn tag(&self) -> &'static str {
- "Generalizer"
- }
-
- fn a_is_expected(&self) -> bool {
- true
- }
-
- fn binders<T>(
- &mut self,
- a: ty::Binder<'tcx, T>,
- b: ty::Binder<'tcx, T>,
- ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
- where
- T: Relate<'tcx>,
- {
- Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
- }
-
- fn relate_item_substs(
- &mut self,
- item_def_id: DefId,
- a_subst: SubstsRef<'tcx>,
- b_subst: SubstsRef<'tcx>,
- ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
- if self.ambient_variance == ty::Variance::Invariant {
- // Avoid fetching the variance if we are in an invariant
- // context; no need, and it can induce dependency cycles
- // (e.g., #41849).
- relate::relate_substs(self, a_subst, b_subst)
- } else {
- let tcx = self.tcx();
- let opt_variances = tcx.variances_of(item_def_id);
- relate::relate_substs_with_variances(
- self,
- item_def_id,
- &opt_variances,
- a_subst,
- b_subst,
- true,
- )
- }
- }
-
- fn relate_with_variance<T: Relate<'tcx>>(
- &mut self,
- variance: ty::Variance,
- _info: ty::VarianceDiagInfo<'tcx>,
- a: T,
- b: T,
- ) -> RelateResult<'tcx, T> {
- let old_ambient_variance = self.ambient_variance;
- self.ambient_variance = self.ambient_variance.xform(variance);
-
- let result = self.relate(a, b);
- self.ambient_variance = old_ambient_variance;
- result
- }
-
- fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
- assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
-
- if let Some(&result) = self.cache.get(&t) {
- return Ok(result);
- }
- debug!("generalize: t={:?}", t);
-
- // Check to see whether the type we are generalizing references
- // any other type variable related to `vid` via
- // subtyping. This is basically our "occurs check", preventing
- // us from creating infinitely sized types.
- let result = match *t.kind() {
- ty::Infer(ty::TyVar(vid)) => {
- let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
- let sub_vid = self.infcx.inner.borrow_mut().type_variables().sub_root_var(vid);
- if sub_vid == self.for_vid_sub_root {
- // If sub-roots are equal, then `for_vid` and
- // `vid` are related via subtyping.
- Err(TypeError::CyclicTy(self.root_ty))
- } else {
- let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
- match probe {
- TypeVariableValue::Known { value: u } => {
- debug!("generalize: known value {:?}", u);
- self.relate(u, u)
- }
- TypeVariableValue::Unknown { universe } => {
- match self.ambient_variance {
- // Invariant: no need to make a fresh type variable.
- ty::Invariant => {
- if self.for_universe.can_name(universe) {
- return Ok(t);
- }
- }
-
- // Bivariant: make a fresh var, but we
- // may need a WF predicate. See
- // comment on `needs_wf` field for
- // more info.
- ty::Bivariant => self.needs_wf = true,
-
- // Co/contravariant: this will be
- // sufficiently constrained later on.
- ty::Covariant | ty::Contravariant => (),
- }
-
- let origin =
- *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
- let new_var_id = self
- .infcx
- .inner
- .borrow_mut()
- .type_variables()
- .new_var(self.for_universe, origin);
- let u = self.tcx().mk_ty_var(new_var_id);
-
- // Record that we replaced `vid` with `new_var_id` as part of a generalization
- // operation. This is needed to detect cyclic types. To see why, see the
- // docs in the `type_variables` module.
- self.infcx.inner.borrow_mut().type_variables().sub(vid, new_var_id);
- debug!("generalize: replacing original vid={:?} with new={:?}", vid, u);
- Ok(u)
- }
- }
- }
- }
- ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
- // No matter what mode we are in,
- // integer/floating-point types must be equal to be
- // relatable.
- Ok(t)
- }
- ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
- let s = self.relate(substs, substs)?;
- Ok(if s == substs { t } else { self.infcx.tcx.mk_opaque(def_id, s) })
- }
- _ => relate::super_relate_tys(self, t, t),
- }?;
-
- self.cache.insert(t, result);
- Ok(result)
- }
-
- fn regions(
- &mut self,
- r: ty::Region<'tcx>,
- r2: ty::Region<'tcx>,
- ) -> RelateResult<'tcx, ty::Region<'tcx>> {
- assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
-
- debug!("generalize: regions r={:?}", r);
-
- match *r {
- // Never make variables for regions bound within the type itself,
- // nor for erased regions.
- ty::ReLateBound(..) | ty::ReErased => {
- return Ok(r);
- }
-
- ty::ReError(_) => {
- return Ok(r);
- }
-
- ty::RePlaceholder(..)
- | ty::ReVar(..)
- | ty::ReStatic
- | ty::ReEarlyBound(..)
- | ty::ReFree(..) => {
- // see common code below
- }
- }
-
- // If we are in an invariant context, we can re-use the region
- // as is, unless it happens to be in some universe that we
- // can't name. (In the case of a region *variable*, we could
- // use it if we promoted it into our universe, but we don't
- // bother.)
- if let ty::Invariant = self.ambient_variance {
- let r_universe = self.infcx.universe_of_region(r);
- if self.for_universe.can_name(r_universe) {
- return Ok(r);
- }
- }
-
- // FIXME: This is non-ideal because we don't give a
- // very descriptive origin for this region variable.
- Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.cause.span), self.for_universe))
- }
-
- fn consts(
- &mut self,
- c: ty::Const<'tcx>,
- c2: ty::Const<'tcx>,
- ) -> RelateResult<'tcx, ty::Const<'tcx>> {
- assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
-
- match c.kind() {
- ty::ConstKind::Infer(InferConst::Var(vid)) => {
- let mut inner = self.infcx.inner.borrow_mut();
- let variable_table = &mut inner.const_unification_table();
- let var_value = variable_table.probe_value(vid);
- match var_value.val {
- ConstVariableValue::Known { value: u } => {
- drop(inner);
- self.relate(u, u)
- }
- ConstVariableValue::Unknown { universe } => {
- if self.for_universe.can_name(universe) {
- Ok(c)
- } else {
- let new_var_id = variable_table.new_key(ConstVarValue {
- origin: var_value.origin,
- val: ConstVariableValue::Unknown { universe: self.for_universe },
- });
- Ok(self.tcx().mk_const(new_var_id, c.ty()))
- }
- }
- }
- }
- ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
- let substs = self.relate_with_variance(
- ty::Variance::Invariant,
- ty::VarianceDiagInfo::default(),
- substs,
- substs,
- )?;
- Ok(self.tcx().mk_const(ty::UnevaluatedConst { def, substs }, c.ty()))
- }
- _ => relate::super_relate_consts(self, c, c),
- }
- }
-}
-
pub trait ObligationEmittingRelation<'tcx>: TypeRelation<'tcx> {
/// Register obligations that must hold in order for this relation to hold
fn register_obligations(&mut self, obligations: PredicateObligations<'tcx>);
/// Register predicates that must hold in order for this relation to hold. Uses
/// a default obligation cause, [`ObligationEmittingRelation::register_obligations`] should
- /// be used if control over the obligaton causes is required.
+ /// be used if control over the obligation causes is required.
fn register_predicates(&mut self, obligations: impl IntoIterator<Item: ToPredicate<'tcx>>);
/// Register an obligation that both constants must be equal to each other.
@@ -878,135 +496,3 @@ fn float_unification_error<'tcx>(
let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
TypeError::FloatMismatch(ExpectedFound::new(a_is_expected, a, b))
}
-
-struct ConstInferUnifier<'cx, 'tcx> {
- infcx: &'cx InferCtxt<'tcx>,
-
- span: Span,
-
- for_universe: ty::UniverseIndex,
-
- /// The vid of the const variable that is in the process of being
- /// instantiated; if we find this within the const we are folding,
- /// that means we would have created a cyclic const.
- target_vid: ty::ConstVid<'tcx>,
-}
-
-impl<'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for ConstInferUnifier<'_, 'tcx> {
- type Error = TypeError<'tcx>;
-
- fn interner(&self) -> TyCtxt<'tcx> {
- self.infcx.tcx
- }
-
- #[instrument(level = "debug", skip(self), ret)]
- fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, TypeError<'tcx>> {
- match t.kind() {
- &ty::Infer(ty::TyVar(vid)) => {
- let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
- let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
- match probe {
- TypeVariableValue::Known { value: u } => {
- debug!("ConstOccursChecker: known value {:?}", u);
- u.try_fold_with(self)
- }
- TypeVariableValue::Unknown { universe } => {
- if self.for_universe.can_name(universe) {
- return Ok(t);
- }
-
- let origin =
- *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
- let new_var_id = self
- .infcx
- .inner
- .borrow_mut()
- .type_variables()
- .new_var(self.for_universe, origin);
- Ok(self.interner().mk_ty_var(new_var_id))
- }
- }
- }
- ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => Ok(t),
- _ => t.try_super_fold_with(self),
- }
- }
-
- #[instrument(level = "debug", skip(self), ret)]
- fn try_fold_region(
- &mut self,
- r: ty::Region<'tcx>,
- ) -> Result<ty::Region<'tcx>, TypeError<'tcx>> {
- debug!("ConstInferUnifier: r={:?}", r);
-
- match *r {
- // Never make variables for regions bound within the type itself,
- // nor for erased regions.
- ty::ReLateBound(..) | ty::ReErased | ty::ReError(_) => {
- return Ok(r);
- }
-
- ty::RePlaceholder(..)
- | ty::ReVar(..)
- | ty::ReStatic
- | ty::ReEarlyBound(..)
- | ty::ReFree(..) => {
- // see common code below
- }
- }
-
- let r_universe = self.infcx.universe_of_region(r);
- if self.for_universe.can_name(r_universe) {
- return Ok(r);
- } else {
- // FIXME: This is non-ideal because we don't give a
- // very descriptive origin for this region variable.
- Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
- }
- }
-
- #[instrument(level = "debug", skip(self), ret)]
- fn try_fold_const(&mut self, c: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, TypeError<'tcx>> {
- match c.kind() {
- ty::ConstKind::Infer(InferConst::Var(vid)) => {
- // Check if the current unification would end up
- // unifying `target_vid` with a const which contains
- // an inference variable which is unioned with `target_vid`.
- //
- // Not doing so can easily result in stack overflows.
- if self
- .infcx
- .inner
- .borrow_mut()
- .const_unification_table()
- .unioned(self.target_vid, vid)
- {
- return Err(TypeError::CyclicConst(c));
- }
-
- let var_value =
- self.infcx.inner.borrow_mut().const_unification_table().probe_value(vid);
- match var_value.val {
- ConstVariableValue::Known { value: u } => u.try_fold_with(self),
- ConstVariableValue::Unknown { universe } => {
- if self.for_universe.can_name(universe) {
- Ok(c)
- } else {
- let new_var_id =
- self.infcx.inner.borrow_mut().const_unification_table().new_key(
- ConstVarValue {
- origin: var_value.origin,
- val: ConstVariableValue::Unknown {
- universe: self.for_universe,
- },
- },
- );
- Ok(self.interner().mk_const(new_var_id, c.ty()))
- }
- }
- }
- }
- _ => c.try_super_fold_with(self),
- }
- }
-}