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