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::ty::error::TypeError;
40 use rustc_middle::ty::relate::{self, Relate, RelateResult, TypeRelation};
41 use rustc_middle::ty::subst::SubstsRef;
42 use rustc_middle::ty::{self, InferConst, Ty, TyCtxt};
43 use rustc_middle::ty::{IntType, UintType};
44 use rustc_span::{Span, DUMMY_SP};
47 pub struct CombineFields<'infcx, 'tcx> {
48 pub infcx: &'infcx InferCtxt<'infcx, 'tcx>,
49 pub trace: TypeTrace<'tcx>,
50 pub cause: Option<ty::relate::Cause>,
51 pub param_env: ty::ParamEnv<'tcx>,
52 pub obligations: PredicateObligations<'tcx>,
55 #[derive(Copy, Clone, Debug)]
56 pub enum RelationDir {
62 impl<'infcx, 'tcx> InferCtxt<'infcx, 'tcx> {
63 pub fn super_combine_tys<R>(
68 ) -> RelateResult<'tcx, Ty<'tcx>>
70 R: TypeRelation<'tcx>,
72 let a_is_expected = relation.a_is_expected();
74 match (&a.kind, &b.kind) {
75 // Relate integral variables to other types
76 (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => {
79 .int_unification_table()
80 .unify_var_var(a_id, b_id)
81 .map_err(|e| int_unification_error(a_is_expected, e))?;
84 (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
85 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
87 (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
88 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
90 (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
91 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
93 (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
94 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
97 // Relate floating-point variables to other types
98 (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
101 .float_unification_table()
102 .unify_var_var(a_id, b_id)
103 .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
106 (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
107 self.unify_float_variable(a_is_expected, v_id, v)
109 (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
110 self.unify_float_variable(!a_is_expected, v_id, v)
113 // All other cases of inference are errors
114 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
115 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
118 _ => ty::relate::super_relate_tys(relation, a, b),
122 pub fn super_combine_consts<R>(
125 a: &'tcx ty::Const<'tcx>,
126 b: &'tcx ty::Const<'tcx>,
127 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>
129 R: TypeRelation<'tcx>,
131 debug!("{}.consts({:?}, {:?})", relation.tag(), a, b);
136 let a = replace_if_possible(&mut self.inner.borrow_mut().const_unification_table(), a);
137 let b = replace_if_possible(&mut self.inner.borrow_mut().const_unification_table(), b);
139 let a_is_expected = relation.a_is_expected();
141 match (a.val, b.val) {
143 ty::ConstKind::Infer(InferConst::Var(a_vid)),
144 ty::ConstKind::Infer(InferConst::Var(b_vid)),
148 .const_unification_table()
149 .unify_var_var(a_vid, b_vid)
150 .map_err(|e| const_unification_error(a_is_expected, e))?;
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(a_is_expected, vid, b);
164 (_, ty::ConstKind::Infer(InferConst::Var(vid))) => {
165 return self.unify_const_variable(!a_is_expected, vid, a);
171 ty::relate::super_relate_consts(relation, a, b)
174 pub fn unify_const_variable(
176 vid_is_expected: bool,
177 vid: ty::ConstVid<'tcx>,
178 value: &'tcx ty::Const<'tcx>,
179 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
182 .const_unification_table()
186 origin: ConstVariableOrigin {
187 kind: ConstVariableOriginKind::ConstInference,
190 val: ConstVariableValue::Known { value },
193 .map_err(|e| const_unification_error(vid_is_expected, e))?;
197 fn unify_integral_variable(
199 vid_is_expected: bool,
201 val: ty::IntVarValue,
202 ) -> RelateResult<'tcx, Ty<'tcx>> {
205 .int_unification_table()
206 .unify_var_value(vid, Some(val))
207 .map_err(|e| int_unification_error(vid_is_expected, e))?;
209 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
210 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
214 fn unify_float_variable(
216 vid_is_expected: bool,
219 ) -> RelateResult<'tcx, Ty<'tcx>> {
222 .float_unification_table()
223 .unify_var_value(vid, Some(ty::FloatVarValue(val)))
224 .map_err(|e| float_unification_error(vid_is_expected, e))?;
225 Ok(self.tcx.mk_mach_float(val))
229 impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
230 pub fn tcx(&self) -> TyCtxt<'tcx> {
234 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'tcx> {
235 Equate::new(self, a_is_expected)
238 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'tcx> {
239 Sub::new(self, a_is_expected)
242 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'tcx> {
243 Lub::new(self, a_is_expected)
246 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'tcx> {
247 Glb::new(self, a_is_expected)
250 /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
251 /// The idea is that we should ensure that the type `a_ty` is equal
252 /// to, a subtype of, or a supertype of (respectively) the type
253 /// to which `b_vid` is bound.
255 /// Since `b_vid` has not yet been instantiated with a type, we
256 /// will first instantiate `b_vid` with a *generalized* version
257 /// of `a_ty`. Generalization introduces other inference
258 /// variables wherever subtyping could occur.
265 ) -> RelateResult<'tcx, ()> {
266 use self::RelationDir::*;
268 // Get the actual variable that b_vid has been inferred to
269 debug_assert!(self.infcx.inner.borrow_mut().type_variables().probe(b_vid).is_unknown());
271 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
273 // Generalize type of `a_ty` appropriately depending on the
274 // direction. As an example, assume:
276 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
277 // inference variable,
278 // - and `dir` == `SubtypeOf`.
280 // Then the generalized form `b_ty` would be `&'?2 ?3`, where
281 // `'?2` and `?3` are fresh region/type inference
282 // variables. (Down below, we will relate `a_ty <: b_ty`,
283 // adding constraints like `'x: '?2` and `?1 <: ?3`.)
284 let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
286 "instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
287 a_ty, dir, b_vid, b_ty
289 self.infcx.inner.borrow_mut().type_variables().instantiate(b_vid, b_ty);
292 self.obligations.push(Obligation::new(
293 self.trace.cause.clone(),
295 ty::Predicate::WellFormed(b_ty),
299 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
301 // FIXME(#16847): This code is non-ideal because all these subtype
302 // relations wind up attributed to the same spans. We need
303 // to associate causes/spans with each of the relations in
304 // the stack to get this right.
306 EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
307 SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
309 self.sub(a_is_expected).relate_with_variance(ty::Contravariant, &a_ty, &b_ty)
316 /// Attempts to generalize `ty` for the type variable `for_vid`.
317 /// This checks for cycle -- that is, whether the type `ty`
318 /// references `for_vid`. The `dir` is the "direction" for which we
319 /// a performing the generalization (i.e., are we producing a type
320 /// that can be used as a supertype etc).
324 /// - `for_vid` is a "root vid"
330 ) -> RelateResult<'tcx, Generalization<'tcx>> {
331 debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
332 // Determine the ambient variance within which `ty` appears.
333 // The surrounding equation is:
337 // where `op` is either `==`, `<:`, or `:>`. This maps quite
339 let ambient_variance = match dir {
340 RelationDir::EqTo => ty::Invariant,
341 RelationDir::SubtypeOf => ty::Covariant,
342 RelationDir::SupertypeOf => ty::Contravariant,
345 debug!("generalize: ambient_variance = {:?}", ambient_variance);
347 let for_universe = match self.infcx.inner.borrow_mut().type_variables().probe(for_vid) {
348 v @ TypeVariableValue::Known { .. } => {
349 panic!("instantiating {:?} which has a known value {:?}", for_vid, v,)
351 TypeVariableValue::Unknown { universe } => universe,
354 debug!("generalize: for_universe = {:?}", for_universe);
356 let mut generalize = Generalizer {
358 span: self.trace.cause.span,
359 for_vid_sub_root: self.infcx.inner.borrow_mut().type_variables().sub_root_var(for_vid),
364 param_env: self.param_env,
367 let ty = match generalize.relate(&ty, &ty) {
370 debug!("generalize: failure {:?}", e);
374 let needs_wf = generalize.needs_wf;
375 debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
376 Ok(Generalization { ty, needs_wf })
380 struct Generalizer<'cx, 'tcx> {
381 infcx: &'cx InferCtxt<'cx, 'tcx>,
383 /// The span, used when creating new type variables and things.
386 /// The vid of the type variable that is in the process of being
387 /// instantiated; if we find this within the type we are folding,
388 /// that means we would have created a cyclic type.
389 for_vid_sub_root: ty::TyVid,
391 /// The universe of the type variable that is in the process of
392 /// being instantiated. Any fresh variables that we create in this
393 /// process should be in that same universe.
394 for_universe: ty::UniverseIndex,
396 /// Track the variance as we descend into the type.
397 ambient_variance: ty::Variance,
399 /// See the field `needs_wf` in `Generalization`.
402 /// The root type that we are generalizing. Used when reporting cycles.
405 param_env: ty::ParamEnv<'tcx>,
408 /// Result from a generalization operation. This includes
409 /// not only the generalized type, but also a bool flag
410 /// indicating whether further WF checks are needed.
411 struct Generalization<'tcx> {
414 /// If true, then the generalized type may not be well-formed,
415 /// even if the source type is well-formed, so we should add an
416 /// additional check to enforce that it is. This arises in
417 /// particular around 'bivariant' type parameters that are only
418 /// constrained by a where-clause. As an example, imagine a type:
420 /// struct Foo<A, B> where A: Iterator<Item = B> {
424 /// here, `A` will be covariant, but `B` is
425 /// unconstrained. However, whatever it is, for `Foo` to be WF, it
426 /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
427 /// then after generalization we will wind up with a type like
428 /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
429 /// ?D>` (or `>:`), we will wind up with the requirement that `?A
430 /// <: ?C`, but no particular relationship between `?B` and `?D`
431 /// (after all, we do not know the variance of the normalized form
432 /// of `A::Item` with respect to `A`). If we do nothing else, this
433 /// may mean that `?D` goes unconstrained (as in #41677). So, in
434 /// this scenario where we create a new type variable in a
435 /// bivariant context, we set the `needs_wf` flag to true. This
436 /// will force the calling code to check that `WF(Foo<?C, ?D>)`
437 /// holds, which in turn implies that `?C::Item == ?D`. So once
438 /// `?C` is constrained, that should suffice to restrict `?D`.
442 impl TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
443 fn tcx(&self) -> TyCtxt<'tcx> {
446 fn param_env(&self) -> ty::ParamEnv<'tcx> {
450 fn tag(&self) -> &'static str {
454 fn a_is_expected(&self) -> bool {
462 ) -> RelateResult<'tcx, ty::Binder<T>>
466 Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))
469 fn relate_item_substs(
472 a_subst: SubstsRef<'tcx>,
473 b_subst: SubstsRef<'tcx>,
474 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
475 if self.ambient_variance == ty::Variance::Invariant {
476 // Avoid fetching the variance if we are in an invariant
477 // context; no need, and it can induce dependency cycles
479 relate::relate_substs(self, None, a_subst, b_subst)
481 let opt_variances = self.tcx().variances_of(item_def_id);
482 relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
486 fn relate_with_variance<T: Relate<'tcx>>(
488 variance: ty::Variance,
491 ) -> RelateResult<'tcx, T> {
492 let old_ambient_variance = self.ambient_variance;
493 self.ambient_variance = self.ambient_variance.xform(variance);
495 let result = self.relate(a, b);
496 self.ambient_variance = old_ambient_variance;
500 fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
501 assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
503 debug!("generalize: t={:?}", t);
505 // Check to see whether the type we are generalizing references
506 // any other type variable related to `vid` via
507 // subtyping. This is basically our "occurs check", preventing
508 // us from creating infinitely sized types.
510 ty::Infer(ty::TyVar(vid)) => {
511 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
512 let sub_vid = self.infcx.inner.borrow_mut().type_variables().sub_root_var(vid);
513 if sub_vid == self.for_vid_sub_root {
514 // If sub-roots are equal, then `for_vid` and
515 // `vid` are related via subtyping.
516 Err(TypeError::CyclicTy(self.root_ty))
518 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
520 TypeVariableValue::Known { value: u } => {
521 debug!("generalize: known value {:?}", u);
524 TypeVariableValue::Unknown { universe } => {
525 match self.ambient_variance {
526 // Invariant: no need to make a fresh type variable.
528 if self.for_universe.can_name(universe) {
533 // Bivariant: make a fresh var, but we
534 // may need a WF predicate. See
535 // comment on `needs_wf` field for
537 ty::Bivariant => self.needs_wf = true,
539 // Co/contravariant: this will be
540 // sufficiently constrained later on.
541 ty::Covariant | ty::Contravariant => (),
545 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
546 let new_var_id = self
551 .new_var(self.for_universe, false, origin);
552 let u = self.tcx().mk_ty_var(new_var_id);
553 debug!("generalize: replacing original vid={:?} with new={:?}", vid, u);
559 ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
560 // No matter what mode we are in,
561 // integer/floating-point types must be equal to be
565 _ => relate::super_relate_tys(self, t, t),
572 r2: ty::Region<'tcx>,
573 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
574 assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
576 debug!("generalize: regions r={:?}", r);
579 // Never make variables for regions bound within the type itself,
580 // nor for erased regions.
581 ty::ReLateBound(..) | ty::ReErased => {
585 ty::RePlaceholder(..)
590 | ty::ReEarlyBound(..)
591 | ty::ReFree(..) => {
592 // see common code below
596 // If we are in an invariant context, we can re-use the region
597 // as is, unless it happens to be in some universe that we
598 // can't name. (In the case of a region *variable*, we could
599 // use it if we promoted it into our universe, but we don't
601 if let ty::Invariant = self.ambient_variance {
602 let r_universe = self.infcx.universe_of_region(r);
603 if self.for_universe.can_name(r_universe) {
608 // FIXME: This is non-ideal because we don't give a
609 // very descriptive origin for this region variable.
610 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
615 c: &'tcx ty::Const<'tcx>,
616 c2: &'tcx ty::Const<'tcx>,
617 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
618 assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
621 ty::ConstKind::Infer(InferConst::Var(vid)) => {
622 let mut inner = self.infcx.inner.borrow_mut();
623 let variable_table = &mut inner.const_unification_table();
624 let var_value = variable_table.probe_value(vid);
625 match var_value.val {
626 ConstVariableValue::Known { value: u } => self.relate(&u, &u),
627 ConstVariableValue::Unknown { universe } => {
628 if self.for_universe.can_name(universe) {
631 let new_var_id = variable_table.new_key(ConstVarValue {
632 origin: var_value.origin,
633 val: ConstVariableValue::Unknown { universe: self.for_universe },
635 Ok(self.tcx().mk_const_var(new_var_id, c.ty))
640 _ => relate::super_relate_consts(self, c, c),
645 pub trait RelateResultCompare<'tcx, T> {
646 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
648 F: FnOnce() -> TypeError<'tcx>;
651 impl<'tcx, T: Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
652 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
654 F: FnOnce() -> TypeError<'tcx>,
656 self.clone().and_then(|s| if s == t { self.clone() } else { Err(f()) })
660 pub fn const_unification_error<'tcx>(
662 (a, b): (&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>),
663 ) -> TypeError<'tcx> {
664 TypeError::ConstMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
667 fn int_unification_error<'tcx>(
669 v: (ty::IntVarValue, ty::IntVarValue),
670 ) -> TypeError<'tcx> {
672 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
675 fn float_unification_error<'tcx>(
677 v: (ty::FloatVarValue, ty::FloatVarValue),
678 ) -> TypeError<'tcx> {
679 let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
680 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))