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.
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.
11 ///////////////////////////////////////////////////////////////////////////
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.
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.
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.
35 use super::equate::Equate;
39 use super::unify::InferCtxtMethodsForSimplyUnifiableTypes;
40 use super::{InferCtxt, cres};
41 use super::{MiscVariable, TypeTrace};
42 use super::type_variable::{RelationDir, EqTo, SubtypeOf, SupertypeOf};
45 use middle::subst::{ErasedRegions, NonerasedRegions, Substs};
46 use middle::ty::{FloatVar, FnSig, IntVar, TyVar};
47 use middle::ty::{IntType, UintType};
48 use middle::ty::{BuiltinBounds};
49 use middle::ty::{mod, Ty};
51 use middle::ty_fold::{TypeFoldable};
52 use util::ppaux::Repr;
55 use syntax::ast::{Onceness, Unsafety};
58 use syntax::codemap::Span;
60 pub trait Combine<'tcx> : Sized {
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>;
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>;
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>>;
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.
85 if as_.len() != bs.len() {
86 return Err(ty::terr_ty_param_size(expected_found(self,
91 try!(as_.iter().zip(bs.iter())
92 .map(|(a, b)| self.equate().tys(*a, *b))
93 .collect::<cres<Vec<Ty>>>());
98 item_def_id: ast::DefId,
99 a_subst: &subst::Substs<'tcx>,
100 b_subst: &subst::Substs<'tcx>)
101 -> cres<'tcx, subst::Substs<'tcx>>
103 let variances = if self.infcx().tcx.variance_computed.get() {
104 Some(ty::item_variances(self.infcx().tcx, item_def_id))
108 self.substs_variances(variances.as_ref().map(|v| &**v), a_subst, b_subst)
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>>
117 let mut substs = subst::Substs::empty();
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);
126 match (&a_subst.regions, &b_subst.regions) {
127 (&ErasedRegions, _) | (_, &ErasedRegions) => {
128 substs.regions = ErasedRegions;
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);
136 let mut invariance = Vec::new();
137 let r_variances = match variances {
139 variances.regions.get_slice(space)
142 for _ in a_regions.iter() {
143 invariance.push(ty::Invariant);
149 let regions = try!(relate_region_params(self,
153 substs.mut_regions().replace(space, regions);
160 fn relate_region_params<'tcx, C: Combine<'tcx>>(this: &C,
161 variances: &[ty::Variance],
164 -> cres<'tcx, Vec<ty::Region>> {
165 let tcx = this.infcx().tcx;
166 let num_region_params = variances.len();
168 debug!("relate_region_params(\
174 variances.repr(tcx));
176 assert_eq!(num_region_params, a_rs.len());
177 assert_eq!(num_region_params, b_rs.len());
179 for i in range(0, num_region_params) {
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),
195 fn bare_fn_tys(&self, a: &ty::BareFnTy<'tcx>,
196 b: &ty::BareFnTy<'tcx>) -> cres<'tcx, ty::BareFnTy<'tcx>> {
197 let unsafety = try!(self.unsafeties(a.unsafety, b.unsafety));
198 let abi = try!(self.abi(a.abi, b.abi));
199 let sig = try!(self.binders(&a.sig, &b.sig));
200 Ok(ty::BareFnTy {unsafety: unsafety,
205 fn closure_tys(&self, a: &ty::ClosureTy<'tcx>,
206 b: &ty::ClosureTy<'tcx>) -> cres<'tcx, ty::ClosureTy<'tcx>> {
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)
215 _ if a.store == b.store => {
220 return Err(ty::terr_sigil_mismatch(expected_found(self, a.store, b.store)))
223 let unsafety = try!(self.unsafeties(a.unsafety, b.unsafety));
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.binders(&a.sig, &b.sig));
227 let abi = try!(self.abi(a.abi, b.abi));
238 fn fn_sigs(&self, a: &ty::FnSig<'tcx>, b: &ty::FnSig<'tcx>) -> cres<'tcx, ty::FnSig<'tcx>> {
239 if a.variadic != b.variadic {
240 return Err(ty::terr_variadic_mismatch(expected_found(self, a.variadic, b.variadic)));
243 let inputs = try!(argvecs(self,
245 b.inputs.as_slice()));
247 let output = try!(match (a.output, b.output) {
248 (ty::FnConverging(a_ty), ty::FnConverging(b_ty)) =>
249 Ok(ty::FnConverging(try!(self.tys(a_ty, b_ty)))),
250 (ty::FnDiverging, ty::FnDiverging) =>
253 Err(ty::terr_convergence_mismatch(
254 expected_found(self, a != ty::FnDiverging, b != ty::FnDiverging))),
257 return Ok(ty::FnSig {inputs: inputs,
259 variadic: a.variadic});
262 fn argvecs<'tcx, C: Combine<'tcx>>(combiner: &C,
265 -> cres<'tcx, Vec<Ty<'tcx>>>
267 if a_args.len() == b_args.len() {
268 a_args.iter().zip(b_args.iter())
269 .map(|(a, b)| combiner.args(*a, *b)).collect()
271 Err(ty::terr_arg_count)
276 fn args(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> {
277 self.contratys(a, b).and_then(|t| Ok(t))
280 fn unsafeties(&self, a: Unsafety, b: Unsafety) -> cres<'tcx, Unsafety>;
282 fn abi(&self, a: abi::Abi, b: abi::Abi) -> cres<'tcx, abi::Abi> {
286 Err(ty::terr_abi_mismatch(expected_found(self, a, b)))
290 fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<'tcx, Onceness>;
292 fn projection_tys(&self,
293 a: &ty::ProjectionTy<'tcx>,
294 b: &ty::ProjectionTy<'tcx>)
295 -> cres<'tcx, ty::ProjectionTy<'tcx>>
297 if a.item_name != b.item_name {
298 Err(ty::terr_projection_name_mismatched(
299 expected_found(self, a.item_name, b.item_name)))
301 let trait_ref = try!(self.trait_refs(&*a.trait_ref, &*b.trait_ref));
302 Ok(ty::ProjectionTy { trait_ref: Rc::new(trait_ref), item_name: a.item_name })
306 fn projection_predicates(&self,
307 a: &ty::ProjectionPredicate<'tcx>,
308 b: &ty::ProjectionPredicate<'tcx>)
309 -> cres<'tcx, ty::ProjectionPredicate<'tcx>>
311 let projection_ty = try!(self.projection_tys(&a.projection_ty, &b.projection_ty));
312 let ty = try!(self.tys(a.ty, b.ty));
313 Ok(ty::ProjectionPredicate { projection_ty: projection_ty, ty: ty })
316 fn projection_bounds(&self,
317 a: &Vec<ty::PolyProjectionPredicate<'tcx>>,
318 b: &Vec<ty::PolyProjectionPredicate<'tcx>>)
319 -> cres<'tcx, Vec<ty::PolyProjectionPredicate<'tcx>>>
321 // To be compatible, `a` and `b` must be for precisely the
322 // same set of traits and item names. We always require that
323 // projection bounds lists are sorted by trait-def-id and item-name,
324 // so we can just iterate through the lists pairwise, so long as they are the
326 if a.len() != b.len() {
327 Err(ty::terr_projection_bounds_length(expected_found(self, a.len(), b.len())))
331 .map(|(a, b)| self.binders(a, b))
336 fn existential_bounds(&self,
337 a: &ty::ExistentialBounds<'tcx>,
338 b: &ty::ExistentialBounds<'tcx>)
339 -> cres<'tcx, ty::ExistentialBounds<'tcx>>
341 let r = try!(self.contraregions(a.region_bound, b.region_bound));
342 let nb = try!(self.builtin_bounds(a.builtin_bounds, b.builtin_bounds));
343 let pb = try!(self.projection_bounds(&a.projection_bounds, &b.projection_bounds));
344 Ok(ty::ExistentialBounds { region_bound: r,
346 projection_bounds: pb })
349 fn builtin_bounds(&self,
350 a: ty::BuiltinBounds,
351 b: ty::BuiltinBounds)
352 -> cres<'tcx, ty::BuiltinBounds>;
354 fn contraregions(&self, a: ty::Region, b: ty::Region)
355 -> cres<'tcx, ty::Region>;
357 fn regions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region>;
359 fn trait_stores(&self,
360 vk: ty::terr_vstore_kind,
363 -> cres<'tcx, ty::TraitStore> {
364 debug!("{}.trait_stores(a={}, b={})", self.tag(), a, b);
367 (ty::RegionTraitStore(a_r, a_m),
368 ty::RegionTraitStore(b_r, b_m)) if a_m == b_m => {
369 self.contraregions(a_r, b_r).and_then(|r| {
370 Ok(ty::RegionTraitStore(r, a_m))
379 Err(ty::terr_trait_stores_differ(vk, expected_found(self, a, b)))
385 a: &ty::TraitRef<'tcx>,
386 b: &ty::TraitRef<'tcx>)
387 -> cres<'tcx, ty::TraitRef<'tcx>>
389 // Different traits cannot be related
390 if a.def_id != b.def_id {
391 Err(ty::terr_traits(expected_found(self, a.def_id, b.def_id)))
393 let substs = try!(self.substs(a.def_id, a.substs, b.substs));
394 Ok(ty::TraitRef { def_id: a.def_id, substs: self.tcx().mk_substs(substs) })
398 fn binders<T>(&self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> cres<'tcx, ty::Binder<T>>
399 where T : Combineable<'tcx>;
400 // this must be overridden to do correctly, so as to account for higher-ranked
404 pub trait Combineable<'tcx> : Repr<'tcx> + TypeFoldable<'tcx> {
405 fn combine<C:Combine<'tcx>>(combiner: &C, a: &Self, b: &Self) -> cres<'tcx, Self>;
408 impl<'tcx,T> Combineable<'tcx> for Rc<T>
409 where T : Combineable<'tcx>
411 fn combine<C:Combine<'tcx>>(combiner: &C,
416 Ok(Rc::new(try!(Combineable::combine(combiner, &**a, &**b))))
420 impl<'tcx> Combineable<'tcx> for ty::TraitRef<'tcx> {
421 fn combine<C:Combine<'tcx>>(combiner: &C,
422 a: &ty::TraitRef<'tcx>,
423 b: &ty::TraitRef<'tcx>)
424 -> cres<'tcx, ty::TraitRef<'tcx>>
426 combiner.trait_refs(a, b)
430 impl<'tcx> Combineable<'tcx> for ty::ProjectionPredicate<'tcx> {
431 fn combine<C:Combine<'tcx>>(combiner: &C,
432 a: &ty::ProjectionPredicate<'tcx>,
433 b: &ty::ProjectionPredicate<'tcx>)
434 -> cres<'tcx, ty::ProjectionPredicate<'tcx>>
436 combiner.projection_predicates(a, b)
440 impl<'tcx> Combineable<'tcx> for ty::FnSig<'tcx> {
441 fn combine<C:Combine<'tcx>>(combiner: &C,
444 -> cres<'tcx, ty::FnSig<'tcx>>
446 combiner.fn_sigs(a, b)
451 pub struct CombineFields<'a, 'tcx: 'a> {
452 pub infcx: &'a InferCtxt<'a, 'tcx>,
453 pub a_is_expected: bool,
454 pub trace: TypeTrace<'tcx>,
457 pub fn expected_found<'tcx, C: Combine<'tcx>, T>(
458 this: &C, a: T, b: T) -> ty::expected_found<T> {
459 if this.a_is_expected() {
460 ty::expected_found {expected: a, found: b}
462 ty::expected_found {expected: b, found: a}
466 pub fn super_tys<'tcx, C: Combine<'tcx>>(this: &C,
469 -> cres<'tcx, Ty<'tcx>>
471 let tcx = this.infcx().tcx;
474 debug!("super_tys: a_sty={} b_sty={}", a_sty, b_sty);
475 return match (a_sty, b_sty) {
476 // The "subtype" ought to be handling cases involving var:
477 (&ty::ty_infer(TyVar(_)), _) |
478 (_, &ty::ty_infer(TyVar(_))) => {
480 format!("{}: bot and var types should have been handled ({},{})",
482 a.repr(this.infcx().tcx),
483 b.repr(this.infcx().tcx))[]);
486 (&ty::ty_err, _) | (_, &ty::ty_err) => {
490 // Relate integral variables to other types
491 (&ty::ty_infer(IntVar(a_id)), &ty::ty_infer(IntVar(b_id))) => {
492 try!(this.infcx().simple_vars(this.a_is_expected(),
496 (&ty::ty_infer(IntVar(v_id)), &ty::ty_int(v)) => {
497 unify_integral_variable(this, this.a_is_expected(),
500 (&ty::ty_int(v), &ty::ty_infer(IntVar(v_id))) => {
501 unify_integral_variable(this, !this.a_is_expected(),
504 (&ty::ty_infer(IntVar(v_id)), &ty::ty_uint(v)) => {
505 unify_integral_variable(this, this.a_is_expected(),
508 (&ty::ty_uint(v), &ty::ty_infer(IntVar(v_id))) => {
509 unify_integral_variable(this, !this.a_is_expected(),
513 // Relate floating-point variables to other types
514 (&ty::ty_infer(FloatVar(a_id)), &ty::ty_infer(FloatVar(b_id))) => {
515 try!(this.infcx().simple_vars(this.a_is_expected(), a_id, b_id));
518 (&ty::ty_infer(FloatVar(v_id)), &ty::ty_float(v)) => {
519 unify_float_variable(this, this.a_is_expected(), v_id, v)
521 (&ty::ty_float(v), &ty::ty_infer(FloatVar(v_id))) => {
522 unify_float_variable(this, !this.a_is_expected(), v_id, v)
527 (&ty::ty_int(_), _) |
528 (&ty::ty_uint(_), _) |
529 (&ty::ty_float(_), _) => {
533 Err(ty::terr_sorts(expected_found(this, a, b)))
537 (&ty::ty_param(ref a_p), &ty::ty_param(ref b_p)) if
538 a_p.idx == b_p.idx && a_p.space == b_p.space => {
542 (&ty::ty_enum(a_id, a_substs),
543 &ty::ty_enum(b_id, b_substs))
545 let substs = try!(this.substs(a_id,
548 Ok(ty::mk_enum(tcx, a_id, tcx.mk_substs(substs)))
551 (&ty::ty_trait(ref a_),
552 &ty::ty_trait(ref b_)) => {
553 debug!("Trying to match traits {} and {}", a, b);
554 let principal = try!(this.binders(&a_.principal, &b_.principal));
555 let bounds = try!(this.existential_bounds(&a_.bounds, &b_.bounds));
556 Ok(ty::mk_trait(tcx, principal, bounds))
559 (&ty::ty_struct(a_id, a_substs), &ty::ty_struct(b_id, b_substs))
561 let substs = try!(this.substs(a_id, a_substs, b_substs));
562 Ok(ty::mk_struct(tcx, a_id, tcx.mk_substs(substs)))
565 (&ty::ty_unboxed_closure(a_id, a_region, a_substs),
566 &ty::ty_unboxed_closure(b_id, b_region, b_substs))
568 // All ty_unboxed_closure types with the same id represent
569 // the (anonymous) type of the same closure expression. So
570 // all of their regions should be equated.
571 let region = try!(this.equate().regions(*a_region, *b_region));
572 let substs = try!(this.substs_variances(None, a_substs, b_substs));
573 Ok(ty::mk_unboxed_closure(tcx, a_id, tcx.mk_region(region), tcx.mk_substs(substs)))
576 (&ty::ty_uniq(a_inner), &ty::ty_uniq(b_inner)) => {
577 let typ = try!(this.tys(a_inner, b_inner));
578 Ok(ty::mk_uniq(tcx, typ))
581 (&ty::ty_ptr(ref a_mt), &ty::ty_ptr(ref b_mt)) => {
582 let mt = try!(this.mts(a_mt, b_mt));
583 Ok(ty::mk_ptr(tcx, mt))
586 (&ty::ty_rptr(a_r, ref a_mt), &ty::ty_rptr(b_r, ref b_mt)) => {
587 let r = try!(this.contraregions(*a_r, *b_r));
588 // FIXME(14985) If we have mutable references to trait objects, we
589 // used to use covariant subtyping. I have preserved this behaviour,
590 // even though it is probably incorrect. So don't go down the usual
591 // path which would require invariance.
592 let mt = match (&a_mt.ty.sty, &b_mt.ty.sty) {
593 (&ty::ty_trait(..), &ty::ty_trait(..)) if a_mt.mutbl == b_mt.mutbl => {
594 let ty = try!(this.tys(a_mt.ty, b_mt.ty));
595 ty::mt { ty: ty, mutbl: a_mt.mutbl }
597 _ => try!(this.mts(a_mt, b_mt))
599 Ok(ty::mk_rptr(tcx, tcx.mk_region(r), mt))
602 (&ty::ty_vec(a_t, Some(sz_a)), &ty::ty_vec(b_t, Some(sz_b))) => {
603 this.tys(a_t, b_t).and_then(|t| {
605 Ok(ty::mk_vec(tcx, t, Some(sz_a)))
607 Err(ty::terr_fixed_array_size(expected_found(this, sz_a, sz_b)))
612 (&ty::ty_vec(a_t, sz_a), &ty::ty_vec(b_t, sz_b)) => {
613 this.tys(a_t, b_t).and_then(|t| {
615 Ok(ty::mk_vec(tcx, t, sz_a))
617 Err(ty::terr_sorts(expected_found(this, a, b)))
622 (&ty::ty_str, &ty::ty_str) => {
626 (&ty::ty_tup(ref as_), &ty::ty_tup(ref bs)) => {
627 if as_.len() == bs.len() {
628 as_.iter().zip(bs.iter())
629 .map(|(a, b)| this.tys(*a, *b))
630 .collect::<Result<_, _>>()
631 .map(|ts| ty::mk_tup(tcx, ts))
632 } else if as_.len() != 0 && bs.len() != 0 {
633 Err(ty::terr_tuple_size(
634 expected_found(this, as_.len(), bs.len())))
636 Err(ty::terr_sorts(expected_found(this, a, b)))
640 (&ty::ty_bare_fn(a_opt_def_id, a_fty), &ty::ty_bare_fn(b_opt_def_id, b_fty))
641 if a_opt_def_id == b_opt_def_id =>
643 let fty = try!(this.bare_fn_tys(a_fty, b_fty));
644 Ok(ty::mk_bare_fn(tcx, a_opt_def_id, tcx.mk_bare_fn(fty)))
647 (&ty::ty_closure(ref a_fty), &ty::ty_closure(ref b_fty)) => {
648 this.closure_tys(&**a_fty, &**b_fty).and_then(|fty| {
649 Ok(ty::mk_closure(tcx, fty))
653 (&ty::ty_projection(ref a_data), &ty::ty_projection(ref b_data)) => {
654 let projection_ty = try!(this.projection_tys(a_data, b_data));
655 Ok(ty::mk_projection(tcx, projection_ty.trait_ref, projection_ty.item_name))
658 _ => Err(ty::terr_sorts(expected_found(this, a, b)))
661 fn unify_integral_variable<'tcx, C: Combine<'tcx>>(
663 vid_is_expected: bool,
665 val: ty::IntVarValue) -> cres<'tcx, Ty<'tcx>>
667 try!(this.infcx().simple_var_t(vid_is_expected, vid, val));
669 IntType(v) => Ok(ty::mk_mach_int(this.tcx(), v)),
670 UintType(v) => Ok(ty::mk_mach_uint(this.tcx(), v))
674 fn unify_float_variable<'tcx, C: Combine<'tcx>>(
676 vid_is_expected: bool,
678 val: ast::FloatTy) -> cres<'tcx, Ty<'tcx>>
680 try!(this.infcx().simple_var_t(vid_is_expected, vid, val));
681 Ok(ty::mk_mach_float(this.tcx(), val))
685 impl<'f, 'tcx> CombineFields<'f, 'tcx> {
686 pub fn switch_expected(&self) -> CombineFields<'f, 'tcx> {
688 a_is_expected: !self.a_is_expected,
693 fn equate(&self) -> Equate<'f, 'tcx> {
694 Equate((*self).clone())
697 fn sub(&self) -> Sub<'f, 'tcx> {
701 pub fn instantiate(&self,
707 let tcx = self.infcx.tcx;
708 let mut stack = Vec::new();
709 stack.push((a_ty, dir, b_vid));
711 // For each turn of the loop, we extract a tuple
713 // (a_ty, dir, b_vid)
715 // to relate. Here dir is either SubtypeOf or
716 // SupertypeOf. The idea is that we should ensure that
717 // the type `a_ty` is a subtype or supertype (respectively) of the
718 // type to which `b_vid` is bound.
720 // If `b_vid` has not yet been instantiated with a type
721 // (which is always true on the first iteration, but not
722 // necessarily true on later iterations), we will first
723 // instantiate `b_vid` with a *generalized* version of
724 // `a_ty`. Generalization introduces other inference
725 // variables wherever subtyping could occur (at time of
726 // this writing, this means replacing free regions with
727 // region variables).
728 let (a_ty, dir, b_vid) = match stack.pop() {
733 debug!("instantiate(a_ty={} dir={} b_vid={})",
738 // Check whether `vid` has been instantiated yet. If not,
739 // make a generalized form of `ty` and instantiate with
741 let b_ty = self.infcx.type_variables.borrow().probe(b_vid);
742 let b_ty = match b_ty {
743 Some(t) => t, // ...already instantiated.
744 None => { // ...not yet instantiated:
745 // Generalize type if necessary.
746 let generalized_ty = try!(match dir {
748 self.generalize(a_ty, b_vid, false)
750 SupertypeOf | SubtypeOf => {
751 self.generalize(a_ty, b_vid, true)
754 debug!("instantiate(a_ty={}, dir={}, \
755 b_vid={}, generalized_ty={})",
756 a_ty.repr(tcx), dir, b_vid.repr(tcx),
757 generalized_ty.repr(tcx));
758 self.infcx.type_variables
760 .instantiate_and_push(
761 b_vid, generalized_ty, &mut stack);
766 // The original triple was `(a_ty, dir, b_vid)` -- now we have
767 // resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`:
769 // FIXME(#16847): This code is non-ideal because all these subtype
770 // relations wind up attributed to the same spans. We need
771 // to associate causes/spans with each of the relations in
772 // the stack to get this right.
775 try!(self.equate().tys(a_ty, b_ty));
779 try!(self.sub().tys(a_ty, b_ty));
783 try!(self.sub().contratys(a_ty, b_ty));
791 /// Attempts to generalize `ty` for the type variable `for_vid`. This checks for cycle -- that
792 /// is, whether the type `ty` references `for_vid`. If `make_region_vars` is true, it will also
793 /// replace all regions with fresh variables. Returns `ty_err` in the case of a cycle, `Ok`
798 make_region_vars: bool)
799 -> cres<'tcx, Ty<'tcx>>
801 let mut generalize = Generalizer { infcx: self.infcx,
802 span: self.trace.origin.span(),
804 make_region_vars: make_region_vars,
805 cycle_detected: false };
806 let u = ty.fold_with(&mut generalize);
807 if generalize.cycle_detected {
808 Err(ty::terr_cyclic_ty)
815 struct Generalizer<'cx, 'tcx:'cx> {
816 infcx: &'cx InferCtxt<'cx, 'tcx>,
819 make_region_vars: bool,
820 cycle_detected: bool,
823 impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> {
824 fn tcx(&self) -> &ty::ctxt<'tcx> {
828 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
829 // Check to see whether the type we are genealizing references
830 // `vid`. At the same time, also update any type variables to
831 // the values that they are bound to. This is needed to truly
832 // check for cycles, but also just makes things readable.
834 // (In particular, you could have something like `$0 = Box<$1>`
835 // where `$1` has already been instantiated with `Box<$0>`)
837 ty::ty_infer(ty::TyVar(vid)) => {
838 if vid == self.for_vid {
839 self.cycle_detected = true;
842 match self.infcx.type_variables.borrow().probe(vid) {
843 Some(u) => self.fold_ty(u),
849 ty_fold::super_fold_ty(self, t)
854 fn fold_region(&mut self, r: ty::Region) -> ty::Region {
856 // Never make variables for regions bound within the type itself.
857 ty::ReLateBound(..) => { return r; }
859 // Early-bound regions should really have been substituted away before
860 // we get to this point.
861 ty::ReEarlyBound(..) => {
862 self.tcx().sess.span_bug(
864 format!("Encountered early bound region when generalizing: {}",
865 r.repr(self.tcx()))[]);
868 // Always make a fresh region variable for skolemized regions;
869 // the higher-ranked decision procedures rely on this.
870 ty::ReInfer(ty::ReSkolemized(..)) => { }
872 // For anything else, we make a region variable, unless we
873 // are *equating*, in which case it's just wasteful.
877 ty::ReInfer(ty::ReVar(..)) |
879 if !self.make_region_vars {
885 // FIXME: This is non-ideal because we don't give a
886 // very descriptive origin for this region variable.
887 self.infcx.next_region_var(MiscVariable(self.span))