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::const_variable::ConstVariableValue;
33 use crate::hir::def_id::DefId;
34 use crate::mir::interpret::ConstValue;
35 use crate::ty::{IntType, UintType};
36 use crate::ty::{self, Ty, TyCtxt, InferConst, LazyConst};
37 use crate::ty::error::{ConstError, TypeError};
38 use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
39 use crate::ty::subst::SubstsRef;
40 use crate::traits::{Obligation, PredicateObligations};
46 pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
47 pub infcx: &'infcx InferCtxt<'infcx, 'gcx, 'tcx>,
48 pub trace: TypeTrace<'tcx>,
49 pub cause: Option<ty::relate::Cause>,
50 pub param_env: ty::ParamEnv<'tcx>,
51 pub obligations: PredicateObligations<'tcx>,
54 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
55 pub enum RelationDir {
56 SubtypeOf, SupertypeOf, EqTo
59 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
60 pub fn super_combine_tys<R>(&self,
64 -> RelateResult<'tcx, Ty<'tcx>>
65 where R: TypeRelation<'infcx, 'gcx, 'tcx>
67 let a_is_expected = relation.a_is_expected();
69 match (&a.sty, &b.sty) {
70 // Relate integral variables to other types
71 (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => {
72 self.int_unification_table
74 .unify_var_var(a_id, b_id)
75 .map_err(|e| int_unification_error(a_is_expected, e))?;
78 (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
79 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
81 (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
82 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
84 (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
85 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
87 (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
88 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
91 // Relate floating-point variables to other types
92 (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
93 self.float_unification_table
95 .unify_var_var(a_id, b_id)
96 .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
99 (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
100 self.unify_float_variable(a_is_expected, v_id, v)
102 (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
103 self.unify_float_variable(!a_is_expected, v_id, v)
106 // All other cases of inference are errors
108 (_, &ty::Infer(_)) => {
109 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
113 ty::relate::super_relate_tys(relation, a, b)
118 pub fn super_combine_consts<R>(
121 a: &'tcx LazyConst<'tcx>,
122 b: &'tcx LazyConst<'tcx>,
123 ) -> RelateResult<'tcx, &'tcx LazyConst<'tcx>>
125 R: TypeRelation<'infcx, 'gcx, 'tcx>,
127 let a_is_expected = relation.a_is_expected();
129 if let (&ty::LazyConst::Evaluated(a_eval), &ty::LazyConst::Evaluated(b_eval)) = (a, b) {
130 match (a_eval.val, b_eval.val) {
131 (ConstValue::Infer(InferConst::Var(a_vid)),
132 ConstValue::Infer(InferConst::Var(b_vid))) => {
133 self.const_unification_table
135 .unify_var_var(a_vid, b_vid)
136 .map_err(|e| const_unification_error(a_is_expected, e))?;
140 // All other cases of inference with other variables are errors.
141 (ConstValue::Infer(InferConst::Var(_)), ConstValue::Infer(_)) |
142 (ConstValue::Infer(_), ConstValue::Infer(InferConst::Var(_))) => {
143 bug!("tried to combine ConstValue::Infer/ConstValue::Infer(InferConst::Var)")
146 (ConstValue::Infer(InferConst::Var(vid)), _) => {
147 return self.unify_const_variable(a_is_expected, vid, b);
150 (_, ConstValue::Infer(InferConst::Var(vid))) => {
151 return self.unify_const_variable(!a_is_expected, vid, a);
158 ty::relate::super_relate_consts(relation, a, b)
161 pub fn unify_const_variable(
163 vid_is_expected: bool,
164 vid: ty::ConstVid<'tcx>,
165 value: &'tcx LazyConst<'tcx>,
166 ) -> RelateResult<'tcx, &'tcx LazyConst<'tcx>> {
167 self.const_unification_table
169 .unify_var_value(vid, ConstVariableValue::Known { value })
170 .map_err(|e| const_unification_error(vid_is_expected, e))?;
174 fn unify_integral_variable(&self,
175 vid_is_expected: bool,
177 val: ty::IntVarValue)
178 -> RelateResult<'tcx, Ty<'tcx>>
180 self.int_unification_table
182 .unify_var_value(vid, Some(val))
183 .map_err(|e| int_unification_error(vid_is_expected, e))?;
185 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
186 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
190 fn unify_float_variable(&self,
191 vid_is_expected: bool,
194 -> RelateResult<'tcx, Ty<'tcx>>
196 self.float_unification_table
198 .unify_var_value(vid, Some(ty::FloatVarValue(val)))
199 .map_err(|e| float_unification_error(vid_is_expected, e))?;
200 Ok(self.tcx.mk_mach_float(val))
204 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
205 pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
209 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
210 Equate::new(self, a_is_expected)
213 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
214 Sub::new(self, a_is_expected)
217 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
218 Lub::new(self, a_is_expected)
221 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
222 Glb::new(self, a_is_expected)
225 /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
226 /// The idea is that we should ensure that the type `a_ty` is equal
227 /// to, a subtype of, or a supertype of (respectively) the type
228 /// to which `b_vid` is bound.
230 /// Since `b_vid` has not yet been instantiated with a type, we
231 /// will first instantiate `b_vid` with a *generalized* version
232 /// of `a_ty`. Generalization introduces other inference
233 /// variables wherever subtyping could occur.
234 pub fn instantiate(&mut self,
239 -> RelateResult<'tcx, ()>
241 use self::RelationDir::*;
243 // Get the actual variable that b_vid has been inferred to
244 debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_unknown());
246 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
248 // Generalize type of `a_ty` appropriately depending on the
249 // direction. As an example, assume:
251 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
252 // inference variable,
253 // - and `dir` == `SubtypeOf`.
255 // Then the generalized form `b_ty` would be `&'?2 ?3`, where
256 // `'?2` and `?3` are fresh region/type inference
257 // variables. (Down below, we will relate `a_ty <: b_ty`,
258 // adding constraints like `'x: '?2` and `?1 <: ?3`.)
259 let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
260 debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
261 a_ty, dir, b_vid, b_ty);
262 self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
265 self.obligations.push(Obligation::new(self.trace.cause.clone(),
267 ty::Predicate::WellFormed(b_ty)));
270 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
272 // FIXME(#16847): This code is non-ideal because all these subtype
273 // relations wind up attributed to the same spans. We need
274 // to associate causes/spans with each of the relations in
275 // the stack to get this right.
277 EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
278 SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
279 SupertypeOf => self.sub(a_is_expected).relate_with_variance(
280 ty::Contravariant, &a_ty, &b_ty),
286 /// Attempts to generalize `ty` for the type variable `for_vid`.
287 /// This checks for cycle -- that is, whether the type `ty`
288 /// references `for_vid`. The `dir` is the "direction" for which we
289 /// a performing the generalization (i.e., are we producing a type
290 /// that can be used as a supertype etc).
294 /// - `for_vid` is a "root vid"
299 -> RelateResult<'tcx, Generalization<'tcx>>
301 debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
302 // Determine the ambient variance within which `ty` appears.
303 // The surrounding equation is:
307 // where `op` is either `==`, `<:`, or `:>`. This maps quite
309 let ambient_variance = match dir {
310 RelationDir::EqTo => ty::Invariant,
311 RelationDir::SubtypeOf => ty::Covariant,
312 RelationDir::SupertypeOf => ty::Contravariant,
315 debug!("generalize: ambient_variance = {:?}", ambient_variance);
317 let for_universe = match self.infcx.type_variables.borrow_mut().probe(for_vid) {
318 v @ TypeVariableValue::Known { .. } => panic!(
319 "instantiating {:?} which has a known value {:?}",
323 TypeVariableValue::Unknown { universe } => universe,
326 debug!("generalize: for_universe = {:?}", for_universe);
328 let mut generalize = Generalizer {
330 span: self.trace.cause.span,
331 for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
338 let ty = match generalize.relate(&ty, &ty) {
341 debug!("generalize: failure {:?}", e);
345 let needs_wf = generalize.needs_wf;
346 debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
347 Ok(Generalization { ty, needs_wf })
351 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
352 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
354 /// The span, used when creating new type variables and things.
357 /// The vid of the type variable that is in the process of being
358 /// instantiated; if we find this within the type we are folding,
359 /// that means we would have created a cyclic type.
360 for_vid_sub_root: ty::TyVid,
362 /// The universe of the type variable that is in the process of
363 /// being instantiated. Any fresh variables that we create in this
364 /// process should be in that same universe.
365 for_universe: ty::UniverseIndex,
367 /// Track the variance as we descend into the type.
368 ambient_variance: ty::Variance,
370 /// See the field `needs_wf` in `Generalization`.
373 /// The root type that we are generalizing. Used when reporting cycles.
377 /// Result from a generalization operation. This includes
378 /// not only the generalized type, but also a bool flag
379 /// indicating whether further WF checks are needed.
380 struct Generalization<'tcx> {
383 /// If true, then the generalized type may not be well-formed,
384 /// even if the source type is well-formed, so we should add an
385 /// additional check to enforce that it is. This arises in
386 /// particular around 'bivariant' type parameters that are only
387 /// constrained by a where-clause. As an example, imagine a type:
389 /// struct Foo<A, B> where A: Iterator<Item = B> {
393 /// here, `A` will be covariant, but `B` is
394 /// unconstrained. However, whatever it is, for `Foo` to be WF, it
395 /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
396 /// then after generalization we will wind up with a type like
397 /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
398 /// ?D>` (or `>:`), we will wind up with the requirement that `?A
399 /// <: ?C`, but no particular relationship between `?B` and `?D`
400 /// (after all, we do not know the variance of the normalized form
401 /// of `A::Item` with respect to `A`). If we do nothing else, this
402 /// may mean that `?D` goes unconstrained (as in #41677). So, in
403 /// this scenario where we create a new type variable in a
404 /// bivariant context, we set the `needs_wf` flag to true. This
405 /// will force the calling code to check that `WF(Foo<?C, ?D>)`
406 /// holds, which in turn implies that `?C::Item == ?D`. So once
407 /// `?C` is constrained, that should suffice to restrict `?D`.
411 impl<'cx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
412 fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
416 fn tag(&self) -> &'static str {
420 fn a_is_expected(&self) -> bool {
424 fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
425 -> RelateResult<'tcx, ty::Binder<T>>
426 where T: Relate<'tcx>
428 Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))
431 fn relate_item_substs(&mut self,
433 a_subst: SubstsRef<'tcx>,
434 b_subst: SubstsRef<'tcx>)
435 -> RelateResult<'tcx, SubstsRef<'tcx>>
437 if self.ambient_variance == ty::Variance::Invariant {
438 // Avoid fetching the variance if we are in an invariant
439 // context; no need, and it can induce dependency cycles
441 relate::relate_substs(self, None, a_subst, b_subst)
443 let opt_variances = self.tcx().variances_of(item_def_id);
444 relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
448 fn relate_with_variance<T: Relate<'tcx>>(&mut self,
449 variance: ty::Variance,
452 -> RelateResult<'tcx, T>
454 let old_ambient_variance = self.ambient_variance;
455 self.ambient_variance = self.ambient_variance.xform(variance);
457 let result = self.relate(a, b);
458 self.ambient_variance = old_ambient_variance;
462 fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
463 assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
465 debug!("generalize: t={:?}", t);
467 // Check to see whether the type we are genealizing references
468 // any other type variable related to `vid` via
469 // subtyping. This is basically our "occurs check", preventing
470 // us from creating infinitely sized types.
472 ty::Infer(ty::TyVar(vid)) => {
473 let mut variables = self.infcx.type_variables.borrow_mut();
474 let vid = variables.root_var(vid);
475 let sub_vid = variables.sub_root_var(vid);
476 if sub_vid == self.for_vid_sub_root {
477 // If sub-roots are equal, then `for_vid` and
478 // `vid` are related via subtyping.
479 return Err(TypeError::CyclicTy(self.root_ty));
481 match variables.probe(vid) {
482 TypeVariableValue::Known { value: u } => {
484 debug!("generalize: known value {:?}", u);
487 TypeVariableValue::Unknown { universe } => {
488 match self.ambient_variance {
489 // Invariant: no need to make a fresh type variable.
491 if self.for_universe.can_name(universe) {
496 // Bivariant: make a fresh var, but we
497 // may need a WF predicate. See
498 // comment on `needs_wf` field for
500 ty::Bivariant => self.needs_wf = true,
502 // Co/contravariant: this will be
503 // sufficiently constrained later on.
504 ty::Covariant | ty::Contravariant => (),
507 let origin = *variables.var_origin(vid);
508 let new_var_id = variables.new_var(self.for_universe, false, origin);
509 let u = self.tcx().mk_ty_var(new_var_id);
510 debug!("generalize: replacing original vid={:?} with new={:?}",
517 ty::Infer(ty::IntVar(_)) |
518 ty::Infer(ty::FloatVar(_)) => {
519 // No matter what mode we are in,
520 // integer/floating-point types must be equal to be
525 relate::super_relate_tys(self, t, t)
530 fn regions(&mut self, r: ty::Region<'tcx>, r2: ty::Region<'tcx>)
531 -> RelateResult<'tcx, ty::Region<'tcx>> {
532 assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
534 debug!("generalize: regions r={:?}", r);
537 // Never make variables for regions bound within the type itself,
538 // nor for erased regions.
539 ty::ReLateBound(..) |
544 ty::ReClosureBound(..) => {
547 "encountered unexpected ReClosureBound: {:?}",
552 ty::RePlaceholder(..) |
557 ty::ReEarlyBound(..) |
559 // see common code below
563 // If we are in an invariant context, we can re-use the region
564 // as is, unless it happens to be in some universe that we
565 // can't name. (In the case of a region *variable*, we could
566 // use it if we promoted it into our universe, but we don't
568 if let ty::Invariant = self.ambient_variance {
569 let r_universe = self.infcx.universe_of_region(r);
570 if self.for_universe.can_name(r_universe) {
575 // FIXME: This is non-ideal because we don't give a
576 // very descriptive origin for this region variable.
577 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
581 pub trait RelateResultCompare<'tcx, T> {
582 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
583 F: FnOnce() -> TypeError<'tcx>;
586 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
587 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
588 F: FnOnce() -> TypeError<'tcx>,
590 self.clone().and_then(|s| {
600 pub fn const_unification_error<'tcx>(
602 (a, b): (&'tcx LazyConst<'tcx>, &'tcx LazyConst<'tcx>),
603 ) -> TypeError<'tcx> {
604 TypeError::ConstError(
605 ConstError::Mismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
609 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
613 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
616 fn float_unification_error<'tcx>(a_is_expected: bool,
617 v: (ty::FloatVarValue, ty::FloatVarValue))
620 let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
621 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))