]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/infer/combine.rs
Rollup merge of #31055 - steveklabnik:alt-tags, r=alexcrichton
[rust.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::{IntType, UintType};
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};
49
50 use syntax::ast;
51 use syntax::codemap::Span;
52
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>,
58     pub cause: Option<ty::relate::Cause>,
59 }
60
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>
67 {
68     let a_is_expected = relation.a_is_expected();
69
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
74                       .borrow_mut()
75                       .unify_var_var(a_id, b_id)
76                       .map_err(|e| int_unification_error(a_is_expected, e)));
77             Ok(a)
78         }
79         (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
80             unify_integral_variable(infcx, a_is_expected, v_id, IntType(v))
81         }
82         (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => {
83             unify_integral_variable(infcx, !a_is_expected, v_id, IntType(v))
84         }
85         (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => {
86             unify_integral_variable(infcx, a_is_expected, v_id, UintType(v))
87         }
88         (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => {
89             unify_integral_variable(infcx, !a_is_expected, v_id, UintType(v))
90         }
91
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
95                       .borrow_mut()
96                       .unify_var_var(a_id, b_id)
97                       .map_err(|e| float_unification_error(relation.a_is_expected(), e)));
98             Ok(a)
99         }
100         (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
101             unify_float_variable(infcx, a_is_expected, v_id, v)
102         }
103         (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => {
104             unify_float_variable(infcx, !a_is_expected, v_id, v)
105         }
106
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)))
111         }
112
113
114         _ => {
115             ty::relate::super_relate_tys(relation, a, b)
116         }
117     }
118 }
119
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 {
132         IntType(v) => Ok(infcx.tcx.mk_mach_int(v)),
133         UintType(v) => Ok(infcx.tcx.mk_mach_uint(v)),
134     }
135 }
136
137 fn unify_float_variable<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
138                                  vid_is_expected: bool,
139                                  vid: ty::FloatVid,
140                                  val: ast::FloatTy)
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)));
148     Ok(infcx.tcx.mk_mach_float(val))
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> {
157         CombineFields {
158             a_is_expected: !self.a_is_expected,
159             ..(*self).clone()
160         }
161     }
162
163     pub fn equate(&self) -> Equate<'a, 'tcx> {
164         Equate::new(self.clone())
165     }
166
167     pub fn bivariate(&self) -> Bivariate<'a, 'tcx> {
168         Bivariate::new(self.clone())
169     }
170
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())
181     }
182
183     pub fn instantiate(&self,
184                        a_ty: Ty<'tcx>,
185                        dir: RelationDir,
186                        b_vid: ty::TyVid)
187                        -> RelateResult<'tcx, ()>
188     {
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
214             debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})",
215                    a_ty,
216                    dir,
217                    b_vid);
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 {
228                         EqTo => self.generalize(a_ty, b_vid, false),
229                         BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true),
230                     });
231                     debug!("instantiate(a_ty={:?}, dir={:?}, \
232                                         b_vid={:?}, generalized_ty={:?})",
233                            a_ty, dir, b_vid,
234                            generalized_ty);
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.
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             });
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
263     /// replace all regions with fresh variables. Returns `TyError` in the case of a cycle, `Ok`
264     /// otherwise.
265     fn generalize(&self,
266                   ty: Ty<'tcx>,
267                   for_vid: ty::TyVid,
268                   make_region_vars: bool)
269                   -> RelateResult<'tcx, Ty<'tcx>>
270     {
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         };
278         let u = ty.fold_with(&mut generalize);
279         if generalize.cycle_detected {
280             Err(TypeError::CyclicTy)
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
295 impl<'cx, 'tcx> ty::fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> {
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 {
309             ty::TyInfer(ty::TyVar(vid)) => {
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             _ => {
321                 t.super_fold_with(self)
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,
336                     &format!("Encountered early bound region when generalizing: {:?}",
337                             r));
338             }
339
340             // Always make a fresh region variable for skolemized regions;
341             // the higher-ranked decision procedures rely on this.
342             ty::ReSkolemized(..) => { }
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(..) |
349             ty::ReVar(..) |
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 }
362
363 pub trait RelateResultCompare<'tcx, T> {
364     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
365         F: FnOnce() -> TypeError<'tcx>;
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
370         F: FnOnce() -> TypeError<'tcx>,
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))
383                                -> TypeError<'tcx>
384 {
385     let (a, b) = v;
386     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
387 }
388
389 fn float_unification_error<'tcx>(a_is_expected: bool,
390                                  v: (ast::FloatTy, ast::FloatTy))
391                                  -> TypeError<'tcx>
392 {
393     let (a, b) = v;
394     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
395 }