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::fold::TypeFoldable;
46 use ty::relate::{RelateResult, TypeRelation};
47 use traits::PredicateObligations;
53 pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
54 pub infcx: &'infcx InferCtxt<'infcx, 'gcx, 'tcx>,
55 pub trace: TypeTrace<'tcx>,
56 pub cause: Option<ty::relate::Cause>,
57 pub obligations: PredicateObligations<'tcx>,
60 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
61 pub enum RelationDir {
62 SubtypeOf, SupertypeOf, EqTo
65 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
66 pub fn super_combine_tys<R>(&self,
70 -> RelateResult<'tcx, Ty<'tcx>>
71 where R: TypeRelation<'infcx, 'gcx, 'tcx>
73 let a_is_expected = relation.a_is_expected();
75 match (&a.sty, &b.sty) {
76 // Relate integral variables to other types
77 (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
78 self.int_unification_table
80 .unify_var_var(a_id, b_id)
81 .map_err(|e| int_unification_error(a_is_expected, e))?;
84 (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
85 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
87 (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => {
88 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
90 (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => {
91 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
93 (&ty::TyUint(v), &ty::TyInfer(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::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
99 self.float_unification_table
101 .unify_var_var(a_id, b_id)
102 .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
105 (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
106 self.unify_float_variable(a_is_expected, v_id, v)
108 (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => {
109 self.unify_float_variable(!a_is_expected, v_id, v)
112 // All other cases of inference are errors
113 (&ty::TyInfer(_), _) |
114 (_, &ty::TyInfer(_)) => {
115 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
120 ty::relate::super_relate_tys(relation, a, b)
125 fn unify_integral_variable(&self,
126 vid_is_expected: bool,
128 val: ty::IntVarValue)
129 -> RelateResult<'tcx, Ty<'tcx>>
131 self.int_unification_table
133 .unify_var_value(vid, val)
134 .map_err(|e| int_unification_error(vid_is_expected, e))?;
136 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
137 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
141 fn unify_float_variable(&self,
142 vid_is_expected: bool,
145 -> RelateResult<'tcx, Ty<'tcx>>
147 self.float_unification_table
149 .unify_var_value(vid, val)
150 .map_err(|e| float_unification_error(vid_is_expected, e))?;
151 Ok(self.tcx.mk_mach_float(val))
155 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
156 pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
160 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
161 Equate::new(self, a_is_expected)
164 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
165 Sub::new(self, a_is_expected)
168 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
169 Lub::new(self, a_is_expected)
172 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
173 Glb::new(self, a_is_expected)
176 /// Here dir is either EqTo, SubtypeOf, or SupertypeOf. The
177 /// idea is that we should ensure that the type `a_ty` is equal
178 /// to, a subtype of, or a supertype of (respectively) the type
179 /// to which `b_vid` is bound.
181 /// Since `b_vid` has not yet been instantiated with a type, we
182 /// will first instantiate `b_vid` with a *generalized* version
183 /// of `a_ty`. Generalization introduces other inference
184 /// variables wherever subtyping could occur.
185 pub fn instantiate(&mut self,
190 -> RelateResult<'tcx, ()>
192 use self::RelationDir::*;
194 // Get the actual variable that b_vid has been inferred to
195 debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_none());
197 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
199 // Generalize type of `a_ty` appropriately depending on the
200 // direction. As an example, assume:
202 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
203 // inference variable,
204 // - and `dir` == `SubtypeOf`.
206 // Then the generalized form `b_ty` would be `&'?2 ?3`, where
207 // `'?2` and `?3` are fresh region/type inference
208 // variables. (Down below, we will relate `a_ty <: b_ty`,
209 // adding constraints like `'x: '?2` and `?1 <: ?3`.)
210 let b_ty = self.generalize(a_ty, b_vid, dir == EqTo)?;
211 debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
212 a_ty, dir, b_vid, b_ty);
213 self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
215 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
217 // FIXME(#16847): This code is non-ideal because all these subtype
218 // relations wind up attributed to the same spans. We need
219 // to associate causes/spans with each of the relations in
220 // the stack to get this right.
222 EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
223 SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
224 SupertypeOf => self.sub(a_is_expected).relate_with_variance(
225 ty::Contravariant, &a_ty, &b_ty),
231 /// Attempts to generalize `ty` for the type variable `for_vid`.
232 /// This checks for cycle -- that is, whether the type `ty`
233 /// references `for_vid`. If `is_eq_relation` is false, it will
234 /// also replace all regions/unbound-type-variables with fresh
235 /// variables. Returns `TyError` in the case of a cycle, `Ok`
240 /// - `for_vid` is a "root vid"
244 is_eq_relation: bool)
245 -> RelateResult<'tcx, Ty<'tcx>>
247 let mut generalize = Generalizer {
249 span: self.trace.cause.span,
250 for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
251 is_eq_relation: is_eq_relation,
252 cycle_detected: false
254 let u = ty.fold_with(&mut generalize);
255 if generalize.cycle_detected {
256 Err(TypeError::CyclicTy)
263 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
264 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
266 for_vid_sub_root: ty::TyVid,
267 is_eq_relation: bool,
268 cycle_detected: bool,
271 impl<'cx, 'gcx, 'tcx> ty::fold::TypeFolder<'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
272 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
276 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
277 // Check to see whether the type we are genealizing references
278 // any other type variable related to `vid` via
279 // subtyping. This is basically our "occurs check", preventing
280 // us from creating infinitely sized types.
282 ty::TyInfer(ty::TyVar(vid)) => {
283 let mut variables = self.infcx.type_variables.borrow_mut();
284 let vid = variables.root_var(vid);
285 let sub_vid = variables.sub_root_var(vid);
286 if sub_vid == self.for_vid_sub_root {
287 // If sub-roots are equal, then `for_vid` and
288 // `vid` are related via subtyping.
289 self.cycle_detected = true;
292 match variables.probe_root(vid) {
298 if !self.is_eq_relation {
299 let origin = variables.origin(vid);
300 let new_var_id = variables.new_var(false, origin, None);
301 let u = self.tcx().mk_var(new_var_id);
302 debug!("generalize: replacing original vid={:?} with new={:?}",
313 t.super_fold_with(self)
318 fn fold_region(&mut self, r: &'tcx ty::Region) -> &'tcx ty::Region {
320 // Never make variables for regions bound within the type itself,
321 // nor for erased regions.
322 ty::ReLateBound(..) |
323 ty::ReErased => { return r; }
325 // Early-bound regions should really have been substituted away before
326 // we get to this point.
327 ty::ReEarlyBound(..) => {
330 "Encountered early bound region when generalizing: {:?}",
334 // Always make a fresh region variable for skolemized regions;
335 // the higher-ranked decision procedures rely on this.
336 ty::ReSkolemized(..) => { }
338 // For anything else, we make a region variable, unless we
339 // are *equating*, in which case it's just wasteful.
345 if self.is_eq_relation {
351 // FIXME: This is non-ideal because we don't give a
352 // very descriptive origin for this region variable.
353 self.infcx.next_region_var(MiscVariable(self.span))
357 pub trait RelateResultCompare<'tcx, T> {
358 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
359 F: FnOnce() -> TypeError<'tcx>;
362 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
363 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
364 F: FnOnce() -> TypeError<'tcx>,
366 self.clone().and_then(|s| {
376 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
380 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
383 fn float_unification_error<'tcx>(a_is_expected: bool,
384 v: (ast::FloatTy, ast::FloatTy))
388 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))