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::bivariate::Bivariate;
36 use super::equate::Equate;
40 use super::{InferCtxt};
41 use super::{MiscVariable, TypeTrace};
42 use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf};
44 use middle::ty::{IntType, UintType};
45 use middle::ty::{self, Ty, TyCtxt};
46 use middle::ty::error::TypeError;
47 use middle::ty::fold::{TypeFolder, TypeFoldable};
48 use middle::ty::relate::{Relate, RelateResult, TypeRelation};
51 use syntax::codemap::Span;
54 pub struct CombineFields<'a, 'tcx: 'a> {
55 pub infcx: &'a InferCtxt<'a, 'tcx>,
56 pub a_is_expected: bool,
57 pub trace: TypeTrace<'tcx>,
58 pub cause: Option<ty::relate::Cause>,
61 pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>,
65 -> RelateResult<'tcx, Ty<'tcx>>
66 where R: TypeRelation<'a,'tcx>
68 let a_is_expected = relation.a_is_expected();
70 match (&a.sty, &b.sty) {
71 // Relate integral variables to other types
72 (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
73 try!(infcx.int_unification_table
75 .unify_var_var(a_id, b_id)
76 .map_err(|e| int_unification_error(a_is_expected, e)));
79 (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
80 unify_integral_variable(infcx, a_is_expected, v_id, IntType(v))
82 (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => {
83 unify_integral_variable(infcx, !a_is_expected, v_id, IntType(v))
85 (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => {
86 unify_integral_variable(infcx, a_is_expected, v_id, UintType(v))
88 (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => {
89 unify_integral_variable(infcx, !a_is_expected, v_id, UintType(v))
92 // Relate floating-point variables to other types
93 (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
94 try!(infcx.float_unification_table
96 .unify_var_var(a_id, b_id)
97 .map_err(|e| float_unification_error(relation.a_is_expected(), e)));
100 (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
101 unify_float_variable(infcx, a_is_expected, v_id, v)
103 (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => {
104 unify_float_variable(infcx, !a_is_expected, v_id, v)
107 // All other cases of inference are errors
108 (&ty::TyInfer(_), _) |
109 (_, &ty::TyInfer(_)) => {
110 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
115 ty::relate::super_relate_tys(relation, a, b)
120 fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
121 vid_is_expected: bool,
123 val: ty::IntVarValue)
124 -> RelateResult<'tcx, Ty<'tcx>>
127 .int_unification_table
129 .unify_var_value(vid, val)
130 .map_err(|e| int_unification_error(vid_is_expected, e)));
132 IntType(v) => Ok(infcx.tcx.mk_mach_int(v)),
133 UintType(v) => Ok(infcx.tcx.mk_mach_uint(v)),
137 fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
138 vid_is_expected: bool,
141 -> RelateResult<'tcx, Ty<'tcx>>
144 .float_unification_table
146 .unify_var_value(vid, val)
147 .map_err(|e| float_unification_error(vid_is_expected, e)));
148 Ok(infcx.tcx.mk_mach_float(val))
151 impl<'a, 'tcx> CombineFields<'a, 'tcx> {
152 pub fn tcx(&self) -> &'a TyCtxt<'tcx> {
156 pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> {
158 a_is_expected: !self.a_is_expected,
163 pub fn equate(&self) -> Equate<'a, 'tcx> {
164 Equate::new(self.clone())
167 pub fn bivariate(&self) -> Bivariate<'a, 'tcx> {
168 Bivariate::new(self.clone())
171 pub fn sub(&self) -> Sub<'a, 'tcx> {
172 Sub::new(self.clone())
175 pub fn lub(&self) -> Lub<'a, 'tcx> {
176 Lub::new(self.clone())
179 pub fn glb(&self) -> Glb<'a, 'tcx> {
180 Glb::new(self.clone())
183 pub fn instantiate(&self,
187 -> RelateResult<'tcx, ()>
189 let mut stack = Vec::new();
190 stack.push((a_ty, dir, b_vid));
192 // For each turn of the loop, we extract a tuple
194 // (a_ty, dir, b_vid)
196 // to relate. Here dir is either SubtypeOf or
197 // SupertypeOf. The idea is that we should ensure that
198 // the type `a_ty` is a subtype or supertype (respectively) of the
199 // type to which `b_vid` is bound.
201 // If `b_vid` has not yet been instantiated with a type
202 // (which is always true on the first iteration, but not
203 // necessarily true on later iterations), we will first
204 // instantiate `b_vid` with a *generalized* version of
205 // `a_ty`. Generalization introduces other inference
206 // variables wherever subtyping could occur (at time of
207 // this writing, this means replacing free regions with
208 // region variables).
209 let (a_ty, dir, b_vid) = match stack.pop() {
214 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})",
219 // Check whether `vid` has been instantiated yet. If not,
220 // make a generalized form of `ty` and instantiate with
222 let b_ty = self.infcx.type_variables.borrow().probe(b_vid);
223 let b_ty = match b_ty {
224 Some(t) => t, // ...already instantiated.
225 None => { // ...not yet instantiated:
226 // Generalize type if necessary.
227 let generalized_ty = try!(match dir {
228 EqTo => self.generalize(a_ty, b_vid, false),
229 BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true),
231 debug!("instantiate(a_ty={:?}, dir={:?}, \
232 b_vid={:?}, generalized_ty={:?})",
235 self.infcx.type_variables
237 .instantiate_and_push(
238 b_vid, generalized_ty, &mut stack);
243 // The original triple was `(a_ty, dir, b_vid)` -- now we have
244 // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`:
246 // FIXME(#16847): This code is non-ideal because all these subtype
247 // relations wind up attributed to the same spans. We need
248 // to associate causes/spans with each of the relations in
249 // the stack to get this right.
251 BiTo => self.bivariate().relate(&a_ty, &b_ty),
252 EqTo => self.equate().relate(&a_ty, &b_ty),
253 SubtypeOf => self.sub().relate(&a_ty, &b_ty),
254 SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty),
261 /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that
262 /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also
263 /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok`
268 make_region_vars: bool)
269 -> RelateResult<'tcx, Ty<'tcx>>
271 let mut generalize = Generalizer {
273 span: self.trace.origin.span(),
275 make_region_vars: make_region_vars,
276 cycle_detected: false
278 let u = ty.fold_with(&mut generalize);
279 if generalize.cycle_detected {
280 Err(TypeError::CyclicTy)
287 struct Generalizer<'cx, 'tcx:'cx> {
288 infcx: &'cx InferCtxt<'cx, 'tcx>,
291 make_region_vars: bool,
292 cycle_detected: bool,
295 impl<'cx, 'tcx> ty::fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> {
296 fn tcx(&self) -> &TyCtxt<'tcx> {
300 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
301 // Check to see whether the type we are genealizing references
302 // `vid`. At the same time, also update any type variables to
303 // the values that they are bound to. This is needed to truly
304 // check for cycles, but also just makes things readable.
306 // (In particular, you could have something like `$0 = Box<$1>`
307 // where `$1` has already been instantiated with `Box<$0>`)
309 ty::TyInfer(ty::TyVar(vid)) => {
310 if vid == self.for_vid {
311 self.cycle_detected = true;
314 match self.infcx.type_variables.borrow().probe(vid) {
315 Some(u) => self.fold_ty(u),
321 t.super_fold_with(self)
326 fn fold_region(&mut self, r: ty::Region) -> ty::Region {
328 // Never make variables for regions bound within the type itself.
329 ty::ReLateBound(..) => { return r; }
331 // Early-bound regions should really have been substituted away before
332 // we get to this point.
333 ty::ReEarlyBound(..) => {
334 self.tcx().sess.span_bug(
336 &format!("Encountered early bound region when generalizing: {:?}",
340 // Always make a fresh region variable for skolemized regions;
341 // the higher-ranked decision procedures rely on this.
342 ty::ReSkolemized(..) => { }
344 // For anything else, we make a region variable, unless we
345 // are *equating*, in which case it's just wasteful.
351 if !self.make_region_vars {
357 // FIXME: This is non-ideal because we don't give a
358 // very descriptive origin for this region variable.
359 self.infcx.next_region_var(MiscVariable(self.span))
363 pub trait RelateResultCompare<'tcx, T> {
364 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
365 F: FnOnce() -> TypeError<'tcx>;
368 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
369 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
370 F: FnOnce() -> TypeError<'tcx>,
372 self.clone().and_then(|s| {
382 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
386 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
389 fn float_unification_error<'tcx>(a_is_expected: bool,
390 v: (ast::FloatTy, ast::FloatTy))
394 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))