1 ///////////////////////////////////////////////////////////////////////////
4 // There are four type combiners: equate, sub, lub, and glb. Each
5 // implements the trait `Combine` and contains methods for combining
6 // two instances of various things and yielding a new instance. These
7 // combiner methods always yield a `Result<T>`. There is a lot of
8 // common code for these operations, implemented as default methods on
9 // the `Combine` trait.
11 // Each operation may have side-effects on the inference context,
12 // though these can be unrolled using snapshots. On success, the
13 // LUB/GLB operations return the appropriate bound. The Eq and Sub
14 // operations generally return the first operand.
18 // When you are relating two things which have a contravariant
19 // relationship, you should use `contratys()` or `contraregions()`,
20 // rather than inversing the order of arguments! This is necessary
21 // because the order of arguments is not relevant for LUB and GLB. It
22 // is also useful to track which value is the "expected" value in
23 // terms of error reporting.
25 use super::equate::Equate;
29 use super::type_variable::TypeVariableValue;
30 use super::unify_key::replace_if_possible;
31 use super::unify_key::{ConstVarValue, ConstVariableValue};
32 use super::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
33 use super::{InferCtxt, MiscVariable, TypeTrace};
35 use crate::traits::{Obligation, PredicateObligations};
38 use rustc_hir::def_id::DefId;
39 use rustc_middle::traits::ObligationCause;
40 use rustc_middle::ty::error::TypeError;
41 use rustc_middle::ty::relate::{self, Relate, RelateResult, TypeRelation};
42 use rustc_middle::ty::subst::SubstsRef;
43 use rustc_middle::ty::{self, InferConst, ToPredicate, Ty, TyCtxt, TypeFoldable};
44 use rustc_middle::ty::{IntType, UintType};
45 use rustc_span::DUMMY_SP;
48 pub struct CombineFields<'infcx, 'tcx> {
49 pub infcx: &'infcx InferCtxt<'infcx, 'tcx>,
50 pub trace: TypeTrace<'tcx>,
51 pub cause: Option<ty::relate::Cause>,
52 pub param_env: ty::ParamEnv<'tcx>,
53 pub obligations: PredicateObligations<'tcx>,
56 #[derive(Copy, Clone, Debug)]
57 pub enum RelationDir {
63 impl<'infcx, 'tcx> InferCtxt<'infcx, 'tcx> {
64 pub fn super_combine_tys<R>(
69 ) -> RelateResult<'tcx, Ty<'tcx>>
71 R: TypeRelation<'tcx>,
73 let a_is_expected = relation.a_is_expected();
75 match (&a.kind, &b.kind) {
76 // Relate integral variables to other types
77 (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => {
80 .int_unification_table()
81 .unify_var_var(a_id, b_id)
82 .map_err(|e| int_unification_error(a_is_expected, e))?;
85 (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
86 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
88 (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
89 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
91 (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
92 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
94 (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
95 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
98 // Relate floating-point variables to other types
99 (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
102 .float_unification_table()
103 .unify_var_var(a_id, b_id)
104 .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
107 (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
108 self.unify_float_variable(a_is_expected, v_id, v)
110 (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
111 self.unify_float_variable(!a_is_expected, v_id, v)
114 // All other cases of inference are errors
115 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
116 Err(TypeError::Sorts(ty::relate::expected_found(relation, a, b)))
119 _ => ty::relate::super_relate_tys(relation, a, b),
123 pub fn super_combine_consts<R>(
126 a: &'tcx ty::Const<'tcx>,
127 b: &'tcx ty::Const<'tcx>,
128 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>
130 R: ConstEquateRelation<'tcx>,
132 debug!("{}.consts({:?}, {:?})", relation.tag(), a, b);
137 let a = replace_if_possible(&mut self.inner.borrow_mut().const_unification_table(), a);
138 let b = replace_if_possible(&mut self.inner.borrow_mut().const_unification_table(), b);
140 let a_is_expected = relation.a_is_expected();
142 match (a.val, b.val) {
144 ty::ConstKind::Infer(InferConst::Var(a_vid)),
145 ty::ConstKind::Infer(InferConst::Var(b_vid)),
149 .const_unification_table()
150 .unify_var_var(a_vid, b_vid)
151 .map_err(|e| const_unification_error(a_is_expected, e))?;
155 // All other cases of inference with other variables are errors.
156 (ty::ConstKind::Infer(InferConst::Var(_)), ty::ConstKind::Infer(_))
157 | (ty::ConstKind::Infer(_), ty::ConstKind::Infer(InferConst::Var(_))) => {
158 bug!("tried to combine ConstKind::Infer/ConstKind::Infer(InferConst::Var)")
161 (ty::ConstKind::Infer(InferConst::Var(vid)), _) => {
162 return self.unify_const_variable(a_is_expected, vid, b);
165 (_, ty::ConstKind::Infer(InferConst::Var(vid))) => {
166 return self.unify_const_variable(!a_is_expected, vid, a);
168 (ty::ConstKind::Unevaluated(..), _) if self.tcx.lazy_normalization() => {
169 // FIXME(#59490): Need to remove the leak check to accomodate
170 // escaping bound variables here.
171 if !a.has_escaping_bound_vars() && !b.has_escaping_bound_vars() {
172 relation.const_equate_obligation(a, b);
176 (_, ty::ConstKind::Unevaluated(..)) if self.tcx.lazy_normalization() => {
177 // FIXME(#59490): Need to remove the leak check to accomodate
178 // escaping bound variables here.
179 if !a.has_escaping_bound_vars() && !b.has_escaping_bound_vars() {
180 relation.const_equate_obligation(a, b);
187 ty::relate::super_relate_consts(relation, a, b)
190 pub fn unify_const_variable(
192 vid_is_expected: bool,
193 vid: ty::ConstVid<'tcx>,
194 value: &'tcx ty::Const<'tcx>,
195 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
198 .const_unification_table()
202 origin: ConstVariableOrigin {
203 kind: ConstVariableOriginKind::ConstInference,
206 val: ConstVariableValue::Known { value },
209 .map_err(|e| const_unification_error(vid_is_expected, e))?;
213 fn unify_integral_variable(
215 vid_is_expected: bool,
217 val: ty::IntVarValue,
218 ) -> RelateResult<'tcx, Ty<'tcx>> {
221 .int_unification_table()
222 .unify_var_value(vid, Some(val))
223 .map_err(|e| int_unification_error(vid_is_expected, e))?;
225 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
226 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
230 fn unify_float_variable(
232 vid_is_expected: bool,
235 ) -> RelateResult<'tcx, Ty<'tcx>> {
238 .float_unification_table()
239 .unify_var_value(vid, Some(ty::FloatVarValue(val)))
240 .map_err(|e| float_unification_error(vid_is_expected, e))?;
241 Ok(self.tcx.mk_mach_float(val))
245 impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
246 pub fn tcx(&self) -> TyCtxt<'tcx> {
250 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'tcx> {
251 Equate::new(self, a_is_expected)
254 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'tcx> {
255 Sub::new(self, a_is_expected)
258 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'tcx> {
259 Lub::new(self, a_is_expected)
262 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'tcx> {
263 Glb::new(self, a_is_expected)
266 /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
267 /// The idea is that we should ensure that the type `a_ty` is equal
268 /// to, a subtype of, or a supertype of (respectively) the type
269 /// to which `b_vid` is bound.
271 /// Since `b_vid` has not yet been instantiated with a type, we
272 /// will first instantiate `b_vid` with a *generalized* version
273 /// of `a_ty`. Generalization introduces other inference
274 /// variables wherever subtyping could occur.
281 ) -> RelateResult<'tcx, ()> {
282 use self::RelationDir::*;
284 // Get the actual variable that b_vid has been inferred to
285 debug_assert!(self.infcx.inner.borrow_mut().type_variables().probe(b_vid).is_unknown());
287 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
289 // Generalize type of `a_ty` appropriately depending on the
290 // direction. As an example, assume:
292 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
293 // inference variable,
294 // - and `dir` == `SubtypeOf`.
296 // Then the generalized form `b_ty` would be `&'?2 ?3`, where
297 // `'?2` and `?3` are fresh region/type inference
298 // variables. (Down below, we will relate `a_ty <: b_ty`,
299 // adding constraints like `'x: '?2` and `?1 <: ?3`.)
300 let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
302 "instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
303 a_ty, dir, b_vid, b_ty
305 self.infcx.inner.borrow_mut().type_variables().instantiate(b_vid, b_ty);
308 self.obligations.push(Obligation::new(
309 self.trace.cause.clone(),
311 ty::PredicateKind::WellFormed(b_ty.into()).to_predicate(self.infcx.tcx),
315 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
317 // FIXME(#16847): This code is non-ideal because all these subtype
318 // relations wind up attributed to the same spans. We need
319 // to associate causes/spans with each of the relations in
320 // the stack to get this right.
322 EqTo => self.equate(a_is_expected).relate(a_ty, b_ty),
323 SubtypeOf => self.sub(a_is_expected).relate(a_ty, b_ty),
325 self.sub(a_is_expected).relate_with_variance(ty::Contravariant, a_ty, b_ty)
332 /// Attempts to generalize `ty` for the type variable `for_vid`.
333 /// This checks for cycle -- that is, whether the type `ty`
334 /// references `for_vid`. The `dir` is the "direction" for which we
335 /// a performing the generalization (i.e., are we producing a type
336 /// that can be used as a supertype etc).
340 /// - `for_vid` is a "root vid"
346 ) -> RelateResult<'tcx, Generalization<'tcx>> {
347 debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
348 // Determine the ambient variance within which `ty` appears.
349 // The surrounding equation is:
353 // where `op` is either `==`, `<:`, or `:>`. This maps quite
355 let ambient_variance = match dir {
356 RelationDir::EqTo => ty::Invariant,
357 RelationDir::SubtypeOf => ty::Covariant,
358 RelationDir::SupertypeOf => ty::Contravariant,
361 debug!("generalize: ambient_variance = {:?}", ambient_variance);
363 let for_universe = match self.infcx.inner.borrow_mut().type_variables().probe(for_vid) {
364 v @ TypeVariableValue::Known { .. } => {
365 panic!("instantiating {:?} which has a known value {:?}", for_vid, v,)
367 TypeVariableValue::Unknown { universe } => universe,
370 debug!("generalize: for_universe = {:?}", for_universe);
371 debug!("generalize: trace = {:?}", self.trace);
373 let mut generalize = Generalizer {
375 cause: &self.trace.cause,
376 for_vid_sub_root: self.infcx.inner.borrow_mut().type_variables().sub_root_var(for_vid),
381 param_env: self.param_env,
384 let ty = match generalize.relate(ty, ty) {
387 debug!("generalize: failure {:?}", e);
391 let needs_wf = generalize.needs_wf;
392 debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
393 Ok(Generalization { ty, needs_wf })
396 pub fn add_const_equate_obligation(
399 a: &'tcx ty::Const<'tcx>,
400 b: &'tcx ty::Const<'tcx>,
402 let predicate = if a_is_expected {
403 ty::PredicateKind::ConstEquate(a, b)
405 ty::PredicateKind::ConstEquate(b, a)
407 self.obligations.push(Obligation::new(
408 self.trace.cause.clone(),
410 predicate.to_predicate(self.tcx()),
415 struct Generalizer<'cx, 'tcx> {
416 infcx: &'cx InferCtxt<'cx, 'tcx>,
418 /// The span, used when creating new type variables and things.
419 cause: &'cx ObligationCause<'tcx>,
421 /// The vid of the type variable that is in the process of being
422 /// instantiated; if we find this within the type we are folding,
423 /// that means we would have created a cyclic type.
424 for_vid_sub_root: ty::TyVid,
426 /// The universe of the type variable that is in the process of
427 /// being instantiated. Any fresh variables that we create in this
428 /// process should be in that same universe.
429 for_universe: ty::UniverseIndex,
431 /// Track the variance as we descend into the type.
432 ambient_variance: ty::Variance,
434 /// See the field `needs_wf` in `Generalization`.
437 /// The root type that we are generalizing. Used when reporting cycles.
440 param_env: ty::ParamEnv<'tcx>,
443 /// Result from a generalization operation. This includes
444 /// not only the generalized type, but also a bool flag
445 /// indicating whether further WF checks are needed.
446 struct Generalization<'tcx> {
449 /// If true, then the generalized type may not be well-formed,
450 /// even if the source type is well-formed, so we should add an
451 /// additional check to enforce that it is. This arises in
452 /// particular around 'bivariant' type parameters that are only
453 /// constrained by a where-clause. As an example, imagine a type:
455 /// struct Foo<A, B> where A: Iterator<Item = B> {
459 /// here, `A` will be covariant, but `B` is
460 /// unconstrained. However, whatever it is, for `Foo` to be WF, it
461 /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
462 /// then after generalization we will wind up with a type like
463 /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
464 /// ?D>` (or `>:`), we will wind up with the requirement that `?A
465 /// <: ?C`, but no particular relationship between `?B` and `?D`
466 /// (after all, we do not know the variance of the normalized form
467 /// of `A::Item` with respect to `A`). If we do nothing else, this
468 /// may mean that `?D` goes unconstrained (as in #41677). So, in
469 /// this scenario where we create a new type variable in a
470 /// bivariant context, we set the `needs_wf` flag to true. This
471 /// will force the calling code to check that `WF(Foo<?C, ?D>)`
472 /// holds, which in turn implies that `?C::Item == ?D`. So once
473 /// `?C` is constrained, that should suffice to restrict `?D`.
477 impl TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
478 fn tcx(&self) -> TyCtxt<'tcx> {
481 fn param_env(&self) -> ty::ParamEnv<'tcx> {
485 fn tag(&self) -> &'static str {
489 fn a_is_expected(&self) -> bool {
497 ) -> RelateResult<'tcx, ty::Binder<T>>
501 Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))
504 fn relate_item_substs(
507 a_subst: SubstsRef<'tcx>,
508 b_subst: SubstsRef<'tcx>,
509 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
510 if self.ambient_variance == ty::Variance::Invariant {
511 // Avoid fetching the variance if we are in an invariant
512 // context; no need, and it can induce dependency cycles
514 relate::relate_substs(self, None, a_subst, b_subst)
516 let opt_variances = self.tcx().variances_of(item_def_id);
517 relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
521 fn relate_with_variance<T: Relate<'tcx>>(
523 variance: ty::Variance,
526 ) -> RelateResult<'tcx, T> {
527 let old_ambient_variance = self.ambient_variance;
528 self.ambient_variance = self.ambient_variance.xform(variance);
530 let result = self.relate(a, b);
531 self.ambient_variance = old_ambient_variance;
535 fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
536 assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
538 debug!("generalize: t={:?}", t);
540 // Check to see whether the type we are generalizing references
541 // any other type variable related to `vid` via
542 // subtyping. This is basically our "occurs check", preventing
543 // us from creating infinitely sized types.
545 ty::Infer(ty::TyVar(vid)) => {
546 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
547 let sub_vid = self.infcx.inner.borrow_mut().type_variables().sub_root_var(vid);
548 if sub_vid == self.for_vid_sub_root {
549 // If sub-roots are equal, then `for_vid` and
550 // `vid` are related via subtyping.
551 Err(TypeError::CyclicTy(self.root_ty))
553 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
555 TypeVariableValue::Known { value: u } => {
556 debug!("generalize: known value {:?}", u);
559 TypeVariableValue::Unknown { universe } => {
560 match self.ambient_variance {
561 // Invariant: no need to make a fresh type variable.
563 if self.for_universe.can_name(universe) {
568 // Bivariant: make a fresh var, but we
569 // may need a WF predicate. See
570 // comment on `needs_wf` field for
572 ty::Bivariant => self.needs_wf = true,
574 // Co/contravariant: this will be
575 // sufficiently constrained later on.
576 ty::Covariant | ty::Contravariant => (),
580 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
581 let new_var_id = self
586 .new_var(self.for_universe, false, origin);
587 let u = self.tcx().mk_ty_var(new_var_id);
588 debug!("generalize: replacing original vid={:?} with new={:?}", vid, u);
594 ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
595 // No matter what mode we are in,
596 // integer/floating-point types must be equal to be
600 _ => relate::super_relate_tys(self, t, t),
607 r2: ty::Region<'tcx>,
608 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
609 assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
611 debug!("generalize: regions r={:?}", r);
614 // Never make variables for regions bound within the type itself,
615 // nor for erased regions.
616 ty::ReLateBound(..) | ty::ReErased => {
620 ty::RePlaceholder(..)
624 | ty::ReEarlyBound(..)
625 | ty::ReFree(..) => {
626 // see common code below
630 // If we are in an invariant context, we can re-use the region
631 // as is, unless it happens to be in some universe that we
632 // can't name. (In the case of a region *variable*, we could
633 // use it if we promoted it into our universe, but we don't
635 if let ty::Invariant = self.ambient_variance {
636 let r_universe = self.infcx.universe_of_region(r);
637 if self.for_universe.can_name(r_universe) {
642 // FIXME: This is non-ideal because we don't give a
643 // very descriptive origin for this region variable.
644 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.cause.span), self.for_universe))
649 c: &'tcx ty::Const<'tcx>,
650 c2: &'tcx ty::Const<'tcx>,
651 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
652 assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
655 ty::ConstKind::Infer(InferConst::Var(vid)) => {
656 let mut inner = self.infcx.inner.borrow_mut();
657 let variable_table = &mut inner.const_unification_table();
658 let var_value = variable_table.probe_value(vid);
659 match var_value.val {
660 ConstVariableValue::Known { value: u } => self.relate(u, u),
661 ConstVariableValue::Unknown { universe } => {
662 if self.for_universe.can_name(universe) {
665 let new_var_id = variable_table.new_key(ConstVarValue {
666 origin: var_value.origin,
667 val: ConstVariableValue::Unknown { universe: self.for_universe },
669 Ok(self.tcx().mk_const_var(new_var_id, c.ty))
674 ty::ConstKind::Unevaluated(..) if self.tcx().lazy_normalization() => Ok(c),
675 _ => relate::super_relate_consts(self, c, c),
680 pub trait ConstEquateRelation<'tcx>: TypeRelation<'tcx> {
681 /// Register an obligation that both constants must be equal to each other.
683 /// If they aren't equal then the relation doesn't hold.
684 fn const_equate_obligation(&mut self, a: &'tcx ty::Const<'tcx>, b: &'tcx ty::Const<'tcx>);
687 pub trait RelateResultCompare<'tcx, T> {
688 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
690 F: FnOnce() -> TypeError<'tcx>;
693 impl<'tcx, T: Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
694 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
696 F: FnOnce() -> TypeError<'tcx>,
698 self.clone().and_then(|s| if s == t { self.clone() } else { Err(f()) })
702 pub fn const_unification_error<'tcx>(
704 (a, b): (&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>),
705 ) -> TypeError<'tcx> {
706 TypeError::ConstMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))
709 fn int_unification_error<'tcx>(
711 v: (ty::IntVarValue, ty::IntVarValue),
712 ) -> TypeError<'tcx> {
714 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))
717 fn float_unification_error<'tcx>(
719 v: (ty::FloatVarValue, ty::FloatVarValue),
720 ) -> TypeError<'tcx> {
721 let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
722 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))