]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
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 | ||
85aaf69f | 35 | use super::bivariate::Bivariate; |
1a4d82fc JJ |
36 | use super::equate::Equate; |
37 | use super::glb::Glb; | |
38 | use super::lub::Lub; | |
39 | use super::sub::Sub; | |
c34b1796 | 40 | use super::{InferCtxt}; |
1a4d82fc | 41 | use super::{MiscVariable, TypeTrace}; |
85aaf69f | 42 | use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf}; |
1a4d82fc | 43 | |
1a4d82fc | 44 | use middle::ty::{IntType, UintType}; |
e9174d1e SL |
45 | use middle::ty::{self, Ty}; |
46 | use middle::ty::error::TypeError; | |
47 | use middle::ty::fold::{TypeFolder, TypeFoldable}; | |
48 | use middle::ty::relate::{Relate, RelateResult, TypeRelation}; | |
1a4d82fc | 49 | |
b039eaaf | 50 | use syntax::ast; |
1a4d82fc JJ |
51 | use syntax::codemap::Span; |
52 | ||
1a4d82fc JJ |
53 | #[derive(Clone)] |
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>, | |
e9174d1e | 58 | pub cause: Option<ty::relate::Cause>, |
1a4d82fc JJ |
59 | } |
60 | ||
c34b1796 AL |
61 | pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>, |
62 | relation: &mut R, | |
63 | a: Ty<'tcx>, | |
64 | b: Ty<'tcx>) | |
65 | -> RelateResult<'tcx, Ty<'tcx>> | |
66 | where R: TypeRelation<'a,'tcx> | |
1a4d82fc | 67 | { |
c34b1796 | 68 | let a_is_expected = relation.a_is_expected(); |
1a4d82fc | 69 | |
c34b1796 | 70 | match (&a.sty, &b.sty) { |
1a4d82fc | 71 | // Relate integral variables to other types |
62682a34 | 72 | (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => { |
c34b1796 AL |
73 | try!(infcx.int_unification_table |
74 | .borrow_mut() | |
75 | .unify_var_var(a_id, b_id) | |
76 | .map_err(|e| int_unification_error(a_is_expected, e))); | |
1a4d82fc JJ |
77 | Ok(a) |
78 | } | |
62682a34 | 79 | (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => { |
c34b1796 | 80 | unify_integral_variable(infcx, a_is_expected, v_id, IntType(v)) |
1a4d82fc | 81 | } |
62682a34 | 82 | (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => { |
c34b1796 | 83 | unify_integral_variable(infcx, !a_is_expected, v_id, IntType(v)) |
1a4d82fc | 84 | } |
62682a34 | 85 | (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => { |
c34b1796 | 86 | unify_integral_variable(infcx, a_is_expected, v_id, UintType(v)) |
1a4d82fc | 87 | } |
62682a34 | 88 | (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => { |
c34b1796 | 89 | unify_integral_variable(infcx, !a_is_expected, v_id, UintType(v)) |
1a4d82fc JJ |
90 | } |
91 | ||
92 | // Relate floating-point variables to other types | |
62682a34 | 93 | (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => { |
c34b1796 AL |
94 | try!(infcx.float_unification_table |
95 | .borrow_mut() | |
96 | .unify_var_var(a_id, b_id) | |
97 | .map_err(|e| float_unification_error(relation.a_is_expected(), e))); | |
1a4d82fc JJ |
98 | Ok(a) |
99 | } | |
62682a34 | 100 | (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => { |
c34b1796 | 101 | unify_float_variable(infcx, a_is_expected, v_id, v) |
1a4d82fc | 102 | } |
62682a34 | 103 | (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => { |
c34b1796 | 104 | unify_float_variable(infcx, !a_is_expected, v_id, v) |
1a4d82fc JJ |
105 | } |
106 | ||
c34b1796 | 107 | // All other cases of inference are errors |
62682a34 SL |
108 | (&ty::TyInfer(_), _) | |
109 | (_, &ty::TyInfer(_)) => { | |
e9174d1e | 110 | Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b))) |
1a4d82fc | 111 | } |
1a4d82fc | 112 | |
1a4d82fc | 113 | |
c34b1796 | 114 | _ => { |
e9174d1e | 115 | ty::relate::super_relate_tys(relation, a, b) |
1a4d82fc JJ |
116 | } |
117 | } | |
c34b1796 | 118 | } |
1a4d82fc | 119 | |
c34b1796 AL |
120 | fn unify_integral_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, |
121 | vid_is_expected: bool, | |
122 | vid: ty::IntVid, | |
123 | val: ty::IntVarValue) | |
124 | -> RelateResult<'tcx, Ty<'tcx>> | |
125 | { | |
126 | try!(infcx | |
127 | .int_unification_table | |
128 | .borrow_mut() | |
129 | .unify_var_value(vid, val) | |
130 | .map_err(|e| int_unification_error(vid_is_expected, e))); | |
131 | match val { | |
c1a9b12d SL |
132 | IntType(v) => Ok(infcx.tcx.mk_mach_int(v)), |
133 | UintType(v) => Ok(infcx.tcx.mk_mach_uint(v)), | |
1a4d82fc JJ |
134 | } |
135 | } | |
136 | ||
c34b1796 AL |
137 | fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, |
138 | vid_is_expected: bool, | |
139 | vid: ty::FloatVid, | |
b039eaaf | 140 | val: ast::FloatTy) |
c34b1796 AL |
141 | -> RelateResult<'tcx, Ty<'tcx>> |
142 | { | |
143 | try!(infcx | |
144 | .float_unification_table | |
145 | .borrow_mut() | |
146 | .unify_var_value(vid, val) | |
147 | .map_err(|e| float_unification_error(vid_is_expected, e))); | |
c1a9b12d | 148 | Ok(infcx.tcx.mk_mach_float(val)) |
c34b1796 AL |
149 | } |
150 | ||
151 | impl<'a, 'tcx> CombineFields<'a, 'tcx> { | |
152 | pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { | |
153 | self.infcx.tcx | |
154 | } | |
155 | ||
156 | pub fn switch_expected(&self) -> CombineFields<'a, 'tcx> { | |
1a4d82fc JJ |
157 | CombineFields { |
158 | a_is_expected: !self.a_is_expected, | |
159 | ..(*self).clone() | |
160 | } | |
161 | } | |
162 | ||
c34b1796 AL |
163 | pub fn equate(&self) -> Equate<'a, 'tcx> { |
164 | Equate::new(self.clone()) | |
1a4d82fc JJ |
165 | } |
166 | ||
c34b1796 AL |
167 | pub fn bivariate(&self) -> Bivariate<'a, 'tcx> { |
168 | Bivariate::new(self.clone()) | |
85aaf69f SL |
169 | } |
170 | ||
c34b1796 AL |
171 | pub fn sub(&self) -> Sub<'a, 'tcx> { |
172 | Sub::new(self.clone()) | |
173 | } | |
174 | ||
175 | pub fn lub(&self) -> Lub<'a, 'tcx> { | |
176 | Lub::new(self.clone()) | |
177 | } | |
178 | ||
179 | pub fn glb(&self) -> Glb<'a, 'tcx> { | |
180 | Glb::new(self.clone()) | |
1a4d82fc JJ |
181 | } |
182 | ||
183 | pub fn instantiate(&self, | |
184 | a_ty: Ty<'tcx>, | |
185 | dir: RelationDir, | |
186 | b_vid: ty::TyVid) | |
c34b1796 | 187 | -> RelateResult<'tcx, ()> |
1a4d82fc | 188 | { |
1a4d82fc JJ |
189 | let mut stack = Vec::new(); |
190 | stack.push((a_ty, dir, b_vid)); | |
191 | loop { | |
192 | // For each turn of the loop, we extract a tuple | |
193 | // | |
194 | // (a_ty, dir, b_vid) | |
195 | // | |
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. | |
200 | // | |
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() { | |
210 | None => break, | |
211 | Some(e) => e, | |
212 | }; | |
213 | ||
62682a34 SL |
214 | debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", |
215 | a_ty, | |
1a4d82fc | 216 | dir, |
62682a34 | 217 | b_vid); |
1a4d82fc JJ |
218 | |
219 | // Check whether `vid` has been instantiated yet. If not, | |
220 | // make a generalized form of `ty` and instantiate with | |
221 | // that. | |
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 { | |
c34b1796 AL |
228 | EqTo => self.generalize(a_ty, b_vid, false), |
229 | BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true), | |
1a4d82fc | 230 | }); |
62682a34 SL |
231 | debug!("instantiate(a_ty={:?}, dir={:?}, \ |
232 | b_vid={:?}, generalized_ty={:?})", | |
233 | a_ty, dir, b_vid, | |
234 | generalized_ty); | |
1a4d82fc JJ |
235 | self.infcx.type_variables |
236 | .borrow_mut() | |
237 | .instantiate_and_push( | |
238 | b_vid, generalized_ty, &mut stack); | |
239 | generalized_ty | |
240 | } | |
241 | }; | |
242 | ||
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)`: | |
245 | // | |
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. | |
c34b1796 AL |
250 | try!(match dir { |
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), | |
255 | }); | |
1a4d82fc JJ |
256 | } |
257 | ||
258 | Ok(()) | |
259 | } | |
260 | ||
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 | |
62682a34 | 263 | /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok` |
1a4d82fc JJ |
264 | /// otherwise. |
265 | fn generalize(&self, | |
266 | ty: Ty<'tcx>, | |
267 | for_vid: ty::TyVid, | |
268 | make_region_vars: bool) | |
c34b1796 | 269 | -> RelateResult<'tcx, Ty<'tcx>> |
1a4d82fc | 270 | { |
c34b1796 AL |
271 | let mut generalize = Generalizer { |
272 | infcx: self.infcx, | |
273 | span: self.trace.origin.span(), | |
274 | for_vid: for_vid, | |
275 | make_region_vars: make_region_vars, | |
276 | cycle_detected: false | |
277 | }; | |
1a4d82fc JJ |
278 | let u = ty.fold_with(&mut generalize); |
279 | if generalize.cycle_detected { | |
c1a9b12d | 280 | Err(TypeError::CyclicTy) |
1a4d82fc JJ |
281 | } else { |
282 | Ok(u) | |
283 | } | |
284 | } | |
285 | } | |
286 | ||
287 | struct Generalizer<'cx, 'tcx:'cx> { | |
288 | infcx: &'cx InferCtxt<'cx, 'tcx>, | |
289 | span: Span, | |
290 | for_vid: ty::TyVid, | |
291 | make_region_vars: bool, | |
292 | cycle_detected: bool, | |
293 | } | |
294 | ||
e9174d1e | 295 | impl<'cx, 'tcx> ty::fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> { |
1a4d82fc JJ |
296 | fn tcx(&self) -> &ty::ctxt<'tcx> { |
297 | self.infcx.tcx | |
298 | } | |
299 | ||
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. | |
305 | // | |
306 | // (In particular, you could have something like `$0 = Box<$1>` | |
307 | // where `$1` has already been instantiated with `Box<$0>`) | |
308 | match t.sty { | |
62682a34 | 309 | ty::TyInfer(ty::TyVar(vid)) => { |
1a4d82fc JJ |
310 | if vid == self.for_vid { |
311 | self.cycle_detected = true; | |
312 | self.tcx().types.err | |
313 | } else { | |
314 | match self.infcx.type_variables.borrow().probe(vid) { | |
315 | Some(u) => self.fold_ty(u), | |
316 | None => t, | |
317 | } | |
318 | } | |
319 | } | |
320 | _ => { | |
9cc50fc6 | 321 | t.super_fold_with(self) |
1a4d82fc JJ |
322 | } |
323 | } | |
324 | } | |
325 | ||
326 | fn fold_region(&mut self, r: ty::Region) -> ty::Region { | |
327 | match r { | |
328 | // Never make variables for regions bound within the type itself. | |
329 | ty::ReLateBound(..) => { return r; } | |
330 | ||
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( | |
335 | self.span, | |
62682a34 SL |
336 | &format!("Encountered early bound region when generalizing: {:?}", |
337 | r)); | |
1a4d82fc JJ |
338 | } |
339 | ||
340 | // Always make a fresh region variable for skolemized regions; | |
341 | // the higher-ranked decision procedures rely on this. | |
e9174d1e | 342 | ty::ReSkolemized(..) => { } |
1a4d82fc JJ |
343 | |
344 | // For anything else, we make a region variable, unless we | |
345 | // are *equating*, in which case it's just wasteful. | |
346 | ty::ReEmpty | | |
347 | ty::ReStatic | | |
348 | ty::ReScope(..) | | |
e9174d1e | 349 | ty::ReVar(..) | |
1a4d82fc JJ |
350 | ty::ReFree(..) => { |
351 | if !self.make_region_vars { | |
352 | return r; | |
353 | } | |
354 | } | |
355 | } | |
356 | ||
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)) | |
360 | } | |
361 | } | |
c34b1796 AL |
362 | |
363 | pub trait RelateResultCompare<'tcx, T> { | |
364 | fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where | |
e9174d1e | 365 | F: FnOnce() -> TypeError<'tcx>; |
c34b1796 AL |
366 | } |
367 | ||
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 | |
e9174d1e | 370 | F: FnOnce() -> TypeError<'tcx>, |
c34b1796 AL |
371 | { |
372 | self.clone().and_then(|s| { | |
373 | if s == t { | |
374 | self.clone() | |
375 | } else { | |
376 | Err(f()) | |
377 | } | |
378 | }) | |
379 | } | |
380 | } | |
381 | ||
382 | fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue)) | |
e9174d1e | 383 | -> TypeError<'tcx> |
c34b1796 AL |
384 | { |
385 | let (a, b) = v; | |
e9174d1e | 386 | TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b)) |
c34b1796 AL |
387 | } |
388 | ||
389 | fn float_unification_error<'tcx>(a_is_expected: bool, | |
b039eaaf | 390 | v: (ast::FloatTy, ast::FloatTy)) |
e9174d1e | 391 | -> TypeError<'tcx> |
c34b1796 AL |
392 | { |
393 | let (a, b) = v; | |
e9174d1e | 394 | TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b)) |
c34b1796 | 395 | } |