]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/typeck/infer/combine.rs
/*! -> //!
[rust.git] / src / librustc / middle / typeck / 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
36 use middle::subst;
37 use middle::subst::{ErasedRegions, NonerasedRegions, Substs};
38 use middle::ty::{FloatVar, FnSig, IntVar, TyVar};
39 use middle::ty::{IntType, UintType};
40 use middle::ty::{BuiltinBounds};
41 use middle::ty::{mod, Ty};
42 use middle::ty_fold;
43 use middle::typeck::infer::equate::Equate;
44 use middle::typeck::infer::glb::Glb;
45 use middle::typeck::infer::lub::Lub;
46 use middle::typeck::infer::sub::Sub;
47 use middle::typeck::infer::unify::InferCtxtMethodsForSimplyUnifiableTypes;
48 use middle::typeck::infer::{InferCtxt, cres};
49 use middle::typeck::infer::{MiscVariable, TypeTrace};
50 use middle::typeck::infer::type_variable::{RelationDir, EqTo,
51                                            SubtypeOf, SupertypeOf};
52 use middle::ty_fold::{TypeFoldable};
53 use util::ppaux::Repr;
54
55 use syntax::ast::{Onceness, FnStyle};
56 use syntax::ast;
57 use syntax::abi;
58 use syntax::codemap::Span;
59
60 pub trait Combine<'tcx> {
61     fn infcx<'a>(&'a self) -> &'a InferCtxt<'a, 'tcx>;
62     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.infcx().tcx }
63     fn tag(&self) -> String;
64     fn a_is_expected(&self) -> bool;
65     fn trace(&self) -> TypeTrace<'tcx>;
66
67     fn equate<'a>(&'a self) -> Equate<'a, 'tcx>;
68     fn sub<'a>(&'a self) -> Sub<'a, 'tcx>;
69     fn lub<'a>(&'a self) -> Lub<'a, 'tcx>;
70     fn glb<'a>(&'a self) -> Glb<'a, 'tcx>;
71
72     fn mts(&self, a: &ty::mt<'tcx>, b: &ty::mt<'tcx>) -> cres<'tcx, ty::mt<'tcx>>;
73     fn contratys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>>;
74     fn tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>>;
75
76     fn tps(&self,
77            _: subst::ParamSpace,
78            as_: &[Ty<'tcx>],
79            bs: &[Ty<'tcx>])
80            -> cres<'tcx, Vec<Ty<'tcx>>> {
81         // FIXME -- In general, we treat variance a bit wrong
82         // here. For historical reasons, we treat tps and Self
83         // as invariant. This is overly conservative.
84
85         if as_.len() != bs.len() {
86             return Err(ty::terr_ty_param_size(expected_found(self,
87                                                              as_.len(),
88                                                              bs.len())));
89         }
90
91         try!(as_.iter().zip(bs.iter())
92                 .map(|(a, b)| self.equate().tys(*a, *b))
93                 .collect::<cres<Vec<Ty>>>());
94         Ok(as_.to_vec())
95     }
96
97     fn substs(&self,
98               item_def_id: ast::DefId,
99               a_subst: &subst::Substs<'tcx>,
100               b_subst: &subst::Substs<'tcx>)
101               -> cres<'tcx, subst::Substs<'tcx>>
102     {
103         let variances = if self.infcx().tcx.variance_computed.get() {
104             Some(ty::item_variances(self.infcx().tcx, item_def_id))
105         } else {
106             None
107         };
108         self.substs_variances(variances.as_ref().map(|v| &**v), a_subst, b_subst)
109     }
110
111     fn substs_variances(&self,
112                         variances: Option<&ty::ItemVariances>,
113                         a_subst: &subst::Substs<'tcx>,
114                         b_subst: &subst::Substs<'tcx>)
115                         -> cres<'tcx, subst::Substs<'tcx>>
116     {
117         let mut substs = subst::Substs::empty();
118
119         for &space in subst::ParamSpace::all().iter() {
120             let a_tps = a_subst.types.get_slice(space);
121             let b_tps = b_subst.types.get_slice(space);
122             let tps = try!(self.tps(space, a_tps, b_tps));
123             substs.types.replace(space, tps);
124         }
125
126         match (&a_subst.regions, &b_subst.regions) {
127             (&ErasedRegions, _) | (_, &ErasedRegions) => {
128                 substs.regions = ErasedRegions;
129             }
130
131             (&NonerasedRegions(ref a), &NonerasedRegions(ref b)) => {
132                 for &space in subst::ParamSpace::all().iter() {
133                     let a_regions = a.get_slice(space);
134                     let b_regions = b.get_slice(space);
135
136                     let mut invariance = Vec::new();
137                     let r_variances = match variances {
138                         Some(variances) => {
139                             variances.regions.get_slice(space)
140                         }
141                         None => {
142                             for _ in a_regions.iter() {
143                                 invariance.push(ty::Invariant);
144                             }
145                             invariance.as_slice()
146                         }
147                     };
148
149                     let regions = try!(relate_region_params(self,
150                                                             r_variances,
151                                                             a_regions,
152                                                             b_regions));
153                     substs.mut_regions().replace(space, regions);
154                 }
155             }
156         }
157
158         return Ok(substs);
159
160         fn relate_region_params<'tcx, C: Combine<'tcx>>(this: &C,
161                                                         variances: &[ty::Variance],
162                                                         a_rs: &[ty::Region],
163                                                         b_rs: &[ty::Region])
164                                                         -> cres<'tcx, Vec<ty::Region>> {
165             let tcx = this.infcx().tcx;
166             let num_region_params = variances.len();
167
168             debug!("relate_region_params(\
169                    a_rs={}, \
170                    b_rs={},
171                    variances={})",
172                    a_rs.repr(tcx),
173                    b_rs.repr(tcx),
174                    variances.repr(tcx));
175
176             assert_eq!(num_region_params, a_rs.len());
177             assert_eq!(num_region_params, b_rs.len());
178             let mut rs = vec!();
179             for i in range(0, num_region_params) {
180                 let a_r = a_rs[i];
181                 let b_r = b_rs[i];
182                 let variance = variances[i];
183                 let r = match variance {
184                     ty::Invariant => this.equate().regions(a_r, b_r),
185                     ty::Covariant => this.regions(a_r, b_r),
186                     ty::Contravariant => this.contraregions(a_r, b_r),
187                     ty::Bivariant => Ok(a_r),
188                 };
189                 rs.push(try!(r));
190             }
191             Ok(rs)
192         }
193     }
194
195     fn bare_fn_tys(&self, a: &ty::BareFnTy<'tcx>,
196                    b: &ty::BareFnTy<'tcx>) -> cres<'tcx, ty::BareFnTy<'tcx>> {
197         let fn_style = try!(self.fn_styles(a.fn_style, b.fn_style));
198         let abi = try!(self.abi(a.abi, b.abi));
199         let sig = try!(self.fn_sigs(&a.sig, &b.sig));
200         Ok(ty::BareFnTy {fn_style: fn_style,
201                 abi: abi,
202                 sig: sig})
203     }
204
205     fn closure_tys(&self, a: &ty::ClosureTy<'tcx>,
206                    b: &ty::ClosureTy<'tcx>) -> cres<'tcx, ty::ClosureTy<'tcx>> {
207
208         let store = match (a.store, b.store) {
209             (ty::RegionTraitStore(a_r, a_m),
210              ty::RegionTraitStore(b_r, b_m)) if a_m == b_m => {
211                 let r = try!(self.contraregions(a_r, b_r));
212                 ty::RegionTraitStore(r, a_m)
213             }
214
215             _ if a.store == b.store => {
216                 a.store
217             }
218
219             _ => {
220                 return Err(ty::terr_sigil_mismatch(expected_found(self, a.store, b.store)))
221             }
222         };
223         let fn_style = try!(self.fn_styles(a.fn_style, b.fn_style));
224         let onceness = try!(self.oncenesses(a.onceness, b.onceness));
225         let bounds = try!(self.existential_bounds(a.bounds, b.bounds));
226         let sig = try!(self.fn_sigs(&a.sig, &b.sig));
227         let abi = try!(self.abi(a.abi, b.abi));
228         Ok(ty::ClosureTy {
229             fn_style: fn_style,
230             onceness: onceness,
231             store: store,
232             bounds: bounds,
233             sig: sig,
234             abi: abi,
235         })
236     }
237
238     fn fn_sigs(&self, a: &ty::FnSig<'tcx>, b: &ty::FnSig<'tcx>) -> cres<'tcx, ty::FnSig<'tcx>>;
239
240     fn args(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> {
241         self.contratys(a, b).and_then(|t| Ok(t))
242     }
243
244     fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<'tcx, FnStyle>;
245
246     fn abi(&self, a: abi::Abi, b: abi::Abi) -> cres<'tcx, abi::Abi> {
247         if a == b {
248             Ok(a)
249         } else {
250             Err(ty::terr_abi_mismatch(expected_found(self, a, b)))
251         }
252     }
253
254     fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<'tcx, Onceness>;
255
256     fn existential_bounds(&self,
257                           a: ty::ExistentialBounds,
258                           b: ty::ExistentialBounds)
259                           -> cres<'tcx, ty::ExistentialBounds>
260     {
261         let r = try!(self.contraregions(a.region_bound, b.region_bound));
262         let nb = try!(self.builtin_bounds(a.builtin_bounds, b.builtin_bounds));
263         Ok(ty::ExistentialBounds { region_bound: r,
264                                    builtin_bounds: nb })
265     }
266
267     fn builtin_bounds(&self,
268                       a: ty::BuiltinBounds,
269                       b: ty::BuiltinBounds)
270                       -> cres<'tcx, ty::BuiltinBounds>;
271
272     fn contraregions(&self, a: ty::Region, b: ty::Region)
273                   -> cres<'tcx, ty::Region>;
274
275     fn regions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region>;
276
277     fn trait_stores(&self,
278                     vk: ty::terr_vstore_kind,
279                     a: ty::TraitStore,
280                     b: ty::TraitStore)
281                     -> cres<'tcx, ty::TraitStore> {
282         debug!("{}.trait_stores(a={}, b={})", self.tag(), a, b);
283
284         match (a, b) {
285             (ty::RegionTraitStore(a_r, a_m),
286              ty::RegionTraitStore(b_r, b_m)) if a_m == b_m => {
287                 self.contraregions(a_r, b_r).and_then(|r| {
288                     Ok(ty::RegionTraitStore(r, a_m))
289                 })
290             }
291
292             _ if a == b => {
293                 Ok(a)
294             }
295
296             _ => {
297                 Err(ty::terr_trait_stores_differ(vk, expected_found(self, a, b)))
298             }
299         }
300     }
301
302     fn trait_refs(&self,
303                   a: &ty::TraitRef<'tcx>,
304                   b: &ty::TraitRef<'tcx>)
305                   -> cres<'tcx, ty::TraitRef<'tcx>>;
306     // this must be overridden to do correctly, so as to account for higher-ranked
307     // behavior
308 }
309
310 #[deriving(Clone)]
311 pub struct CombineFields<'a, 'tcx: 'a> {
312     pub infcx: &'a InferCtxt<'a, 'tcx>,
313     pub a_is_expected: bool,
314     pub trace: TypeTrace<'tcx>,
315 }
316
317 pub fn expected_found<'tcx, C: Combine<'tcx>, T>(
318         this: &C, a: T, b: T) -> ty::expected_found<T> {
319     if this.a_is_expected() {
320         ty::expected_found {expected: a, found: b}
321     } else {
322         ty::expected_found {expected: b, found: a}
323     }
324 }
325
326 pub fn super_tys<'tcx, C: Combine<'tcx>>(this: &C,
327                                          a: Ty<'tcx>,
328                                          b: Ty<'tcx>)
329                                          -> cres<'tcx, Ty<'tcx>> {
330
331     let tcx = this.infcx().tcx;
332     let a_sty = &a.sty;
333     let b_sty = &b.sty;
334     debug!("super_tys: a_sty={} b_sty={}", a_sty, b_sty);
335     return match (a_sty, b_sty) {
336       // The "subtype" ought to be handling cases involving var:
337       (&ty::ty_infer(TyVar(_)), _) |
338       (_, &ty::ty_infer(TyVar(_))) => {
339         tcx.sess.bug(
340             format!("{}: bot and var types should have been handled ({},{})",
341                     this.tag(),
342                     a.repr(this.infcx().tcx),
343                     b.repr(this.infcx().tcx)).as_slice());
344       }
345
346       (&ty::ty_err, _) | (_, &ty::ty_err) => {
347           Ok(ty::mk_err())
348       }
349
350         // Relate integral variables to other types
351         (&ty::ty_infer(IntVar(a_id)), &ty::ty_infer(IntVar(b_id))) => {
352             try!(this.infcx().simple_vars(this.a_is_expected(),
353                                             a_id, b_id));
354             Ok(a)
355         }
356         (&ty::ty_infer(IntVar(v_id)), &ty::ty_int(v)) => {
357             unify_integral_variable(this, this.a_is_expected(),
358                                     v_id, IntType(v))
359         }
360         (&ty::ty_int(v), &ty::ty_infer(IntVar(v_id))) => {
361             unify_integral_variable(this, !this.a_is_expected(),
362                                     v_id, IntType(v))
363         }
364         (&ty::ty_infer(IntVar(v_id)), &ty::ty_uint(v)) => {
365             unify_integral_variable(this, this.a_is_expected(),
366                                     v_id, UintType(v))
367         }
368         (&ty::ty_uint(v), &ty::ty_infer(IntVar(v_id))) => {
369             unify_integral_variable(this, !this.a_is_expected(),
370                                     v_id, UintType(v))
371         }
372
373         // Relate floating-point variables to other types
374         (&ty::ty_infer(FloatVar(a_id)), &ty::ty_infer(FloatVar(b_id))) => {
375             try!(this.infcx().simple_vars(this.a_is_expected(), a_id, b_id));
376             Ok(a)
377         }
378         (&ty::ty_infer(FloatVar(v_id)), &ty::ty_float(v)) => {
379             unify_float_variable(this, this.a_is_expected(), v_id, v)
380         }
381         (&ty::ty_float(v), &ty::ty_infer(FloatVar(v_id))) => {
382             unify_float_variable(this, !this.a_is_expected(), v_id, v)
383         }
384
385       (&ty::ty_char, _) |
386       (&ty::ty_bool, _) |
387       (&ty::ty_int(_), _) |
388       (&ty::ty_uint(_), _) |
389       (&ty::ty_float(_), _) => {
390         if a == b {
391             Ok(a)
392         } else {
393             Err(ty::terr_sorts(expected_found(this, a, b)))
394         }
395       }
396
397       (&ty::ty_param(ref a_p), &ty::ty_param(ref b_p)) if
398           a_p.idx == b_p.idx && a_p.space == b_p.space => {
399         Ok(a)
400       }
401
402       (&ty::ty_enum(a_id, ref a_substs),
403        &ty::ty_enum(b_id, ref b_substs))
404       if a_id == b_id => {
405           let substs = try!(this.substs(a_id,
406                                           a_substs,
407                                           b_substs));
408           Ok(ty::mk_enum(tcx, a_id, substs))
409       }
410
411       (&ty::ty_trait(ref a_),
412        &ty::ty_trait(ref b_)) => {
413           debug!("Trying to match traits {} and {}", a, b);
414           let principal = try!(this.trait_refs(&a_.principal, &b_.principal));
415           let bounds = try!(this.existential_bounds(a_.bounds, b_.bounds));
416           Ok(ty::mk_trait(tcx, principal, bounds))
417       }
418
419       (&ty::ty_struct(a_id, ref a_substs), &ty::ty_struct(b_id, ref b_substs))
420       if a_id == b_id => {
421             let substs = try!(this.substs(a_id, a_substs, b_substs));
422             Ok(ty::mk_struct(tcx, a_id, substs))
423       }
424
425       (&ty::ty_unboxed_closure(a_id, a_region, ref a_substs),
426        &ty::ty_unboxed_closure(b_id, b_region, ref b_substs))
427       if a_id == b_id => {
428           // All ty_unboxed_closure types with the same id represent
429           // the (anonymous) type of the same closure expression. So
430           // all of their regions should be equated.
431           let region = try!(this.equate().regions(a_region, b_region));
432           let substs = try!(this.substs_variances(None, a_substs, b_substs));
433           Ok(ty::mk_unboxed_closure(tcx, a_id, region, substs))
434       }
435
436       (&ty::ty_uniq(a_inner), &ty::ty_uniq(b_inner)) => {
437           let typ = try!(this.tys(a_inner, b_inner));
438           Ok(ty::mk_uniq(tcx, typ))
439       }
440
441       (&ty::ty_ptr(ref a_mt), &ty::ty_ptr(ref b_mt)) => {
442           let mt = try!(this.mts(a_mt, b_mt));
443           Ok(ty::mk_ptr(tcx, mt))
444       }
445
446       (&ty::ty_rptr(a_r, ref a_mt), &ty::ty_rptr(b_r, ref b_mt)) => {
447             let r = try!(this.contraregions(a_r, b_r));
448             // FIXME(14985)  If we have mutable references to trait objects, we
449             // used to use covariant subtyping. I have preserved this behaviour,
450             // even though it is probably incorrect. So don't go down the usual
451             // path which would require invariance.
452             let mt = match (&a_mt.ty.sty, &b_mt.ty.sty) {
453                 (&ty::ty_trait(..), &ty::ty_trait(..)) if a_mt.mutbl == b_mt.mutbl => {
454                     let ty = try!(this.tys(a_mt.ty, b_mt.ty));
455                     ty::mt { ty: ty, mutbl: a_mt.mutbl }
456                 }
457                 _ => try!(this.mts(a_mt, b_mt))
458             };
459             Ok(ty::mk_rptr(tcx, r, mt))
460       }
461
462       (&ty::ty_vec(a_t, Some(sz_a)), &ty::ty_vec(b_t, Some(sz_b))) => {
463         this.tys(a_t, b_t).and_then(|t| {
464             if sz_a == sz_b {
465                 Ok(ty::mk_vec(tcx, t, Some(sz_a)))
466             } else {
467                 Err(ty::terr_fixed_array_size(expected_found(this, sz_a, sz_b)))
468             }
469         })
470       }
471
472       (&ty::ty_vec(a_t, sz_a), &ty::ty_vec(b_t, sz_b)) => {
473         this.tys(a_t, b_t).and_then(|t| {
474             if sz_a == sz_b {
475                 Ok(ty::mk_vec(tcx, t, sz_a))
476             } else {
477                 Err(ty::terr_sorts(expected_found(this, a, b)))
478             }
479         })
480       }
481
482       (&ty::ty_str, &ty::ty_str) => {
483             Ok(ty::mk_str(tcx))
484       }
485
486       (&ty::ty_tup(ref as_), &ty::ty_tup(ref bs)) => {
487         if as_.len() == bs.len() {
488             as_.iter().zip(bs.iter())
489                .map(|(a, b)| this.tys(*a, *b))
490                .collect::<Result<_, _>>()
491                .map(|ts| ty::mk_tup(tcx, ts))
492         } else if as_.len() != 0 && bs.len() != 0 {
493             Err(ty::terr_tuple_size(
494                 expected_found(this, as_.len(), bs.len())))
495         } else {
496             Err(ty::terr_sorts(expected_found(this, a, b)))
497         }
498       }
499
500       (&ty::ty_bare_fn(ref a_fty), &ty::ty_bare_fn(ref b_fty)) => {
501         this.bare_fn_tys(a_fty, b_fty).and_then(|fty| {
502             Ok(ty::mk_bare_fn(tcx, fty))
503         })
504       }
505
506       (&ty::ty_closure(ref a_fty), &ty::ty_closure(ref b_fty)) => {
507         this.closure_tys(&**a_fty, &**b_fty).and_then(|fty| {
508             Ok(ty::mk_closure(tcx, fty))
509         })
510       }
511
512       _ => Err(ty::terr_sorts(expected_found(this, a, b)))
513     };
514
515     fn unify_integral_variable<'tcx, C: Combine<'tcx>>(
516         this: &C,
517         vid_is_expected: bool,
518         vid: ty::IntVid,
519         val: ty::IntVarValue) -> cres<'tcx, Ty<'tcx>>
520     {
521         try!(this.infcx().simple_var_t(vid_is_expected, vid, val));
522         match val {
523             IntType(v) => Ok(ty::mk_mach_int(v)),
524             UintType(v) => Ok(ty::mk_mach_uint(v))
525         }
526     }
527
528     fn unify_float_variable<'tcx, C: Combine<'tcx>>(
529         this: &C,
530         vid_is_expected: bool,
531         vid: ty::FloatVid,
532         val: ast::FloatTy) -> cres<'tcx, Ty<'tcx>>
533     {
534         try!(this.infcx().simple_var_t(vid_is_expected, vid, val));
535         Ok(ty::mk_mach_float(val))
536     }
537 }
538
539 impl<'f, 'tcx> CombineFields<'f, 'tcx> {
540     pub fn switch_expected(&self) -> CombineFields<'f, 'tcx> {
541         CombineFields {
542             a_is_expected: !self.a_is_expected,
543             ..(*self).clone()
544         }
545     }
546
547     fn equate(&self) -> Equate<'f, 'tcx> {
548         Equate((*self).clone())
549     }
550
551     fn sub(&self) -> Sub<'f, 'tcx> {
552         Sub((*self).clone())
553     }
554
555     pub fn instantiate(&self,
556                        a_ty: Ty<'tcx>,
557                        dir: RelationDir,
558                        b_vid: ty::TyVid)
559                        -> cres<'tcx, ()>
560     {
561         let tcx = self.infcx.tcx;
562         let mut stack = Vec::new();
563         stack.push((a_ty, dir, b_vid));
564         loop {
565             // For each turn of the loop, we extract a tuple
566             //
567             //     (a_ty, dir, b_vid)
568             //
569             // to relate. Here dir is either SubtypeOf or
570             // SupertypeOf. The idea is that we should ensure that
571             // the type `a_ty` is a subtype or supertype (respectively) of the
572             // type to which `b_vid` is bound.
573             //
574             // If `b_vid` has not yet been instantiated with a type
575             // (which is always true on the first iteration, but not
576             // necessarily true on later iterations), we will first
577             // instantiate `b_vid` with a *generalized* version of
578             // `a_ty`. Generalization introduces other inference
579             // variables wherever subtyping could occur (at time of
580             // this writing, this means replacing free regions with
581             // region variables).
582             let (a_ty, dir, b_vid) = match stack.pop() {
583                 None => break,
584                 Some(e) => e,
585             };
586
587             debug!("instantiate(a_ty={} dir={} b_vid={})",
588                    a_ty.repr(tcx),
589                    dir,
590                    b_vid.repr(tcx));
591
592             // Check whether `vid` has been instantiated yet.  If not,
593             // make a generalized form of `ty` and instantiate with
594             // that.
595             let b_ty = self.infcx.type_variables.borrow().probe(b_vid);
596             let b_ty = match b_ty {
597                 Some(t) => t, // ...already instantiated.
598                 None => {     // ...not yet instantiated:
599                     // Generalize type if necessary.
600                     let generalized_ty = try!(match dir {
601                         EqTo => {
602                             self.generalize(a_ty, b_vid, false)
603                         }
604                         SupertypeOf | SubtypeOf => {
605                             self.generalize(a_ty, b_vid, true)
606                         }
607                     });
608                     debug!("instantiate(a_ty={}, dir={}, \
609                                         b_vid={}, generalized_ty={})",
610                            a_ty.repr(tcx), dir, b_vid.repr(tcx),
611                            generalized_ty.repr(tcx));
612                     self.infcx.type_variables
613                         .borrow_mut()
614                         .instantiate_and_push(
615                             b_vid, generalized_ty, &mut stack);
616                     generalized_ty
617                 }
618             };
619
620             // The original triple was `(a_ty, dir, b_vid)` -- now we have
621             // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`:
622             //
623             // FIXME(#16847): This code is non-ideal because all these subtype
624             // relations wind up attributed to the same spans. We need
625             // to associate causes/spans with each of the relations in
626             // the stack to get this right.
627             match dir {
628                 EqTo => {
629                     try!(self.equate().tys(a_ty, b_ty));
630                 }
631
632                 SubtypeOf => {
633                     try!(self.sub().tys(a_ty, b_ty));
634                 }
635
636                 SupertypeOf => {
637                     try!(self.sub().contratys(a_ty, b_ty));
638                 }
639             }
640         }
641
642         Ok(())
643     }
644
645     /// Attempts to generalize `ty` for the type variable `for_vid`.  This checks for cycle -- that
646     /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also
647     /// replace all regions with fresh variables. Returns `ty_err` in the case of a cycle, `Ok`
648     /// otherwise.
649     fn generalize(&self,
650                   ty: Ty<'tcx>,
651                   for_vid: ty::TyVid,
652                   make_region_vars: bool)
653                   -> cres<'tcx, Ty<'tcx>>
654     {
655         let mut generalize = Generalizer { infcx: self.infcx,
656                                            span: self.trace.origin.span(),
657                                            for_vid: for_vid,
658                                            make_region_vars: make_region_vars,
659                                            cycle_detected: false };
660         let u = ty.fold_with(&mut generalize);
661         if generalize.cycle_detected {
662             Err(ty::terr_cyclic_ty)
663         } else {
664             Ok(u)
665         }
666     }
667 }
668
669 struct Generalizer<'cx, 'tcx:'cx> {
670     infcx: &'cx InferCtxt<'cx, 'tcx>,
671     span: Span,
672     for_vid: ty::TyVid,
673     make_region_vars: bool,
674     cycle_detected: bool,
675 }
676
677 impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> {
678     fn tcx(&self) -> &ty::ctxt<'tcx> {
679         self.infcx.tcx
680     }
681
682     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
683         // Check to see whether the type we are genealizing references
684         // `vid`. At the same time, also update any type variables to
685         // the values that they are bound to. This is needed to truly
686         // check for cycles, but also just makes things readable.
687         //
688         // (In particular, you could have something like `$0 = Box<$1>`
689         //  where `$1` has already been instantiated with `Box<$0>`)
690         match t.sty {
691             ty::ty_infer(ty::TyVar(vid)) => {
692                 if vid == self.for_vid {
693                     self.cycle_detected = true;
694                     ty::mk_err()
695                 } else {
696                     match self.infcx.type_variables.borrow().probe(vid) {
697                         Some(u) => self.fold_ty(u),
698                         None => t,
699                     }
700                 }
701             }
702             _ => {
703                 ty_fold::super_fold_ty(self, t)
704             }
705         }
706     }
707
708     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
709         match r {
710             ty::ReLateBound(..) | ty::ReEarlyBound(..) => r,
711             _ if self.make_region_vars => {
712                 // FIXME: This is non-ideal because we don't give a
713                 // very descriptive origin for this region variable.
714                 self.infcx.next_region_var(MiscVariable(self.span))
715             }
716             _ => r,
717         }
718     }
719 }
720
721