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::hir::def_id::DefId;
36 use crate::traits::{Obligation, PredicateObligations};
37 use crate::ty::error::TypeError;
38 use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
39 use crate::ty::subst::SubstsRef;
40 use crate::ty::{self, InferConst, Ty, TyCtxt};
41 use crate::ty::{IntType, UintType};
44 use syntax_pos::{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))) => {
77 self.int_unification_table
79 .unify_var_var(a_id, b_id)
80 .map_err(|e| int_unification_error(a_is_expected, e))?;
83 (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
84 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
86 (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
87 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
89 (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
90 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
92 (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
93 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
96 // Relate floating-point variables to other types
97 (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
98 self.float_unification_table
100 .unify_var_var(a_id, b_id)
101 .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
104 (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
105 self.unify_float_variable(a_is_expected, v_id, v)
107 (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
108 self.unify_float_variable(!a_is_expected, v_id, v)
111 // All other cases of inference are errors
112 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
113 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
116 _ => ty::relate::super_relate_tys(relation, a, b),
120 pub fn super_combine_consts<R>(
123 a: &'tcx ty::Const<'tcx>,
124 b: &'tcx ty::Const<'tcx>,
125 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>
127 R: TypeRelation<'tcx>,
129 debug!("{}.consts({:?}, {:?})", relation.tag(), a, b);
134 let a = replace_if_possible(self.const_unification_table.borrow_mut(), a);
135 let b = replace_if_possible(self.const_unification_table.borrow_mut(), b);
137 let a_is_expected = relation.a_is_expected();
139 match (a.val, b.val) {
141 ty::ConstKind::Infer(InferConst::Var(a_vid)),
142 ty::ConstKind::Infer(InferConst::Var(b_vid)),
144 self.const_unification_table
146 .unify_var_var(a_vid, b_vid)
147 .map_err(|e| const_unification_error(a_is_expected, e))?;
151 // All other cases of inference with other variables are errors.
152 (ty::ConstKind::Infer(InferConst::Var(_)), ty::ConstKind::Infer(_))
153 | (ty::ConstKind::Infer(_), ty::ConstKind::Infer(InferConst::Var(_))) => {
154 bug!("tried to combine ConstKind::Infer/ConstKind::Infer(InferConst::Var)")
157 (ty::ConstKind::Infer(InferConst::Var(vid)), _) => {
158 return self.unify_const_variable(a_is_expected, vid, b);
161 (_, ty::ConstKind::Infer(InferConst::Var(vid))) => {
162 return self.unify_const_variable(!a_is_expected, vid, a);
168 ty::relate::super_relate_consts(relation, a, b)
171 pub fn unify_const_variable(
173 vid_is_expected: bool,
174 vid: ty::ConstVid<'tcx>,
175 value: &'tcx ty::Const<'tcx>,
176 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
177 self.const_unification_table
182 origin: ConstVariableOrigin {
183 kind: ConstVariableOriginKind::ConstInference,
186 val: ConstVariableValue::Known { value },
189 .map_err(|e| const_unification_error(vid_is_expected, e))?;
193 fn unify_integral_variable(
195 vid_is_expected: bool,
197 val: ty::IntVarValue,
198 ) -> RelateResult<'tcx, Ty<'tcx>> {
199 self.int_unification_table
201 .unify_var_value(vid, Some(val))
202 .map_err(|e| int_unification_error(vid_is_expected, e))?;
204 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
205 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
209 fn unify_float_variable(
211 vid_is_expected: bool,
214 ) -> RelateResult<'tcx, Ty<'tcx>> {
215 self.float_unification_table
217 .unify_var_value(vid, Some(ty::FloatVarValue(val)))
218 .map_err(|e| float_unification_error(vid_is_expected, e))?;
219 Ok(self.tcx.mk_mach_float(val))
223 impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
224 pub fn tcx(&self) -> TyCtxt<'tcx> {
228 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'tcx> {
229 Equate::new(self, a_is_expected)
232 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'tcx> {
233 Sub::new(self, a_is_expected)
236 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'tcx> {
237 Lub::new(self, a_is_expected)
240 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'tcx> {
241 Glb::new(self, a_is_expected)
244 /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
245 /// The idea is that we should ensure that the type `a_ty` is equal
246 /// to, a subtype of, or a supertype of (respectively) the type
247 /// to which `b_vid` is bound.
249 /// Since `b_vid` has not yet been instantiated with a type, we
250 /// will first instantiate `b_vid` with a *generalized* version
251 /// of `a_ty`. Generalization introduces other inference
252 /// variables wherever subtyping could occur.
259 ) -> RelateResult<'tcx, ()> {
260 use self::RelationDir::*;
262 // Get the actual variable that b_vid has been inferred to
263 debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_unknown());
265 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
267 // Generalize type of `a_ty` appropriately depending on the
268 // direction. As an example, assume:
270 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
271 // inference variable,
272 // - and `dir` == `SubtypeOf`.
274 // Then the generalized form `b_ty` would be `&'?2 ?3`, where
275 // `'?2` and `?3` are fresh region/type inference
276 // variables. (Down below, we will relate `a_ty <: b_ty`,
277 // adding constraints like `'x: '?2` and `?1 <: ?3`.)
278 let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
280 "instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
281 a_ty, dir, b_vid, b_ty
283 self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
286 self.obligations.push(Obligation::new(
287 self.trace.cause.clone(),
289 ty::Predicate::WellFormed(b_ty),
293 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
295 // FIXME(#16847): This code is non-ideal because all these subtype
296 // relations wind up attributed to the same spans. We need
297 // to associate causes/spans with each of the relations in
298 // the stack to get this right.
300 EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
301 SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
303 self.sub(a_is_expected).relate_with_variance(ty::Contravariant, &a_ty, &b_ty)
310 /// Attempts to generalize `ty` for the type variable `for_vid`.
311 /// This checks for cycle -- that is, whether the type `ty`
312 /// references `for_vid`. The `dir` is the "direction" for which we
313 /// a performing the generalization (i.e., are we producing a type
314 /// that can be used as a supertype etc).
318 /// - `for_vid` is a "root vid"
324 ) -> RelateResult<'tcx, Generalization<'tcx>> {
325 debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
326 // Determine the ambient variance within which `ty` appears.
327 // The surrounding equation is:
331 // where `op` is either `==`, `<:`, or `:>`. This maps quite
333 let ambient_variance = match dir {
334 RelationDir::EqTo => ty::Invariant,
335 RelationDir::SubtypeOf => ty::Covariant,
336 RelationDir::SupertypeOf => ty::Contravariant,
339 debug!("generalize: ambient_variance = {:?}", ambient_variance);
341 let for_universe = match self.infcx.type_variables.borrow_mut().probe(for_vid) {
342 v @ TypeVariableValue::Known { .. } => {
343 panic!("instantiating {:?} which has a known value {:?}", for_vid, v,)
345 TypeVariableValue::Unknown { universe } => universe,
348 debug!("generalize: for_universe = {:?}", for_universe);
350 let mut generalize = Generalizer {
352 span: self.trace.cause.span,
353 for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
358 param_env: self.param_env,
361 let ty = match generalize.relate(&ty, &ty) {
364 debug!("generalize: failure {:?}", e);
368 let needs_wf = generalize.needs_wf;
369 debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
370 Ok(Generalization { ty, needs_wf })
374 struct Generalizer<'cx, 'tcx> {
375 infcx: &'cx InferCtxt<'cx, 'tcx>,
377 /// The span, used when creating new type variables and things.
380 /// The vid of the type variable that is in the process of being
381 /// instantiated; if we find this within the type we are folding,
382 /// that means we would have created a cyclic type.
383 for_vid_sub_root: ty::TyVid,
385 /// The universe of the type variable that is in the process of
386 /// being instantiated. Any fresh variables that we create in this
387 /// process should be in that same universe.
388 for_universe: ty::UniverseIndex,
390 /// Track the variance as we descend into the type.
391 ambient_variance: ty::Variance,
393 /// See the field `needs_wf` in `Generalization`.
396 /// The root type that we are generalizing. Used when reporting cycles.
399 param_env: ty::ParamEnv<'tcx>,
402 /// Result from a generalization operation. This includes
403 /// not only the generalized type, but also a bool flag
404 /// indicating whether further WF checks are needed.
405 struct Generalization<'tcx> {
408 /// If true, then the generalized type may not be well-formed,
409 /// even if the source type is well-formed, so we should add an
410 /// additional check to enforce that it is. This arises in
411 /// particular around 'bivariant' type parameters that are only
412 /// constrained by a where-clause. As an example, imagine a type:
414 /// struct Foo<A, B> where A: Iterator<Item = B> {
418 /// here, `A` will be covariant, but `B` is
419 /// unconstrained. However, whatever it is, for `Foo` to be WF, it
420 /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
421 /// then after generalization we will wind up with a type like
422 /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
423 /// ?D>` (or `>:`), we will wind up with the requirement that `?A
424 /// <: ?C`, but no particular relationship between `?B` and `?D`
425 /// (after all, we do not know the variance of the normalized form
426 /// of `A::Item` with respect to `A`). If we do nothing else, this
427 /// may mean that `?D` goes unconstrained (as in #41677). So, in
428 /// this scenario where we create a new type variable in a
429 /// bivariant context, we set the `needs_wf` flag to true. This
430 /// will force the calling code to check that `WF(Foo<?C, ?D>)`
431 /// holds, which in turn implies that `?C::Item == ?D`. So once
432 /// `?C` is constrained, that should suffice to restrict `?D`.
436 impl TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
437 fn tcx(&self) -> TyCtxt<'tcx> {
440 fn param_env(&self) -> ty::ParamEnv<'tcx> {
444 fn tag(&self) -> &'static str {
448 fn a_is_expected(&self) -> bool {
456 ) -> RelateResult<'tcx, ty::Binder<T>>
460 Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))
463 fn relate_item_substs(
466 a_subst: SubstsRef<'tcx>,
467 b_subst: SubstsRef<'tcx>,
468 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
469 if self.ambient_variance == ty::Variance::Invariant {
470 // Avoid fetching the variance if we are in an invariant
471 // context; no need, and it can induce dependency cycles
473 relate::relate_substs(self, None, a_subst, b_subst)
475 let opt_variances = self.tcx().variances_of(item_def_id);
476 relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
480 fn relate_with_variance<T: Relate<'tcx>>(
482 variance: ty::Variance,
485 ) -> RelateResult<'tcx, T> {
486 let old_ambient_variance = self.ambient_variance;
487 self.ambient_variance = self.ambient_variance.xform(variance);
489 let result = self.relate(a, b);
490 self.ambient_variance = old_ambient_variance;
494 fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
495 assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
497 debug!("generalize: t={:?}", t);
499 // Check to see whether the type we are generalizing references
500 // any other type variable related to `vid` via
501 // subtyping. This is basically our "occurs check", preventing
502 // us from creating infinitely sized types.
504 ty::Infer(ty::TyVar(vid)) => {
505 let mut variables = self.infcx.type_variables.borrow_mut();
506 let vid = variables.root_var(vid);
507 let sub_vid = variables.sub_root_var(vid);
508 if sub_vid == self.for_vid_sub_root {
509 // If sub-roots are equal, then `for_vid` and
510 // `vid` are related via subtyping.
511 Err(TypeError::CyclicTy(self.root_ty))
513 match variables.probe(vid) {
514 TypeVariableValue::Known { value: u } => {
516 debug!("generalize: known value {:?}", u);
519 TypeVariableValue::Unknown { universe } => {
520 match self.ambient_variance {
521 // Invariant: no need to make a fresh type variable.
523 if self.for_universe.can_name(universe) {
528 // Bivariant: make a fresh var, but we
529 // may need a WF predicate. See
530 // comment on `needs_wf` field for
532 ty::Bivariant => self.needs_wf = true,
534 // Co/contravariant: this will be
535 // sufficiently constrained later on.
536 ty::Covariant | ty::Contravariant => (),
539 let origin = *variables.var_origin(vid);
540 let new_var_id = variables.new_var(self.for_universe, false, origin);
541 let u = self.tcx().mk_ty_var(new_var_id);
542 debug!("generalize: replacing original vid={:?} with new={:?}", vid, u);
548 ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) => {
549 // No matter what mode we are in,
550 // integer/floating-point types must be equal to be
554 _ => relate::super_relate_tys(self, t, t),
561 r2: ty::Region<'tcx>,
562 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
563 assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
565 debug!("generalize: regions r={:?}", r);
568 // Never make variables for regions bound within the type itself,
569 // nor for erased regions.
570 ty::ReLateBound(..) | ty::ReErased => {
574 ty::ReClosureBound(..) => {
575 span_bug!(self.span, "encountered unexpected ReClosureBound: {:?}", r,);
578 ty::RePlaceholder(..)
583 | ty::ReEarlyBound(..)
584 | ty::ReFree(..) => {
585 // see common code below
589 // If we are in an invariant context, we can re-use the region
590 // as is, unless it happens to be in some universe that we
591 // can't name. (In the case of a region *variable*, we could
592 // use it if we promoted it into our universe, but we don't
594 if let ty::Invariant = self.ambient_variance {
595 let r_universe = self.infcx.universe_of_region(r);
596 if self.for_universe.can_name(r_universe) {
601 // FIXME: This is non-ideal because we don't give a
602 // very descriptive origin for this region variable.
603 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
608 c: &'tcx ty::Const<'tcx>,
609 c2: &'tcx ty::Const<'tcx>,
610 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
611 assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
614 ty::ConstKind::Infer(InferConst::Var(vid)) => {
615 let mut variable_table = self.infcx.const_unification_table.borrow_mut();
616 let var_value = variable_table.probe_value(vid);
617 match var_value.val {
618 ConstVariableValue::Known { value: u } => self.relate(&u, &u),
619 ConstVariableValue::Unknown { universe } => {
620 if self.for_universe.can_name(universe) {
623 let new_var_id = variable_table.new_key(ConstVarValue {
624 origin: var_value.origin,
625 val: ConstVariableValue::Unknown { universe: self.for_universe },
627 Ok(self.tcx().mk_const_var(new_var_id, c.ty))
632 _ => relate::super_relate_consts(self, c, c),
637 pub trait RelateResultCompare<'tcx, T> {
638 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
640 F: FnOnce() -> TypeError<'tcx>;
643 impl<'tcx, T: Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
644 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
646 F: FnOnce() -> TypeError<'tcx>,
648 self.clone().and_then(|s| if s == t { self.clone() } else { Err(f()) })
652 pub fn const_unification_error<'tcx>(
654 (a, b): (&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>),
655 ) -> TypeError<'tcx> {
656 TypeError::ConstMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
659 fn int_unification_error<'tcx>(
661 v: (ty::IntVarValue, ty::IntVarValue),
662 ) -> TypeError<'tcx> {
664 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
667 fn float_unification_error<'tcx>(
669 v: (ty::FloatVarValue, ty::FloatVarValue),
670 ) -> TypeError<'tcx> {
671 let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
672 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))