1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 ///////////////////////////////////////////////////////////////////////////
14 // There are four type combiners: equate, sub, lub, and glb. Each
15 // implements the trait `Combine` and contains methods for combining
16 // two instances of various things and yielding a new instance. These
17 // combiner methods always yield a `Result<T>`. There is a lot of
18 // common code for these operations, implemented as default methods on
19 // the `Combine` trait.
21 // Each operation may have side-effects on the inference context,
22 // though these can be unrolled using snapshots. On success, the
23 // LUB/GLB operations return the appropriate bound. The Eq and Sub
24 // operations generally return the first operand.
28 // When you are relating two things which have a contravariant
29 // relationship, you should use `contratys()` or `contraregions()`,
30 // rather than inversing the order of arguments! This is necessary
31 // because the order of arguments is not relevant for LUB and GLB. It
32 // is also useful to track which value is the "expected" value in
33 // terms of error reporting.
35 use super::equate::Equate;
40 use super::{MiscVariable, TypeTrace};
42 use ty::{IntType, UintType};
43 use ty::{self, Ty, TyCtxt};
44 use ty::error::TypeError;
45 use ty::relate::{self, Relate, RelateResult, TypeRelation};
46 use traits::PredicateObligations;
52 pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
53 pub infcx: &'infcx InferCtxt<'infcx, 'gcx, 'tcx>,
54 pub trace: TypeTrace<'tcx>,
55 pub cause: Option<ty::relate::Cause>,
56 pub obligations: PredicateObligations<'tcx>,
59 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
60 pub enum RelationDir {
61 SubtypeOf, SupertypeOf, EqTo
64 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
65 pub fn super_combine_tys<R>(&self,
69 -> RelateResult<'tcx, Ty<'tcx>>
70 where R: TypeRelation<'infcx, 'gcx, 'tcx>
72 let a_is_expected = relation.a_is_expected();
74 match (&a.sty, &b.sty) {
75 // Relate integral variables to other types
76 (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(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::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
84 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
86 (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => {
87 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
89 (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => {
90 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
92 (&ty::TyUint(v), &ty::TyInfer(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::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(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::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
105 self.unify_float_variable(a_is_expected, v_id, v)
107 (&ty::TyFloat(v), &ty::TyInfer(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::TyInfer(_), _) |
113 (_, &ty::TyInfer(_)) => {
114 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
119 ty::relate::super_relate_tys(relation, a, b)
124 fn unify_integral_variable(&self,
125 vid_is_expected: bool,
127 val: ty::IntVarValue)
128 -> RelateResult<'tcx, Ty<'tcx>>
130 self.int_unification_table
132 .unify_var_value(vid, val)
133 .map_err(|e| int_unification_error(vid_is_expected, e))?;
135 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
136 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
140 fn unify_float_variable(&self,
141 vid_is_expected: bool,
144 -> RelateResult<'tcx, Ty<'tcx>>
146 self.float_unification_table
148 .unify_var_value(vid, val)
149 .map_err(|e| float_unification_error(vid_is_expected, e))?;
150 Ok(self.tcx.mk_mach_float(val))
154 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
155 pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
159 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
160 Equate::new(self, a_is_expected)
163 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
164 Sub::new(self, a_is_expected)
167 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
168 Lub::new(self, a_is_expected)
171 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
172 Glb::new(self, a_is_expected)
175 /// Here dir is either EqTo, SubtypeOf, or SupertypeOf. The
176 /// idea is that we should ensure that the type `a_ty` is equal
177 /// to, a subtype of, or a supertype of (respectively) the type
178 /// to which `b_vid` is bound.
180 /// Since `b_vid` has not yet been instantiated with a type, we
181 /// will first instantiate `b_vid` with a *generalized* version
182 /// of `a_ty`. Generalization introduces other inference
183 /// variables wherever subtyping could occur.
184 pub fn instantiate(&mut self,
189 -> RelateResult<'tcx, ()>
191 use self::RelationDir::*;
193 // Get the actual variable that b_vid has been inferred to
194 debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_none());
196 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
198 // Generalize type of `a_ty` appropriately depending on the
199 // direction. As an example, assume:
201 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
202 // inference variable,
203 // - and `dir` == `SubtypeOf`.
205 // Then the generalized form `b_ty` would be `&'?2 ?3`, where
206 // `'?2` and `?3` are fresh region/type inference
207 // variables. (Down below, we will relate `a_ty <: b_ty`,
208 // adding constraints like `'x: '?2` and `?1 <: ?3`.)
209 let b_ty = self.generalize(a_ty, b_vid, dir)?;
210 debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
211 a_ty, dir, b_vid, b_ty);
212 self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
214 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
216 // FIXME(#16847): This code is non-ideal because all these subtype
217 // relations wind up attributed to the same spans. We need
218 // to associate causes/spans with each of the relations in
219 // the stack to get this right.
221 EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
222 SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
223 SupertypeOf => self.sub(a_is_expected).relate_with_variance(
224 ty::Contravariant, &a_ty, &b_ty),
230 /// Attempts to generalize `ty` for the type variable `for_vid`.
231 /// This checks for cycle -- that is, whether the type `ty`
232 /// references `for_vid`. If `is_eq_relation` is false, it will
233 /// also replace all regions/unbound-type-variables with fresh
234 /// variables. Returns `TyError` in the case of a cycle, `Ok`
239 /// - `for_vid` is a "root vid"
244 -> RelateResult<'tcx, Ty<'tcx>>
246 // Determine the ambient variance within which `ty` appears.
247 // The surrounding equation is:
251 // where `op` is either `==`, `<:`, or `:>`. This maps quite
253 let ambient_variance = match dir {
254 RelationDir::EqTo => ty::Invariant,
255 RelationDir::SubtypeOf => ty::Covariant,
256 RelationDir::SupertypeOf => ty::Contravariant,
259 let mut generalize = Generalizer {
261 span: self.trace.cause.span,
262 for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
263 ambient_variance: ambient_variance,
266 generalize.relate(&ty, &ty)
270 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
271 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
273 for_vid_sub_root: ty::TyVid,
274 ambient_variance: ty::Variance,
277 impl<'cx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
278 fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
282 fn tag(&self) -> &'static str {
286 fn a_is_expected(&self) -> bool {
290 fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
291 -> RelateResult<'tcx, ty::Binder<T>>
292 where T: Relate<'tcx>
294 Ok(ty::Binder(self.relate(a.skip_binder(), b.skip_binder())?))
297 fn relate_with_variance<T: Relate<'tcx>>(&mut self,
298 variance: ty::Variance,
301 -> RelateResult<'tcx, T>
303 let old_ambient_variance = self.ambient_variance;
304 self.ambient_variance = self.ambient_variance.xform(variance);
306 let result = self.relate(a, b);
307 self.ambient_variance = old_ambient_variance;
311 fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
312 assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
314 // Check to see whether the type we are genealizing references
315 // any other type variable related to `vid` via
316 // subtyping. This is basically our "occurs check", preventing
317 // us from creating infinitely sized types.
319 ty::TyInfer(ty::TyVar(vid)) => {
320 let mut variables = self.infcx.type_variables.borrow_mut();
321 let vid = variables.root_var(vid);
322 let sub_vid = variables.sub_root_var(vid);
323 if sub_vid == self.for_vid_sub_root {
324 // If sub-roots are equal, then `for_vid` and
325 // `vid` are related via subtyping.
326 return Err(TypeError::CyclicTy);
328 match variables.probe_root(vid) {
334 match self.ambient_variance {
335 ty::Invariant => Ok(t),
337 ty::Bivariant | ty::Covariant | ty::Contravariant => {
338 let origin = variables.origin(vid);
339 let new_var_id = variables.new_var(false, origin, None);
340 let u = self.tcx().mk_var(new_var_id);
341 debug!("generalize: replacing original vid={:?} with new={:?}",
350 ty::TyInfer(ty::IntVar(_)) |
351 ty::TyInfer(ty::FloatVar(_)) => {
352 // No matter what mode we are in,
353 // integer/floating-point types must be equal to be
358 relate::super_relate_tys(self, t, t)
363 fn regions(&mut self, r: ty::Region<'tcx>, r2: ty::Region<'tcx>)
364 -> RelateResult<'tcx, ty::Region<'tcx>> {
365 assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
368 // Never make variables for regions bound within the type itself,
369 // nor for erased regions.
370 ty::ReLateBound(..) |
375 // Early-bound regions should really have been substituted away before
376 // we get to this point.
377 ty::ReEarlyBound(..) => {
380 "Encountered early bound region when generalizing: {:?}",
384 // Always make a fresh region variable for skolemized regions;
385 // the higher-ranked decision procedures rely on this.
386 ty::ReSkolemized(..) => { }
388 // For anything else, we make a region variable, unless we
389 // are *equating*, in which case it's just wasteful.
395 match self.ambient_variance {
396 ty::Invariant => return Ok(r),
397 ty::Bivariant | ty::Covariant | ty::Contravariant => (),
402 // FIXME: This is non-ideal because we don't give a
403 // very descriptive origin for this region variable.
404 Ok(self.infcx.next_region_var(MiscVariable(self.span)))
408 pub trait RelateResultCompare<'tcx, T> {
409 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
410 F: FnOnce() -> TypeError<'tcx>;
413 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
414 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
415 F: FnOnce() -> TypeError<'tcx>,
417 self.clone().and_then(|s| {
427 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
431 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
434 fn float_unification_error<'tcx>(a_is_expected: bool,
435 v: (ast::FloatTy, ast::FloatTy))
439 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))