]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/infer/combine.rs
a1608f57cd19d650d2dc11a8ad997cd4f5e5731e
[rustc.git] / src / librustc / middle / infer / combine.rs
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.
4 //
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.
10
11 ///////////////////////////////////////////////////////////////////////////
12 // # Type combining
13 //
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.
20 //
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.
25 //
26 // ## Contravariance
27 //
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.
34
35 use super::bivariate::Bivariate;
36 use super::equate::Equate;
37 use super::glb::Glb;
38 use super::lub::Lub;
39 use super::sub::Sub;
40 use super::{InferCtxt};
41 use super::{MiscVariable, TypeTrace};
42 use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf};
43
44 use middle::ty::{TyVar};
45 use middle::ty::{IntType, UintType};
46 use middle::ty::{self, Ty};
47 use middle::ty_fold;
48 use middle::ty_fold::{TypeFolder, TypeFoldable};
49 use middle::ty_relate::{self, Relate, RelateResult, TypeRelation};
50
51 use syntax::ast;
52 use syntax::codemap::Span;
53
54 #[derive(Clone)]
55 pub struct CombineFields<'a, 'tcx: 'a> {
56 pub infcx: &'a InferCtxt<'a, 'tcx>,
57 pub a_is_expected: bool,
58 pub trace: TypeTrace<'tcx>,
59 pub cause: Option<ty_relate::Cause>,
60 }
61
62 pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>,
63 relation: &mut R,
64 a: Ty<'tcx>,
65 b: Ty<'tcx>)
66 -> RelateResult<'tcx, Ty<'tcx>>
67 where R: TypeRelation<'a,'tcx>
68 {
69 let a_is_expected = relation.a_is_expected();
70
71 match (&a.sty, &b.sty) {
72 // Relate integral variables to other types
73 (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
74 try!(infcx.int_unification_table
75 .borrow_mut()
76 .unify_var_var(a_id, b_id)
77 .map_err(|e| int_unification_error(a_is_expected, e)));
78 Ok(a)
79 }
80 (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
81 unify_integral_variable(infcx, a_is_expected, v_id, IntType(v))
82 }
83 (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => {
84 unify_integral_variable(infcx, !a_is_expected, v_id, IntType(v))
85 }
86 (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => {
87 unify_integral_variable(infcx, a_is_expected, v_id, UintType(v))
88 }
89 (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => {
90 unify_integral_variable(infcx, !a_is_expected, v_id, UintType(v))
91 }
92
93 // Relate floating-point variables to other types
94 (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
95 try!(infcx.float_unification_table
96 .borrow_mut()
97 .unify_var_var(a_id, b_id)
98 .map_err(|e| float_unification_error(relation.a_is_expected(), e)));
99 Ok(a)
100 }
101 (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
102 unify_float_variable(infcx, a_is_expected, v_id, v)
103 }
104 (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => {
105 unify_float_variable(infcx, !a_is_expected, v_id, v)
106 }
107
108 // All other cases of inference are errors
109 (&ty::TyInfer(_), _) |
110 (_, &ty::TyInfer(_)) => {
111 Err(ty::terr_sorts(ty_relate::expected_found(relation, &a, &b)))
112 }
113
114
115 _ => {
116 ty_relate::super_relate_tys(relation, a, b)
117 }
118 }
119 }
120
121 fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
122 vid_is_expected: bool,
123 vid: ty::IntVid,
124 val: ty::IntVarValue)
125 -> RelateResult<'tcx, Ty<'tcx>>
126 {
127 try!(infcx
128 .int_unification_table
129 .borrow_mut()
130 .unify_var_value(vid, val)
131 .map_err(|e| int_unification_error(vid_is_expected, e)));
132 match val {
133 IntType(v) => Ok(ty::mk_mach_int(infcx.tcx, v)),
134 UintType(v) => Ok(ty::mk_mach_uint(infcx.tcx, v)),
135 }
136 }
137
138 fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
139 vid_is_expected: bool,
140 vid: ty::FloatVid,
141 val: ast::FloatTy)
142 -> RelateResult<'tcx, Ty<'tcx>>
143 {
144 try!(infcx
145 .float_unification_table
146 .borrow_mut()
147 .unify_var_value(vid, val)
148 .map_err(|e| float_unification_error(vid_is_expected, e)));
149 Ok(ty::mk_mach_float(infcx.tcx, val))
150 }
151
152 impl<'a, 'tcx> CombineFields<'a, 'tcx> {
153 pub fn tcx(&self) -> &'a ty::ctxt<'tcx> {
154 self.infcx.tcx
155 }
156
157 pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> {
158 CombineFields {
159 a_is_expected: !self.a_is_expected,
160 ..(*self).clone()
161 }
162 }
163
164 pub fn equate(&self) -> Equate<'a, 'tcx> {
165 Equate::new(self.clone())
166 }
167
168 pub fn bivariate(&self) -> Bivariate<'a, 'tcx> {
169 Bivariate::new(self.clone())
170 }
171
172 pub fn sub(&self) -> Sub<'a, 'tcx> {
173 Sub::new(self.clone())
174 }
175
176 pub fn lub(&self) -> Lub<'a, 'tcx> {
177 Lub::new(self.clone())
178 }
179
180 pub fn glb(&self) -> Glb<'a, 'tcx> {
181 Glb::new(self.clone())
182 }
183
184 pub fn instantiate(&self,
185 a_ty: Ty<'tcx>,
186 dir: RelationDir,
187 b_vid: ty::TyVid)
188 -> RelateResult<'tcx, ()>
189 {
190 let mut stack = Vec::new();
191 stack.push((a_ty, dir, b_vid));
192 loop {
193 // For each turn of the loop, we extract a tuple
194 //
195 // (a_ty, dir, b_vid)
196 //
197 // to relate. Here dir is either SubtypeOf or
198 // SupertypeOf. The idea is that we should ensure that
199 // the type `a_ty` is a subtype or supertype (respectively) of the
200 // type to which `b_vid` is bound.
201 //
202 // If `b_vid` has not yet been instantiated with a type
203 // (which is always true on the first iteration, but not
204 // necessarily true on later iterations), we will first
205 // instantiate `b_vid` with a *generalized* version of
206 // `a_ty`. Generalization introduces other inference
207 // variables wherever subtyping could occur (at time of
208 // this writing, this means replacing free regions with
209 // region variables).
210 let (a_ty, dir, b_vid) = match stack.pop() {
211 None => break,
212 Some(e) => e,
213 };
214
215 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})",
216 a_ty,
217 dir,
218 b_vid);
219
220 // Check whether `vid` has been instantiated yet. If not,
221 // make a generalized form of `ty` and instantiate with
222 // that.
223 let b_ty = self.infcx.type_variables.borrow().probe(b_vid);
224 let b_ty = match b_ty {
225 Some(t) => t, // ...already instantiated.
226 None => { // ...not yet instantiated:
227 // Generalize type if necessary.
228 let generalized_ty = try!(match dir {
229 EqTo => self.generalize(a_ty, b_vid, false),
230 BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true),
231 });
232 debug!("instantiate(a_ty={:?}, dir={:?}, \
233 b_vid={:?}, generalized_ty={:?})",
234 a_ty, dir, b_vid,
235 generalized_ty);
236 self.infcx.type_variables
237 .borrow_mut()
238 .instantiate_and_push(
239 b_vid, generalized_ty, &mut stack);
240 generalized_ty
241 }
242 };
243
244 // The original triple was `(a_ty, dir, b_vid)` -- now we have
245 // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`:
246 //
247 // FIXME(#16847): This code is non-ideal because all these subtype
248 // relations wind up attributed to the same spans. We need
249 // to associate causes/spans with each of the relations in
250 // the stack to get this right.
251 try!(match dir {
252 BiTo => self.bivariate().relate(&a_ty, &b_ty),
253 EqTo => self.equate().relate(&a_ty, &b_ty),
254 SubtypeOf => self.sub().relate(&a_ty, &b_ty),
255 SupertypeOf => self.sub().relate_with_variance(ty::Contravariant, &a_ty, &b_ty),
256 });
257 }
258
259 Ok(())
260 }
261
262 /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that
263 /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also
264 /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok`
265 /// otherwise.
266 fn generalize(&self,
267 ty: Ty<'tcx>,
268 for_vid: ty::TyVid,
269 make_region_vars: bool)
270 -> RelateResult<'tcx, Ty<'tcx>>
271 {
272 let mut generalize = Generalizer {
273 infcx: self.infcx,
274 span: self.trace.origin.span(),
275 for_vid: for_vid,
276 make_region_vars: make_region_vars,
277 cycle_detected: false
278 };
279 let u = ty.fold_with(&mut generalize);
280 if generalize.cycle_detected {
281 Err(ty::terr_cyclic_ty)
282 } else {
283 Ok(u)
284 }
285 }
286 }
287
288 struct Generalizer<'cx, 'tcx:'cx> {
289 infcx: &'cx InferCtxt<'cx, 'tcx>,
290 span: Span,
291 for_vid: ty::TyVid,
292 make_region_vars: bool,
293 cycle_detected: bool,
294 }
295
296 impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> {
297 fn tcx(&self) -> &ty::ctxt<'tcx> {
298 self.infcx.tcx
299 }
300
301 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
302 // Check to see whether the type we are genealizing references
303 // `vid`. At the same time, also update any type variables to
304 // the values that they are bound to. This is needed to truly
305 // check for cycles, but also just makes things readable.
306 //
307 // (In particular, you could have something like `$0 = Box<$1>`
308 // where `$1` has already been instantiated with `Box<$0>`)
309 match t.sty {
310 ty::TyInfer(ty::TyVar(vid)) => {
311 if vid == self.for_vid {
312 self.cycle_detected = true;
313 self.tcx().types.err
314 } else {
315 match self.infcx.type_variables.borrow().probe(vid) {
316 Some(u) => self.fold_ty(u),
317 None => t,
318 }
319 }
320 }
321 _ => {
322 ty_fold::super_fold_ty(self, t)
323 }
324 }
325 }
326
327 fn fold_region(&mut self, r: ty::Region) -> ty::Region {
328 match r {
329 // Never make variables for regions bound within the type itself.
330 ty::ReLateBound(..) => { return r; }
331
332 // Early-bound regions should really have been substituted away before
333 // we get to this point.
334 ty::ReEarlyBound(..) => {
335 self.tcx().sess.span_bug(
336 self.span,
337 &format!("Encountered early bound region when generalizing: {:?}",
338 r));
339 }
340
341 // Always make a fresh region variable for skolemized regions;
342 // the higher-ranked decision procedures rely on this.
343 ty::ReInfer(ty::ReSkolemized(..)) => { }
344
345 // For anything else, we make a region variable, unless we
346 // are *equating*, in which case it's just wasteful.
347 ty::ReEmpty |
348 ty::ReStatic |
349 ty::ReScope(..) |
350 ty::ReInfer(ty::ReVar(..)) |
351 ty::ReFree(..) => {
352 if !self.make_region_vars {
353 return r;
354 }
355 }
356 }
357
358 // FIXME: This is non-ideal because we don't give a
359 // very descriptive origin for this region variable.
360 self.infcx.next_region_var(MiscVariable(self.span))
361 }
362 }
363
364 pub trait RelateResultCompare<'tcx, T> {
365 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
366 F: FnOnce() -> ty::type_err<'tcx>;
367 }
368
369 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
370 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
371 F: FnOnce() -> ty::type_err<'tcx>,
372 {
373 self.clone().and_then(|s| {
374 if s == t {
375 self.clone()
376 } else {
377 Err(f())
378 }
379 })
380 }
381 }
382
383 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
384 -> ty::type_err<'tcx>
385 {
386 let (a, b) = v;
387 ty::terr_int_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b))
388 }
389
390 fn float_unification_error<'tcx>(a_is_expected: bool,
391 v: (ast::FloatTy, ast::FloatTy))
392 -> ty::type_err<'tcx>
393 {
394 let (a, b) = v;
395 ty::terr_float_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b))
396 }