1 // Copyright 2012-2013 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 //! Generalized type relating mechanism. A type relation R relates a
12 //! pair of values (A, B). A and B are usually types or regions but
13 //! can be other things. Examples of type relations are subtyping,
14 //! type equality, etc.
16 use hir::def_id::DefId;
17 use ty::subst::{Kind, Substs};
18 use ty::{self, Ty, TyCtxt, TypeFoldable};
19 use ty::error::{ExpectedFound, TypeError};
24 use rustc_data_structures::accumulate_vec::AccumulateVec;
26 pub type RelateResult<'tcx, T> = Result<T, TypeError<'tcx>>;
28 #[derive(Clone, Debug)]
30 ExistentialRegionBound, // relating an existential region bound
33 pub trait TypeRelation<'a, 'gcx: 'a+'tcx, 'tcx: 'a> : Sized {
34 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx>;
36 /// Returns a static string we can use for printouts.
37 fn tag(&self) -> &'static str;
39 /// Returns true if the value `a` is the "expected" type in the
40 /// relation. Just affects error messages.
41 fn a_is_expected(&self) -> bool;
43 fn with_cause<F,R>(&mut self, _cause: Cause, f: F) -> R
44 where F: FnOnce(&mut Self) -> R
49 /// Generic relation routine suitable for most anything.
50 fn relate<T: Relate<'tcx>>(&mut self, a: &T, b: &T) -> RelateResult<'tcx, T> {
51 Relate::relate(self, a, b)
54 /// Relate the two substitutions for the given item. The default
55 /// is to look up the variance for the item and proceed
57 fn relate_item_substs(&mut self,
59 a_subst: &'tcx Substs<'tcx>,
60 b_subst: &'tcx Substs<'tcx>)
61 -> RelateResult<'tcx, &'tcx Substs<'tcx>>
63 debug!("relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
68 let opt_variances = self.tcx().variances_of(item_def_id);
69 relate_substs(self, Some(&opt_variances), a_subst, b_subst)
72 /// Switch variance for the purpose of relating `a` and `b`.
73 fn relate_with_variance<T: Relate<'tcx>>(&mut self,
74 variance: ty::Variance,
77 -> RelateResult<'tcx, T>;
79 // Overrideable relations. You shouldn't typically call these
80 // directly, instead call `relate()`, which in turn calls
81 // these. This is both more uniform but also allows us to add
82 // additional hooks for other types in the future if needed
83 // without making older code, which called `relate`, obsolete.
85 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>)
86 -> RelateResult<'tcx, Ty<'tcx>>;
88 fn regions(&mut self, a: ty::Region<'tcx>, b: ty::Region<'tcx>)
89 -> RelateResult<'tcx, ty::Region<'tcx>>;
91 fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
92 -> RelateResult<'tcx, ty::Binder<T>>
93 where T: Relate<'tcx>;
96 pub trait Relate<'tcx>: TypeFoldable<'tcx> {
97 fn relate<'a, 'gcx, R>(relation: &mut R, a: &Self, b: &Self)
98 -> RelateResult<'tcx, Self>
99 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a;
102 ///////////////////////////////////////////////////////////////////////////
105 impl<'tcx> Relate<'tcx> for ty::TypeAndMut<'tcx> {
106 fn relate<'a, 'gcx, R>(relation: &mut R,
107 a: &ty::TypeAndMut<'tcx>,
108 b: &ty::TypeAndMut<'tcx>)
109 -> RelateResult<'tcx, ty::TypeAndMut<'tcx>>
110 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
112 debug!("{}.mts({:?}, {:?})",
116 if a.mutbl != b.mutbl {
117 Err(TypeError::Mutability)
120 let variance = match mutbl {
121 ast::Mutability::MutImmutable => ty::Covariant,
122 ast::Mutability::MutMutable => ty::Invariant,
124 let ty = relation.relate_with_variance(variance, &a.ty, &b.ty)?;
125 Ok(ty::TypeAndMut {ty: ty, mutbl: mutbl})
130 pub fn relate_substs<'a, 'gcx, 'tcx, R>(relation: &mut R,
131 variances: Option<&Vec<ty::Variance>>,
132 a_subst: &'tcx Substs<'tcx>,
133 b_subst: &'tcx Substs<'tcx>)
134 -> RelateResult<'tcx, &'tcx Substs<'tcx>>
135 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
137 let tcx = relation.tcx();
139 let params = a_subst.iter().zip(b_subst).enumerate().map(|(i, (a, b))| {
140 let variance = variances.map_or(ty::Invariant, |v| v[i]);
141 if let (Some(a_ty), Some(b_ty)) = (a.as_type(), b.as_type()) {
142 Ok(Kind::from(relation.relate_with_variance(variance, &a_ty, &b_ty)?))
143 } else if let (Some(a_r), Some(b_r)) = (a.as_region(), b.as_region()) {
144 Ok(Kind::from(relation.relate_with_variance(variance, &a_r, &b_r)?))
150 Ok(tcx.mk_substs(params)?)
153 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
154 fn relate<'a, 'gcx, R>(relation: &mut R,
157 -> RelateResult<'tcx, ty::FnSig<'tcx>>
158 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
160 if a.variadic != b.variadic {
161 return Err(TypeError::VariadicMismatch(
162 expected_found(relation, &a.variadic, &b.variadic)));
164 let unsafety = relation.relate(&a.unsafety, &b.unsafety)?;
165 let abi = relation.relate(&a.abi, &b.abi)?;
167 if a.inputs().len() != b.inputs().len() {
168 return Err(TypeError::ArgCount);
171 let inputs_and_output = a.inputs().iter().cloned()
172 .zip(b.inputs().iter().cloned())
174 .chain(iter::once(((a.output(), b.output()), true)))
175 .map(|((a, b), is_output)| {
177 relation.relate(&a, &b)
179 relation.relate_with_variance(ty::Contravariant, &a, &b)
181 }).collect::<Result<AccumulateVec<[_; 8]>, _>>()?;
183 inputs_and_output: relation.tcx().intern_type_list(&inputs_and_output),
184 variadic: a.variadic,
191 impl<'tcx> Relate<'tcx> for ast::Unsafety {
192 fn relate<'a, 'gcx, R>(relation: &mut R,
195 -> RelateResult<'tcx, ast::Unsafety>
196 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
199 Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
206 impl<'tcx> Relate<'tcx> for abi::Abi {
207 fn relate<'a, 'gcx, R>(relation: &mut R,
210 -> RelateResult<'tcx, abi::Abi>
211 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
216 Err(TypeError::AbiMismatch(expected_found(relation, a, b)))
221 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
222 fn relate<'a, 'gcx, R>(relation: &mut R,
223 a: &ty::ProjectionTy<'tcx>,
224 b: &ty::ProjectionTy<'tcx>)
225 -> RelateResult<'tcx, ty::ProjectionTy<'tcx>>
226 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
228 if a.item_name != b.item_name {
229 Err(TypeError::ProjectionNameMismatched(
230 expected_found(relation, &a.item_name, &b.item_name)))
232 let trait_ref = relation.relate(&a.trait_ref, &b.trait_ref)?;
233 Ok(ty::ProjectionTy { trait_ref: trait_ref, item_name: a.item_name })
238 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
239 fn relate<'a, 'gcx, R>(relation: &mut R,
240 a: &ty::ExistentialProjection<'tcx>,
241 b: &ty::ExistentialProjection<'tcx>)
242 -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>>
243 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
245 if a.item_name != b.item_name {
246 Err(TypeError::ProjectionNameMismatched(
247 expected_found(relation, &a.item_name, &b.item_name)))
249 let trait_ref = relation.relate(&a.trait_ref, &b.trait_ref)?;
250 let ty = relation.relate(&a.ty, &b.ty)?;
251 Ok(ty::ExistentialProjection {
252 trait_ref: trait_ref,
253 item_name: a.item_name,
260 impl<'tcx> Relate<'tcx> for Vec<ty::PolyExistentialProjection<'tcx>> {
261 fn relate<'a, 'gcx, R>(relation: &mut R,
262 a: &Vec<ty::PolyExistentialProjection<'tcx>>,
263 b: &Vec<ty::PolyExistentialProjection<'tcx>>)
264 -> RelateResult<'tcx, Vec<ty::PolyExistentialProjection<'tcx>>>
265 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
267 // To be compatible, `a` and `b` must be for precisely the
268 // same set of traits and item names. We always require that
269 // projection bounds lists are sorted by trait-def-id and item-name,
270 // so we can just iterate through the lists pairwise, so long as they are the
272 if a.len() != b.len() {
273 Err(TypeError::ProjectionBoundsLength(expected_found(relation, &a.len(), &b.len())))
276 .map(|(a, b)| relation.relate(a, b))
282 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
283 fn relate<'a, 'gcx, R>(relation: &mut R,
284 a: &ty::TraitRef<'tcx>,
285 b: &ty::TraitRef<'tcx>)
286 -> RelateResult<'tcx, ty::TraitRef<'tcx>>
287 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
289 // Different traits cannot be related
290 if a.def_id != b.def_id {
291 Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
293 let substs = relation.relate_item_substs(a.def_id, a.substs, b.substs)?;
294 Ok(ty::TraitRef { def_id: a.def_id, substs: substs })
299 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
300 fn relate<'a, 'gcx, R>(relation: &mut R,
301 a: &ty::ExistentialTraitRef<'tcx>,
302 b: &ty::ExistentialTraitRef<'tcx>)
303 -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>>
304 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
306 // Different traits cannot be related
307 if a.def_id != b.def_id {
308 Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
310 let substs = relation.relate_item_substs(a.def_id, a.substs, b.substs)?;
311 Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs: substs })
316 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
317 fn relate<'a, 'gcx, R>(relation: &mut R,
320 -> RelateResult<'tcx, Ty<'tcx>>
321 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
327 /// The main "type relation" routine. Note that this does not handle
328 /// inference artifacts, so you should filter those out before calling
330 pub fn super_relate_tys<'a, 'gcx, 'tcx, R>(relation: &mut R,
333 -> RelateResult<'tcx, Ty<'tcx>>
334 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
336 let tcx = relation.tcx();
339 debug!("super_tys: a_sty={:?} b_sty={:?}", a_sty, b_sty);
340 match (a_sty, b_sty) {
341 (&ty::TyInfer(_), _) |
342 (_, &ty::TyInfer(_)) =>
344 // The caller should handle these cases!
345 bug!("var types encountered in super_relate_tys")
348 (&ty::TyError, _) | (_, &ty::TyError) =>
357 (&ty::TyUint(_), _) |
358 (&ty::TyFloat(_), _) |
365 (&ty::TyParam(ref a_p), &ty::TyParam(ref b_p))
366 if a_p.idx == b_p.idx =>
371 (&ty::TyAdt(a_def, a_substs), &ty::TyAdt(b_def, b_substs))
374 let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
375 Ok(tcx.mk_adt(a_def, substs))
378 (&ty::TyDynamic(ref a_obj, ref a_region), &ty::TyDynamic(ref b_obj, ref b_region)) => {
379 let region_bound = relation.with_cause(Cause::ExistentialRegionBound,
381 relation.relate_with_variance(
386 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
389 (&ty::TyClosure(a_id, a_substs),
390 &ty::TyClosure(b_id, b_substs))
393 // All TyClosure types with the same id represent
394 // the (anonymous) type of the same closure expression. So
395 // all of their regions should be equated.
396 let substs = relation.relate(&a_substs, &b_substs)?;
397 Ok(tcx.mk_closure_from_closure_substs(a_id, substs))
400 (&ty::TyRawPtr(ref a_mt), &ty::TyRawPtr(ref b_mt)) =>
402 let mt = relation.relate(a_mt, b_mt)?;
406 (&ty::TyRef(a_r, ref a_mt), &ty::TyRef(b_r, ref b_mt)) =>
408 let r = relation.relate_with_variance(ty::Contravariant, &a_r, &b_r)?;
409 let mt = relation.relate(a_mt, b_mt)?;
410 Ok(tcx.mk_ref(r, mt))
413 (&ty::TyArray(a_t, sz_a), &ty::TyArray(b_t, sz_b)) =>
415 let t = relation.relate(&a_t, &b_t)?;
417 Ok(tcx.mk_array(t, sz_a))
419 Err(TypeError::FixedArraySize(expected_found(relation, &sz_a, &sz_b)))
423 (&ty::TySlice(a_t), &ty::TySlice(b_t)) =>
425 let t = relation.relate(&a_t, &b_t)?;
429 (&ty::TyTuple(as_, a_defaulted), &ty::TyTuple(bs, b_defaulted)) =>
431 if as_.len() == bs.len() {
432 let defaulted = a_defaulted || b_defaulted;
433 Ok(tcx.mk_tup(as_.iter().zip(bs).map(|(a, b)| relation.relate(a, b)), defaulted)?)
434 } else if !(as_.is_empty() || bs.is_empty()) {
435 Err(TypeError::TupleSize(
436 expected_found(relation, &as_.len(), &bs.len())))
438 Err(TypeError::Sorts(expected_found(relation, &a, &b)))
442 (&ty::TyFnDef(a_def_id, a_substs, a_fty),
443 &ty::TyFnDef(b_def_id, b_substs, b_fty))
444 if a_def_id == b_def_id =>
446 let substs = relate_substs(relation, None, a_substs, b_substs)?;
447 let fty = relation.relate(&a_fty, &b_fty)?;
448 Ok(tcx.mk_fn_def(a_def_id, substs, fty))
451 (&ty::TyFnPtr(a_fty), &ty::TyFnPtr(b_fty)) =>
453 let fty = relation.relate(&a_fty, &b_fty)?;
454 Ok(tcx.mk_fn_ptr(fty))
457 (&ty::TyProjection(ref a_data), &ty::TyProjection(ref b_data)) =>
459 let projection_ty = relation.relate(a_data, b_data)?;
460 Ok(tcx.mk_projection(projection_ty.trait_ref, projection_ty.item_name))
463 (&ty::TyAnon(a_def_id, a_substs), &ty::TyAnon(b_def_id, b_substs))
464 if a_def_id == b_def_id =>
466 let substs = relate_substs(relation, None, a_substs, b_substs)?;
467 Ok(tcx.mk_anon(a_def_id, substs))
472 Err(TypeError::Sorts(expected_found(relation, &a, &b)))
477 impl<'tcx> Relate<'tcx> for &'tcx ty::Slice<ty::ExistentialPredicate<'tcx>> {
478 fn relate<'a, 'gcx, R>(relation: &mut R,
481 -> RelateResult<'tcx, Self>
482 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a {
484 if a.len() != b.len() {
485 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
488 let tcx = relation.tcx();
489 let v = a.iter().zip(b.iter()).map(|(ep_a, ep_b)| {
490 use ty::ExistentialPredicate::*;
491 match (*ep_a, *ep_b) {
492 (Trait(ref a), Trait(ref b)) => Ok(Trait(relation.relate(a, b)?)),
493 (Projection(ref a), Projection(ref b)) => Ok(Projection(relation.relate(a, b)?)),
494 (AutoTrait(ref a), AutoTrait(ref b)) if a == b => Ok(AutoTrait(*a)),
495 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)))
498 Ok(tcx.mk_existential_predicates(v)?)
502 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
503 fn relate<'a, 'gcx, R>(relation: &mut R,
504 a: &ty::ClosureSubsts<'tcx>,
505 b: &ty::ClosureSubsts<'tcx>)
506 -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>>
507 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
509 let substs = relate_substs(relation, None, a.substs, b.substs)?;
510 Ok(ty::ClosureSubsts { substs: substs })
514 impl<'tcx> Relate<'tcx> for &'tcx Substs<'tcx> {
515 fn relate<'a, 'gcx, R>(relation: &mut R,
516 a: &&'tcx Substs<'tcx>,
517 b: &&'tcx Substs<'tcx>)
518 -> RelateResult<'tcx, &'tcx Substs<'tcx>>
519 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
521 relate_substs(relation, None, a, b)
525 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
526 fn relate<'a, 'gcx, R>(relation: &mut R,
527 a: &ty::Region<'tcx>,
528 b: &ty::Region<'tcx>)
529 -> RelateResult<'tcx, ty::Region<'tcx>>
530 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
532 relation.regions(*a, *b)
536 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<T> {
537 fn relate<'a, 'gcx, R>(relation: &mut R,
540 -> RelateResult<'tcx, ty::Binder<T>>
541 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
543 relation.binders(a, b)
547 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Rc<T> {
548 fn relate<'a, 'gcx, R>(relation: &mut R,
551 -> RelateResult<'tcx, Rc<T>>
552 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
556 Ok(Rc::new(relation.relate(a, b)?))
560 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Box<T> {
561 fn relate<'a, 'gcx, R>(relation: &mut R,
564 -> RelateResult<'tcx, Box<T>>
565 where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
569 Ok(Box::new(relation.relate(a, b)?))
573 ///////////////////////////////////////////////////////////////////////////
576 pub fn expected_found<'a, 'gcx, 'tcx, R, T>(relation: &mut R,
580 where R: TypeRelation<'a, 'gcx, 'tcx>, T: Clone, 'gcx: 'a+'tcx, 'tcx: 'a
582 expected_found_bool(relation.a_is_expected(), a, b)
585 pub fn expected_found_bool<T>(a_is_expected: bool,
594 ExpectedFound {expected: a, found: b}
596 ExpectedFound {expected: b, found: a}