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