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;
27 use super::{InferCtxt, MiscVariable, TypeTrace};
30 use super::type_variable::TypeVariableValue;
31 use super::unify_key::{ConstVarValue, ConstVariableValue};
32 use super::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
33 use super::unify_key::replace_if_possible;
35 use crate::hir::def_id::DefId;
36 use crate::mir::interpret::ConstValue;
37 use crate::ty::{IntType, UintType};
38 use crate::ty::{self, Ty, TyCtxt, InferConst};
39 use crate::ty::error::TypeError;
40 use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
41 use crate::ty::subst::SubstsRef;
42 use crate::traits::{Obligation, PredicateObligations};
45 use syntax_pos::{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, Eq, PartialEq, Hash, Debug)]
57 pub enum RelationDir {
58 SubtypeOf, SupertypeOf, EqTo
61 impl<'infcx, 'tcx> InferCtxt<'infcx, 'tcx> {
62 pub fn super_combine_tys<R>(
67 ) -> RelateResult<'tcx, Ty<'tcx>>
69 R: TypeRelation<'tcx>,
71 let a_is_expected = relation.a_is_expected();
73 match (&a.kind, &b.kind) {
74 // Relate integral variables to other types
75 (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => {
76 self.int_unification_table
78 .unify_var_var(a_id, b_id)
79 .map_err(|e| int_unification_error(a_is_expected, e))?;
82 (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
83 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
85 (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
86 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
88 (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
89 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
91 (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
92 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
95 // Relate floating-point variables to other types
96 (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
97 self.float_unification_table
99 .unify_var_var(a_id, b_id)
100 .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
103 (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
104 self.unify_float_variable(a_is_expected, v_id, v)
106 (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
107 self.unify_float_variable(!a_is_expected, v_id, v)
110 // All other cases of inference are errors
112 (_, &ty::Infer(_)) => {
113 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
117 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);
132 if a == b { return Ok(a); }
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) {
140 (ConstValue::Infer(InferConst::Var(a_vid)),
141 ConstValue::Infer(InferConst::Var(b_vid))) => {
142 self.const_unification_table
144 .unify_var_var(a_vid, b_vid)
145 .map_err(|e| const_unification_error(a_is_expected, e))?;
149 // All other cases of inference with other variables are errors.
150 (ConstValue::Infer(InferConst::Var(_)), ConstValue::Infer(_)) |
151 (ConstValue::Infer(_), ConstValue::Infer(InferConst::Var(_))) => {
152 bug!("tried to combine ConstValue::Infer/ConstValue::Infer(InferConst::Var)")
155 (ConstValue::Infer(InferConst::Var(vid)), _) => {
156 return self.unify_const_variable(a_is_expected, vid, b);
159 (_, ConstValue::Infer(InferConst::Var(vid))) => {
160 return self.unify_const_variable(!a_is_expected, vid, a);
166 ty::relate::super_relate_consts(relation, a, b)
169 pub fn unify_const_variable(
171 vid_is_expected: bool,
172 vid: ty::ConstVid<'tcx>,
173 value: &'tcx ty::Const<'tcx>,
174 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
175 self.const_unification_table
177 .unify_var_value(vid, ConstVarValue {
178 origin: ConstVariableOrigin {
179 kind: ConstVariableOriginKind::ConstInference,
182 val: ConstVariableValue::Known { value },
184 .map_err(|e| const_unification_error(vid_is_expected, e))?;
188 fn unify_integral_variable(&self,
189 vid_is_expected: bool,
191 val: ty::IntVarValue)
192 -> RelateResult<'tcx, Ty<'tcx>>
194 self.int_unification_table
196 .unify_var_value(vid, Some(val))
197 .map_err(|e| int_unification_error(vid_is_expected, e))?;
199 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
200 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
204 fn unify_float_variable(&self,
205 vid_is_expected: bool,
208 -> RelateResult<'tcx, Ty<'tcx>>
210 self.float_unification_table
212 .unify_var_value(vid, Some(ty::FloatVarValue(val)))
213 .map_err(|e| float_unification_error(vid_is_expected, e))?;
214 Ok(self.tcx.mk_mach_float(val))
218 impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
219 pub fn tcx(&self) -> TyCtxt<'tcx> {
223 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'tcx> {
224 Equate::new(self, a_is_expected)
227 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'tcx> {
228 Sub::new(self, a_is_expected)
231 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'tcx> {
232 Lub::new(self, a_is_expected)
235 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'tcx> {
236 Glb::new(self, a_is_expected)
239 /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
240 /// The idea is that we should ensure that the type `a_ty` is equal
241 /// to, a subtype of, or a supertype of (respectively) the type
242 /// to which `b_vid` is bound.
244 /// Since `b_vid` has not yet been instantiated with a type, we
245 /// will first instantiate `b_vid` with a *generalized* version
246 /// of `a_ty`. Generalization introduces other inference
247 /// variables wherever subtyping could occur.
248 pub fn instantiate(&mut self,
253 -> RelateResult<'tcx, ()>
255 use self::RelationDir::*;
257 // Get the actual variable that b_vid has been inferred to
258 debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_unknown());
260 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
262 // Generalize type of `a_ty` appropriately depending on the
263 // direction. As an example, assume:
265 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
266 // inference variable,
267 // - and `dir` == `SubtypeOf`.
269 // Then the generalized form `b_ty` would be `&'?2 ?3`, where
270 // `'?2` and `?3` are fresh region/type inference
271 // variables. (Down below, we will relate `a_ty <: b_ty`,
272 // adding constraints like `'x: '?2` and `?1 <: ?3`.)
273 let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
274 debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
275 a_ty, dir, b_vid, b_ty);
276 self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
279 self.obligations.push(Obligation::new(self.trace.cause.clone(),
281 ty::Predicate::WellFormed(b_ty)));
284 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
286 // FIXME(#16847): This code is non-ideal because all these subtype
287 // relations wind up attributed to the same spans. We need
288 // to associate causes/spans with each of the relations in
289 // the stack to get this right.
291 EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
292 SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
293 SupertypeOf => self.sub(a_is_expected).relate_with_variance(
294 ty::Contravariant, &a_ty, &b_ty),
300 /// Attempts to generalize `ty` for the type variable `for_vid`.
301 /// This checks for cycle -- that is, whether the type `ty`
302 /// references `for_vid`. The `dir` is the "direction" for which we
303 /// a performing the generalization (i.e., are we producing a type
304 /// that can be used as a supertype etc).
308 /// - `for_vid` is a "root vid"
313 -> RelateResult<'tcx, Generalization<'tcx>>
315 debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
316 // Determine the ambient variance within which `ty` appears.
317 // The surrounding equation is:
321 // where `op` is either `==`, `<:`, or `:>`. This maps quite
323 let ambient_variance = match dir {
324 RelationDir::EqTo => ty::Invariant,
325 RelationDir::SubtypeOf => ty::Covariant,
326 RelationDir::SupertypeOf => ty::Contravariant,
329 debug!("generalize: ambient_variance = {:?}", ambient_variance);
331 let for_universe = match self.infcx.type_variables.borrow_mut().probe(for_vid) {
332 v @ TypeVariableValue::Known { .. } => panic!(
333 "instantiating {:?} which has a known value {:?}",
337 TypeVariableValue::Unknown { universe } => universe,
340 debug!("generalize: for_universe = {:?}", for_universe);
342 let mut generalize = Generalizer {
344 span: self.trace.cause.span,
345 for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
350 param_env: self.param_env,
353 let ty = match generalize.relate(&ty, &ty) {
356 debug!("generalize: failure {:?}", e);
360 let needs_wf = generalize.needs_wf;
361 debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
362 Ok(Generalization { ty, needs_wf })
366 struct Generalizer<'cx, 'tcx> {
367 infcx: &'cx InferCtxt<'cx, 'tcx>,
369 /// The span, used when creating new type variables and things.
372 /// The vid of the type variable that is in the process of being
373 /// instantiated; if we find this within the type we are folding,
374 /// that means we would have created a cyclic type.
375 for_vid_sub_root: ty::TyVid,
377 /// The universe of the type variable that is in the process of
378 /// being instantiated. Any fresh variables that we create in this
379 /// process should be in that same universe.
380 for_universe: ty::UniverseIndex,
382 /// Track the variance as we descend into the type.
383 ambient_variance: ty::Variance,
385 /// See the field `needs_wf` in `Generalization`.
388 /// The root type that we are generalizing. Used when reporting cycles.
391 param_env: ty::ParamEnv<'tcx>,
394 /// Result from a generalization operation. This includes
395 /// not only the generalized type, but also a bool flag
396 /// indicating whether further WF checks are needed.
397 struct Generalization<'tcx> {
400 /// If true, then the generalized type may not be well-formed,
401 /// even if the source type is well-formed, so we should add an
402 /// additional check to enforce that it is. This arises in
403 /// particular around 'bivariant' type parameters that are only
404 /// constrained by a where-clause. As an example, imagine a type:
406 /// struct Foo<A, B> where A: Iterator<Item = B> {
410 /// here, `A` will be covariant, but `B` is
411 /// unconstrained. However, whatever it is, for `Foo` to be WF, it
412 /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
413 /// then after generalization we will wind up with a type like
414 /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
415 /// ?D>` (or `>:`), we will wind up with the requirement that `?A
416 /// <: ?C`, but no particular relationship between `?B` and `?D`
417 /// (after all, we do not know the variance of the normalized form
418 /// of `A::Item` with respect to `A`). If we do nothing else, this
419 /// may mean that `?D` goes unconstrained (as in #41677). So, in
420 /// this scenario where we create a new type variable in a
421 /// bivariant context, we set the `needs_wf` flag to true. This
422 /// will force the calling code to check that `WF(Foo<?C, ?D>)`
423 /// holds, which in turn implies that `?C::Item == ?D`. So once
424 /// `?C` is constrained, that should suffice to restrict `?D`.
428 impl TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
429 fn tcx(&self) -> TyCtxt<'tcx> {
432 fn param_env(&self) -> ty::ParamEnv<'tcx> { self.param_env }
434 fn tag(&self) -> &'static str {
438 fn a_is_expected(&self) -> bool {
442 fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
443 -> RelateResult<'tcx, ty::Binder<T>>
444 where T: Relate<'tcx>
446 Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))
449 fn relate_item_substs(&mut self,
451 a_subst: SubstsRef<'tcx>,
452 b_subst: SubstsRef<'tcx>)
453 -> RelateResult<'tcx, SubstsRef<'tcx>>
455 if self.ambient_variance == ty::Variance::Invariant {
456 // Avoid fetching the variance if we are in an invariant
457 // context; no need, and it can induce dependency cycles
459 relate::relate_substs(self, None, a_subst, b_subst)
461 let opt_variances = self.tcx().variances_of(item_def_id);
462 relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
466 fn relate_with_variance<T: Relate<'tcx>>(&mut self,
467 variance: ty::Variance,
470 -> RelateResult<'tcx, T>
472 let old_ambient_variance = self.ambient_variance;
473 self.ambient_variance = self.ambient_variance.xform(variance);
475 let result = self.relate(a, b);
476 self.ambient_variance = old_ambient_variance;
480 fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
481 assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
483 debug!("generalize: t={:?}", t);
485 // Check to see whether the type we are generalizing references
486 // any other type variable related to `vid` via
487 // subtyping. This is basically our "occurs check", preventing
488 // us from creating infinitely sized types.
490 ty::Infer(ty::TyVar(vid)) => {
491 let mut variables = self.infcx.type_variables.borrow_mut();
492 let vid = variables.root_var(vid);
493 let sub_vid = variables.sub_root_var(vid);
494 if sub_vid == self.for_vid_sub_root {
495 // If sub-roots are equal, then `for_vid` and
496 // `vid` are related via subtyping.
497 return Err(TypeError::CyclicTy(self.root_ty));
499 match variables.probe(vid) {
500 TypeVariableValue::Known { value: u } => {
502 debug!("generalize: known value {:?}", u);
505 TypeVariableValue::Unknown { universe } => {
506 match self.ambient_variance {
507 // Invariant: no need to make a fresh type variable.
509 if self.for_universe.can_name(universe) {
514 // Bivariant: make a fresh var, but we
515 // may need a WF predicate. See
516 // comment on `needs_wf` field for
518 ty::Bivariant => self.needs_wf = true,
520 // Co/contravariant: this will be
521 // sufficiently constrained later on.
522 ty::Covariant | ty::Contravariant => (),
525 let origin = *variables.var_origin(vid);
526 let new_var_id = variables.new_var(self.for_universe, false, origin);
527 let u = self.tcx().mk_ty_var(new_var_id);
528 debug!("generalize: replacing original vid={:?} with new={:?}",
535 ty::Infer(ty::IntVar(_)) |
536 ty::Infer(ty::FloatVar(_)) => {
537 // No matter what mode we are in,
538 // integer/floating-point types must be equal to be
543 relate::super_relate_tys(self, t, t)
548 fn regions(&mut self, r: ty::Region<'tcx>, r2: ty::Region<'tcx>)
549 -> RelateResult<'tcx, ty::Region<'tcx>> {
550 assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
552 debug!("generalize: regions r={:?}", r);
555 // Never make variables for regions bound within the type itself,
556 // nor for erased regions.
557 ty::ReLateBound(..) |
562 ty::ReClosureBound(..) => {
565 "encountered unexpected ReClosureBound: {:?}",
570 ty::RePlaceholder(..) |
575 ty::ReEarlyBound(..) |
577 // see common code below
581 // If we are in an invariant context, we can re-use the region
582 // as is, unless it happens to be in some universe that we
583 // can't name. (In the case of a region *variable*, we could
584 // use it if we promoted it into our universe, but we don't
586 if let ty::Invariant = self.ambient_variance {
587 let r_universe = self.infcx.universe_of_region(r);
588 if self.for_universe.can_name(r_universe) {
593 // FIXME: This is non-ideal because we don't give a
594 // very descriptive origin for this region variable.
595 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
600 c: &'tcx ty::Const<'tcx>,
601 c2: &'tcx ty::Const<'tcx>
602 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
603 assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
606 ty::Const { val: ConstValue::Infer(InferConst::Var(vid)), .. } => {
607 let mut variable_table = self.infcx.const_unification_table.borrow_mut();
608 match variable_table.probe_value(*vid).val.known() {
616 relate::super_relate_consts(self, c, c)
622 pub trait RelateResultCompare<'tcx, T> {
623 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
624 F: FnOnce() -> TypeError<'tcx>;
627 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
628 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
629 F: FnOnce() -> TypeError<'tcx>,
631 self.clone().and_then(|s| {
641 pub fn const_unification_error<'tcx>(
643 (a, b): (&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>),
644 ) -> TypeError<'tcx> {
645 TypeError::ConstMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
648 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
652 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
655 fn float_unification_error<'tcx>(a_is_expected: bool,
656 v: (ty::FloatVarValue, ty::FloatVarValue))
659 let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
660 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))