]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/combine.rs
Rollup merge of #41249 - GuillaumeGomez:rustdoc-render, r=steveklabnik,frewsxcv
[rust.git] / src / librustc / 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::equate::Equate;
36 use super::glb::Glb;
37 use super::lub::Lub;
38 use super::sub::Sub;
39 use super::InferCtxt;
40 use super::{MiscVariable, TypeTrace};
41
42 use ty::{IntType, UintType};
43 use ty::{self, Ty, TyCtxt};
44 use ty::error::TypeError;
45 use ty::fold::TypeFoldable;
46 use ty::relate::{RelateResult, TypeRelation};
47 use traits::PredicateObligations;
48
49 use syntax::ast;
50 use syntax_pos::Span;
51
52 #[derive(Clone)]
53 pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
54     pub infcx: &'infcx InferCtxt<'infcx, 'gcx, 'tcx>,
55     pub trace: TypeTrace<'tcx>,
56     pub cause: Option<ty::relate::Cause>,
57     pub obligations: PredicateObligations<'tcx>,
58 }
59
60 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
61 pub enum RelationDir {
62     SubtypeOf, SupertypeOf, EqTo
63 }
64
65 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
66     pub fn super_combine_tys<R>(&self,
67                                 relation: &mut R,
68                                 a: Ty<'tcx>,
69                                 b: Ty<'tcx>)
70                                 -> RelateResult<'tcx, Ty<'tcx>>
71         where R: TypeRelation<'infcx, 'gcx, 'tcx>
72     {
73         let a_is_expected = relation.a_is_expected();
74
75         match (&a.sty, &b.sty) {
76             // Relate integral variables to other types
77             (&ty::TyInfer(ty::IntVar(a_id)), &ty::TyInfer(ty::IntVar(b_id))) => {
78                 self.int_unification_table
79                     .borrow_mut()
80                     .unify_var_var(a_id, b_id)
81                     .map_err(|e| int_unification_error(a_is_expected, e))?;
82                 Ok(a)
83             }
84             (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyInt(v)) => {
85                 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
86             }
87             (&ty::TyInt(v), &ty::TyInfer(ty::IntVar(v_id))) => {
88                 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
89             }
90             (&ty::TyInfer(ty::IntVar(v_id)), &ty::TyUint(v)) => {
91                 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
92             }
93             (&ty::TyUint(v), &ty::TyInfer(ty::IntVar(v_id))) => {
94                 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
95             }
96
97             // Relate floating-point variables to other types
98             (&ty::TyInfer(ty::FloatVar(a_id)), &ty::TyInfer(ty::FloatVar(b_id))) => {
99                 self.float_unification_table
100                     .borrow_mut()
101                     .unify_var_var(a_id, b_id)
102                     .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
103                 Ok(a)
104             }
105             (&ty::TyInfer(ty::FloatVar(v_id)), &ty::TyFloat(v)) => {
106                 self.unify_float_variable(a_is_expected, v_id, v)
107             }
108             (&ty::TyFloat(v), &ty::TyInfer(ty::FloatVar(v_id))) => {
109                 self.unify_float_variable(!a_is_expected, v_id, v)
110             }
111
112             // All other cases of inference are errors
113             (&ty::TyInfer(_), _) |
114             (_, &ty::TyInfer(_)) => {
115                 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
116             }
117
118
119             _ => {
120                 ty::relate::super_relate_tys(relation, a, b)
121             }
122         }
123     }
124
125     fn unify_integral_variable(&self,
126                                vid_is_expected: bool,
127                                vid: ty::IntVid,
128                                val: ty::IntVarValue)
129                                -> RelateResult<'tcx, Ty<'tcx>>
130     {
131         self.int_unification_table
132             .borrow_mut()
133             .unify_var_value(vid, val)
134             .map_err(|e| int_unification_error(vid_is_expected, e))?;
135         match val {
136             IntType(v) => Ok(self.tcx.mk_mach_int(v)),
137             UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
138         }
139     }
140
141     fn unify_float_variable(&self,
142                             vid_is_expected: bool,
143                             vid: ty::FloatVid,
144                             val: ast::FloatTy)
145                             -> RelateResult<'tcx, Ty<'tcx>>
146     {
147         self.float_unification_table
148             .borrow_mut()
149             .unify_var_value(vid, val)
150             .map_err(|e| float_unification_error(vid_is_expected, e))?;
151         Ok(self.tcx.mk_mach_float(val))
152     }
153 }
154
155 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
156     pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
157         self.infcx.tcx
158     }
159
160     pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
161         Equate::new(self, a_is_expected)
162     }
163
164     pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
165         Sub::new(self, a_is_expected)
166     }
167
168     pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
169         Lub::new(self, a_is_expected)
170     }
171
172     pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
173         Glb::new(self, a_is_expected)
174     }
175
176     /// Here dir is either EqTo, SubtypeOf, or SupertypeOf. The
177     /// idea is that we should ensure that the type `a_ty` is equal
178     /// to, a subtype of, or a supertype of (respectively) the type
179     /// to which `b_vid` is bound.
180     ///
181     /// Since `b_vid` has not yet been instantiated with a type, we
182     /// will first instantiate `b_vid` with a *generalized* version
183     /// of `a_ty`. Generalization introduces other inference
184     /// variables wherever subtyping could occur.
185     pub fn instantiate(&mut self,
186                        a_ty: Ty<'tcx>,
187                        dir: RelationDir,
188                        b_vid: ty::TyVid,
189                        a_is_expected: bool)
190                        -> RelateResult<'tcx, ()>
191     {
192         use self::RelationDir::*;
193
194         // Get the actual variable that b_vid has been inferred to
195         debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_none());
196
197         debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
198
199         // Generalize type of `a_ty` appropriately depending on the
200         // direction.  As an example, assume:
201         //
202         // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
203         //   inference variable,
204         // - and `dir` == `SubtypeOf`.
205         //
206         // Then the generalized form `b_ty` would be `&'?2 ?3`, where
207         // `'?2` and `?3` are fresh region/type inference
208         // variables. (Down below, we will relate `a_ty <: b_ty`,
209         // adding constraints like `'x: '?2` and `?1 <: ?3`.)
210         let b_ty = self.generalize(a_ty, b_vid, dir == EqTo)?;
211         debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
212                a_ty, dir, b_vid, b_ty);
213         self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
214
215         // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
216         //
217         // FIXME(#16847): This code is non-ideal because all these subtype
218         // relations wind up attributed to the same spans. We need
219         // to associate causes/spans with each of the relations in
220         // the stack to get this right.
221         match dir {
222             EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
223             SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
224             SupertypeOf => self.sub(a_is_expected).relate_with_variance(
225                 ty::Contravariant, &a_ty, &b_ty),
226         }?;
227
228         Ok(())
229     }
230
231     /// Attempts to generalize `ty` for the type variable `for_vid`.
232     /// This checks for cycle -- that is, whether the type `ty`
233     /// references `for_vid`. If `is_eq_relation` is false, it will
234     /// also replace all regions/unbound-type-variables with fresh
235     /// variables. Returns `TyError` in the case of a cycle, `Ok`
236     /// otherwise.
237     ///
238     /// Preconditions:
239     ///
240     /// - `for_vid` is a "root vid"
241     fn generalize(&self,
242                   ty: Ty<'tcx>,
243                   for_vid: ty::TyVid,
244                   is_eq_relation: bool)
245                   -> RelateResult<'tcx, Ty<'tcx>>
246     {
247         let mut generalize = Generalizer {
248             infcx: self.infcx,
249             span: self.trace.cause.span,
250             for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
251             is_eq_relation: is_eq_relation,
252             cycle_detected: false
253         };
254         let u = ty.fold_with(&mut generalize);
255         if generalize.cycle_detected {
256             Err(TypeError::CyclicTy)
257         } else {
258             Ok(u)
259         }
260     }
261 }
262
263 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
264     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
265     span: Span,
266     for_vid_sub_root: ty::TyVid,
267     is_eq_relation: bool,
268     cycle_detected: bool,
269 }
270
271 impl<'cx, 'gcx, 'tcx> ty::fold::TypeFolder<'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
272     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
273         self.infcx.tcx
274     }
275
276     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
277         // Check to see whether the type we are genealizing references
278         // any other type variable related to `vid` via
279         // subtyping. This is basically our "occurs check", preventing
280         // us from creating infinitely sized types.
281         match t.sty {
282             ty::TyInfer(ty::TyVar(vid)) => {
283                 let mut variables = self.infcx.type_variables.borrow_mut();
284                 let vid = variables.root_var(vid);
285                 let sub_vid = variables.sub_root_var(vid);
286                 if sub_vid == self.for_vid_sub_root {
287                     // If sub-roots are equal, then `for_vid` and
288                     // `vid` are related via subtyping.
289                     self.cycle_detected = true;
290                     self.tcx().types.err
291                 } else {
292                     match variables.probe_root(vid) {
293                         Some(u) => {
294                             drop(variables);
295                             self.fold_ty(u)
296                         }
297                         None => {
298                             if !self.is_eq_relation {
299                                 let origin = variables.origin(vid);
300                                 let new_var_id = variables.new_var(false, origin, None);
301                                 let u = self.tcx().mk_var(new_var_id);
302                                 debug!("generalize: replacing original vid={:?} with new={:?}",
303                                        vid, u);
304                                 u
305                             } else {
306                                 t
307                             }
308                         }
309                     }
310                 }
311             }
312             _ => {
313                 t.super_fold_with(self)
314             }
315         }
316     }
317
318     fn fold_region(&mut self, r: &'tcx ty::Region) -> &'tcx ty::Region {
319         match *r {
320             // Never make variables for regions bound within the type itself,
321             // nor for erased regions.
322             ty::ReLateBound(..) |
323             ty::ReErased => { return r; }
324
325             // Early-bound regions should really have been substituted away before
326             // we get to this point.
327             ty::ReEarlyBound(..) => {
328                 span_bug!(
329                     self.span,
330                     "Encountered early bound region when generalizing: {:?}",
331                     r);
332             }
333
334             // Always make a fresh region variable for skolemized regions;
335             // the higher-ranked decision procedures rely on this.
336             ty::ReSkolemized(..) => { }
337
338             // For anything else, we make a region variable, unless we
339             // are *equating*, in which case it's just wasteful.
340             ty::ReEmpty |
341             ty::ReStatic |
342             ty::ReScope(..) |
343             ty::ReVar(..) |
344             ty::ReFree(..) => {
345                 if self.is_eq_relation {
346                     return r;
347                 }
348             }
349         }
350
351         // FIXME: This is non-ideal because we don't give a
352         // very descriptive origin for this region variable.
353         self.infcx.next_region_var(MiscVariable(self.span))
354     }
355 }
356
357 pub trait RelateResultCompare<'tcx, T> {
358     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
359         F: FnOnce() -> TypeError<'tcx>;
360 }
361
362 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
363     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
364         F: FnOnce() -> TypeError<'tcx>,
365     {
366         self.clone().and_then(|s| {
367             if s == t {
368                 self.clone()
369             } else {
370                 Err(f())
371             }
372         })
373     }
374 }
375
376 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
377                                -> TypeError<'tcx>
378 {
379     let (a, b) = v;
380     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
381 }
382
383 fn float_unification_error<'tcx>(a_is_expected: bool,
384                                  v: (ast::FloatTy, ast::FloatTy))
385                                  -> TypeError<'tcx>
386 {
387     let (a, b) = v;
388     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
389 }